LLVM 22.0.0git
TargetSchedule.cpp
Go to the documentation of this file.
1//===- llvm/Target/TargetSchedule.cpp - Sched Machine Model ---------------===//
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// This file implements a wrapper around MCSchedModel that allows the interface
10// to benefit from information currently only available in TargetInstrInfo.
11//
12//===----------------------------------------------------------------------===//
13
20#include "llvm/MC/MCInstrDesc.h"
22#include "llvm/MC/MCSchedule.h"
26#include <algorithm>
27#include <cassert>
28#include <numeric>
29
30using namespace llvm;
31
33 "sched-model-force-enable-intervals", cl::Hidden, cl::init(false),
34 cl::desc("Force the use of resource intervals in the schedule model"));
35
37 return EnableSchedModel && SchedModel.hasInstrSchedModel();
38}
39
41 return EnableSchedItins && !InstrItins.isEmpty();
42}
43
45 bool EnableSModel, bool EnableSItins) {
46 STI = TSInfo;
47 SchedModel = TSInfo->getSchedModel();
48 TII = TSInfo->getInstrInfo();
49 STI->initInstrItins(InstrItins);
50
51 EnableSchedModel = EnableSModel;
52 EnableSchedItins = EnableSItins;
53
54 unsigned NumRes = SchedModel.getNumProcResourceKinds();
55 ResourceFactors.resize(NumRes);
56 ResourceLCM = SchedModel.IssueWidth;
57 for (unsigned Idx = 0; Idx < NumRes; ++Idx) {
58 unsigned NumUnits = SchedModel.getProcResource(Idx)->NumUnits;
59 if (NumUnits > 0)
60 ResourceLCM = std::lcm(ResourceLCM, NumUnits);
61 }
62 MicroOpFactor = ResourceLCM / SchedModel.IssueWidth;
63 for (unsigned Idx = 0; Idx < NumRes; ++Idx) {
64 unsigned NumUnits = SchedModel.getProcResource(Idx)->NumUnits;
65 ResourceFactors[Idx] = NumUnits ? (ResourceLCM / NumUnits) : 0;
66 }
67}
68
69/// Returns true only if instruction is specified as single issue.
71 const MCSchedClassDesc *SC) const {
72 if (hasInstrSchedModel()) {
73 if (!SC)
75 if (SC->isValid())
76 return SC->BeginGroup;
77 }
78 return false;
79}
80
82 const MCSchedClassDesc *SC) const {
83 if (hasInstrSchedModel()) {
84 if (!SC)
86 if (SC->isValid())
87 return SC->EndGroup;
88 }
89 return false;
90}
91
93 const MCSchedClassDesc *SC) const {
94 if (hasInstrItineraries()) {
95 int UOps = InstrItins.getNumMicroOps(MI->getDesc().getSchedClass());
96 return (UOps >= 0) ? UOps : TII->getNumMicroOps(&InstrItins, *MI);
97 }
98 if (hasInstrSchedModel()) {
99 if (!SC)
100 SC = resolveSchedClass(MI);
101 if (SC->isValid())
102 return SC->NumMicroOps;
103 }
104 return MI->isTransient() ? 0 : 1;
105}
106
107// The machine model may explicitly specify an invalid latency, which
108// effectively means infinite latency. Since users of the TargetSchedule API
109// don't know how to handle this, we convert it to a very large latency that is
110// easy to distinguish when debugging the DAG but won't induce overflow.
111static unsigned capLatency(int Cycles) {
112 return Cycles >= 0 ? Cycles : 1000;
113}
114
115/// Return the MCSchedClassDesc for this instruction. Some SchedClasses require
116/// evaluation of predicates that depend on instruction operands or flags.
118resolveSchedClass(const MachineInstr *MI) const {
119 // Get the definition's scheduling class descriptor from this machine model.
120 unsigned SchedClass = MI->getDesc().getSchedClass();
121 const MCSchedClassDesc *SCDesc = SchedModel.getSchedClassDesc(SchedClass);
122 if (!SCDesc->isValid())
123 return SCDesc;
124
125#ifndef NDEBUG
126 unsigned NIter = 0;
127#endif
128 while (SCDesc->isVariant()) {
129 assert(++NIter < 6 && "Variants are nested deeper than the magic number");
130
131 SchedClass = STI->resolveSchedClass(SchedClass, MI, this);
132 SCDesc = SchedModel.getSchedClassDesc(SchedClass);
133 }
134 return SCDesc;
135}
136
137/// Find the def index of this operand. This index maps to the machine model and
138/// is independent of use operands. Def operands may be reordered with uses or
139/// merged with uses without affecting the def index (e.g. before/after
140/// regalloc). However, an instruction's def operands must never be reordered
141/// with respect to each other.
142static unsigned findDefIdx(const MachineInstr *MI, unsigned DefOperIdx) {
143 unsigned DefIdx = 0;
144 for (unsigned i = 0; i != DefOperIdx; ++i) {
145 const MachineOperand &MO = MI->getOperand(i);
146 if (MO.isReg() && MO.isDef())
147 ++DefIdx;
148 }
149 return DefIdx;
150}
151
152/// Find the use index of this operand. This is independent of the instruction's
153/// def operands.
154///
155/// Note that uses are not determined by the operand's isUse property, which
156/// is simply the inverse of isDef. Here we consider any readsReg operand to be
157/// a "use". The machine model allows an operand to be both a Def and Use.
158static unsigned findUseIdx(const MachineInstr *MI, unsigned UseOperIdx) {
159 unsigned UseIdx = 0;
160 for (unsigned i = 0; i != UseOperIdx; ++i) {
161 const MachineOperand &MO = MI->getOperand(i);
162 if (MO.isReg() && MO.readsReg() && !MO.isDef())
163 ++UseIdx;
164 }
165 return UseIdx;
166}
167
168// Top-level API for clients that know the operand indices. This doesn't need to
169// return std::optional<unsigned>, as it always returns a valid latency.
171 const MachineInstr *DefMI, unsigned DefOperIdx,
172 const MachineInstr *UseMI, unsigned UseOperIdx) const {
173
174 const unsigned InstrLatency = computeInstrLatency(DefMI);
175 const unsigned DefaultDefLatency = TII->defaultDefLatency(SchedModel, *DefMI);
176
178 return DefaultDefLatency;
179
180 if (hasInstrItineraries()) {
181 std::optional<unsigned> OperLatency;
182 if (UseMI) {
183 OperLatency = TII->getOperandLatency(&InstrItins, *DefMI, DefOperIdx,
184 *UseMI, UseOperIdx);
185 }
186 else {
187 unsigned DefClass = DefMI->getDesc().getSchedClass();
188 OperLatency = InstrItins.getOperandCycle(DefClass, DefOperIdx);
189 }
190
191 // Expected latency is the max of InstrLatency and DefaultDefLatency, if we
192 // didn't find an operand latency.
193 return OperLatency ? *OperLatency
194 : std::max(InstrLatency, DefaultDefLatency);
195 }
196
197 // hasInstrSchedModel()
199 unsigned DefIdx = findDefIdx(DefMI, DefOperIdx);
200 if (DefIdx < SCDesc->NumWriteLatencyEntries) {
201 // Lookup the definition's write latency in SubtargetInfo.
202 const MCWriteLatencyEntry *WLEntry =
203 STI->getWriteLatencyEntry(SCDesc, DefIdx);
204 unsigned WriteID = WLEntry->WriteResourceID;
205 unsigned Latency = capLatency(WLEntry->Cycles);
206 if (!UseMI)
207 return Latency;
208
209 // Lookup the use's latency adjustment in SubtargetInfo.
210 const MCSchedClassDesc *UseDesc = resolveSchedClass(UseMI);
211 if (UseDesc->NumReadAdvanceEntries == 0)
212 return Latency;
213 unsigned UseIdx = findUseIdx(UseMI, UseOperIdx);
214 int Advance = STI->getReadAdvanceCycles(UseDesc, UseIdx, WriteID);
215 if (Advance > 0 && (unsigned)Advance > Latency) // unsigned wrap
216 return 0;
217 return Latency - Advance;
218 }
219 // If DefIdx does not exist in the model (e.g. implicit defs), then return
220 // unit latency (defaultDefLatency may be too conservative).
221#ifndef NDEBUG
222 if (SCDesc->isValid() && !DefMI->getOperand(DefOperIdx).isImplicit() &&
223 !DefMI->getDesc().operands()[DefOperIdx].isOptionalDef() &&
224 SchedModel.isComplete()) {
225 errs() << "DefIdx " << DefIdx << " exceeds machine model writes for "
226 << *DefMI << " (Try with MCSchedModel.CompleteModel set to false)";
227 llvm_unreachable("incomplete machine model");
228 }
229#endif
230 // FIXME: Automatically giving all implicit defs defaultDefLatency is
231 // undesirable. We should only do it for defs that are known to the MC
232 // desc like flags. Truly implicit defs should get 1 cycle latency.
233 return DefMI->isTransient() ? 0 : DefaultDefLatency;
234}
235
236unsigned
237TargetSchedModel::computeInstrLatency(const MCSchedClassDesc &SCDesc) const {
238 return capLatency(MCSchedModel::computeInstrLatency(*STI, SCDesc));
239}
240
241unsigned TargetSchedModel::computeInstrLatency(unsigned Opcode) const {
242 assert(hasInstrSchedModel() && "Only call this function with a SchedModel");
243 unsigned SCIdx = TII->get(Opcode).getSchedClass();
244 return capLatency(SchedModel.computeInstrLatency(*STI, SCIdx));
245}
246
247unsigned TargetSchedModel::computeInstrLatency(const MCInst &Inst) const {
248 if (hasInstrSchedModel())
249 return capLatency(SchedModel.computeInstrLatency(*STI, *TII, Inst));
250 return computeInstrLatency(Inst.getOpcode());
251}
252
253unsigned
254TargetSchedModel::computeInstrLatency(const MachineInstr *MI,
255 bool UseDefaultDefLatency) const {
256 // For the itinerary model, fall back to the old subtarget hook.
257 // Allow subtargets to compute Bundle latencies outside the machine model.
258 if (hasInstrItineraries() || MI->isBundle() ||
259 (!hasInstrSchedModel() && !UseDefaultDefLatency))
260 return TII->getInstrLatency(&InstrItins, *MI);
261
262 if (hasInstrSchedModel()) {
263 const MCSchedClassDesc *SCDesc = resolveSchedClass(MI);
264 if (SCDesc->isValid())
265 return computeInstrLatency(*SCDesc);
266 }
267 return TII->defaultDefLatency(SchedModel, *MI);
268}
269
271computeOutputLatency(const MachineInstr *DefMI, unsigned DefOperIdx,
272 const MachineInstr *DepMI) const {
273 if (!SchedModel.isOutOfOrder())
274 return 1;
275
276 // Out-of-order processor can dispatch WAW dependencies in the same cycle.
277
278 // Treat predication as a data dependency for out-of-order cpus. In-order
279 // cpus do not need to treat predicated writes specially.
280 //
281 // TODO: The following hack exists because predication passes do not
282 // correctly append imp-use operands, and readsReg() strangely returns false
283 // for predicated defs.
284 Register Reg = DefMI->getOperand(DefOperIdx).getReg();
285 const MachineFunction &MF = *DefMI->getMF();
287 if (!DepMI->readsRegister(Reg, TRI) && TII->isPredicated(*DepMI))
288 return computeInstrLatency(DefMI);
289
290 // If we have a per operand scheduling model, check if this def is writing
291 // an unbuffered resource. If so, it treated like an in-order cpu.
292 if (hasInstrSchedModel()) {
294 if (SCDesc->isValid()) {
295 for (const MCWriteProcResEntry *PRI = STI->getWriteProcResBegin(SCDesc),
296 *PRE = STI->getWriteProcResEnd(SCDesc); PRI != PRE; ++PRI) {
297 if (!SchedModel.getProcResource(PRI->ProcResourceIdx)->BufferSize)
298 return 1;
299 }
300 }
301 }
302 return 0;
303}
304
305double
307 if (hasInstrItineraries()) {
308 unsigned SchedClass = MI->getDesc().getSchedClass();
311 }
312
313 if (hasInstrSchedModel())
315
316 return 0.0;
317}
318
319double
321 unsigned SchedClass = TII->get(Opcode).getSchedClass();
325 if (hasInstrSchedModel()) {
326 const MCSchedClassDesc &SCDesc = *SchedModel.getSchedClassDesc(SchedClass);
327 if (SCDesc.isValid() && !SCDesc.isVariant())
328 return MCSchedModel::getReciprocalThroughput(*STI, SCDesc);
329 }
330
331 return 0.0;
332}
333
334double
336 if (hasInstrSchedModel())
337 return SchedModel.getReciprocalThroughput(*STI, *TII, MI);
338 return computeReciprocalThroughput(MI.getOpcode());
339}
340
343 return true;
344
345 return SchedModel.EnableIntervals;
346}
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
IRTranslator LLVM IR MI
Register const TargetRegisterInfo * TRI
static unsigned findUseIdx(const MachineInstr *MI, unsigned UseOperIdx)
Find the use index of this operand.
static unsigned capLatency(int Cycles)
static unsigned findDefIdx(const MachineInstr *MI, unsigned DefOperIdx)
Find the def index of this operand.
static cl::opt< bool > ForceEnableIntervals("sched-model-force-enable-intervals", cl::Hidden, cl::init(false), cl::desc("Force the use of resource intervals in the schedule model"))
int getNumMicroOps(unsigned ItinClassIndx) const
Return the number of micro-ops that the given class decodes to.
std::optional< unsigned > getOperandCycle(unsigned ItinClassIndx, unsigned OperandIdx) const
Return the cycle for the given class and operand.
bool isEmpty() const
Returns true if there are no itineraries.
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:188
unsigned getOpcode() const
Definition: MCInst.h:202
unsigned getSchedClass() const
Return the scheduling class for this instruction.
Definition: MCInstrDesc.h:603
ArrayRef< MCOperandInfo > operands() const
Definition: MCInstrDesc.h:240
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition: MCInstrInfo.h:64
const MCWriteProcResEntry * getWriteProcResEnd(const MCSchedClassDesc *SC) const
int getReadAdvanceCycles(const MCSchedClassDesc *SC, unsigned UseIdx, unsigned WriteResID) const
const MCWriteLatencyEntry * getWriteLatencyEntry(const MCSchedClassDesc *SC, unsigned DefIdx) const
void initInstrItins(InstrItineraryData &InstrItins) const
Initialize an InstrItineraryData instance.
const MCWriteProcResEntry * getWriteProcResBegin(const MCSchedClassDesc *SC) const
Return an iterator at the first process resource consumed by the given scheduling class.
const MCSchedModel & getSchedModel() const
Get the machine model for this subtarget's CPU.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Representation of each machine instruction.
Definition: MachineInstr.h:72
bool readsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr reads the specified register.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:584
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
bool isTransient() const
Return true if this is a transient instruction that is either very likely to be eliminated during reg...
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:595
MachineOperand class - Representation of each machine instruction operand.
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register.
bool isImplicit() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Register getReg() const
getReg - Returns the register number.
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
void resize(size_type N)
Definition: SmallVector.h:639
virtual unsigned getNumMicroOps(const InstrItineraryData *ItinData, const MachineInstr &MI) const
Return the number of u-operations the given machine instruction will be decoded to on the target cpu.
virtual std::optional< unsigned > getOperandLatency(const InstrItineraryData *ItinData, SDNode *DefNode, unsigned DefIdx, SDNode *UseNode, unsigned UseIdx) const
virtual bool isPredicated(const MachineInstr &MI) const
Returns true if the instruction is already predicated.
virtual unsigned getInstrLatency(const InstrItineraryData *ItinData, const MachineInstr &MI, unsigned *PredCost=nullptr) const
Compute the instruction latency of a given instruction.
unsigned defaultDefLatency(const MCSchedModel &SchedModel, const MachineInstr &DefMI) const
Return the default expected latency for a def based on its opcode.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
LLVM_ABI bool mustEndGroup(const MachineInstr *MI, const MCSchedClassDesc *SC=nullptr) const
Return true if current group must end.
LLVM_ABI bool hasInstrSchedModel() const
Return true if this machine model includes an instruction-level scheduling model.
LLVM_ABI unsigned computeOutputLatency(const MachineInstr *DefMI, unsigned DefOperIdx, const MachineInstr *DepMI) const
Output dependency latency of a pair of defs of the same register.
LLVM_ABI bool mustBeginGroup(const MachineInstr *MI, const MCSchedClassDesc *SC=nullptr) const
Return true if new group must begin.
LLVM_ABI void init(const TargetSubtargetInfo *TSInfo, bool EnableSModel=true, bool EnableSItins=true)
Initialize the machine model for instruction scheduling.
LLVM_ABI const MCSchedClassDesc * resolveSchedClass(const MachineInstr *MI) const
Return the MCSchedClassDesc for this instruction.
LLVM_ABI unsigned computeOperandLatency(const MachineInstr *DefMI, unsigned DefOperIdx, const MachineInstr *UseMI, unsigned UseOperIdx) const
Compute operand latency based on the available machine model.
LLVM_ABI double computeReciprocalThroughput(const MachineInstr *MI) const
Compute the reciprocal throughput of the given instruction.
LLVM_ABI unsigned getNumMicroOps(const MachineInstr *MI, const MCSchedClassDesc *SC=nullptr) const
Return the number of issue slots required for this MI.
const InstrItineraryData * getInstrItineraries() const
LLVM_ABI bool enableIntervals() const
LLVM_ABI bool hasInstrItineraries() const
Return true if this machine model includes cycle-to-cycle itinerary data.
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual unsigned resolveSchedClass(unsigned SchedClass, const MachineInstr *MI, const TargetSchedModel *SchedModel) const
Resolve a SchedClass at runtime, where SchedClass identifies an MCSchedClassDesc with the isVariant p...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:444
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Summarize the scheduling resources required for an instruction of a particular scheduling class.
Definition: MCSchedule.h:123
bool isValid() const
Definition: MCSchedule.h:141
bool isVariant() const
Definition: MCSchedule.h:144
uint16_t NumReadAdvanceEntries
Definition: MCSchedule.h:139
bool isOutOfOrder() const
Return true if machine supports out of order execution.
Definition: MCSchedule.h:353
const MCSchedClassDesc * getSchedClassDesc(unsigned SchedClassIdx) const
Definition: MCSchedule.h:366
unsigned getNumProcResourceKinds() const
Definition: MCSchedule.h:355
bool hasInstrSchedModel() const
Does this machine model include instruction-level scheduling.
Definition: MCSchedule.h:340
static LLVM_ABI int computeInstrLatency(const MCSubtargetInfo &STI, const MCSchedClassDesc &SCDesc)
Returns the latency value for the scheduling class.
Definition: MCSchedule.cpp:43
unsigned IssueWidth
Definition: MCSchedule.h:270
const MCProcResourceDesc * getProcResource(unsigned ProcResourceIdx) const
Definition: MCSchedule.h:359
static LLVM_ABI double getReciprocalThroughput(const MCSubtargetInfo &STI, const MCSchedClassDesc &SCDesc)
Definition: MCSchedule.cpp:98
bool isComplete() const
Return true if this machine model data for all instructions with a scheduling class (itinerary class ...
Definition: MCSchedule.h:350
Specify the latency in cpu cycles for a particular scheduling class and def index.
Definition: MCSchedule.h:91
Identify one of the processor resource kinds consumed by a particular scheduling class for the specif...
Definition: MCSchedule.h:68