Make MachineScheduler debug output less confusing.
[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 an interface for customizing the standard MachineScheduler
11 // pass. Note that the entire pass may be replaced as follows:
12 //
13 // <Target>TargetMachine::createPassConfig(PassManagerBase &PM) {
14 //   PM.substitutePass(&MachineSchedulerID, &CustomSchedulerPassID);
15 //   ...}
16 //
17 // The MachineScheduler pass is only responsible for choosing the regions to be
18 // scheduled. Targets can override the DAG builder and scheduler without
19 // replacing the pass as follows:
20 //
21 // ScheduleDAGInstrs *<Target>PassConfig::
22 // createMachineScheduler(MachineSchedContext *C) {
23 //   return new CustomMachineScheduler(C);
24 // }
25 //
26 // The default scheduler, ScheduleDAGMILive, builds the DAG and drives list
27 // scheduling while updating the instruction stream, register pressure, and live
28 // intervals. Most targets don't need to override the DAG builder and list
29 // schedulier, but subtargets that require custom scheduling heuristics may
30 // plugin an alternate MachineSchedStrategy. The strategy is responsible for
31 // selecting the highest priority node from the list:
32 //
33 // ScheduleDAGInstrs *<Target>PassConfig::
34 // createMachineScheduler(MachineSchedContext *C) {
35 //   return new ScheduleDAGMI(C, CustomStrategy(C));
36 // }
37 //
38 // The DAG builder can also be customized in a sense by adding DAG mutations
39 // that will run after DAG building and before list scheduling. DAG mutations
40 // can adjust dependencies based on target-specific knowledge or add weak edges
41 // to aid heuristics:
42 //
43 // ScheduleDAGInstrs *<Target>PassConfig::
44 // createMachineScheduler(MachineSchedContext *C) {
45 //   ScheduleDAGMI *DAG = new ScheduleDAGMI(C, CustomStrategy(C));
46 //   DAG->addMutation(new CustomDependencies(DAG->TII, DAG->TRI));
47 //   return DAG;
48 // }
49 //
50 // A target that supports alternative schedulers can use the
51 // MachineSchedRegistry to allow command line selection. This can be done by
52 // implementing the following boilerplate:
53 //
54 // static ScheduleDAGInstrs *createCustomMachineSched(MachineSchedContext *C) {
55 //  return new CustomMachineScheduler(C);
56 // }
57 // static MachineSchedRegistry
58 // SchedCustomRegistry("custom", "Run my target's custom scheduler",
59 //                     createCustomMachineSched);
60 //
61 //
62 // Finally, subtargets that don't need to implement custom heuristics but would
63 // like to configure the GenericScheduler's policy for a given scheduler region,
64 // including scheduling direction and register pressure tracking policy, can do
65 // this:
66 //
67 // void <SubTarget>Subtarget::
68 // overrideSchedPolicy(MachineSchedPolicy &Policy,
69 //                     MachineInstr *begin,
70 //                     MachineInstr *end,
71 //                     unsigned NumRegionInstrs) const {
72 //   Policy.<Flag> = true;
73 // }
74 //
75 //===----------------------------------------------------------------------===//
76
77 #ifndef LLVM_CODEGEN_MACHINESCHEDULER_H
78 #define LLVM_CODEGEN_MACHINESCHEDULER_H
79
80 #include "llvm/Analysis/AliasAnalysis.h"
81 #include "llvm/CodeGen/MachinePassRegistry.h"
82 #include "llvm/CodeGen/RegisterPressure.h"
83 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
84 #include <memory>
85
86 namespace llvm {
87
88 extern cl::opt<bool> ForceTopDown;
89 extern cl::opt<bool> ForceBottomUp;
90
91 class LiveIntervals;
92 class MachineDominatorTree;
93 class MachineLoopInfo;
94 class RegisterClassInfo;
95 class ScheduleDAGInstrs;
96 class SchedDFSResult;
97 class ScheduleHazardRecognizer;
98
99 /// MachineSchedContext provides enough context from the MachineScheduler pass
100 /// for the target to instantiate a scheduler.
101 struct MachineSchedContext {
102   MachineFunction *MF;
103   const MachineLoopInfo *MLI;
104   const MachineDominatorTree *MDT;
105   const TargetPassConfig *PassConfig;
106   AliasAnalysis *AA;
107   LiveIntervals *LIS;
108
109   RegisterClassInfo *RegClassInfo;
110
111   MachineSchedContext();
112   virtual ~MachineSchedContext();
113 };
114
115 /// MachineSchedRegistry provides a selection of available machine instruction
116 /// schedulers.
117 class MachineSchedRegistry : public MachinePassRegistryNode {
118 public:
119   typedef ScheduleDAGInstrs *(*ScheduleDAGCtor)(MachineSchedContext *);
120
121   // RegisterPassParser requires a (misnamed) FunctionPassCtor type.
122   typedef ScheduleDAGCtor FunctionPassCtor;
123
124   static MachinePassRegistry Registry;
125
126   MachineSchedRegistry(const char *N, const char *D, ScheduleDAGCtor C)
127     : MachinePassRegistryNode(N, D, (MachinePassCtor)C) {
128     Registry.Add(this);
129   }
130   ~MachineSchedRegistry() { Registry.Remove(this); }
131
132   // Accessors.
133   //
134   MachineSchedRegistry *getNext() const {
135     return (MachineSchedRegistry *)MachinePassRegistryNode::getNext();
136   }
137   static MachineSchedRegistry *getList() {
138     return (MachineSchedRegistry *)Registry.getList();
139   }
140   static void setListener(MachinePassRegistryListener *L) {
141     Registry.setListener(L);
142   }
143 };
144
145 class ScheduleDAGMI;
146
147 /// Define a generic scheduling policy for targets that don't provide their own
148 /// MachineSchedStrategy. This can be overriden for each scheduling region
149 /// before building the DAG.
150 struct MachineSchedPolicy {
151   // Allow the scheduler to disable register pressure tracking.
152   bool ShouldTrackPressure;
153
154   // Allow the scheduler to force top-down or bottom-up scheduling. If neither
155   // is true, the scheduler runs in both directions and converges.
156   bool OnlyTopDown;
157   bool OnlyBottomUp;
158
159   MachineSchedPolicy(): ShouldTrackPressure(false), OnlyTopDown(false),
160     OnlyBottomUp(false) {}
161 };
162
163 /// MachineSchedStrategy - Interface to the scheduling algorithm used by
164 /// ScheduleDAGMI.
165 ///
166 /// Initialization sequence:
167 ///   initPolicy -> shouldTrackPressure -> initialize(DAG) -> registerRoots
168 class MachineSchedStrategy {
169   virtual void anchor();
170 public:
171   virtual ~MachineSchedStrategy() {}
172
173   /// Optionally override the per-region scheduling policy.
174   virtual void initPolicy(MachineBasicBlock::iterator Begin,
175                           MachineBasicBlock::iterator End,
176                           unsigned NumRegionInstrs) {}
177
178   virtual void dumpPolicy() {}
179
180   /// Check if pressure tracking is needed before building the DAG and
181   /// initializing this strategy. Called after initPolicy.
182   virtual bool shouldTrackPressure() const { return true; }
183
184   /// Initialize the strategy after building the DAG for a new region.
185   virtual void initialize(ScheduleDAGMI *DAG) = 0;
186
187   /// Notify this strategy that all roots have been released (including those
188   /// that depend on EntrySU or ExitSU).
189   virtual void registerRoots() {}
190
191   /// Pick the next node to schedule, or return NULL. Set IsTopNode to true to
192   /// schedule the node at the top of the unscheduled region. Otherwise it will
193   /// be scheduled at the bottom.
194   virtual SUnit *pickNode(bool &IsTopNode) = 0;
195
196   /// \brief Scheduler callback to notify that a new subtree is scheduled.
197   virtual void scheduleTree(unsigned SubtreeID) {}
198
199   /// Notify MachineSchedStrategy that ScheduleDAGMI has scheduled an
200   /// instruction and updated scheduled/remaining flags in the DAG nodes.
201   virtual void schedNode(SUnit *SU, bool IsTopNode) = 0;
202
203   /// When all predecessor dependencies have been resolved, free this node for
204   /// top-down scheduling.
205   virtual void releaseTopNode(SUnit *SU) = 0;
206   /// When all successor dependencies have been resolved, free this node for
207   /// bottom-up scheduling.
208   virtual void releaseBottomNode(SUnit *SU) = 0;
209 };
210
211 /// Mutate the DAG as a postpass after normal DAG building.
212 class ScheduleDAGMutation {
213   virtual void anchor();
214 public:
215   virtual ~ScheduleDAGMutation() {}
216
217   virtual void apply(ScheduleDAGMI *DAG) = 0;
218 };
219
220 /// ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply
221 /// schedules machine instructions according to the given MachineSchedStrategy
222 /// without much extra book-keeping. This is the common functionality between
223 /// PreRA and PostRA MachineScheduler.
224 class ScheduleDAGMI : public ScheduleDAGInstrs {
225 protected:
226   AliasAnalysis *AA;
227   std::unique_ptr<MachineSchedStrategy> SchedImpl;
228
229   /// Topo - A topological ordering for SUnits which permits fast IsReachable
230   /// and similar queries.
231   ScheduleDAGTopologicalSort Topo;
232
233   /// Ordered list of DAG postprocessing steps.
234   std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;
235
236   /// The top of the unscheduled zone.
237   MachineBasicBlock::iterator CurrentTop;
238
239   /// The bottom of the unscheduled zone.
240   MachineBasicBlock::iterator CurrentBottom;
241
242   /// Record the next node in a scheduled cluster.
243   const SUnit *NextClusterPred;
244   const SUnit *NextClusterSucc;
245
246 #ifndef NDEBUG
247   /// The number of instructions scheduled so far. Used to cut off the
248   /// scheduler at the point determined by misched-cutoff.
249   unsigned NumInstrsScheduled;
250 #endif
251 public:
252   ScheduleDAGMI(MachineSchedContext *C, std::unique_ptr<MachineSchedStrategy> S,
253                 bool IsPostRA)
254       : ScheduleDAGInstrs(*C->MF, C->MLI, IsPostRA,
255                           /*RemoveKillFlags=*/IsPostRA, C->LIS),
256         AA(C->AA), SchedImpl(std::move(S)), Topo(SUnits, &ExitSU), CurrentTop(),
257         CurrentBottom(), NextClusterPred(nullptr), NextClusterSucc(nullptr) {
258 #ifndef NDEBUG
259     NumInstrsScheduled = 0;
260 #endif
261   }
262
263   // Provide a vtable anchor
264   ~ScheduleDAGMI() override;
265
266   /// Return true if this DAG supports VReg liveness and RegPressure.
267   virtual bool hasVRegLiveness() const { return false; }
268
269   /// Add a postprocessing step to the DAG builder.
270   /// Mutations are applied in the order that they are added after normal DAG
271   /// building and before MachineSchedStrategy initialization.
272   ///
273   /// ScheduleDAGMI takes ownership of the Mutation object.
274   void addMutation(std::unique_ptr<ScheduleDAGMutation> Mutation) {
275     Mutations.push_back(std::move(Mutation));
276   }
277
278   /// \brief True if an edge can be added from PredSU to SuccSU without creating
279   /// a cycle.
280   bool canAddEdge(SUnit *SuccSU, SUnit *PredSU);
281
282   /// \brief Add a DAG edge to the given SU with the given predecessor
283   /// dependence data.
284   ///
285   /// \returns true if the edge may be added without creating a cycle OR if an
286   /// equivalent edge already existed (false indicates failure).
287   bool addEdge(SUnit *SuccSU, const SDep &PredDep);
288
289   MachineBasicBlock::iterator top() const { return CurrentTop; }
290   MachineBasicBlock::iterator bottom() const { return CurrentBottom; }
291
292   /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
293   /// region. This covers all instructions in a block, while schedule() may only
294   /// cover a subset.
295   void enterRegion(MachineBasicBlock *bb,
296                    MachineBasicBlock::iterator begin,
297                    MachineBasicBlock::iterator end,
298                    unsigned regioninstrs) override;
299
300   /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
301   /// reorderable instructions.
302   void schedule() override;
303
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);
307
308   const SUnit *getNextClusterPred() const { return NextClusterPred; }
309
310   const SUnit *getNextClusterSucc() const { return NextClusterSucc; }
311
312   void viewGraph(const Twine &Name, const Twine &Title) override;
313   void viewGraph() override;
314
315 protected:
316   // Top-Level entry points for the schedule() driver...
317
318   /// Apply each ScheduleDAGMutation step in order. This allows different
319   /// instances of ScheduleDAGMI to perform custom DAG postprocessing.
320   void postprocessDAG();
321
322   /// Release ExitSU predecessors and setup scheduler queues.
323   void initQueues(ArrayRef<SUnit*> TopRoots, ArrayRef<SUnit*> BotRoots);
324
325   /// Update scheduler DAG and queues after scheduling an instruction.
326   void updateQueues(SUnit *SU, bool IsTopNode);
327
328   /// Reinsert debug_values recorded in ScheduleDAGInstrs::DbgValues.
329   void placeDebugValues();
330
331   /// \brief dump the scheduled Sequence.
332   void dumpSchedule() const;
333
334   // Lesser helpers...
335   bool checkSchedLimit();
336
337   void findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
338                              SmallVectorImpl<SUnit*> &BotRoots);
339
340   void releaseSucc(SUnit *SU, SDep *SuccEdge);
341   void releaseSuccessors(SUnit *SU);
342   void releasePred(SUnit *SU, SDep *PredEdge);
343   void releasePredecessors(SUnit *SU);
344 };
345
346 /// ScheduleDAGMILive is an implementation of ScheduleDAGInstrs that schedules
347 /// machine instructions while updating LiveIntervals and tracking regpressure.
348 class ScheduleDAGMILive : public ScheduleDAGMI {
349 protected:
350   RegisterClassInfo *RegClassInfo;
351
352   /// Information about DAG subtrees. If DFSResult is NULL, then SchedulerTrees
353   /// will be empty.
354   SchedDFSResult *DFSResult;
355   BitVector ScheduledTrees;
356
357   MachineBasicBlock::iterator LiveRegionEnd;
358
359   // Map each SU to its summary of pressure changes. This array is updated for
360   // liveness during bottom-up scheduling. Top-down scheduling may proceed but
361   // has no affect on the pressure diffs.
362   PressureDiffs SUPressureDiffs;
363
364   /// Register pressure in this region computed by initRegPressure.
365   bool ShouldTrackPressure;
366   IntervalPressure RegPressure;
367   RegPressureTracker RPTracker;
368
369   /// List of pressure sets that exceed the target's pressure limit before
370   /// scheduling, listed in increasing set ID order. Each pressure set is paired
371   /// with its max pressure in the currently scheduled regions.
372   std::vector<PressureChange> RegionCriticalPSets;
373
374   /// The top of the unscheduled zone.
375   IntervalPressure TopPressure;
376   RegPressureTracker TopRPTracker;
377
378   /// The bottom of the unscheduled zone.
379   IntervalPressure BotPressure;
380   RegPressureTracker BotRPTracker;
381
382 public:
383   ScheduleDAGMILive(MachineSchedContext *C,
384                     std::unique_ptr<MachineSchedStrategy> S)
385       : ScheduleDAGMI(C, std::move(S), /*IsPostRA=*/false),
386         RegClassInfo(C->RegClassInfo), DFSResult(nullptr),
387         ShouldTrackPressure(false), RPTracker(RegPressure),
388         TopRPTracker(TopPressure), BotRPTracker(BotPressure) {}
389
390   ~ScheduleDAGMILive() override;
391
392   /// Return true if this DAG supports VReg liveness and RegPressure.
393   bool hasVRegLiveness() const override { return true; }
394
395   /// \brief Return true if register pressure tracking is enabled.
396   bool isTrackingPressure() const { return ShouldTrackPressure; }
397
398   /// Get current register pressure for the top scheduled instructions.
399   const IntervalPressure &getTopPressure() const { return TopPressure; }
400   const RegPressureTracker &getTopRPTracker() const { return TopRPTracker; }
401
402   /// Get current register pressure for the bottom scheduled instructions.
403   const IntervalPressure &getBotPressure() const { return BotPressure; }
404   const RegPressureTracker &getBotRPTracker() const { return BotRPTracker; }
405
406   /// Get register pressure for the entire scheduling region before scheduling.
407   const IntervalPressure &getRegPressure() const { return RegPressure; }
408
409   const std::vector<PressureChange> &getRegionCriticalPSets() const {
410     return RegionCriticalPSets;
411   }
412
413   PressureDiff &getPressureDiff(const SUnit *SU) {
414     return SUPressureDiffs[SU->NodeNum];
415   }
416
417   /// Compute a DFSResult after DAG building is complete, and before any
418   /// queue comparisons.
419   void computeDFSResult();
420
421   /// Return a non-null DFS result if the scheduling strategy initialized it.
422   const SchedDFSResult *getDFSResult() const { return DFSResult; }
423
424   BitVector &getScheduledTrees() { return ScheduledTrees; }
425
426   /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
427   /// region. This covers all instructions in a block, while schedule() may only
428   /// cover a subset.
429   void enterRegion(MachineBasicBlock *bb,
430                    MachineBasicBlock::iterator begin,
431                    MachineBasicBlock::iterator end,
432                    unsigned regioninstrs) override;
433
434   /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
435   /// reorderable instructions.
436   void schedule() override;
437
438   /// Compute the cyclic critical path through the DAG.
439   unsigned computeCyclicCriticalPath();
440
441 protected:
442   // Top-Level entry points for the schedule() driver...
443
444   /// Call ScheduleDAGInstrs::buildSchedGraph with register pressure tracking
445   /// enabled. This sets up three trackers. RPTracker will cover the entire DAG
446   /// region, TopTracker and BottomTracker will be initialized to the top and
447   /// bottom of the DAG region without covereing any unscheduled instruction.
448   void buildDAGWithRegPressure();
449
450   /// Move an instruction and update register pressure.
451   void scheduleMI(SUnit *SU, bool IsTopNode);
452
453   // Lesser helpers...
454
455   void initRegPressure();
456
457   void updatePressureDiffs(ArrayRef<unsigned> LiveUses);
458
459   void updateScheduledPressure(const SUnit *SU,
460                                const std::vector<unsigned> &NewMaxPressure);
461 };
462
463 //===----------------------------------------------------------------------===//
464 ///
465 /// Helpers for implementing custom MachineSchedStrategy classes. These take
466 /// care of the book-keeping associated with list scheduling heuristics.
467 ///
468 //===----------------------------------------------------------------------===//
469
470 /// ReadyQueue encapsulates vector of "ready" SUnits with basic convenience
471 /// methods for pushing and removing nodes. ReadyQueue's are uniquely identified
472 /// by an ID. SUnit::NodeQueueId is a mask of the ReadyQueues the SUnit is in.
473 ///
474 /// This is a convenience class that may be used by implementations of
475 /// MachineSchedStrategy.
476 class ReadyQueue {
477   unsigned ID;
478   std::string Name;
479   std::vector<SUnit*> Queue;
480
481 public:
482   ReadyQueue(unsigned id, const Twine &name): ID(id), Name(name.str()) {}
483
484   unsigned getID() const { return ID; }
485
486   StringRef getName() const { return Name; }
487
488   // SU is in this queue if it's NodeQueueID is a superset of this ID.
489   bool isInQueue(SUnit *SU) const { return (SU->NodeQueueId & ID); }
490
491   bool empty() const { return Queue.empty(); }
492
493   void clear() { Queue.clear(); }
494
495   unsigned size() const { return Queue.size(); }
496
497   typedef std::vector<SUnit*>::iterator iterator;
498
499   iterator begin() { return Queue.begin(); }
500
501   iterator end() { return Queue.end(); }
502
503   ArrayRef<SUnit*> elements() { return Queue; }
504
505   iterator find(SUnit *SU) {
506     return std::find(Queue.begin(), Queue.end(), SU);
507   }
508
509   void push(SUnit *SU) {
510     Queue.push_back(SU);
511     SU->NodeQueueId |= ID;
512   }
513
514   iterator remove(iterator I) {
515     (*I)->NodeQueueId &= ~ID;
516     *I = Queue.back();
517     unsigned idx = I - Queue.begin();
518     Queue.pop_back();
519     return Queue.begin() + idx;
520   }
521
522   void dump();
523 };
524
525 /// Summarize the unscheduled region.
526 struct SchedRemainder {
527   // Critical path through the DAG in expected latency.
528   unsigned CriticalPath;
529   unsigned CyclicCritPath;
530
531   // Scaled count of micro-ops left to schedule.
532   unsigned RemIssueCount;
533
534   bool IsAcyclicLatencyLimited;
535
536   // Unscheduled resources
537   SmallVector<unsigned, 16> RemainingCounts;
538
539   void reset() {
540     CriticalPath = 0;
541     CyclicCritPath = 0;
542     RemIssueCount = 0;
543     IsAcyclicLatencyLimited = false;
544     RemainingCounts.clear();
545   }
546
547   SchedRemainder() { reset(); }
548
549   void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
550 };
551
552 /// Each Scheduling boundary is associated with ready queues. It tracks the
553 /// current cycle in the direction of movement, and maintains the state
554 /// of "hazards" and other interlocks at the current cycle.
555 class SchedBoundary {
556 public:
557   /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
558   enum {
559     TopQID = 1,
560     BotQID = 2,
561     LogMaxQID = 2
562   };
563
564   ScheduleDAGMI *DAG;
565   const TargetSchedModel *SchedModel;
566   SchedRemainder *Rem;
567
568   ReadyQueue Available;
569   ReadyQueue Pending;
570
571   ScheduleHazardRecognizer *HazardRec;
572
573 private:
574   /// True if the pending Q should be checked/updated before scheduling another
575   /// instruction.
576   bool CheckPending;
577
578   // For heuristics, keep a list of the nodes that immediately depend on the
579   // most recently scheduled node.
580   SmallPtrSet<const SUnit*, 8> NextSUs;
581
582   /// Number of cycles it takes to issue the instructions scheduled in this
583   /// zone. It is defined as: scheduled-micro-ops / issue-width + stalls.
584   /// See getStalls().
585   unsigned CurrCycle;
586
587   /// Micro-ops issued in the current cycle
588   unsigned CurrMOps;
589
590   /// MinReadyCycle - Cycle of the soonest available instruction.
591   unsigned MinReadyCycle;
592
593   // The expected latency of the critical path in this scheduled zone.
594   unsigned ExpectedLatency;
595
596   // The latency of dependence chains leading into this zone.
597   // For each node scheduled bottom-up: DLat = max DLat, N.Depth.
598   // For each cycle scheduled: DLat -= 1.
599   unsigned DependentLatency;
600
601   /// Count the scheduled (issued) micro-ops that can be retired by
602   /// time=CurrCycle assuming the first scheduled instr is retired at time=0.
603   unsigned RetiredMOps;
604
605   // Count scheduled resources that have been executed. Resources are
606   // considered executed if they become ready in the time that it takes to
607   // saturate any resource including the one in question. Counts are scaled
608   // for direct comparison with other resources. Counts can be compared with
609   // MOps * getMicroOpFactor and Latency * getLatencyFactor.
610   SmallVector<unsigned, 16> ExecutedResCounts;
611
612   /// Cache the max count for a single resource.
613   unsigned MaxExecutedResCount;
614
615   // Cache the critical resources ID in this scheduled zone.
616   unsigned ZoneCritResIdx;
617
618   // Is the scheduled region resource limited vs. latency limited.
619   bool IsResourceLimited;
620
621   // Record the highest cycle at which each resource has been reserved by a
622   // scheduled instruction.
623   SmallVector<unsigned, 16> ReservedCycles;
624
625 #ifndef NDEBUG
626   // Remember the greatest possible stall as an upper bound on the number of
627   // times we should retry the pending queue because of a hazard.
628   unsigned MaxObservedStall;
629 #endif
630
631 public:
632   /// Pending queues extend the ready queues with the same ID and the
633   /// PendingFlag set.
634   SchedBoundary(unsigned ID, const Twine &Name):
635     DAG(nullptr), SchedModel(nullptr), Rem(nullptr), Available(ID, Name+".A"),
636     Pending(ID << LogMaxQID, Name+".P"),
637     HazardRec(nullptr) {
638     reset();
639   }
640
641   ~SchedBoundary();
642
643   void reset();
644
645   void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
646             SchedRemainder *rem);
647
648   bool isTop() const {
649     return Available.getID() == TopQID;
650   }
651
652   /// Number of cycles to issue the instructions scheduled in this zone.
653   unsigned getCurrCycle() const { return CurrCycle; }
654
655   /// Micro-ops issued in the current cycle
656   unsigned getCurrMOps() const { return CurrMOps; }
657
658   /// Return true if the given SU is used by the most recently scheduled
659   /// instruction.
660   bool isNextSU(const SUnit *SU) const { return NextSUs.count(SU); }
661
662   // The latency of dependence chains leading into this zone.
663   unsigned getDependentLatency() const { return DependentLatency; }
664
665   /// Get the number of latency cycles "covered" by the scheduled
666   /// instructions. This is the larger of the critical path within the zone
667   /// and the number of cycles required to issue the instructions.
668   unsigned getScheduledLatency() const {
669     return std::max(ExpectedLatency, CurrCycle);
670   }
671
672   unsigned getUnscheduledLatency(SUnit *SU) const {
673     return isTop() ? SU->getHeight() : SU->getDepth();
674   }
675
676   unsigned getResourceCount(unsigned ResIdx) const {
677     return ExecutedResCounts[ResIdx];
678   }
679
680   /// Get the scaled count of scheduled micro-ops and resources, including
681   /// executed resources.
682   unsigned getCriticalCount() const {
683     if (!ZoneCritResIdx)
684       return RetiredMOps * SchedModel->getMicroOpFactor();
685     return getResourceCount(ZoneCritResIdx);
686   }
687
688   /// Get a scaled count for the minimum execution time of the scheduled
689   /// micro-ops that are ready to execute by getExecutedCount. Notice the
690   /// feedback loop.
691   unsigned getExecutedCount() const {
692     return std::max(CurrCycle * SchedModel->getLatencyFactor(),
693                     MaxExecutedResCount);
694   }
695
696   unsigned getZoneCritResIdx() const { return ZoneCritResIdx; }
697
698   // Is the scheduled region resource limited vs. latency limited.
699   bool isResourceLimited() const { return IsResourceLimited; }
700
701   /// Get the difference between the given SUnit's ready time and the current
702   /// cycle.
703   unsigned getLatencyStallCycles(SUnit *SU);
704
705   unsigned getNextResourceCycle(unsigned PIdx, unsigned Cycles);
706
707   bool checkHazard(SUnit *SU);
708
709   unsigned findMaxLatency(ArrayRef<SUnit*> ReadySUs);
710
711   unsigned getOtherResourceCount(unsigned &OtherCritIdx);
712
713   void releaseNode(SUnit *SU, unsigned ReadyCycle);
714
715   void releaseTopNode(SUnit *SU);
716
717   void releaseBottomNode(SUnit *SU);
718
719   void bumpCycle(unsigned NextCycle);
720
721   void incExecutedResources(unsigned PIdx, unsigned Count);
722
723   unsigned countResource(unsigned PIdx, unsigned Cycles, unsigned ReadyCycle);
724
725   void bumpNode(SUnit *SU);
726
727   void releasePending();
728
729   void removeReady(SUnit *SU);
730
731   /// Call this before applying any other heuristics to the Available queue.
732   /// Updates the Available/Pending Q's if necessary and returns the single
733   /// available instruction, or NULL if there are multiple candidates.
734   SUnit *pickOnlyChoice();
735
736 #ifndef NDEBUG
737   void dumpScheduledState();
738 #endif
739 };
740
741 /// Base class for GenericScheduler. This class maintains information about
742 /// scheduling candidates based on TargetSchedModel making it easy to implement
743 /// heuristics for either preRA or postRA scheduling.
744 class GenericSchedulerBase : public MachineSchedStrategy {
745 public:
746   /// Represent the type of SchedCandidate found within a single queue.
747   /// pickNodeBidirectional depends on these listed by decreasing priority.
748   enum CandReason {
749     NoCand, PhysRegCopy, RegExcess, RegCritical, Stall, Cluster, Weak, RegMax,
750     ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
751     TopDepthReduce, TopPathReduce, NextDefUse, NodeOrder};
752
753 #ifndef NDEBUG
754   static const char *getReasonStr(GenericSchedulerBase::CandReason Reason);
755 #endif
756
757   /// Policy for scheduling the next instruction in the candidate's zone.
758   struct CandPolicy {
759     bool ReduceLatency;
760     unsigned ReduceResIdx;
761     unsigned DemandResIdx;
762
763     CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
764   };
765
766   /// Status of an instruction's critical resource consumption.
767   struct SchedResourceDelta {
768     // Count critical resources in the scheduled region required by SU.
769     unsigned CritResources;
770
771     // Count critical resources from another region consumed by SU.
772     unsigned DemandedResources;
773
774     SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
775
776     bool operator==(const SchedResourceDelta &RHS) const {
777       return CritResources == RHS.CritResources
778         && DemandedResources == RHS.DemandedResources;
779     }
780     bool operator!=(const SchedResourceDelta &RHS) const {
781       return !operator==(RHS);
782     }
783   };
784
785   /// Store the state used by GenericScheduler heuristics, required for the
786   /// lifetime of one invocation of pickNode().
787   struct SchedCandidate {
788     CandPolicy Policy;
789
790     // The best SUnit candidate.
791     SUnit *SU;
792
793     // The reason for this candidate.
794     CandReason Reason;
795
796     // Set of reasons that apply to multiple candidates.
797     uint32_t RepeatReasonSet;
798
799     // Register pressure values for the best candidate.
800     RegPressureDelta RPDelta;
801
802     // Critical resource consumption of the best candidate.
803     SchedResourceDelta ResDelta;
804
805     SchedCandidate(const CandPolicy &policy)
806       : Policy(policy), SU(nullptr), Reason(NoCand), RepeatReasonSet(0) {}
807
808     bool isValid() const { return SU; }
809
810     // Copy the status of another candidate without changing policy.
811     void setBest(SchedCandidate &Best) {
812       assert(Best.Reason != NoCand && "uninitialized Sched candidate");
813       SU = Best.SU;
814       Reason = Best.Reason;
815       RPDelta = Best.RPDelta;
816       ResDelta = Best.ResDelta;
817     }
818
819     bool isRepeat(CandReason R) { return RepeatReasonSet & (1 << R); }
820     void setRepeat(CandReason R) { RepeatReasonSet |= (1 << R); }
821
822     void initResourceDelta(const ScheduleDAGMI *DAG,
823                            const TargetSchedModel *SchedModel);
824   };
825
826 protected:
827   const MachineSchedContext *Context;
828   const TargetSchedModel *SchedModel;
829   const TargetRegisterInfo *TRI;
830
831   SchedRemainder Rem;
832 protected:
833   GenericSchedulerBase(const MachineSchedContext *C):
834     Context(C), SchedModel(nullptr), TRI(nullptr) {}
835
836   void setPolicy(CandPolicy &Policy, bool IsPostRA, SchedBoundary &CurrZone,
837                  SchedBoundary *OtherZone);
838
839 #ifndef NDEBUG
840   void traceCandidate(const SchedCandidate &Cand);
841 #endif
842 };
843
844 /// GenericScheduler shrinks the unscheduled zone using heuristics to balance
845 /// the schedule.
846 class GenericScheduler : public GenericSchedulerBase {
847   ScheduleDAGMILive *DAG;
848
849   // State of the top and bottom scheduled instruction boundaries.
850   SchedBoundary Top;
851   SchedBoundary Bot;
852
853   MachineSchedPolicy RegionPolicy;
854 public:
855   GenericScheduler(const MachineSchedContext *C):
856     GenericSchedulerBase(C), DAG(nullptr), Top(SchedBoundary::TopQID, "TopQ"),
857     Bot(SchedBoundary::BotQID, "BotQ") {}
858
859   void initPolicy(MachineBasicBlock::iterator Begin,
860                   MachineBasicBlock::iterator End,
861                   unsigned NumRegionInstrs) override;
862
863   void dumpPolicy() override;
864
865   bool shouldTrackPressure() const override {
866     return RegionPolicy.ShouldTrackPressure;
867   }
868
869   void initialize(ScheduleDAGMI *dag) override;
870
871   SUnit *pickNode(bool &IsTopNode) override;
872
873   void schedNode(SUnit *SU, bool IsTopNode) override;
874
875   void releaseTopNode(SUnit *SU) override {
876     Top.releaseTopNode(SU);
877   }
878
879   void releaseBottomNode(SUnit *SU) override {
880     Bot.releaseBottomNode(SU);
881   }
882
883   void registerRoots() override;
884
885 protected:
886   void checkAcyclicLatency();
887
888   void tryCandidate(SchedCandidate &Cand,
889                     SchedCandidate &TryCand,
890                     SchedBoundary &Zone,
891                     const RegPressureTracker &RPTracker,
892                     RegPressureTracker &TempTracker);
893
894   SUnit *pickNodeBidirectional(bool &IsTopNode);
895
896   void pickNodeFromQueue(SchedBoundary &Zone,
897                          const RegPressureTracker &RPTracker,
898                          SchedCandidate &Candidate);
899
900   void reschedulePhysRegCopies(SUnit *SU, bool isTop);
901 };
902
903 /// PostGenericScheduler - Interface to the scheduling algorithm used by
904 /// ScheduleDAGMI.
905 ///
906 /// Callbacks from ScheduleDAGMI:
907 ///   initPolicy -> initialize(DAG) -> registerRoots -> pickNode ...
908 class PostGenericScheduler : public GenericSchedulerBase {
909   ScheduleDAGMI *DAG;
910   SchedBoundary Top;
911   SmallVector<SUnit*, 8> BotRoots;
912 public:
913   PostGenericScheduler(const MachineSchedContext *C):
914     GenericSchedulerBase(C), Top(SchedBoundary::TopQID, "TopQ") {}
915
916   ~PostGenericScheduler() override {}
917
918   void initPolicy(MachineBasicBlock::iterator Begin,
919                   MachineBasicBlock::iterator End,
920                   unsigned NumRegionInstrs) override {
921     /* no configurable policy */
922   }
923
924   /// PostRA scheduling does not track pressure.
925   bool shouldTrackPressure() const override { return false; }
926
927   void initialize(ScheduleDAGMI *Dag) override;
928
929   void registerRoots() override;
930
931   SUnit *pickNode(bool &IsTopNode) override;
932
933   void scheduleTree(unsigned SubtreeID) override {
934     llvm_unreachable("PostRA scheduler does not support subtree analysis.");
935   }
936
937   void schedNode(SUnit *SU, bool IsTopNode) override;
938
939   void releaseTopNode(SUnit *SU) override {
940     Top.releaseTopNode(SU);
941   }
942
943   // Only called for roots.
944   void releaseBottomNode(SUnit *SU) override {
945     BotRoots.push_back(SU);
946   }
947
948 protected:
949   void tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand);
950
951   void pickNodeFromQueue(SchedCandidate &Cand);
952 };
953
954 } // namespace llvm
955
956 #endif