blob: 900a0a63e96ee3d47466fc2f27ca28e1c7629a3c [file] [log] [blame]
Andrew Trick6a50baa2012-05-17 22:37:09 +00001//===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
Andrew Tricke77e84e2012-01-13 06:30:30 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// MachineScheduler schedules machine instructions after phi elimination. It
11// preserves LiveIntervals so it can be invoked before register allocation.
12//
13//===----------------------------------------------------------------------===//
14
Chandler Carruth6bda14b2017-06-06 11:49:48 +000015#include "llvm/CodeGen/MachineScheduler.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000016#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/DenseMap.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/PriorityQueue.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000020#include "llvm/ADT/STLExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000021#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/iterator_range.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000024#include "llvm/CodeGen/LiveInterval.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000026#include "llvm/CodeGen/MachineBasicBlock.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000027#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFunctionPass.h"
30#include "llvm/CodeGen/MachineInstr.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000031#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000032#include "llvm/CodeGen/MachineOperand.h"
33#include "llvm/CodeGen/MachinePassRegistry.h"
Andrew Trick736dd9a2013-06-21 18:32:58 +000034#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000035#include "llvm/CodeGen/MachineValueType.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000036#include "llvm/CodeGen/Passes.h"
Andrew Trick05ff4662012-06-06 20:29:31 +000037#include "llvm/CodeGen/RegisterClassInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000038#include "llvm/CodeGen/RegisterPressure.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000039#include "llvm/CodeGen/ScheduleDAG.h"
40#include "llvm/CodeGen/ScheduleDAGInstrs.h"
41#include "llvm/CodeGen/ScheduleDAGMutation.h"
Andrew Trickcd1c2f92012-11-28 05:13:24 +000042#include "llvm/CodeGen/ScheduleDFS.h"
Andrew Trick61f1a272012-05-24 22:11:09 +000043#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000044#include "llvm/CodeGen/SlotIndexes.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000045#include "llvm/CodeGen/TargetInstrInfo.h"
Matthias Braun31d19d42016-05-10 03:21:59 +000046#include "llvm/CodeGen/TargetPassConfig.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000047#include "llvm/CodeGen/TargetSchedule.h"
48#include "llvm/MC/LaneBitmask.h"
49#include "llvm/Pass.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000050#include "llvm/Support/CommandLine.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000051#include "llvm/Support/Compiler.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000052#include "llvm/Support/Debug.h"
53#include "llvm/Support/ErrorHandling.h"
Andrew Trickea9fd952013-01-25 07:45:29 +000054#include "llvm/Support/GraphWriter.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000055#include "llvm/Support/raw_ostream.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000056#include "llvm/Target/TargetLowering.h"
57#include "llvm/Target/TargetRegisterInfo.h"
58#include "llvm/Target/TargetSubtargetInfo.h"
59#include <algorithm>
60#include <cassert>
61#include <cstdint>
62#include <iterator>
63#include <limits>
64#include <memory>
65#include <string>
66#include <tuple>
67#include <utility>
68#include <vector>
Andrew Trick7ccdc5c2012-01-17 06:55:07 +000069
Andrew Tricke77e84e2012-01-13 06:30:30 +000070using namespace llvm;
71
Matthias Braun1527baa2017-05-25 21:26:32 +000072#define DEBUG_TYPE "machine-scheduler"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000073
Andrew Trick7a8e1002012-09-11 00:39:15 +000074namespace llvm {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000075
Andrew Trick7a8e1002012-09-11 00:39:15 +000076cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
77 cl::desc("Force top-down list scheduling"));
78cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
79 cl::desc("Force bottom-up list scheduling"));
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +000080cl::opt<bool>
81DumpCriticalPathLength("misched-dcpl", cl::Hidden,
82 cl::desc("Print critical path length to stdout"));
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000083
84} // end namespace llvm
Andrew Trick8823dec2012-03-14 04:00:41 +000085
Andrew Tricka5f19562012-03-07 00:18:25 +000086#ifndef NDEBUG
87static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
88 cl::desc("Pop up a window to show MISched dags after they are processed"));
Lang Hamesdd98c492012-03-19 18:38:38 +000089
Matthias Braund78ee542015-09-17 21:09:59 +000090/// In some situations a few uninteresting nodes depend on nearly all other
91/// nodes in the graph, provide a cutoff to hide them.
92static cl::opt<unsigned> ViewMISchedCutoff("view-misched-cutoff", cl::Hidden,
93 cl::desc("Hide nodes with more predecessor/successor than cutoff"));
94
Lang Hamesdd98c492012-03-19 18:38:38 +000095static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
96 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
Andrew Trick33e05d72013-12-28 21:57:02 +000097
98static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden,
99 cl::desc("Only schedule this function"));
100static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden,
101 cl::desc("Only schedule this MBB#"));
Andrew Tricka5f19562012-03-07 00:18:25 +0000102#else
103static bool ViewMISchedDAGs = false;
104#endif // NDEBUG
105
Matthias Braun6493bc22016-04-22 19:09:17 +0000106/// Avoid quadratic complexity in unusually large basic blocks by limiting the
107/// size of the ready lists.
108static cl::opt<unsigned> ReadyListLimit("misched-limit", cl::Hidden,
109 cl::desc("Limit ready list to N instructions"), cl::init(256));
110
Andrew Trickb6e74712013-09-04 20:59:59 +0000111static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
112 cl::desc("Enable register pressure scheduling."), cl::init(true));
113
Andrew Trickc01b0042013-08-23 17:48:43 +0000114static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
Andrew Trick6c88b352013-09-09 23:31:14 +0000115 cl::desc("Enable cyclic critical path analysis."), cl::init(true));
Andrew Trickc01b0042013-08-23 17:48:43 +0000116
Jun Bum Lim4c5bd582016-04-15 14:58:38 +0000117static cl::opt<bool> EnableMemOpCluster("misched-cluster", cl::Hidden,
118 cl::desc("Enable memop clustering."),
119 cl::init(true));
Andrew Tricka7714a02012-11-12 19:40:10 +0000120
Andrew Trick48f2a722013-03-08 05:40:34 +0000121static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
122 cl::desc("Verify machine instrs before and after machine scheduling"));
123
Andrew Trick44f750a2013-01-25 04:01:04 +0000124// DAG subtrees must have at least this many nodes.
125static const unsigned MinSubtreeSize = 8;
126
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000127// Pin the vtables to this file.
128void MachineSchedStrategy::anchor() {}
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000129
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000130void ScheduleDAGMutation::anchor() {}
131
Andrew Trick63440872012-01-14 02:17:06 +0000132//===----------------------------------------------------------------------===//
133// Machine Instruction Scheduling Pass and Registry
134//===----------------------------------------------------------------------===//
135
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000136MachineSchedContext::MachineSchedContext() {
Andrew Trick4d4b5462012-04-24 20:36:19 +0000137 RegClassInfo = new RegisterClassInfo();
138}
139
140MachineSchedContext::~MachineSchedContext() {
141 delete RegClassInfo;
142}
143
Andrew Tricke77e84e2012-01-13 06:30:30 +0000144namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000145
Andrew Trickd7f890e2013-12-28 21:56:47 +0000146/// Base class for a machine scheduler class that can run at any point.
147class MachineSchedulerBase : public MachineSchedContext,
148 public MachineFunctionPass {
149public:
150 MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
151
Craig Topperc0196b12014-04-14 00:51:57 +0000152 void print(raw_ostream &O, const Module* = nullptr) const override;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000153
154protected:
Matthias Braun93563e72015-11-03 01:53:29 +0000155 void scheduleRegions(ScheduleDAGInstrs &Scheduler, bool FixKillFlags);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000156};
157
Andrew Tricke1c034f2012-01-17 06:55:03 +0000158/// MachineScheduler runs after coalescing and before register allocation.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000159class MachineScheduler : public MachineSchedulerBase {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000160public:
Andrew Tricke1c034f2012-01-17 06:55:03 +0000161 MachineScheduler();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000162
Craig Topper4584cd52014-03-07 09:26:03 +0000163 void getAnalysisUsage(AnalysisUsage &AU) const override;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000164
Craig Topper4584cd52014-03-07 09:26:03 +0000165 bool runOnMachineFunction(MachineFunction&) override;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000166
Andrew Tricke77e84e2012-01-13 06:30:30 +0000167 static char ID; // Class identification, replacement for typeinfo
Andrew Trick978674b2013-09-20 05:14:41 +0000168
169protected:
170 ScheduleDAGInstrs *createMachineScheduler();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000171};
Andrew Trick17080b92013-12-28 21:56:51 +0000172
173/// PostMachineScheduler runs after shortly before code emission.
174class PostMachineScheduler : public MachineSchedulerBase {
175public:
176 PostMachineScheduler();
177
Craig Topper4584cd52014-03-07 09:26:03 +0000178 void getAnalysisUsage(AnalysisUsage &AU) const override;
Andrew Trick17080b92013-12-28 21:56:51 +0000179
Craig Topper4584cd52014-03-07 09:26:03 +0000180 bool runOnMachineFunction(MachineFunction&) override;
Andrew Trick17080b92013-12-28 21:56:51 +0000181
182 static char ID; // Class identification, replacement for typeinfo
183
184protected:
185 ScheduleDAGInstrs *createPostMachineScheduler();
186};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000187
188} // end anonymous namespace
Andrew Tricke77e84e2012-01-13 06:30:30 +0000189
Andrew Tricke1c034f2012-01-17 06:55:03 +0000190char MachineScheduler::ID = 0;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000191
Andrew Tricke1c034f2012-01-17 06:55:03 +0000192char &llvm::MachineSchedulerID = MachineScheduler::ID;
Andrew Tricke77e84e2012-01-13 06:30:30 +0000193
Matthias Braun1527baa2017-05-25 21:26:32 +0000194INITIALIZE_PASS_BEGIN(MachineScheduler, DEBUG_TYPE,
Andrew Tricke77e84e2012-01-13 06:30:30 +0000195 "Machine Instruction Scheduler", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000196INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Davide Italiano6a1209e2017-03-24 20:52:56 +0000197INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Andrew Tricke77e84e2012-01-13 06:30:30 +0000198INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
199INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
Matthias Braun1527baa2017-05-25 21:26:32 +0000200INITIALIZE_PASS_END(MachineScheduler, DEBUG_TYPE,
Andrew Tricke77e84e2012-01-13 06:30:30 +0000201 "Machine Instruction Scheduler", false, false)
202
Eugene Zelenko32a40562017-09-11 23:00:48 +0000203MachineScheduler::MachineScheduler() : MachineSchedulerBase(ID) {
Andrew Tricke1c034f2012-01-17 06:55:03 +0000204 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Andrew Tricke77e84e2012-01-13 06:30:30 +0000205}
206
Andrew Tricke1c034f2012-01-17 06:55:03 +0000207void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000208 AU.setPreservesCFG();
209 AU.addRequiredID(MachineDominatorsID);
210 AU.addRequired<MachineLoopInfo>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000211 AU.addRequired<AAResultsWrapperPass>();
Andrew Trick45300682012-03-09 00:52:20 +0000212 AU.addRequired<TargetPassConfig>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000213 AU.addRequired<SlotIndexes>();
214 AU.addPreserved<SlotIndexes>();
215 AU.addRequired<LiveIntervals>();
216 AU.addPreserved<LiveIntervals>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000217 MachineFunctionPass::getAnalysisUsage(AU);
218}
219
Andrew Trick17080b92013-12-28 21:56:51 +0000220char PostMachineScheduler::ID = 0;
221
222char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
223
224INITIALIZE_PASS(PostMachineScheduler, "postmisched",
Saleem Abdulrasool7230b372013-12-28 22:47:55 +0000225 "PostRA Machine Instruction Scheduler", false, false)
Andrew Trick17080b92013-12-28 21:56:51 +0000226
Eugene Zelenko32a40562017-09-11 23:00:48 +0000227PostMachineScheduler::PostMachineScheduler() : MachineSchedulerBase(ID) {
Andrew Trick17080b92013-12-28 21:56:51 +0000228 initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
229}
230
231void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
232 AU.setPreservesCFG();
233 AU.addRequiredID(MachineDominatorsID);
234 AU.addRequired<MachineLoopInfo>();
235 AU.addRequired<TargetPassConfig>();
236 MachineFunctionPass::getAnalysisUsage(AU);
237}
238
Andrew Tricke77e84e2012-01-13 06:30:30 +0000239MachinePassRegistry MachineSchedRegistry::Registry;
240
Andrew Trick45300682012-03-09 00:52:20 +0000241/// A dummy default scheduler factory indicates whether the scheduler
242/// is overridden on the command line.
243static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
Craig Topperc0196b12014-04-14 00:51:57 +0000244 return nullptr;
Andrew Trick45300682012-03-09 00:52:20 +0000245}
Andrew Tricke77e84e2012-01-13 06:30:30 +0000246
247/// MachineSchedOpt allows command line selection of the scheduler.
248static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000249 RegisterPassParser<MachineSchedRegistry>>
Andrew Tricke77e84e2012-01-13 06:30:30 +0000250MachineSchedOpt("misched",
Andrew Trick45300682012-03-09 00:52:20 +0000251 cl::init(&useDefaultMachineSched), cl::Hidden,
Andrew Tricke77e84e2012-01-13 06:30:30 +0000252 cl::desc("Machine instruction scheduler to use"));
253
Andrew Trick45300682012-03-09 00:52:20 +0000254static MachineSchedRegistry
Andrew Trick8823dec2012-03-14 04:00:41 +0000255DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
Andrew Trick45300682012-03-09 00:52:20 +0000256 useDefaultMachineSched);
257
Eric Christopher5f141b02015-03-11 22:56:10 +0000258static cl::opt<bool> EnableMachineSched(
259 "enable-misched",
260 cl::desc("Enable the machine instruction scheduling pass."), cl::init(true),
261 cl::Hidden);
262
Chad Rosier816a1ab2016-01-20 23:08:32 +0000263static cl::opt<bool> EnablePostRAMachineSched(
264 "enable-post-misched",
265 cl::desc("Enable the post-ra machine instruction scheduling pass."),
266 cl::init(true), cl::Hidden);
267
Andrew Trickcc45a282012-04-24 18:04:34 +0000268/// Decrement this iterator until reaching the top or a non-debug instr.
Andrew Trick2bc74c22013-08-30 04:36:57 +0000269static MachineBasicBlock::const_iterator
270priorNonDebug(MachineBasicBlock::const_iterator I,
271 MachineBasicBlock::const_iterator Beg) {
Andrew Trickcc45a282012-04-24 18:04:34 +0000272 assert(I != Beg && "reached the top of the region, cannot decrement");
273 while (--I != Beg) {
274 if (!I->isDebugValue())
275 break;
276 }
277 return I;
278}
279
Andrew Trick2bc74c22013-08-30 04:36:57 +0000280/// Non-const version.
281static MachineBasicBlock::iterator
282priorNonDebug(MachineBasicBlock::iterator I,
283 MachineBasicBlock::const_iterator Beg) {
Duncan P. N. Exon Smithdcbce9c2016-08-16 23:34:07 +0000284 return priorNonDebug(MachineBasicBlock::const_iterator(I), Beg)
285 .getNonConstIterator();
Andrew Trick2bc74c22013-08-30 04:36:57 +0000286}
287
Andrew Trickcc45a282012-04-24 18:04:34 +0000288/// If this iterator is a debug value, increment until reaching the End or a
289/// non-debug instruction.
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000290static MachineBasicBlock::const_iterator
291nextIfDebug(MachineBasicBlock::const_iterator I,
292 MachineBasicBlock::const_iterator End) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000293 for(; I != End; ++I) {
Andrew Trickcc45a282012-04-24 18:04:34 +0000294 if (!I->isDebugValue())
295 break;
296 }
297 return I;
298}
299
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000300/// Non-const version.
301static MachineBasicBlock::iterator
302nextIfDebug(MachineBasicBlock::iterator I,
303 MachineBasicBlock::const_iterator End) {
Duncan P. N. Exon Smithdcbce9c2016-08-16 23:34:07 +0000304 return nextIfDebug(MachineBasicBlock::const_iterator(I), End)
305 .getNonConstIterator();
Andrew Trick2c4f8b72013-08-31 05:17:58 +0000306}
307
Andrew Trickdc4c1ad2013-09-24 17:11:19 +0000308/// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
Andrew Trick978674b2013-09-20 05:14:41 +0000309ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
310 // Select the scheduler, or set the default.
311 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
312 if (Ctor != useDefaultMachineSched)
313 return Ctor(this);
314
315 // Get the default scheduler set by the target for this function.
316 ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
317 if (Scheduler)
318 return Scheduler;
319
320 // Default to GenericScheduler.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000321 return createGenericSchedLive(this);
Andrew Trick978674b2013-09-20 05:14:41 +0000322}
323
Andrew Trick17080b92013-12-28 21:56:51 +0000324/// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
325/// the caller. We don't have a command line option to override the postRA
326/// scheduler. The Target must configure it.
327ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
328 // Get the postRA scheduler set by the target for this function.
329 ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
330 if (Scheduler)
331 return Scheduler;
332
333 // Default to GenericScheduler.
Andrew Trickd14d7c22013-12-28 21:56:57 +0000334 return createGenericSchedPostRA(this);
Andrew Trick17080b92013-12-28 21:56:51 +0000335}
336
Andrew Trick72515be2012-03-14 04:00:38 +0000337/// Top-level MachineScheduler pass driver.
338///
339/// Visit blocks in function order. Divide each block into scheduling regions
Andrew Trick8823dec2012-03-14 04:00:41 +0000340/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
341/// consistent with the DAG builder, which traverses the interior of the
342/// scheduling regions bottom-up.
Andrew Trick72515be2012-03-14 04:00:38 +0000343///
344/// This design avoids exposing scheduling boundaries to the DAG builder,
Andrew Trick8823dec2012-03-14 04:00:41 +0000345/// simplifying the DAG builder's support for "special" target instructions.
346/// At the same time the design allows target schedulers to operate across
Andrew Trick72515be2012-03-14 04:00:38 +0000347/// scheduling boundaries, for example to bundle the boudary instructions
348/// without reordering them. This creates complexity, because the target
349/// scheduler must update the RegionBegin and RegionEnd positions cached by
350/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
351/// design would be to split blocks at scheduling boundaries, but LLVM has a
352/// general bias against block splitting purely for implementation simplicity.
Andrew Tricke1c034f2012-01-17 06:55:03 +0000353bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000354 if (skipFunction(*mf.getFunction()))
Chad Rosier6338d7c2016-01-20 22:38:25 +0000355 return false;
356
Eric Christopher5f141b02015-03-11 22:56:10 +0000357 if (EnableMachineSched.getNumOccurrences()) {
358 if (!EnableMachineSched)
359 return false;
360 } else if (!mf.getSubtarget().enableMachineScheduler())
361 return false;
362
Matthias Braundc7580a2015-10-29 03:57:28 +0000363 DEBUG(dbgs() << "Before MISched:\n"; mf.print(dbgs()));
Andrew Trickc5d70082012-05-10 21:06:21 +0000364
Andrew Tricke77e84e2012-01-13 06:30:30 +0000365 // Initialize the context of the pass.
366 MF = &mf;
367 MLI = &getAnalysis<MachineLoopInfo>();
368 MDT = &getAnalysis<MachineDominatorTree>();
Andrew Trick45300682012-03-09 00:52:20 +0000369 PassConfig = &getAnalysis<TargetPassConfig>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000370 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Andrew Trick02a80da2012-03-08 01:41:12 +0000371
Lang Hamesad33d5a2012-01-27 22:36:19 +0000372 LIS = &getAnalysis<LiveIntervals>();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000373
Andrew Trick48f2a722013-03-08 05:40:34 +0000374 if (VerifyScheduling) {
Andrew Trick97064962013-07-25 07:26:26 +0000375 DEBUG(LIS->dump());
Andrew Trick48f2a722013-03-08 05:40:34 +0000376 MF->verify(this, "Before machine scheduling.");
377 }
Andrew Trick4d4b5462012-04-24 20:36:19 +0000378 RegClassInfo->runOnMachineFunction(*MF);
Andrew Trick88639922012-04-24 17:56:43 +0000379
Andrew Trick978674b2013-09-20 05:14:41 +0000380 // Instantiate the selected scheduler for this target, function, and
381 // optimization level.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000382 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
Matthias Braun93563e72015-11-03 01:53:29 +0000383 scheduleRegions(*Scheduler, false);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000384
385 DEBUG(LIS->dump());
386 if (VerifyScheduling)
387 MF->verify(this, "After machine scheduling.");
388 return true;
389}
390
Andrew Trick17080b92013-12-28 21:56:51 +0000391bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000392 if (skipFunction(*mf.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000393 return false;
394
Chad Rosier816a1ab2016-01-20 23:08:32 +0000395 if (EnablePostRAMachineSched.getNumOccurrences()) {
396 if (!EnablePostRAMachineSched)
397 return false;
398 } else if (!mf.getSubtarget().enablePostRAScheduler()) {
Andrew Trick8d2ee372014-06-04 07:06:27 +0000399 DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
400 return false;
401 }
Andrew Trick17080b92013-12-28 21:56:51 +0000402 DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
403
404 // Initialize the context of the pass.
405 MF = &mf;
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000406 MLI = &getAnalysis<MachineLoopInfo>();
Andrew Trick17080b92013-12-28 21:56:51 +0000407 PassConfig = &getAnalysis<TargetPassConfig>();
408
409 if (VerifyScheduling)
410 MF->verify(this, "Before post machine scheduling.");
411
412 // Instantiate the selected scheduler for this target, function, and
413 // optimization level.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000414 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
Matthias Braun93563e72015-11-03 01:53:29 +0000415 scheduleRegions(*Scheduler, true);
Andrew Trick17080b92013-12-28 21:56:51 +0000416
417 if (VerifyScheduling)
418 MF->verify(this, "After post machine scheduling.");
419 return true;
420}
421
Andrew Trickd14d7c22013-12-28 21:56:57 +0000422/// Return true of the given instruction should not be included in a scheduling
423/// region.
424///
425/// MachineScheduler does not currently support scheduling across calls. To
426/// handle calls, the DAG builder needs to be modified to create register
427/// anti/output dependencies on the registers clobbered by the call's regmask
428/// operand. In PreRA scheduling, the stack pointer adjustment already prevents
429/// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
430/// the boundary, but there would be no benefit to postRA scheduling across
431/// calls this late anyway.
432static bool isSchedBoundary(MachineBasicBlock::iterator MI,
433 MachineBasicBlock *MBB,
434 MachineFunction *MF,
Matthias Braun93563e72015-11-03 01:53:29 +0000435 const TargetInstrInfo *TII) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000436 return MI->isCall() || TII->isSchedulingBoundary(*MI, MBB, *MF);
Andrew Trickd14d7c22013-12-28 21:56:57 +0000437}
438
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000439/// A region of an MBB for scheduling.
Mikael Holmen4eb2a962017-09-13 14:07:47 +0000440namespace {
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000441struct SchedRegion {
442 /// RegionBegin is the first instruction in the scheduling region, and
443 /// RegionEnd is either MBB->end() or the scheduling boundary after the
444 /// last instruction in the scheduling region. These iterators cannot refer
445 /// to instructions outside of the identified scheduling region because
446 /// those may be reordered before scheduling this region.
447 MachineBasicBlock::iterator RegionBegin;
448 MachineBasicBlock::iterator RegionEnd;
449 unsigned NumRegionInstrs;
Eugene Zelenko32a40562017-09-11 23:00:48 +0000450
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000451 SchedRegion(MachineBasicBlock::iterator B, MachineBasicBlock::iterator E,
452 unsigned N) :
453 RegionBegin(B), RegionEnd(E), NumRegionInstrs(N) {}
454};
Mikael Holmen4eb2a962017-09-13 14:07:47 +0000455} // end anonymous namespace
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000456
Eugene Zelenko32a40562017-09-11 23:00:48 +0000457using MBBRegionsVector = SmallVector<SchedRegion, 16>;
458
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000459static void
460getSchedRegions(MachineBasicBlock *MBB,
461 MBBRegionsVector &Regions,
462 bool RegionsTopDown) {
463 MachineFunction *MF = MBB->getParent();
464 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
465
466 MachineBasicBlock::iterator I = nullptr;
467 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
468 RegionEnd != MBB->begin(); RegionEnd = I) {
469
470 // Avoid decrementing RegionEnd for blocks with no terminator.
471 if (RegionEnd != MBB->end() ||
472 isSchedBoundary(&*std::prev(RegionEnd), &*MBB, MF, TII)) {
473 --RegionEnd;
474 }
475
476 // The next region starts above the previous region. Look backward in the
477 // instruction stream until we find the nearest boundary.
478 unsigned NumRegionInstrs = 0;
479 I = RegionEnd;
480 for (;I != MBB->begin(); --I) {
481 MachineInstr &MI = *std::prev(I);
482 if (isSchedBoundary(&MI, &*MBB, MF, TII))
483 break;
484 if (!MI.isDebugValue())
485 // MBB::size() uses instr_iterator to count. Here we need a bundle to
486 // count as a single instruction.
487 ++NumRegionInstrs;
488 }
489
490 Regions.push_back(SchedRegion(I, RegionEnd, NumRegionInstrs));
491 }
492
493 if (RegionsTopDown)
494 std::reverse(Regions.begin(), Regions.end());
495}
496
Andrew Trickd7f890e2013-12-28 21:56:47 +0000497/// Main driver for both MachineScheduler and PostMachineScheduler.
Matthias Braun93563e72015-11-03 01:53:29 +0000498void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler,
499 bool FixKillFlags) {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000500 // Visit all machine basic blocks.
Andrew Trick88639922012-04-24 17:56:43 +0000501 //
502 // TODO: Visit blocks in global postorder or postorder within the bottom-up
503 // loop tree. Then we can optionally compute global RegPressure.
Andrew Tricke77e84e2012-01-13 06:30:30 +0000504 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
505 MBB != MBBEnd; ++MBB) {
506
Duncan P. N. Exon Smith5ec15682015-10-09 19:40:45 +0000507 Scheduler.startBlock(&*MBB);
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000508
Andrew Trick33e05d72013-12-28 21:57:02 +0000509#ifndef NDEBUG
510 if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
511 continue;
512 if (SchedOnlyBlock.getNumOccurrences()
513 && (int)SchedOnlyBlock != MBB->getNumber())
514 continue;
515#endif
516
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000517 // Break the block into scheduling regions [I, RegionEnd). RegionEnd
518 // points to the scheduling boundary at the bottom of the region. The DAG
519 // does not include RegionEnd, but the region does (i.e. the next
520 // RegionEnd is above the previous RegionBegin). If the current block has
521 // no terminator then RegionEnd == MBB->end() for the bottom region.
522 //
523 // All the regions of MBB are first found and stored in MBBRegions, which
524 // will be processed (MBB) top-down if initialized with true.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000525 //
526 // The Scheduler may insert instructions during either schedule() or
527 // exitRegion(), even for empty regions. So the local iterators 'I' and
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000528 // 'RegionEnd' are invalid across these calls. Instructions must not be
529 // added to other regions than the current one without updating MBBRegions.
Andrew Trick88639922012-04-24 17:56:43 +0000530
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000531 MBBRegionsVector MBBRegions;
532 getSchedRegions(&*MBB, MBBRegions, Scheduler.doMBBSchedRegionsTopDown());
533 for (MBBRegionsVector::iterator R = MBBRegions.begin();
534 R != MBBRegions.end(); ++R) {
535 MachineBasicBlock::iterator I = R->RegionBegin;
536 MachineBasicBlock::iterator RegionEnd = R->RegionEnd;
537 unsigned NumRegionInstrs = R->NumRegionInstrs;
Andrew Trickedfe2ec2012-03-09 08:02:51 +0000538
Andrew Trick60cf03e2012-03-07 05:21:52 +0000539 // Notify the scheduler of the region, even if we may skip scheduling
540 // it. Perhaps it still needs to be bundled.
Duncan P. N. Exon Smith5ec15682015-10-09 19:40:45 +0000541 Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
Andrew Trick60cf03e2012-03-07 05:21:52 +0000542
543 // Skip empty scheduling regions (0 or 1 schedulable instructions).
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000544 if (I == RegionEnd || I == std::prev(RegionEnd)) {
Andrew Trick60cf03e2012-03-07 05:21:52 +0000545 // Close the current region. Bundle the terminator if needed.
Andrew Trickaf1bee72012-03-09 22:34:56 +0000546 // This invalidates 'RegionEnd' and 'I'.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000547 Scheduler.exitRegion();
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000548 continue;
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000549 }
Matthias Braun93563e72015-11-03 01:53:29 +0000550 DEBUG(dbgs() << "********** MI Scheduling **********\n");
Craig Toppera538d832012-08-22 06:07:19 +0000551 DEBUG(dbgs() << MF->getName()
Andrew Trick54b2ce32013-01-25 07:45:31 +0000552 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
553 << "\n From: " << *I << " To: ";
Andrew Tricke57583a2012-02-08 02:17:21 +0000554 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
555 else dbgs() << "End";
Matthias Braun858d1df2016-05-20 19:46:13 +0000556 dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +0000557 if (DumpCriticalPathLength) {
558 errs() << MF->getName();
559 errs() << ":BB# " << MBB->getNumber();
560 errs() << " " << MBB->getName() << " \n";
561 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000562
Andrew Trick1c0ec452012-03-09 03:46:42 +0000563 // Schedule a region: possibly reorder instructions.
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000564 // This invalidates the original region iterators.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000565 Scheduler.schedule();
Andrew Trick1c0ec452012-03-09 03:46:42 +0000566
567 // Close the current region.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000568 Scheduler.exitRegion();
Andrew Trick7e120f42012-01-14 02:17:09 +0000569 }
Andrew Trickd7f890e2013-12-28 21:56:47 +0000570 Scheduler.finishBlock();
Matthias Braun93563e72015-11-03 01:53:29 +0000571 // FIXME: Ideally, no further passes should rely on kill flags. However,
572 // thumb2 size reduction is currently an exception, so the PostMIScheduler
573 // needs to do this.
574 if (FixKillFlags)
Matthias Braun868bbd42017-05-27 02:50:50 +0000575 Scheduler.fixupKills(*MBB);
Andrew Tricke77e84e2012-01-13 06:30:30 +0000576 }
Andrew Trickd7f890e2013-12-28 21:56:47 +0000577 Scheduler.finalizeSchedule();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000578}
579
Andrew Trickd7f890e2013-12-28 21:56:47 +0000580void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000581 // unimplemented
582}
583
Aaron Ballman615eb472017-10-15 14:32:27 +0000584#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Clegg705f7982017-06-21 22:19:17 +0000585LLVM_DUMP_METHOD void ReadyQueue::dump() const {
James Y Knighte72b0db2015-09-18 18:52:20 +0000586 dbgs() << "Queue " << Name << ": ";
Javed Absare3a0cc22017-06-21 09:10:10 +0000587 for (const SUnit *SU : Queue)
588 dbgs() << SU->NodeNum << " ";
Andrew Trick7a8e1002012-09-11 00:39:15 +0000589 dbgs() << "\n";
590}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000591#endif
Andrew Trick8823dec2012-03-14 04:00:41 +0000592
593//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +0000594// ScheduleDAGMI - Basic machine instruction scheduling. This is
595// independent of PreRA/PostRA scheduling and involves no extra book-keeping for
596// virtual registers.
597// ===----------------------------------------------------------------------===/
Andrew Trick8823dec2012-03-14 04:00:41 +0000598
David Blaikie422b93d2014-04-21 20:32:32 +0000599// Provide a vtable anchor.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000600ScheduleDAGMI::~ScheduleDAGMI() = default;
Andrew Trick44f750a2013-01-25 04:01:04 +0000601
Andrew Trick85a1d4c2013-04-24 15:54:43 +0000602bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
603 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
604}
605
Andrew Tricka7714a02012-11-12 19:40:10 +0000606bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick263280242012-11-12 19:52:20 +0000607 if (SuccSU != &ExitSU) {
608 // Do not use WillCreateCycle, it assumes SD scheduling.
609 // If Pred is reachable from Succ, then the edge creates a cycle.
610 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
611 return false;
612 Topo.AddPred(SuccSU, PredDep.getSUnit());
613 }
Andrew Tricka7714a02012-11-12 19:40:10 +0000614 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
615 // Return true regardless of whether a new edge needed to be inserted.
616 return true;
617}
618
Andrew Trick02a80da2012-03-08 01:41:12 +0000619/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
620/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000621///
622/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000623void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trick02a80da2012-03-08 01:41:12 +0000624 SUnit *SuccSU = SuccEdge->getSUnit();
625
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000626 if (SuccEdge->isWeak()) {
627 --SuccSU->WeakPredsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000628 if (SuccEdge->isCluster())
629 NextClusterSucc = SuccSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000630 return;
631 }
Andrew Trick02a80da2012-03-08 01:41:12 +0000632#ifndef NDEBUG
633 if (SuccSU->NumPredsLeft == 0) {
634 dbgs() << "*** Scheduling failed! ***\n";
635 SuccSU->dump(this);
636 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000637 llvm_unreachable(nullptr);
Andrew Trick02a80da2012-03-08 01:41:12 +0000638 }
639#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000640 // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
641 // CurrCycle may have advanced since then.
642 if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
643 SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
644
Andrew Trick02a80da2012-03-08 01:41:12 +0000645 --SuccSU->NumPredsLeft;
646 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick8823dec2012-03-14 04:00:41 +0000647 SchedImpl->releaseTopNode(SuccSU);
Andrew Trick02a80da2012-03-08 01:41:12 +0000648}
649
650/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick8823dec2012-03-14 04:00:41 +0000651void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Javed Absare3a0cc22017-06-21 09:10:10 +0000652 for (SDep &Succ : SU->Succs)
653 releaseSucc(SU, &Succ);
Andrew Trick02a80da2012-03-08 01:41:12 +0000654}
655
Andrew Trick8823dec2012-03-14 04:00:41 +0000656/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
657/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000658///
659/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000660void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
661 SUnit *PredSU = PredEdge->getSUnit();
662
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000663 if (PredEdge->isWeak()) {
664 --PredSU->WeakSuccsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000665 if (PredEdge->isCluster())
666 NextClusterPred = PredSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000667 return;
668 }
Andrew Trick8823dec2012-03-14 04:00:41 +0000669#ifndef NDEBUG
670 if (PredSU->NumSuccsLeft == 0) {
671 dbgs() << "*** Scheduling failed! ***\n";
672 PredSU->dump(this);
673 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000674 llvm_unreachable(nullptr);
Andrew Trick8823dec2012-03-14 04:00:41 +0000675 }
676#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000677 // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
678 // CurrCycle may have advanced since then.
679 if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
680 PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
681
Andrew Trick8823dec2012-03-14 04:00:41 +0000682 --PredSU->NumSuccsLeft;
683 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
684 SchedImpl->releaseBottomNode(PredSU);
685}
686
687/// releasePredecessors - Call releasePred on each of SU's predecessors.
688void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
Javed Absare3a0cc22017-06-21 09:10:10 +0000689 for (SDep &Pred : SU->Preds)
690 releasePred(SU, &Pred);
Andrew Trick8823dec2012-03-14 04:00:41 +0000691}
692
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000693void ScheduleDAGMI::startBlock(MachineBasicBlock *bb) {
694 ScheduleDAGInstrs::startBlock(bb);
695 SchedImpl->enterMBB(bb);
696}
697
698void ScheduleDAGMI::finishBlock() {
699 SchedImpl->leaveMBB();
700 ScheduleDAGInstrs::finishBlock();
701}
702
Andrew Trickd7f890e2013-12-28 21:56:47 +0000703/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
704/// crossing a scheduling boundary. [begin, end) includes all instructions in
705/// the region, including the boundary itself and single-instruction regions
706/// that don't get scheduled.
707void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
708 MachineBasicBlock::iterator begin,
709 MachineBasicBlock::iterator end,
710 unsigned regioninstrs)
711{
712 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
713
714 SchedImpl->initPolicy(begin, end, regioninstrs);
715}
716
Andrew Tricke833e1c2013-04-13 06:07:40 +0000717/// This is normally called from the main scheduler loop but may also be invoked
718/// by the scheduling strategy to perform additional code motion.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000719void ScheduleDAGMI::moveInstruction(
720 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000721 // Advance RegionBegin if the first instruction moves down.
Andrew Trick54f7def2012-03-21 04:12:10 +0000722 if (&*RegionBegin == MI)
Andrew Trick463b2f12012-05-17 18:35:03 +0000723 ++RegionBegin;
724
725 // Update the instruction stream.
Andrew Trick8823dec2012-03-14 04:00:41 +0000726 BB->splice(InsertPos, BB, MI);
Andrew Trick463b2f12012-05-17 18:35:03 +0000727
728 // Update LiveIntervals
Andrew Trickd7f890e2013-12-28 21:56:47 +0000729 if (LIS)
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +0000730 LIS->handleMove(*MI, /*UpdateFlags=*/true);
Andrew Trick463b2f12012-05-17 18:35:03 +0000731
732 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick8823dec2012-03-14 04:00:41 +0000733 if (RegionBegin == InsertPos)
734 RegionBegin = MI;
735}
736
Andrew Trickde670c02012-03-21 04:12:07 +0000737bool ScheduleDAGMI::checkSchedLimit() {
738#ifndef NDEBUG
739 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
740 CurrentTop = CurrentBottom;
741 return false;
742 }
743 ++NumInstrsScheduled;
744#endif
745 return true;
746}
747
Andrew Trickd7f890e2013-12-28 21:56:47 +0000748/// Per-region scheduling driver, called back from
749/// MachineScheduler::runOnMachineFunction. This is a simplified driver that
750/// does not consider liveness or register pressure. It is useful for PostRA
751/// scheduling and potentially other custom schedulers.
752void ScheduleDAGMI::schedule() {
James Y Knighte72b0db2015-09-18 18:52:20 +0000753 DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n");
754 DEBUG(SchedImpl->dumpPolicy());
755
Andrew Trickd7f890e2013-12-28 21:56:47 +0000756 // Build the DAG.
757 buildSchedGraph(AA);
758
759 Topo.InitDAGTopologicalSorting();
760
761 postprocessDAG();
762
763 SmallVector<SUnit*, 8> TopRoots, BotRoots;
764 findRootsAndBiasEdges(TopRoots, BotRoots);
765
766 // Initialize the strategy before modifying the DAG.
767 // This may initialize a DFSResult to be used for queue priority.
768 SchedImpl->initialize(this);
769
Matthias Braun69f1d122016-11-11 22:37:28 +0000770 DEBUG(
771 if (EntrySU.getInstr() != nullptr)
772 EntrySU.dumpAll(this);
Javed Absare3a0cc22017-06-21 09:10:10 +0000773 for (const SUnit &SU : SUnits)
774 SU.dumpAll(this);
Matthias Braun69f1d122016-11-11 22:37:28 +0000775 if (ExitSU.getInstr() != nullptr)
776 ExitSU.dumpAll(this);
777 );
Andrew Trickd7f890e2013-12-28 21:56:47 +0000778 if (ViewMISchedDAGs) viewGraph();
779
780 // Initialize ready queues now that the DAG and priority data are finalized.
781 initQueues(TopRoots, BotRoots);
782
783 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +0000784 while (true) {
785 DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n");
786 SUnit *SU = SchedImpl->pickNode(IsTopNode);
787 if (!SU) break;
788
Andrew Trickd7f890e2013-12-28 21:56:47 +0000789 assert(!SU->isScheduled && "Node already scheduled");
790 if (!checkSchedLimit())
791 break;
792
793 MachineInstr *MI = SU->getInstr();
794 if (IsTopNode) {
795 assert(SU->isTopReady() && "node still has unscheduled dependencies");
796 if (&*CurrentTop == MI)
797 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
798 else
799 moveInstruction(MI, CurrentTop);
Matthias Braunb550b762016-04-21 01:54:13 +0000800 } else {
Andrew Trickd7f890e2013-12-28 21:56:47 +0000801 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
802 MachineBasicBlock::iterator priorII =
803 priorNonDebug(CurrentBottom, CurrentTop);
804 if (&*priorII == MI)
805 CurrentBottom = priorII;
806 else {
807 if (&*CurrentTop == MI)
808 CurrentTop = nextIfDebug(++CurrentTop, priorII);
809 moveInstruction(MI, CurrentBottom);
810 CurrentBottom = MI;
811 }
812 }
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000813 // Notify the scheduling strategy before updating the DAG.
Andrew Trick491e34a2014-06-12 22:36:28 +0000814 // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000815 // runs, it can then use the accurate ReadyCycle time to determine whether
816 // newly released nodes can move to the readyQ.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000817 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000818
819 updateQueues(SU, IsTopNode);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000820 }
821 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
822
823 placeDebugValues();
824
825 DEBUG({
826 unsigned BBNum = begin()->getParent()->getNumber();
827 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
828 dumpSchedule();
829 dbgs() << '\n';
830 });
831}
832
833/// Apply each ScheduleDAGMutation step in order.
834void ScheduleDAGMI::postprocessDAG() {
Javed Absare3a0cc22017-06-21 09:10:10 +0000835 for (auto &m : Mutations)
836 m->apply(this);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000837}
838
839void ScheduleDAGMI::
840findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
841 SmallVectorImpl<SUnit*> &BotRoots) {
Javed Absare3a0cc22017-06-21 09:10:10 +0000842 for (SUnit &SU : SUnits) {
843 assert(!SU.isBoundaryNode() && "Boundary node should not be in SUnits");
Andrew Trickd7f890e2013-12-28 21:56:47 +0000844
845 // Order predecessors so DFSResult follows the critical path.
Javed Absare3a0cc22017-06-21 09:10:10 +0000846 SU.biasCriticalPath();
Andrew Trickd7f890e2013-12-28 21:56:47 +0000847
848 // A SUnit is ready to top schedule if it has no predecessors.
Javed Absare3a0cc22017-06-21 09:10:10 +0000849 if (!SU.NumPredsLeft)
850 TopRoots.push_back(&SU);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000851 // A SUnit is ready to bottom schedule if it has no successors.
Javed Absare3a0cc22017-06-21 09:10:10 +0000852 if (!SU.NumSuccsLeft)
853 BotRoots.push_back(&SU);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000854 }
855 ExitSU.biasCriticalPath();
856}
857
858/// Identify DAG roots and setup scheduler queues.
859void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
860 ArrayRef<SUnit*> BotRoots) {
Craig Topperc0196b12014-04-14 00:51:57 +0000861 NextClusterSucc = nullptr;
862 NextClusterPred = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000863
864 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
865 //
866 // Nodes with unreleased weak edges can still be roots.
867 // Release top roots in forward order.
Javed Absare3a0cc22017-06-21 09:10:10 +0000868 for (SUnit *SU : TopRoots)
869 SchedImpl->releaseTopNode(SU);
870
Andrew Trickd7f890e2013-12-28 21:56:47 +0000871 // Release bottom roots in reverse order so the higher priority nodes appear
872 // first. This is more natural and slightly more efficient.
873 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
874 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
875 SchedImpl->releaseBottomNode(*I);
876 }
877
878 releaseSuccessors(&EntrySU);
879 releasePredecessors(&ExitSU);
880
881 SchedImpl->registerRoots();
882
883 // Advance past initial DebugValues.
884 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
885 CurrentBottom = RegionEnd;
886}
887
888/// Update scheduler queues after scheduling an instruction.
889void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
890 // Release dependent instructions for scheduling.
891 if (IsTopNode)
892 releaseSuccessors(SU);
893 else
894 releasePredecessors(SU);
895
896 SU->isScheduled = true;
897}
898
899/// Reinsert any remaining debug_values, just like the PostRA scheduler.
900void ScheduleDAGMI::placeDebugValues() {
901 // If first instruction was a DBG_VALUE then put it back.
902 if (FirstDbgValue) {
903 BB->splice(RegionBegin, BB, FirstDbgValue);
904 RegionBegin = FirstDbgValue;
905 }
906
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000907 for (std::vector<std::pair<MachineInstr *, MachineInstr *>>::iterator
Andrew Trickd7f890e2013-12-28 21:56:47 +0000908 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000909 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000910 MachineInstr *DbgValue = P.first;
911 MachineBasicBlock::iterator OrigPrevMI = P.second;
912 if (&*RegionBegin == DbgValue)
913 ++RegionBegin;
914 BB->splice(++OrigPrevMI, BB, DbgValue);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000915 if (OrigPrevMI == std::prev(RegionEnd))
Andrew Trickd7f890e2013-12-28 21:56:47 +0000916 RegionEnd = DbgValue;
917 }
918 DbgValues.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000919 FirstDbgValue = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000920}
921
Aaron Ballman615eb472017-10-15 14:32:27 +0000922#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000923LLVM_DUMP_METHOD void ScheduleDAGMI::dumpSchedule() const {
Andrew Trickd7f890e2013-12-28 21:56:47 +0000924 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
925 if (SUnit *SU = getSUnit(&(*MI)))
926 SU->dump(this);
927 else
928 dbgs() << "Missing SUnit\n";
929 }
930}
931#endif
932
933//===----------------------------------------------------------------------===//
934// ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
935// preservation.
936//===----------------------------------------------------------------------===//
937
938ScheduleDAGMILive::~ScheduleDAGMILive() {
939 delete DFSResult;
940}
941
Matthias Braun40639882016-11-11 22:37:31 +0000942void ScheduleDAGMILive::collectVRegUses(SUnit &SU) {
943 const MachineInstr &MI = *SU.getInstr();
944 for (const MachineOperand &MO : MI.operands()) {
945 if (!MO.isReg())
946 continue;
947 if (!MO.readsReg())
948 continue;
949 if (TrackLaneMasks && !MO.isUse())
950 continue;
951
952 unsigned Reg = MO.getReg();
953 if (!TargetRegisterInfo::isVirtualRegister(Reg))
954 continue;
955
956 // Ignore re-defs.
957 if (TrackLaneMasks) {
958 bool FoundDef = false;
959 for (const MachineOperand &MO2 : MI.operands()) {
960 if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
961 FoundDef = true;
962 break;
963 }
964 }
965 if (FoundDef)
966 continue;
967 }
968
969 // Record this local VReg use.
970 VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg);
971 for (; UI != VRegUses.end(); ++UI) {
972 if (UI->SU == &SU)
973 break;
974 }
975 if (UI == VRegUses.end())
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000976 VRegUses.insert(VReg2SUnit(Reg, LaneBitmask::getNone(), &SU));
Matthias Braun40639882016-11-11 22:37:31 +0000977 }
978}
979
Andrew Trick88639922012-04-24 17:56:43 +0000980/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
981/// crossing a scheduling boundary. [begin, end) includes all instructions in
982/// the region, including the boundary itself and single-instruction regions
983/// that don't get scheduled.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000984void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
Andrew Trick88639922012-04-24 17:56:43 +0000985 MachineBasicBlock::iterator begin,
986 MachineBasicBlock::iterator end,
Andrew Tricka53e1012013-08-23 17:48:33 +0000987 unsigned regioninstrs)
Andrew Trick88639922012-04-24 17:56:43 +0000988{
Andrew Trickd7f890e2013-12-28 21:56:47 +0000989 // ScheduleDAGMI initializes SchedImpl's per-region policy.
990 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
Andrew Trick4add42f2012-05-10 21:06:10 +0000991
992 // For convenience remember the end of the liveness region.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000993 LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
Andrew Trick75e411c2013-09-06 17:32:34 +0000994
Andrew Trickb248b4a2013-09-06 17:32:47 +0000995 SUPressureDiffs.clear();
996
Andrew Trick75e411c2013-09-06 17:32:34 +0000997 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
Matthias Braund4f64092016-01-20 00:23:32 +0000998 ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
999
Matthias Braunf9acaca2016-05-31 22:38:06 +00001000 assert((!ShouldTrackLaneMasks || ShouldTrackPressure) &&
1001 "ShouldTrackLaneMasks requires ShouldTrackPressure");
Andrew Trick4add42f2012-05-10 21:06:10 +00001002}
1003
1004// Setup the register pressure trackers for the top scheduled top and bottom
1005// scheduled regions.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001006void ScheduleDAGMILive::initRegPressure() {
Matthias Braun40639882016-11-11 22:37:31 +00001007 VRegUses.clear();
1008 VRegUses.setUniverse(MRI.getNumVirtRegs());
1009 for (SUnit &SU : SUnits)
1010 collectVRegUses(SU);
1011
Matthias Braund4f64092016-01-20 00:23:32 +00001012 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin,
1013 ShouldTrackLaneMasks, false);
1014 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
1015 ShouldTrackLaneMasks, false);
Andrew Trick4add42f2012-05-10 21:06:10 +00001016
1017 // Close the RPTracker to finalize live ins.
1018 RPTracker.closeRegion();
1019
Andrew Trick9c17eab2013-07-30 19:59:12 +00001020 DEBUG(RPTracker.dump());
Andrew Trick79d3eec2012-05-24 22:11:14 +00001021
Andrew Trick4add42f2012-05-10 21:06:10 +00001022 // Initialize the live ins and live outs.
Matthias Braun3e86de12015-09-17 21:12:24 +00001023 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
1024 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick4add42f2012-05-10 21:06:10 +00001025
1026 // Close one end of the tracker so we can call
1027 // getMaxUpward/DownwardPressureDelta before advancing across any
1028 // instructions. This converts currently live regs into live ins/outs.
1029 TopRPTracker.closeTop();
1030 BotRPTracker.closeBottom();
1031
Andrew Trick9c17eab2013-07-30 19:59:12 +00001032 BotRPTracker.initLiveThru(RPTracker);
1033 if (!BotRPTracker.getLiveThru().empty()) {
1034 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
1035 DEBUG(dbgs() << "Live Thru: ";
1036 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
1037 };
1038
Andrew Trick2bc74c22013-08-30 04:36:57 +00001039 // For each live out vreg reduce the pressure change associated with other
1040 // uses of the same vreg below the live-out reaching def.
Matthias Braun3e86de12015-09-17 21:12:24 +00001041 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick2bc74c22013-08-30 04:36:57 +00001042
Andrew Trick4add42f2012-05-10 21:06:10 +00001043 // Account for liveness generated by the region boundary.
Andrew Trick2bc74c22013-08-30 04:36:57 +00001044 if (LiveRegionEnd != RegionEnd) {
Matthias Braun5d458612016-01-20 00:23:26 +00001045 SmallVector<RegisterMaskPair, 8> LiveUses;
Andrew Trick2bc74c22013-08-30 04:36:57 +00001046 BotRPTracker.recede(&LiveUses);
1047 updatePressureDiffs(LiveUses);
1048 }
Andrew Trick4add42f2012-05-10 21:06:10 +00001049
Matthias Braune6edd482015-11-13 22:30:31 +00001050 DEBUG(
1051 dbgs() << "Top Pressure:\n";
1052 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
1053 dbgs() << "Bottom Pressure:\n";
1054 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);
1055 );
1056
Andrew Trick4add42f2012-05-10 21:06:10 +00001057 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick22025772012-05-17 18:35:10 +00001058
1059 // Cache the list of excess pressure sets in this region. This will also track
1060 // the max pressure in the scheduled code for these sets.
1061 RegionCriticalPSets.clear();
Jakub Staszakc641ada2013-01-25 21:44:27 +00001062 const std::vector<unsigned> &RegionPressure =
1063 RPTracker.getPressure().MaxSetPressure;
Andrew Trick22025772012-05-17 18:35:10 +00001064 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
Andrew Trick736dd9a2013-06-21 18:32:58 +00001065 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
Andrew Trickb55db582013-06-21 18:33:01 +00001066 if (RegionPressure[i] > Limit) {
1067 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
1068 << " Limit " << Limit
1069 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick1a831342013-08-30 03:49:48 +00001070 RegionCriticalPSets.push_back(PressureChange(i));
Andrew Trickb55db582013-06-21 18:33:01 +00001071 }
Andrew Trick22025772012-05-17 18:35:10 +00001072 }
1073 DEBUG(dbgs() << "Excess PSets: ";
Javed Absare3a0cc22017-06-21 09:10:10 +00001074 for (const PressureChange &RCPS : RegionCriticalPSets)
Andrew Trick22025772012-05-17 18:35:10 +00001075 dbgs() << TRI->getRegPressureSetName(
Javed Absare3a0cc22017-06-21 09:10:10 +00001076 RCPS.getPSet()) << " ";
Andrew Trick22025772012-05-17 18:35:10 +00001077 dbgs() << "\n");
1078}
1079
Andrew Trickd7f890e2013-12-28 21:56:47 +00001080void ScheduleDAGMILive::
Andrew Trickb248b4a2013-09-06 17:32:47 +00001081updateScheduledPressure(const SUnit *SU,
1082 const std::vector<unsigned> &NewMaxPressure) {
1083 const PressureDiff &PDiff = getPressureDiff(SU);
1084 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
Javed Absare3a0cc22017-06-21 09:10:10 +00001085 for (const PressureChange &PC : PDiff) {
1086 if (!PC.isValid())
Andrew Trickb248b4a2013-09-06 17:32:47 +00001087 break;
Javed Absare3a0cc22017-06-21 09:10:10 +00001088 unsigned ID = PC.getPSet();
Andrew Trickb248b4a2013-09-06 17:32:47 +00001089 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
1090 ++CritIdx;
1091 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
1092 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
Simon Pilgrim858d8e62017-02-23 12:00:34 +00001093 && NewMaxPressure[ID] <= (unsigned)std::numeric_limits<int16_t>::max())
Andrew Trickb248b4a2013-09-06 17:32:47 +00001094 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
1095 }
1096 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
1097 if (NewMaxPressure[ID] >= Limit - 2) {
1098 DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
Andrew Trick569dc65a2015-05-17 23:40:31 +00001099 << NewMaxPressure[ID]
1100 << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ") << Limit
1101 << "(+ " << BotRPTracker.getLiveThru()[ID] << " livethru)\n");
Andrew Trickb248b4a2013-09-06 17:32:47 +00001102 }
Andrew Trick22025772012-05-17 18:35:10 +00001103 }
Andrew Trick88639922012-04-24 17:56:43 +00001104}
1105
Andrew Trick2bc74c22013-08-30 04:36:57 +00001106/// Update the PressureDiff array for liveness after scheduling this
1107/// instruction.
Matthias Braun5d458612016-01-20 00:23:26 +00001108void ScheduleDAGMILive::updatePressureDiffs(
1109 ArrayRef<RegisterMaskPair> LiveUses) {
1110 for (const RegisterMaskPair &P : LiveUses) {
Matthias Braun5d458612016-01-20 00:23:26 +00001111 unsigned Reg = P.RegUnit;
Matthias Braund4f64092016-01-20 00:23:32 +00001112 /// FIXME: Currently assuming single-use physregs.
Andrew Trick2bc74c22013-08-30 04:36:57 +00001113 if (!TRI->isVirtualRegister(Reg))
1114 continue;
Andrew Trickffdbefb2013-09-06 17:32:39 +00001115
Matthias Braund4f64092016-01-20 00:23:32 +00001116 if (ShouldTrackLaneMasks) {
1117 // If the register has just become live then other uses won't change
1118 // this fact anymore => decrement pressure.
1119 // If the register has just become dead then other uses make it come
1120 // back to life => increment pressure.
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +00001121 bool Decrement = P.LaneMask.any();
Matthias Braund4f64092016-01-20 00:23:32 +00001122
1123 for (const VReg2SUnit &V2SU
1124 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1125 SUnit &SU = *V2SU.SU;
1126 if (SU.isScheduled || &SU == &ExitSU)
1127 continue;
1128
1129 PressureDiff &PDiff = getPressureDiff(&SU);
Stanislav Mekhanoshin42259cf2017-02-24 21:56:16 +00001130 PDiff.addPressureChange(Reg, Decrement, &MRI);
Matthias Braund4f64092016-01-20 00:23:32 +00001131 DEBUG(
1132 dbgs() << " UpdateRegP: SU(" << SU.NodeNum << ") "
1133 << PrintReg(Reg, TRI) << ':' << PrintLaneMask(P.LaneMask)
1134 << ' ' << *SU.getInstr();
1135 dbgs() << " to ";
1136 PDiff.dump(*TRI);
1137 );
1138 }
1139 } else {
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +00001140 assert(P.LaneMask.any());
Matthias Braund4f64092016-01-20 00:23:32 +00001141 DEBUG(dbgs() << " LiveReg: " << PrintVRegOrUnit(Reg, TRI) << "\n");
1142 // This may be called before CurrentBottom has been initialized. However,
1143 // BotRPTracker must have a valid position. We want the value live into the
1144 // instruction or live out of the block, so ask for the previous
1145 // instruction's live-out.
1146 const LiveInterval &LI = LIS->getInterval(Reg);
1147 VNInfo *VNI;
1148 MachineBasicBlock::const_iterator I =
1149 nextIfDebug(BotRPTracker.getPos(), BB->end());
1150 if (I == BB->end())
1151 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1152 else {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001153 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I));
Matthias Braund4f64092016-01-20 00:23:32 +00001154 VNI = LRQ.valueIn();
1155 }
1156 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
1157 assert(VNI && "No live value at use.");
1158 for (const VReg2SUnit &V2SU
1159 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1160 SUnit *SU = V2SU.SU;
1161 // If this use comes before the reaching def, it cannot be a last use,
1162 // so decrease its pressure change.
1163 if (!SU->isScheduled && SU != &ExitSU) {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001164 LiveQueryResult LRQ =
1165 LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Matthias Braund4f64092016-01-20 00:23:32 +00001166 if (LRQ.valueIn() == VNI) {
1167 PressureDiff &PDiff = getPressureDiff(SU);
Stanislav Mekhanoshin42259cf2017-02-24 21:56:16 +00001168 PDiff.addPressureChange(Reg, true, &MRI);
Matthias Braund4f64092016-01-20 00:23:32 +00001169 DEBUG(
1170 dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
1171 << *SU->getInstr();
1172 dbgs() << " to ";
1173 PDiff.dump(*TRI);
1174 );
1175 }
Matthias Braun9198c672015-11-06 20:59:02 +00001176 }
Andrew Trick2bc74c22013-08-30 04:36:57 +00001177 }
1178 }
1179 }
1180}
1181
Andrew Trick8823dec2012-03-14 04:00:41 +00001182/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick88639922012-04-24 17:56:43 +00001183/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
1184/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick7a8e1002012-09-11 00:39:15 +00001185///
1186/// This is a skeletal driver, with all the functionality pushed into helpers,
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001187/// so that it can be easily extended by experimental schedulers. Generally,
Andrew Trick7a8e1002012-09-11 00:39:15 +00001188/// implementing MachineSchedStrategy should be sufficient to implement a new
1189/// scheduling algorithm. However, if a scheduler further subclasses
Andrew Trickd7f890e2013-12-28 21:56:47 +00001190/// ScheduleDAGMILive then it will want to override this virtual method in order
1191/// to update any specialized state.
1192void ScheduleDAGMILive::schedule() {
James Y Knighte72b0db2015-09-18 18:52:20 +00001193 DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n");
1194 DEBUG(SchedImpl->dumpPolicy());
Andrew Trick7a8e1002012-09-11 00:39:15 +00001195 buildDAGWithRegPressure();
1196
Andrew Tricka7714a02012-11-12 19:40:10 +00001197 Topo.InitDAGTopologicalSorting();
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 Braun9198c672015-11-06 20:59:02 +00001208 DEBUG(
Matthias Braun69f1d122016-11-11 22:37:28 +00001209 if (EntrySU.getInstr() != nullptr)
1210 EntrySU.dumpAll(this);
Matthias Braun9198c672015-11-06 20:59:02 +00001211 for (const SUnit &SU : SUnits) {
1212 SU.dumpAll(this);
1213 if (ShouldTrackPressure) {
1214 dbgs() << " Pressure Diff : ";
1215 getPressureDiff(&SU).dump(*TRI);
1216 }
Javed Absar3d594372017-03-27 20:46:37 +00001217 dbgs() << " Single Issue : ";
1218 if (SchedModel.mustBeginGroup(SU.getInstr()) &&
1219 SchedModel.mustEndGroup(SU.getInstr()))
1220 dbgs() << "true;";
1221 else
1222 dbgs() << "false;";
Matthias Braun9198c672015-11-06 20:59:02 +00001223 dbgs() << '\n';
1224 }
Matthias Braun69f1d122016-11-11 22:37:28 +00001225 if (ExitSU.getInstr() != nullptr)
1226 ExitSU.dumpAll(this);
Matthias Braun9198c672015-11-06 20:59:02 +00001227 );
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001228 if (ViewMISchedDAGs) viewGraph();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001229
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001230 // Initialize ready queues now that the DAG and priority data are finalized.
1231 initQueues(TopRoots, BotRoots);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001232
1233 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +00001234 while (true) {
1235 DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n");
1236 SUnit *SU = SchedImpl->pickNode(IsTopNode);
1237 if (!SU) break;
1238
Andrew Trick984d98b2012-10-08 18:53:53 +00001239 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick7a8e1002012-09-11 00:39:15 +00001240 if (!checkSchedLimit())
1241 break;
1242
1243 scheduleMI(SU, IsTopNode);
1244
Andrew Trickd7f890e2013-12-28 21:56:47 +00001245 if (DFSResult) {
1246 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1247 if (!ScheduledTrees.test(SubtreeID)) {
1248 ScheduledTrees.set(SubtreeID);
1249 DFSResult->scheduleTree(SubtreeID);
1250 SchedImpl->scheduleTree(SubtreeID);
1251 }
1252 }
1253
1254 // Notify the scheduling strategy after updating the DAG.
1255 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick43adfb32015-03-27 06:10:13 +00001256
1257 updateQueues(SU, IsTopNode);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001258 }
1259 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1260
1261 placeDebugValues();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001262
1263 DEBUG({
Andrew Trickcf7e6972012-11-28 03:42:47 +00001264 unsigned BBNum = begin()->getParent()->getNumber();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001265 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
1266 dumpSchedule();
1267 dbgs() << '\n';
1268 });
Andrew Trick7a8e1002012-09-11 00:39:15 +00001269}
1270
1271/// Build the DAG and setup three register pressure trackers.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001272void ScheduleDAGMILive::buildDAGWithRegPressure() {
Andrew Trickb6e74712013-09-04 20:59:59 +00001273 if (!ShouldTrackPressure) {
1274 RPTracker.reset();
1275 RegionCriticalPSets.clear();
1276 buildSchedGraph(AA);
1277 return;
1278 }
1279
Andrew Trick4add42f2012-05-10 21:06:10 +00001280 // Initialize the register pressure tracker used by buildSchedGraph.
Andrew Trick9c17eab2013-07-30 19:59:12 +00001281 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
Matthias Braund4f64092016-01-20 00:23:32 +00001282 ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true);
Andrew Trick88639922012-04-24 17:56:43 +00001283
Andrew Trick4add42f2012-05-10 21:06:10 +00001284 // Account for liveness generate by the region boundary.
1285 if (LiveRegionEnd != RegionEnd)
1286 RPTracker.recede();
1287
1288 // Build the DAG, and compute current register pressure.
Matthias Braund4f64092016-01-20 00:23:32 +00001289 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks);
Andrew Trick02a80da2012-03-08 01:41:12 +00001290
Andrew Trick4add42f2012-05-10 21:06:10 +00001291 // Initialize top/bottom trackers after computing region pressure.
1292 initRegPressure();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001293}
Andrew Trick4add42f2012-05-10 21:06:10 +00001294
Andrew Trickd7f890e2013-12-28 21:56:47 +00001295void ScheduleDAGMILive::computeDFSResult() {
Andrew Trick44f750a2013-01-25 04:01:04 +00001296 if (!DFSResult)
1297 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1298 DFSResult->clear();
Andrew Trick44f750a2013-01-25 04:01:04 +00001299 ScheduledTrees.clear();
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001300 DFSResult->resize(SUnits.size());
1301 DFSResult->compute(SUnits);
Andrew Trick44f750a2013-01-25 04:01:04 +00001302 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1303}
1304
Andrew Trick483f4192013-08-29 18:04:49 +00001305/// Compute the max cyclic critical path through the DAG. The scheduling DAG
1306/// only provides the critical path for single block loops. To handle loops that
1307/// span blocks, we could use the vreg path latencies provided by
1308/// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1309/// available for use in the scheduler.
1310///
1311/// The cyclic path estimation identifies a def-use pair that crosses the back
Andrew Trickef80f502013-08-30 02:02:12 +00001312/// edge and considers the depth and height of the nodes. For example, consider
Andrew Trick483f4192013-08-29 18:04:49 +00001313/// the following instruction sequence where each instruction has unit latency
1314/// and defines an epomymous virtual register:
1315///
1316/// a->b(a,c)->c(b)->d(c)->exit
1317///
1318/// The cyclic critical path is a two cycles: b->c->b
1319/// The acyclic critical path is four cycles: a->b->c->d->exit
1320/// LiveOutHeight = height(c) = len(c->d->exit) = 2
1321/// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1322/// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1323/// LiveInDepth = depth(b) = len(a->b) = 1
1324///
1325/// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1326/// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1327/// CyclicCriticalPath = min(2, 2) = 2
Andrew Trickd7f890e2013-12-28 21:56:47 +00001328///
1329/// This could be relevant to PostRA scheduling, but is currently implemented
1330/// assuming LiveIntervals.
1331unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
Andrew Trick483f4192013-08-29 18:04:49 +00001332 // This only applies to single block loop.
1333 if (!BB->isSuccessor(BB))
1334 return 0;
1335
1336 unsigned MaxCyclicLatency = 0;
1337 // Visit each live out vreg def to find def/use pairs that cross iterations.
Matthias Braun5d458612016-01-20 00:23:26 +00001338 for (const RegisterMaskPair &P : RPTracker.getPressure().LiveOutRegs) {
1339 unsigned Reg = P.RegUnit;
Andrew Trick483f4192013-08-29 18:04:49 +00001340 if (!TRI->isVirtualRegister(Reg))
1341 continue;
1342 const LiveInterval &LI = LIS->getInterval(Reg);
1343 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1344 if (!DefVNI)
1345 continue;
1346
1347 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1348 const SUnit *DefSU = getSUnit(DefMI);
1349 if (!DefSU)
1350 continue;
1351
1352 unsigned LiveOutHeight = DefSU->getHeight();
1353 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1354 // Visit all local users of the vreg def.
Matthias Braunb0c437b2015-10-29 03:57:17 +00001355 for (const VReg2SUnit &V2SU
1356 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1357 SUnit *SU = V2SU.SU;
1358 if (SU == &ExitSU)
Andrew Trick483f4192013-08-29 18:04:49 +00001359 continue;
1360
1361 // Only consider uses of the phi.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001362 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Andrew Trick483f4192013-08-29 18:04:49 +00001363 if (!LRQ.valueIn()->isPHIDef())
1364 continue;
1365
1366 // Assume that a path spanning two iterations is a cycle, which could
1367 // overestimate in strange cases. This allows cyclic latency to be
1368 // estimated as the minimum slack of the vreg's depth or height.
1369 unsigned CyclicLatency = 0;
Matthias Braunb0c437b2015-10-29 03:57:17 +00001370 if (LiveOutDepth > SU->getDepth())
1371 CyclicLatency = LiveOutDepth - SU->getDepth();
Andrew Trick483f4192013-08-29 18:04:49 +00001372
Matthias Braunb0c437b2015-10-29 03:57:17 +00001373 unsigned LiveInHeight = SU->getHeight() + DefSU->Latency;
Andrew Trick483f4192013-08-29 18:04:49 +00001374 if (LiveInHeight > LiveOutHeight) {
1375 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1376 CyclicLatency = LiveInHeight - LiveOutHeight;
Matthias Braunb550b762016-04-21 01:54:13 +00001377 } else
Andrew Trick483f4192013-08-29 18:04:49 +00001378 CyclicLatency = 0;
1379
1380 DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
Matthias Braunb0c437b2015-10-29 03:57:17 +00001381 << SU->NodeNum << ") = " << CyclicLatency << "c\n");
Andrew Trick483f4192013-08-29 18:04:49 +00001382 if (CyclicLatency > MaxCyclicLatency)
1383 MaxCyclicLatency = CyclicLatency;
1384 }
1385 }
1386 DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
1387 return MaxCyclicLatency;
1388}
1389
Krzysztof Parzyszek7ea9a522016-04-28 19:17:44 +00001390/// Release ExitSU predecessors and setup scheduler queues. Re-position
1391/// the Top RP tracker in case the region beginning has changed.
1392void ScheduleDAGMILive::initQueues(ArrayRef<SUnit*> TopRoots,
1393 ArrayRef<SUnit*> BotRoots) {
1394 ScheduleDAGMI::initQueues(TopRoots, BotRoots);
1395 if (ShouldTrackPressure) {
1396 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
1397 TopRPTracker.setPos(CurrentTop);
1398 }
1399}
1400
Andrew Trick7a8e1002012-09-11 00:39:15 +00001401/// Move an instruction and update register pressure.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001402void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001403 // Move the instruction to its new location in the instruction stream.
1404 MachineInstr *MI = SU->getInstr();
Andrew Trick02a80da2012-03-08 01:41:12 +00001405
Andrew Trick7a8e1002012-09-11 00:39:15 +00001406 if (IsTopNode) {
1407 assert(SU->isTopReady() && "node still has unscheduled dependencies");
1408 if (&*CurrentTop == MI)
1409 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick8823dec2012-03-14 04:00:41 +00001410 else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001411 moveInstruction(MI, CurrentTop);
1412 TopRPTracker.setPos(MI);
Andrew Trick8823dec2012-03-14 04:00:41 +00001413 }
Andrew Trickc3ea0052012-04-24 18:04:37 +00001414
Andrew Trickb6e74712013-09-04 20:59:59 +00001415 if (ShouldTrackPressure) {
1416 // Update top scheduled pressure.
Matthias Braund4f64092016-01-20 00:23:32 +00001417 RegisterOperands RegOpers;
1418 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1419 if (ShouldTrackLaneMasks) {
1420 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001421 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund4f64092016-01-20 00:23:32 +00001422 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1423 } else {
1424 // Adjust for missing dead-def flags.
1425 RegOpers.detectDeadDefs(*MI, *LIS);
1426 }
1427
1428 TopRPTracker.advance(RegOpers);
Andrew Trickb6e74712013-09-04 20:59:59 +00001429 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
Matthias Braun9198c672015-11-06 20:59:02 +00001430 DEBUG(
1431 dbgs() << "Top Pressure:\n";
1432 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
1433 );
1434
Andrew Trickb248b4a2013-09-06 17:32:47 +00001435 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001436 }
Matthias Braunb550b762016-04-21 01:54:13 +00001437 } else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001438 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1439 MachineBasicBlock::iterator priorII =
1440 priorNonDebug(CurrentBottom, CurrentTop);
1441 if (&*priorII == MI)
1442 CurrentBottom = priorII;
1443 else {
1444 if (&*CurrentTop == MI) {
1445 CurrentTop = nextIfDebug(++CurrentTop, priorII);
1446 TopRPTracker.setPos(CurrentTop);
1447 }
1448 moveInstruction(MI, CurrentBottom);
1449 CurrentBottom = MI;
1450 }
Andrew Trickb6e74712013-09-04 20:59:59 +00001451 if (ShouldTrackPressure) {
Matthias Braund4f64092016-01-20 00:23:32 +00001452 RegisterOperands RegOpers;
1453 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1454 if (ShouldTrackLaneMasks) {
1455 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001456 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund4f64092016-01-20 00:23:32 +00001457 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1458 } else {
1459 // Adjust for missing dead-def flags.
1460 RegOpers.detectDeadDefs(*MI, *LIS);
1461 }
1462
1463 BotRPTracker.recedeSkipDebugValues();
Matthias Braun5d458612016-01-20 00:23:26 +00001464 SmallVector<RegisterMaskPair, 8> LiveUses;
Matthias Braund4f64092016-01-20 00:23:32 +00001465 BotRPTracker.recede(RegOpers, &LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001466 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
Matthias Braun9198c672015-11-06 20:59:02 +00001467 DEBUG(
1468 dbgs() << "Bottom Pressure:\n";
1469 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);
1470 );
1471
Andrew Trickb248b4a2013-09-06 17:32:47 +00001472 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001473 updatePressureDiffs(LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001474 }
Andrew Trick7a8e1002012-09-11 00:39:15 +00001475 }
1476}
1477
Andrew Trick263280242012-11-12 19:52:20 +00001478//===----------------------------------------------------------------------===//
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001479// BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores.
Andrew Trick263280242012-11-12 19:52:20 +00001480//===----------------------------------------------------------------------===//
1481
Andrew Tricka7714a02012-11-12 19:40:10 +00001482namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001483
Andrew Tricka7714a02012-11-12 19:40:10 +00001484/// \brief Post-process the DAG to create cluster edges between neighboring
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001485/// loads or between neighboring stores.
1486class BaseMemOpClusterMutation : public ScheduleDAGMutation {
1487 struct MemOpInfo {
Andrew Tricka7714a02012-11-12 19:40:10 +00001488 SUnit *SU;
1489 unsigned BaseReg;
Chad Rosierc27a18f2016-03-09 16:00:35 +00001490 int64_t Offset;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001491
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001492 MemOpInfo(SUnit *su, unsigned reg, int64_t ofs)
1493 : SU(su), BaseReg(reg), Offset(ofs) {}
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001494
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001495 bool operator<(const MemOpInfo&RHS) const {
Mandeep Singh Grange82678a2016-10-18 00:11:19 +00001496 return std::tie(BaseReg, Offset, SU->NodeNum) <
1497 std::tie(RHS.BaseReg, RHS.Offset, RHS.SU->NodeNum);
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001498 }
Andrew Tricka7714a02012-11-12 19:40:10 +00001499 };
Andrew Tricka7714a02012-11-12 19:40:10 +00001500
1501 const TargetInstrInfo *TII;
1502 const TargetRegisterInfo *TRI;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001503 bool IsLoad;
1504
Andrew Tricka7714a02012-11-12 19:40:10 +00001505public:
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001506 BaseMemOpClusterMutation(const TargetInstrInfo *tii,
1507 const TargetRegisterInfo *tri, bool IsLoad)
1508 : TII(tii), TRI(tri), IsLoad(IsLoad) {}
Andrew Tricka7714a02012-11-12 19:40:10 +00001509
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001510 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001511
Andrew Tricka7714a02012-11-12 19:40:10 +00001512protected:
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001513 void clusterNeighboringMemOps(ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG);
1514};
1515
1516class StoreClusterMutation : public BaseMemOpClusterMutation {
1517public:
1518 StoreClusterMutation(const TargetInstrInfo *tii,
1519 const TargetRegisterInfo *tri)
1520 : BaseMemOpClusterMutation(tii, tri, false) {}
1521};
1522
1523class LoadClusterMutation : public BaseMemOpClusterMutation {
1524public:
1525 LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri)
1526 : BaseMemOpClusterMutation(tii, tri, true) {}
Andrew Tricka7714a02012-11-12 19:40:10 +00001527};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001528
1529} // end anonymous namespace
Andrew Tricka7714a02012-11-12 19:40:10 +00001530
Tom Stellard68726a52016-08-19 19:59:18 +00001531namespace llvm {
1532
1533std::unique_ptr<ScheduleDAGMutation>
1534createLoadClusterDAGMutation(const TargetInstrInfo *TII,
1535 const TargetRegisterInfo *TRI) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001536 return EnableMemOpCluster ? llvm::make_unique<LoadClusterMutation>(TII, TRI)
Matthias Braun115efcd2016-11-28 20:11:54 +00001537 : nullptr;
Tom Stellard68726a52016-08-19 19:59:18 +00001538}
1539
1540std::unique_ptr<ScheduleDAGMutation>
1541createStoreClusterDAGMutation(const TargetInstrInfo *TII,
1542 const TargetRegisterInfo *TRI) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001543 return EnableMemOpCluster ? llvm::make_unique<StoreClusterMutation>(TII, TRI)
Matthias Braun115efcd2016-11-28 20:11:54 +00001544 : nullptr;
Tom Stellard68726a52016-08-19 19:59:18 +00001545}
1546
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001547} // end namespace llvm
Tom Stellard68726a52016-08-19 19:59:18 +00001548
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001549void BaseMemOpClusterMutation::clusterNeighboringMemOps(
1550 ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG) {
1551 SmallVector<MemOpInfo, 32> MemOpRecords;
Javed Absare3a0cc22017-06-21 09:10:10 +00001552 for (SUnit *SU : MemOps) {
Andrew Tricka7714a02012-11-12 19:40:10 +00001553 unsigned BaseReg;
Chad Rosierc27a18f2016-03-09 16:00:35 +00001554 int64_t Offset;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001555 if (TII->getMemOpBaseRegImmOfs(*SU->getInstr(), BaseReg, Offset, TRI))
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001556 MemOpRecords.push_back(MemOpInfo(SU, BaseReg, Offset));
Andrew Tricka7714a02012-11-12 19:40:10 +00001557 }
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001558 if (MemOpRecords.size() < 2)
Andrew Tricka7714a02012-11-12 19:40:10 +00001559 return;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001560
1561 std::sort(MemOpRecords.begin(), MemOpRecords.end());
Andrew Tricka7714a02012-11-12 19:40:10 +00001562 unsigned ClusterLength = 1;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001563 for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) {
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001564 SUnit *SUa = MemOpRecords[Idx].SU;
1565 SUnit *SUb = MemOpRecords[Idx+1].SU;
Stanislav Mekhanoshin7fe9a5d2017-09-13 22:20:47 +00001566 if (TII->shouldClusterMemOps(*SUa->getInstr(), MemOpRecords[Idx].BaseReg,
1567 *SUb->getInstr(), MemOpRecords[Idx+1].BaseReg,
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001568 ClusterLength) &&
1569 DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001570 DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU("
Andrew Tricka7714a02012-11-12 19:40:10 +00001571 << SUb->NodeNum << ")\n");
1572 // Copy successor edges from SUa to SUb. Interleaving computation
1573 // dependent on SUa can prevent load combining due to register reuse.
1574 // Predecessor edges do not need to be copied from SUb to SUa since nearby
1575 // loads should have effectively the same inputs.
Javed Absare3a0cc22017-06-21 09:10:10 +00001576 for (const SDep &Succ : SUa->Succs) {
1577 if (Succ.getSUnit() == SUb)
Andrew Tricka7714a02012-11-12 19:40:10 +00001578 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001579 DEBUG(dbgs() << " Copy Succ SU(" << Succ.getSUnit()->NodeNum << ")\n");
1580 DAG->addEdge(Succ.getSUnit(), SDep(SUb, SDep::Artificial));
Andrew Tricka7714a02012-11-12 19:40:10 +00001581 }
1582 ++ClusterLength;
Matthias Braunb550b762016-04-21 01:54:13 +00001583 } else
Andrew Tricka7714a02012-11-12 19:40:10 +00001584 ClusterLength = 1;
1585 }
1586}
1587
1588/// \brief Callback from DAG postProcessing to create cluster edges for loads.
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001589void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAGInstrs) {
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001590 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
1591
Andrew Tricka7714a02012-11-12 19:40:10 +00001592 // Map DAG NodeNum to store chain ID.
1593 DenseMap<unsigned, unsigned> StoreChainIDs;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001594 // Map each store chain to a set of dependent MemOps.
Andrew Tricka7714a02012-11-12 19:40:10 +00001595 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
Javed Absare3a0cc22017-06-21 09:10:10 +00001596 for (SUnit &SU : DAG->SUnits) {
1597 if ((IsLoad && !SU.getInstr()->mayLoad()) ||
1598 (!IsLoad && !SU.getInstr()->mayStore()))
Andrew Tricka7714a02012-11-12 19:40:10 +00001599 continue;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001600
Andrew Tricka7714a02012-11-12 19:40:10 +00001601 unsigned ChainPredID = DAG->SUnits.size();
Javed Absare3a0cc22017-06-21 09:10:10 +00001602 for (const SDep &Pred : SU.Preds) {
1603 if (Pred.isCtrl()) {
1604 ChainPredID = Pred.getSUnit()->NodeNum;
Andrew Tricka7714a02012-11-12 19:40:10 +00001605 break;
1606 }
1607 }
1608 // Check if this chain-like pred has been seen
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001609 // before. ChainPredID==MaxNodeID at the top of the schedule.
Andrew Tricka7714a02012-11-12 19:40:10 +00001610 unsigned NumChains = StoreChainDependents.size();
1611 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1612 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1613 if (Result.second)
1614 StoreChainDependents.resize(NumChains + 1);
Javed Absare3a0cc22017-06-21 09:10:10 +00001615 StoreChainDependents[Result.first->second].push_back(&SU);
Andrew Tricka7714a02012-11-12 19:40:10 +00001616 }
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001617
Andrew Tricka7714a02012-11-12 19:40:10 +00001618 // Iterate over the store chains.
Javed Absare3a0cc22017-06-21 09:10:10 +00001619 for (auto &SCD : StoreChainDependents)
1620 clusterNeighboringMemOps(SCD, DAG);
Andrew Tricka7714a02012-11-12 19:40:10 +00001621}
1622
Andrew Trick02a80da2012-03-08 01:41:12 +00001623//===----------------------------------------------------------------------===//
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001624// CopyConstrain - DAG post-processing to encourage copy elimination.
1625//===----------------------------------------------------------------------===//
1626
1627namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001628
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001629/// \brief Post-process the DAG to create weak edges from all uses of a copy to
1630/// the one use that defines the copy's source vreg, most likely an induction
1631/// variable increment.
1632class CopyConstrain : public ScheduleDAGMutation {
1633 // Transient state.
1634 SlotIndex RegionBeginIdx;
Eugene Zelenko32a40562017-09-11 23:00:48 +00001635
Andrew Trick2e875172013-04-24 23:19:56 +00001636 // RegionEndIdx is the slot index of the last non-debug instruction in the
1637 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001638 SlotIndex RegionEndIdx;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001639
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001640public:
1641 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1642
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001643 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001644
1645protected:
Andrew Trickd7f890e2013-12-28 21:56:47 +00001646 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001647};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001648
1649} // end anonymous namespace
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001650
Tom Stellard68726a52016-08-19 19:59:18 +00001651namespace llvm {
1652
1653std::unique_ptr<ScheduleDAGMutation>
1654createCopyConstrainDAGMutation(const TargetInstrInfo *TII,
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001655 const TargetRegisterInfo *TRI) {
1656 return llvm::make_unique<CopyConstrain>(TII, TRI);
Tom Stellard68726a52016-08-19 19:59:18 +00001657}
1658
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001659} // end namespace llvm
Tom Stellard68726a52016-08-19 19:59:18 +00001660
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001661/// constrainLocalCopy handles two possibilities:
1662/// 1) Local src:
1663/// I0: = dst
1664/// I1: src = ...
1665/// I2: = dst
1666/// I3: dst = src (copy)
1667/// (create pred->succ edges I0->I1, I2->I1)
1668///
1669/// 2) Local copy:
1670/// I0: dst = src (copy)
1671/// I1: = dst
1672/// I2: src = ...
1673/// I3: = dst
1674/// (create pred->succ edges I1->I2, I3->I2)
1675///
1676/// Although the MachineScheduler is currently constrained to single blocks,
1677/// this algorithm should handle extended blocks. An EBB is a set of
1678/// contiguously numbered blocks such that the previous block in the EBB is
1679/// always the single predecessor.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001680void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001681 LiveIntervals *LIS = DAG->getLIS();
1682 MachineInstr *Copy = CopySU->getInstr();
1683
1684 // Check for pure vreg copies.
Matthias Braun7511abd2016-04-04 21:23:46 +00001685 const MachineOperand &SrcOp = Copy->getOperand(1);
1686 unsigned SrcReg = SrcOp.getReg();
1687 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) || !SrcOp.readsReg())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001688 return;
1689
Matthias Braun7511abd2016-04-04 21:23:46 +00001690 const MachineOperand &DstOp = Copy->getOperand(0);
1691 unsigned DstReg = DstOp.getReg();
1692 if (!TargetRegisterInfo::isVirtualRegister(DstReg) || DstOp.isDead())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001693 return;
1694
1695 // Check if either the dest or source is local. If it's live across a back
1696 // edge, it's not local. Note that if both vregs are live across the back
1697 // edge, we cannot successfully contrain the copy without cyclic scheduling.
Michael Kuperstein54c61ed2015-01-19 07:30:47 +00001698 // If both the copy's source and dest are local live intervals, then we
1699 // should treat the dest as the global for the purpose of adding
1700 // constraints. This adds edges from source's other uses to the copy.
1701 unsigned LocalReg = SrcReg;
1702 unsigned GlobalReg = DstReg;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001703 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1704 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
Michael Kuperstein54c61ed2015-01-19 07:30:47 +00001705 LocalReg = DstReg;
1706 GlobalReg = SrcReg;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001707 LocalLI = &LIS->getInterval(LocalReg);
1708 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1709 return;
1710 }
1711 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1712
1713 // Find the global segment after the start of the local LI.
1714 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1715 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1716 // local live range. We could create edges from other global uses to the local
1717 // start, but the coalescer should have already eliminated these cases, so
1718 // don't bother dealing with it.
1719 if (GlobalSegment == GlobalLI->end())
1720 return;
1721
1722 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1723 // returned the next global segment. But if GlobalSegment overlaps with
1724 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1725 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1726 if (GlobalSegment->contains(LocalLI->beginIndex()))
1727 ++GlobalSegment;
1728
1729 if (GlobalSegment == GlobalLI->end())
1730 return;
1731
1732 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1733 if (GlobalSegment != GlobalLI->begin()) {
1734 // Two address defs have no hole.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001735 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001736 GlobalSegment->start)) {
1737 return;
1738 }
Andrew Trickd9761772013-07-30 19:59:08 +00001739 // If the prior global segment may be defined by the same two-address
1740 // instruction that also defines LocalLI, then can't make a hole here.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001741 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
Andrew Trickd9761772013-07-30 19:59:08 +00001742 LocalLI->beginIndex())) {
1743 return;
1744 }
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001745 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1746 // it would be a disconnected component in the live range.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001747 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001748 "Disconnected LRG within the scheduling region.");
1749 }
1750 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1751 if (!GlobalDef)
1752 return;
1753
1754 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1755 if (!GlobalSU)
1756 return;
1757
1758 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1759 // constraining the uses of the last local def to precede GlobalDef.
1760 SmallVector<SUnit*,8> LocalUses;
1761 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1762 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1763 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
Javed Absare3a0cc22017-06-21 09:10:10 +00001764 for (const SDep &Succ : LastLocalSU->Succs) {
1765 if (Succ.getKind() != SDep::Data || Succ.getReg() != LocalReg)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001766 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001767 if (Succ.getSUnit() == GlobalSU)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001768 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001769 if (!DAG->canAddEdge(GlobalSU, Succ.getSUnit()))
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001770 return;
Javed Absare3a0cc22017-06-21 09:10:10 +00001771 LocalUses.push_back(Succ.getSUnit());
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001772 }
1773 // Open the top of the GlobalLI hole by constraining any earlier global uses
1774 // to precede the start of LocalLI.
1775 SmallVector<SUnit*,8> GlobalUses;
1776 MachineInstr *FirstLocalDef =
1777 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1778 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
Javed Absare3a0cc22017-06-21 09:10:10 +00001779 for (const SDep &Pred : GlobalSU->Preds) {
1780 if (Pred.getKind() != SDep::Anti || Pred.getReg() != GlobalReg)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001781 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001782 if (Pred.getSUnit() == FirstLocalSU)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001783 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001784 if (!DAG->canAddEdge(FirstLocalSU, Pred.getSUnit()))
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001785 return;
Javed Absare3a0cc22017-06-21 09:10:10 +00001786 GlobalUses.push_back(Pred.getSUnit());
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001787 }
1788 DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1789 // Add the weak edges.
1790 for (SmallVectorImpl<SUnit*>::const_iterator
1791 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1792 DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1793 << GlobalSU->NodeNum << ")\n");
1794 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1795 }
1796 for (SmallVectorImpl<SUnit*>::const_iterator
1797 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1798 DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1799 << FirstLocalSU->NodeNum << ")\n");
1800 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1801 }
1802}
1803
1804/// \brief Callback from DAG postProcessing to create weak edges to encourage
1805/// copy elimination.
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001806void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) {
1807 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
Andrew Trickd7f890e2013-12-28 21:56:47 +00001808 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1809
Andrew Trick2e875172013-04-24 23:19:56 +00001810 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1811 if (FirstPos == DAG->end())
1812 return;
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001813 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001814 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001815 *priorNonDebug(DAG->end(), DAG->begin()));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001816
Javed Absare3a0cc22017-06-21 09:10:10 +00001817 for (SUnit &SU : DAG->SUnits) {
1818 if (!SU.getInstr()->isCopy())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001819 continue;
1820
Javed Absare3a0cc22017-06-21 09:10:10 +00001821 constrainLocalCopy(&SU, static_cast<ScheduleDAGMILive*>(DAG));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001822 }
1823}
1824
1825//===----------------------------------------------------------------------===//
Andrew Trickfc127d12013-12-07 05:59:44 +00001826// MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1827// and possibly other custom schedulers.
Andrew Trickd14d7c22013-12-28 21:56:57 +00001828//===----------------------------------------------------------------------===//
Andrew Tricke1c034f2012-01-17 06:55:03 +00001829
Andrew Trick5a22df42013-12-05 17:56:02 +00001830static const unsigned InvalidCycle = ~0U;
1831
Andrew Trickfc127d12013-12-07 05:59:44 +00001832SchedBoundary::~SchedBoundary() { delete HazardRec; }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001833
Jonas Paulsson238c14b2017-10-25 08:23:33 +00001834/// Given a Count of resource usage and a Latency value, return true if a
1835/// SchedBoundary becomes resource limited.
1836static bool checkResourceLimit(unsigned LFactor, unsigned Count,
1837 unsigned Latency) {
1838 return (int)(Count - (Latency * LFactor)) > (int)LFactor;
1839}
1840
Andrew Trickfc127d12013-12-07 05:59:44 +00001841void SchedBoundary::reset() {
1842 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1843 // Destroying and reconstructing it is very expensive though. So keep
1844 // invalid, placeholder HazardRecs.
1845 if (HazardRec && HazardRec->isEnabled()) {
1846 delete HazardRec;
Craig Topperc0196b12014-04-14 00:51:57 +00001847 HazardRec = nullptr;
Andrew Trickfc127d12013-12-07 05:59:44 +00001848 }
1849 Available.clear();
1850 Pending.clear();
1851 CheckPending = false;
Andrew Trickfc127d12013-12-07 05:59:44 +00001852 CurrCycle = 0;
1853 CurrMOps = 0;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001854 MinReadyCycle = std::numeric_limits<unsigned>::max();
Andrew Trickfc127d12013-12-07 05:59:44 +00001855 ExpectedLatency = 0;
1856 DependentLatency = 0;
1857 RetiredMOps = 0;
1858 MaxExecutedResCount = 0;
1859 ZoneCritResIdx = 0;
1860 IsResourceLimited = false;
1861 ReservedCycles.clear();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001862#ifndef NDEBUG
Andrew Trickd14d7c22013-12-28 21:56:57 +00001863 // Track the maximum number of stall cycles that could arise either from the
1864 // latency of a DAG edge or the number of cycles that a processor resource is
1865 // reserved (SchedBoundary::ReservedCycles).
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00001866 MaxObservedStall = 0;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001867#endif
Andrew Trickfc127d12013-12-07 05:59:44 +00001868 // Reserve a zero-count for invalid CritResIdx.
1869 ExecutedResCounts.resize(1);
1870 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1871}
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001872
Andrew Trickfc127d12013-12-07 05:59:44 +00001873void SchedRemainder::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001874init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1875 reset();
1876 if (!SchedModel->hasInstrSchedModel())
1877 return;
1878 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
Javed Absare3a0cc22017-06-21 09:10:10 +00001879 for (SUnit &SU : DAG->SUnits) {
1880 const MCSchedClassDesc *SC = DAG->getSchedClass(&SU);
1881 RemIssueCount += SchedModel->getNumMicroOps(SU.getInstr(), SC)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001882 * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001883 for (TargetSchedModel::ProcResIter
1884 PI = SchedModel->getWriteProcResBegin(SC),
1885 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1886 unsigned PIdx = PI->ProcResourceIdx;
1887 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1888 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1889 }
1890 }
1891}
1892
Andrew Trickfc127d12013-12-07 05:59:44 +00001893void SchedBoundary::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001894init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1895 reset();
1896 DAG = dag;
1897 SchedModel = smodel;
1898 Rem = rem;
Andrew Trick5a22df42013-12-05 17:56:02 +00001899 if (SchedModel->hasInstrSchedModel()) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001900 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
Andrew Trick5a22df42013-12-05 17:56:02 +00001901 ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1902 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001903}
1904
Andrew Trick880e5732013-12-05 17:55:58 +00001905/// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1906/// these "soft stalls" differently than the hard stall cycles based on CPU
1907/// resources and computed by checkHazard(). A fully in-order model
1908/// (MicroOpBufferSize==0) will not make use of this since instructions are not
1909/// available for scheduling until they are ready. However, a weaker in-order
1910/// model may use this for heuristics. For example, if a processor has in-order
1911/// behavior when reading certain resources, this may come into play.
Andrew Trickfc127d12013-12-07 05:59:44 +00001912unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
Andrew Trick880e5732013-12-05 17:55:58 +00001913 if (!SU->isUnbuffered)
1914 return 0;
1915
1916 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1917 if (ReadyCycle > CurrCycle)
1918 return ReadyCycle - CurrCycle;
1919 return 0;
1920}
1921
Andrew Trick5a22df42013-12-05 17:56:02 +00001922/// Compute the next cycle at which the given processor resource can be
1923/// scheduled.
Andrew Trickfc127d12013-12-07 05:59:44 +00001924unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00001925getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1926 unsigned NextUnreserved = ReservedCycles[PIdx];
1927 // If this resource has never been used, always return cycle zero.
1928 if (NextUnreserved == InvalidCycle)
1929 return 0;
1930 // For bottom-up scheduling add the cycles needed for the current operation.
1931 if (!isTop())
1932 NextUnreserved += Cycles;
1933 return NextUnreserved;
1934}
1935
Andrew Trick8c9e6722012-06-29 03:23:24 +00001936/// Does this SU have a hazard within the current instruction group.
1937///
1938/// The scheduler supports two modes of hazard recognition. The first is the
1939/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1940/// supports highly complicated in-order reservation tables
1941/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1942///
1943/// The second is a streamlined mechanism that checks for hazards based on
1944/// simple counters that the scheduler itself maintains. It explicitly checks
1945/// for instruction dispatch limitations, including the number of micro-ops that
1946/// can dispatch per cycle.
1947///
1948/// TODO: Also check whether the SU must start a new group.
Andrew Trickfc127d12013-12-07 05:59:44 +00001949bool SchedBoundary::checkHazard(SUnit *SU) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00001950 if (HazardRec->isEnabled()
1951 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
1952 return true;
1953 }
Javed Absar3d594372017-03-27 20:46:37 +00001954
Andrew Trickdd79f0f2012-10-10 05:43:09 +00001955 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Tricke2ff5752013-06-15 04:49:49 +00001956 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001957 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1958 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick8c9e6722012-06-29 03:23:24 +00001959 return true;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001960 }
Javed Absar3d594372017-03-27 20:46:37 +00001961
1962 if (CurrMOps > 0 &&
1963 ((isTop() && SchedModel->mustBeginGroup(SU->getInstr())) ||
1964 (!isTop() && SchedModel->mustEndGroup(SU->getInstr())))) {
1965 DEBUG(dbgs() << " hazard: SU(" << SU->NodeNum << ") must "
1966 << (isTop()? "begin" : "end") << " group\n");
1967 return true;
1968 }
1969
Andrew Trick5a22df42013-12-05 17:56:02 +00001970 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1971 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
Javed Absare485b142017-10-03 09:35:04 +00001972 for (const MCWriteProcResEntry &PE :
1973 make_range(SchedModel->getWriteProcResBegin(SC),
1974 SchedModel->getWriteProcResEnd(SC))) {
1975 unsigned ResIdx = PE.ProcResourceIdx;
1976 unsigned Cycles = PE.Cycles;
1977 unsigned NRCycle = getNextResourceCycle(ResIdx, Cycles);
Andrew Trick56327222014-06-27 04:57:05 +00001978 if (NRCycle > CurrCycle) {
Andrew Trick040c0da2014-06-27 05:09:36 +00001979#ifndef NDEBUG
Javed Absare485b142017-10-03 09:35:04 +00001980 MaxObservedStall = std::max(Cycles, MaxObservedStall);
Andrew Trick040c0da2014-06-27 05:09:36 +00001981#endif
Andrew Trick56327222014-06-27 04:57:05 +00001982 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") "
Javed Absare485b142017-10-03 09:35:04 +00001983 << SchedModel->getResourceName(ResIdx)
Andrew Trick56327222014-06-27 04:57:05 +00001984 << "=" << NRCycle << "c\n");
Andrew Trick5a22df42013-12-05 17:56:02 +00001985 return true;
Andrew Trick56327222014-06-27 04:57:05 +00001986 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001987 }
1988 }
Andrew Trick8c9e6722012-06-29 03:23:24 +00001989 return false;
1990}
1991
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001992// Find the unscheduled node in ReadySUs with the highest latency.
Andrew Trickfc127d12013-12-07 05:59:44 +00001993unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001994findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
Craig Topperc0196b12014-04-14 00:51:57 +00001995 SUnit *LateSU = nullptr;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001996 unsigned RemLatency = 0;
Javed Absare3a0cc22017-06-21 09:10:10 +00001997 for (SUnit *SU : ReadySUs) {
1998 unsigned L = getUnscheduledLatency(SU);
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001999 if (L > RemLatency) {
Andrew Trickd6d5ad32012-12-18 20:52:56 +00002000 RemLatency = L;
Javed Absare3a0cc22017-06-21 09:10:10 +00002001 LateSU = SU;
Andrew Trickf5b8ef22013-06-15 04:49:44 +00002002 }
Andrew Trickd6d5ad32012-12-18 20:52:56 +00002003 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002004 if (LateSU) {
2005 DEBUG(dbgs() << Available.getName() << " RemLatency SU("
2006 << LateSU->NodeNum << ") " << RemLatency << "c\n");
Andrew Trickd6d5ad32012-12-18 20:52:56 +00002007 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002008 return RemLatency;
2009}
Andrew Trickf5b8ef22013-06-15 04:49:44 +00002010
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002011// Count resources in this zone and the remaining unscheduled
2012// instruction. Return the max count, scaled. Set OtherCritIdx to the critical
2013// resource index, or zero if the zone is issue limited.
Andrew Trickfc127d12013-12-07 05:59:44 +00002014unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002015getOtherResourceCount(unsigned &OtherCritIdx) {
Alexey Samsonov64c391d2013-07-19 08:55:18 +00002016 OtherCritIdx = 0;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002017 if (!SchedModel->hasInstrSchedModel())
2018 return 0;
2019
2020 unsigned OtherCritCount = Rem->RemIssueCount
2021 + (RetiredMOps * SchedModel->getMicroOpFactor());
2022 DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
2023 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002024 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
2025 PIdx != PEnd; ++PIdx) {
2026 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
2027 if (OtherCount > OtherCritCount) {
2028 OtherCritCount = OtherCount;
2029 OtherCritIdx = PIdx;
2030 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002031 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002032 if (OtherCritIdx) {
2033 DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
2034 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
Andrew Trickfc127d12013-12-07 05:59:44 +00002035 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002036 }
2037 return OtherCritCount;
2038}
2039
Andrew Trickfc127d12013-12-07 05:59:44 +00002040void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00002041 assert(SU->getInstr() && "Scheduled SUnit must have instr");
2042
2043#ifndef NDEBUG
Andrew Trick491e34a2014-06-12 22:36:28 +00002044 // ReadyCycle was been bumped up to the CurrCycle when this node was
2045 // scheduled, but CurrCycle may have been eagerly advanced immediately after
2046 // scheduling, so may now be greater than ReadyCycle.
2047 if (ReadyCycle > CurrCycle)
2048 MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00002049#endif
2050
Andrew Trick61f1a272012-05-24 22:11:09 +00002051 if (ReadyCycle < MinReadyCycle)
2052 MinReadyCycle = ReadyCycle;
2053
2054 // Check for interlocks first. For the purpose of other heuristics, an
2055 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002056 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Matthias Braun6493bc22016-04-22 19:09:17 +00002057 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU) ||
2058 Available.size() >= ReadyListLimit)
Andrew Trick61f1a272012-05-24 22:11:09 +00002059 Pending.push(SU);
2060 else
2061 Available.push(SU);
2062}
2063
2064/// Move the boundary of scheduled code by one cycle.
Andrew Trickfc127d12013-12-07 05:59:44 +00002065void SchedBoundary::bumpCycle(unsigned NextCycle) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002066 if (SchedModel->getMicroOpBufferSize() == 0) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00002067 assert(MinReadyCycle < std::numeric_limits<unsigned>::max() &&
2068 "MinReadyCycle uninitialized");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002069 if (MinReadyCycle > NextCycle)
2070 NextCycle = MinReadyCycle;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002071 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002072 // Update the current micro-ops, which will issue in the next cycle.
2073 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
2074 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
2075
2076 // Decrement DependentLatency based on the next cycle.
Andrew Trickf5b8ef22013-06-15 04:49:44 +00002077 if ((NextCycle - CurrCycle) > DependentLatency)
2078 DependentLatency = 0;
2079 else
2080 DependentLatency -= (NextCycle - CurrCycle);
Andrew Trick61f1a272012-05-24 22:11:09 +00002081
2082 if (!HazardRec->isEnabled()) {
Andrew Trick45446062012-06-05 21:11:27 +00002083 // Bypass HazardRec virtual calls.
Andrew Trick61f1a272012-05-24 22:11:09 +00002084 CurrCycle = NextCycle;
Matthias Braunb550b762016-04-21 01:54:13 +00002085 } else {
Andrew Trick45446062012-06-05 21:11:27 +00002086 // Bypass getHazardType calls in case of long latency.
Andrew Trick61f1a272012-05-24 22:11:09 +00002087 for (; CurrCycle != NextCycle; ++CurrCycle) {
2088 if (isTop())
2089 HazardRec->AdvanceCycle();
2090 else
2091 HazardRec->RecedeCycle();
2092 }
2093 }
2094 CheckPending = true;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002095 IsResourceLimited =
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002096 checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
2097 getScheduledLatency());
Andrew Trick61f1a272012-05-24 22:11:09 +00002098
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002099 DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
2100}
2101
Andrew Trickfc127d12013-12-07 05:59:44 +00002102void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002103 ExecutedResCounts[PIdx] += Count;
2104 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
2105 MaxExecutedResCount = ExecutedResCounts[PIdx];
Andrew Trick61f1a272012-05-24 22:11:09 +00002106}
2107
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002108/// Add the given processor resource to this scheduled zone.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002109///
2110/// \param Cycles indicates the number of consecutive (non-pipelined) cycles
2111/// during which this resource is consumed.
2112///
2113/// \return the next cycle at which the instruction may execute without
2114/// oversubscribing resources.
Andrew Trickfc127d12013-12-07 05:59:44 +00002115unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00002116countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002117 unsigned Factor = SchedModel->getResourceFactor(PIdx);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002118 unsigned Count = Factor * Cycles;
Andrew Trickfc127d12013-12-07 05:59:44 +00002119 DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002120 << " +" << Cycles << "x" << Factor << "u\n");
2121
2122 // Update Executed resources counts.
2123 incExecutedResources(PIdx, Count);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002124 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
2125 Rem->RemainingCounts[PIdx] -= Count;
2126
Andrew Trickb13ef172013-07-19 00:20:07 +00002127 // Check if this resource exceeds the current critical resource. If so, it
2128 // becomes the critical resource.
2129 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002130 ZoneCritResIdx = PIdx;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002131 DEBUG(dbgs() << " *** Critical resource "
Andrew Trickfc127d12013-12-07 05:59:44 +00002132 << SchedModel->getResourceName(PIdx) << ": "
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002133 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002134 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002135 // For reserved resources, record the highest cycle using the resource.
2136 unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
2137 if (NextAvailable > CurrCycle) {
2138 DEBUG(dbgs() << " Resource conflict: "
2139 << SchedModel->getProcResource(PIdx)->Name << " reserved until @"
2140 << NextAvailable << "\n");
2141 }
2142 return NextAvailable;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002143}
2144
Andrew Trick45446062012-06-05 21:11:27 +00002145/// Move the boundary of scheduled code by one SUnit.
Andrew Trickfc127d12013-12-07 05:59:44 +00002146void SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trick45446062012-06-05 21:11:27 +00002147 // Update the reservation table.
2148 if (HazardRec->isEnabled()) {
2149 if (!isTop() && SU->isCall) {
2150 // Calls are scheduled with their preceding instructions. For bottom-up
2151 // scheduling, clear the pipeline state before emitting.
2152 HazardRec->Reset();
2153 }
2154 HazardRec->EmitInstruction(SU);
2155 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002156 // checkHazard should prevent scheduling multiple instructions per cycle that
2157 // exceed the issue width.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002158 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2159 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
Daniel Jasper0d92abd2013-12-06 08:58:22 +00002160 assert(
2161 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
Andrew Trickf7760a22013-12-06 17:19:20 +00002162 "Cannot schedule this instruction's MicroOps in the current cycle.");
Andrew Trick5a22df42013-12-05 17:56:02 +00002163
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002164 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
2165 DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
2166
Andrew Trick5a22df42013-12-05 17:56:02 +00002167 unsigned NextCycle = CurrCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002168 switch (SchedModel->getMicroOpBufferSize()) {
2169 case 0:
2170 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
2171 break;
2172 case 1:
2173 if (ReadyCycle > NextCycle) {
2174 NextCycle = ReadyCycle;
2175 DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
2176 }
2177 break;
2178 default:
2179 // We don't currently model the OOO reorder buffer, so consider all
Andrew Trick880e5732013-12-05 17:55:58 +00002180 // scheduled MOps to be "retired". We do loosely model in-order resource
2181 // latency. If this instruction uses an in-order resource, account for any
2182 // likely stall cycles.
2183 if (SU->isUnbuffered && ReadyCycle > NextCycle)
2184 NextCycle = ReadyCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002185 break;
2186 }
2187 RetiredMOps += IncMOps;
2188
2189 // Update resource counts and critical resource.
2190 if (SchedModel->hasInstrSchedModel()) {
2191 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
2192 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
2193 Rem->RemIssueCount -= DecRemIssue;
2194 if (ZoneCritResIdx) {
2195 // Scale scheduled micro-ops for comparing with the critical resource.
2196 unsigned ScaledMOps =
2197 RetiredMOps * SchedModel->getMicroOpFactor();
2198
2199 // If scaled micro-ops are now more than the previous critical resource by
2200 // a full cycle, then micro-ops issue becomes critical.
2201 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
2202 >= (int)SchedModel->getLatencyFactor()) {
2203 ZoneCritResIdx = 0;
2204 DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
2205 << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
2206 }
2207 }
2208 for (TargetSchedModel::ProcResIter
2209 PI = SchedModel->getWriteProcResBegin(SC),
2210 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2211 unsigned RCycle =
Andrew Trick5a22df42013-12-05 17:56:02 +00002212 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002213 if (RCycle > NextCycle)
2214 NextCycle = RCycle;
2215 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002216 if (SU->hasReservedResource) {
2217 // For reserved resources, record the highest cycle using the resource.
2218 // For top-down scheduling, this is the cycle in which we schedule this
2219 // instruction plus the number of cycles the operations reserves the
2220 // resource. For bottom-up is it simply the instruction's cycle.
2221 for (TargetSchedModel::ProcResIter
2222 PI = SchedModel->getWriteProcResBegin(SC),
2223 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2224 unsigned PIdx = PI->ProcResourceIdx;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002225 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
Chad Rosieraba845e2014-07-02 16:46:08 +00002226 if (isTop()) {
2227 ReservedCycles[PIdx] =
2228 std::max(getNextResourceCycle(PIdx, 0), NextCycle + PI->Cycles);
2229 }
2230 else
2231 ReservedCycles[PIdx] = NextCycle;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002232 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002233 }
2234 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002235 }
2236 // Update ExpectedLatency and DependentLatency.
2237 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
2238 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
2239 if (SU->getDepth() > TopLatency) {
2240 TopLatency = SU->getDepth();
2241 DEBUG(dbgs() << " " << Available.getName()
2242 << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
2243 }
2244 if (SU->getHeight() > BotLatency) {
2245 BotLatency = SU->getHeight();
2246 DEBUG(dbgs() << " " << Available.getName()
2247 << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
2248 }
2249 // If we stall for any reason, bump the cycle.
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002250 if (NextCycle > CurrCycle)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002251 bumpCycle(NextCycle);
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002252 else
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002253 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
Alp Tokercb402912014-01-24 17:20:08 +00002254 // resource limited. If a stall occurred, bumpCycle does this.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002255 IsResourceLimited =
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002256 checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
2257 getScheduledLatency());
2258
Andrew Trick5a22df42013-12-05 17:56:02 +00002259 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
2260 // resets CurrMOps. Loop to handle instructions with more MOps than issue in
2261 // one cycle. Since we commonly reach the max MOps here, opportunistically
2262 // bump the cycle to avoid uselessly checking everything in the readyQ.
2263 CurrMOps += IncMOps;
Javed Absar3d594372017-03-27 20:46:37 +00002264
2265 // Bump the cycle count for issue group constraints.
2266 // This must be done after NextCycle has been adjust for all other stalls.
2267 // Calling bumpCycle(X) will reduce CurrMOps by one issue group and set
2268 // currCycle to X.
2269 if ((isTop() && SchedModel->mustEndGroup(SU->getInstr())) ||
2270 (!isTop() && SchedModel->mustBeginGroup(SU->getInstr()))) {
2271 DEBUG(dbgs() << " Bump cycle to "
2272 << (isTop() ? "end" : "begin") << " group\n");
2273 bumpCycle(++NextCycle);
2274 }
2275
Andrew Trick5a22df42013-12-05 17:56:02 +00002276 while (CurrMOps >= SchedModel->getIssueWidth()) {
Andrew Trick5a22df42013-12-05 17:56:02 +00002277 DEBUG(dbgs() << " *** Max MOps " << CurrMOps
2278 << " at cycle " << CurrCycle << '\n');
Andrew Trickd14d7c22013-12-28 21:56:57 +00002279 bumpCycle(++NextCycle);
Andrew Trick5a22df42013-12-05 17:56:02 +00002280 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002281 DEBUG(dumpScheduledState());
Andrew Trick45446062012-06-05 21:11:27 +00002282}
2283
Andrew Trick61f1a272012-05-24 22:11:09 +00002284/// Release pending ready nodes in to the available queue. This makes them
2285/// visible to heuristics.
Andrew Trickfc127d12013-12-07 05:59:44 +00002286void SchedBoundary::releasePending() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002287 // If the available queue is empty, it is safe to reset MinReadyCycle.
2288 if (Available.empty())
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00002289 MinReadyCycle = std::numeric_limits<unsigned>::max();
Andrew Trick61f1a272012-05-24 22:11:09 +00002290
2291 // Check to see if any of the pending instructions are ready to issue. If
2292 // so, add them to the available queue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002293 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Andrew Trick61f1a272012-05-24 22:11:09 +00002294 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2295 SUnit *SU = *(Pending.begin()+i);
Andrew Trick45446062012-06-05 21:11:27 +00002296 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick61f1a272012-05-24 22:11:09 +00002297
2298 if (ReadyCycle < MinReadyCycle)
2299 MinReadyCycle = ReadyCycle;
2300
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002301 if (!IsBuffered && ReadyCycle > CurrCycle)
Andrew Trick61f1a272012-05-24 22:11:09 +00002302 continue;
2303
Andrew Trick8c9e6722012-06-29 03:23:24 +00002304 if (checkHazard(SU))
Andrew Trick61f1a272012-05-24 22:11:09 +00002305 continue;
2306
Matthias Braun6493bc22016-04-22 19:09:17 +00002307 if (Available.size() >= ReadyListLimit)
2308 break;
2309
Andrew Trick61f1a272012-05-24 22:11:09 +00002310 Available.push(SU);
2311 Pending.remove(Pending.begin()+i);
2312 --i; --e;
2313 }
2314 CheckPending = false;
2315}
2316
2317/// Remove SU from the ready set for this boundary.
Andrew Trickfc127d12013-12-07 05:59:44 +00002318void SchedBoundary::removeReady(SUnit *SU) {
Andrew Trick61f1a272012-05-24 22:11:09 +00002319 if (Available.isInQueue(SU))
2320 Available.remove(Available.find(SU));
2321 else {
2322 assert(Pending.isInQueue(SU) && "bad ready count");
2323 Pending.remove(Pending.find(SU));
2324 }
2325}
2326
2327/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002328/// defer any nodes that now hit a hazard, and advance the cycle until at least
2329/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trickfc127d12013-12-07 05:59:44 +00002330SUnit *SchedBoundary::pickOnlyChoice() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002331 if (CheckPending)
2332 releasePending();
2333
Andrew Tricke2ff5752013-06-15 04:49:49 +00002334 if (CurrMOps > 0) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002335 // Defer any ready instrs that now have a hazard.
2336 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2337 if (checkHazard(*I)) {
2338 Pending.push(*I);
2339 I = Available.remove(I);
2340 continue;
2341 }
2342 ++I;
2343 }
2344 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002345 for (unsigned i = 0; Available.empty(); ++i) {
Chad Rosieraba845e2014-07-02 16:46:08 +00002346// FIXME: Re-enable assert once PR20057 is resolved.
2347// assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
2348// "permanent hazard");
2349 (void)i;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002350 bumpCycle(CurrCycle + 1);
Andrew Trick61f1a272012-05-24 22:11:09 +00002351 releasePending();
2352 }
Matthias Braund29d31e2016-06-23 21:27:38 +00002353
2354 DEBUG(Pending.dump());
2355 DEBUG(Available.dump());
2356
Andrew Trick61f1a272012-05-24 22:11:09 +00002357 if (Available.size() == 1)
2358 return *Available.begin();
Craig Topperc0196b12014-04-14 00:51:57 +00002359 return nullptr;
Andrew Trick61f1a272012-05-24 22:11:09 +00002360}
2361
Aaron Ballman615eb472017-10-15 14:32:27 +00002362#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002363// This is useful information to dump after bumpNode.
2364// Note that the Queue contents are more useful before pickNodeFromQueue.
Sam Clegg705f7982017-06-21 22:19:17 +00002365LLVM_DUMP_METHOD void SchedBoundary::dumpScheduledState() const {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002366 unsigned ResFactor;
2367 unsigned ResCount;
2368 if (ZoneCritResIdx) {
2369 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2370 ResCount = getResourceCount(ZoneCritResIdx);
Matthias Braunb550b762016-04-21 01:54:13 +00002371 } else {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002372 ResFactor = SchedModel->getMicroOpFactor();
Javed Absar1a77bcc2017-09-27 10:31:58 +00002373 ResCount = RetiredMOps * ResFactor;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002374 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002375 unsigned LFactor = SchedModel->getLatencyFactor();
2376 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2377 << " Retired: " << RetiredMOps;
2378 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2379 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
Andrew Trickfc127d12013-12-07 05:59:44 +00002380 << ResCount / ResFactor << " "
2381 << SchedModel->getResourceName(ZoneCritResIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002382 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2383 << (IsResourceLimited ? " - Resource" : " - Latency")
2384 << " limited.\n";
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002385}
Andrew Trick8e8415f2013-06-15 05:46:47 +00002386#endif
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002387
Andrew Trickfc127d12013-12-07 05:59:44 +00002388//===----------------------------------------------------------------------===//
Andrew Trickd14d7c22013-12-28 21:56:57 +00002389// GenericScheduler - Generic implementation of MachineSchedStrategy.
Andrew Trickfc127d12013-12-07 05:59:44 +00002390//===----------------------------------------------------------------------===//
2391
Andrew Trickd14d7c22013-12-28 21:56:57 +00002392void GenericSchedulerBase::SchedCandidate::
2393initResourceDelta(const ScheduleDAGMI *DAG,
2394 const TargetSchedModel *SchedModel) {
2395 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2396 return;
2397
2398 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2399 for (TargetSchedModel::ProcResIter
2400 PI = SchedModel->getWriteProcResBegin(SC),
2401 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2402 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2403 ResDelta.CritResources += PI->Cycles;
2404 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2405 ResDelta.DemandedResources += PI->Cycles;
2406 }
2407}
2408
2409/// Set the CandPolicy given a scheduling zone given the current resources and
2410/// latencies inside and outside the zone.
Matthias Braunb550b762016-04-21 01:54:13 +00002411void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA,
Andrew Trickd14d7c22013-12-28 21:56:57 +00002412 SchedBoundary &CurrZone,
2413 SchedBoundary *OtherZone) {
Eric Christopher572e03a2015-06-19 01:53:21 +00002414 // Apply preemptive heuristics based on the total latency and resources
Andrew Trickd14d7c22013-12-28 21:56:57 +00002415 // inside and outside this zone. Potential stalls should be considered before
2416 // following this policy.
2417
2418 // Compute remaining latency. We need this both to determine whether the
2419 // overall schedule has become latency-limited and whether the instructions
2420 // outside this zone are resource or latency limited.
2421 //
2422 // The "dependent" latency is updated incrementally during scheduling as the
2423 // max height/depth of scheduled nodes minus the cycles since it was
2424 // scheduled:
2425 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2426 //
2427 // The "independent" latency is the max ready queue depth:
2428 // ILat = max N.depth for N in Available|Pending
2429 //
2430 // RemainingLatency is the greater of independent and dependent latency.
2431 unsigned RemLatency = CurrZone.getDependentLatency();
2432 RemLatency = std::max(RemLatency,
2433 CurrZone.findMaxLatency(CurrZone.Available.elements()));
2434 RemLatency = std::max(RemLatency,
2435 CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2436
2437 // Compute the critical resource outside the zone.
Andrew Trick7afe4812013-12-28 22:25:57 +00002438 unsigned OtherCritIdx = 0;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002439 unsigned OtherCount =
2440 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
2441
2442 bool OtherResLimited = false;
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002443 if (SchedModel->hasInstrSchedModel())
2444 OtherResLimited = checkResourceLimit(SchedModel->getLatencyFactor(),
2445 OtherCount, RemLatency);
2446
Andrew Trickd14d7c22013-12-28 21:56:57 +00002447 // Schedule aggressively for latency in PostRA mode. We don't check for
2448 // acyclic latency during PostRA, and highly out-of-order processors will
2449 // skip PostRA scheduling.
2450 if (!OtherResLimited) {
2451 if (IsPostRA || (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) {
2452 Policy.ReduceLatency |= true;
2453 DEBUG(dbgs() << " " << CurrZone.Available.getName()
2454 << " RemainingLatency " << RemLatency << " + "
2455 << CurrZone.getCurrCycle() << "c > CritPath "
2456 << Rem.CriticalPath << "\n");
2457 }
2458 }
2459 // If the same resource is limiting inside and outside the zone, do nothing.
2460 if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2461 return;
2462
2463 DEBUG(
2464 if (CurrZone.isResourceLimited()) {
2465 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
2466 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx())
2467 << "\n";
2468 }
2469 if (OtherResLimited)
2470 dbgs() << " RemainingLimit: "
2471 << SchedModel->getResourceName(OtherCritIdx) << "\n";
2472 if (!CurrZone.isResourceLimited() && !OtherResLimited)
2473 dbgs() << " Latency limited both directions.\n");
2474
2475 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2476 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2477
2478 if (OtherResLimited)
2479 Policy.DemandResIdx = OtherCritIdx;
2480}
2481
2482#ifndef NDEBUG
2483const char *GenericSchedulerBase::getReasonStr(
2484 GenericSchedulerBase::CandReason Reason) {
2485 switch (Reason) {
2486 case NoCand: return "NOCAND ";
Matthias Braun49cb6e92016-05-27 22:14:26 +00002487 case Only1: return "ONLY1 ";
2488 case PhysRegCopy: return "PREG-COPY ";
Andrew Trickd14d7c22013-12-28 21:56:57 +00002489 case RegExcess: return "REG-EXCESS";
2490 case RegCritical: return "REG-CRIT ";
2491 case Stall: return "STALL ";
2492 case Cluster: return "CLUSTER ";
2493 case Weak: return "WEAK ";
2494 case RegMax: return "REG-MAX ";
2495 case ResourceReduce: return "RES-REDUCE";
2496 case ResourceDemand: return "RES-DEMAND";
2497 case TopDepthReduce: return "TOP-DEPTH ";
2498 case TopPathReduce: return "TOP-PATH ";
2499 case BotHeightReduce:return "BOT-HEIGHT";
2500 case BotPathReduce: return "BOT-PATH ";
2501 case NextDefUse: return "DEF-USE ";
2502 case NodeOrder: return "ORDER ";
2503 };
2504 llvm_unreachable("Unknown reason!");
2505}
2506
2507void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
2508 PressureChange P;
2509 unsigned ResIdx = 0;
2510 unsigned Latency = 0;
2511 switch (Cand.Reason) {
2512 default:
2513 break;
2514 case RegExcess:
2515 P = Cand.RPDelta.Excess;
2516 break;
2517 case RegCritical:
2518 P = Cand.RPDelta.CriticalMax;
2519 break;
2520 case RegMax:
2521 P = Cand.RPDelta.CurrentMax;
2522 break;
2523 case ResourceReduce:
2524 ResIdx = Cand.Policy.ReduceResIdx;
2525 break;
2526 case ResourceDemand:
2527 ResIdx = Cand.Policy.DemandResIdx;
2528 break;
2529 case TopDepthReduce:
2530 Latency = Cand.SU->getDepth();
2531 break;
2532 case TopPathReduce:
2533 Latency = Cand.SU->getHeight();
2534 break;
2535 case BotHeightReduce:
2536 Latency = Cand.SU->getHeight();
2537 break;
2538 case BotPathReduce:
2539 Latency = Cand.SU->getDepth();
2540 break;
2541 }
James Y Knighte72b0db2015-09-18 18:52:20 +00002542 dbgs() << " Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002543 if (P.isValid())
2544 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2545 << ":" << P.getUnitInc() << " ";
2546 else
2547 dbgs() << " ";
2548 if (ResIdx)
2549 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2550 else
2551 dbgs() << " ";
2552 if (Latency)
2553 dbgs() << " " << Latency << " cycles ";
2554 else
2555 dbgs() << " ";
2556 dbgs() << '\n';
2557}
2558#endif
2559
2560/// Return true if this heuristic determines order.
2561static bool tryLess(int TryVal, int CandVal,
2562 GenericSchedulerBase::SchedCandidate &TryCand,
2563 GenericSchedulerBase::SchedCandidate &Cand,
2564 GenericSchedulerBase::CandReason Reason) {
2565 if (TryVal < CandVal) {
2566 TryCand.Reason = Reason;
2567 return true;
2568 }
2569 if (TryVal > CandVal) {
2570 if (Cand.Reason > Reason)
2571 Cand.Reason = Reason;
2572 return true;
2573 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00002574 return false;
2575}
2576
2577static bool tryGreater(int TryVal, int CandVal,
2578 GenericSchedulerBase::SchedCandidate &TryCand,
2579 GenericSchedulerBase::SchedCandidate &Cand,
2580 GenericSchedulerBase::CandReason Reason) {
2581 if (TryVal > CandVal) {
2582 TryCand.Reason = Reason;
2583 return true;
2584 }
2585 if (TryVal < CandVal) {
2586 if (Cand.Reason > Reason)
2587 Cand.Reason = Reason;
2588 return true;
2589 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00002590 return false;
2591}
2592
2593static bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
2594 GenericSchedulerBase::SchedCandidate &Cand,
2595 SchedBoundary &Zone) {
2596 if (Zone.isTop()) {
2597 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2598 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2599 TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
2600 return true;
2601 }
2602 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2603 TryCand, Cand, GenericSchedulerBase::TopPathReduce))
2604 return true;
Matthias Braunb550b762016-04-21 01:54:13 +00002605 } else {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002606 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2607 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2608 TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
2609 return true;
2610 }
2611 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2612 TryCand, Cand, GenericSchedulerBase::BotPathReduce))
2613 return true;
2614 }
2615 return false;
2616}
2617
Matthias Braun49cb6e92016-05-27 22:14:26 +00002618static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop) {
2619 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2620 << GenericSchedulerBase::getReasonStr(Reason) << '\n');
2621}
2622
Matthias Braun6ad3d052016-06-25 00:23:00 +00002623static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand) {
2624 tracePick(Cand.Reason, Cand.AtTop);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002625}
2626
Andrew Trickfc127d12013-12-07 05:59:44 +00002627void GenericScheduler::initialize(ScheduleDAGMI *dag) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00002628 assert(dag->hasVRegLiveness() &&
2629 "(PreRA)GenericScheduler needs vreg liveness");
2630 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Trickfc127d12013-12-07 05:59:44 +00002631 SchedModel = DAG->getSchedModel();
2632 TRI = DAG->TRI;
2633
2634 Rem.init(DAG, SchedModel);
2635 Top.init(DAG, SchedModel, &Rem);
2636 Bot.init(DAG, SchedModel, &Rem);
2637
2638 // Initialize resource counts.
2639
2640 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2641 // are disabled, then these HazardRecs will be disabled.
2642 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trickfc127d12013-12-07 05:59:44 +00002643 if (!Top.HazardRec) {
2644 Top.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00002645 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00002646 Itin, DAG);
Andrew Trickfc127d12013-12-07 05:59:44 +00002647 }
2648 if (!Bot.HazardRec) {
2649 Bot.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00002650 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00002651 Itin, DAG);
Andrew Trickfc127d12013-12-07 05:59:44 +00002652 }
Matthias Brauncc676c42016-06-25 02:03:36 +00002653 TopCand.SU = nullptr;
2654 BotCand.SU = nullptr;
Andrew Trickfc127d12013-12-07 05:59:44 +00002655}
2656
2657/// Initialize the per-region scheduling policy.
2658void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2659 MachineBasicBlock::iterator End,
2660 unsigned NumRegionInstrs) {
Justin Bognerfdf9bf42017-10-10 23:50:49 +00002661 const MachineFunction &MF = *Begin->getMF();
Eric Christopher99556d72014-10-14 06:56:25 +00002662 const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
Andrew Trickfc127d12013-12-07 05:59:44 +00002663
2664 // Avoid setting up the register pressure tracker for small regions to save
2665 // compile time. As a rough heuristic, only track pressure when the number of
2666 // schedulable instructions exceeds half the integer register file.
Andrew Trick350ff2c2014-01-21 21:27:37 +00002667 RegionPolicy.ShouldTrackPressure = true;
Andrew Trick46753512014-01-22 03:38:55 +00002668 for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
2669 MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
2670 if (TLI->isTypeLegal(LegalIntVT)) {
Andrew Trick350ff2c2014-01-21 21:27:37 +00002671 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
Andrew Trick46753512014-01-22 03:38:55 +00002672 TLI->getRegClassFor(LegalIntVT));
Andrew Trick350ff2c2014-01-21 21:27:37 +00002673 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2674 }
2675 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002676
2677 // For generic targets, we default to bottom-up, because it's simpler and more
2678 // compile-time optimizations have been implemented in that direction.
2679 RegionPolicy.OnlyBottomUp = true;
2680
2681 // Allow the subtarget to override default policy.
Duncan P. N. Exon Smith63298722016-07-01 00:23:27 +00002682 MF.getSubtarget().overrideSchedPolicy(RegionPolicy, NumRegionInstrs);
Andrew Trickfc127d12013-12-07 05:59:44 +00002683
2684 // After subtarget overrides, apply command line options.
2685 if (!EnableRegPressure)
2686 RegionPolicy.ShouldTrackPressure = false;
2687
2688 // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2689 // e.g. -misched-bottomup=false allows scheduling in both directions.
2690 assert((!ForceTopDown || !ForceBottomUp) &&
2691 "-misched-topdown incompatible with -misched-bottomup");
2692 if (ForceBottomUp.getNumOccurrences() > 0) {
2693 RegionPolicy.OnlyBottomUp = ForceBottomUp;
2694 if (RegionPolicy.OnlyBottomUp)
2695 RegionPolicy.OnlyTopDown = false;
2696 }
2697 if (ForceTopDown.getNumOccurrences() > 0) {
2698 RegionPolicy.OnlyTopDown = ForceTopDown;
2699 if (RegionPolicy.OnlyTopDown)
2700 RegionPolicy.OnlyBottomUp = false;
2701 }
2702}
2703
Sam Clegg705f7982017-06-21 22:19:17 +00002704void GenericScheduler::dumpPolicy() const {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002705 // Cannot completely remove virtual function even in release mode.
Aaron Ballman615eb472017-10-15 14:32:27 +00002706#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
James Y Knighte72b0db2015-09-18 18:52:20 +00002707 dbgs() << "GenericScheduler RegionPolicy: "
2708 << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
2709 << " OnlyTopDown=" << RegionPolicy.OnlyTopDown
2710 << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
2711 << "\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +00002712#endif
James Y Knighte72b0db2015-09-18 18:52:20 +00002713}
2714
Andrew Trickfc127d12013-12-07 05:59:44 +00002715/// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2716/// critical path by more cycles than it takes to drain the instruction buffer.
2717/// We estimate an upper bounds on in-flight instructions as:
2718///
2719/// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2720/// InFlightIterations = AcyclicPath / CyclesPerIteration
2721/// InFlightResources = InFlightIterations * LoopResources
2722///
2723/// TODO: Check execution resources in addition to IssueCount.
2724void GenericScheduler::checkAcyclicLatency() {
2725 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2726 return;
2727
2728 // Scaled number of cycles per loop iteration.
2729 unsigned IterCount =
2730 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2731 Rem.RemIssueCount);
2732 // Scaled acyclic critical path.
2733 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2734 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2735 unsigned InFlightCount =
2736 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2737 unsigned BufferLimit =
2738 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2739
2740 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2741
2742 DEBUG(dbgs() << "IssueCycles="
2743 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2744 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2745 << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
2746 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2747 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2748 if (Rem.IsAcyclicLatencyLimited)
2749 dbgs() << " ACYCLIC LATENCY LIMIT\n");
2750}
2751
2752void GenericScheduler::registerRoots() {
2753 Rem.CriticalPath = DAG->ExitSU.getDepth();
2754
2755 // Some roots may not feed into ExitSU. Check all of them in case.
Javed Absare3a0cc22017-06-21 09:10:10 +00002756 for (const SUnit *SU : Bot.Available) {
2757 if (SU->getDepth() > Rem.CriticalPath)
2758 Rem.CriticalPath = SU->getDepth();
Andrew Trickfc127d12013-12-07 05:59:44 +00002759 }
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +00002760 DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n');
2761 if (DumpCriticalPathLength) {
2762 errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n";
2763 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002764
Matthias Braun99551052017-04-12 18:09:05 +00002765 if (EnableCyclicPath && SchedModel->getMicroOpBufferSize() > 0) {
Andrew Trickfc127d12013-12-07 05:59:44 +00002766 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2767 checkAcyclicLatency();
2768 }
2769}
2770
Andrew Trick1a831342013-08-30 03:49:48 +00002771static bool tryPressure(const PressureChange &TryP,
2772 const PressureChange &CandP,
Andrew Trickd14d7c22013-12-28 21:56:57 +00002773 GenericSchedulerBase::SchedCandidate &TryCand,
2774 GenericSchedulerBase::SchedCandidate &Cand,
Tom Stellard5ce53062015-12-16 18:31:01 +00002775 GenericSchedulerBase::CandReason Reason,
2776 const TargetRegisterInfo *TRI,
2777 const MachineFunction &MF) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002778 // If one candidate decreases and the other increases, go with it.
2779 // Invalid candidates have UnitInc==0.
Hal Finkel7a87f8a2014-10-10 17:06:20 +00002780 if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2781 Reason)) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002782 return true;
2783 }
Matthias Braun6ad3d052016-06-25 00:23:00 +00002784 // Do not compare the magnitude of pressure changes between top and bottom
2785 // boundary.
2786 if (Cand.AtTop != TryCand.AtTop)
2787 return false;
2788
2789 // If both candidates affect the same set in the same boundary, go with the
2790 // smallest increase.
2791 unsigned TryPSet = TryP.getPSetOrMax();
2792 unsigned CandPSet = CandP.getPSetOrMax();
2793 if (TryPSet == CandPSet) {
2794 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2795 Reason);
2796 }
Tom Stellard5ce53062015-12-16 18:31:01 +00002797
2798 int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) :
2799 std::numeric_limits<int>::max();
2800
2801 int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) :
2802 std::numeric_limits<int>::max();
2803
Andrew Trick401b6952013-07-25 07:26:35 +00002804 // If the candidates are decreasing pressure, reverse priority.
Andrew Trick1a831342013-08-30 03:49:48 +00002805 if (TryP.getUnitInc() < 0)
Andrew Trick401b6952013-07-25 07:26:35 +00002806 std::swap(TryRank, CandRank);
2807 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2808}
2809
Andrew Tricka7714a02012-11-12 19:40:10 +00002810static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2811 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2812}
2813
Andrew Tricke833e1c2013-04-13 06:07:40 +00002814/// Minimize physical register live ranges. Regalloc wants them adjacent to
2815/// their physreg def/use.
2816///
2817/// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2818/// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2819/// with the operation that produces or consumes the physreg. We'll do this when
2820/// regalloc has support for parallel copies.
2821static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2822 const MachineInstr *MI = SU->getInstr();
2823 if (!MI->isCopy())
2824 return 0;
2825
2826 unsigned ScheduledOper = isTop ? 1 : 0;
2827 unsigned UnscheduledOper = isTop ? 0 : 1;
2828 // If we have already scheduled the physreg produce/consumer, immediately
2829 // schedule the copy.
2830 if (TargetRegisterInfo::isPhysicalRegister(
2831 MI->getOperand(ScheduledOper).getReg()))
2832 return 1;
2833 // If the physreg is at the boundary, defer it. Otherwise schedule it
2834 // immediately to free the dependent. We can hoist the copy later.
2835 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2836 if (TargetRegisterInfo::isPhysicalRegister(
2837 MI->getOperand(UnscheduledOper).getReg()))
2838 return AtBoundary ? -1 : 1;
2839 return 0;
2840}
2841
Matthias Braun4f573772016-04-22 19:10:15 +00002842void GenericScheduler::initCandidate(SchedCandidate &Cand, SUnit *SU,
2843 bool AtTop,
2844 const RegPressureTracker &RPTracker,
2845 RegPressureTracker &TempTracker) {
2846 Cand.SU = SU;
Matthias Braun6ad3d052016-06-25 00:23:00 +00002847 Cand.AtTop = AtTop;
Matthias Braun4f573772016-04-22 19:10:15 +00002848 if (DAG->isTrackingPressure()) {
2849 if (AtTop) {
2850 TempTracker.getMaxDownwardPressureDelta(
2851 Cand.SU->getInstr(),
2852 Cand.RPDelta,
2853 DAG->getRegionCriticalPSets(),
2854 DAG->getRegPressure().MaxSetPressure);
2855 } else {
2856 if (VerifyScheduling) {
2857 TempTracker.getMaxUpwardPressureDelta(
2858 Cand.SU->getInstr(),
2859 &DAG->getPressureDiff(Cand.SU),
2860 Cand.RPDelta,
2861 DAG->getRegionCriticalPSets(),
2862 DAG->getRegPressure().MaxSetPressure);
2863 } else {
2864 RPTracker.getUpwardPressureDelta(
2865 Cand.SU->getInstr(),
2866 DAG->getPressureDiff(Cand.SU),
2867 Cand.RPDelta,
2868 DAG->getRegionCriticalPSets(),
2869 DAG->getRegPressure().MaxSetPressure);
2870 }
2871 }
2872 }
2873 DEBUG(if (Cand.RPDelta.Excess.isValid())
2874 dbgs() << " Try SU(" << Cand.SU->NodeNum << ") "
2875 << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet())
2876 << ":" << Cand.RPDelta.Excess.getUnitInc() << "\n");
2877}
2878
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002879/// Apply a set of heursitics to a new candidate. Heuristics are currently
2880/// hierarchical. This may be more efficient than a graduated cost model because
2881/// we don't need to evaluate all aspects of the model for each node in the
2882/// queue. But it's really done to make the heuristics easier to debug and
2883/// statistically analyze.
2884///
2885/// \param Cand provides the policy and current best candidate.
2886/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002887/// \param Zone describes the scheduled zone that we are extending, or nullptr
2888// if Cand is from a different zone than TryCand.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002889void GenericScheduler::tryCandidate(SchedCandidate &Cand,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002890 SchedCandidate &TryCand,
Matthias Braun6ad3d052016-06-25 00:23:00 +00002891 SchedBoundary *Zone) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002892 // Initialize the candidate if needed.
2893 if (!Cand.isValid()) {
2894 TryCand.Reason = NodeOrder;
2895 return;
2896 }
Andrew Tricke833e1c2013-04-13 06:07:40 +00002897
Matthias Braun6ad3d052016-06-25 00:23:00 +00002898 if (tryGreater(biasPhysRegCopy(TryCand.SU, TryCand.AtTop),
2899 biasPhysRegCopy(Cand.SU, Cand.AtTop),
Andrew Tricke833e1c2013-04-13 06:07:40 +00002900 TryCand, Cand, PhysRegCopy))
2901 return;
2902
Andrew Tricke02d5da2015-05-17 23:40:27 +00002903 // Avoid exceeding the target's limit.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002904 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2905 Cand.RPDelta.Excess,
Tom Stellard5ce53062015-12-16 18:31:01 +00002906 TryCand, Cand, RegExcess, TRI,
2907 DAG->MF))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002908 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002909
2910 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002911 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2912 Cand.RPDelta.CriticalMax,
Tom Stellard5ce53062015-12-16 18:31:01 +00002913 TryCand, Cand, RegCritical, TRI,
2914 DAG->MF))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002915 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002916
Matthias Braun6ad3d052016-06-25 00:23:00 +00002917 // We only compare a subset of features when comparing nodes between
2918 // Top and Bottom boundary. Some properties are simply incomparable, in many
2919 // other instances we should only override the other boundary if something
2920 // is a clear good pick on one boundary. Skip heuristics that are more
2921 // "tie-breaking" in nature.
2922 bool SameBoundary = Zone != nullptr;
2923 if (SameBoundary) {
2924 // For loops that are acyclic path limited, aggressively schedule for
Jonas Paulssonbaeb4022016-11-04 08:31:14 +00002925 // latency. Within an single cycle, whenever CurrMOps > 0, allow normal
2926 // heuristics to take precedence.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002927 if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() &&
2928 tryLatency(TryCand, Cand, *Zone))
2929 return;
Andrew Trickddffae92013-09-06 17:32:36 +00002930
Matthias Braun6ad3d052016-06-25 00:23:00 +00002931 // Prioritize instructions that read unbuffered resources by stall cycles.
2932 if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
2933 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2934 return;
2935 }
Andrew Trick880e5732013-12-05 17:55:58 +00002936
Andrew Tricka7714a02012-11-12 19:40:10 +00002937 // Keep clustered nodes together to encourage downstream peephole
2938 // optimizations which may reduce resource requirements.
2939 //
2940 // This is a best effort to set things up for a post-RA pass. Optimizations
2941 // like generating loads of multiple registers should ideally be done within
2942 // the scheduler pass by combining the loads during DAG postprocessing.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002943 const SUnit *CandNextClusterSU =
2944 Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2945 const SUnit *TryCandNextClusterSU =
2946 TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2947 if (tryGreater(TryCand.SU == TryCandNextClusterSU,
2948 Cand.SU == CandNextClusterSU,
Andrew Tricka7714a02012-11-12 19:40:10 +00002949 TryCand, Cand, Cluster))
2950 return;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00002951
Matthias Braun6ad3d052016-06-25 00:23:00 +00002952 if (SameBoundary) {
2953 // Weak edges are for clustering and other constraints.
2954 if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
2955 getWeakLeft(Cand.SU, Cand.AtTop),
2956 TryCand, Cand, Weak))
2957 return;
Andrew Tricka7714a02012-11-12 19:40:10 +00002958 }
Matthias Braun6ad3d052016-06-25 00:23:00 +00002959
Andrew Trick71f08a32013-06-17 21:45:13 +00002960 // Avoid increasing the max pressure of the entire region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002961 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
2962 Cand.RPDelta.CurrentMax,
Tom Stellard5ce53062015-12-16 18:31:01 +00002963 TryCand, Cand, RegMax, TRI,
2964 DAG->MF))
Andrew Trick71f08a32013-06-17 21:45:13 +00002965 return;
2966
Matthias Braun6ad3d052016-06-25 00:23:00 +00002967 if (SameBoundary) {
2968 // Avoid critical resource consumption and balance the schedule.
2969 TryCand.initResourceDelta(DAG, SchedModel);
2970 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2971 TryCand, Cand, ResourceReduce))
2972 return;
2973 if (tryGreater(TryCand.ResDelta.DemandedResources,
2974 Cand.ResDelta.DemandedResources,
2975 TryCand, Cand, ResourceDemand))
2976 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002977
Matthias Braun6ad3d052016-06-25 00:23:00 +00002978 // Avoid serializing long latency dependence chains.
2979 // For acyclic path limited loops, latency was already checked above.
2980 if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency &&
2981 !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone))
2982 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002983
Matthias Braun6ad3d052016-06-25 00:23:00 +00002984 // Fall through to original instruction order.
2985 if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2986 || (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2987 TryCand.Reason = NodeOrder;
2988 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002989 }
2990}
Andrew Trick419eae22012-05-10 21:06:19 +00002991
Andrew Trickc573cd92013-09-06 17:32:44 +00002992/// Pick the best candidate from the queue.
Andrew Trick7ee9de52012-05-10 21:06:16 +00002993///
2994/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2995/// DAG building. To adjust for the current scheduling location we need to
2996/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002997void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
Matthias Braun6ad3d052016-06-25 00:23:00 +00002998 const CandPolicy &ZonePolicy,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002999 const RegPressureTracker &RPTracker,
3000 SchedCandidate &Cand) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00003001 // getMaxPressureDelta temporarily modifies the tracker.
3002 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
3003
Matthias Braund29d31e2016-06-23 21:27:38 +00003004 ReadyQueue &Q = Zone.Available;
Javed Absare3a0cc22017-06-21 09:10:10 +00003005 for (SUnit *SU : Q) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00003006
Matthias Braun6ad3d052016-06-25 00:23:00 +00003007 SchedCandidate TryCand(ZonePolicy);
Javed Absare3a0cc22017-06-21 09:10:10 +00003008 initCandidate(TryCand, SU, Zone.isTop(), RPTracker, TempTracker);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003009 // Pass SchedBoundary only when comparing nodes from the same boundary.
3010 SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
3011 tryCandidate(Cand, TryCand, ZoneArg);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003012 if (TryCand.Reason != NoCand) {
3013 // Initialize resource delta if needed in case future heuristics query it.
3014 if (TryCand.ResDelta == SchedResourceDelta())
3015 TryCand.initResourceDelta(DAG, SchedModel);
3016 Cand.setBest(TryCand);
Andrew Trick419d4912013-04-05 00:31:29 +00003017 DEBUG(traceCandidate(Cand));
Andrew Trick22025772012-05-17 18:35:10 +00003018 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00003019 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003020}
3021
Andrew Trick22025772012-05-17 18:35:10 +00003022/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003023SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick22025772012-05-17 18:35:10 +00003024 // Schedule as far as possible in the direction of no choice. This is most
3025 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick61f1a272012-05-24 22:11:09 +00003026 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00003027 IsTopNode = false;
Matthias Braun49cb6e92016-05-27 22:14:26 +00003028 tracePick(Only1, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00003029 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00003030 }
Andrew Trick61f1a272012-05-24 22:11:09 +00003031 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00003032 IsTopNode = true;
Matthias Braun49cb6e92016-05-27 22:14:26 +00003033 tracePick(Only1, true);
Andrew Trick61f1a272012-05-24 22:11:09 +00003034 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00003035 }
Andrew Trickfc127d12013-12-07 05:59:44 +00003036 // Set the bottom-up policy based on the state of the current bottom zone and
3037 // the instructions outside the zone, including the top zone.
Matthias Braun6ad3d052016-06-25 00:23:00 +00003038 CandPolicy BotPolicy;
3039 setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
Andrew Trickfc127d12013-12-07 05:59:44 +00003040 // Set the top-down policy based on the state of the current top zone and
3041 // the instructions outside the zone, including the bottom zone.
Matthias Braun6ad3d052016-06-25 00:23:00 +00003042 CandPolicy TopPolicy;
3043 setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003044
Matthias Brauncc676c42016-06-25 02:03:36 +00003045 // See if BotCand is still valid (because we previously scheduled from Top).
Matthias Braund29d31e2016-06-23 21:27:38 +00003046 DEBUG(dbgs() << "Picking from Bot:\n");
Matthias Brauncc676c42016-06-25 02:03:36 +00003047 if (!BotCand.isValid() || BotCand.SU->isScheduled ||
3048 BotCand.Policy != BotPolicy) {
3049 BotCand.reset(CandPolicy());
3050 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand);
3051 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
3052 } else {
3053 DEBUG(traceCandidate(BotCand));
3054#ifndef NDEBUG
3055 if (VerifyScheduling) {
3056 SchedCandidate TCand;
3057 TCand.reset(CandPolicy());
3058 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
3059 assert(TCand.SU == BotCand.SU &&
3060 "Last pick result should correspond to re-picking right now");
3061 }
3062#endif
3063 }
Andrew Trick22025772012-05-17 18:35:10 +00003064
Andrew Trick22025772012-05-17 18:35:10 +00003065 // Check if the top Q has a better candidate.
Matthias Braund29d31e2016-06-23 21:27:38 +00003066 DEBUG(dbgs() << "Picking from Top:\n");
Matthias Brauncc676c42016-06-25 02:03:36 +00003067 if (!TopCand.isValid() || TopCand.SU->isScheduled ||
3068 TopCand.Policy != TopPolicy) {
3069 TopCand.reset(CandPolicy());
3070 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand);
3071 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
3072 } else {
3073 DEBUG(traceCandidate(TopCand));
3074#ifndef NDEBUG
3075 if (VerifyScheduling) {
3076 SchedCandidate TCand;
3077 TCand.reset(CandPolicy());
3078 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
3079 assert(TCand.SU == TopCand.SU &&
3080 "Last pick result should correspond to re-picking right now");
3081 }
3082#endif
3083 }
3084
3085 // Pick best from BotCand and TopCand.
3086 assert(BotCand.isValid());
3087 assert(TopCand.isValid());
3088 SchedCandidate Cand = BotCand;
3089 TopCand.Reason = NoCand;
3090 tryCandidate(Cand, TopCand, nullptr);
3091 if (TopCand.Reason != NoCand) {
3092 Cand.setBest(TopCand);
3093 DEBUG(traceCandidate(Cand));
3094 }
Andrew Trick22025772012-05-17 18:35:10 +00003095
Matthias Braun6ad3d052016-06-25 00:23:00 +00003096 IsTopNode = Cand.AtTop;
3097 tracePick(Cand);
3098 return Cand.SU;
Andrew Trick22025772012-05-17 18:35:10 +00003099}
3100
3101/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003102SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00003103 if (DAG->top() == DAG->bottom()) {
Andrew Trick61f1a272012-05-24 22:11:09 +00003104 assert(Top.Available.empty() && Top.Pending.empty() &&
3105 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00003106 return nullptr;
Andrew Trick7ee9de52012-05-10 21:06:16 +00003107 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00003108 SUnit *SU;
Andrew Trick984d98b2012-10-08 18:53:53 +00003109 do {
Andrew Trick75e411c2013-09-06 17:32:34 +00003110 if (RegionPolicy.OnlyTopDown) {
Andrew Trick984d98b2012-10-08 18:53:53 +00003111 SU = Top.pickOnlyChoice();
3112 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003113 CandPolicy NoPolicy;
Matthias Brauncc676c42016-06-25 02:03:36 +00003114 TopCand.reset(NoPolicy);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003115 pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00003116 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003117 tracePick(TopCand);
Andrew Trick984d98b2012-10-08 18:53:53 +00003118 SU = TopCand.SU;
3119 }
3120 IsTopNode = true;
Matthias Braunb550b762016-04-21 01:54:13 +00003121 } else if (RegionPolicy.OnlyBottomUp) {
Andrew Trick984d98b2012-10-08 18:53:53 +00003122 SU = Bot.pickOnlyChoice();
3123 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003124 CandPolicy NoPolicy;
Matthias Brauncc676c42016-06-25 02:03:36 +00003125 BotCand.reset(NoPolicy);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003126 pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00003127 assert(BotCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003128 tracePick(BotCand);
Andrew Trick984d98b2012-10-08 18:53:53 +00003129 SU = BotCand.SU;
3130 }
3131 IsTopNode = false;
Matthias Braunb550b762016-04-21 01:54:13 +00003132 } else {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003133 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick984d98b2012-10-08 18:53:53 +00003134 }
3135 } while (SU->isScheduled);
3136
Andrew Trick61f1a272012-05-24 22:11:09 +00003137 if (SU->isTopReady())
3138 Top.removeReady(SU);
3139 if (SU->isBottomReady())
3140 Bot.removeReady(SU);
Andrew Trick4e7f6a72012-05-25 02:02:39 +00003141
Andrew Trick1f0bb692013-04-13 06:07:49 +00003142 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
Andrew Trick7ee9de52012-05-10 21:06:16 +00003143 return SU;
3144}
3145
Andrew Trick665d3ec2013-09-19 23:10:59 +00003146void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
Andrew Tricke833e1c2013-04-13 06:07:40 +00003147 MachineBasicBlock::iterator InsertPos = SU->getInstr();
3148 if (!isTop)
3149 ++InsertPos;
3150 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
3151
3152 // Find already scheduled copies with a single physreg dependence and move
3153 // them just above the scheduled instruction.
Javed Absare3a0cc22017-06-21 09:10:10 +00003154 for (SDep &Dep : Deps) {
3155 if (Dep.getKind() != SDep::Data || !TRI->isPhysicalRegister(Dep.getReg()))
Andrew Tricke833e1c2013-04-13 06:07:40 +00003156 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00003157 SUnit *DepSU = Dep.getSUnit();
Andrew Tricke833e1c2013-04-13 06:07:40 +00003158 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
3159 continue;
3160 MachineInstr *Copy = DepSU->getInstr();
3161 if (!Copy->isCopy())
3162 continue;
3163 DEBUG(dbgs() << " Rescheduling physreg copy ";
Javed Absare3a0cc22017-06-21 09:10:10 +00003164 Dep.getSUnit()->dump(DAG));
Andrew Tricke833e1c2013-04-13 06:07:40 +00003165 DAG->moveInstruction(Copy, InsertPos);
3166 }
3167}
3168
Andrew Trick61f1a272012-05-24 22:11:09 +00003169/// Update the scheduler's state after scheduling a node. This is the same node
Andrew Trickd14d7c22013-12-28 21:56:57 +00003170/// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
3171/// update it's state based on the current cycle before MachineSchedStrategy
3172/// does.
Andrew Tricke833e1c2013-04-13 06:07:40 +00003173///
3174/// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
3175/// them here. See comments in biasPhysRegCopy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003176void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trick45446062012-06-05 21:11:27 +00003177 if (IsTopNode) {
Andrew Trickfc127d12013-12-07 05:59:44 +00003178 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00003179 Top.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00003180 if (SU->hasPhysRegUses)
3181 reschedulePhysRegCopies(SU, true);
Matthias Braunb550b762016-04-21 01:54:13 +00003182 } else {
Andrew Trickfc127d12013-12-07 05:59:44 +00003183 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00003184 Bot.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00003185 if (SU->hasPhysRegDefs)
3186 reschedulePhysRegCopies(SU, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00003187 }
3188}
3189
Andrew Trick8823dec2012-03-14 04:00:41 +00003190/// Create the standard converging machine scheduler. This will be used as the
3191/// default scheduler if the target does not set a default.
Matthias Braun115efcd2016-11-28 20:11:54 +00003192ScheduleDAGMILive *llvm::createGenericSchedLive(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003193 ScheduleDAGMILive *DAG =
3194 new ScheduleDAGMILive(C, llvm::make_unique<GenericScheduler>(C));
Andrew Tricka7714a02012-11-12 19:40:10 +00003195 // Register DAG post-processors.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00003196 //
3197 // FIXME: extend the mutation API to allow earlier mutations to instantiate
3198 // data and pass it to later mutations. Have a single mutation that gathers
3199 // the interesting nodes in one pass.
Tom Stellard68726a52016-08-19 19:59:18 +00003200 DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI));
Andrew Tricka7714a02012-11-12 19:40:10 +00003201 return DAG;
Andrew Tricke1c034f2012-01-17 06:55:03 +00003202}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003203
Matthias Braun115efcd2016-11-28 20:11:54 +00003204static ScheduleDAGInstrs *createConveringSched(MachineSchedContext *C) {
3205 return createGenericSchedLive(C);
3206}
3207
Andrew Tricke1c034f2012-01-17 06:55:03 +00003208static MachineSchedRegistry
Andrew Trick665d3ec2013-09-19 23:10:59 +00003209GenericSchedRegistry("converge", "Standard converging scheduler.",
Matthias Braun115efcd2016-11-28 20:11:54 +00003210 createConveringSched);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003211
3212//===----------------------------------------------------------------------===//
3213// PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
3214//===----------------------------------------------------------------------===//
3215
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003216void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
3217 DAG = Dag;
3218 SchedModel = DAG->getSchedModel();
3219 TRI = DAG->TRI;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003220
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003221 Rem.init(DAG, SchedModel);
3222 Top.init(DAG, SchedModel, &Rem);
3223 BotRoots.clear();
Andrew Trickd14d7c22013-12-28 21:56:57 +00003224
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003225 // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
3226 // or are disabled, then these HazardRecs will be disabled.
3227 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003228 if (!Top.HazardRec) {
3229 Top.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00003230 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00003231 Itin, DAG);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003232 }
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003233}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003234
Andrew Trickd14d7c22013-12-28 21:56:57 +00003235void PostGenericScheduler::registerRoots() {
3236 Rem.CriticalPath = DAG->ExitSU.getDepth();
3237
3238 // Some roots may not feed into ExitSU. Check all of them in case.
Javed Absare3a0cc22017-06-21 09:10:10 +00003239 for (const SUnit *SU : BotRoots) {
3240 if (SU->getDepth() > Rem.CriticalPath)
3241 Rem.CriticalPath = SU->getDepth();
Andrew Trickd14d7c22013-12-28 21:56:57 +00003242 }
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +00003243 DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n');
3244 if (DumpCriticalPathLength) {
3245 errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n";
3246 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00003247}
3248
3249/// Apply a set of heursitics to a new candidate for PostRA scheduling.
3250///
3251/// \param Cand provides the policy and current best candidate.
3252/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
3253void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
3254 SchedCandidate &TryCand) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003255 // Initialize the candidate if needed.
3256 if (!Cand.isValid()) {
3257 TryCand.Reason = NodeOrder;
3258 return;
3259 }
3260
3261 // Prioritize instructions that read unbuffered resources by stall cycles.
3262 if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
3263 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3264 return;
3265
Florian Hahnabb42182017-05-23 09:33:34 +00003266 // Keep clustered nodes together.
3267 if (tryGreater(TryCand.SU == DAG->getNextClusterSucc(),
3268 Cand.SU == DAG->getNextClusterSucc(),
3269 TryCand, Cand, Cluster))
3270 return;
3271
Andrew Trickd14d7c22013-12-28 21:56:57 +00003272 // Avoid critical resource consumption and balance the schedule.
3273 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3274 TryCand, Cand, ResourceReduce))
3275 return;
3276 if (tryGreater(TryCand.ResDelta.DemandedResources,
3277 Cand.ResDelta.DemandedResources,
3278 TryCand, Cand, ResourceDemand))
3279 return;
3280
3281 // Avoid serializing long latency dependence chains.
3282 if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
3283 return;
3284 }
3285
3286 // Fall through to original instruction order.
3287 if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
3288 TryCand.Reason = NodeOrder;
3289}
3290
3291void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
3292 ReadyQueue &Q = Top.Available;
Javed Absare3a0cc22017-06-21 09:10:10 +00003293 for (SUnit *SU : Q) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003294 SchedCandidate TryCand(Cand.Policy);
Javed Absare3a0cc22017-06-21 09:10:10 +00003295 TryCand.SU = SU;
Matthias Braun6ad3d052016-06-25 00:23:00 +00003296 TryCand.AtTop = true;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003297 TryCand.initResourceDelta(DAG, SchedModel);
3298 tryCandidate(Cand, TryCand);
3299 if (TryCand.Reason != NoCand) {
3300 Cand.setBest(TryCand);
3301 DEBUG(traceCandidate(Cand));
3302 }
3303 }
3304}
3305
3306/// Pick the next node to schedule.
3307SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
3308 if (DAG->top() == DAG->bottom()) {
3309 assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00003310 return nullptr;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003311 }
3312 SUnit *SU;
3313 do {
3314 SU = Top.pickOnlyChoice();
Matthias Braun49cb6e92016-05-27 22:14:26 +00003315 if (SU) {
3316 tracePick(Only1, true);
3317 } else {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003318 CandPolicy NoPolicy;
3319 SchedCandidate TopCand(NoPolicy);
3320 // Set the top-down policy based on the state of the current top zone and
3321 // the instructions outside the zone, including the bottom zone.
Craig Topperc0196b12014-04-14 00:51:57 +00003322 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003323 pickNodeFromQueue(TopCand);
3324 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003325 tracePick(TopCand);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003326 SU = TopCand.SU;
3327 }
3328 } while (SU->isScheduled);
3329
3330 IsTopNode = true;
3331 Top.removeReady(SU);
3332
3333 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
3334 return SU;
3335}
3336
3337/// Called after ScheduleDAGMI has scheduled an instruction and updated
3338/// scheduled/remaining flags in the DAG nodes.
3339void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
3340 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
3341 Top.bumpNode(SU);
3342}
3343
Matthias Braun115efcd2016-11-28 20:11:54 +00003344ScheduleDAGMI *llvm::createGenericSchedPostRA(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003345 return new ScheduleDAGMI(C, llvm::make_unique<PostGenericScheduler>(C),
Jonas Paulsson28f29482016-11-09 09:59:27 +00003346 /*RemoveKillFlags=*/true);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003347}
Andrew Tricke1c034f2012-01-17 06:55:03 +00003348
3349//===----------------------------------------------------------------------===//
Andrew Trick90f711d2012-10-15 18:02:27 +00003350// ILP Scheduler. Currently for experimental analysis of heuristics.
3351//===----------------------------------------------------------------------===//
3352
3353namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003354
Andrew Trick90f711d2012-10-15 18:02:27 +00003355/// \brief Order nodes by the ILP metric.
3356struct ILPOrder {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003357 const SchedDFSResult *DFSResult = nullptr;
3358 const BitVector *ScheduledTrees = nullptr;
Andrew Trick90f711d2012-10-15 18:02:27 +00003359 bool MaximizeILP;
3360
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003361 ILPOrder(bool MaxILP) : MaximizeILP(MaxILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003362
3363 /// \brief Apply a less-than relation on node priority.
Andrew Trick48d392e2012-11-28 05:13:28 +00003364 ///
3365 /// (Return true if A comes after B in the Q.)
Andrew Trick90f711d2012-10-15 18:02:27 +00003366 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick48d392e2012-11-28 05:13:28 +00003367 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3368 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3369 if (SchedTreeA != SchedTreeB) {
3370 // Unscheduled trees have lower priority.
3371 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3372 return ScheduledTrees->test(SchedTreeB);
3373
3374 // Trees with shallower connections have have lower priority.
3375 if (DFSResult->getSubtreeLevel(SchedTreeA)
3376 != DFSResult->getSubtreeLevel(SchedTreeB)) {
3377 return DFSResult->getSubtreeLevel(SchedTreeA)
3378 < DFSResult->getSubtreeLevel(SchedTreeB);
3379 }
3380 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003381 if (MaximizeILP)
Andrew Trick48d392e2012-11-28 05:13:28 +00003382 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003383 else
Andrew Trick48d392e2012-11-28 05:13:28 +00003384 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003385 }
3386};
3387
3388/// \brief Schedule based on the ILP metric.
3389class ILPScheduler : public MachineSchedStrategy {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003390 ScheduleDAGMILive *DAG = nullptr;
Andrew Trick90f711d2012-10-15 18:02:27 +00003391 ILPOrder Cmp;
3392
3393 std::vector<SUnit*> ReadyQ;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003394
Andrew Trick90f711d2012-10-15 18:02:27 +00003395public:
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003396 ILPScheduler(bool MaximizeILP) : Cmp(MaximizeILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003397
Craig Topper4584cd52014-03-07 09:26:03 +00003398 void initialize(ScheduleDAGMI *dag) override {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003399 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3400 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00003401 DAG->computeDFSResult();
Andrew Trick44f750a2013-01-25 04:01:04 +00003402 Cmp.DFSResult = DAG->getDFSResult();
3403 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick90f711d2012-10-15 18:02:27 +00003404 ReadyQ.clear();
Andrew Trick90f711d2012-10-15 18:02:27 +00003405 }
3406
Craig Topper4584cd52014-03-07 09:26:03 +00003407 void registerRoots() override {
Benjamin Krameraa598b32012-11-29 14:36:26 +00003408 // Restore the heap in ReadyQ with the updated DFS results.
3409 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003410 }
3411
3412 /// Implement MachineSchedStrategy interface.
3413 /// -----------------------------------------
3414
Andrew Trick48d392e2012-11-28 05:13:28 +00003415 /// Callback to select the highest priority node from the ready Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003416 SUnit *pickNode(bool &IsTopNode) override {
Craig Topperc0196b12014-04-14 00:51:57 +00003417 if (ReadyQ.empty()) return nullptr;
Matt Arsenault4ab769f2013-03-21 00:57:21 +00003418 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003419 SUnit *SU = ReadyQ.back();
3420 ReadyQ.pop_back();
3421 IsTopNode = false;
Andrew Trick1f0bb692013-04-13 06:07:49 +00003422 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
Andrew Trick44f750a2013-01-25 04:01:04 +00003423 << " ILP: " << DAG->getDFSResult()->getILP(SU)
3424 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
3425 << DAG->getDFSResult()->getSubtreeLevel(
Andrew Trick1f0bb692013-04-13 06:07:49 +00003426 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
3427 << "Scheduling " << *SU->getInstr());
Andrew Trick90f711d2012-10-15 18:02:27 +00003428 return SU;
3429 }
3430
Andrew Trick44f750a2013-01-25 04:01:04 +00003431 /// \brief Scheduler callback to notify that a new subtree is scheduled.
Craig Topper4584cd52014-03-07 09:26:03 +00003432 void scheduleTree(unsigned SubtreeID) override {
Andrew Trick44f750a2013-01-25 04:01:04 +00003433 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3434 }
3435
Andrew Trick48d392e2012-11-28 05:13:28 +00003436 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3437 /// DFSResults, and resort the priority Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003438 void schedNode(SUnit *SU, bool IsTopNode) override {
Andrew Trick48d392e2012-11-28 05:13:28 +00003439 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick48d392e2012-11-28 05:13:28 +00003440 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003441
Craig Topper4584cd52014-03-07 09:26:03 +00003442 void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
Andrew Trick90f711d2012-10-15 18:02:27 +00003443
Craig Topper4584cd52014-03-07 09:26:03 +00003444 void releaseBottomNode(SUnit *SU) override {
Andrew Trick90f711d2012-10-15 18:02:27 +00003445 ReadyQ.push_back(SU);
3446 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3447 }
3448};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003449
3450} // end anonymous namespace
Andrew Trick90f711d2012-10-15 18:02:27 +00003451
3452static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003453 return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(true));
Andrew Trick90f711d2012-10-15 18:02:27 +00003454}
3455static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003456 return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(false));
Andrew Trick90f711d2012-10-15 18:02:27 +00003457}
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003458
Andrew Trick90f711d2012-10-15 18:02:27 +00003459static MachineSchedRegistry ILPMaxRegistry(
3460 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3461static MachineSchedRegistry ILPMinRegistry(
3462 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3463
3464//===----------------------------------------------------------------------===//
Andrew Trick63440872012-01-14 02:17:06 +00003465// Machine Instruction Shuffler for Correctness Testing
3466//===----------------------------------------------------------------------===//
3467
Andrew Tricke77e84e2012-01-13 06:30:30 +00003468#ifndef NDEBUG
3469namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003470
Andrew Trick8823dec2012-03-14 04:00:41 +00003471/// Apply a less-than relation on the node order, which corresponds to the
3472/// instruction order prior to scheduling. IsReverse implements greater-than.
3473template<bool IsReverse>
3474struct SUnitOrder {
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003475 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick8823dec2012-03-14 04:00:41 +00003476 if (IsReverse)
3477 return A->NodeNum > B->NodeNum;
3478 else
3479 return A->NodeNum < B->NodeNum;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003480 }
3481};
3482
Andrew Tricke77e84e2012-01-13 06:30:30 +00003483/// Reorder instructions as much as possible.
Andrew Trick8823dec2012-03-14 04:00:41 +00003484class InstructionShuffler : public MachineSchedStrategy {
3485 bool IsAlternating;
3486 bool IsTopDown;
3487
3488 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3489 // gives nodes with a higher number higher priority causing the latest
3490 // instructions to be scheduled first.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003491 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false>>
Andrew Trick8823dec2012-03-14 04:00:41 +00003492 TopQ;
Eugene Zelenko32a40562017-09-11 23:00:48 +00003493
Andrew Trick8823dec2012-03-14 04:00:41 +00003494 // When scheduling bottom-up, use greater-than as the queue priority.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003495 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true>>
Andrew Trick8823dec2012-03-14 04:00:41 +00003496 BottomQ;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003497
Andrew Tricke77e84e2012-01-13 06:30:30 +00003498public:
Andrew Trick8823dec2012-03-14 04:00:41 +00003499 InstructionShuffler(bool alternate, bool topdown)
3500 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Tricke77e84e2012-01-13 06:30:30 +00003501
Craig Topper9d74a5a2014-04-29 07:58:41 +00003502 void initialize(ScheduleDAGMI*) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003503 TopQ.clear();
3504 BottomQ.clear();
3505 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003506
Andrew Trick8823dec2012-03-14 04:00:41 +00003507 /// Implement MachineSchedStrategy interface.
3508 /// -----------------------------------------
3509
Craig Topper9d74a5a2014-04-29 07:58:41 +00003510 SUnit *pickNode(bool &IsTopNode) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003511 SUnit *SU;
3512 if (IsTopDown) {
3513 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003514 if (TopQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003515 SU = TopQ.top();
3516 TopQ.pop();
3517 } while (SU->isScheduled);
3518 IsTopNode = true;
Matthias Braunb550b762016-04-21 01:54:13 +00003519 } else {
Andrew Trick8823dec2012-03-14 04:00:41 +00003520 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003521 if (BottomQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003522 SU = BottomQ.top();
3523 BottomQ.pop();
3524 } while (SU->isScheduled);
3525 IsTopNode = false;
3526 }
3527 if (IsAlternating)
3528 IsTopDown = !IsTopDown;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003529 return SU;
3530 }
3531
Craig Topper9d74a5a2014-04-29 07:58:41 +00003532 void schedNode(SUnit *SU, bool IsTopNode) override {}
Andrew Trick61f1a272012-05-24 22:11:09 +00003533
Craig Topper9d74a5a2014-04-29 07:58:41 +00003534 void releaseTopNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003535 TopQ.push(SU);
3536 }
Craig Topper9d74a5a2014-04-29 07:58:41 +00003537 void releaseBottomNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003538 BottomQ.push(SU);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003539 }
3540};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003541
3542} // end anonymous namespace
Andrew Tricke77e84e2012-01-13 06:30:30 +00003543
Andrew Trick02a80da2012-03-08 01:41:12 +00003544static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick8823dec2012-03-14 04:00:41 +00003545 bool Alternate = !ForceTopDown && !ForceBottomUp;
3546 bool TopDown = !ForceBottomUp;
Benjamin Kramer05e7a842012-03-14 11:26:37 +00003547 assert((TopDown || !ForceTopDown) &&
Andrew Trick8823dec2012-03-14 04:00:41 +00003548 "-misched-topdown incompatible with -misched-bottomup");
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003549 return new ScheduleDAGMILive(
3550 C, llvm::make_unique<InstructionShuffler>(Alternate, TopDown));
Andrew Tricke77e84e2012-01-13 06:30:30 +00003551}
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003552
Andrew Trick8823dec2012-03-14 04:00:41 +00003553static MachineSchedRegistry ShufflerRegistry(
3554 "shuffle", "Shuffle machine instructions alternating directions",
3555 createInstructionShuffler);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003556#endif // !NDEBUG
Andrew Trickea9fd952013-01-25 07:45:29 +00003557
3558//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +00003559// GraphWriter support for ScheduleDAGMILive.
Andrew Trickea9fd952013-01-25 07:45:29 +00003560//===----------------------------------------------------------------------===//
3561
3562#ifndef NDEBUG
3563namespace llvm {
3564
3565template<> struct GraphTraits<
3566 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3567
3568template<>
3569struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003570 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
Andrew Trickea9fd952013-01-25 07:45:29 +00003571
3572 static std::string getGraphName(const ScheduleDAG *G) {
3573 return G->MF.getName();
3574 }
3575
3576 static bool renderGraphFromBottomUp() {
3577 return true;
3578 }
3579
3580 static bool isNodeHidden(const SUnit *Node) {
Matthias Braund78ee542015-09-17 21:09:59 +00003581 if (ViewMISchedCutoff == 0)
3582 return false;
3583 return (Node->Preds.size() > ViewMISchedCutoff
3584 || Node->Succs.size() > ViewMISchedCutoff);
Andrew Trickea9fd952013-01-25 07:45:29 +00003585 }
3586
Andrew Trickea9fd952013-01-25 07:45:29 +00003587 /// If you want to override the dot attributes printed for a particular
3588 /// edge, override this method.
3589 static std::string getEdgeAttributes(const SUnit *Node,
3590 SUnitIterator EI,
3591 const ScheduleDAG *Graph) {
3592 if (EI.isArtificialDep())
3593 return "color=cyan,style=dashed";
3594 if (EI.isCtrlDep())
3595 return "color=blue,style=dashed";
3596 return "";
3597 }
3598
3599 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
Alp Tokere69170a2014-06-26 22:52:05 +00003600 std::string Str;
3601 raw_string_ostream SS(Str);
Andrew Trickd7f890e2013-12-28 21:56:47 +00003602 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3603 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003604 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trick7609b7d2013-09-06 17:32:42 +00003605 SS << "SU:" << SU->NodeNum;
3606 if (DFS)
3607 SS << " I:" << DFS->getNumInstrs(SU);
Andrew Trickea9fd952013-01-25 07:45:29 +00003608 return SS.str();
3609 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00003610
Andrew Trickea9fd952013-01-25 07:45:29 +00003611 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3612 return G->getGraphNodeLabel(SU);
3613 }
3614
Andrew Trickd7f890e2013-12-28 21:56:47 +00003615 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
Andrew Trickea9fd952013-01-25 07:45:29 +00003616 std::string Str("shape=Mrecord");
Andrew Trickd7f890e2013-12-28 21:56:47 +00003617 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3618 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003619 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trickea9fd952013-01-25 07:45:29 +00003620 if (DFS) {
3621 Str += ",style=filled,fillcolor=\"#";
3622 Str += DOT::getColorString(DFS->getSubtreeID(N));
3623 Str += '"';
3624 }
3625 return Str;
3626 }
3627};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003628
3629} // end namespace llvm
Andrew Trickea9fd952013-01-25 07:45:29 +00003630#endif // NDEBUG
3631
3632/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3633/// rendered using 'dot'.
Andrew Trickea9fd952013-01-25 07:45:29 +00003634void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3635#ifndef NDEBUG
3636 ViewGraph(this, Name, false, Title);
3637#else
3638 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3639 << "systems with Graphviz or gv!\n";
3640#endif // NDEBUG
3641}
3642
3643/// Out-of-line implementation with no arguments is handy for gdb.
3644void ScheduleDAGMI::viewGraph() {
3645 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
3646}