mi-sched: Suppress register pressure tracking when the scheduling window is too small.
[oota-llvm.git] / include / llvm / CodeGen / MachineScheduler.h
1 //==- MachineScheduler.h - MachineInstr Scheduling Pass ----------*- C++ -*-==//
2 //
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 // 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:
13 //
14 // static ScheduleDAGInstrs *createCustomMachineSched(MachineSchedContext *C) {
15 //  return new CustomMachineScheduler(C);
16 // }
17 // static MachineSchedRegistry
18 // SchedCustomRegistry("custom", "Run my target's custom scheduler",
19 //                     createCustomMachineSched);
20 //
21 // Inside <Target>PassConfig:
22 //   enablePass(&MachineSchedulerID);
23 //   MachineSchedRegistry::setDefault(createCustomMachineSched);
24 //
25 //===----------------------------------------------------------------------===//
26
27 #ifndef LLVM_CODEGEN_MACHINESCHEDULER_H
28 #define LLVM_CODEGEN_MACHINESCHEDULER_H
29
30 #include "llvm/CodeGen/MachinePassRegistry.h"
31 #include "llvm/CodeGen/RegisterPressure.h"
32 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
33
34 namespace llvm {
35
36 extern cl::opt<bool> ForceTopDown;
37 extern cl::opt<bool> ForceBottomUp;
38
39 class AliasAnalysis;
40 class LiveIntervals;
41 class MachineDominatorTree;
42 class MachineLoopInfo;
43 class RegisterClassInfo;
44 class ScheduleDAGInstrs;
45 class SchedDFSResult;
46
47 /// MachineSchedContext provides enough context from the MachineScheduler pass
48 /// for the target to instantiate a scheduler.
49 struct MachineSchedContext {
50   MachineFunction *MF;
51   const MachineLoopInfo *MLI;
52   const MachineDominatorTree *MDT;
53   const TargetPassConfig *PassConfig;
54   AliasAnalysis *AA;
55   LiveIntervals *LIS;
56
57   RegisterClassInfo *RegClassInfo;
58
59   MachineSchedContext();
60   virtual ~MachineSchedContext();
61 };
62
63 /// MachineSchedRegistry provides a selection of available machine instruction
64 /// schedulers.
65 class MachineSchedRegistry : public MachinePassRegistryNode {
66 public:
67   typedef ScheduleDAGInstrs *(*ScheduleDAGCtor)(MachineSchedContext *);
68
69   // RegisterPassParser requires a (misnamed) FunctionPassCtor type.
70   typedef ScheduleDAGCtor FunctionPassCtor;
71
72   static MachinePassRegistry Registry;
73
74   MachineSchedRegistry(const char *N, const char *D, ScheduleDAGCtor C)
75     : MachinePassRegistryNode(N, D, (MachinePassCtor)C) {
76     Registry.Add(this);
77   }
78   ~MachineSchedRegistry() { Registry.Remove(this); }
79
80   // Accessors.
81   //
82   MachineSchedRegistry *getNext() const {
83     return (MachineSchedRegistry *)MachinePassRegistryNode::getNext();
84   }
85   static MachineSchedRegistry *getList() {
86     return (MachineSchedRegistry *)Registry.getList();
87   }
88   static ScheduleDAGCtor getDefault() {
89     return (ScheduleDAGCtor)Registry.getDefault();
90   }
91   static void setDefault(ScheduleDAGCtor C) {
92     Registry.setDefault((MachinePassCtor)C);
93   }
94   static void setDefault(StringRef Name) {
95     Registry.setDefault(Name);
96   }
97   static void setListener(MachinePassRegistryListener *L) {
98     Registry.setListener(L);
99   }
100 };
101
102 class ScheduleDAGMI;
103
104 /// MachineSchedStrategy - Interface to the scheduling algorithm used by
105 /// ScheduleDAGMI.
106 class MachineSchedStrategy {
107 public:
108   virtual ~MachineSchedStrategy() {}
109
110   /// Check if pressure tracking is needed before building the DAG and
111   /// initializing this strategy.
112   virtual bool shouldTrackPressure(unsigned NumRegionInstrs) { return true; }
113
114   /// Initialize the strategy after building the DAG for a new region.
115   virtual void initialize(ScheduleDAGMI *DAG) = 0;
116
117   /// Notify this strategy that all roots have been released (including those
118   /// that depend on EntrySU or ExitSU).
119   virtual void registerRoots() {}
120
121   /// Pick the next node to schedule, or return NULL. Set IsTopNode to true to
122   /// schedule the node at the top of the unscheduled region. Otherwise it will
123   /// be scheduled at the bottom.
124   virtual SUnit *pickNode(bool &IsTopNode) = 0;
125
126   /// \brief Scheduler callback to notify that a new subtree is scheduled.
127   virtual void scheduleTree(unsigned SubtreeID) {}
128
129   /// Notify MachineSchedStrategy that ScheduleDAGMI has scheduled an
130   /// instruction and updated scheduled/remaining flags in the DAG nodes.
131   virtual void schedNode(SUnit *SU, bool IsTopNode) = 0;
132
133   /// When all predecessor dependencies have been resolved, free this node for
134   /// top-down scheduling.
135   virtual void releaseTopNode(SUnit *SU) = 0;
136   /// When all successor dependencies have been resolved, free this node for
137   /// bottom-up scheduling.
138   virtual void releaseBottomNode(SUnit *SU) = 0;
139 };
140
141 /// ReadyQueue encapsulates vector of "ready" SUnits with basic convenience
142 /// methods for pushing and removing nodes. ReadyQueue's are uniquely identified
143 /// by an ID. SUnit::NodeQueueId is a mask of the ReadyQueues the SUnit is in.
144 ///
145 /// This is a convenience class that may be used by implementations of
146 /// MachineSchedStrategy.
147 class ReadyQueue {
148   unsigned ID;
149   std::string Name;
150   std::vector<SUnit*> Queue;
151
152 public:
153   ReadyQueue(unsigned id, const Twine &name): ID(id), Name(name.str()) {}
154
155   unsigned getID() const { return ID; }
156
157   StringRef getName() const { return Name; }
158
159   // SU is in this queue if it's NodeQueueID is a superset of this ID.
160   bool isInQueue(SUnit *SU) const { return (SU->NodeQueueId & ID); }
161
162   bool empty() const { return Queue.empty(); }
163
164   void clear() { Queue.clear(); }
165
166   unsigned size() const { return Queue.size(); }
167
168   typedef std::vector<SUnit*>::iterator iterator;
169
170   iterator begin() { return Queue.begin(); }
171
172   iterator end() { return Queue.end(); }
173
174   ArrayRef<SUnit*> elements() { return Queue; }
175
176   iterator find(SUnit *SU) {
177     return std::find(Queue.begin(), Queue.end(), SU);
178   }
179
180   void push(SUnit *SU) {
181     Queue.push_back(SU);
182     SU->NodeQueueId |= ID;
183   }
184
185   iterator remove(iterator I) {
186     (*I)->NodeQueueId &= ~ID;
187     *I = Queue.back();
188     unsigned idx = I - Queue.begin();
189     Queue.pop_back();
190     return Queue.begin() + idx;
191   }
192
193 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
194   void dump();
195 #endif
196 };
197
198 /// Mutate the DAG as a postpass after normal DAG building.
199 class ScheduleDAGMutation {
200 public:
201   virtual ~ScheduleDAGMutation() {}
202
203   virtual void apply(ScheduleDAGMI *DAG) = 0;
204 };
205
206 /// ScheduleDAGMI is an implementation of ScheduleDAGInstrs that schedules
207 /// machine instructions while updating LiveIntervals and tracking regpressure.
208 class ScheduleDAGMI : public ScheduleDAGInstrs {
209 protected:
210   AliasAnalysis *AA;
211   RegisterClassInfo *RegClassInfo;
212   MachineSchedStrategy *SchedImpl;
213
214   /// Information about DAG subtrees. If DFSResult is NULL, then SchedulerTrees
215   /// will be empty.
216   SchedDFSResult *DFSResult;
217   BitVector ScheduledTrees;
218
219   /// Topo - A topological ordering for SUnits which permits fast IsReachable
220   /// and similar queries.
221   ScheduleDAGTopologicalSort Topo;
222
223   /// Ordered list of DAG postprocessing steps.
224   std::vector<ScheduleDAGMutation*> Mutations;
225
226   MachineBasicBlock::iterator LiveRegionEnd;
227
228   // Map each SU to its summary of pressure changes. This array is updated for
229   // liveness during bottom-up scheduling. Top-down scheduling may proceed but
230   // has no affect on the pressure diffs.
231   PressureDiffs SUPressureDiffs;
232
233   /// Register pressure in this region computed by initRegPressure.
234   bool ShouldTrackPressure;
235   IntervalPressure RegPressure;
236   RegPressureTracker RPTracker;
237
238   /// List of pressure sets that exceed the target's pressure limit before
239   /// scheduling, listed in increasing set ID order. Each pressure set is paired
240   /// with its max pressure in the currently scheduled regions.
241   std::vector<PressureChange> RegionCriticalPSets;
242
243   /// The top of the unscheduled zone.
244   MachineBasicBlock::iterator CurrentTop;
245   IntervalPressure TopPressure;
246   RegPressureTracker TopRPTracker;
247
248   /// The bottom of the unscheduled zone.
249   MachineBasicBlock::iterator CurrentBottom;
250   IntervalPressure BotPressure;
251   RegPressureTracker BotRPTracker;
252
253   /// Record the next node in a scheduled cluster.
254   const SUnit *NextClusterPred;
255   const SUnit *NextClusterSucc;
256
257 #ifndef NDEBUG
258   /// The number of instructions scheduled so far. Used to cut off the
259   /// scheduler at the point determined by misched-cutoff.
260   unsigned NumInstrsScheduled;
261 #endif
262
263 public:
264   ScheduleDAGMI(MachineSchedContext *C, MachineSchedStrategy *S):
265     ScheduleDAGInstrs(*C->MF, *C->MLI, *C->MDT, /*IsPostRA=*/false, C->LIS),
266     AA(C->AA), RegClassInfo(C->RegClassInfo), SchedImpl(S), DFSResult(0),
267     Topo(SUnits, &ExitSU), ShouldTrackPressure(false),
268     RPTracker(RegPressure), CurrentTop(), TopRPTracker(TopPressure),
269     CurrentBottom(), BotRPTracker(BotPressure),
270     NextClusterPred(NULL), NextClusterSucc(NULL) {
271 #ifndef NDEBUG
272     NumInstrsScheduled = 0;
273 #endif
274   }
275
276   virtual ~ScheduleDAGMI();
277
278   /// \brief Return true if register pressure tracking is enabled.
279   bool isTrackingPressure() const { return ShouldTrackPressure; }
280
281   /// Add a postprocessing step to the DAG builder.
282   /// Mutations are applied in the order that they are added after normal DAG
283   /// building and before MachineSchedStrategy initialization.
284   ///
285   /// ScheduleDAGMI takes ownership of the Mutation object.
286   void addMutation(ScheduleDAGMutation *Mutation) {
287     Mutations.push_back(Mutation);
288   }
289
290   /// \brief True if an edge can be added from PredSU to SuccSU without creating
291   /// a cycle.
292   bool canAddEdge(SUnit *SuccSU, SUnit *PredSU);
293
294   /// \brief Add a DAG edge to the given SU with the given predecessor
295   /// dependence data.
296   ///
297   /// \returns true if the edge may be added without creating a cycle OR if an
298   /// equivalent edge already existed (false indicates failure).
299   bool addEdge(SUnit *SuccSU, const SDep &PredDep);
300
301   MachineBasicBlock::iterator top() const { return CurrentTop; }
302   MachineBasicBlock::iterator bottom() const { return CurrentBottom; }
303
304   /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
305   /// region. This covers all instructions in a block, while schedule() may only
306   /// cover a subset.
307   void enterRegion(MachineBasicBlock *bb,
308                    MachineBasicBlock::iterator begin,
309                    MachineBasicBlock::iterator end,
310                    unsigned regioninstrs) LLVM_OVERRIDE;
311
312   /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
313   /// reorderable instructions.
314   virtual void schedule();
315
316   /// Change the position of an instruction within the basic block and update
317   /// live ranges and region boundary iterators.
318   void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos);
319
320   /// Get current register pressure for the top scheduled instructions.
321   const IntervalPressure &getTopPressure() const { return TopPressure; }
322   const RegPressureTracker &getTopRPTracker() const { return TopRPTracker; }
323
324   /// Get current register pressure for the bottom scheduled instructions.
325   const IntervalPressure &getBotPressure() const { return BotPressure; }
326   const RegPressureTracker &getBotRPTracker() const { return BotRPTracker; }
327
328   /// Get register pressure for the entire scheduling region before scheduling.
329   const IntervalPressure &getRegPressure() const { return RegPressure; }
330
331   const std::vector<PressureChange> &getRegionCriticalPSets() const {
332     return RegionCriticalPSets;
333   }
334
335   PressureDiff &getPressureDiff(const SUnit *SU) {
336     return SUPressureDiffs[SU->NodeNum];
337   }
338
339   const SUnit *getNextClusterPred() const { return NextClusterPred; }
340
341   const SUnit *getNextClusterSucc() const { return NextClusterSucc; }
342
343   /// Compute a DFSResult after DAG building is complete, and before any
344   /// queue comparisons.
345   void computeDFSResult();
346
347   /// Return a non-null DFS result if the scheduling strategy initialized it.
348   const SchedDFSResult *getDFSResult() const { return DFSResult; }
349
350   BitVector &getScheduledTrees() { return ScheduledTrees; }
351
352   /// Compute the cyclic critical path through the DAG.
353   unsigned computeCyclicCriticalPath();
354
355   void viewGraph(const Twine &Name, const Twine &Title) LLVM_OVERRIDE;
356   void viewGraph() LLVM_OVERRIDE;
357
358 protected:
359   // Top-Level entry points for the schedule() driver...
360
361   /// Call ScheduleDAGInstrs::buildSchedGraph with register pressure tracking
362   /// enabled. This sets up three trackers. RPTracker will cover the entire DAG
363   /// region, TopTracker and BottomTracker will be initialized to the top and
364   /// bottom of the DAG region without covereing any unscheduled instruction.
365   void buildDAGWithRegPressure();
366
367   /// Apply each ScheduleDAGMutation step in order. This allows different
368   /// instances of ScheduleDAGMI to perform custom DAG postprocessing.
369   void postprocessDAG();
370
371   /// Release ExitSU predecessors and setup scheduler queues.
372   void initQueues(ArrayRef<SUnit*> TopRoots, ArrayRef<SUnit*> BotRoots);
373
374   /// Move an instruction and update register pressure.
375   void scheduleMI(SUnit *SU, bool IsTopNode);
376
377   /// Update scheduler DAG and queues after scheduling an instruction.
378   void updateQueues(SUnit *SU, bool IsTopNode);
379
380   /// Reinsert debug_values recorded in ScheduleDAGInstrs::DbgValues.
381   void placeDebugValues();
382
383   /// \brief dump the scheduled Sequence.
384   void dumpSchedule() const;
385
386   // Lesser helpers...
387
388   void initRegPressure();
389
390   void updatePressureDiffs(ArrayRef<unsigned> LiveUses);
391
392   void updateScheduledPressure(const std::vector<unsigned> &NewMaxPressure);
393
394   bool checkSchedLimit();
395
396   void findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
397                              SmallVectorImpl<SUnit*> &BotRoots);
398
399   void releaseSucc(SUnit *SU, SDep *SuccEdge);
400   void releaseSuccessors(SUnit *SU);
401   void releasePred(SUnit *SU, SDep *PredEdge);
402   void releasePredecessors(SUnit *SU);
403 };
404
405 } // namespace llvm
406
407 #endif