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