blob: f3017ac14489e6d2fc715350ed461d308574050f [file] [log] [blame]
Andrew Trick6a50baa2012-05-17 22:37:09 +00001//===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
Andrew Tricke77e84e2012-01-13 06:30:30 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// MachineScheduler schedules machine instructions after phi elimination. It
11// preserves LiveIntervals so it can be invoked before register allocation.
12//
13//===----------------------------------------------------------------------===//
14
Chandler Carruth6bda14b2017-06-06 11:49:48 +000015#include "llvm/CodeGen/MachineScheduler.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000016#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/DenseMap.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/PriorityQueue.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000020#include "llvm/ADT/STLExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000021#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/iterator_range.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000024#include "llvm/CodeGen/LiveInterval.h"
Matthias Braunf8422972017-12-13 02:51:04 +000025#include "llvm/CodeGen/LiveIntervals.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000026#include "llvm/CodeGen/MachineBasicBlock.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000027#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFunctionPass.h"
30#include "llvm/CodeGen/MachineInstr.h"
Jakub Staszakdf17ddd2013-03-10 13:11:23 +000031#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000032#include "llvm/CodeGen/MachineOperand.h"
33#include "llvm/CodeGen/MachinePassRegistry.h"
Andrew Trick736dd9a2013-06-21 18:32:58 +000034#include "llvm/CodeGen/MachineRegisterInfo.h"
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"
David Blaikieb3bde2e2017-11-17 01:07:10 +000046#include "llvm/CodeGen/TargetLowering.h"
Matthias Braun31d19d42016-05-10 03:21:59 +000047#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000048#include "llvm/CodeGen/TargetRegisterInfo.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000049#include "llvm/CodeGen/TargetSchedule.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000050#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000051#include "llvm/MC/LaneBitmask.h"
52#include "llvm/Pass.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000053#include "llvm/Support/CommandLine.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000054#include "llvm/Support/Compiler.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000055#include "llvm/Support/Debug.h"
56#include "llvm/Support/ErrorHandling.h"
Andrew Trickea9fd952013-01-25 07:45:29 +000057#include "llvm/Support/GraphWriter.h"
Andrew Tricke77e84e2012-01-13 06:30:30 +000058#include "llvm/Support/raw_ostream.h"
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +000059#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,
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000101 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");
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000551 DEBUG(dbgs() << MF->getName() << ":" << printMBBReference(*MBB) << " "
552 << MBB->getName() << "\n From: " << *I << " To: ";
Andrew Tricke57583a2012-02-08 02:17:21 +0000553 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
554 else dbgs() << "End";
Matthias Braun858d1df2016-05-20 19:46:13 +0000555 dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +0000556 if (DumpCriticalPathLength) {
557 errs() << MF->getName();
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000558 errs() << ":%bb. " << MBB->getNumber();
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +0000559 errs() << " " << MBB->getName() << " \n";
560 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +0000561
Andrew Trick1c0ec452012-03-09 03:46:42 +0000562 // Schedule a region: possibly reorder instructions.
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000563 // This invalidates the original region iterators.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000564 Scheduler.schedule();
Andrew Trick1c0ec452012-03-09 03:46:42 +0000565
566 // Close the current region.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000567 Scheduler.exitRegion();
Andrew Trick7e120f42012-01-14 02:17:09 +0000568 }
Andrew Trickd7f890e2013-12-28 21:56:47 +0000569 Scheduler.finishBlock();
Matthias Braun93563e72015-11-03 01:53:29 +0000570 // FIXME: Ideally, no further passes should rely on kill flags. However,
571 // thumb2 size reduction is currently an exception, so the PostMIScheduler
572 // needs to do this.
573 if (FixKillFlags)
Matthias Braun868bbd42017-05-27 02:50:50 +0000574 Scheduler.fixupKills(*MBB);
Andrew Tricke77e84e2012-01-13 06:30:30 +0000575 }
Andrew Trickd7f890e2013-12-28 21:56:47 +0000576 Scheduler.finalizeSchedule();
Andrew Tricke77e84e2012-01-13 06:30:30 +0000577}
578
Andrew Trickd7f890e2013-12-28 21:56:47 +0000579void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
Andrew Tricke77e84e2012-01-13 06:30:30 +0000580 // unimplemented
581}
582
Aaron Ballman615eb472017-10-15 14:32:27 +0000583#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Clegg705f7982017-06-21 22:19:17 +0000584LLVM_DUMP_METHOD void ReadyQueue::dump() const {
James Y Knighte72b0db2015-09-18 18:52:20 +0000585 dbgs() << "Queue " << Name << ": ";
Javed Absare3a0cc22017-06-21 09:10:10 +0000586 for (const SUnit *SU : Queue)
587 dbgs() << SU->NodeNum << " ";
Andrew Trick7a8e1002012-09-11 00:39:15 +0000588 dbgs() << "\n";
589}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000590#endif
Andrew Trick8823dec2012-03-14 04:00:41 +0000591
592//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +0000593// ScheduleDAGMI - Basic machine instruction scheduling. This is
594// independent of PreRA/PostRA scheduling and involves no extra book-keeping for
595// virtual registers.
596// ===----------------------------------------------------------------------===/
Andrew Trick8823dec2012-03-14 04:00:41 +0000597
David Blaikie422b93d2014-04-21 20:32:32 +0000598// Provide a vtable anchor.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000599ScheduleDAGMI::~ScheduleDAGMI() = default;
Andrew Trick44f750a2013-01-25 04:01:04 +0000600
Andrew Trick85a1d4c2013-04-24 15:54:43 +0000601bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
602 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
603}
604
Andrew Tricka7714a02012-11-12 19:40:10 +0000605bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
Andrew Trick263280242012-11-12 19:52:20 +0000606 if (SuccSU != &ExitSU) {
607 // Do not use WillCreateCycle, it assumes SD scheduling.
608 // If Pred is reachable from Succ, then the edge creates a cycle.
609 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
610 return false;
611 Topo.AddPred(SuccSU, PredDep.getSUnit());
612 }
Andrew Tricka7714a02012-11-12 19:40:10 +0000613 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
614 // Return true regardless of whether a new edge needed to be inserted.
615 return true;
616}
617
Andrew Trick02a80da2012-03-08 01:41:12 +0000618/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
619/// NumPredsLeft reaches zero, release the successor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000620///
621/// FIXME: Adjust SuccSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000622void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
Andrew Trick02a80da2012-03-08 01:41:12 +0000623 SUnit *SuccSU = SuccEdge->getSUnit();
624
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000625 if (SuccEdge->isWeak()) {
626 --SuccSU->WeakPredsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000627 if (SuccEdge->isCluster())
628 NextClusterSucc = SuccSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000629 return;
630 }
Andrew Trick02a80da2012-03-08 01:41:12 +0000631#ifndef NDEBUG
632 if (SuccSU->NumPredsLeft == 0) {
633 dbgs() << "*** Scheduling failed! ***\n";
634 SuccSU->dump(this);
635 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000636 llvm_unreachable(nullptr);
Andrew Trick02a80da2012-03-08 01:41:12 +0000637 }
638#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000639 // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
640 // CurrCycle may have advanced since then.
641 if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
642 SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
643
Andrew Trick02a80da2012-03-08 01:41:12 +0000644 --SuccSU->NumPredsLeft;
645 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Andrew Trick8823dec2012-03-14 04:00:41 +0000646 SchedImpl->releaseTopNode(SuccSU);
Andrew Trick02a80da2012-03-08 01:41:12 +0000647}
648
649/// releaseSuccessors - Call releaseSucc on each of SU's successors.
Andrew Trick8823dec2012-03-14 04:00:41 +0000650void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
Javed Absare3a0cc22017-06-21 09:10:10 +0000651 for (SDep &Succ : SU->Succs)
652 releaseSucc(SU, &Succ);
Andrew Trick02a80da2012-03-08 01:41:12 +0000653}
654
Andrew Trick8823dec2012-03-14 04:00:41 +0000655/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
656/// NumSuccsLeft reaches zero, release the predecessor node.
Andrew Trick61f1a272012-05-24 22:11:09 +0000657///
658/// FIXME: Adjust PredSU height based on MinLatency.
Andrew Trick8823dec2012-03-14 04:00:41 +0000659void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
660 SUnit *PredSU = PredEdge->getSUnit();
661
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000662 if (PredEdge->isWeak()) {
663 --PredSU->WeakSuccsLeft;
Andrew Tricka7714a02012-11-12 19:40:10 +0000664 if (PredEdge->isCluster())
665 NextClusterPred = PredSU;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000666 return;
667 }
Andrew Trick8823dec2012-03-14 04:00:41 +0000668#ifndef NDEBUG
669 if (PredSU->NumSuccsLeft == 0) {
670 dbgs() << "*** Scheduling failed! ***\n";
671 PredSU->dump(this);
672 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000673 llvm_unreachable(nullptr);
Andrew Trick8823dec2012-03-14 04:00:41 +0000674 }
675#endif
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000676 // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
677 // CurrCycle may have advanced since then.
678 if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
679 PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
680
Andrew Trick8823dec2012-03-14 04:00:41 +0000681 --PredSU->NumSuccsLeft;
682 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
683 SchedImpl->releaseBottomNode(PredSU);
684}
685
686/// releasePredecessors - Call releasePred on each of SU's predecessors.
687void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
Javed Absare3a0cc22017-06-21 09:10:10 +0000688 for (SDep &Pred : SU->Preds)
689 releasePred(SU, &Pred);
Andrew Trick8823dec2012-03-14 04:00:41 +0000690}
691
Jonas Paulsson57a705d2017-08-17 08:33:44 +0000692void ScheduleDAGMI::startBlock(MachineBasicBlock *bb) {
693 ScheduleDAGInstrs::startBlock(bb);
694 SchedImpl->enterMBB(bb);
695}
696
697void ScheduleDAGMI::finishBlock() {
698 SchedImpl->leaveMBB();
699 ScheduleDAGInstrs::finishBlock();
700}
701
Andrew Trickd7f890e2013-12-28 21:56:47 +0000702/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
703/// crossing a scheduling boundary. [begin, end) includes all instructions in
704/// the region, including the boundary itself and single-instruction regions
705/// that don't get scheduled.
706void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
707 MachineBasicBlock::iterator begin,
708 MachineBasicBlock::iterator end,
709 unsigned regioninstrs)
710{
711 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
712
713 SchedImpl->initPolicy(begin, end, regioninstrs);
714}
715
Andrew Tricke833e1c2013-04-13 06:07:40 +0000716/// This is normally called from the main scheduler loop but may also be invoked
717/// by the scheduling strategy to perform additional code motion.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000718void ScheduleDAGMI::moveInstruction(
719 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
Andrew Trick463b2f12012-05-17 18:35:03 +0000720 // Advance RegionBegin if the first instruction moves down.
Andrew Trick54f7def2012-03-21 04:12:10 +0000721 if (&*RegionBegin == MI)
Andrew Trick463b2f12012-05-17 18:35:03 +0000722 ++RegionBegin;
723
724 // Update the instruction stream.
Andrew Trick8823dec2012-03-14 04:00:41 +0000725 BB->splice(InsertPos, BB, MI);
Andrew Trick463b2f12012-05-17 18:35:03 +0000726
727 // Update LiveIntervals
Andrew Trickd7f890e2013-12-28 21:56:47 +0000728 if (LIS)
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +0000729 LIS->handleMove(*MI, /*UpdateFlags=*/true);
Andrew Trick463b2f12012-05-17 18:35:03 +0000730
731 // Recede RegionBegin if an instruction moves above the first.
Andrew Trick8823dec2012-03-14 04:00:41 +0000732 if (RegionBegin == InsertPos)
733 RegionBegin = MI;
734}
735
Andrew Trickde670c02012-03-21 04:12:07 +0000736bool ScheduleDAGMI::checkSchedLimit() {
737#ifndef NDEBUG
738 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
739 CurrentTop = CurrentBottom;
740 return false;
741 }
742 ++NumInstrsScheduled;
743#endif
744 return true;
745}
746
Andrew Trickd7f890e2013-12-28 21:56:47 +0000747/// Per-region scheduling driver, called back from
748/// MachineScheduler::runOnMachineFunction. This is a simplified driver that
749/// does not consider liveness or register pressure. It is useful for PostRA
750/// scheduling and potentially other custom schedulers.
751void ScheduleDAGMI::schedule() {
James Y Knighte72b0db2015-09-18 18:52:20 +0000752 DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n");
753 DEBUG(SchedImpl->dumpPolicy());
754
Andrew Trickd7f890e2013-12-28 21:56:47 +0000755 // Build the DAG.
756 buildSchedGraph(AA);
757
758 Topo.InitDAGTopologicalSorting();
759
760 postprocessDAG();
761
762 SmallVector<SUnit*, 8> TopRoots, BotRoots;
763 findRootsAndBiasEdges(TopRoots, BotRoots);
764
765 // Initialize the strategy before modifying the DAG.
766 // This may initialize a DFSResult to be used for queue priority.
767 SchedImpl->initialize(this);
768
Matthias Braun69f1d122016-11-11 22:37:28 +0000769 DEBUG(
770 if (EntrySU.getInstr() != nullptr)
771 EntrySU.dumpAll(this);
Javed Absare3a0cc22017-06-21 09:10:10 +0000772 for (const SUnit &SU : SUnits)
773 SU.dumpAll(this);
Matthias Braun69f1d122016-11-11 22:37:28 +0000774 if (ExitSU.getInstr() != nullptr)
775 ExitSU.dumpAll(this);
776 );
Andrew Trickd7f890e2013-12-28 21:56:47 +0000777 if (ViewMISchedDAGs) viewGraph();
778
779 // Initialize ready queues now that the DAG and priority data are finalized.
780 initQueues(TopRoots, BotRoots);
781
782 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +0000783 while (true) {
784 DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n");
785 SUnit *SU = SchedImpl->pickNode(IsTopNode);
786 if (!SU) break;
787
Andrew Trickd7f890e2013-12-28 21:56:47 +0000788 assert(!SU->isScheduled && "Node already scheduled");
789 if (!checkSchedLimit())
790 break;
791
792 MachineInstr *MI = SU->getInstr();
793 if (IsTopNode) {
794 assert(SU->isTopReady() && "node still has unscheduled dependencies");
795 if (&*CurrentTop == MI)
796 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
797 else
798 moveInstruction(MI, CurrentTop);
Matthias Braunb550b762016-04-21 01:54:13 +0000799 } else {
Andrew Trickd7f890e2013-12-28 21:56:47 +0000800 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
801 MachineBasicBlock::iterator priorII =
802 priorNonDebug(CurrentBottom, CurrentTop);
803 if (&*priorII == MI)
804 CurrentBottom = priorII;
805 else {
806 if (&*CurrentTop == MI)
807 CurrentTop = nextIfDebug(++CurrentTop, priorII);
808 moveInstruction(MI, CurrentBottom);
809 CurrentBottom = MI;
810 }
811 }
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000812 // Notify the scheduling strategy before updating the DAG.
Andrew Trick491e34a2014-06-12 22:36:28 +0000813 // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000814 // runs, it can then use the accurate ReadyCycle time to determine whether
815 // newly released nodes can move to the readyQ.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000816 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +0000817
818 updateQueues(SU, IsTopNode);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000819 }
820 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
821
822 placeDebugValues();
823
824 DEBUG({
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000825 dbgs() << "*** Final schedule for "
826 << printMBBReference(*begin()->getParent()) << " ***\n";
827 dumpSchedule();
828 dbgs() << '\n';
829 });
Andrew Trickd7f890e2013-12-28 21:56:47 +0000830}
831
832/// Apply each ScheduleDAGMutation step in order.
833void ScheduleDAGMI::postprocessDAG() {
Javed Absare3a0cc22017-06-21 09:10:10 +0000834 for (auto &m : Mutations)
835 m->apply(this);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000836}
837
838void ScheduleDAGMI::
839findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
840 SmallVectorImpl<SUnit*> &BotRoots) {
Javed Absare3a0cc22017-06-21 09:10:10 +0000841 for (SUnit &SU : SUnits) {
842 assert(!SU.isBoundaryNode() && "Boundary node should not be in SUnits");
Andrew Trickd7f890e2013-12-28 21:56:47 +0000843
844 // Order predecessors so DFSResult follows the critical path.
Javed Absare3a0cc22017-06-21 09:10:10 +0000845 SU.biasCriticalPath();
Andrew Trickd7f890e2013-12-28 21:56:47 +0000846
847 // A SUnit is ready to top schedule if it has no predecessors.
Javed Absare3a0cc22017-06-21 09:10:10 +0000848 if (!SU.NumPredsLeft)
849 TopRoots.push_back(&SU);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000850 // A SUnit is ready to bottom schedule if it has no successors.
Javed Absare3a0cc22017-06-21 09:10:10 +0000851 if (!SU.NumSuccsLeft)
852 BotRoots.push_back(&SU);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000853 }
854 ExitSU.biasCriticalPath();
855}
856
857/// Identify DAG roots and setup scheduler queues.
858void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
859 ArrayRef<SUnit*> BotRoots) {
Craig Topperc0196b12014-04-14 00:51:57 +0000860 NextClusterSucc = nullptr;
861 NextClusterPred = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000862
863 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
864 //
865 // Nodes with unreleased weak edges can still be roots.
866 // Release top roots in forward order.
Javed Absare3a0cc22017-06-21 09:10:10 +0000867 for (SUnit *SU : TopRoots)
868 SchedImpl->releaseTopNode(SU);
869
Andrew Trickd7f890e2013-12-28 21:56:47 +0000870 // Release bottom roots in reverse order so the higher priority nodes appear
871 // first. This is more natural and slightly more efficient.
872 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
873 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
874 SchedImpl->releaseBottomNode(*I);
875 }
876
877 releaseSuccessors(&EntrySU);
878 releasePredecessors(&ExitSU);
879
880 SchedImpl->registerRoots();
881
882 // Advance past initial DebugValues.
883 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
884 CurrentBottom = RegionEnd;
885}
886
887/// Update scheduler queues after scheduling an instruction.
888void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
889 // Release dependent instructions for scheduling.
890 if (IsTopNode)
891 releaseSuccessors(SU);
892 else
893 releasePredecessors(SU);
894
895 SU->isScheduled = true;
896}
897
898/// Reinsert any remaining debug_values, just like the PostRA scheduler.
899void ScheduleDAGMI::placeDebugValues() {
900 // If first instruction was a DBG_VALUE then put it back.
901 if (FirstDbgValue) {
902 BB->splice(RegionBegin, BB, FirstDbgValue);
903 RegionBegin = FirstDbgValue;
904 }
905
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +0000906 for (std::vector<std::pair<MachineInstr *, MachineInstr *>>::iterator
Andrew Trickd7f890e2013-12-28 21:56:47 +0000907 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000908 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
Andrew Trickd7f890e2013-12-28 21:56:47 +0000909 MachineInstr *DbgValue = P.first;
910 MachineBasicBlock::iterator OrigPrevMI = P.second;
911 if (&*RegionBegin == DbgValue)
912 ++RegionBegin;
913 BB->splice(++OrigPrevMI, BB, DbgValue);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000914 if (OrigPrevMI == std::prev(RegionEnd))
Andrew Trickd7f890e2013-12-28 21:56:47 +0000915 RegionEnd = DbgValue;
916 }
917 DbgValues.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000918 FirstDbgValue = nullptr;
Andrew Trickd7f890e2013-12-28 21:56:47 +0000919}
920
Aaron Ballman615eb472017-10-15 14:32:27 +0000921#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000922LLVM_DUMP_METHOD void ScheduleDAGMI::dumpSchedule() const {
Andrew Trickd7f890e2013-12-28 21:56:47 +0000923 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
924 if (SUnit *SU = getSUnit(&(*MI)))
925 SU->dump(this);
926 else
927 dbgs() << "Missing SUnit\n";
928 }
929}
930#endif
931
932//===----------------------------------------------------------------------===//
933// ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
934// preservation.
935//===----------------------------------------------------------------------===//
936
937ScheduleDAGMILive::~ScheduleDAGMILive() {
938 delete DFSResult;
939}
940
Matthias Braun40639882016-11-11 22:37:31 +0000941void ScheduleDAGMILive::collectVRegUses(SUnit &SU) {
942 const MachineInstr &MI = *SU.getInstr();
943 for (const MachineOperand &MO : MI.operands()) {
944 if (!MO.isReg())
945 continue;
946 if (!MO.readsReg())
947 continue;
948 if (TrackLaneMasks && !MO.isUse())
949 continue;
950
951 unsigned Reg = MO.getReg();
952 if (!TargetRegisterInfo::isVirtualRegister(Reg))
953 continue;
954
955 // Ignore re-defs.
956 if (TrackLaneMasks) {
957 bool FoundDef = false;
958 for (const MachineOperand &MO2 : MI.operands()) {
959 if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
960 FoundDef = true;
961 break;
962 }
963 }
964 if (FoundDef)
965 continue;
966 }
967
968 // Record this local VReg use.
969 VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg);
970 for (; UI != VRegUses.end(); ++UI) {
971 if (UI->SU == &SU)
972 break;
973 }
974 if (UI == VRegUses.end())
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000975 VRegUses.insert(VReg2SUnit(Reg, LaneBitmask::getNone(), &SU));
Matthias Braun40639882016-11-11 22:37:31 +0000976 }
977}
978
Andrew Trick88639922012-04-24 17:56:43 +0000979/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
980/// crossing a scheduling boundary. [begin, end) includes all instructions in
981/// the region, including the boundary itself and single-instruction regions
982/// that don't get scheduled.
Andrew Trickd7f890e2013-12-28 21:56:47 +0000983void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
Andrew Trick88639922012-04-24 17:56:43 +0000984 MachineBasicBlock::iterator begin,
985 MachineBasicBlock::iterator end,
Andrew Tricka53e1012013-08-23 17:48:33 +0000986 unsigned regioninstrs)
Andrew Trick88639922012-04-24 17:56:43 +0000987{
Andrew Trickd7f890e2013-12-28 21:56:47 +0000988 // ScheduleDAGMI initializes SchedImpl's per-region policy.
989 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
Andrew Trick4add42f2012-05-10 21:06:10 +0000990
991 // For convenience remember the end of the liveness region.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000992 LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
Andrew Trick75e411c2013-09-06 17:32:34 +0000993
Andrew Trickb248b4a2013-09-06 17:32:47 +0000994 SUPressureDiffs.clear();
995
Andrew Trick75e411c2013-09-06 17:32:34 +0000996 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
Matthias Braund4f64092016-01-20 00:23:32 +0000997 ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
998
Matthias Braunf9acaca2016-05-31 22:38:06 +0000999 assert((!ShouldTrackLaneMasks || ShouldTrackPressure) &&
1000 "ShouldTrackLaneMasks requires ShouldTrackPressure");
Andrew Trick4add42f2012-05-10 21:06:10 +00001001}
1002
1003// Setup the register pressure trackers for the top scheduled top and bottom
1004// scheduled regions.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001005void ScheduleDAGMILive::initRegPressure() {
Matthias Braun40639882016-11-11 22:37:31 +00001006 VRegUses.clear();
1007 VRegUses.setUniverse(MRI.getNumVirtRegs());
1008 for (SUnit &SU : SUnits)
1009 collectVRegUses(SU);
1010
Matthias Braund4f64092016-01-20 00:23:32 +00001011 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin,
1012 ShouldTrackLaneMasks, false);
1013 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
1014 ShouldTrackLaneMasks, false);
Andrew Trick4add42f2012-05-10 21:06:10 +00001015
1016 // Close the RPTracker to finalize live ins.
1017 RPTracker.closeRegion();
1018
Andrew Trick9c17eab2013-07-30 19:59:12 +00001019 DEBUG(RPTracker.dump());
Andrew Trick79d3eec2012-05-24 22:11:14 +00001020
Andrew Trick4add42f2012-05-10 21:06:10 +00001021 // Initialize the live ins and live outs.
Matthias Braun3e86de12015-09-17 21:12:24 +00001022 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
1023 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick4add42f2012-05-10 21:06:10 +00001024
1025 // Close one end of the tracker so we can call
1026 // getMaxUpward/DownwardPressureDelta before advancing across any
1027 // instructions. This converts currently live regs into live ins/outs.
1028 TopRPTracker.closeTop();
1029 BotRPTracker.closeBottom();
1030
Andrew Trick9c17eab2013-07-30 19:59:12 +00001031 BotRPTracker.initLiveThru(RPTracker);
1032 if (!BotRPTracker.getLiveThru().empty()) {
1033 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
1034 DEBUG(dbgs() << "Live Thru: ";
1035 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
1036 };
1037
Andrew Trick2bc74c22013-08-30 04:36:57 +00001038 // For each live out vreg reduce the pressure change associated with other
1039 // uses of the same vreg below the live-out reaching def.
Matthias Braun3e86de12015-09-17 21:12:24 +00001040 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
Andrew Trick2bc74c22013-08-30 04:36:57 +00001041
Andrew Trick4add42f2012-05-10 21:06:10 +00001042 // Account for liveness generated by the region boundary.
Andrew Trick2bc74c22013-08-30 04:36:57 +00001043 if (LiveRegionEnd != RegionEnd) {
Matthias Braun5d458612016-01-20 00:23:26 +00001044 SmallVector<RegisterMaskPair, 8> LiveUses;
Andrew Trick2bc74c22013-08-30 04:36:57 +00001045 BotRPTracker.recede(&LiveUses);
1046 updatePressureDiffs(LiveUses);
1047 }
Andrew Trick4add42f2012-05-10 21:06:10 +00001048
Matthias Braune6edd482015-11-13 22:30:31 +00001049 DEBUG(
1050 dbgs() << "Top Pressure:\n";
1051 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
1052 dbgs() << "Bottom Pressure:\n";
1053 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);
1054 );
1055
Yaxun Liuf902ef02017-12-14 16:12:04 +00001056 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
Andrew Trick22025772012-05-17 18:35:10 +00001057
1058 // Cache the list of excess pressure sets in this region. This will also track
1059 // the max pressure in the scheduled code for these sets.
1060 RegionCriticalPSets.clear();
Jakub Staszakc641ada2013-01-25 21:44:27 +00001061 const std::vector<unsigned> &RegionPressure =
1062 RPTracker.getPressure().MaxSetPressure;
Andrew Trick22025772012-05-17 18:35:10 +00001063 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
Andrew Trick736dd9a2013-06-21 18:32:58 +00001064 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
Andrew Trickb55db582013-06-21 18:33:01 +00001065 if (RegionPressure[i] > Limit) {
1066 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
1067 << " Limit " << Limit
1068 << " Actual " << RegionPressure[i] << "\n");
Andrew Trick1a831342013-08-30 03:49:48 +00001069 RegionCriticalPSets.push_back(PressureChange(i));
Andrew Trickb55db582013-06-21 18:33:01 +00001070 }
Andrew Trick22025772012-05-17 18:35:10 +00001071 }
1072 DEBUG(dbgs() << "Excess PSets: ";
Javed Absare3a0cc22017-06-21 09:10:10 +00001073 for (const PressureChange &RCPS : RegionCriticalPSets)
Andrew Trick22025772012-05-17 18:35:10 +00001074 dbgs() << TRI->getRegPressureSetName(
Javed Absare3a0cc22017-06-21 09:10:10 +00001075 RCPS.getPSet()) << " ";
Andrew Trick22025772012-05-17 18:35:10 +00001076 dbgs() << "\n");
1077}
1078
Andrew Trickd7f890e2013-12-28 21:56:47 +00001079void ScheduleDAGMILive::
Andrew Trickb248b4a2013-09-06 17:32:47 +00001080updateScheduledPressure(const SUnit *SU,
1081 const std::vector<unsigned> &NewMaxPressure) {
1082 const PressureDiff &PDiff = getPressureDiff(SU);
1083 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
Javed Absare3a0cc22017-06-21 09:10:10 +00001084 for (const PressureChange &PC : PDiff) {
1085 if (!PC.isValid())
Andrew Trickb248b4a2013-09-06 17:32:47 +00001086 break;
Javed Absare3a0cc22017-06-21 09:10:10 +00001087 unsigned ID = PC.getPSet();
Andrew Trickb248b4a2013-09-06 17:32:47 +00001088 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
1089 ++CritIdx;
1090 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
1091 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
Simon Pilgrim858d8e62017-02-23 12:00:34 +00001092 && NewMaxPressure[ID] <= (unsigned)std::numeric_limits<int16_t>::max())
Andrew Trickb248b4a2013-09-06 17:32:47 +00001093 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
1094 }
1095 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
1096 if (NewMaxPressure[ID] >= Limit - 2) {
1097 DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
Andrew Trick569dc65a2015-05-17 23:40:31 +00001098 << NewMaxPressure[ID]
1099 << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ") << Limit
1100 << "(+ " << BotRPTracker.getLiveThru()[ID] << " livethru)\n");
Andrew Trickb248b4a2013-09-06 17:32:47 +00001101 }
Andrew Trick22025772012-05-17 18:35:10 +00001102 }
Andrew Trick88639922012-04-24 17:56:43 +00001103}
1104
Andrew Trick2bc74c22013-08-30 04:36:57 +00001105/// Update the PressureDiff array for liveness after scheduling this
1106/// instruction.
Matthias Braun5d458612016-01-20 00:23:26 +00001107void ScheduleDAGMILive::updatePressureDiffs(
1108 ArrayRef<RegisterMaskPair> LiveUses) {
1109 for (const RegisterMaskPair &P : LiveUses) {
Matthias Braun5d458612016-01-20 00:23:26 +00001110 unsigned Reg = P.RegUnit;
Matthias Braund4f64092016-01-20 00:23:32 +00001111 /// FIXME: Currently assuming single-use physregs.
Andrew Trick2bc74c22013-08-30 04:36:57 +00001112 if (!TRI->isVirtualRegister(Reg))
1113 continue;
Andrew Trickffdbefb2013-09-06 17:32:39 +00001114
Matthias Braund4f64092016-01-20 00:23:32 +00001115 if (ShouldTrackLaneMasks) {
1116 // If the register has just become live then other uses won't change
1117 // this fact anymore => decrement pressure.
1118 // If the register has just become dead then other uses make it come
1119 // back to life => increment pressure.
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +00001120 bool Decrement = P.LaneMask.any();
Matthias Braund4f64092016-01-20 00:23:32 +00001121
1122 for (const VReg2SUnit &V2SU
1123 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1124 SUnit &SU = *V2SU.SU;
1125 if (SU.isScheduled || &SU == &ExitSU)
1126 continue;
1127
1128 PressureDiff &PDiff = getPressureDiff(&SU);
Stanislav Mekhanoshin42259cf2017-02-24 21:56:16 +00001129 PDiff.addPressureChange(Reg, Decrement, &MRI);
Matthias Braund4f64092016-01-20 00:23:32 +00001130 DEBUG(
1131 dbgs() << " UpdateRegP: SU(" << SU.NodeNum << ") "
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001132 << printReg(Reg, TRI) << ':' << PrintLaneMask(P.LaneMask)
Matthias Braund4f64092016-01-20 00:23:32 +00001133 << ' ' << *SU.getInstr();
1134 dbgs() << " to ";
1135 PDiff.dump(*TRI);
1136 );
1137 }
1138 } else {
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +00001139 assert(P.LaneMask.any());
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001140 DEBUG(dbgs() << " LiveReg: " << printVRegOrUnit(Reg, TRI) << "\n");
Matthias Braund4f64092016-01-20 00:23:32 +00001141 // This may be called before CurrentBottom has been initialized. However,
1142 // BotRPTracker must have a valid position. We want the value live into the
1143 // instruction or live out of the block, so ask for the previous
1144 // instruction's live-out.
1145 const LiveInterval &LI = LIS->getInterval(Reg);
1146 VNInfo *VNI;
1147 MachineBasicBlock::const_iterator I =
1148 nextIfDebug(BotRPTracker.getPos(), BB->end());
1149 if (I == BB->end())
1150 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1151 else {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001152 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I));
Matthias Braund4f64092016-01-20 00:23:32 +00001153 VNI = LRQ.valueIn();
1154 }
1155 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
1156 assert(VNI && "No live value at use.");
1157 for (const VReg2SUnit &V2SU
1158 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1159 SUnit *SU = V2SU.SU;
1160 // If this use comes before the reaching def, it cannot be a last use,
1161 // so decrease its pressure change.
1162 if (!SU->isScheduled && SU != &ExitSU) {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001163 LiveQueryResult LRQ =
1164 LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Matthias Braund4f64092016-01-20 00:23:32 +00001165 if (LRQ.valueIn() == VNI) {
1166 PressureDiff &PDiff = getPressureDiff(SU);
Stanislav Mekhanoshin42259cf2017-02-24 21:56:16 +00001167 PDiff.addPressureChange(Reg, true, &MRI);
Matthias Braund4f64092016-01-20 00:23:32 +00001168 DEBUG(
1169 dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
1170 << *SU->getInstr();
1171 dbgs() << " to ";
1172 PDiff.dump(*TRI);
1173 );
1174 }
Matthias Braun9198c672015-11-06 20:59:02 +00001175 }
Andrew Trick2bc74c22013-08-30 04:36:57 +00001176 }
1177 }
1178 }
1179}
1180
Andrew Trick8823dec2012-03-14 04:00:41 +00001181/// schedule - Called back from MachineScheduler::runOnMachineFunction
Andrew Trick88639922012-04-24 17:56:43 +00001182/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
1183/// only includes instructions that have DAG nodes, not scheduling boundaries.
Andrew Trick7a8e1002012-09-11 00:39:15 +00001184///
1185/// This is a skeletal driver, with all the functionality pushed into helpers,
Nick Lewycky06b0ea22015-08-18 22:41:58 +00001186/// so that it can be easily extended by experimental schedulers. Generally,
Andrew Trick7a8e1002012-09-11 00:39:15 +00001187/// implementing MachineSchedStrategy should be sufficient to implement a new
1188/// scheduling algorithm. However, if a scheduler further subclasses
Andrew Trickd7f890e2013-12-28 21:56:47 +00001189/// ScheduleDAGMILive then it will want to override this virtual method in order
1190/// to update any specialized state.
1191void ScheduleDAGMILive::schedule() {
James Y Knighte72b0db2015-09-18 18:52:20 +00001192 DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n");
1193 DEBUG(SchedImpl->dumpPolicy());
Andrew Trick7a8e1002012-09-11 00:39:15 +00001194 buildDAGWithRegPressure();
1195
Andrew Tricka7714a02012-11-12 19:40:10 +00001196 Topo.InitDAGTopologicalSorting();
1197
Andrew Tricka2733e92012-09-14 17:22:42 +00001198 postprocessDAG();
1199
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001200 SmallVector<SUnit*, 8> TopRoots, BotRoots;
1201 findRootsAndBiasEdges(TopRoots, BotRoots);
1202
1203 // Initialize the strategy before modifying the DAG.
1204 // This may initialize a DFSResult to be used for queue priority.
1205 SchedImpl->initialize(this);
1206
Matthias Braun9198c672015-11-06 20:59:02 +00001207 DEBUG(
Matthias Braun69f1d122016-11-11 22:37:28 +00001208 if (EntrySU.getInstr() != nullptr)
1209 EntrySU.dumpAll(this);
Matthias Braun9198c672015-11-06 20:59:02 +00001210 for (const SUnit &SU : SUnits) {
1211 SU.dumpAll(this);
1212 if (ShouldTrackPressure) {
1213 dbgs() << " Pressure Diff : ";
1214 getPressureDiff(&SU).dump(*TRI);
1215 }
Javed Absar3d594372017-03-27 20:46:37 +00001216 dbgs() << " Single Issue : ";
1217 if (SchedModel.mustBeginGroup(SU.getInstr()) &&
1218 SchedModel.mustEndGroup(SU.getInstr()))
1219 dbgs() << "true;";
1220 else
1221 dbgs() << "false;";
Matthias Braun9198c672015-11-06 20:59:02 +00001222 dbgs() << '\n';
1223 }
Matthias Braun69f1d122016-11-11 22:37:28 +00001224 if (ExitSU.getInstr() != nullptr)
1225 ExitSU.dumpAll(this);
Matthias Braun9198c672015-11-06 20:59:02 +00001226 );
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001227 if (ViewMISchedDAGs) viewGraph();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001228
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001229 // Initialize ready queues now that the DAG and priority data are finalized.
1230 initQueues(TopRoots, BotRoots);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001231
1232 bool IsTopNode = false;
James Y Knighte72b0db2015-09-18 18:52:20 +00001233 while (true) {
1234 DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n");
1235 SUnit *SU = SchedImpl->pickNode(IsTopNode);
1236 if (!SU) break;
1237
Andrew Trick984d98b2012-10-08 18:53:53 +00001238 assert(!SU->isScheduled && "Node already scheduled");
Andrew Trick7a8e1002012-09-11 00:39:15 +00001239 if (!checkSchedLimit())
1240 break;
1241
1242 scheduleMI(SU, IsTopNode);
1243
Andrew Trickd7f890e2013-12-28 21:56:47 +00001244 if (DFSResult) {
1245 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1246 if (!ScheduledTrees.test(SubtreeID)) {
1247 ScheduledTrees.set(SubtreeID);
1248 DFSResult->scheduleTree(SubtreeID);
1249 SchedImpl->scheduleTree(SubtreeID);
1250 }
1251 }
1252
1253 // Notify the scheduling strategy after updating the DAG.
1254 SchedImpl->schedNode(SU, IsTopNode);
Andrew Trick43adfb32015-03-27 06:10:13 +00001255
1256 updateQueues(SU, IsTopNode);
Andrew Trick7a8e1002012-09-11 00:39:15 +00001257 }
1258 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1259
1260 placeDebugValues();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001261
1262 DEBUG({
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001263 dbgs() << "*** Final schedule for "
1264 << printMBBReference(*begin()->getParent()) << " ***\n";
1265 dumpSchedule();
1266 dbgs() << '\n';
1267 });
Andrew Trick7a8e1002012-09-11 00:39:15 +00001268}
1269
1270/// Build the DAG and setup three register pressure trackers.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001271void ScheduleDAGMILive::buildDAGWithRegPressure() {
Andrew Trickb6e74712013-09-04 20:59:59 +00001272 if (!ShouldTrackPressure) {
1273 RPTracker.reset();
1274 RegionCriticalPSets.clear();
1275 buildSchedGraph(AA);
1276 return;
1277 }
1278
Andrew Trick4add42f2012-05-10 21:06:10 +00001279 // Initialize the register pressure tracker used by buildSchedGraph.
Andrew Trick9c17eab2013-07-30 19:59:12 +00001280 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
Matthias Braund4f64092016-01-20 00:23:32 +00001281 ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true);
Andrew Trick88639922012-04-24 17:56:43 +00001282
Andrew Trick4add42f2012-05-10 21:06:10 +00001283 // Account for liveness generate by the region boundary.
1284 if (LiveRegionEnd != RegionEnd)
1285 RPTracker.recede();
1286
1287 // Build the DAG, and compute current register pressure.
Matthias Braund4f64092016-01-20 00:23:32 +00001288 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks);
Andrew Trick02a80da2012-03-08 01:41:12 +00001289
Andrew Trick4add42f2012-05-10 21:06:10 +00001290 // Initialize top/bottom trackers after computing region pressure.
1291 initRegPressure();
Andrew Trick7a8e1002012-09-11 00:39:15 +00001292}
Andrew Trick4add42f2012-05-10 21:06:10 +00001293
Andrew Trickd7f890e2013-12-28 21:56:47 +00001294void ScheduleDAGMILive::computeDFSResult() {
Andrew Trick44f750a2013-01-25 04:01:04 +00001295 if (!DFSResult)
1296 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1297 DFSResult->clear();
Andrew Trick44f750a2013-01-25 04:01:04 +00001298 ScheduledTrees.clear();
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001299 DFSResult->resize(SUnits.size());
1300 DFSResult->compute(SUnits);
Andrew Trick44f750a2013-01-25 04:01:04 +00001301 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1302}
1303
Andrew Trick483f4192013-08-29 18:04:49 +00001304/// Compute the max cyclic critical path through the DAG. The scheduling DAG
1305/// only provides the critical path for single block loops. To handle loops that
1306/// span blocks, we could use the vreg path latencies provided by
1307/// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1308/// available for use in the scheduler.
1309///
1310/// The cyclic path estimation identifies a def-use pair that crosses the back
Andrew Trickef80f502013-08-30 02:02:12 +00001311/// edge and considers the depth and height of the nodes. For example, consider
Andrew Trick483f4192013-08-29 18:04:49 +00001312/// the following instruction sequence where each instruction has unit latency
1313/// and defines an epomymous virtual register:
1314///
1315/// a->b(a,c)->c(b)->d(c)->exit
1316///
1317/// The cyclic critical path is a two cycles: b->c->b
1318/// The acyclic critical path is four cycles: a->b->c->d->exit
1319/// LiveOutHeight = height(c) = len(c->d->exit) = 2
1320/// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1321/// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1322/// LiveInDepth = depth(b) = len(a->b) = 1
1323///
1324/// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1325/// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1326/// CyclicCriticalPath = min(2, 2) = 2
Andrew Trickd7f890e2013-12-28 21:56:47 +00001327///
1328/// This could be relevant to PostRA scheduling, but is currently implemented
1329/// assuming LiveIntervals.
1330unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
Andrew Trick483f4192013-08-29 18:04:49 +00001331 // This only applies to single block loop.
1332 if (!BB->isSuccessor(BB))
1333 return 0;
1334
1335 unsigned MaxCyclicLatency = 0;
1336 // Visit each live out vreg def to find def/use pairs that cross iterations.
Matthias Braun5d458612016-01-20 00:23:26 +00001337 for (const RegisterMaskPair &P : RPTracker.getPressure().LiveOutRegs) {
1338 unsigned Reg = P.RegUnit;
Andrew Trick483f4192013-08-29 18:04:49 +00001339 if (!TRI->isVirtualRegister(Reg))
1340 continue;
1341 const LiveInterval &LI = LIS->getInterval(Reg);
1342 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1343 if (!DefVNI)
1344 continue;
1345
1346 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1347 const SUnit *DefSU = getSUnit(DefMI);
1348 if (!DefSU)
1349 continue;
1350
1351 unsigned LiveOutHeight = DefSU->getHeight();
1352 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1353 // Visit all local users of the vreg def.
Matthias Braunb0c437b2015-10-29 03:57:17 +00001354 for (const VReg2SUnit &V2SU
1355 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1356 SUnit *SU = V2SU.SU;
1357 if (SU == &ExitSU)
Andrew Trick483f4192013-08-29 18:04:49 +00001358 continue;
1359
1360 // Only consider uses of the phi.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001361 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
Andrew Trick483f4192013-08-29 18:04:49 +00001362 if (!LRQ.valueIn()->isPHIDef())
1363 continue;
1364
1365 // Assume that a path spanning two iterations is a cycle, which could
1366 // overestimate in strange cases. This allows cyclic latency to be
1367 // estimated as the minimum slack of the vreg's depth or height.
1368 unsigned CyclicLatency = 0;
Matthias Braunb0c437b2015-10-29 03:57:17 +00001369 if (LiveOutDepth > SU->getDepth())
1370 CyclicLatency = LiveOutDepth - SU->getDepth();
Andrew Trick483f4192013-08-29 18:04:49 +00001371
Matthias Braunb0c437b2015-10-29 03:57:17 +00001372 unsigned LiveInHeight = SU->getHeight() + DefSU->Latency;
Andrew Trick483f4192013-08-29 18:04:49 +00001373 if (LiveInHeight > LiveOutHeight) {
1374 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1375 CyclicLatency = LiveInHeight - LiveOutHeight;
Matthias Braunb550b762016-04-21 01:54:13 +00001376 } else
Andrew Trick483f4192013-08-29 18:04:49 +00001377 CyclicLatency = 0;
1378
1379 DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
Matthias Braunb0c437b2015-10-29 03:57:17 +00001380 << SU->NodeNum << ") = " << CyclicLatency << "c\n");
Andrew Trick483f4192013-08-29 18:04:49 +00001381 if (CyclicLatency > MaxCyclicLatency)
1382 MaxCyclicLatency = CyclicLatency;
1383 }
1384 }
1385 DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
1386 return MaxCyclicLatency;
1387}
1388
Krzysztof Parzyszek7ea9a522016-04-28 19:17:44 +00001389/// Release ExitSU predecessors and setup scheduler queues. Re-position
1390/// the Top RP tracker in case the region beginning has changed.
1391void ScheduleDAGMILive::initQueues(ArrayRef<SUnit*> TopRoots,
1392 ArrayRef<SUnit*> BotRoots) {
1393 ScheduleDAGMI::initQueues(TopRoots, BotRoots);
1394 if (ShouldTrackPressure) {
1395 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
1396 TopRPTracker.setPos(CurrentTop);
1397 }
1398}
1399
Andrew Trick7a8e1002012-09-11 00:39:15 +00001400/// Move an instruction and update register pressure.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001401void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001402 // Move the instruction to its new location in the instruction stream.
1403 MachineInstr *MI = SU->getInstr();
Andrew Trick02a80da2012-03-08 01:41:12 +00001404
Andrew Trick7a8e1002012-09-11 00:39:15 +00001405 if (IsTopNode) {
1406 assert(SU->isTopReady() && "node still has unscheduled dependencies");
1407 if (&*CurrentTop == MI)
1408 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
Andrew Trick8823dec2012-03-14 04:00:41 +00001409 else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001410 moveInstruction(MI, CurrentTop);
1411 TopRPTracker.setPos(MI);
Andrew Trick8823dec2012-03-14 04:00:41 +00001412 }
Andrew Trickc3ea0052012-04-24 18:04:37 +00001413
Andrew Trickb6e74712013-09-04 20:59:59 +00001414 if (ShouldTrackPressure) {
1415 // Update top scheduled pressure.
Matthias Braund4f64092016-01-20 00:23:32 +00001416 RegisterOperands RegOpers;
1417 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1418 if (ShouldTrackLaneMasks) {
1419 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001420 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund4f64092016-01-20 00:23:32 +00001421 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1422 } else {
1423 // Adjust for missing dead-def flags.
1424 RegOpers.detectDeadDefs(*MI, *LIS);
1425 }
1426
1427 TopRPTracker.advance(RegOpers);
Andrew Trickb6e74712013-09-04 20:59:59 +00001428 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
Matthias Braun9198c672015-11-06 20:59:02 +00001429 DEBUG(
1430 dbgs() << "Top Pressure:\n";
1431 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
1432 );
1433
Andrew Trickb248b4a2013-09-06 17:32:47 +00001434 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001435 }
Matthias Braunb550b762016-04-21 01:54:13 +00001436 } else {
Andrew Trick7a8e1002012-09-11 00:39:15 +00001437 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1438 MachineBasicBlock::iterator priorII =
1439 priorNonDebug(CurrentBottom, CurrentTop);
1440 if (&*priorII == MI)
1441 CurrentBottom = priorII;
1442 else {
1443 if (&*CurrentTop == MI) {
1444 CurrentTop = nextIfDebug(++CurrentTop, priorII);
1445 TopRPTracker.setPos(CurrentTop);
1446 }
1447 moveInstruction(MI, CurrentBottom);
1448 CurrentBottom = MI;
1449 }
Andrew Trickb6e74712013-09-04 20:59:59 +00001450 if (ShouldTrackPressure) {
Matthias Braund4f64092016-01-20 00:23:32 +00001451 RegisterOperands RegOpers;
1452 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1453 if (ShouldTrackLaneMasks) {
1454 // Adjust liveness and add missing dead+read-undef flags.
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001455 SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
Matthias Braund4f64092016-01-20 00:23:32 +00001456 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1457 } else {
1458 // Adjust for missing dead-def flags.
1459 RegOpers.detectDeadDefs(*MI, *LIS);
1460 }
1461
Yaxun Liuf902ef02017-12-14 16:12:04 +00001462 BotRPTracker.recedeSkipDebugValues();
Matthias Braun5d458612016-01-20 00:23:26 +00001463 SmallVector<RegisterMaskPair, 8> LiveUses;
Matthias Braund4f64092016-01-20 00:23:32 +00001464 BotRPTracker.recede(RegOpers, &LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001465 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
Matthias Braun9198c672015-11-06 20:59:02 +00001466 DEBUG(
1467 dbgs() << "Bottom Pressure:\n";
1468 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);
1469 );
1470
Andrew Trickb248b4a2013-09-06 17:32:47 +00001471 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
Andrew Trickb6e74712013-09-04 20:59:59 +00001472 updatePressureDiffs(LiveUses);
Andrew Trickb6e74712013-09-04 20:59:59 +00001473 }
Andrew Trick7a8e1002012-09-11 00:39:15 +00001474 }
1475}
1476
Andrew Trick263280242012-11-12 19:52:20 +00001477//===----------------------------------------------------------------------===//
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001478// BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores.
Andrew Trick263280242012-11-12 19:52:20 +00001479//===----------------------------------------------------------------------===//
1480
Andrew Tricka7714a02012-11-12 19:40:10 +00001481namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001482
Andrew Tricka7714a02012-11-12 19:40:10 +00001483/// \brief Post-process the DAG to create cluster edges between neighboring
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001484/// loads or between neighboring stores.
1485class BaseMemOpClusterMutation : public ScheduleDAGMutation {
1486 struct MemOpInfo {
Andrew Tricka7714a02012-11-12 19:40:10 +00001487 SUnit *SU;
1488 unsigned BaseReg;
Chad Rosierc27a18f2016-03-09 16:00:35 +00001489 int64_t Offset;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001490
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001491 MemOpInfo(SUnit *su, unsigned reg, int64_t ofs)
1492 : SU(su), BaseReg(reg), Offset(ofs) {}
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001493
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001494 bool operator<(const MemOpInfo&RHS) const {
Mandeep Singh Grange82678a2016-10-18 00:11:19 +00001495 return std::tie(BaseReg, Offset, SU->NodeNum) <
1496 std::tie(RHS.BaseReg, RHS.Offset, RHS.SU->NodeNum);
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001497 }
Andrew Tricka7714a02012-11-12 19:40:10 +00001498 };
Andrew Tricka7714a02012-11-12 19:40:10 +00001499
1500 const TargetInstrInfo *TII;
1501 const TargetRegisterInfo *TRI;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001502 bool IsLoad;
1503
Andrew Tricka7714a02012-11-12 19:40:10 +00001504public:
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001505 BaseMemOpClusterMutation(const TargetInstrInfo *tii,
1506 const TargetRegisterInfo *tri, bool IsLoad)
1507 : TII(tii), TRI(tri), IsLoad(IsLoad) {}
Andrew Tricka7714a02012-11-12 19:40:10 +00001508
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001509 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001510
Andrew Tricka7714a02012-11-12 19:40:10 +00001511protected:
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001512 void clusterNeighboringMemOps(ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG);
1513};
1514
1515class StoreClusterMutation : public BaseMemOpClusterMutation {
1516public:
1517 StoreClusterMutation(const TargetInstrInfo *tii,
1518 const TargetRegisterInfo *tri)
1519 : BaseMemOpClusterMutation(tii, tri, false) {}
1520};
1521
1522class LoadClusterMutation : public BaseMemOpClusterMutation {
1523public:
1524 LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri)
1525 : BaseMemOpClusterMutation(tii, tri, true) {}
Andrew Tricka7714a02012-11-12 19:40:10 +00001526};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001527
1528} // end anonymous namespace
Andrew Tricka7714a02012-11-12 19:40:10 +00001529
Tom Stellard68726a52016-08-19 19:59:18 +00001530namespace llvm {
1531
1532std::unique_ptr<ScheduleDAGMutation>
1533createLoadClusterDAGMutation(const TargetInstrInfo *TII,
1534 const TargetRegisterInfo *TRI) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001535 return EnableMemOpCluster ? llvm::make_unique<LoadClusterMutation>(TII, TRI)
Matthias Braun115efcd2016-11-28 20:11:54 +00001536 : nullptr;
Tom Stellard68726a52016-08-19 19:59:18 +00001537}
1538
1539std::unique_ptr<ScheduleDAGMutation>
1540createStoreClusterDAGMutation(const TargetInstrInfo *TII,
1541 const TargetRegisterInfo *TRI) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001542 return EnableMemOpCluster ? llvm::make_unique<StoreClusterMutation>(TII, TRI)
Matthias Braun115efcd2016-11-28 20:11:54 +00001543 : nullptr;
Tom Stellard68726a52016-08-19 19:59:18 +00001544}
1545
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001546} // end namespace llvm
Tom Stellard68726a52016-08-19 19:59:18 +00001547
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001548void BaseMemOpClusterMutation::clusterNeighboringMemOps(
1549 ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG) {
1550 SmallVector<MemOpInfo, 32> MemOpRecords;
Javed Absare3a0cc22017-06-21 09:10:10 +00001551 for (SUnit *SU : MemOps) {
Andrew Tricka7714a02012-11-12 19:40:10 +00001552 unsigned BaseReg;
Chad Rosierc27a18f2016-03-09 16:00:35 +00001553 int64_t Offset;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001554 if (TII->getMemOpBaseRegImmOfs(*SU->getInstr(), BaseReg, Offset, TRI))
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001555 MemOpRecords.push_back(MemOpInfo(SU, BaseReg, Offset));
Andrew Tricka7714a02012-11-12 19:40:10 +00001556 }
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001557 if (MemOpRecords.size() < 2)
Andrew Tricka7714a02012-11-12 19:40:10 +00001558 return;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001559
1560 std::sort(MemOpRecords.begin(), MemOpRecords.end());
Andrew Tricka7714a02012-11-12 19:40:10 +00001561 unsigned ClusterLength = 1;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001562 for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) {
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001563 SUnit *SUa = MemOpRecords[Idx].SU;
1564 SUnit *SUb = MemOpRecords[Idx+1].SU;
Stanislav Mekhanoshin7fe9a5d2017-09-13 22:20:47 +00001565 if (TII->shouldClusterMemOps(*SUa->getInstr(), MemOpRecords[Idx].BaseReg,
1566 *SUb->getInstr(), MemOpRecords[Idx+1].BaseReg,
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001567 ClusterLength) &&
1568 DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001569 DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU("
Andrew Tricka7714a02012-11-12 19:40:10 +00001570 << SUb->NodeNum << ")\n");
1571 // Copy successor edges from SUa to SUb. Interleaving computation
1572 // dependent on SUa can prevent load combining due to register reuse.
1573 // Predecessor edges do not need to be copied from SUb to SUa since nearby
1574 // loads should have effectively the same inputs.
Javed Absare3a0cc22017-06-21 09:10:10 +00001575 for (const SDep &Succ : SUa->Succs) {
1576 if (Succ.getSUnit() == SUb)
Andrew Tricka7714a02012-11-12 19:40:10 +00001577 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001578 DEBUG(dbgs() << " Copy Succ SU(" << Succ.getSUnit()->NodeNum << ")\n");
1579 DAG->addEdge(Succ.getSUnit(), SDep(SUb, SDep::Artificial));
Andrew Tricka7714a02012-11-12 19:40:10 +00001580 }
1581 ++ClusterLength;
Matthias Braunb550b762016-04-21 01:54:13 +00001582 } else
Andrew Tricka7714a02012-11-12 19:40:10 +00001583 ClusterLength = 1;
1584 }
1585}
1586
1587/// \brief Callback from DAG postProcessing to create cluster edges for loads.
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001588void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAGInstrs) {
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001589 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
1590
Andrew Tricka7714a02012-11-12 19:40:10 +00001591 // Map DAG NodeNum to store chain ID.
1592 DenseMap<unsigned, unsigned> StoreChainIDs;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001593 // Map each store chain to a set of dependent MemOps.
Andrew Tricka7714a02012-11-12 19:40:10 +00001594 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
Javed Absare3a0cc22017-06-21 09:10:10 +00001595 for (SUnit &SU : DAG->SUnits) {
1596 if ((IsLoad && !SU.getInstr()->mayLoad()) ||
1597 (!IsLoad && !SU.getInstr()->mayStore()))
Andrew Tricka7714a02012-11-12 19:40:10 +00001598 continue;
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001599
Andrew Tricka7714a02012-11-12 19:40:10 +00001600 unsigned ChainPredID = DAG->SUnits.size();
Javed Absare3a0cc22017-06-21 09:10:10 +00001601 for (const SDep &Pred : SU.Preds) {
1602 if (Pred.isCtrl()) {
1603 ChainPredID = Pred.getSUnit()->NodeNum;
Andrew Tricka7714a02012-11-12 19:40:10 +00001604 break;
1605 }
1606 }
1607 // Check if this chain-like pred has been seen
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001608 // before. ChainPredID==MaxNodeID at the top of the schedule.
Andrew Tricka7714a02012-11-12 19:40:10 +00001609 unsigned NumChains = StoreChainDependents.size();
1610 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1611 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1612 if (Result.second)
1613 StoreChainDependents.resize(NumChains + 1);
Javed Absare3a0cc22017-06-21 09:10:10 +00001614 StoreChainDependents[Result.first->second].push_back(&SU);
Andrew Tricka7714a02012-11-12 19:40:10 +00001615 }
Jun Bum Lim4c5bd582016-04-15 14:58:38 +00001616
Andrew Tricka7714a02012-11-12 19:40:10 +00001617 // Iterate over the store chains.
Javed Absare3a0cc22017-06-21 09:10:10 +00001618 for (auto &SCD : StoreChainDependents)
1619 clusterNeighboringMemOps(SCD, DAG);
Andrew Tricka7714a02012-11-12 19:40:10 +00001620}
1621
Andrew Trick02a80da2012-03-08 01:41:12 +00001622//===----------------------------------------------------------------------===//
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001623// CopyConstrain - DAG post-processing to encourage copy elimination.
1624//===----------------------------------------------------------------------===//
1625
1626namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001627
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001628/// \brief Post-process the DAG to create weak edges from all uses of a copy to
1629/// the one use that defines the copy's source vreg, most likely an induction
1630/// variable increment.
1631class CopyConstrain : public ScheduleDAGMutation {
1632 // Transient state.
1633 SlotIndex RegionBeginIdx;
Eugene Zelenko32a40562017-09-11 23:00:48 +00001634
Andrew Trick2e875172013-04-24 23:19:56 +00001635 // RegionEndIdx is the slot index of the last non-debug instruction in the
1636 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001637 SlotIndex RegionEndIdx;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001638
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001639public:
1640 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1641
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001642 void apply(ScheduleDAGInstrs *DAGInstrs) override;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001643
1644protected:
Andrew Trickd7f890e2013-12-28 21:56:47 +00001645 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001646};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001647
1648} // end anonymous namespace
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001649
Tom Stellard68726a52016-08-19 19:59:18 +00001650namespace llvm {
1651
1652std::unique_ptr<ScheduleDAGMutation>
1653createCopyConstrainDAGMutation(const TargetInstrInfo *TII,
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001654 const TargetRegisterInfo *TRI) {
1655 return llvm::make_unique<CopyConstrain>(TII, TRI);
Tom Stellard68726a52016-08-19 19:59:18 +00001656}
1657
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001658} // end namespace llvm
Tom Stellard68726a52016-08-19 19:59:18 +00001659
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001660/// constrainLocalCopy handles two possibilities:
1661/// 1) Local src:
1662/// I0: = dst
1663/// I1: src = ...
1664/// I2: = dst
1665/// I3: dst = src (copy)
1666/// (create pred->succ edges I0->I1, I2->I1)
1667///
1668/// 2) Local copy:
1669/// I0: dst = src (copy)
1670/// I1: = dst
1671/// I2: src = ...
1672/// I3: = dst
1673/// (create pred->succ edges I1->I2, I3->I2)
1674///
1675/// Although the MachineScheduler is currently constrained to single blocks,
1676/// this algorithm should handle extended blocks. An EBB is a set of
1677/// contiguously numbered blocks such that the previous block in the EBB is
1678/// always the single predecessor.
Andrew Trickd7f890e2013-12-28 21:56:47 +00001679void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001680 LiveIntervals *LIS = DAG->getLIS();
1681 MachineInstr *Copy = CopySU->getInstr();
1682
1683 // Check for pure vreg copies.
Matthias Braun7511abd2016-04-04 21:23:46 +00001684 const MachineOperand &SrcOp = Copy->getOperand(1);
1685 unsigned SrcReg = SrcOp.getReg();
1686 if (!TargetRegisterInfo::isVirtualRegister(SrcReg) || !SrcOp.readsReg())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001687 return;
1688
Matthias Braun7511abd2016-04-04 21:23:46 +00001689 const MachineOperand &DstOp = Copy->getOperand(0);
1690 unsigned DstReg = DstOp.getReg();
1691 if (!TargetRegisterInfo::isVirtualRegister(DstReg) || DstOp.isDead())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001692 return;
1693
1694 // Check if either the dest or source is local. If it's live across a back
1695 // edge, it's not local. Note that if both vregs are live across the back
1696 // edge, we cannot successfully contrain the copy without cyclic scheduling.
Michael Kuperstein54c61ed2015-01-19 07:30:47 +00001697 // If both the copy's source and dest are local live intervals, then we
1698 // should treat the dest as the global for the purpose of adding
1699 // constraints. This adds edges from source's other uses to the copy.
1700 unsigned LocalReg = SrcReg;
1701 unsigned GlobalReg = DstReg;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001702 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1703 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
Michael Kuperstein54c61ed2015-01-19 07:30:47 +00001704 LocalReg = DstReg;
1705 GlobalReg = SrcReg;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001706 LocalLI = &LIS->getInterval(LocalReg);
1707 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1708 return;
1709 }
1710 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1711
1712 // Find the global segment after the start of the local LI.
1713 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1714 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1715 // local live range. We could create edges from other global uses to the local
1716 // start, but the coalescer should have already eliminated these cases, so
1717 // don't bother dealing with it.
1718 if (GlobalSegment == GlobalLI->end())
1719 return;
1720
1721 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1722 // returned the next global segment. But if GlobalSegment overlaps with
1723 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1724 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1725 if (GlobalSegment->contains(LocalLI->beginIndex()))
1726 ++GlobalSegment;
1727
1728 if (GlobalSegment == GlobalLI->end())
1729 return;
1730
1731 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1732 if (GlobalSegment != GlobalLI->begin()) {
1733 // Two address defs have no hole.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001734 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001735 GlobalSegment->start)) {
1736 return;
1737 }
Andrew Trickd9761772013-07-30 19:59:08 +00001738 // If the prior global segment may be defined by the same two-address
1739 // instruction that also defines LocalLI, then can't make a hole here.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001740 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
Andrew Trickd9761772013-07-30 19:59:08 +00001741 LocalLI->beginIndex())) {
1742 return;
1743 }
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001744 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1745 // it would be a disconnected component in the live range.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001746 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001747 "Disconnected LRG within the scheduling region.");
1748 }
1749 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1750 if (!GlobalDef)
1751 return;
1752
1753 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1754 if (!GlobalSU)
1755 return;
1756
1757 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1758 // constraining the uses of the last local def to precede GlobalDef.
1759 SmallVector<SUnit*,8> LocalUses;
1760 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1761 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1762 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
Javed Absare3a0cc22017-06-21 09:10:10 +00001763 for (const SDep &Succ : LastLocalSU->Succs) {
1764 if (Succ.getKind() != SDep::Data || Succ.getReg() != LocalReg)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001765 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001766 if (Succ.getSUnit() == GlobalSU)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001767 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001768 if (!DAG->canAddEdge(GlobalSU, Succ.getSUnit()))
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001769 return;
Javed Absare3a0cc22017-06-21 09:10:10 +00001770 LocalUses.push_back(Succ.getSUnit());
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001771 }
1772 // Open the top of the GlobalLI hole by constraining any earlier global uses
1773 // to precede the start of LocalLI.
1774 SmallVector<SUnit*,8> GlobalUses;
1775 MachineInstr *FirstLocalDef =
1776 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1777 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
Javed Absare3a0cc22017-06-21 09:10:10 +00001778 for (const SDep &Pred : GlobalSU->Preds) {
1779 if (Pred.getKind() != SDep::Anti || Pred.getReg() != GlobalReg)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001780 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001781 if (Pred.getSUnit() == FirstLocalSU)
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001782 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00001783 if (!DAG->canAddEdge(FirstLocalSU, Pred.getSUnit()))
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001784 return;
Javed Absare3a0cc22017-06-21 09:10:10 +00001785 GlobalUses.push_back(Pred.getSUnit());
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001786 }
1787 DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1788 // Add the weak edges.
1789 for (SmallVectorImpl<SUnit*>::const_iterator
1790 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1791 DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1792 << GlobalSU->NodeNum << ")\n");
1793 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1794 }
1795 for (SmallVectorImpl<SUnit*>::const_iterator
1796 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1797 DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1798 << FirstLocalSU->NodeNum << ")\n");
1799 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1800 }
1801}
1802
1803/// \brief Callback from DAG postProcessing to create weak edges to encourage
1804/// copy elimination.
Krzysztof Parzyszek5c61d112016-03-05 15:45:23 +00001805void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) {
1806 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
Andrew Trickd7f890e2013-12-28 21:56:47 +00001807 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1808
Andrew Trick2e875172013-04-24 23:19:56 +00001809 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1810 if (FirstPos == DAG->end())
1811 return;
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001812 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos);
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001813 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001814 *priorNonDebug(DAG->end(), DAG->begin()));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001815
Javed Absare3a0cc22017-06-21 09:10:10 +00001816 for (SUnit &SU : DAG->SUnits) {
1817 if (!SU.getInstr()->isCopy())
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001818 continue;
1819
Javed Absare3a0cc22017-06-21 09:10:10 +00001820 constrainLocalCopy(&SU, static_cast<ScheduleDAGMILive*>(DAG));
Andrew Trick85a1d4c2013-04-24 15:54:43 +00001821 }
1822}
1823
1824//===----------------------------------------------------------------------===//
Andrew Trickfc127d12013-12-07 05:59:44 +00001825// MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1826// and possibly other custom schedulers.
Andrew Trickd14d7c22013-12-28 21:56:57 +00001827//===----------------------------------------------------------------------===//
Andrew Tricke1c034f2012-01-17 06:55:03 +00001828
Andrew Trick5a22df42013-12-05 17:56:02 +00001829static const unsigned InvalidCycle = ~0U;
1830
Andrew Trickfc127d12013-12-07 05:59:44 +00001831SchedBoundary::~SchedBoundary() { delete HazardRec; }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001832
Jonas Paulsson238c14b2017-10-25 08:23:33 +00001833/// Given a Count of resource usage and a Latency value, return true if a
1834/// SchedBoundary becomes resource limited.
1835static bool checkResourceLimit(unsigned LFactor, unsigned Count,
1836 unsigned Latency) {
1837 return (int)(Count - (Latency * LFactor)) > (int)LFactor;
1838}
1839
Andrew Trickfc127d12013-12-07 05:59:44 +00001840void SchedBoundary::reset() {
1841 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1842 // Destroying and reconstructing it is very expensive though. So keep
1843 // invalid, placeholder HazardRecs.
1844 if (HazardRec && HazardRec->isEnabled()) {
1845 delete HazardRec;
Craig Topperc0196b12014-04-14 00:51:57 +00001846 HazardRec = nullptr;
Andrew Trickfc127d12013-12-07 05:59:44 +00001847 }
1848 Available.clear();
1849 Pending.clear();
1850 CheckPending = false;
Andrew Trickfc127d12013-12-07 05:59:44 +00001851 CurrCycle = 0;
1852 CurrMOps = 0;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00001853 MinReadyCycle = std::numeric_limits<unsigned>::max();
Andrew Trickfc127d12013-12-07 05:59:44 +00001854 ExpectedLatency = 0;
1855 DependentLatency = 0;
1856 RetiredMOps = 0;
1857 MaxExecutedResCount = 0;
1858 ZoneCritResIdx = 0;
1859 IsResourceLimited = false;
1860 ReservedCycles.clear();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001861#ifndef NDEBUG
Andrew Trickd14d7c22013-12-28 21:56:57 +00001862 // Track the maximum number of stall cycles that could arise either from the
1863 // latency of a DAG edge or the number of cycles that a processor resource is
1864 // reserved (SchedBoundary::ReservedCycles).
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00001865 MaxObservedStall = 0;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001866#endif
Andrew Trickfc127d12013-12-07 05:59:44 +00001867 // Reserve a zero-count for invalid CritResIdx.
1868 ExecutedResCounts.resize(1);
1869 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1870}
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001871
Andrew Trickfc127d12013-12-07 05:59:44 +00001872void SchedRemainder::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001873init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1874 reset();
1875 if (!SchedModel->hasInstrSchedModel())
1876 return;
1877 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
Javed Absare3a0cc22017-06-21 09:10:10 +00001878 for (SUnit &SU : DAG->SUnits) {
1879 const MCSchedClassDesc *SC = DAG->getSchedClass(&SU);
1880 RemIssueCount += SchedModel->getNumMicroOps(SU.getInstr(), SC)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001881 * SchedModel->getMicroOpFactor();
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001882 for (TargetSchedModel::ProcResIter
1883 PI = SchedModel->getWriteProcResBegin(SC),
1884 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1885 unsigned PIdx = PI->ProcResourceIdx;
1886 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1887 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1888 }
1889 }
1890}
1891
Andrew Trickfc127d12013-12-07 05:59:44 +00001892void SchedBoundary::
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001893init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1894 reset();
1895 DAG = dag;
1896 SchedModel = smodel;
1897 Rem = rem;
Andrew Trick5a22df42013-12-05 17:56:02 +00001898 if (SchedModel->hasInstrSchedModel()) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001899 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
Andrew Trick5a22df42013-12-05 17:56:02 +00001900 ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1901 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001902}
1903
Andrew Trick880e5732013-12-05 17:55:58 +00001904/// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1905/// these "soft stalls" differently than the hard stall cycles based on CPU
1906/// resources and computed by checkHazard(). A fully in-order model
1907/// (MicroOpBufferSize==0) will not make use of this since instructions are not
1908/// available for scheduling until they are ready. However, a weaker in-order
1909/// model may use this for heuristics. For example, if a processor has in-order
1910/// behavior when reading certain resources, this may come into play.
Andrew Trickfc127d12013-12-07 05:59:44 +00001911unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
Andrew Trick880e5732013-12-05 17:55:58 +00001912 if (!SU->isUnbuffered)
1913 return 0;
1914
1915 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1916 if (ReadyCycle > CurrCycle)
1917 return ReadyCycle - CurrCycle;
1918 return 0;
1919}
1920
Andrew Trick5a22df42013-12-05 17:56:02 +00001921/// Compute the next cycle at which the given processor resource can be
1922/// scheduled.
Andrew Trickfc127d12013-12-07 05:59:44 +00001923unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00001924getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1925 unsigned NextUnreserved = ReservedCycles[PIdx];
1926 // If this resource has never been used, always return cycle zero.
1927 if (NextUnreserved == InvalidCycle)
1928 return 0;
1929 // For bottom-up scheduling add the cycles needed for the current operation.
1930 if (!isTop())
1931 NextUnreserved += Cycles;
1932 return NextUnreserved;
1933}
1934
Andrew Trick8c9e6722012-06-29 03:23:24 +00001935/// Does this SU have a hazard within the current instruction group.
1936///
1937/// The scheduler supports two modes of hazard recognition. The first is the
1938/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1939/// supports highly complicated in-order reservation tables
1940/// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1941///
1942/// The second is a streamlined mechanism that checks for hazards based on
1943/// simple counters that the scheduler itself maintains. It explicitly checks
1944/// for instruction dispatch limitations, including the number of micro-ops that
1945/// can dispatch per cycle.
1946///
1947/// TODO: Also check whether the SU must start a new group.
Andrew Trickfc127d12013-12-07 05:59:44 +00001948bool SchedBoundary::checkHazard(SUnit *SU) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00001949 if (HazardRec->isEnabled()
1950 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
1951 return true;
1952 }
Javed Absar3d594372017-03-27 20:46:37 +00001953
Andrew Trickdd79f0f2012-10-10 05:43:09 +00001954 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
Andrew Tricke2ff5752013-06-15 04:49:49 +00001955 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001956 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1957 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
Andrew Trick8c9e6722012-06-29 03:23:24 +00001958 return true;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00001959 }
Javed Absar3d594372017-03-27 20:46:37 +00001960
1961 if (CurrMOps > 0 &&
1962 ((isTop() && SchedModel->mustBeginGroup(SU->getInstr())) ||
1963 (!isTop() && SchedModel->mustEndGroup(SU->getInstr())))) {
1964 DEBUG(dbgs() << " hazard: SU(" << SU->NodeNum << ") must "
1965 << (isTop()? "begin" : "end") << " group\n");
1966 return true;
1967 }
1968
Andrew Trick5a22df42013-12-05 17:56:02 +00001969 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1970 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
Javed Absare485b142017-10-03 09:35:04 +00001971 for (const MCWriteProcResEntry &PE :
1972 make_range(SchedModel->getWriteProcResBegin(SC),
1973 SchedModel->getWriteProcResEnd(SC))) {
1974 unsigned ResIdx = PE.ProcResourceIdx;
1975 unsigned Cycles = PE.Cycles;
1976 unsigned NRCycle = getNextResourceCycle(ResIdx, Cycles);
Andrew Trick56327222014-06-27 04:57:05 +00001977 if (NRCycle > CurrCycle) {
Andrew Trick040c0da2014-06-27 05:09:36 +00001978#ifndef NDEBUG
Javed Absare485b142017-10-03 09:35:04 +00001979 MaxObservedStall = std::max(Cycles, MaxObservedStall);
Andrew Trick040c0da2014-06-27 05:09:36 +00001980#endif
Andrew Trick56327222014-06-27 04:57:05 +00001981 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") "
Javed Absare485b142017-10-03 09:35:04 +00001982 << SchedModel->getResourceName(ResIdx)
Andrew Trick56327222014-06-27 04:57:05 +00001983 << "=" << NRCycle << "c\n");
Andrew Trick5a22df42013-12-05 17:56:02 +00001984 return true;
Andrew Trick56327222014-06-27 04:57:05 +00001985 }
Andrew Trick5a22df42013-12-05 17:56:02 +00001986 }
1987 }
Andrew Trick8c9e6722012-06-29 03:23:24 +00001988 return false;
1989}
1990
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001991// Find the unscheduled node in ReadySUs with the highest latency.
Andrew Trickfc127d12013-12-07 05:59:44 +00001992unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001993findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
Craig Topperc0196b12014-04-14 00:51:57 +00001994 SUnit *LateSU = nullptr;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00001995 unsigned RemLatency = 0;
Javed Absare3a0cc22017-06-21 09:10:10 +00001996 for (SUnit *SU : ReadySUs) {
1997 unsigned L = getUnscheduledLatency(SU);
Andrew Trickf5b8ef22013-06-15 04:49:44 +00001998 if (L > RemLatency) {
Andrew Trickd6d5ad32012-12-18 20:52:56 +00001999 RemLatency = L;
Javed Absare3a0cc22017-06-21 09:10:10 +00002000 LateSU = SU;
Andrew Trickf5b8ef22013-06-15 04:49:44 +00002001 }
Andrew Trickd6d5ad32012-12-18 20:52:56 +00002002 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002003 if (LateSU) {
2004 DEBUG(dbgs() << Available.getName() << " RemLatency SU("
2005 << LateSU->NodeNum << ") " << RemLatency << "c\n");
Andrew Trickd6d5ad32012-12-18 20:52:56 +00002006 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002007 return RemLatency;
2008}
Andrew Trickf5b8ef22013-06-15 04:49:44 +00002009
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002010// Count resources in this zone and the remaining unscheduled
2011// instruction. Return the max count, scaled. Set OtherCritIdx to the critical
2012// resource index, or zero if the zone is issue limited.
Andrew Trickfc127d12013-12-07 05:59:44 +00002013unsigned SchedBoundary::
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002014getOtherResourceCount(unsigned &OtherCritIdx) {
Alexey Samsonov64c391d2013-07-19 08:55:18 +00002015 OtherCritIdx = 0;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002016 if (!SchedModel->hasInstrSchedModel())
2017 return 0;
2018
2019 unsigned OtherCritCount = Rem->RemIssueCount
2020 + (RetiredMOps * SchedModel->getMicroOpFactor());
2021 DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
2022 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002023 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
2024 PIdx != PEnd; ++PIdx) {
2025 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
2026 if (OtherCount > OtherCritCount) {
2027 OtherCritCount = OtherCount;
2028 OtherCritIdx = PIdx;
2029 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002030 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002031 if (OtherCritIdx) {
2032 DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
2033 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
Andrew Trickfc127d12013-12-07 05:59:44 +00002034 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002035 }
2036 return OtherCritCount;
2037}
2038
Andrew Trickfc127d12013-12-07 05:59:44 +00002039void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00002040 assert(SU->getInstr() && "Scheduled SUnit must have instr");
2041
2042#ifndef NDEBUG
Andrew Trick491e34a2014-06-12 22:36:28 +00002043 // ReadyCycle was been bumped up to the CurrCycle when this node was
2044 // scheduled, but CurrCycle may have been eagerly advanced immediately after
2045 // scheduling, so may now be greater than ReadyCycle.
2046 if (ReadyCycle > CurrCycle)
2047 MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
Andrew Trick7f1ebbe2014-06-07 01:48:43 +00002048#endif
2049
Andrew Trick61f1a272012-05-24 22:11:09 +00002050 if (ReadyCycle < MinReadyCycle)
2051 MinReadyCycle = ReadyCycle;
2052
2053 // Check for interlocks first. For the purpose of other heuristics, an
2054 // instruction that cannot issue appears as if it's not in the ReadyQueue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002055 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Matthias Braun6493bc22016-04-22 19:09:17 +00002056 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU) ||
2057 Available.size() >= ReadyListLimit)
Andrew Trick61f1a272012-05-24 22:11:09 +00002058 Pending.push(SU);
2059 else
2060 Available.push(SU);
2061}
2062
2063/// Move the boundary of scheduled code by one cycle.
Andrew Trickfc127d12013-12-07 05:59:44 +00002064void SchedBoundary::bumpCycle(unsigned NextCycle) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002065 if (SchedModel->getMicroOpBufferSize() == 0) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00002066 assert(MinReadyCycle < std::numeric_limits<unsigned>::max() &&
2067 "MinReadyCycle uninitialized");
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002068 if (MinReadyCycle > NextCycle)
2069 NextCycle = MinReadyCycle;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002070 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002071 // Update the current micro-ops, which will issue in the next cycle.
2072 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
2073 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
2074
2075 // Decrement DependentLatency based on the next cycle.
Andrew Trickf5b8ef22013-06-15 04:49:44 +00002076 if ((NextCycle - CurrCycle) > DependentLatency)
2077 DependentLatency = 0;
2078 else
2079 DependentLatency -= (NextCycle - CurrCycle);
Andrew Trick61f1a272012-05-24 22:11:09 +00002080
2081 if (!HazardRec->isEnabled()) {
Andrew Trick45446062012-06-05 21:11:27 +00002082 // Bypass HazardRec virtual calls.
Andrew Trick61f1a272012-05-24 22:11:09 +00002083 CurrCycle = NextCycle;
Matthias Braunb550b762016-04-21 01:54:13 +00002084 } else {
Andrew Trick45446062012-06-05 21:11:27 +00002085 // Bypass getHazardType calls in case of long latency.
Andrew Trick61f1a272012-05-24 22:11:09 +00002086 for (; CurrCycle != NextCycle; ++CurrCycle) {
2087 if (isTop())
2088 HazardRec->AdvanceCycle();
2089 else
2090 HazardRec->RecedeCycle();
2091 }
2092 }
2093 CheckPending = true;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002094 IsResourceLimited =
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002095 checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
2096 getScheduledLatency());
Andrew Trick61f1a272012-05-24 22:11:09 +00002097
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002098 DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
2099}
2100
Andrew Trickfc127d12013-12-07 05:59:44 +00002101void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002102 ExecutedResCounts[PIdx] += Count;
2103 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
2104 MaxExecutedResCount = ExecutedResCounts[PIdx];
Andrew Trick61f1a272012-05-24 22:11:09 +00002105}
2106
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002107/// Add the given processor resource to this scheduled zone.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002108///
2109/// \param Cycles indicates the number of consecutive (non-pipelined) cycles
2110/// during which this resource is consumed.
2111///
2112/// \return the next cycle at which the instruction may execute without
2113/// oversubscribing resources.
Andrew Trickfc127d12013-12-07 05:59:44 +00002114unsigned SchedBoundary::
Andrew Trick5a22df42013-12-05 17:56:02 +00002115countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002116 unsigned Factor = SchedModel->getResourceFactor(PIdx);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002117 unsigned Count = Factor * Cycles;
Andrew Trickfc127d12013-12-07 05:59:44 +00002118 DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002119 << " +" << Cycles << "x" << Factor << "u\n");
2120
2121 // Update Executed resources counts.
2122 incExecutedResources(PIdx, Count);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002123 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
2124 Rem->RemainingCounts[PIdx] -= Count;
2125
Andrew Trickb13ef172013-07-19 00:20:07 +00002126 // Check if this resource exceeds the current critical resource. If so, it
2127 // becomes the critical resource.
2128 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002129 ZoneCritResIdx = PIdx;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002130 DEBUG(dbgs() << " *** Critical resource "
Andrew Trickfc127d12013-12-07 05:59:44 +00002131 << SchedModel->getResourceName(PIdx) << ": "
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002132 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002133 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002134 // For reserved resources, record the highest cycle using the resource.
2135 unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
2136 if (NextAvailable > CurrCycle) {
2137 DEBUG(dbgs() << " Resource conflict: "
2138 << SchedModel->getProcResource(PIdx)->Name << " reserved until @"
2139 << NextAvailable << "\n");
2140 }
2141 return NextAvailable;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002142}
2143
Andrew Trick45446062012-06-05 21:11:27 +00002144/// Move the boundary of scheduled code by one SUnit.
Andrew Trickfc127d12013-12-07 05:59:44 +00002145void SchedBoundary::bumpNode(SUnit *SU) {
Andrew Trick45446062012-06-05 21:11:27 +00002146 // Update the reservation table.
2147 if (HazardRec->isEnabled()) {
2148 if (!isTop() && SU->isCall) {
2149 // Calls are scheduled with their preceding instructions. For bottom-up
2150 // scheduling, clear the pipeline state before emitting.
2151 HazardRec->Reset();
2152 }
2153 HazardRec->EmitInstruction(SU);
2154 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002155 // checkHazard should prevent scheduling multiple instructions per cycle that
2156 // exceed the issue width.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002157 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2158 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
Daniel Jasper0d92abd2013-12-06 08:58:22 +00002159 assert(
2160 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
Andrew Trickf7760a22013-12-06 17:19:20 +00002161 "Cannot schedule this instruction's MicroOps in the current cycle.");
Andrew Trick5a22df42013-12-05 17:56:02 +00002162
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002163 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
2164 DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
2165
Andrew Trick5a22df42013-12-05 17:56:02 +00002166 unsigned NextCycle = CurrCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002167 switch (SchedModel->getMicroOpBufferSize()) {
2168 case 0:
2169 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
2170 break;
2171 case 1:
2172 if (ReadyCycle > NextCycle) {
2173 NextCycle = ReadyCycle;
2174 DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
2175 }
2176 break;
2177 default:
2178 // We don't currently model the OOO reorder buffer, so consider all
Andrew Trick880e5732013-12-05 17:55:58 +00002179 // scheduled MOps to be "retired". We do loosely model in-order resource
2180 // latency. If this instruction uses an in-order resource, account for any
2181 // likely stall cycles.
2182 if (SU->isUnbuffered && ReadyCycle > NextCycle)
2183 NextCycle = ReadyCycle;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002184 break;
2185 }
2186 RetiredMOps += IncMOps;
2187
2188 // Update resource counts and critical resource.
2189 if (SchedModel->hasInstrSchedModel()) {
2190 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
2191 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
2192 Rem->RemIssueCount -= DecRemIssue;
2193 if (ZoneCritResIdx) {
2194 // Scale scheduled micro-ops for comparing with the critical resource.
2195 unsigned ScaledMOps =
2196 RetiredMOps * SchedModel->getMicroOpFactor();
2197
2198 // If scaled micro-ops are now more than the previous critical resource by
2199 // a full cycle, then micro-ops issue becomes critical.
2200 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
2201 >= (int)SchedModel->getLatencyFactor()) {
2202 ZoneCritResIdx = 0;
2203 DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
2204 << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
2205 }
2206 }
2207 for (TargetSchedModel::ProcResIter
2208 PI = SchedModel->getWriteProcResBegin(SC),
2209 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2210 unsigned RCycle =
Andrew Trick5a22df42013-12-05 17:56:02 +00002211 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002212 if (RCycle > NextCycle)
2213 NextCycle = RCycle;
2214 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002215 if (SU->hasReservedResource) {
2216 // For reserved resources, record the highest cycle using the resource.
2217 // For top-down scheduling, this is the cycle in which we schedule this
2218 // instruction plus the number of cycles the operations reserves the
2219 // resource. For bottom-up is it simply the instruction's cycle.
2220 for (TargetSchedModel::ProcResIter
2221 PI = SchedModel->getWriteProcResBegin(SC),
2222 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2223 unsigned PIdx = PI->ProcResourceIdx;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002224 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
Chad Rosieraba845e2014-07-02 16:46:08 +00002225 if (isTop()) {
2226 ReservedCycles[PIdx] =
2227 std::max(getNextResourceCycle(PIdx, 0), NextCycle + PI->Cycles);
2228 }
2229 else
2230 ReservedCycles[PIdx] = NextCycle;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002231 }
Andrew Trick5a22df42013-12-05 17:56:02 +00002232 }
2233 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002234 }
2235 // Update ExpectedLatency and DependentLatency.
2236 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
2237 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
2238 if (SU->getDepth() > TopLatency) {
2239 TopLatency = SU->getDepth();
2240 DEBUG(dbgs() << " " << Available.getName()
2241 << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
2242 }
2243 if (SU->getHeight() > BotLatency) {
2244 BotLatency = SU->getHeight();
2245 DEBUG(dbgs() << " " << Available.getName()
2246 << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
2247 }
2248 // If we stall for any reason, bump the cycle.
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002249 if (NextCycle > CurrCycle)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002250 bumpCycle(NextCycle);
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002251 else
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002252 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
Alp Tokercb402912014-01-24 17:20:08 +00002253 // resource limited. If a stall occurred, bumpCycle does this.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002254 IsResourceLimited =
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002255 checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
2256 getScheduledLatency());
2257
Andrew Trick5a22df42013-12-05 17:56:02 +00002258 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
2259 // resets CurrMOps. Loop to handle instructions with more MOps than issue in
2260 // one cycle. Since we commonly reach the max MOps here, opportunistically
2261 // bump the cycle to avoid uselessly checking everything in the readyQ.
2262 CurrMOps += IncMOps;
Javed Absar3d594372017-03-27 20:46:37 +00002263
2264 // Bump the cycle count for issue group constraints.
2265 // This must be done after NextCycle has been adjust for all other stalls.
2266 // Calling bumpCycle(X) will reduce CurrMOps by one issue group and set
2267 // currCycle to X.
2268 if ((isTop() && SchedModel->mustEndGroup(SU->getInstr())) ||
2269 (!isTop() && SchedModel->mustBeginGroup(SU->getInstr()))) {
2270 DEBUG(dbgs() << " Bump cycle to "
2271 << (isTop() ? "end" : "begin") << " group\n");
2272 bumpCycle(++NextCycle);
2273 }
2274
Andrew Trick5a22df42013-12-05 17:56:02 +00002275 while (CurrMOps >= SchedModel->getIssueWidth()) {
Andrew Trick5a22df42013-12-05 17:56:02 +00002276 DEBUG(dbgs() << " *** Max MOps " << CurrMOps
2277 << " at cycle " << CurrCycle << '\n');
Andrew Trickd14d7c22013-12-28 21:56:57 +00002278 bumpCycle(++NextCycle);
Andrew Trick5a22df42013-12-05 17:56:02 +00002279 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002280 DEBUG(dumpScheduledState());
Andrew Trick45446062012-06-05 21:11:27 +00002281}
2282
Andrew Trick61f1a272012-05-24 22:11:09 +00002283/// Release pending ready nodes in to the available queue. This makes them
2284/// visible to heuristics.
Andrew Trickfc127d12013-12-07 05:59:44 +00002285void SchedBoundary::releasePending() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002286 // If the available queue is empty, it is safe to reset MinReadyCycle.
2287 if (Available.empty())
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00002288 MinReadyCycle = std::numeric_limits<unsigned>::max();
Andrew Trick61f1a272012-05-24 22:11:09 +00002289
2290 // Check to see if any of the pending instructions are ready to issue. If
2291 // so, add them to the available queue.
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002292 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
Andrew Trick61f1a272012-05-24 22:11:09 +00002293 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2294 SUnit *SU = *(Pending.begin()+i);
Andrew Trick45446062012-06-05 21:11:27 +00002295 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
Andrew Trick61f1a272012-05-24 22:11:09 +00002296
2297 if (ReadyCycle < MinReadyCycle)
2298 MinReadyCycle = ReadyCycle;
2299
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002300 if (!IsBuffered && ReadyCycle > CurrCycle)
Andrew Trick61f1a272012-05-24 22:11:09 +00002301 continue;
2302
Andrew Trick8c9e6722012-06-29 03:23:24 +00002303 if (checkHazard(SU))
Andrew Trick61f1a272012-05-24 22:11:09 +00002304 continue;
2305
Matthias Braun6493bc22016-04-22 19:09:17 +00002306 if (Available.size() >= ReadyListLimit)
2307 break;
2308
Andrew Trick61f1a272012-05-24 22:11:09 +00002309 Available.push(SU);
2310 Pending.remove(Pending.begin()+i);
2311 --i; --e;
2312 }
2313 CheckPending = false;
2314}
2315
2316/// Remove SU from the ready set for this boundary.
Andrew Trickfc127d12013-12-07 05:59:44 +00002317void SchedBoundary::removeReady(SUnit *SU) {
Andrew Trick61f1a272012-05-24 22:11:09 +00002318 if (Available.isInQueue(SU))
2319 Available.remove(Available.find(SU));
2320 else {
2321 assert(Pending.isInQueue(SU) && "bad ready count");
2322 Pending.remove(Pending.find(SU));
2323 }
2324}
2325
2326/// If this queue only has one ready candidate, return it. As a side effect,
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002327/// defer any nodes that now hit a hazard, and advance the cycle until at least
2328/// one node is ready. If multiple instructions are ready, return NULL.
Andrew Trickfc127d12013-12-07 05:59:44 +00002329SUnit *SchedBoundary::pickOnlyChoice() {
Andrew Trick61f1a272012-05-24 22:11:09 +00002330 if (CheckPending)
2331 releasePending();
2332
Andrew Tricke2ff5752013-06-15 04:49:49 +00002333 if (CurrMOps > 0) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002334 // Defer any ready instrs that now have a hazard.
2335 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2336 if (checkHazard(*I)) {
2337 Pending.push(*I);
2338 I = Available.remove(I);
2339 continue;
2340 }
2341 ++I;
2342 }
2343 }
Andrew Trick61f1a272012-05-24 22:11:09 +00002344 for (unsigned i = 0; Available.empty(); ++i) {
Chad Rosieraba845e2014-07-02 16:46:08 +00002345// FIXME: Re-enable assert once PR20057 is resolved.
2346// assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
2347// "permanent hazard");
2348 (void)i;
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002349 bumpCycle(CurrCycle + 1);
Andrew Trick61f1a272012-05-24 22:11:09 +00002350 releasePending();
2351 }
Matthias Braund29d31e2016-06-23 21:27:38 +00002352
2353 DEBUG(Pending.dump());
2354 DEBUG(Available.dump());
2355
Andrew Trick61f1a272012-05-24 22:11:09 +00002356 if (Available.size() == 1)
2357 return *Available.begin();
Craig Topperc0196b12014-04-14 00:51:57 +00002358 return nullptr;
Andrew Trick61f1a272012-05-24 22:11:09 +00002359}
2360
Aaron Ballman615eb472017-10-15 14:32:27 +00002361#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002362// This is useful information to dump after bumpNode.
2363// Note that the Queue contents are more useful before pickNodeFromQueue.
Sam Clegg705f7982017-06-21 22:19:17 +00002364LLVM_DUMP_METHOD void SchedBoundary::dumpScheduledState() const {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002365 unsigned ResFactor;
2366 unsigned ResCount;
2367 if (ZoneCritResIdx) {
2368 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2369 ResCount = getResourceCount(ZoneCritResIdx);
Matthias Braunb550b762016-04-21 01:54:13 +00002370 } else {
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002371 ResFactor = SchedModel->getMicroOpFactor();
Javed Absar1a77bcc2017-09-27 10:31:58 +00002372 ResCount = RetiredMOps * ResFactor;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002373 }
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002374 unsigned LFactor = SchedModel->getLatencyFactor();
2375 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2376 << " Retired: " << RetiredMOps;
2377 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2378 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
Andrew Trickfc127d12013-12-07 05:59:44 +00002379 << ResCount / ResFactor << " "
2380 << SchedModel->getResourceName(ZoneCritResIdx)
Andrew Trickf78e7fa2013-06-15 05:39:19 +00002381 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2382 << (IsResourceLimited ? " - Resource" : " - Latency")
2383 << " limited.\n";
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002384}
Andrew Trick8e8415f2013-06-15 05:46:47 +00002385#endif
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002386
Andrew Trickfc127d12013-12-07 05:59:44 +00002387//===----------------------------------------------------------------------===//
Andrew Trickd14d7c22013-12-28 21:56:57 +00002388// GenericScheduler - Generic implementation of MachineSchedStrategy.
Andrew Trickfc127d12013-12-07 05:59:44 +00002389//===----------------------------------------------------------------------===//
2390
Andrew Trickd14d7c22013-12-28 21:56:57 +00002391void GenericSchedulerBase::SchedCandidate::
2392initResourceDelta(const ScheduleDAGMI *DAG,
2393 const TargetSchedModel *SchedModel) {
2394 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2395 return;
2396
2397 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2398 for (TargetSchedModel::ProcResIter
2399 PI = SchedModel->getWriteProcResBegin(SC),
2400 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2401 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2402 ResDelta.CritResources += PI->Cycles;
2403 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2404 ResDelta.DemandedResources += PI->Cycles;
2405 }
2406}
2407
2408/// Set the CandPolicy given a scheduling zone given the current resources and
2409/// latencies inside and outside the zone.
Matthias Braunb550b762016-04-21 01:54:13 +00002410void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA,
Andrew Trickd14d7c22013-12-28 21:56:57 +00002411 SchedBoundary &CurrZone,
2412 SchedBoundary *OtherZone) {
Eric Christopher572e03a2015-06-19 01:53:21 +00002413 // Apply preemptive heuristics based on the total latency and resources
Andrew Trickd14d7c22013-12-28 21:56:57 +00002414 // inside and outside this zone. Potential stalls should be considered before
2415 // following this policy.
2416
2417 // Compute remaining latency. We need this both to determine whether the
2418 // overall schedule has become latency-limited and whether the instructions
2419 // outside this zone are resource or latency limited.
2420 //
2421 // The "dependent" latency is updated incrementally during scheduling as the
2422 // max height/depth of scheduled nodes minus the cycles since it was
2423 // scheduled:
2424 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2425 //
2426 // The "independent" latency is the max ready queue depth:
2427 // ILat = max N.depth for N in Available|Pending
2428 //
2429 // RemainingLatency is the greater of independent and dependent latency.
2430 unsigned RemLatency = CurrZone.getDependentLatency();
2431 RemLatency = std::max(RemLatency,
2432 CurrZone.findMaxLatency(CurrZone.Available.elements()));
2433 RemLatency = std::max(RemLatency,
2434 CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2435
2436 // Compute the critical resource outside the zone.
Andrew Trick7afe4812013-12-28 22:25:57 +00002437 unsigned OtherCritIdx = 0;
Andrew Trickd14d7c22013-12-28 21:56:57 +00002438 unsigned OtherCount =
2439 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
2440
2441 bool OtherResLimited = false;
Jonas Paulsson238c14b2017-10-25 08:23:33 +00002442 if (SchedModel->hasInstrSchedModel())
2443 OtherResLimited = checkResourceLimit(SchedModel->getLatencyFactor(),
2444 OtherCount, RemLatency);
2445
Andrew Trickd14d7c22013-12-28 21:56:57 +00002446 // Schedule aggressively for latency in PostRA mode. We don't check for
2447 // acyclic latency during PostRA, and highly out-of-order processors will
2448 // skip PostRA scheduling.
2449 if (!OtherResLimited) {
2450 if (IsPostRA || (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) {
2451 Policy.ReduceLatency |= true;
2452 DEBUG(dbgs() << " " << CurrZone.Available.getName()
2453 << " RemainingLatency " << RemLatency << " + "
2454 << CurrZone.getCurrCycle() << "c > CritPath "
2455 << Rem.CriticalPath << "\n");
2456 }
2457 }
2458 // If the same resource is limiting inside and outside the zone, do nothing.
2459 if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2460 return;
2461
2462 DEBUG(
2463 if (CurrZone.isResourceLimited()) {
2464 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
2465 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx())
2466 << "\n";
2467 }
2468 if (OtherResLimited)
2469 dbgs() << " RemainingLimit: "
2470 << SchedModel->getResourceName(OtherCritIdx) << "\n";
2471 if (!CurrZone.isResourceLimited() && !OtherResLimited)
2472 dbgs() << " Latency limited both directions.\n");
2473
2474 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2475 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2476
2477 if (OtherResLimited)
2478 Policy.DemandResIdx = OtherCritIdx;
2479}
2480
2481#ifndef NDEBUG
2482const char *GenericSchedulerBase::getReasonStr(
2483 GenericSchedulerBase::CandReason Reason) {
2484 switch (Reason) {
2485 case NoCand: return "NOCAND ";
Matthias Braun49cb6e92016-05-27 22:14:26 +00002486 case Only1: return "ONLY1 ";
2487 case PhysRegCopy: return "PREG-COPY ";
Andrew Trickd14d7c22013-12-28 21:56:57 +00002488 case RegExcess: return "REG-EXCESS";
2489 case RegCritical: return "REG-CRIT ";
2490 case Stall: return "STALL ";
2491 case Cluster: return "CLUSTER ";
2492 case Weak: return "WEAK ";
2493 case RegMax: return "REG-MAX ";
2494 case ResourceReduce: return "RES-REDUCE";
2495 case ResourceDemand: return "RES-DEMAND";
2496 case TopDepthReduce: return "TOP-DEPTH ";
2497 case TopPathReduce: return "TOP-PATH ";
2498 case BotHeightReduce:return "BOT-HEIGHT";
2499 case BotPathReduce: return "BOT-PATH ";
2500 case NextDefUse: return "DEF-USE ";
2501 case NodeOrder: return "ORDER ";
2502 };
2503 llvm_unreachable("Unknown reason!");
2504}
2505
2506void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
2507 PressureChange P;
2508 unsigned ResIdx = 0;
2509 unsigned Latency = 0;
2510 switch (Cand.Reason) {
2511 default:
2512 break;
2513 case RegExcess:
2514 P = Cand.RPDelta.Excess;
2515 break;
2516 case RegCritical:
2517 P = Cand.RPDelta.CriticalMax;
2518 break;
2519 case RegMax:
2520 P = Cand.RPDelta.CurrentMax;
2521 break;
2522 case ResourceReduce:
2523 ResIdx = Cand.Policy.ReduceResIdx;
2524 break;
2525 case ResourceDemand:
2526 ResIdx = Cand.Policy.DemandResIdx;
2527 break;
2528 case TopDepthReduce:
2529 Latency = Cand.SU->getDepth();
2530 break;
2531 case TopPathReduce:
2532 Latency = Cand.SU->getHeight();
2533 break;
2534 case BotHeightReduce:
2535 Latency = Cand.SU->getHeight();
2536 break;
2537 case BotPathReduce:
2538 Latency = Cand.SU->getDepth();
2539 break;
2540 }
James Y Knighte72b0db2015-09-18 18:52:20 +00002541 dbgs() << " Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002542 if (P.isValid())
2543 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2544 << ":" << P.getUnitInc() << " ";
2545 else
2546 dbgs() << " ";
2547 if (ResIdx)
2548 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2549 else
2550 dbgs() << " ";
2551 if (Latency)
2552 dbgs() << " " << Latency << " cycles ";
2553 else
2554 dbgs() << " ";
2555 dbgs() << '\n';
2556}
2557#endif
2558
2559/// Return true if this heuristic determines order.
2560static bool tryLess(int TryVal, int CandVal,
2561 GenericSchedulerBase::SchedCandidate &TryCand,
2562 GenericSchedulerBase::SchedCandidate &Cand,
2563 GenericSchedulerBase::CandReason Reason) {
2564 if (TryVal < CandVal) {
2565 TryCand.Reason = Reason;
2566 return true;
2567 }
2568 if (TryVal > CandVal) {
2569 if (Cand.Reason > Reason)
2570 Cand.Reason = Reason;
2571 return true;
2572 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00002573 return false;
2574}
2575
2576static bool tryGreater(int TryVal, int CandVal,
2577 GenericSchedulerBase::SchedCandidate &TryCand,
2578 GenericSchedulerBase::SchedCandidate &Cand,
2579 GenericSchedulerBase::CandReason Reason) {
2580 if (TryVal > CandVal) {
2581 TryCand.Reason = Reason;
2582 return true;
2583 }
2584 if (TryVal < CandVal) {
2585 if (Cand.Reason > Reason)
2586 Cand.Reason = Reason;
2587 return true;
2588 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00002589 return false;
2590}
2591
2592static bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
2593 GenericSchedulerBase::SchedCandidate &Cand,
2594 SchedBoundary &Zone) {
2595 if (Zone.isTop()) {
2596 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2597 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2598 TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
2599 return true;
2600 }
2601 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2602 TryCand, Cand, GenericSchedulerBase::TopPathReduce))
2603 return true;
Matthias Braunb550b762016-04-21 01:54:13 +00002604 } else {
Andrew Trickd14d7c22013-12-28 21:56:57 +00002605 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2606 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2607 TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
2608 return true;
2609 }
2610 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2611 TryCand, Cand, GenericSchedulerBase::BotPathReduce))
2612 return true;
2613 }
2614 return false;
2615}
2616
Matthias Braun49cb6e92016-05-27 22:14:26 +00002617static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop) {
2618 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2619 << GenericSchedulerBase::getReasonStr(Reason) << '\n');
2620}
2621
Matthias Braun6ad3d052016-06-25 00:23:00 +00002622static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand) {
2623 tracePick(Cand.Reason, Cand.AtTop);
Andrew Trickd14d7c22013-12-28 21:56:57 +00002624}
2625
Andrew Trickfc127d12013-12-07 05:59:44 +00002626void GenericScheduler::initialize(ScheduleDAGMI *dag) {
Andrew Trickd7f890e2013-12-28 21:56:47 +00002627 assert(dag->hasVRegLiveness() &&
2628 "(PreRA)GenericScheduler needs vreg liveness");
2629 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Trickfc127d12013-12-07 05:59:44 +00002630 SchedModel = DAG->getSchedModel();
2631 TRI = DAG->TRI;
2632
2633 Rem.init(DAG, SchedModel);
2634 Top.init(DAG, SchedModel, &Rem);
2635 Bot.init(DAG, SchedModel, &Rem);
2636
2637 // Initialize resource counts.
2638
2639 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2640 // are disabled, then these HazardRecs will be disabled.
2641 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trickfc127d12013-12-07 05:59:44 +00002642 if (!Top.HazardRec) {
2643 Top.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00002644 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00002645 Itin, DAG);
Andrew Trickfc127d12013-12-07 05:59:44 +00002646 }
2647 if (!Bot.HazardRec) {
2648 Bot.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00002649 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00002650 Itin, DAG);
Andrew Trickfc127d12013-12-07 05:59:44 +00002651 }
Matthias Brauncc676c42016-06-25 02:03:36 +00002652 TopCand.SU = nullptr;
2653 BotCand.SU = nullptr;
Andrew Trickfc127d12013-12-07 05:59:44 +00002654}
2655
2656/// Initialize the per-region scheduling policy.
2657void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2658 MachineBasicBlock::iterator End,
2659 unsigned NumRegionInstrs) {
Justin Bognerfdf9bf42017-10-10 23:50:49 +00002660 const MachineFunction &MF = *Begin->getMF();
Eric Christopher99556d72014-10-14 06:56:25 +00002661 const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
Andrew Trickfc127d12013-12-07 05:59:44 +00002662
2663 // Avoid setting up the register pressure tracker for small regions to save
2664 // compile time. As a rough heuristic, only track pressure when the number of
2665 // schedulable instructions exceeds half the integer register file.
Andrew Trick350ff2c2014-01-21 21:27:37 +00002666 RegionPolicy.ShouldTrackPressure = true;
Andrew Trick46753512014-01-22 03:38:55 +00002667 for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
2668 MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
2669 if (TLI->isTypeLegal(LegalIntVT)) {
Andrew Trick350ff2c2014-01-21 21:27:37 +00002670 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
Andrew Trick46753512014-01-22 03:38:55 +00002671 TLI->getRegClassFor(LegalIntVT));
Andrew Trick350ff2c2014-01-21 21:27:37 +00002672 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2673 }
2674 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002675
2676 // For generic targets, we default to bottom-up, because it's simpler and more
2677 // compile-time optimizations have been implemented in that direction.
2678 RegionPolicy.OnlyBottomUp = true;
2679
2680 // Allow the subtarget to override default policy.
Duncan P. N. Exon Smith63298722016-07-01 00:23:27 +00002681 MF.getSubtarget().overrideSchedPolicy(RegionPolicy, NumRegionInstrs);
Andrew Trickfc127d12013-12-07 05:59:44 +00002682
2683 // After subtarget overrides, apply command line options.
2684 if (!EnableRegPressure)
2685 RegionPolicy.ShouldTrackPressure = false;
2686
2687 // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2688 // e.g. -misched-bottomup=false allows scheduling in both directions.
2689 assert((!ForceTopDown || !ForceBottomUp) &&
2690 "-misched-topdown incompatible with -misched-bottomup");
2691 if (ForceBottomUp.getNumOccurrences() > 0) {
2692 RegionPolicy.OnlyBottomUp = ForceBottomUp;
2693 if (RegionPolicy.OnlyBottomUp)
2694 RegionPolicy.OnlyTopDown = false;
2695 }
2696 if (ForceTopDown.getNumOccurrences() > 0) {
2697 RegionPolicy.OnlyTopDown = ForceTopDown;
2698 if (RegionPolicy.OnlyTopDown)
2699 RegionPolicy.OnlyBottomUp = false;
2700 }
2701}
2702
Sam Clegg705f7982017-06-21 22:19:17 +00002703void GenericScheduler::dumpPolicy() const {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002704 // Cannot completely remove virtual function even in release mode.
Aaron Ballman615eb472017-10-15 14:32:27 +00002705#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
James Y Knighte72b0db2015-09-18 18:52:20 +00002706 dbgs() << "GenericScheduler RegionPolicy: "
2707 << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
2708 << " OnlyTopDown=" << RegionPolicy.OnlyTopDown
2709 << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
2710 << "\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +00002711#endif
James Y Knighte72b0db2015-09-18 18:52:20 +00002712}
2713
Andrew Trickfc127d12013-12-07 05:59:44 +00002714/// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2715/// critical path by more cycles than it takes to drain the instruction buffer.
2716/// We estimate an upper bounds on in-flight instructions as:
2717///
2718/// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2719/// InFlightIterations = AcyclicPath / CyclesPerIteration
2720/// InFlightResources = InFlightIterations * LoopResources
2721///
2722/// TODO: Check execution resources in addition to IssueCount.
2723void GenericScheduler::checkAcyclicLatency() {
2724 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2725 return;
2726
2727 // Scaled number of cycles per loop iteration.
2728 unsigned IterCount =
2729 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2730 Rem.RemIssueCount);
2731 // Scaled acyclic critical path.
2732 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2733 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2734 unsigned InFlightCount =
2735 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2736 unsigned BufferLimit =
2737 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2738
2739 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2740
2741 DEBUG(dbgs() << "IssueCycles="
2742 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2743 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2744 << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
2745 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2746 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2747 if (Rem.IsAcyclicLatencyLimited)
2748 dbgs() << " ACYCLIC LATENCY LIMIT\n");
2749}
2750
2751void GenericScheduler::registerRoots() {
2752 Rem.CriticalPath = DAG->ExitSU.getDepth();
2753
2754 // Some roots may not feed into ExitSU. Check all of them in case.
Javed Absare3a0cc22017-06-21 09:10:10 +00002755 for (const SUnit *SU : Bot.Available) {
2756 if (SU->getDepth() > Rem.CriticalPath)
2757 Rem.CriticalPath = SU->getDepth();
Andrew Trickfc127d12013-12-07 05:59:44 +00002758 }
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +00002759 DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n');
2760 if (DumpCriticalPathLength) {
2761 errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n";
2762 }
Andrew Trickfc127d12013-12-07 05:59:44 +00002763
Matthias Braun99551052017-04-12 18:09:05 +00002764 if (EnableCyclicPath && SchedModel->getMicroOpBufferSize() > 0) {
Andrew Trickfc127d12013-12-07 05:59:44 +00002765 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2766 checkAcyclicLatency();
2767 }
2768}
2769
Andrew Trick1a831342013-08-30 03:49:48 +00002770static bool tryPressure(const PressureChange &TryP,
2771 const PressureChange &CandP,
Andrew Trickd14d7c22013-12-28 21:56:57 +00002772 GenericSchedulerBase::SchedCandidate &TryCand,
2773 GenericSchedulerBase::SchedCandidate &Cand,
Tom Stellard5ce53062015-12-16 18:31:01 +00002774 GenericSchedulerBase::CandReason Reason,
2775 const TargetRegisterInfo *TRI,
2776 const MachineFunction &MF) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002777 // If one candidate decreases and the other increases, go with it.
2778 // Invalid candidates have UnitInc==0.
Hal Finkel7a87f8a2014-10-10 17:06:20 +00002779 if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2780 Reason)) {
Andrew Trickb1a45b62013-08-30 04:27:29 +00002781 return true;
2782 }
Matthias Braun6ad3d052016-06-25 00:23:00 +00002783 // Do not compare the magnitude of pressure changes between top and bottom
2784 // boundary.
2785 if (Cand.AtTop != TryCand.AtTop)
2786 return false;
2787
2788 // If both candidates affect the same set in the same boundary, go with the
2789 // smallest increase.
2790 unsigned TryPSet = TryP.getPSetOrMax();
2791 unsigned CandPSet = CandP.getPSetOrMax();
2792 if (TryPSet == CandPSet) {
2793 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2794 Reason);
2795 }
Tom Stellard5ce53062015-12-16 18:31:01 +00002796
2797 int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) :
2798 std::numeric_limits<int>::max();
2799
2800 int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) :
2801 std::numeric_limits<int>::max();
2802
Andrew Trick401b6952013-07-25 07:26:35 +00002803 // If the candidates are decreasing pressure, reverse priority.
Andrew Trick1a831342013-08-30 03:49:48 +00002804 if (TryP.getUnitInc() < 0)
Andrew Trick401b6952013-07-25 07:26:35 +00002805 std::swap(TryRank, CandRank);
2806 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2807}
2808
Andrew Tricka7714a02012-11-12 19:40:10 +00002809static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2810 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2811}
2812
Andrew Tricke833e1c2013-04-13 06:07:40 +00002813/// Minimize physical register live ranges. Regalloc wants them adjacent to
2814/// their physreg def/use.
2815///
2816/// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2817/// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2818/// with the operation that produces or consumes the physreg. We'll do this when
2819/// regalloc has support for parallel copies.
2820static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2821 const MachineInstr *MI = SU->getInstr();
2822 if (!MI->isCopy())
2823 return 0;
2824
2825 unsigned ScheduledOper = isTop ? 1 : 0;
2826 unsigned UnscheduledOper = isTop ? 0 : 1;
2827 // If we have already scheduled the physreg produce/consumer, immediately
2828 // schedule the copy.
2829 if (TargetRegisterInfo::isPhysicalRegister(
2830 MI->getOperand(ScheduledOper).getReg()))
2831 return 1;
2832 // If the physreg is at the boundary, defer it. Otherwise schedule it
2833 // immediately to free the dependent. We can hoist the copy later.
2834 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2835 if (TargetRegisterInfo::isPhysicalRegister(
2836 MI->getOperand(UnscheduledOper).getReg()))
2837 return AtBoundary ? -1 : 1;
2838 return 0;
2839}
2840
Matthias Braun4f573772016-04-22 19:10:15 +00002841void GenericScheduler::initCandidate(SchedCandidate &Cand, SUnit *SU,
2842 bool AtTop,
2843 const RegPressureTracker &RPTracker,
2844 RegPressureTracker &TempTracker) {
2845 Cand.SU = SU;
Matthias Braun6ad3d052016-06-25 00:23:00 +00002846 Cand.AtTop = AtTop;
Matthias Braun4f573772016-04-22 19:10:15 +00002847 if (DAG->isTrackingPressure()) {
2848 if (AtTop) {
2849 TempTracker.getMaxDownwardPressureDelta(
2850 Cand.SU->getInstr(),
2851 Cand.RPDelta,
2852 DAG->getRegionCriticalPSets(),
2853 DAG->getRegPressure().MaxSetPressure);
2854 } else {
2855 if (VerifyScheduling) {
2856 TempTracker.getMaxUpwardPressureDelta(
2857 Cand.SU->getInstr(),
2858 &DAG->getPressureDiff(Cand.SU),
2859 Cand.RPDelta,
2860 DAG->getRegionCriticalPSets(),
2861 DAG->getRegPressure().MaxSetPressure);
2862 } else {
2863 RPTracker.getUpwardPressureDelta(
2864 Cand.SU->getInstr(),
2865 DAG->getPressureDiff(Cand.SU),
2866 Cand.RPDelta,
2867 DAG->getRegionCriticalPSets(),
2868 DAG->getRegPressure().MaxSetPressure);
2869 }
2870 }
2871 }
2872 DEBUG(if (Cand.RPDelta.Excess.isValid())
2873 dbgs() << " Try SU(" << Cand.SU->NodeNum << ") "
2874 << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet())
2875 << ":" << Cand.RPDelta.Excess.getUnitInc() << "\n");
2876}
2877
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002878/// Apply a set of heursitics to a new candidate. Heuristics are currently
2879/// hierarchical. This may be more efficient than a graduated cost model because
2880/// we don't need to evaluate all aspects of the model for each node in the
2881/// queue. But it's really done to make the heuristics easier to debug and
2882/// statistically analyze.
2883///
2884/// \param Cand provides the policy and current best candidate.
2885/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002886/// \param Zone describes the scheduled zone that we are extending, or nullptr
2887// if Cand is from a different zone than TryCand.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002888void GenericScheduler::tryCandidate(SchedCandidate &Cand,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002889 SchedCandidate &TryCand,
Matthias Braun6ad3d052016-06-25 00:23:00 +00002890 SchedBoundary *Zone) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002891 // Initialize the candidate if needed.
2892 if (!Cand.isValid()) {
2893 TryCand.Reason = NodeOrder;
2894 return;
2895 }
Andrew Tricke833e1c2013-04-13 06:07:40 +00002896
Matthias Braun6ad3d052016-06-25 00:23:00 +00002897 if (tryGreater(biasPhysRegCopy(TryCand.SU, TryCand.AtTop),
2898 biasPhysRegCopy(Cand.SU, Cand.AtTop),
Andrew Tricke833e1c2013-04-13 06:07:40 +00002899 TryCand, Cand, PhysRegCopy))
2900 return;
2901
Andrew Tricke02d5da2015-05-17 23:40:27 +00002902 // Avoid exceeding the target's limit.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002903 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2904 Cand.RPDelta.Excess,
Tom Stellard5ce53062015-12-16 18:31:01 +00002905 TryCand, Cand, RegExcess, TRI,
2906 DAG->MF))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002907 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002908
2909 // Avoid increasing the max critical pressure in the scheduled region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002910 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2911 Cand.RPDelta.CriticalMax,
Tom Stellard5ce53062015-12-16 18:31:01 +00002912 TryCand, Cand, RegCritical, TRI,
2913 DAG->MF))
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002914 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002915
Matthias Braun6ad3d052016-06-25 00:23:00 +00002916 // We only compare a subset of features when comparing nodes between
2917 // Top and Bottom boundary. Some properties are simply incomparable, in many
2918 // other instances we should only override the other boundary if something
2919 // is a clear good pick on one boundary. Skip heuristics that are more
2920 // "tie-breaking" in nature.
2921 bool SameBoundary = Zone != nullptr;
2922 if (SameBoundary) {
2923 // For loops that are acyclic path limited, aggressively schedule for
Jonas Paulssonbaeb4022016-11-04 08:31:14 +00002924 // latency. Within an single cycle, whenever CurrMOps > 0, allow normal
2925 // heuristics to take precedence.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002926 if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() &&
2927 tryLatency(TryCand, Cand, *Zone))
2928 return;
Andrew Trickddffae92013-09-06 17:32:36 +00002929
Matthias Braun6ad3d052016-06-25 00:23:00 +00002930 // Prioritize instructions that read unbuffered resources by stall cycles.
2931 if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
2932 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2933 return;
2934 }
Andrew Trick880e5732013-12-05 17:55:58 +00002935
Andrew Tricka7714a02012-11-12 19:40:10 +00002936 // Keep clustered nodes together to encourage downstream peephole
2937 // optimizations which may reduce resource requirements.
2938 //
2939 // This is a best effort to set things up for a post-RA pass. Optimizations
2940 // like generating loads of multiple registers should ideally be done within
2941 // the scheduler pass by combining the loads during DAG postprocessing.
Matthias Braun6ad3d052016-06-25 00:23:00 +00002942 const SUnit *CandNextClusterSU =
2943 Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2944 const SUnit *TryCandNextClusterSU =
2945 TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2946 if (tryGreater(TryCand.SU == TryCandNextClusterSU,
2947 Cand.SU == CandNextClusterSU,
Andrew Tricka7714a02012-11-12 19:40:10 +00002948 TryCand, Cand, Cluster))
2949 return;
Andrew Trick85a1d4c2013-04-24 15:54:43 +00002950
Matthias Braun6ad3d052016-06-25 00:23:00 +00002951 if (SameBoundary) {
2952 // Weak edges are for clustering and other constraints.
2953 if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
2954 getWeakLeft(Cand.SU, Cand.AtTop),
2955 TryCand, Cand, Weak))
2956 return;
Andrew Tricka7714a02012-11-12 19:40:10 +00002957 }
Matthias Braun6ad3d052016-06-25 00:23:00 +00002958
Andrew Trick71f08a32013-06-17 21:45:13 +00002959 // Avoid increasing the max pressure of the entire region.
Andrew Trick66c3dfb2013-09-04 21:00:11 +00002960 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
2961 Cand.RPDelta.CurrentMax,
Tom Stellard5ce53062015-12-16 18:31:01 +00002962 TryCand, Cand, RegMax, TRI,
2963 DAG->MF))
Andrew Trick71f08a32013-06-17 21:45:13 +00002964 return;
2965
Matthias Braun6ad3d052016-06-25 00:23:00 +00002966 if (SameBoundary) {
2967 // Avoid critical resource consumption and balance the schedule.
2968 TryCand.initResourceDelta(DAG, SchedModel);
2969 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2970 TryCand, Cand, ResourceReduce))
2971 return;
2972 if (tryGreater(TryCand.ResDelta.DemandedResources,
2973 Cand.ResDelta.DemandedResources,
2974 TryCand, Cand, ResourceDemand))
2975 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002976
Matthias Braun6ad3d052016-06-25 00:23:00 +00002977 // Avoid serializing long latency dependence chains.
2978 // For acyclic path limited loops, latency was already checked above.
2979 if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency &&
2980 !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone))
2981 return;
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002982
Matthias Braun6ad3d052016-06-25 00:23:00 +00002983 // Fall through to original instruction order.
2984 if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2985 || (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2986 TryCand.Reason = NodeOrder;
2987 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00002988 }
2989}
Andrew Trick419eae22012-05-10 21:06:19 +00002990
Andrew Trickc573cd92013-09-06 17:32:44 +00002991/// Pick the best candidate from the queue.
Andrew Trick7ee9de52012-05-10 21:06:16 +00002992///
2993/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2994/// DAG building. To adjust for the current scheduling location we need to
2995/// maintain the number of vreg uses remaining to be top-scheduled.
Andrew Trick665d3ec2013-09-19 23:10:59 +00002996void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
Matthias Braun6ad3d052016-06-25 00:23:00 +00002997 const CandPolicy &ZonePolicy,
Andrew Trickbb1247b2013-12-05 17:55:47 +00002998 const RegPressureTracker &RPTracker,
2999 SchedCandidate &Cand) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00003000 // getMaxPressureDelta temporarily modifies the tracker.
3001 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
3002
Matthias Braund29d31e2016-06-23 21:27:38 +00003003 ReadyQueue &Q = Zone.Available;
Javed Absare3a0cc22017-06-21 09:10:10 +00003004 for (SUnit *SU : Q) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00003005
Matthias Braun6ad3d052016-06-25 00:23:00 +00003006 SchedCandidate TryCand(ZonePolicy);
Javed Absare3a0cc22017-06-21 09:10:10 +00003007 initCandidate(TryCand, SU, Zone.isTop(), RPTracker, TempTracker);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003008 // Pass SchedBoundary only when comparing nodes from the same boundary.
3009 SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
3010 tryCandidate(Cand, TryCand, ZoneArg);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003011 if (TryCand.Reason != NoCand) {
3012 // Initialize resource delta if needed in case future heuristics query it.
3013 if (TryCand.ResDelta == SchedResourceDelta())
3014 TryCand.initResourceDelta(DAG, SchedModel);
3015 Cand.setBest(TryCand);
Andrew Trick419d4912013-04-05 00:31:29 +00003016 DEBUG(traceCandidate(Cand));
Andrew Trick22025772012-05-17 18:35:10 +00003017 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00003018 }
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003019}
3020
Andrew Trick22025772012-05-17 18:35:10 +00003021/// Pick the best candidate node from either the top or bottom queue.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003022SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
Andrew Trick22025772012-05-17 18:35:10 +00003023 // Schedule as far as possible in the direction of no choice. This is most
3024 // efficient, but also provides the best heuristics for CriticalPSets.
Andrew Trick61f1a272012-05-24 22:11:09 +00003025 if (SUnit *SU = Bot.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00003026 IsTopNode = false;
Matthias Braun49cb6e92016-05-27 22:14:26 +00003027 tracePick(Only1, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00003028 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00003029 }
Andrew Trick61f1a272012-05-24 22:11:09 +00003030 if (SUnit *SU = Top.pickOnlyChoice()) {
Andrew Trick22025772012-05-17 18:35:10 +00003031 IsTopNode = true;
Matthias Braun49cb6e92016-05-27 22:14:26 +00003032 tracePick(Only1, true);
Andrew Trick61f1a272012-05-24 22:11:09 +00003033 return SU;
Andrew Trick22025772012-05-17 18:35:10 +00003034 }
Andrew Trickfc127d12013-12-07 05:59:44 +00003035 // Set the bottom-up policy based on the state of the current bottom zone and
3036 // the instructions outside the zone, including the top zone.
Matthias Braun6ad3d052016-06-25 00:23:00 +00003037 CandPolicy BotPolicy;
3038 setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
Andrew Trickfc127d12013-12-07 05:59:44 +00003039 // Set the top-down policy based on the state of the current top zone and
3040 // the instructions outside the zone, including the bottom zone.
Matthias Braun6ad3d052016-06-25 00:23:00 +00003041 CandPolicy TopPolicy;
3042 setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003043
Matthias Brauncc676c42016-06-25 02:03:36 +00003044 // See if BotCand is still valid (because we previously scheduled from Top).
Matthias Braund29d31e2016-06-23 21:27:38 +00003045 DEBUG(dbgs() << "Picking from Bot:\n");
Matthias Brauncc676c42016-06-25 02:03:36 +00003046 if (!BotCand.isValid() || BotCand.SU->isScheduled ||
3047 BotCand.Policy != BotPolicy) {
3048 BotCand.reset(CandPolicy());
3049 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand);
3050 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
3051 } else {
3052 DEBUG(traceCandidate(BotCand));
3053#ifndef NDEBUG
3054 if (VerifyScheduling) {
3055 SchedCandidate TCand;
3056 TCand.reset(CandPolicy());
3057 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
3058 assert(TCand.SU == BotCand.SU &&
3059 "Last pick result should correspond to re-picking right now");
3060 }
3061#endif
3062 }
Andrew Trick22025772012-05-17 18:35:10 +00003063
Andrew Trick22025772012-05-17 18:35:10 +00003064 // Check if the top Q has a better candidate.
Matthias Braund29d31e2016-06-23 21:27:38 +00003065 DEBUG(dbgs() << "Picking from Top:\n");
Matthias Brauncc676c42016-06-25 02:03:36 +00003066 if (!TopCand.isValid() || TopCand.SU->isScheduled ||
3067 TopCand.Policy != TopPolicy) {
3068 TopCand.reset(CandPolicy());
3069 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand);
3070 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
3071 } else {
3072 DEBUG(traceCandidate(TopCand));
3073#ifndef NDEBUG
3074 if (VerifyScheduling) {
3075 SchedCandidate TCand;
3076 TCand.reset(CandPolicy());
3077 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
3078 assert(TCand.SU == TopCand.SU &&
3079 "Last pick result should correspond to re-picking right now");
3080 }
3081#endif
3082 }
3083
3084 // Pick best from BotCand and TopCand.
3085 assert(BotCand.isValid());
3086 assert(TopCand.isValid());
3087 SchedCandidate Cand = BotCand;
3088 TopCand.Reason = NoCand;
3089 tryCandidate(Cand, TopCand, nullptr);
3090 if (TopCand.Reason != NoCand) {
3091 Cand.setBest(TopCand);
3092 DEBUG(traceCandidate(Cand));
3093 }
Andrew Trick22025772012-05-17 18:35:10 +00003094
Matthias Braun6ad3d052016-06-25 00:23:00 +00003095 IsTopNode = Cand.AtTop;
3096 tracePick(Cand);
3097 return Cand.SU;
Andrew Trick22025772012-05-17 18:35:10 +00003098}
3099
3100/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003101SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
Andrew Trick7ee9de52012-05-10 21:06:16 +00003102 if (DAG->top() == DAG->bottom()) {
Andrew Trick61f1a272012-05-24 22:11:09 +00003103 assert(Top.Available.empty() && Top.Pending.empty() &&
3104 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00003105 return nullptr;
Andrew Trick7ee9de52012-05-10 21:06:16 +00003106 }
Andrew Trick7ee9de52012-05-10 21:06:16 +00003107 SUnit *SU;
Andrew Trick984d98b2012-10-08 18:53:53 +00003108 do {
Andrew Trick75e411c2013-09-06 17:32:34 +00003109 if (RegionPolicy.OnlyTopDown) {
Andrew Trick984d98b2012-10-08 18:53:53 +00003110 SU = Top.pickOnlyChoice();
3111 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003112 CandPolicy NoPolicy;
Matthias Brauncc676c42016-06-25 02:03:36 +00003113 TopCand.reset(NoPolicy);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003114 pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00003115 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003116 tracePick(TopCand);
Andrew Trick984d98b2012-10-08 18:53:53 +00003117 SU = TopCand.SU;
3118 }
3119 IsTopNode = true;
Matthias Braunb550b762016-04-21 01:54:13 +00003120 } else if (RegionPolicy.OnlyBottomUp) {
Andrew Trick984d98b2012-10-08 18:53:53 +00003121 SU = Bot.pickOnlyChoice();
3122 if (!SU) {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003123 CandPolicy NoPolicy;
Matthias Brauncc676c42016-06-25 02:03:36 +00003124 BotCand.reset(NoPolicy);
Matthias Braun6ad3d052016-06-25 00:23:00 +00003125 pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand);
Andrew Trick1ab16d92013-09-04 21:00:13 +00003126 assert(BotCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003127 tracePick(BotCand);
Andrew Trick984d98b2012-10-08 18:53:53 +00003128 SU = BotCand.SU;
3129 }
3130 IsTopNode = false;
Matthias Braunb550b762016-04-21 01:54:13 +00003131 } else {
Andrew Trick3ca33ac2012-11-07 07:05:09 +00003132 SU = pickNodeBidirectional(IsTopNode);
Andrew Trick984d98b2012-10-08 18:53:53 +00003133 }
3134 } while (SU->isScheduled);
3135
Andrew Trick61f1a272012-05-24 22:11:09 +00003136 if (SU->isTopReady())
3137 Top.removeReady(SU);
3138 if (SU->isBottomReady())
3139 Bot.removeReady(SU);
Andrew Trick4e7f6a72012-05-25 02:02:39 +00003140
Andrew Trick1f0bb692013-04-13 06:07:49 +00003141 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
Andrew Trick7ee9de52012-05-10 21:06:16 +00003142 return SU;
3143}
3144
Andrew Trick665d3ec2013-09-19 23:10:59 +00003145void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
Andrew Tricke833e1c2013-04-13 06:07:40 +00003146 MachineBasicBlock::iterator InsertPos = SU->getInstr();
3147 if (!isTop)
3148 ++InsertPos;
3149 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
3150
3151 // Find already scheduled copies with a single physreg dependence and move
3152 // them just above the scheduled instruction.
Javed Absare3a0cc22017-06-21 09:10:10 +00003153 for (SDep &Dep : Deps) {
3154 if (Dep.getKind() != SDep::Data || !TRI->isPhysicalRegister(Dep.getReg()))
Andrew Tricke833e1c2013-04-13 06:07:40 +00003155 continue;
Javed Absare3a0cc22017-06-21 09:10:10 +00003156 SUnit *DepSU = Dep.getSUnit();
Andrew Tricke833e1c2013-04-13 06:07:40 +00003157 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
3158 continue;
3159 MachineInstr *Copy = DepSU->getInstr();
3160 if (!Copy->isCopy())
3161 continue;
3162 DEBUG(dbgs() << " Rescheduling physreg copy ";
Javed Absare3a0cc22017-06-21 09:10:10 +00003163 Dep.getSUnit()->dump(DAG));
Andrew Tricke833e1c2013-04-13 06:07:40 +00003164 DAG->moveInstruction(Copy, InsertPos);
3165 }
3166}
3167
Andrew Trick61f1a272012-05-24 22:11:09 +00003168/// Update the scheduler's state after scheduling a node. This is the same node
Andrew Trickd14d7c22013-12-28 21:56:57 +00003169/// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
3170/// update it's state based on the current cycle before MachineSchedStrategy
3171/// does.
Andrew Tricke833e1c2013-04-13 06:07:40 +00003172///
3173/// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
3174/// them here. See comments in biasPhysRegCopy.
Andrew Trick665d3ec2013-09-19 23:10:59 +00003175void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
Andrew Trick45446062012-06-05 21:11:27 +00003176 if (IsTopNode) {
Andrew Trickfc127d12013-12-07 05:59:44 +00003177 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00003178 Top.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00003179 if (SU->hasPhysRegUses)
3180 reschedulePhysRegCopies(SU, true);
Matthias Braunb550b762016-04-21 01:54:13 +00003181 } else {
Andrew Trickfc127d12013-12-07 05:59:44 +00003182 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
Andrew Trickce27bb92012-06-29 03:23:22 +00003183 Bot.bumpNode(SU);
Andrew Tricke833e1c2013-04-13 06:07:40 +00003184 if (SU->hasPhysRegDefs)
3185 reschedulePhysRegCopies(SU, false);
Andrew Trick61f1a272012-05-24 22:11:09 +00003186 }
3187}
3188
Andrew Trick8823dec2012-03-14 04:00:41 +00003189/// Create the standard converging machine scheduler. This will be used as the
3190/// default scheduler if the target does not set a default.
Matthias Braun115efcd2016-11-28 20:11:54 +00003191ScheduleDAGMILive *llvm::createGenericSchedLive(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003192 ScheduleDAGMILive *DAG =
3193 new ScheduleDAGMILive(C, llvm::make_unique<GenericScheduler>(C));
Andrew Tricka7714a02012-11-12 19:40:10 +00003194 // Register DAG post-processors.
Andrew Trick85a1d4c2013-04-24 15:54:43 +00003195 //
3196 // FIXME: extend the mutation API to allow earlier mutations to instantiate
3197 // data and pass it to later mutations. Have a single mutation that gathers
3198 // the interesting nodes in one pass.
Tom Stellard68726a52016-08-19 19:59:18 +00003199 DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI));
Andrew Tricka7714a02012-11-12 19:40:10 +00003200 return DAG;
Andrew Tricke1c034f2012-01-17 06:55:03 +00003201}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003202
Matthias Braun115efcd2016-11-28 20:11:54 +00003203static ScheduleDAGInstrs *createConveringSched(MachineSchedContext *C) {
3204 return createGenericSchedLive(C);
3205}
3206
Andrew Tricke1c034f2012-01-17 06:55:03 +00003207static MachineSchedRegistry
Andrew Trick665d3ec2013-09-19 23:10:59 +00003208GenericSchedRegistry("converge", "Standard converging scheduler.",
Matthias Braun115efcd2016-11-28 20:11:54 +00003209 createConveringSched);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003210
3211//===----------------------------------------------------------------------===//
3212// PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
3213//===----------------------------------------------------------------------===//
3214
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003215void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
3216 DAG = Dag;
3217 SchedModel = DAG->getSchedModel();
3218 TRI = DAG->TRI;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003219
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003220 Rem.init(DAG, SchedModel);
3221 Top.init(DAG, SchedModel, &Rem);
3222 BotRoots.clear();
Andrew Trickd14d7c22013-12-28 21:56:57 +00003223
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003224 // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
3225 // or are disabled, then these HazardRecs will be disabled.
3226 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003227 if (!Top.HazardRec) {
3228 Top.HazardRec =
Eric Christopher99556d72014-10-14 06:56:25 +00003229 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
Eric Christopherd9134482014-08-04 21:25:23 +00003230 Itin, DAG);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003231 }
Andrew Trick3ccf71d2014-06-04 07:06:18 +00003232}
Andrew Trickd14d7c22013-12-28 21:56:57 +00003233
Andrew Trickd14d7c22013-12-28 21:56:57 +00003234void PostGenericScheduler::registerRoots() {
3235 Rem.CriticalPath = DAG->ExitSU.getDepth();
3236
3237 // Some roots may not feed into ExitSU. Check all of them in case.
Javed Absare3a0cc22017-06-21 09:10:10 +00003238 for (const SUnit *SU : BotRoots) {
3239 if (SU->getDepth() > Rem.CriticalPath)
3240 Rem.CriticalPath = SU->getDepth();
Andrew Trickd14d7c22013-12-28 21:56:57 +00003241 }
Gerolf Hoflehnerb5220dc2014-08-07 21:49:44 +00003242 DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n');
3243 if (DumpCriticalPathLength) {
3244 errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n";
3245 }
Andrew Trickd14d7c22013-12-28 21:56:57 +00003246}
3247
3248/// Apply a set of heursitics to a new candidate for PostRA scheduling.
3249///
3250/// \param Cand provides the policy and current best candidate.
3251/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
3252void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
3253 SchedCandidate &TryCand) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003254 // Initialize the candidate if needed.
3255 if (!Cand.isValid()) {
3256 TryCand.Reason = NodeOrder;
3257 return;
3258 }
3259
3260 // Prioritize instructions that read unbuffered resources by stall cycles.
3261 if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
3262 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3263 return;
3264
Florian Hahnabb42182017-05-23 09:33:34 +00003265 // Keep clustered nodes together.
3266 if (tryGreater(TryCand.SU == DAG->getNextClusterSucc(),
3267 Cand.SU == DAG->getNextClusterSucc(),
3268 TryCand, Cand, Cluster))
3269 return;
3270
Andrew Trickd14d7c22013-12-28 21:56:57 +00003271 // Avoid critical resource consumption and balance the schedule.
3272 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3273 TryCand, Cand, ResourceReduce))
3274 return;
3275 if (tryGreater(TryCand.ResDelta.DemandedResources,
3276 Cand.ResDelta.DemandedResources,
3277 TryCand, Cand, ResourceDemand))
3278 return;
3279
3280 // Avoid serializing long latency dependence chains.
3281 if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
3282 return;
3283 }
3284
3285 // Fall through to original instruction order.
3286 if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
3287 TryCand.Reason = NodeOrder;
3288}
3289
3290void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
3291 ReadyQueue &Q = Top.Available;
Javed Absare3a0cc22017-06-21 09:10:10 +00003292 for (SUnit *SU : Q) {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003293 SchedCandidate TryCand(Cand.Policy);
Javed Absare3a0cc22017-06-21 09:10:10 +00003294 TryCand.SU = SU;
Matthias Braun6ad3d052016-06-25 00:23:00 +00003295 TryCand.AtTop = true;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003296 TryCand.initResourceDelta(DAG, SchedModel);
3297 tryCandidate(Cand, TryCand);
3298 if (TryCand.Reason != NoCand) {
3299 Cand.setBest(TryCand);
3300 DEBUG(traceCandidate(Cand));
3301 }
3302 }
3303}
3304
3305/// Pick the next node to schedule.
3306SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
3307 if (DAG->top() == DAG->bottom()) {
3308 assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
Craig Topperc0196b12014-04-14 00:51:57 +00003309 return nullptr;
Andrew Trickd14d7c22013-12-28 21:56:57 +00003310 }
3311 SUnit *SU;
3312 do {
3313 SU = Top.pickOnlyChoice();
Matthias Braun49cb6e92016-05-27 22:14:26 +00003314 if (SU) {
3315 tracePick(Only1, true);
3316 } else {
Andrew Trickd14d7c22013-12-28 21:56:57 +00003317 CandPolicy NoPolicy;
3318 SchedCandidate TopCand(NoPolicy);
3319 // Set the top-down policy based on the state of the current top zone and
3320 // the instructions outside the zone, including the bottom zone.
Craig Topperc0196b12014-04-14 00:51:57 +00003321 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003322 pickNodeFromQueue(TopCand);
3323 assert(TopCand.Reason != NoCand && "failed to find a candidate");
Matthias Braun6ad3d052016-06-25 00:23:00 +00003324 tracePick(TopCand);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003325 SU = TopCand.SU;
3326 }
3327 } while (SU->isScheduled);
3328
3329 IsTopNode = true;
3330 Top.removeReady(SU);
3331
3332 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
3333 return SU;
3334}
3335
3336/// Called after ScheduleDAGMI has scheduled an instruction and updated
3337/// scheduled/remaining flags in the DAG nodes.
3338void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
3339 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
3340 Top.bumpNode(SU);
3341}
3342
Matthias Braun115efcd2016-11-28 20:11:54 +00003343ScheduleDAGMI *llvm::createGenericSchedPostRA(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003344 return new ScheduleDAGMI(C, llvm::make_unique<PostGenericScheduler>(C),
Jonas Paulsson28f29482016-11-09 09:59:27 +00003345 /*RemoveKillFlags=*/true);
Andrew Trickd14d7c22013-12-28 21:56:57 +00003346}
Andrew Tricke1c034f2012-01-17 06:55:03 +00003347
3348//===----------------------------------------------------------------------===//
Andrew Trick90f711d2012-10-15 18:02:27 +00003349// ILP Scheduler. Currently for experimental analysis of heuristics.
3350//===----------------------------------------------------------------------===//
3351
3352namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003353
Andrew Trick90f711d2012-10-15 18:02:27 +00003354/// \brief Order nodes by the ILP metric.
3355struct ILPOrder {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003356 const SchedDFSResult *DFSResult = nullptr;
3357 const BitVector *ScheduledTrees = nullptr;
Andrew Trick90f711d2012-10-15 18:02:27 +00003358 bool MaximizeILP;
3359
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003360 ILPOrder(bool MaxILP) : MaximizeILP(MaxILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003361
3362 /// \brief Apply a less-than relation on node priority.
Andrew Trick48d392e2012-11-28 05:13:28 +00003363 ///
3364 /// (Return true if A comes after B in the Q.)
Andrew Trick90f711d2012-10-15 18:02:27 +00003365 bool operator()(const SUnit *A, const SUnit *B) const {
Andrew Trick48d392e2012-11-28 05:13:28 +00003366 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3367 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3368 if (SchedTreeA != SchedTreeB) {
3369 // Unscheduled trees have lower priority.
3370 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3371 return ScheduledTrees->test(SchedTreeB);
3372
3373 // Trees with shallower connections have have lower priority.
3374 if (DFSResult->getSubtreeLevel(SchedTreeA)
3375 != DFSResult->getSubtreeLevel(SchedTreeB)) {
3376 return DFSResult->getSubtreeLevel(SchedTreeA)
3377 < DFSResult->getSubtreeLevel(SchedTreeB);
3378 }
3379 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003380 if (MaximizeILP)
Andrew Trick48d392e2012-11-28 05:13:28 +00003381 return DFSResult->getILP(A) < DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003382 else
Andrew Trick48d392e2012-11-28 05:13:28 +00003383 return DFSResult->getILP(A) > DFSResult->getILP(B);
Andrew Trick90f711d2012-10-15 18:02:27 +00003384 }
3385};
3386
3387/// \brief Schedule based on the ILP metric.
3388class ILPScheduler : public MachineSchedStrategy {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003389 ScheduleDAGMILive *DAG = nullptr;
Andrew Trick90f711d2012-10-15 18:02:27 +00003390 ILPOrder Cmp;
3391
3392 std::vector<SUnit*> ReadyQ;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003393
Andrew Trick90f711d2012-10-15 18:02:27 +00003394public:
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003395 ILPScheduler(bool MaximizeILP) : Cmp(MaximizeILP) {}
Andrew Trick90f711d2012-10-15 18:02:27 +00003396
Craig Topper4584cd52014-03-07 09:26:03 +00003397 void initialize(ScheduleDAGMI *dag) override {
Andrew Trickd7f890e2013-12-28 21:56:47 +00003398 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3399 DAG = static_cast<ScheduleDAGMILive*>(dag);
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00003400 DAG->computeDFSResult();
Andrew Trick44f750a2013-01-25 04:01:04 +00003401 Cmp.DFSResult = DAG->getDFSResult();
3402 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
Andrew Trick90f711d2012-10-15 18:02:27 +00003403 ReadyQ.clear();
Andrew Trick90f711d2012-10-15 18:02:27 +00003404 }
3405
Craig Topper4584cd52014-03-07 09:26:03 +00003406 void registerRoots() override {
Benjamin Krameraa598b32012-11-29 14:36:26 +00003407 // Restore the heap in ReadyQ with the updated DFS results.
3408 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003409 }
3410
3411 /// Implement MachineSchedStrategy interface.
3412 /// -----------------------------------------
3413
Andrew Trick48d392e2012-11-28 05:13:28 +00003414 /// Callback to select the highest priority node from the ready Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003415 SUnit *pickNode(bool &IsTopNode) override {
Craig Topperc0196b12014-04-14 00:51:57 +00003416 if (ReadyQ.empty()) return nullptr;
Matt Arsenault4ab769f2013-03-21 00:57:21 +00003417 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
Andrew Trick90f711d2012-10-15 18:02:27 +00003418 SUnit *SU = ReadyQ.back();
3419 ReadyQ.pop_back();
3420 IsTopNode = false;
Andrew Trick1f0bb692013-04-13 06:07:49 +00003421 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
Andrew Trick44f750a2013-01-25 04:01:04 +00003422 << " ILP: " << DAG->getDFSResult()->getILP(SU)
3423 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
3424 << DAG->getDFSResult()->getSubtreeLevel(
Andrew Trick1f0bb692013-04-13 06:07:49 +00003425 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
3426 << "Scheduling " << *SU->getInstr());
Andrew Trick90f711d2012-10-15 18:02:27 +00003427 return SU;
3428 }
3429
Andrew Trick44f750a2013-01-25 04:01:04 +00003430 /// \brief Scheduler callback to notify that a new subtree is scheduled.
Craig Topper4584cd52014-03-07 09:26:03 +00003431 void scheduleTree(unsigned SubtreeID) override {
Andrew Trick44f750a2013-01-25 04:01:04 +00003432 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3433 }
3434
Andrew Trick48d392e2012-11-28 05:13:28 +00003435 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3436 /// DFSResults, and resort the priority Q.
Craig Topper4584cd52014-03-07 09:26:03 +00003437 void schedNode(SUnit *SU, bool IsTopNode) override {
Andrew Trick48d392e2012-11-28 05:13:28 +00003438 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
Andrew Trick48d392e2012-11-28 05:13:28 +00003439 }
Andrew Trick90f711d2012-10-15 18:02:27 +00003440
Craig Topper4584cd52014-03-07 09:26:03 +00003441 void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
Andrew Trick90f711d2012-10-15 18:02:27 +00003442
Craig Topper4584cd52014-03-07 09:26:03 +00003443 void releaseBottomNode(SUnit *SU) override {
Andrew Trick90f711d2012-10-15 18:02:27 +00003444 ReadyQ.push_back(SU);
3445 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3446 }
3447};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003448
3449} // end anonymous namespace
Andrew Trick90f711d2012-10-15 18:02:27 +00003450
3451static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003452 return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(true));
Andrew Trick90f711d2012-10-15 18:02:27 +00003453}
3454static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003455 return new ScheduleDAGMILive(C, llvm::make_unique<ILPScheduler>(false));
Andrew Trick90f711d2012-10-15 18:02:27 +00003456}
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003457
Andrew Trick90f711d2012-10-15 18:02:27 +00003458static MachineSchedRegistry ILPMaxRegistry(
3459 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3460static MachineSchedRegistry ILPMinRegistry(
3461 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3462
3463//===----------------------------------------------------------------------===//
Andrew Trick63440872012-01-14 02:17:06 +00003464// Machine Instruction Shuffler for Correctness Testing
3465//===----------------------------------------------------------------------===//
3466
Andrew Tricke77e84e2012-01-13 06:30:30 +00003467#ifndef NDEBUG
3468namespace {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003469
Andrew Trick8823dec2012-03-14 04:00:41 +00003470/// Apply a less-than relation on the node order, which corresponds to the
3471/// instruction order prior to scheduling. IsReverse implements greater-than.
3472template<bool IsReverse>
3473struct SUnitOrder {
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003474 bool operator()(SUnit *A, SUnit *B) const {
Andrew Trick8823dec2012-03-14 04:00:41 +00003475 if (IsReverse)
3476 return A->NodeNum > B->NodeNum;
3477 else
3478 return A->NodeNum < B->NodeNum;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003479 }
3480};
3481
Andrew Tricke77e84e2012-01-13 06:30:30 +00003482/// Reorder instructions as much as possible.
Andrew Trick8823dec2012-03-14 04:00:41 +00003483class InstructionShuffler : public MachineSchedStrategy {
3484 bool IsAlternating;
3485 bool IsTopDown;
3486
3487 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3488 // gives nodes with a higher number higher priority causing the latest
3489 // instructions to be scheduled first.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003490 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false>>
Andrew Trick8823dec2012-03-14 04:00:41 +00003491 TopQ;
Eugene Zelenko32a40562017-09-11 23:00:48 +00003492
Andrew Trick8823dec2012-03-14 04:00:41 +00003493 // When scheduling bottom-up, use greater-than as the queue priority.
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003494 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true>>
Andrew Trick8823dec2012-03-14 04:00:41 +00003495 BottomQ;
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003496
Andrew Tricke77e84e2012-01-13 06:30:30 +00003497public:
Andrew Trick8823dec2012-03-14 04:00:41 +00003498 InstructionShuffler(bool alternate, bool topdown)
3499 : IsAlternating(alternate), IsTopDown(topdown) {}
Andrew Tricke77e84e2012-01-13 06:30:30 +00003500
Craig Topper9d74a5a2014-04-29 07:58:41 +00003501 void initialize(ScheduleDAGMI*) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003502 TopQ.clear();
3503 BottomQ.clear();
3504 }
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003505
Andrew Trick8823dec2012-03-14 04:00:41 +00003506 /// Implement MachineSchedStrategy interface.
3507 /// -----------------------------------------
3508
Craig Topper9d74a5a2014-04-29 07:58:41 +00003509 SUnit *pickNode(bool &IsTopNode) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003510 SUnit *SU;
3511 if (IsTopDown) {
3512 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003513 if (TopQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003514 SU = TopQ.top();
3515 TopQ.pop();
3516 } while (SU->isScheduled);
3517 IsTopNode = true;
Matthias Braunb550b762016-04-21 01:54:13 +00003518 } else {
Andrew Trick8823dec2012-03-14 04:00:41 +00003519 do {
Craig Topperc0196b12014-04-14 00:51:57 +00003520 if (BottomQ.empty()) return nullptr;
Andrew Trick8823dec2012-03-14 04:00:41 +00003521 SU = BottomQ.top();
3522 BottomQ.pop();
3523 } while (SU->isScheduled);
3524 IsTopNode = false;
3525 }
3526 if (IsAlternating)
3527 IsTopDown = !IsTopDown;
Andrew Trick7ccdc5c2012-01-17 06:55:07 +00003528 return SU;
3529 }
3530
Craig Topper9d74a5a2014-04-29 07:58:41 +00003531 void schedNode(SUnit *SU, bool IsTopNode) override {}
Andrew Trick61f1a272012-05-24 22:11:09 +00003532
Craig Topper9d74a5a2014-04-29 07:58:41 +00003533 void releaseTopNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003534 TopQ.push(SU);
3535 }
Craig Topper9d74a5a2014-04-29 07:58:41 +00003536 void releaseBottomNode(SUnit *SU) override {
Andrew Trick8823dec2012-03-14 04:00:41 +00003537 BottomQ.push(SU);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003538 }
3539};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003540
3541} // end anonymous namespace
Andrew Tricke77e84e2012-01-13 06:30:30 +00003542
Andrew Trick02a80da2012-03-08 01:41:12 +00003543static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
Andrew Trick8823dec2012-03-14 04:00:41 +00003544 bool Alternate = !ForceTopDown && !ForceBottomUp;
3545 bool TopDown = !ForceBottomUp;
Benjamin Kramer05e7a842012-03-14 11:26:37 +00003546 assert((TopDown || !ForceTopDown) &&
Andrew Trick8823dec2012-03-14 04:00:41 +00003547 "-misched-topdown incompatible with -misched-bottomup");
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003548 return new ScheduleDAGMILive(
3549 C, llvm::make_unique<InstructionShuffler>(Alternate, TopDown));
Andrew Tricke77e84e2012-01-13 06:30:30 +00003550}
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003551
Andrew Trick8823dec2012-03-14 04:00:41 +00003552static MachineSchedRegistry ShufflerRegistry(
3553 "shuffle", "Shuffle machine instructions alternating directions",
3554 createInstructionShuffler);
Andrew Tricke77e84e2012-01-13 06:30:30 +00003555#endif // !NDEBUG
Andrew Trickea9fd952013-01-25 07:45:29 +00003556
3557//===----------------------------------------------------------------------===//
Andrew Trickd7f890e2013-12-28 21:56:47 +00003558// GraphWriter support for ScheduleDAGMILive.
Andrew Trickea9fd952013-01-25 07:45:29 +00003559//===----------------------------------------------------------------------===//
3560
3561#ifndef NDEBUG
3562namespace llvm {
3563
3564template<> struct GraphTraits<
3565 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3566
3567template<>
3568struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003569 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
Andrew Trickea9fd952013-01-25 07:45:29 +00003570
3571 static std::string getGraphName(const ScheduleDAG *G) {
3572 return G->MF.getName();
3573 }
3574
3575 static bool renderGraphFromBottomUp() {
3576 return true;
3577 }
3578
3579 static bool isNodeHidden(const SUnit *Node) {
Matthias Braund78ee542015-09-17 21:09:59 +00003580 if (ViewMISchedCutoff == 0)
3581 return false;
3582 return (Node->Preds.size() > ViewMISchedCutoff
3583 || Node->Succs.size() > ViewMISchedCutoff);
Andrew Trickea9fd952013-01-25 07:45:29 +00003584 }
3585
Andrew Trickea9fd952013-01-25 07:45:29 +00003586 /// If you want to override the dot attributes printed for a particular
3587 /// edge, override this method.
3588 static std::string getEdgeAttributes(const SUnit *Node,
3589 SUnitIterator EI,
3590 const ScheduleDAG *Graph) {
3591 if (EI.isArtificialDep())
3592 return "color=cyan,style=dashed";
3593 if (EI.isCtrlDep())
3594 return "color=blue,style=dashed";
3595 return "";
3596 }
3597
3598 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
Alp Tokere69170a2014-06-26 22:52:05 +00003599 std::string Str;
3600 raw_string_ostream SS(Str);
Andrew Trickd7f890e2013-12-28 21:56:47 +00003601 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3602 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003603 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trick7609b7d2013-09-06 17:32:42 +00003604 SS << "SU:" << SU->NodeNum;
3605 if (DFS)
3606 SS << " I:" << DFS->getNumInstrs(SU);
Andrew Trickea9fd952013-01-25 07:45:29 +00003607 return SS.str();
3608 }
Eugene Zelenko32a40562017-09-11 23:00:48 +00003609
Andrew Trickea9fd952013-01-25 07:45:29 +00003610 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3611 return G->getGraphNodeLabel(SU);
3612 }
3613
Andrew Trickd7f890e2013-12-28 21:56:47 +00003614 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
Andrew Trickea9fd952013-01-25 07:45:29 +00003615 std::string Str("shape=Mrecord");
Andrew Trickd7f890e2013-12-28 21:56:47 +00003616 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3617 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
Craig Topperc0196b12014-04-14 00:51:57 +00003618 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
Andrew Trickea9fd952013-01-25 07:45:29 +00003619 if (DFS) {
3620 Str += ",style=filled,fillcolor=\"#";
3621 Str += DOT::getColorString(DFS->getSubtreeID(N));
3622 Str += '"';
3623 }
3624 return Str;
3625 }
3626};
Eugene Zelenkodb56e5a2017-02-22 22:32:51 +00003627
3628} // end namespace llvm
Andrew Trickea9fd952013-01-25 07:45:29 +00003629#endif // NDEBUG
3630
3631/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3632/// rendered using 'dot'.
Andrew Trickea9fd952013-01-25 07:45:29 +00003633void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3634#ifndef NDEBUG
3635 ViewGraph(this, Name, false, Title);
3636#else
3637 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3638 << "systems with Graphviz or gv!\n";
3639#endif // NDEBUG
3640}
3641
3642/// Out-of-line implementation with no arguments is handy for gdb.
3643void ScheduleDAGMI::viewGraph() {
3644 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
3645}