LLVM 24.0.0git
ScheduleDAGInstrs.h
Go to the documentation of this file.
1//===- ScheduleDAGInstrs.h - MachineInstr Scheduling ------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file Implements the ScheduleDAGInstrs class, which implements scheduling
10/// for a MachineInstr-based dependency graph.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CODEGEN_SCHEDULEDAGINSTRS_H
15#define LLVM_CODEGEN_SCHEDULEDAGINSTRS_H
16
17#include "llvm/ADT/DenseMap.h"
26#include "llvm/MC/LaneBitmask.h"
28#include <cassert>
29#include <cstdint>
30#include <string>
31#include <utility>
32#include <vector>
33
34namespace llvm {
35
36 class AAResults;
37 class LiveIntervals;
38 class MachineFrameInfo;
39 class MachineFunction;
40 class MachineInstr;
41 class MachineLoopInfo;
42 class MachineOperand;
43 struct MCSchedClassDesc;
44 class PressureDiffs;
48 class UndefValue;
49 class Value;
50
51 /// An individual mapping from virtual register number to SUnit.
52 struct VReg2SUnit {
56
59
60 unsigned getSparseSetIndex() const {
61 return VirtReg.virtRegIndex();
62 }
63 };
64
65 /// Mapping from virtual register to SUnit including an operand index.
73
74 /// Record a physical register access.
75 /// For non-data-dependent uses, OpIdx == -1.
78 int OpIdx;
79 MCRegUnit RegUnit;
80
81 PhysRegSUOper(SUnit *su, int op, MCRegUnit R)
82 : SU(su), OpIdx(op), RegUnit(R) {}
83
84 unsigned getSparseSetIndex() const {
85 return static_cast<unsigned>(RegUnit);
86 }
87 };
88
89 /// Use a SparseMultiSet to track physical registers. Storage is only
90 /// allocated once for the pass. It can be cleared in constant time and reused
91 /// without any frees.
94
95 /// Track local uses of virtual registers. These uses are gathered by the DAG
96 /// builder and may be consulted by the scheduler to avoid iterating an entire
97 /// vreg use list.
100
103
105
107
108 /// A ScheduleDAG for scheduling lists of MachineInstr.
110 protected:
111 const MachineLoopInfo *MLI = nullptr;
113
114 /// TargetSchedModel provides an interface to the machine model.
116
117 /// True if the DAG builder should remove kill flags (in preparation for
118 /// rescheduling).
120
121 /// True if regions with a single MI should be scheduled.
123
124 /// The standard DAG builder does not normally include terminators as DAG
125 /// nodes because it does not create the necessary dependencies to prevent
126 /// reordering. A specialized scheduler can override
127 /// TargetInstrInfo::isSchedulingBoundary then enable this flag to indicate
128 /// it has taken responsibility for scheduling the terminator correctly.
130
131 /// Whether lane masks should get tracked.
132 bool TrackLaneMasks = false;
133
134 // State specific to the current scheduling region.
135 // ------------------------------------------------
136
137 /// The block in which to insert instructions
139
140 /// The beginning of the range to be scheduled.
142
143 /// The end of the range to be scheduled.
145
146 /// Instructions in this region (distance(RegionBegin, RegionEnd)).
147 unsigned NumRegionInstrs = 0;
148
149 /// After calling BuildSchedGraph, each machine instruction in the current
150 /// scheduling region is mapped to an SUnit.
152
153 // State internal to DAG building.
154 // -------------------------------
155
156 /// Defs, Uses - Remember where defs and uses of each register are as we
157 /// iterate upward through the instructions. This is allocated here instead
158 /// of inside BuildSchedGraph to avoid the need for it to be initialized and
159 /// destructed for each block.
162
163 /// Tracks the last instruction(s) in this region defining each virtual
164 /// register. There may be multiple current definitions for a register with
165 /// disjunct lanemasks.
167 /// Tracks the last instructions in this region using each virtual register.
169
171
173
174 public:
175 /// The direction that should be used to dump the scheduled Sequence.
182
184
185 protected:
187
188 /// Topo - A topological ordering for SUnits which permits fast IsReachable
189 /// and similar queries.
191
193 std::vector<std::pair<MachineInstr *, MachineInstr *>>;
194 /// Remember instruction that precedes DBG_VALUE.
195 /// These are generated by buildSchedGraph but persist so they can be
196 /// referenced when emitting the final schedule.
199
200 /// Set of live physical registers for updating kill flags.
202
203 public:
205 const MachineLoopInfo *mli,
206 bool RemoveKillFlags = false);
207
208 ~ScheduleDAGInstrs() override = default;
209
210 /// Gets the machine model for instruction scheduling.
211 const TargetSchedModel *getSchedModel() const { return &SchedModel; }
212
213 /// Resolves and cache a resolved scheduling class for an SUnit.
215 if (!SU->SchedClass && SchedModel.hasInstrSchedModel())
216 SU->SchedClass = SchedModel.resolveSchedClass(SU->getInstr());
217 return SU->SchedClass;
218 }
219
220 /// IsReachable - Checks if SU is reachable from TargetSU.
221 bool IsReachable(SUnit *SU, SUnit *TargetSU) {
222 return Topo.IsReachable(SU, TargetSU);
223 }
224
225 /// Whether regions with a single MI should be scheduled.
229
230 /// Returns an iterator to the top of the current scheduling region.
232
233 /// Returns an iterator to the bottom of the current scheduling region.
235
236 /// Creates a new SUnit and return a ptr to it.
237 SUnit *newSUnit(MachineInstr *MI);
238
239 /// Returns an existing SUnit for this MI, or nullptr.
240 SUnit *getSUnit(MachineInstr *MI) const;
241
242 /// If this method returns true, handling of the scheduling regions
243 /// themselves (in case of a scheduling boundary in MBB) will be done
244 /// beginning with the topmost region of MBB.
245 virtual bool doMBBSchedRegionsTopDown() const { return false; }
246
247 /// Prepares to perform scheduling in the given block.
248 virtual void startBlock(MachineBasicBlock *BB);
249
250 /// Cleans up after scheduling in the given block.
251 virtual void finishBlock();
252
253 /// Initialize the DAG and common scheduler state for a new
254 /// scheduling region. This does not actually create the DAG, only clears
255 /// it. The scheduling driver may call BuildSchedGraph multiple times per
256 /// scheduling region.
257 virtual void enterRegion(MachineBasicBlock *bb,
260 unsigned regioninstrs);
261
262 /// Called when the scheduler has finished scheduling the current region.
263 virtual void exitRegion();
264
265 /// Builds SUnits for the current region.
266 /// If \p RPTracker is non-null, compute register pressure as a side effect.
267 /// The DAG builder is an efficient place to do it because it already visits
268 /// operands.
269 void buildSchedGraph(AAResults *AA,
270 RegPressureTracker *RPTracker = nullptr,
271 PressureDiffs *PDiffs = nullptr,
272 LiveIntervals *LIS = nullptr,
273 bool TrackLaneMasks = false);
274
275 /// Adds dependencies from instructions in the current list of
276 /// instructions being scheduled to scheduling barrier. We want to make sure
277 /// instructions which define registers that are either used by the
278 /// terminator or are live-out are properly scheduled. This is especially
279 /// important when the definition latency of the return value(s) are too
280 /// high to be hidden by the branch or when the liveout registers used by
281 /// instructions in the fallthrough block.
282 void addSchedBarrierDeps();
283
284 /// Orders nodes according to selected style.
285 ///
286 /// Typically, a scheduling algorithm will implement schedule() without
287 /// overriding enterRegion() or exitRegion().
288 virtual void schedule() = 0;
289
290 /// Allow targets to perform final scheduling actions at the level of the
291 /// whole MachineFunction. By default does nothing.
292 virtual void finalizeSchedule() {}
293
294 void dumpNode(const SUnit &SU) const override;
295 void dump() const override;
296
297 /// Returns a label for a DAG node that points to an instruction.
298 std::string getGraphNodeLabel(const SUnit *SU) const override;
299
300 /// Returns a label for the region of code covered by the DAG.
301 std::string getDAGName() const override;
302
303 /// Fixes register kill flags that scheduling has made invalid.
304 void fixupKills(MachineBasicBlock &MBB);
305
306 /// True if an edge can be added from PredSU to SuccSU without creating
307 /// a cycle.
308 bool canAddEdge(SUnit *SuccSU, SUnit *PredSU);
309
310 /// Add a DAG edge to the given SU with the given predecessor
311 /// dependence data.
312 ///
313 /// \returns true if the edge may be added without creating a cycle OR if an
314 /// equivalent edge already existed (false indicates failure).
315 bool addEdge(SUnit *SuccSU, const SDep &PredDep);
316
317 /// Returns the array of the clusters.
319
320 /// Get the specific cluster, return nullptr for InvalidClusterId.
321 ClusterInfo *getCluster(unsigned Idx) {
322 return Idx != InvalidClusterId ? &Clusters[Idx] : nullptr;
323 }
324
325 protected:
326 void initSUnits();
327 void addPhysRegDataDeps(SUnit *SU, unsigned OperIdx);
328 void addPhysRegDeps(SUnit *SU, unsigned OperIdx);
329 void addVRegDefDeps(SUnit *SU, unsigned OperIdx);
330 void addVRegUseDeps(SUnit *SU, unsigned OperIdx);
331
332 /// Returns a mask for which lanes get read/written by the given (register)
333 /// machine operand.
334 LaneBitmask getLaneMaskForMO(const MachineOperand &MO) const;
335
336 /// Returns true if the def register in \p MO has no uses.
337 bool deadDefHasNoUse(const MachineOperand &MO);
338 };
339
340 /// Creates a new SUnit and return a ptr to it.
342#ifndef NDEBUG
343 const SUnit *Addr = SUnits.empty() ? nullptr : &SUnits[0];
344#endif
345 SUnits.emplace_back(MI, (unsigned)SUnits.size());
346 assert((Addr == nullptr || Addr == &SUnits[0]) &&
347 "SUnits std::vector reallocated on the fly!");
348 return &SUnits.back();
349 }
350
351 /// Returns an existing SUnit for this MI, or nullptr.
353 return MISUnitMap.lookup(MI);
354 }
355
356} // end namespace llvm
357
358#endif // LLVM_CODEGEN_SCHEDULEDAGINSTRS_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define LLVM_ABI
Definition Compiler.h:215
This file defines the DenseMap class.
#define op(i)
IRTranslator LLVM IR MI
A common definition of LaneBitmask for use in TableGen and CodeGen.
static void addEdge(SmallVectorImpl< LazyCallGraph::Edge > &Edges, DenseMap< LazyCallGraph::Node *, int > &EdgeIndexMap, LazyCallGraph::Node &N, LazyCallGraph::Edge::Kind EK)
A set of register units.
This file defines the PointerUnion class, which is a discriminated union of pointer types.
This file defines the SmallVector class.
This file defines the SparseMultiSet class, which adds multiset behavior to the SparseSet.
A set of register units used to track register liveness.
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
A discriminated union of two or more pointer types, with the discriminator in the low bits of the poi...
Array of PressureDiffs.
Special value supplied for machine level alias analysis.
Track the current register pressure at some position in the instruction stream, and remember the high...
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Scheduling dependency.
Definition ScheduleDAG.h:53
Scheduling unit. This is a node in the scheduling DAG.
const MCSchedClassDesc * SchedClass
nullptr or resolved SchedClass.
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
LiveRegUnits LiveRegs
Set of live physical registers for updating kill flags.
DenseMap< MachineInstr *, SUnit * > MISUnitMap
After calling BuildSchedGraph, each machine instruction in the current scheduling region is mapped to...
SmallVector< ClusterInfo > & getClusters()
Returns the array of the clusters.
MachineBasicBlock::iterator end() const
Returns an iterator to the bottom of the current scheduling region.
MachineBasicBlock * BB
The block in which to insert instructions.
bool CanHandleTerminators
The standard DAG builder does not normally include terminators as DAG nodes because it does not creat...
bool ScheduleSingleMIRegions
True if regions with a single MI should be scheduled.
friend class ScheduleDAGDependencyBuilder
const TargetSchedModel * getSchedModel() const
Gets the machine model for instruction scheduling.
MachineBasicBlock::iterator RegionEnd
The end of the range to be scheduled.
VReg2SUnitOperIdxMultiMap CurrentVRegUses
Tracks the last instructions in this region using each virtual register.
const MCSchedClassDesc * getSchedClass(SUnit *SU) const
Resolves and cache a resolved scheduling class for an SUnit.
~ScheduleDAGInstrs() override=default
ScheduleDAGInstrs(MachineFunction &mf, const MachineLoopInfo *mli, bool RemoveKillFlags=false)
bool shouldScheduleSingleMIRegions() const
Whether regions with a single MI should be scheduled.
DbgValueVector DbgValues
Remember instruction that precedes DBG_VALUE.
std::vector< std::pair< MachineInstr *, MachineInstr * > > DbgValueVector
SUnit * newSUnit(MachineInstr *MI)
Creates a new SUnit and return a ptr to it.
virtual void finalizeSchedule()
Allow targets to perform final scheduling actions at the level of the whole MachineFunction.
ScheduleDAGTopologicalSort Topo
Topo - A topological ordering for SUnits which permits fast IsReachable and similar queries.
DumpDirection
The direction that should be used to dump the scheduled Sequence.
bool TrackLaneMasks
Whether lane masks should get tracked.
ClusterInfo * getCluster(unsigned Idx)
Get the specific cluster, return nullptr for InvalidClusterId.
bool IsReachable(SUnit *SU, SUnit *TargetSU)
IsReachable - Checks if SU is reachable from TargetSU.
RegUnit2SUnitsMap Defs
Defs, Uses - Remember where defs and uses of each register are as we iterate upward through the instr...
VReg2SUnitMultiMap CurrentVRegDefs
Tracks the last instruction(s) in this region defining each virtual register.
MachineBasicBlock::iterator begin() const
Returns an iterator to the top of the current scheduling region.
SUnit * getSUnit(MachineInstr *MI) const
Returns an existing SUnit for this MI, or nullptr.
TargetSchedModel SchedModel
TargetSchedModel provides an interface to the machine model.
virtual void schedule()=0
Orders nodes according to selected style.
const MachineLoopInfo * MLI
bool RemoveKillFlags
True if the DAG builder should remove kill flags (in preparation for rescheduling).
MachineBasicBlock::iterator RegionBegin
The beginning of the range to be scheduled.
unsigned NumRegionInstrs
Instructions in this region (distance(RegionBegin, RegionEnd)).
const MachineFrameInfo & MFI
SmallVector< ClusterInfo > Clusters
virtual bool doMBBSchedRegionsTopDown() const
If this method returns true, handling of the scheduling regions themselves (in case of a scheduling b...
void setDumpDirection(DumpDirection D)
This class can compute a topological ordering for SUnits and provides methods for dynamically updatin...
std::vector< SUnit > SUnits
The scheduling units.
ScheduleDAG(const ScheduleDAG &)=delete
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Fast multiset implementation for objects that can be identified by small unsigned keys.
Provide an instruction scheduling machine model to CodeGen passes.
'undef' values are things that do not have specified contents.
Definition Constants.h:1657
LLVM Value Representation.
Definition Value.h:75
Abstract Attribute helper functions.
Definition Attributor.h:165
This is an optimization pass for GlobalISel generic memory operations.
SparseMultiSet< VReg2SUnitOperIdx, Register, VirtReg2IndexFunctor > VReg2SUnitOperIdxMultiMap
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
SmallVector< ValueType, 4 > UnderlyingObjectsVector
SparseMultiSet< VReg2SUnit, Register, VirtReg2IndexFunctor > VReg2SUnitMultiMap
Track local uses of virtual registers.
constexpr unsigned InvalidClusterId
SmallPtrSet< SUnit *, 8 > ClusterInfo
Keep record of which SUnit are in the same cluster group.
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
SparseMultiSet< PhysRegSUOper, MCRegUnit, MCRegUnitToIndex, uint16_t > RegUnit2SUnitsMap
Use a SparseMultiSet to track physical registers.
Summarize the scheduling resources required for an instruction of a particular scheduling class.
Definition MCSchedule.h:129
unsigned getSparseSetIndex() const
PhysRegSUOper(SUnit *su, int op, MCRegUnit R)
VReg2SUnitOperIdx(Register VReg, LaneBitmask LaneMask, unsigned OperandIndex, SUnit *SU)
VReg2SUnit(Register VReg, LaneBitmask LaneMask, SUnit *SU)
unsigned getSparseSetIndex() const