[C++11] More 'nullptr' conversion. In some cases just using a boolean check instead...
[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/CodeGen/MachinePassRegistry.h"
81 #include "llvm/CodeGen/RegisterPressure.h"
82 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
83
84 namespace llvm {
85
86 extern cl::opt<bool> ForceTopDown;
87 extern cl::opt<bool> ForceBottomUp;
88
89 class AliasAnalysis;
90 class LiveIntervals;
91 class MachineDominatorTree;
92 class MachineLoopInfo;
93 class RegisterClassInfo;
94 class ScheduleDAGInstrs;
95 class SchedDFSResult;
96 class ScheduleHazardRecognizer;
97
98 /// MachineSchedContext provides enough context from the MachineScheduler pass
99 /// for the target to instantiate a scheduler.
100 struct MachineSchedContext {
101   MachineFunction *MF;
102   const MachineLoopInfo *MLI;
103   const MachineDominatorTree *MDT;
104   const TargetPassConfig *PassConfig;
105   AliasAnalysis *AA;
106   LiveIntervals *LIS;
107
108   RegisterClassInfo *RegClassInfo;
109
110   MachineSchedContext();
111   virtual ~MachineSchedContext();
112 };
113
114 /// MachineSchedRegistry provides a selection of available machine instruction
115 /// schedulers.
116 class MachineSchedRegistry : public MachinePassRegistryNode {
117 public:
118   typedef ScheduleDAGInstrs *(*ScheduleDAGCtor)(MachineSchedContext *);
119
120   // RegisterPassParser requires a (misnamed) FunctionPassCtor type.
121   typedef ScheduleDAGCtor FunctionPassCtor;
122
123   static MachinePassRegistry Registry;
124
125   MachineSchedRegistry(const char *N, const char *D, ScheduleDAGCtor C)
126     : MachinePassRegistryNode(N, D, (MachinePassCtor)C) {
127     Registry.Add(this);
128   }
129   ~MachineSchedRegistry() { Registry.Remove(this); }
130
131   // Accessors.
132   //
133   MachineSchedRegistry *getNext() const {
134     return (MachineSchedRegistry *)MachinePassRegistryNode::getNext();
135   }
136   static MachineSchedRegistry *getList() {
137     return (MachineSchedRegistry *)Registry.getList();
138   }
139   static void setListener(MachinePassRegistryListener *L) {
140     Registry.setListener(L);
141   }
142 };
143
144 class ScheduleDAGMI;
145
146 /// Define a generic scheduling policy for targets that don't provide their own
147 /// MachineSchedStrategy. This can be overriden for each scheduling region
148 /// before building the DAG.
149 struct MachineSchedPolicy {
150   // Allow the scheduler to disable register pressure tracking.
151   bool ShouldTrackPressure;
152
153   // Allow the scheduler to force top-down or bottom-up scheduling. If neither
154   // is true, the scheduler runs in both directions and converges.
155   bool OnlyTopDown;
156   bool OnlyBottomUp;
157
158   MachineSchedPolicy(): ShouldTrackPressure(false), OnlyTopDown(false),
159     OnlyBottomUp(false) {}
160 };
161
162 /// MachineSchedStrategy - Interface to the scheduling algorithm used by
163 /// ScheduleDAGMI.
164 ///
165 /// Initialization sequence:
166 ///   initPolicy -> shouldTrackPressure -> initialize(DAG) -> registerRoots
167 class MachineSchedStrategy {
168   virtual void anchor();
169 public:
170   virtual ~MachineSchedStrategy() {}
171
172   /// Optionally override the per-region scheduling policy.
173   virtual void initPolicy(MachineBasicBlock::iterator Begin,
174                           MachineBasicBlock::iterator End,
175                           unsigned NumRegionInstrs) {}
176
177   /// Check if pressure tracking is needed before building the DAG and
178   /// initializing this strategy. Called after initPolicy.
179   virtual bool shouldTrackPressure() const { return true; }
180
181   /// Initialize the strategy after building the DAG for a new region.
182   virtual void initialize(ScheduleDAGMI *DAG) = 0;
183
184   /// Notify this strategy that all roots have been released (including those
185   /// that depend on EntrySU or ExitSU).
186   virtual void registerRoots() {}
187
188   /// Pick the next node to schedule, or return NULL. Set IsTopNode to true to
189   /// schedule the node at the top of the unscheduled region. Otherwise it will
190   /// be scheduled at the bottom.
191   virtual SUnit *pickNode(bool &IsTopNode) = 0;
192
193   /// \brief Scheduler callback to notify that a new subtree is scheduled.
194   virtual void scheduleTree(unsigned SubtreeID) {}
195
196   /// Notify MachineSchedStrategy that ScheduleDAGMI has scheduled an
197   /// instruction and updated scheduled/remaining flags in the DAG nodes.
198   virtual void schedNode(SUnit *SU, bool IsTopNode) = 0;
199
200   /// When all predecessor dependencies have been resolved, free this node for
201   /// top-down scheduling.
202   virtual void releaseTopNode(SUnit *SU) = 0;
203   /// When all successor dependencies have been resolved, free this node for
204   /// bottom-up scheduling.
205   virtual void releaseBottomNode(SUnit *SU) = 0;
206 };
207
208 /// Mutate the DAG as a postpass after normal DAG building.
209 class ScheduleDAGMutation {
210   virtual void anchor();
211 public:
212   virtual ~ScheduleDAGMutation() {}
213
214   virtual void apply(ScheduleDAGMI *DAG) = 0;
215 };
216
217 /// ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply
218 /// schedules machine instructions according to the given MachineSchedStrategy
219 /// without much extra book-keeping. This is the common functionality between
220 /// PreRA and PostRA MachineScheduler.
221 class ScheduleDAGMI : public ScheduleDAGInstrs {
222 protected:
223   AliasAnalysis *AA;
224   MachineSchedStrategy *SchedImpl;
225
226   /// Topo - A topological ordering for SUnits which permits fast IsReachable
227   /// and similar queries.
228   ScheduleDAGTopologicalSort Topo;
229
230   /// Ordered list of DAG postprocessing steps.
231   std::vector<ScheduleDAGMutation*> Mutations;
232
233   /// The top of the unscheduled zone.
234   MachineBasicBlock::iterator CurrentTop;
235
236   /// The bottom of the unscheduled zone.
237   MachineBasicBlock::iterator CurrentBottom;
238
239   /// Record the next node in a scheduled cluster.
240   const SUnit *NextClusterPred;
241   const SUnit *NextClusterSucc;
242
243 #ifndef NDEBUG
244   /// The number of instructions scheduled so far. Used to cut off the
245   /// scheduler at the point determined by misched-cutoff.
246   unsigned NumInstrsScheduled;
247 #endif
248 public:
249   ScheduleDAGMI(MachineSchedContext *C, MachineSchedStrategy *S, bool IsPostRA):
250     ScheduleDAGInstrs(*C->MF, *C->MLI, *C->MDT, IsPostRA,
251                       /*RemoveKillFlags=*/IsPostRA, C->LIS),
252     AA(C->AA), SchedImpl(S), Topo(SUnits, &ExitSU), CurrentTop(),
253     CurrentBottom(), NextClusterPred(nullptr), NextClusterSucc(nullptr) {
254 #ifndef NDEBUG
255     NumInstrsScheduled = 0;
256 #endif
257   }
258
259   virtual ~ScheduleDAGMI();
260
261   /// Return true if this DAG supports VReg liveness and RegPressure.
262   virtual bool hasVRegLiveness() const { return false; }
263
264   /// Add a postprocessing step to the DAG builder.
265   /// Mutations are applied in the order that they are added after normal DAG
266   /// building and before MachineSchedStrategy initialization.
267   ///
268   /// ScheduleDAGMI takes ownership of the Mutation object.
269   void addMutation(ScheduleDAGMutation *Mutation) {
270     Mutations.push_back(Mutation);
271   }
272
273   /// \brief True if an edge can be added from PredSU to SuccSU without creating
274   /// a cycle.
275   bool canAddEdge(SUnit *SuccSU, SUnit *PredSU);
276
277   /// \brief Add a DAG edge to the given SU with the given predecessor
278   /// dependence data.
279   ///
280   /// \returns true if the edge may be added without creating a cycle OR if an
281   /// equivalent edge already existed (false indicates failure).
282   bool addEdge(SUnit *SuccSU, const SDep &PredDep);
283
284   MachineBasicBlock::iterator top() const { return CurrentTop; }
285   MachineBasicBlock::iterator bottom() const { return CurrentBottom; }
286
287   /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
288   /// region. This covers all instructions in a block, while schedule() may only
289   /// cover a subset.
290   void enterRegion(MachineBasicBlock *bb,
291                    MachineBasicBlock::iterator begin,
292                    MachineBasicBlock::iterator end,
293                    unsigned regioninstrs) override;
294
295   /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
296   /// reorderable instructions.
297   void schedule() override;
298
299   /// Change the position of an instruction within the basic block and update
300   /// live ranges and region boundary iterators.
301   void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos);
302
303   const SUnit *getNextClusterPred() const { return NextClusterPred; }
304
305   const SUnit *getNextClusterSucc() const { return NextClusterSucc; }
306
307   void viewGraph(const Twine &Name, const Twine &Title) override;
308   void viewGraph() override;
309
310 protected:
311   // Top-Level entry points for the schedule() driver...
312
313   /// Apply each ScheduleDAGMutation step in order. This allows different
314   /// instances of ScheduleDAGMI to perform custom DAG postprocessing.
315   void postprocessDAG();
316
317   /// Release ExitSU predecessors and setup scheduler queues.
318   void initQueues(ArrayRef<SUnit*> TopRoots, ArrayRef<SUnit*> BotRoots);
319
320   /// Update scheduler DAG and queues after scheduling an instruction.
321   void updateQueues(SUnit *SU, bool IsTopNode);
322
323   /// Reinsert debug_values recorded in ScheduleDAGInstrs::DbgValues.
324   void placeDebugValues();
325
326   /// \brief dump the scheduled Sequence.
327   void dumpSchedule() const;
328
329   // Lesser helpers...
330   bool checkSchedLimit();
331
332   void findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
333                              SmallVectorImpl<SUnit*> &BotRoots);
334
335   void releaseSucc(SUnit *SU, SDep *SuccEdge);
336   void releaseSuccessors(SUnit *SU);
337   void releasePred(SUnit *SU, SDep *PredEdge);
338   void releasePredecessors(SUnit *SU);
339 };
340
341 /// ScheduleDAGMILive is an implementation of ScheduleDAGInstrs that schedules
342 /// machine instructions while updating LiveIntervals and tracking regpressure.
343 class ScheduleDAGMILive : public ScheduleDAGMI {
344 protected:
345   RegisterClassInfo *RegClassInfo;
346
347   /// Information about DAG subtrees. If DFSResult is NULL, then SchedulerTrees
348   /// will be empty.
349   SchedDFSResult *DFSResult;
350   BitVector ScheduledTrees;
351
352   MachineBasicBlock::iterator LiveRegionEnd;
353
354   // Map each SU to its summary of pressure changes. This array is updated for
355   // liveness during bottom-up scheduling. Top-down scheduling may proceed but
356   // has no affect on the pressure diffs.
357   PressureDiffs SUPressureDiffs;
358
359   /// Register pressure in this region computed by initRegPressure.
360   bool ShouldTrackPressure;
361   IntervalPressure RegPressure;
362   RegPressureTracker RPTracker;
363
364   /// List of pressure sets that exceed the target's pressure limit before
365   /// scheduling, listed in increasing set ID order. Each pressure set is paired
366   /// with its max pressure in the currently scheduled regions.
367   std::vector<PressureChange> RegionCriticalPSets;
368
369   /// The top of the unscheduled zone.
370   IntervalPressure TopPressure;
371   RegPressureTracker TopRPTracker;
372
373   /// The bottom of the unscheduled zone.
374   IntervalPressure BotPressure;
375   RegPressureTracker BotRPTracker;
376
377 public:
378   ScheduleDAGMILive(MachineSchedContext *C, MachineSchedStrategy *S):
379     ScheduleDAGMI(C, S, /*IsPostRA=*/false), RegClassInfo(C->RegClassInfo),
380     DFSResult(nullptr), ShouldTrackPressure(false), RPTracker(RegPressure),
381     TopRPTracker(TopPressure), BotRPTracker(BotPressure)
382   {}
383
384   virtual ~ScheduleDAGMILive();
385
386   /// Return true if this DAG supports VReg liveness and RegPressure.
387   bool hasVRegLiveness() const override { return true; }
388
389   /// \brief Return true if register pressure tracking is enabled.
390   bool isTrackingPressure() const { return ShouldTrackPressure; }
391
392   /// Get current register pressure for the top scheduled instructions.
393   const IntervalPressure &getTopPressure() const { return TopPressure; }
394   const RegPressureTracker &getTopRPTracker() const { return TopRPTracker; }
395
396   /// Get current register pressure for the bottom scheduled instructions.
397   const IntervalPressure &getBotPressure() const { return BotPressure; }
398   const RegPressureTracker &getBotRPTracker() const { return BotRPTracker; }
399
400   /// Get register pressure for the entire scheduling region before scheduling.
401   const IntervalPressure &getRegPressure() const { return RegPressure; }
402
403   const std::vector<PressureChange> &getRegionCriticalPSets() const {
404     return RegionCriticalPSets;
405   }
406
407   PressureDiff &getPressureDiff(const SUnit *SU) {
408     return SUPressureDiffs[SU->NodeNum];
409   }
410
411   /// Compute a DFSResult after DAG building is complete, and before any
412   /// queue comparisons.
413   void computeDFSResult();
414
415   /// Return a non-null DFS result if the scheduling strategy initialized it.
416   const SchedDFSResult *getDFSResult() const { return DFSResult; }
417
418   BitVector &getScheduledTrees() { return ScheduledTrees; }
419
420   /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
421   /// region. This covers all instructions in a block, while schedule() may only
422   /// cover a subset.
423   void enterRegion(MachineBasicBlock *bb,
424                    MachineBasicBlock::iterator begin,
425                    MachineBasicBlock::iterator end,
426                    unsigned regioninstrs) override;
427
428   /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
429   /// reorderable instructions.
430   void schedule() override;
431
432   /// Compute the cyclic critical path through the DAG.
433   unsigned computeCyclicCriticalPath();
434
435 protected:
436   // Top-Level entry points for the schedule() driver...
437
438   /// Call ScheduleDAGInstrs::buildSchedGraph with register pressure tracking
439   /// enabled. This sets up three trackers. RPTracker will cover the entire DAG
440   /// region, TopTracker and BottomTracker will be initialized to the top and
441   /// bottom of the DAG region without covereing any unscheduled instruction.
442   void buildDAGWithRegPressure();
443
444   /// Move an instruction and update register pressure.
445   void scheduleMI(SUnit *SU, bool IsTopNode);
446
447   // Lesser helpers...
448
449   void initRegPressure();
450
451   void updatePressureDiffs(ArrayRef<unsigned> LiveUses);
452
453   void updateScheduledPressure(const SUnit *SU,
454                                const std::vector<unsigned> &NewMaxPressure);
455 };
456
457 //===----------------------------------------------------------------------===//
458 ///
459 /// Helpers for implementing custom MachineSchedStrategy classes. These take
460 /// care of the book-keeping associated with list scheduling heuristics.
461 ///
462 //===----------------------------------------------------------------------===//
463
464 /// ReadyQueue encapsulates vector of "ready" SUnits with basic convenience
465 /// methods for pushing and removing nodes. ReadyQueue's are uniquely identified
466 /// by an ID. SUnit::NodeQueueId is a mask of the ReadyQueues the SUnit is in.
467 ///
468 /// This is a convenience class that may be used by implementations of
469 /// MachineSchedStrategy.
470 class ReadyQueue {
471   unsigned ID;
472   std::string Name;
473   std::vector<SUnit*> Queue;
474
475 public:
476   ReadyQueue(unsigned id, const Twine &name): ID(id), Name(name.str()) {}
477
478   unsigned getID() const { return ID; }
479
480   StringRef getName() const { return Name; }
481
482   // SU is in this queue if it's NodeQueueID is a superset of this ID.
483   bool isInQueue(SUnit *SU) const { return (SU->NodeQueueId & ID); }
484
485   bool empty() const { return Queue.empty(); }
486
487   void clear() { Queue.clear(); }
488
489   unsigned size() const { return Queue.size(); }
490
491   typedef std::vector<SUnit*>::iterator iterator;
492
493   iterator begin() { return Queue.begin(); }
494
495   iterator end() { return Queue.end(); }
496
497   ArrayRef<SUnit*> elements() { return Queue; }
498
499   iterator find(SUnit *SU) {
500     return std::find(Queue.begin(), Queue.end(), SU);
501   }
502
503   void push(SUnit *SU) {
504     Queue.push_back(SU);
505     SU->NodeQueueId |= ID;
506   }
507
508   iterator remove(iterator I) {
509     (*I)->NodeQueueId &= ~ID;
510     *I = Queue.back();
511     unsigned idx = I - Queue.begin();
512     Queue.pop_back();
513     return Queue.begin() + idx;
514   }
515
516 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
517   void dump();
518 #endif
519 };
520
521 /// Summarize the unscheduled region.
522 struct SchedRemainder {
523   // Critical path through the DAG in expected latency.
524   unsigned CriticalPath;
525   unsigned CyclicCritPath;
526
527   // Scaled count of micro-ops left to schedule.
528   unsigned RemIssueCount;
529
530   bool IsAcyclicLatencyLimited;
531
532   // Unscheduled resources
533   SmallVector<unsigned, 16> RemainingCounts;
534
535   void reset() {
536     CriticalPath = 0;
537     CyclicCritPath = 0;
538     RemIssueCount = 0;
539     IsAcyclicLatencyLimited = false;
540     RemainingCounts.clear();
541   }
542
543   SchedRemainder() { reset(); }
544
545   void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
546 };
547
548 /// Each Scheduling boundary is associated with ready queues. It tracks the
549 /// current cycle in the direction of movement, and maintains the state
550 /// of "hazards" and other interlocks at the current cycle.
551 class SchedBoundary {
552 public:
553   /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
554   enum {
555     TopQID = 1,
556     BotQID = 2,
557     LogMaxQID = 2
558   };
559
560   ScheduleDAGMI *DAG;
561   const TargetSchedModel *SchedModel;
562   SchedRemainder *Rem;
563
564   ReadyQueue Available;
565   ReadyQueue Pending;
566
567   ScheduleHazardRecognizer *HazardRec;
568
569 private:
570   /// True if the pending Q should be checked/updated before scheduling another
571   /// instruction.
572   bool CheckPending;
573
574   // For heuristics, keep a list of the nodes that immediately depend on the
575   // most recently scheduled node.
576   SmallPtrSet<const SUnit*, 8> NextSUs;
577
578   /// Number of cycles it takes to issue the instructions scheduled in this
579   /// zone. It is defined as: scheduled-micro-ops / issue-width + stalls.
580   /// See getStalls().
581   unsigned CurrCycle;
582
583   /// Micro-ops issued in the current cycle
584   unsigned CurrMOps;
585
586   /// MinReadyCycle - Cycle of the soonest available instruction.
587   unsigned MinReadyCycle;
588
589   // The expected latency of the critical path in this scheduled zone.
590   unsigned ExpectedLatency;
591
592   // The latency of dependence chains leading into this zone.
593   // For each node scheduled bottom-up: DLat = max DLat, N.Depth.
594   // For each cycle scheduled: DLat -= 1.
595   unsigned DependentLatency;
596
597   /// Count the scheduled (issued) micro-ops that can be retired by
598   /// time=CurrCycle assuming the first scheduled instr is retired at time=0.
599   unsigned RetiredMOps;
600
601   // Count scheduled resources that have been executed. Resources are
602   // considered executed if they become ready in the time that it takes to
603   // saturate any resource including the one in question. Counts are scaled
604   // for direct comparison with other resources. Counts can be compared with
605   // MOps * getMicroOpFactor and Latency * getLatencyFactor.
606   SmallVector<unsigned, 16> ExecutedResCounts;
607
608   /// Cache the max count for a single resource.
609   unsigned MaxExecutedResCount;
610
611   // Cache the critical resources ID in this scheduled zone.
612   unsigned ZoneCritResIdx;
613
614   // Is the scheduled region resource limited vs. latency limited.
615   bool IsResourceLimited;
616
617   // Record the highest cycle at which each resource has been reserved by a
618   // scheduled instruction.
619   SmallVector<unsigned, 16> ReservedCycles;
620
621 #ifndef NDEBUG
622   // Remember the greatest operand latency as an upper bound on the number of
623   // times we should retry the pending queue because of a hazard.
624   unsigned MaxObservedLatency;
625 #endif
626
627 public:
628   /// Pending queues extend the ready queues with the same ID and the
629   /// PendingFlag set.
630   SchedBoundary(unsigned ID, const Twine &Name):
631     DAG(nullptr), SchedModel(nullptr), Rem(nullptr), Available(ID, Name+".A"),
632     Pending(ID << LogMaxQID, Name+".P"),
633     HazardRec(nullptr) {
634     reset();
635   }
636
637   ~SchedBoundary();
638
639   void reset();
640
641   void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
642             SchedRemainder *rem);
643
644   bool isTop() const {
645     return Available.getID() == TopQID;
646   }
647
648   /// Number of cycles to issue the instructions scheduled in this zone.
649   unsigned getCurrCycle() const { return CurrCycle; }
650
651   /// Micro-ops issued in the current cycle
652   unsigned getCurrMOps() const { return CurrMOps; }
653
654   /// Return true if the given SU is used by the most recently scheduled
655   /// instruction.
656   bool isNextSU(const SUnit *SU) const { return NextSUs.count(SU); }
657
658   // The latency of dependence chains leading into this zone.
659   unsigned getDependentLatency() const { return DependentLatency; }
660
661   /// Get the number of latency cycles "covered" by the scheduled
662   /// instructions. This is the larger of the critical path within the zone
663   /// and the number of cycles required to issue the instructions.
664   unsigned getScheduledLatency() const {
665     return std::max(ExpectedLatency, CurrCycle);
666   }
667
668   unsigned getUnscheduledLatency(SUnit *SU) const {
669     return isTop() ? SU->getHeight() : SU->getDepth();
670   }
671
672   unsigned getResourceCount(unsigned ResIdx) const {
673     return ExecutedResCounts[ResIdx];
674   }
675
676   /// Get the scaled count of scheduled micro-ops and resources, including
677   /// executed resources.
678   unsigned getCriticalCount() const {
679     if (!ZoneCritResIdx)
680       return RetiredMOps * SchedModel->getMicroOpFactor();
681     return getResourceCount(ZoneCritResIdx);
682   }
683
684   /// Get a scaled count for the minimum execution time of the scheduled
685   /// micro-ops that are ready to execute by getExecutedCount. Notice the
686   /// feedback loop.
687   unsigned getExecutedCount() const {
688     return std::max(CurrCycle * SchedModel->getLatencyFactor(),
689                     MaxExecutedResCount);
690   }
691
692   unsigned getZoneCritResIdx() const { return ZoneCritResIdx; }
693
694   // Is the scheduled region resource limited vs. latency limited.
695   bool isResourceLimited() const { return IsResourceLimited; }
696
697   /// Get the difference between the given SUnit's ready time and the current
698   /// cycle.
699   unsigned getLatencyStallCycles(SUnit *SU);
700
701   unsigned getNextResourceCycle(unsigned PIdx, unsigned Cycles);
702
703   bool checkHazard(SUnit *SU);
704
705   unsigned findMaxLatency(ArrayRef<SUnit*> ReadySUs);
706
707   unsigned getOtherResourceCount(unsigned &OtherCritIdx);
708
709   void releaseNode(SUnit *SU, unsigned ReadyCycle);
710
711   void releaseTopNode(SUnit *SU);
712
713   void releaseBottomNode(SUnit *SU);
714
715   void bumpCycle(unsigned NextCycle);
716
717   void incExecutedResources(unsigned PIdx, unsigned Count);
718
719   unsigned countResource(unsigned PIdx, unsigned Cycles, unsigned ReadyCycle);
720
721   void bumpNode(SUnit *SU);
722
723   void releasePending();
724
725   void removeReady(SUnit *SU);
726
727   /// Call this before applying any other heuristics to the Available queue.
728   /// Updates the Available/Pending Q's if necessary and returns the single
729   /// available instruction, or NULL if there are multiple candidates.
730   SUnit *pickOnlyChoice();
731
732 #ifndef NDEBUG
733   void dumpScheduledState();
734 #endif
735 };
736
737 } // namespace llvm
738
739 #endif