1 //==- MachineScheduler.h - MachineInstr Scheduling Pass ----------*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides a MachineSchedRegistry for registering alternative machine
11 // schedulers. A Target may provide an alternative scheduler implementation by
12 // implementing the following boilerplate:
14 // static ScheduleDAGInstrs *createCustomMachineSched(MachineSchedContext *C) {
15 // return new CustomMachineScheduler(C);
17 // static MachineSchedRegistry
18 // SchedCustomRegistry("custom", "Run my target's custom scheduler",
19 // createCustomMachineSched);
21 // Inside <Target>PassConfig:
22 // enablePass(&MachineSchedulerID);
23 // MachineSchedRegistry::setDefault(createCustomMachineSched);
25 //===----------------------------------------------------------------------===//
27 #ifndef LLVM_CODEGEN_MACHINESCHEDULER_H
28 #define LLVM_CODEGEN_MACHINESCHEDULER_H
30 #include "llvm/CodeGen/MachinePassRegistry.h"
31 #include "llvm/CodeGen/RegisterPressure.h"
32 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
33 #include "llvm/Target/TargetInstrInfo.h"
37 extern cl::opt<bool> ForceTopDown;
38 extern cl::opt<bool> ForceBottomUp;
42 class MachineDominatorTree;
43 class MachineLoopInfo;
44 class RegisterClassInfo;
45 class ScheduleDAGInstrs;
48 /// MachineSchedContext provides enough context from the MachineScheduler pass
49 /// for the target to instantiate a scheduler.
50 struct MachineSchedContext {
52 const MachineLoopInfo *MLI;
53 const MachineDominatorTree *MDT;
54 const TargetPassConfig *PassConfig;
58 RegisterClassInfo *RegClassInfo;
60 MachineSchedContext();
61 virtual ~MachineSchedContext();
64 /// MachineSchedRegistry provides a selection of available machine instruction
66 class MachineSchedRegistry : public MachinePassRegistryNode {
68 typedef ScheduleDAGInstrs *(*ScheduleDAGCtor)(MachineSchedContext *);
70 // RegisterPassParser requires a (misnamed) FunctionPassCtor type.
71 typedef ScheduleDAGCtor FunctionPassCtor;
73 static MachinePassRegistry Registry;
75 MachineSchedRegistry(const char *N, const char *D, ScheduleDAGCtor C)
76 : MachinePassRegistryNode(N, D, (MachinePassCtor)C) {
79 ~MachineSchedRegistry() { Registry.Remove(this); }
83 MachineSchedRegistry *getNext() const {
84 return (MachineSchedRegistry *)MachinePassRegistryNode::getNext();
86 static MachineSchedRegistry *getList() {
87 return (MachineSchedRegistry *)Registry.getList();
89 static ScheduleDAGCtor getDefault() {
90 return (ScheduleDAGCtor)Registry.getDefault();
92 static void setDefault(ScheduleDAGCtor C) {
93 Registry.setDefault((MachinePassCtor)C);
95 static void setDefault(StringRef Name) {
96 Registry.setDefault(Name);
98 static void setListener(MachinePassRegistryListener *L) {
99 Registry.setListener(L);
105 /// MachineSchedStrategy - Interface to the scheduling algorithm used by
107 class MachineSchedStrategy {
109 virtual ~MachineSchedStrategy() {}
111 /// Initialize the strategy after building the DAG for a new region.
112 virtual void initialize(ScheduleDAGMI *DAG) = 0;
114 /// Notify this strategy that all roots have been released (including those
115 /// that depend on EntrySU or ExitSU).
116 virtual void registerRoots() {}
118 /// Pick the next node to schedule, or return NULL. Set IsTopNode to true to
119 /// schedule the node at the top of the unscheduled region. Otherwise it will
120 /// be scheduled at the bottom.
121 virtual SUnit *pickNode(bool &IsTopNode) = 0;
123 /// \brief Scheduler callback to notify that a new subtree is scheduled.
124 virtual void scheduleTree(unsigned SubtreeID) {}
126 /// Notify MachineSchedStrategy that ScheduleDAGMI has scheduled an
127 /// instruction and updated scheduled/remaining flags in the DAG nodes.
128 virtual void schedNode(SUnit *SU, bool IsTopNode) = 0;
130 /// When all predecessor dependencies have been resolved, free this node for
131 /// top-down scheduling.
132 virtual void releaseTopNode(SUnit *SU) = 0;
133 /// When all successor dependencies have been resolved, free this node for
134 /// bottom-up scheduling.
135 virtual void releaseBottomNode(SUnit *SU) = 0;
138 /// ReadyQueue encapsulates vector of "ready" SUnits with basic convenience
139 /// methods for pushing and removing nodes. ReadyQueue's are uniquely identified
140 /// by an ID. SUnit::NodeQueueId is a mask of the ReadyQueues the SUnit is in.
142 /// This is a convenience class that may be used by implementations of
143 /// MachineSchedStrategy.
147 std::vector<SUnit*> Queue;
150 ReadyQueue(unsigned id, const Twine &name): ID(id), Name(name.str()) {}
152 unsigned getID() const { return ID; }
154 StringRef getName() const { return Name; }
156 // SU is in this queue if it's NodeQueueID is a superset of this ID.
157 bool isInQueue(SUnit *SU) const { return (SU->NodeQueueId & ID); }
159 bool empty() const { return Queue.empty(); }
161 void clear() { Queue.clear(); }
163 unsigned size() const { return Queue.size(); }
165 typedef std::vector<SUnit*>::iterator iterator;
167 iterator begin() { return Queue.begin(); }
169 iterator end() { return Queue.end(); }
171 ArrayRef<SUnit*> elements() { return Queue; }
173 iterator find(SUnit *SU) {
174 return std::find(Queue.begin(), Queue.end(), SU);
177 void push(SUnit *SU) {
179 SU->NodeQueueId |= ID;
182 iterator remove(iterator I) {
183 (*I)->NodeQueueId &= ~ID;
185 unsigned idx = I - Queue.begin();
187 return Queue.begin() + idx;
190 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
195 /// Mutate the DAG as a postpass after normal DAG building.
196 class ScheduleDAGMutation {
198 virtual ~ScheduleDAGMutation() {}
200 virtual void apply(ScheduleDAGMI *DAG) = 0;
203 /// ScheduleDAGMI is an implementation of ScheduleDAGInstrs that schedules
204 /// machine instructions while updating LiveIntervals and tracking regpressure.
205 class ScheduleDAGMI : public ScheduleDAGInstrs {
208 RegisterClassInfo *RegClassInfo;
209 MachineSchedStrategy *SchedImpl;
211 /// Information about DAG subtrees. If DFSResult is NULL, then SchedulerTrees
213 SchedDFSResult *DFSResult;
214 BitVector ScheduledTrees;
216 /// Topo - A topological ordering for SUnits which permits fast IsReachable
217 /// and similar queries.
218 ScheduleDAGTopologicalSort Topo;
220 /// Ordered list of DAG postprocessing steps.
221 std::vector<ScheduleDAGMutation*> Mutations;
223 MachineBasicBlock::iterator LiveRegionEnd;
225 /// Register pressure in this region computed by buildSchedGraph.
226 IntervalPressure RegPressure;
227 RegPressureTracker RPTracker;
229 /// List of pressure sets that exceed the target's pressure limit before
230 /// scheduling, listed in increasing set ID order. Each pressure set is paired
231 /// with its max pressure in the currently scheduled regions.
232 std::vector<PressureElement> RegionCriticalPSets;
234 /// The top of the unscheduled zone.
235 MachineBasicBlock::iterator CurrentTop;
236 IntervalPressure TopPressure;
237 RegPressureTracker TopRPTracker;
239 /// The bottom of the unscheduled zone.
240 MachineBasicBlock::iterator CurrentBottom;
241 IntervalPressure BotPressure;
242 RegPressureTracker BotRPTracker;
244 /// Record the next node in a scheduled cluster.
245 const SUnit *NextClusterPred;
246 const SUnit *NextClusterSucc;
249 /// The number of instructions scheduled so far. Used to cut off the
250 /// scheduler at the point determined by misched-cutoff.
251 unsigned NumInstrsScheduled;
255 ScheduleDAGMI(MachineSchedContext *C, MachineSchedStrategy *S):
256 ScheduleDAGInstrs(*C->MF, *C->MLI, *C->MDT, /*IsPostRA=*/false, C->LIS),
257 AA(C->AA), RegClassInfo(C->RegClassInfo), SchedImpl(S), DFSResult(0),
258 Topo(SUnits, &ExitSU), RPTracker(RegPressure), CurrentTop(),
259 TopRPTracker(TopPressure), CurrentBottom(), BotRPTracker(BotPressure),
260 NextClusterPred(NULL), NextClusterSucc(NULL) {
262 NumInstrsScheduled = 0;
266 virtual ~ScheduleDAGMI();
268 /// Add a postprocessing step to the DAG builder.
269 /// Mutations are applied in the order that they are added after normal DAG
270 /// building and before MachineSchedStrategy initialization.
272 /// ScheduleDAGMI takes ownership of the Mutation object.
273 void addMutation(ScheduleDAGMutation *Mutation) {
274 Mutations.push_back(Mutation);
277 /// \brief True if an edge can be added from PredSU to SuccSU without creating
279 bool canAddEdge(SUnit *SuccSU, SUnit *PredSU);
281 /// \brief Add a DAG edge to the given SU with the given predecessor
284 /// \returns true if the edge may be added without creating a cycle OR if an
285 /// equivalent edge already existed (false indicates failure).
286 bool addEdge(SUnit *SuccSU, const SDep &PredDep);
288 MachineBasicBlock::iterator top() const { return CurrentTop; }
289 MachineBasicBlock::iterator bottom() const { return CurrentBottom; }
291 /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
292 /// region. This covers all instructions in a block, while schedule() may only
294 void enterRegion(MachineBasicBlock *bb,
295 MachineBasicBlock::iterator begin,
296 MachineBasicBlock::iterator end,
300 /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
301 /// reorderable instructions.
302 virtual void schedule();
304 /// Change the position of an instruction within the basic block and update
305 /// live ranges and region boundary iterators.
306 void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos);
308 /// Get current register pressure for the top scheduled instructions.
309 const IntervalPressure &getTopPressure() const { return TopPressure; }
310 const RegPressureTracker &getTopRPTracker() const { return TopRPTracker; }
312 /// Get current register pressure for the bottom scheduled instructions.
313 const IntervalPressure &getBotPressure() const { return BotPressure; }
314 const RegPressureTracker &getBotRPTracker() const { return BotRPTracker; }
316 /// Get register pressure for the entire scheduling region before scheduling.
317 const IntervalPressure &getRegPressure() const { return RegPressure; }
319 const std::vector<PressureElement> &getRegionCriticalPSets() const {
320 return RegionCriticalPSets;
323 const SUnit *getNextClusterPred() const { return NextClusterPred; }
325 const SUnit *getNextClusterSucc() const { return NextClusterSucc; }
327 /// Compute a DFSResult after DAG building is complete, and before any
328 /// queue comparisons.
329 void computeDFSResult();
331 /// Return a non-null DFS result if the scheduling strategy initialized it.
332 const SchedDFSResult *getDFSResult() const { return DFSResult; }
334 BitVector &getScheduledTrees() { return ScheduledTrees; }
336 void viewGraph(const Twine &Name, const Twine &Title) LLVM_OVERRIDE;
337 void viewGraph() LLVM_OVERRIDE;
340 // Top-Level entry points for the schedule() driver...
342 /// Call ScheduleDAGInstrs::buildSchedGraph with register pressure tracking
343 /// enabled. This sets up three trackers. RPTracker will cover the entire DAG
344 /// region, TopTracker and BottomTracker will be initialized to the top and
345 /// bottom of the DAG region without covereing any unscheduled instruction.
346 void buildDAGWithRegPressure();
348 /// Apply each ScheduleDAGMutation step in order. This allows different
349 /// instances of ScheduleDAGMI to perform custom DAG postprocessing.
350 void postprocessDAG();
352 /// Release ExitSU predecessors and setup scheduler queues.
353 void initQueues(ArrayRef<SUnit*> TopRoots, ArrayRef<SUnit*> BotRoots);
355 /// Move an instruction and update register pressure.
356 void scheduleMI(SUnit *SU, bool IsTopNode);
358 /// Update scheduler DAG and queues after scheduling an instruction.
359 void updateQueues(SUnit *SU, bool IsTopNode);
361 /// Reinsert debug_values recorded in ScheduleDAGInstrs::DbgValues.
362 void placeDebugValues();
364 /// \brief dump the scheduled Sequence.
365 void dumpSchedule() const;
369 void initRegPressure();
371 void updateScheduledPressure(const std::vector<unsigned> &NewMaxPressure);
373 bool checkSchedLimit();
375 void findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
376 SmallVectorImpl<SUnit*> &BotRoots);
378 void releaseSucc(SUnit *SU, SDep *SuccEdge);
379 void releaseSuccessors(SUnit *SU);
380 void releasePred(SUnit *SU, SDep *PredEdge);
381 void releasePredecessors(SUnit *SU);