1 //==- MachineScheduler.h - MachineInstr Scheduling Pass ----------*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides an interface for customizing the standard MachineScheduler
11 // pass. Note that the entire pass may be replaced as follows:
13 // <Target>TargetMachine::createPassConfig(PassManagerBase &PM) {
14 // PM.substitutePass(&MachineSchedulerID, &CustomSchedulerPassID);
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:
21 // ScheduleDAGInstrs *<Target>PassConfig::
22 // createMachineScheduler(MachineSchedContext *C) {
23 // return new CustomMachineScheduler(C);
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:
33 // ScheduleDAGInstrs *<Target>PassConfig::
34 // createMachineScheduler(MachineSchedContext *C) {
35 // return new ScheduleDAGMI(C, CustomStrategy(C));
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
43 // ScheduleDAGInstrs *<Target>PassConfig::
44 // createMachineScheduler(MachineSchedContext *C) {
45 // ScheduleDAGMI *DAG = createGenericSchedLive(C);
46 // DAG->addMutation(new CustomDAGMutation(...));
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:
54 // static ScheduleDAGInstrs *createCustomMachineSched(MachineSchedContext *C) {
55 // return new CustomMachineScheduler(C);
57 // static MachineSchedRegistry
58 // SchedCustomRegistry("custom", "Run my target's custom scheduler",
59 // createCustomMachineSched);
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
67 // void <SubTarget>Subtarget::
68 // overrideSchedPolicy(MachineSchedPolicy &Policy,
69 // unsigned NumRegionInstrs) const {
70 // Policy.<Flag> = true;
73 //===----------------------------------------------------------------------===//
75 #ifndef LLVM_CODEGEN_MACHINESCHEDULER_H
76 #define LLVM_CODEGEN_MACHINESCHEDULER_H
78 #include "llvm/ADT/ArrayRef.h"
79 #include "llvm/ADT/BitVector.h"
80 #include "llvm/ADT/STLExtras.h"
81 #include "llvm/ADT/SmallVector.h"
82 #include "llvm/ADT/StringRef.h"
83 #include "llvm/ADT/Twine.h"
84 #include "llvm/Analysis/AliasAnalysis.h"
85 #include "llvm/CodeGen/MachineBasicBlock.h"
86 #include "llvm/CodeGen/MachinePassRegistry.h"
87 #include "llvm/CodeGen/RegisterPressure.h"
88 #include "llvm/CodeGen/ScheduleDAG.h"
89 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
90 #include "llvm/CodeGen/ScheduleDAGMutation.h"
91 #include "llvm/CodeGen/TargetSchedule.h"
92 #include "llvm/Support/CommandLine.h"
93 #include "llvm/Support/ErrorHandling.h"
102 extern cl::opt<bool> ForceTopDown;
103 extern cl::opt<bool> ForceBottomUp;
106 class MachineDominatorTree;
107 class MachineLoopInfo;
108 class RegisterClassInfo;
109 class SchedDFSResult;
110 class ScheduleHazardRecognizer;
112 /// MachineSchedContext provides enough context from the MachineScheduler pass
113 /// for the target to instantiate a scheduler.
114 struct MachineSchedContext {
116 const MachineLoopInfo *MLI;
117 const MachineDominatorTree *MDT;
118 const TargetPassConfig *PassConfig;
122 RegisterClassInfo *RegClassInfo;
124 MachineSchedContext();
125 virtual ~MachineSchedContext();
128 /// MachineSchedRegistry provides a selection of available machine instruction
130 class MachineSchedRegistry : public MachinePassRegistryNode {
132 typedef ScheduleDAGInstrs *(*ScheduleDAGCtor)(MachineSchedContext *);
134 // RegisterPassParser requires a (misnamed) FunctionPassCtor type.
135 typedef ScheduleDAGCtor FunctionPassCtor;
137 static MachinePassRegistry Registry;
139 MachineSchedRegistry(const char *N, const char *D, ScheduleDAGCtor C)
140 : MachinePassRegistryNode(N, D, (MachinePassCtor)C) {
144 ~MachineSchedRegistry() { Registry.Remove(this); }
148 MachineSchedRegistry *getNext() const {
149 return (MachineSchedRegistry *)MachinePassRegistryNode::getNext();
152 static MachineSchedRegistry *getList() {
153 return (MachineSchedRegistry *)Registry.getList();
156 static void setListener(MachinePassRegistryListener *L) {
157 Registry.setListener(L);
163 /// Define a generic scheduling policy for targets that don't provide their own
164 /// MachineSchedStrategy. This can be overriden for each scheduling region
165 /// before building the DAG.
166 struct MachineSchedPolicy {
167 // Allow the scheduler to disable register pressure tracking.
168 bool ShouldTrackPressure;
169 /// Track LaneMasks to allow reordering of independent subregister writes
170 /// of the same vreg. \sa MachineSchedStrategy::shouldTrackLaneMasks()
171 bool ShouldTrackLaneMasks;
173 // Allow the scheduler to force top-down or bottom-up scheduling. If neither
174 // is true, the scheduler runs in both directions and converges.
178 // Disable heuristic that tries to fetch nodes from long dependency chains
180 bool DisableLatencyHeuristic;
182 MachineSchedPolicy(): ShouldTrackPressure(false), ShouldTrackLaneMasks(false),
183 OnlyTopDown(false), OnlyBottomUp(false), DisableLatencyHeuristic(false) {}
186 /// MachineSchedStrategy - Interface to the scheduling algorithm used by
189 /// Initialization sequence:
190 /// initPolicy -> shouldTrackPressure -> initialize(DAG) -> registerRoots
191 class MachineSchedStrategy {
192 virtual void anchor();
195 virtual ~MachineSchedStrategy() = default;
197 /// Optionally override the per-region scheduling policy.
198 virtual void initPolicy(MachineBasicBlock::iterator Begin,
199 MachineBasicBlock::iterator End,
200 unsigned NumRegionInstrs) {}
202 virtual void dumpPolicy() {}
204 /// Check if pressure tracking is needed before building the DAG and
205 /// initializing this strategy. Called after initPolicy.
206 virtual bool shouldTrackPressure() const { return true; }
208 /// Returns true if lanemasks should be tracked. LaneMask tracking is
209 /// necessary to reorder independent subregister defs for the same vreg.
210 /// This has to be enabled in combination with shouldTrackPressure().
211 virtual bool shouldTrackLaneMasks() const { return false; }
213 /// Initialize the strategy after building the DAG for a new region.
214 virtual void initialize(ScheduleDAGMI *DAG) = 0;
216 /// Notify this strategy that all roots have been released (including those
217 /// that depend on EntrySU or ExitSU).
218 virtual void registerRoots() {}
220 /// Pick the next node to schedule, or return NULL. Set IsTopNode to true to
221 /// schedule the node at the top of the unscheduled region. Otherwise it will
222 /// be scheduled at the bottom.
223 virtual SUnit *pickNode(bool &IsTopNode) = 0;
225 /// \brief Scheduler callback to notify that a new subtree is scheduled.
226 virtual void scheduleTree(unsigned SubtreeID) {}
228 /// Notify MachineSchedStrategy that ScheduleDAGMI has scheduled an
229 /// instruction and updated scheduled/remaining flags in the DAG nodes.
230 virtual void schedNode(SUnit *SU, bool IsTopNode) = 0;
232 /// When all predecessor dependencies have been resolved, free this node for
233 /// top-down scheduling.
234 virtual void releaseTopNode(SUnit *SU) = 0;
235 /// When all successor dependencies have been resolved, free this node for
236 /// bottom-up scheduling.
237 virtual void releaseBottomNode(SUnit *SU) = 0;
240 /// ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply
241 /// schedules machine instructions according to the given MachineSchedStrategy
242 /// without much extra book-keeping. This is the common functionality between
243 /// PreRA and PostRA MachineScheduler.
244 class ScheduleDAGMI : public ScheduleDAGInstrs {
248 std::unique_ptr<MachineSchedStrategy> SchedImpl;
250 /// Topo - A topological ordering for SUnits which permits fast IsReachable
251 /// and similar queries.
252 ScheduleDAGTopologicalSort Topo;
254 /// Ordered list of DAG postprocessing steps.
255 std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;
257 /// The top of the unscheduled zone.
258 MachineBasicBlock::iterator CurrentTop;
260 /// The bottom of the unscheduled zone.
261 MachineBasicBlock::iterator CurrentBottom;
263 /// Record the next node in a scheduled cluster.
264 const SUnit *NextClusterPred;
265 const SUnit *NextClusterSucc;
268 /// The number of instructions scheduled so far. Used to cut off the
269 /// scheduler at the point determined by misched-cutoff.
270 unsigned NumInstrsScheduled;
273 ScheduleDAGMI(MachineSchedContext *C, std::unique_ptr<MachineSchedStrategy> S,
274 bool RemoveKillFlags)
275 : ScheduleDAGInstrs(*C->MF, C->MLI, RemoveKillFlags), AA(C->AA),
276 LIS(C->LIS), SchedImpl(std::move(S)), Topo(SUnits, &ExitSU),
277 NextClusterPred(nullptr), NextClusterSucc(nullptr) {
279 NumInstrsScheduled = 0;
283 // Provide a vtable anchor
284 ~ScheduleDAGMI() override;
286 // Returns LiveIntervals instance for use in DAG mutators and such.
287 LiveIntervals *getLIS() const { return LIS; }
289 /// Return true if this DAG supports VReg liveness and RegPressure.
290 virtual bool hasVRegLiveness() const { return false; }
292 /// Add a postprocessing step to the DAG builder.
293 /// Mutations are applied in the order that they are added after normal DAG
294 /// building and before MachineSchedStrategy initialization.
296 /// ScheduleDAGMI takes ownership of the Mutation object.
297 void addMutation(std::unique_ptr<ScheduleDAGMutation> Mutation) {
299 Mutations.push_back(std::move(Mutation));
302 /// \brief True if an edge can be added from PredSU to SuccSU without creating
304 bool canAddEdge(SUnit *SuccSU, SUnit *PredSU);
306 /// \brief Add a DAG edge to the given SU with the given predecessor
309 /// \returns true if the edge may be added without creating a cycle OR if an
310 /// equivalent edge already existed (false indicates failure).
311 bool addEdge(SUnit *SuccSU, const SDep &PredDep);
313 MachineBasicBlock::iterator top() const { return CurrentTop; }
314 MachineBasicBlock::iterator bottom() const { return CurrentBottom; }
316 /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
317 /// region. This covers all instructions in a block, while schedule() may only
319 void enterRegion(MachineBasicBlock *bb,
320 MachineBasicBlock::iterator begin,
321 MachineBasicBlock::iterator end,
322 unsigned regioninstrs) override;
324 /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
325 /// reorderable instructions.
326 void schedule() override;
328 /// Change the position of an instruction within the basic block and update
329 /// live ranges and region boundary iterators.
330 void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos);
332 const SUnit *getNextClusterPred() const { return NextClusterPred; }
334 const SUnit *getNextClusterSucc() const { return NextClusterSucc; }
336 void viewGraph(const Twine &Name, const Twine &Title) override;
337 void viewGraph() override;
340 // Top-Level entry points for the schedule() driver...
342 /// Apply each ScheduleDAGMutation step in order. This allows different
343 /// instances of ScheduleDAGMI to perform custom DAG postprocessing.
344 void postprocessDAG();
346 /// Release ExitSU predecessors and setup scheduler queues.
347 void initQueues(ArrayRef<SUnit*> TopRoots, ArrayRef<SUnit*> BotRoots);
349 /// Update scheduler DAG and queues after scheduling an instruction.
350 void updateQueues(SUnit *SU, bool IsTopNode);
352 /// Reinsert debug_values recorded in ScheduleDAGInstrs::DbgValues.
353 void placeDebugValues();
355 /// \brief dump the scheduled Sequence.
356 void dumpSchedule() const;
359 bool checkSchedLimit();
361 void findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
362 SmallVectorImpl<SUnit*> &BotRoots);
364 void releaseSucc(SUnit *SU, SDep *SuccEdge);
365 void releaseSuccessors(SUnit *SU);
366 void releasePred(SUnit *SU, SDep *PredEdge);
367 void releasePredecessors(SUnit *SU);
370 /// ScheduleDAGMILive is an implementation of ScheduleDAGInstrs that schedules
371 /// machine instructions while updating LiveIntervals and tracking regpressure.
372 class ScheduleDAGMILive : public ScheduleDAGMI {
374 RegisterClassInfo *RegClassInfo;
376 /// Information about DAG subtrees. If DFSResult is NULL, then SchedulerTrees
378 SchedDFSResult *DFSResult;
379 BitVector ScheduledTrees;
381 MachineBasicBlock::iterator LiveRegionEnd;
383 /// Maps vregs to the SUnits of their uses in the current scheduling region.
384 VReg2SUnitMultiMap VRegUses;
386 // Map each SU to its summary of pressure changes. This array is updated for
387 // liveness during bottom-up scheduling. Top-down scheduling may proceed but
388 // has no affect on the pressure diffs.
389 PressureDiffs SUPressureDiffs;
391 /// Register pressure in this region computed by initRegPressure.
392 bool ShouldTrackPressure;
393 bool ShouldTrackLaneMasks;
394 IntervalPressure RegPressure;
395 RegPressureTracker RPTracker;
397 /// List of pressure sets that exceed the target's pressure limit before
398 /// scheduling, listed in increasing set ID order. Each pressure set is paired
399 /// with its max pressure in the currently scheduled regions.
400 std::vector<PressureChange> RegionCriticalPSets;
402 /// The top of the unscheduled zone.
403 IntervalPressure TopPressure;
404 RegPressureTracker TopRPTracker;
406 /// The bottom of the unscheduled zone.
407 IntervalPressure BotPressure;
408 RegPressureTracker BotRPTracker;
410 /// True if disconnected subregister components are already renamed.
411 /// The renaming is only done on demand if lane masks are tracked.
412 bool DisconnectedComponentsRenamed;
415 ScheduleDAGMILive(MachineSchedContext *C,
416 std::unique_ptr<MachineSchedStrategy> S)
417 : ScheduleDAGMI(C, std::move(S), /*RemoveKillFlags=*/false),
418 RegClassInfo(C->RegClassInfo), DFSResult(nullptr),
419 ShouldTrackPressure(false), ShouldTrackLaneMasks(false),
420 RPTracker(RegPressure), TopRPTracker(TopPressure),
421 BotRPTracker(BotPressure), DisconnectedComponentsRenamed(false) {}
423 ~ScheduleDAGMILive() override;
425 /// Return true if this DAG supports VReg liveness and RegPressure.
426 bool hasVRegLiveness() const override { return true; }
428 /// \brief Return true if register pressure tracking is enabled.
429 bool isTrackingPressure() const { return ShouldTrackPressure; }
431 /// Get current register pressure for the top scheduled instructions.
432 const IntervalPressure &getTopPressure() const { return TopPressure; }
433 const RegPressureTracker &getTopRPTracker() const { return TopRPTracker; }
435 /// Get current register pressure for the bottom scheduled instructions.
436 const IntervalPressure &getBotPressure() const { return BotPressure; }
437 const RegPressureTracker &getBotRPTracker() const { return BotRPTracker; }
439 /// Get register pressure for the entire scheduling region before scheduling.
440 const IntervalPressure &getRegPressure() const { return RegPressure; }
442 const std::vector<PressureChange> &getRegionCriticalPSets() const {
443 return RegionCriticalPSets;
446 PressureDiff &getPressureDiff(const SUnit *SU) {
447 return SUPressureDiffs[SU->NodeNum];
450 /// Compute a DFSResult after DAG building is complete, and before any
451 /// queue comparisons.
452 void computeDFSResult();
454 /// Return a non-null DFS result if the scheduling strategy initialized it.
455 const SchedDFSResult *getDFSResult() const { return DFSResult; }
457 BitVector &getScheduledTrees() { return ScheduledTrees; }
459 /// Implement the ScheduleDAGInstrs interface for handling the next scheduling
460 /// region. This covers all instructions in a block, while schedule() may only
462 void enterRegion(MachineBasicBlock *bb,
463 MachineBasicBlock::iterator begin,
464 MachineBasicBlock::iterator end,
465 unsigned regioninstrs) override;
467 /// Implement ScheduleDAGInstrs interface for scheduling a sequence of
468 /// reorderable instructions.
469 void schedule() override;
471 /// Compute the cyclic critical path through the DAG.
472 unsigned computeCyclicCriticalPath();
475 // Top-Level entry points for the schedule() driver...
477 /// Call ScheduleDAGInstrs::buildSchedGraph with register pressure tracking
478 /// enabled. This sets up three trackers. RPTracker will cover the entire DAG
479 /// region, TopTracker and BottomTracker will be initialized to the top and
480 /// bottom of the DAG region without covereing any unscheduled instruction.
481 void buildDAGWithRegPressure();
483 /// Release ExitSU predecessors and setup scheduler queues. Re-position
484 /// the Top RP tracker in case the region beginning has changed.
485 void initQueues(ArrayRef<SUnit*> TopRoots, ArrayRef<SUnit*> BotRoots);
487 /// Move an instruction and update register pressure.
488 void scheduleMI(SUnit *SU, bool IsTopNode);
492 void initRegPressure();
494 void updatePressureDiffs(ArrayRef<RegisterMaskPair> LiveUses);
496 void updateScheduledPressure(const SUnit *SU,
497 const std::vector<unsigned> &NewMaxPressure);
499 void collectVRegUses(SUnit &SU);
502 //===----------------------------------------------------------------------===//
504 /// Helpers for implementing custom MachineSchedStrategy classes. These take
505 /// care of the book-keeping associated with list scheduling heuristics.
507 //===----------------------------------------------------------------------===//
509 /// ReadyQueue encapsulates vector of "ready" SUnits with basic convenience
510 /// methods for pushing and removing nodes. ReadyQueue's are uniquely identified
511 /// by an ID. SUnit::NodeQueueId is a mask of the ReadyQueues the SUnit is in.
513 /// This is a convenience class that may be used by implementations of
514 /// MachineSchedStrategy.
518 std::vector<SUnit*> Queue;
521 ReadyQueue(unsigned id, const Twine &name): ID(id), Name(name.str()) {}
523 unsigned getID() const { return ID; }
525 StringRef getName() const { return Name; }
527 // SU is in this queue if it's NodeQueueID is a superset of this ID.
528 bool isInQueue(SUnit *SU) const { return (SU->NodeQueueId & ID); }
530 bool empty() const { return Queue.empty(); }
532 void clear() { Queue.clear(); }
534 unsigned size() const { return Queue.size(); }
536 typedef std::vector<SUnit*>::iterator iterator;
538 iterator begin() { return Queue.begin(); }
540 iterator end() { return Queue.end(); }
542 ArrayRef<SUnit*> elements() { return Queue; }
544 iterator find(SUnit *SU) { return llvm::find(Queue, SU); }
546 void push(SUnit *SU) {
548 SU->NodeQueueId |= ID;
551 iterator remove(iterator I) {
552 (*I)->NodeQueueId &= ~ID;
554 unsigned idx = I - Queue.begin();
556 return Queue.begin() + idx;
562 /// Summarize the unscheduled region.
563 struct SchedRemainder {
564 // Critical path through the DAG in expected latency.
565 unsigned CriticalPath;
566 unsigned CyclicCritPath;
568 // Scaled count of micro-ops left to schedule.
569 unsigned RemIssueCount;
571 bool IsAcyclicLatencyLimited;
573 // Unscheduled resources
574 SmallVector<unsigned, 16> RemainingCounts;
580 IsAcyclicLatencyLimited = false;
581 RemainingCounts.clear();
584 SchedRemainder() { reset(); }
586 void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
589 /// Each Scheduling boundary is associated with ready queues. It tracks the
590 /// current cycle in the direction of movement, and maintains the state
591 /// of "hazards" and other interlocks at the current cycle.
592 class SchedBoundary {
594 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
602 const TargetSchedModel *SchedModel;
605 ReadyQueue Available;
608 ScheduleHazardRecognizer *HazardRec;
611 /// True if the pending Q should be checked/updated before scheduling another
615 /// Number of cycles it takes to issue the instructions scheduled in this
616 /// zone. It is defined as: scheduled-micro-ops / issue-width + stalls.
620 /// Micro-ops issued in the current cycle
623 /// MinReadyCycle - Cycle of the soonest available instruction.
624 unsigned MinReadyCycle;
626 // The expected latency of the critical path in this scheduled zone.
627 unsigned ExpectedLatency;
629 // The latency of dependence chains leading into this zone.
630 // For each node scheduled bottom-up: DLat = max DLat, N.Depth.
631 // For each cycle scheduled: DLat -= 1.
632 unsigned DependentLatency;
634 /// Count the scheduled (issued) micro-ops that can be retired by
635 /// time=CurrCycle assuming the first scheduled instr is retired at time=0.
636 unsigned RetiredMOps;
638 // Count scheduled resources that have been executed. Resources are
639 // considered executed if they become ready in the time that it takes to
640 // saturate any resource including the one in question. Counts are scaled
641 // for direct comparison with other resources. Counts can be compared with
642 // MOps * getMicroOpFactor and Latency * getLatencyFactor.
643 SmallVector<unsigned, 16> ExecutedResCounts;
645 /// Cache the max count for a single resource.
646 unsigned MaxExecutedResCount;
648 // Cache the critical resources ID in this scheduled zone.
649 unsigned ZoneCritResIdx;
651 // Is the scheduled region resource limited vs. latency limited.
652 bool IsResourceLimited;
654 // Record the highest cycle at which each resource has been reserved by a
655 // scheduled instruction.
656 SmallVector<unsigned, 16> ReservedCycles;
659 // Remember the greatest possible stall as an upper bound on the number of
660 // times we should retry the pending queue because of a hazard.
661 unsigned MaxObservedStall;
665 /// Pending queues extend the ready queues with the same ID and the
667 SchedBoundary(unsigned ID, const Twine &Name):
668 DAG(nullptr), SchedModel(nullptr), Rem(nullptr), Available(ID, Name+".A"),
669 Pending(ID << LogMaxQID, Name+".P"),
678 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
679 SchedRemainder *rem);
682 return Available.getID() == TopQID;
685 /// Number of cycles to issue the instructions scheduled in this zone.
686 unsigned getCurrCycle() const { return CurrCycle; }
688 /// Micro-ops issued in the current cycle
689 unsigned getCurrMOps() const { return CurrMOps; }
691 // The latency of dependence chains leading into this zone.
692 unsigned getDependentLatency() const { return DependentLatency; }
694 /// Get the number of latency cycles "covered" by the scheduled
695 /// instructions. This is the larger of the critical path within the zone
696 /// and the number of cycles required to issue the instructions.
697 unsigned getScheduledLatency() const {
698 return std::max(ExpectedLatency, CurrCycle);
701 unsigned getUnscheduledLatency(SUnit *SU) const {
702 return isTop() ? SU->getHeight() : SU->getDepth();
705 unsigned getResourceCount(unsigned ResIdx) const {
706 return ExecutedResCounts[ResIdx];
709 /// Get the scaled count of scheduled micro-ops and resources, including
710 /// executed resources.
711 unsigned getCriticalCount() const {
713 return RetiredMOps * SchedModel->getMicroOpFactor();
714 return getResourceCount(ZoneCritResIdx);
717 /// Get a scaled count for the minimum execution time of the scheduled
718 /// micro-ops that are ready to execute by getExecutedCount. Notice the
720 unsigned getExecutedCount() const {
721 return std::max(CurrCycle * SchedModel->getLatencyFactor(),
722 MaxExecutedResCount);
725 unsigned getZoneCritResIdx() const { return ZoneCritResIdx; }
727 // Is the scheduled region resource limited vs. latency limited.
728 bool isResourceLimited() const { return IsResourceLimited; }
730 /// Get the difference between the given SUnit's ready time and the current
732 unsigned getLatencyStallCycles(SUnit *SU);
734 unsigned getNextResourceCycle(unsigned PIdx, unsigned Cycles);
736 bool checkHazard(SUnit *SU);
738 unsigned findMaxLatency(ArrayRef<SUnit*> ReadySUs);
740 unsigned getOtherResourceCount(unsigned &OtherCritIdx);
742 void releaseNode(SUnit *SU, unsigned ReadyCycle);
744 void bumpCycle(unsigned NextCycle);
746 void incExecutedResources(unsigned PIdx, unsigned Count);
748 unsigned countResource(unsigned PIdx, unsigned Cycles, unsigned ReadyCycle);
750 void bumpNode(SUnit *SU);
752 void releasePending();
754 void removeReady(SUnit *SU);
756 /// Call this before applying any other heuristics to the Available queue.
757 /// Updates the Available/Pending Q's if necessary and returns the single
758 /// available instruction, or NULL if there are multiple candidates.
759 SUnit *pickOnlyChoice();
762 void dumpScheduledState();
766 /// Base class for GenericScheduler. This class maintains information about
767 /// scheduling candidates based on TargetSchedModel making it easy to implement
768 /// heuristics for either preRA or postRA scheduling.
769 class GenericSchedulerBase : public MachineSchedStrategy {
771 /// Represent the type of SchedCandidate found within a single queue.
772 /// pickNodeBidirectional depends on these listed by decreasing priority.
773 enum CandReason : uint8_t {
774 NoCand, Only1, PhysRegCopy, RegExcess, RegCritical, Stall, Cluster, Weak,
775 RegMax, ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
776 TopDepthReduce, TopPathReduce, NextDefUse, NodeOrder};
779 static const char *getReasonStr(GenericSchedulerBase::CandReason Reason);
782 /// Policy for scheduling the next instruction in the candidate's zone.
785 unsigned ReduceResIdx;
786 unsigned DemandResIdx;
788 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
790 bool operator==(const CandPolicy &RHS) const {
791 return ReduceLatency == RHS.ReduceLatency &&
792 ReduceResIdx == RHS.ReduceResIdx &&
793 DemandResIdx == RHS.DemandResIdx;
795 bool operator!=(const CandPolicy &RHS) const {
796 return !(*this == RHS);
800 /// Status of an instruction's critical resource consumption.
801 struct SchedResourceDelta {
802 // Count critical resources in the scheduled region required by SU.
803 unsigned CritResources;
805 // Count critical resources from another region consumed by SU.
806 unsigned DemandedResources;
808 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
810 bool operator==(const SchedResourceDelta &RHS) const {
811 return CritResources == RHS.CritResources
812 && DemandedResources == RHS.DemandedResources;
814 bool operator!=(const SchedResourceDelta &RHS) const {
815 return !operator==(RHS);
819 /// Store the state used by GenericScheduler heuristics, required for the
820 /// lifetime of one invocation of pickNode().
821 struct SchedCandidate {
824 // The best SUnit candidate.
827 // The reason for this candidate.
830 // Whether this candidate should be scheduled at top/bottom.
833 // Register pressure values for the best candidate.
834 RegPressureDelta RPDelta;
836 // Critical resource consumption of the best candidate.
837 SchedResourceDelta ResDelta;
839 SchedCandidate() { reset(CandPolicy()); }
840 SchedCandidate(const CandPolicy &Policy) { reset(Policy); }
842 void reset(const CandPolicy &NewPolicy) {
847 RPDelta = RegPressureDelta();
848 ResDelta = SchedResourceDelta();
851 bool isValid() const { return SU; }
853 // Copy the status of another candidate without changing policy.
854 void setBest(SchedCandidate &Best) {
855 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
857 Reason = Best.Reason;
859 RPDelta = Best.RPDelta;
860 ResDelta = Best.ResDelta;
863 void initResourceDelta(const ScheduleDAGMI *DAG,
864 const TargetSchedModel *SchedModel);
868 const MachineSchedContext *Context;
869 const TargetSchedModel *SchedModel;
870 const TargetRegisterInfo *TRI;
874 GenericSchedulerBase(const MachineSchedContext *C):
875 Context(C), SchedModel(nullptr), TRI(nullptr) {}
877 void setPolicy(CandPolicy &Policy, bool IsPostRA, SchedBoundary &CurrZone,
878 SchedBoundary *OtherZone);
881 void traceCandidate(const SchedCandidate &Cand);
885 /// GenericScheduler shrinks the unscheduled zone using heuristics to balance
887 class GenericScheduler : public GenericSchedulerBase {
889 GenericScheduler(const MachineSchedContext *C):
890 GenericSchedulerBase(C), DAG(nullptr), Top(SchedBoundary::TopQID, "TopQ"),
891 Bot(SchedBoundary::BotQID, "BotQ") {}
893 void initPolicy(MachineBasicBlock::iterator Begin,
894 MachineBasicBlock::iterator End,
895 unsigned NumRegionInstrs) override;
897 void dumpPolicy() override;
899 bool shouldTrackPressure() const override {
900 return RegionPolicy.ShouldTrackPressure;
903 bool shouldTrackLaneMasks() const override {
904 return RegionPolicy.ShouldTrackLaneMasks;
907 void initialize(ScheduleDAGMI *dag) override;
909 SUnit *pickNode(bool &IsTopNode) override;
911 void schedNode(SUnit *SU, bool IsTopNode) override;
913 void releaseTopNode(SUnit *SU) override {
917 Top.releaseNode(SU, SU->TopReadyCycle);
918 TopCand.SU = nullptr;
921 void releaseBottomNode(SUnit *SU) override {
925 Bot.releaseNode(SU, SU->BotReadyCycle);
926 BotCand.SU = nullptr;
929 void registerRoots() override;
932 ScheduleDAGMILive *DAG;
934 MachineSchedPolicy RegionPolicy;
936 // State of the top and bottom scheduled instruction boundaries.
940 /// Candidate last picked from Top boundary.
941 SchedCandidate TopCand;
942 /// Candidate last picked from Bot boundary.
943 SchedCandidate BotCand;
945 void checkAcyclicLatency();
947 void initCandidate(SchedCandidate &Cand, SUnit *SU, bool AtTop,
948 const RegPressureTracker &RPTracker,
949 RegPressureTracker &TempTracker);
951 void tryCandidate(SchedCandidate &Cand,
952 SchedCandidate &TryCand,
953 SchedBoundary *Zone);
955 SUnit *pickNodeBidirectional(bool &IsTopNode);
957 void pickNodeFromQueue(SchedBoundary &Zone,
958 const CandPolicy &ZonePolicy,
959 const RegPressureTracker &RPTracker,
960 SchedCandidate &Candidate);
962 void reschedulePhysRegCopies(SUnit *SU, bool isTop);
965 /// PostGenericScheduler - Interface to the scheduling algorithm used by
968 /// Callbacks from ScheduleDAGMI:
969 /// initPolicy -> initialize(DAG) -> registerRoots -> pickNode ...
970 class PostGenericScheduler : public GenericSchedulerBase {
973 SmallVector<SUnit*, 8> BotRoots;
976 PostGenericScheduler(const MachineSchedContext *C):
977 GenericSchedulerBase(C), Top(SchedBoundary::TopQID, "TopQ") {}
979 ~PostGenericScheduler() override = default;
981 void initPolicy(MachineBasicBlock::iterator Begin,
982 MachineBasicBlock::iterator End,
983 unsigned NumRegionInstrs) override {
984 /* no configurable policy */
987 /// PostRA scheduling does not track pressure.
988 bool shouldTrackPressure() const override { return false; }
990 void initialize(ScheduleDAGMI *Dag) override;
992 void registerRoots() override;
994 SUnit *pickNode(bool &IsTopNode) override;
996 void scheduleTree(unsigned SubtreeID) override {
997 llvm_unreachable("PostRA scheduler does not support subtree analysis.");
1000 void schedNode(SUnit *SU, bool IsTopNode) override;
1002 void releaseTopNode(SUnit *SU) override {
1003 if (SU->isScheduled)
1005 Top.releaseNode(SU, SU->TopReadyCycle);
1008 // Only called for roots.
1009 void releaseBottomNode(SUnit *SU) override {
1010 BotRoots.push_back(SU);
1014 void tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand);
1016 void pickNodeFromQueue(SchedCandidate &Cand);
1019 /// Create the standard converging machine scheduler. This will be used as the
1020 /// default scheduler if the target does not set a default.
1021 /// Adds default DAG mutations.
1022 ScheduleDAGMILive *createGenericSchedLive(MachineSchedContext *C);
1024 /// Create a generic scheduler with no vreg liveness or DAG mutation passes.
1025 ScheduleDAGMI *createGenericSchedPostRA(MachineSchedContext *C);
1027 std::unique_ptr<ScheduleDAGMutation>
1028 createLoadClusterDAGMutation(const TargetInstrInfo *TII,
1029 const TargetRegisterInfo *TRI);
1031 std::unique_ptr<ScheduleDAGMutation>
1032 createStoreClusterDAGMutation(const TargetInstrInfo *TII,
1033 const TargetRegisterInfo *TRI);
1035 std::unique_ptr<ScheduleDAGMutation>
1036 createMacroFusionDAGMutation(const TargetInstrInfo *TII);
1038 std::unique_ptr<ScheduleDAGMutation>
1039 createCopyConstrainDAGMutation(const TargetInstrInfo *TII,
1040 const TargetRegisterInfo *TRI);
1042 } // end namespace llvm
1044 #endif // LLVM_CODEGEN_MACHINESCHEDULER_H