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
14#include "llvm/CodeGen/TargetSchedule.h"
15#include "llvm/CodeGen/MachineFunction.h"
16#include "llvm/CodeGen/MachineInstr.h"
17#include "llvm/CodeGen/MachineOperand.h"
18#include "llvm/CodeGen/TargetInstrInfo.h"
19#include "llvm/CodeGen/TargetSubtargetInfo.h"
20#include "llvm/MC/MCInstrDesc.h"
21#include "llvm/MC/MCInstrItineraries.h"
22#include "llvm/MC/MCSchedule.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/ErrorHandling.h"
25#include "llvm/Support/raw_ostream.h"
26#include <algorithm>
27#include <cassert>
28
29using namespace llvm;
30
31static cl::opt<bool> ForceEnableIntervals(
32 "sched-model-force-enable-intervals", cl::Hidden, cl::init(Val: false),
33 cl::desc("Force the use of resource intervals in the schedule model"));
34
35bool TargetSchedModel::hasInstrSchedModel() const {
36 return EnableSchedModel && SchedModel.hasInstrSchedModel();
37}
38
39bool TargetSchedModel::hasInstrItineraries() const {
40 return EnableSchedItins && !InstrItins.isEmpty();
41}
42
43void TargetSchedModel::init(const TargetSubtargetInfo *TSInfo,
44 bool EnableSModel, bool EnableSItins) {
45 STI = TSInfo;
46 SchedModel = TSInfo->getSchedModel();
47 TII = TSInfo->getInstrInfo();
48 STI->initInstrItins(InstrItins);
49
50 EnableSchedModel = EnableSModel;
51 EnableSchedItins = EnableSItins;
52
53 unsigned NumRes = SchedModel.getNumProcResourceKinds();
54 ResourceFactors.resize(N: NumRes);
55 ResourceLCM = SchedModel.IssueWidth;
56 for (unsigned Idx = 0; Idx < NumRes; ++Idx) {
57 unsigned NumUnits = SchedModel.getProcResource(ProcResourceIdx: Idx)->NumUnits;
58 if (NumUnits > 0)
59 ResourceLCM = std::lcm(m: ResourceLCM, n: NumUnits);
60 }
61 MicroOpFactor = ResourceLCM / SchedModel.IssueWidth;
62 for (unsigned Idx = 0; Idx < NumRes; ++Idx) {
63 unsigned NumUnits = SchedModel.getProcResource(ProcResourceIdx: Idx)->NumUnits;
64 ResourceFactors[Idx] = NumUnits ? (ResourceLCM / NumUnits) : 0;
65 }
66}
67
68/// Returns true only if instruction is specified as single issue.
69bool TargetSchedModel::mustBeginGroup(const MachineInstr *MI,
70 const MCSchedClassDesc *SC) const {
71 if (hasInstrSchedModel()) {
72 if (!SC)
73 SC = resolveSchedClass(MI);
74 if (SC->isValid())
75 return SC->BeginGroup;
76 }
77 return false;
78}
79
80bool TargetSchedModel::mustEndGroup(const MachineInstr *MI,
81 const MCSchedClassDesc *SC) const {
82 if (hasInstrSchedModel()) {
83 if (!SC)
84 SC = resolveSchedClass(MI);
85 if (SC->isValid())
86 return SC->EndGroup;
87 }
88 return false;
89}
90
91unsigned TargetSchedModel::getNumMicroOps(const MachineInstr *MI,
92 const MCSchedClassDesc *SC) const {
93 if (hasInstrItineraries()) {
94 int UOps = InstrItins.getNumMicroOps(ItinClassIndx: MI->getDesc().getSchedClass());
95 return (UOps >= 0) ? UOps : TII->getNumMicroOps(ItinData: &InstrItins, MI: *MI);
96 }
97 if (hasInstrSchedModel()) {
98 if (!SC)
99 SC = resolveSchedClass(MI);
100 if (SC->isValid())
101 return SC->NumMicroOps;
102 }
103 return MI->isTransient() ? 0 : 1;
104}
105
106// The machine model may explicitly specify an invalid latency, which
107// effectively means infinite latency. Since users of the TargetSchedule API
108// don't know how to handle this, we convert it to a very large latency that is
109// easy to distinguish when debugging the DAG but won't induce overflow.
110static unsigned capLatency(int Cycles) {
111 return Cycles >= 0 ? Cycles : 1000;
112}
113
114/// Return the MCSchedClassDesc for this instruction. Some SchedClasses require
115/// evaluation of predicates that depend on instruction operands or flags.
116const MCSchedClassDesc *TargetSchedModel::
117resolveSchedClass(const MachineInstr *MI) const {
118 // Get the definition's scheduling class descriptor from this machine model.
119 unsigned SchedClass = MI->getDesc().getSchedClass();
120 const MCSchedClassDesc *SCDesc = SchedModel.getSchedClassDesc(SchedClassIdx: SchedClass);
121 if (!SCDesc->isValid())
122 return SCDesc;
123
124#ifndef NDEBUG
125 unsigned NIter = 0;
126#endif
127 while (SCDesc->isVariant()) {
128 assert(++NIter < 6 && "Variants are nested deeper than the magic number");
129
130 SchedClass = STI->resolveSchedClass(SchedClass, MI, SchedModel: this);
131 SCDesc = SchedModel.getSchedClassDesc(SchedClassIdx: SchedClass);
132 }
133 return SCDesc;
134}
135
136/// Find the def index of this operand. This index maps to the machine model and
137/// is independent of use operands. Def operands may be reordered with uses or
138/// merged with uses without affecting the def index (e.g. before/after
139/// regalloc). However, an instruction's def operands must never be reordered
140/// with respect to each other.
141static unsigned findDefIdx(const MachineInstr *MI, unsigned DefOperIdx) {
142 unsigned DefIdx = 0;
143 for (unsigned i = 0; i != DefOperIdx; ++i) {
144 const MachineOperand &MO = MI->getOperand(i);
145 if (MO.isReg() && MO.isDef())
146 ++DefIdx;
147 }
148 return DefIdx;
149}
150
151/// Find the use index of this operand. This is independent of the instruction's
152/// def operands.
153///
154/// Note that uses are not determined by the operand's isUse property, which
155/// is simply the inverse of isDef. Here we consider any readsReg operand to be
156/// a "use". The machine model allows an operand to be both a Def and Use.
157static unsigned findUseIdx(const MachineInstr *MI, unsigned UseOperIdx) {
158 unsigned UseIdx = 0;
159 for (unsigned i = 0; i != UseOperIdx; ++i) {
160 const MachineOperand &MO = MI->getOperand(i);
161 if (MO.isReg() && MO.readsReg() && !MO.isDef())
162 ++UseIdx;
163 }
164 return UseIdx;
165}
166
167// Top-level API for clients that know the operand indices. This doesn't need to
168// return std::optional<unsigned>, as it always returns a valid latency.
169unsigned TargetSchedModel::computeOperandLatency(
170 const MachineInstr *DefMI, unsigned DefOperIdx,
171 const MachineInstr *UseMI, unsigned UseOperIdx) const {
172
173 const unsigned InstrLatency = computeInstrLatency(MI: DefMI);
174 const unsigned DefaultDefLatency =
175 TII->defaultDefLatency(STI: *STI, SchedModel, DefMI: *DefMI);
176
177 if (!hasInstrSchedModel() && !hasInstrItineraries())
178 return DefaultDefLatency;
179
180 if (hasInstrItineraries()) {
181 std::optional<unsigned> OperLatency;
182 if (UseMI) {
183 OperLatency = TII->getOperandLatency(ItinData: &InstrItins, DefMI: *DefMI, DefIdx: DefOperIdx,
184 UseMI: *UseMI, UseIdx: UseOperIdx);
185 }
186 else {
187 unsigned DefClass = DefMI->getDesc().getSchedClass();
188 OperLatency = InstrItins.getOperandCycle(ItinClassIndx: DefClass, OperandIdx: 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(a: InstrLatency, b: DefaultDefLatency);
195 }
196
197 // hasInstrSchedModel()
198 const MCSchedClassDesc *SCDesc = resolveSchedClass(MI: DefMI);
199 unsigned DefIdx = findDefIdx(MI: DefMI, DefOperIdx);
200 if (DefIdx < SCDesc->NumWriteLatencyEntries) {
201 // Lookup the definition's write latency in SubtargetInfo.
202 const MCWriteLatencyEntry *WLEntry =
203 STI->getWriteLatencyEntry(SC: SCDesc, DefIdx);
204 unsigned WriteID = WLEntry->WriteResourceID;
205 unsigned Latency = capLatency(Cycles: WLEntry->Cycles);
206 if (!UseMI)
207 return Latency;
208
209 // Lookup the use's latency adjustment in SubtargetInfo.
210 const MCSchedClassDesc *UseDesc = resolveSchedClass(MI: UseMI);
211 if (UseDesc->NumReadAdvanceEntries == 0)
212 return Latency;
213 unsigned UseIdx = findUseIdx(MI: UseMI, UseOperIdx);
214 int Advance = STI->getReadAdvanceCycles(SC: UseDesc, UseIdx, WriteResID: 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(Cycles: MCSchedModel::computeInstrLatency(STI: *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(Cycles: SchedModel.computeInstrLatency(STI: *STI, SClass: SCIdx));
245}
246
247unsigned TargetSchedModel::computeInstrLatency(const MCInst &Inst) const {
248 if (hasInstrSchedModel())
249 return capLatency(Cycles: SchedModel.computeInstrLatency(STI: *STI, MCII: *TII, Inst));
250 return computeInstrLatency(Opcode: 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(ItinData: &InstrItins, MI: *MI);
261
262 if (hasInstrSchedModel()) {
263 const MCSchedClassDesc *SCDesc = resolveSchedClass(MI);
264 if (SCDesc->isValid())
265 return computeInstrLatency(SCDesc: *SCDesc);
266 }
267 return TII->defaultDefLatency(STI: *STI, SchedModel, DefMI: *MI);
268}
269
270unsigned TargetSchedModel::
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(i: DefOperIdx).getReg();
285 const MachineFunction &MF = *DefMI->getMF();
286 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
287 if (!DepMI->readsRegister(Reg, TRI) && TII->isPredicated(MI: *DepMI))
288 return computeInstrLatency(MI: 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()) {
293 const MCSchedClassDesc *SCDesc = resolveSchedClass(MI: DefMI);
294 if (SCDesc->isValid()) {
295 for (const MCWriteProcResEntry *PRI = STI->getWriteProcResBegin(SC: SCDesc),
296 *PRE = STI->getWriteProcResEnd(SC: SCDesc); PRI != PRE; ++PRI) {
297 if (!SchedModel.getResourceBufferSize(ProcResourceIdx: PRI->ProcResourceIdx))
298 return 1;
299 }
300 }
301 }
302 return 0;
303}
304
305double
306TargetSchedModel::computeReciprocalThroughput(const MachineInstr *MI) const {
307 if (hasInstrItineraries()) {
308 unsigned SchedClass = MI->getDesc().getSchedClass();
309 return MCSchedModel::getReciprocalThroughput(SchedClass,
310 IID: *getInstrItineraries());
311 }
312
313 if (hasInstrSchedModel())
314 return MCSchedModel::getReciprocalThroughput(STI: *STI, SCDesc: *resolveSchedClass(MI));
315
316 return 0.0;
317}
318
319double
320TargetSchedModel::computeReciprocalThroughput(unsigned Opcode) const {
321 unsigned SchedClass = TII->get(Opcode).getSchedClass();
322 if (hasInstrItineraries())
323 return MCSchedModel::getReciprocalThroughput(SchedClass,
324 IID: *getInstrItineraries());
325 if (hasInstrSchedModel()) {
326 const MCSchedClassDesc &SCDesc = *SchedModel.getSchedClassDesc(SchedClassIdx: SchedClass);
327 if (SCDesc.isValid() && !SCDesc.isVariant())
328 return MCSchedModel::getReciprocalThroughput(STI: *STI, SCDesc);
329 }
330
331 return 0.0;
332}
333
334double
335TargetSchedModel::computeReciprocalThroughput(const MCInst &MI) const {
336 if (hasInstrSchedModel())
337 return SchedModel.getReciprocalThroughput(STI: *STI, MCII: *TII, Inst: MI);
338 return computeReciprocalThroughput(Opcode: MI.getOpcode());
339}
340
341bool TargetSchedModel::enableIntervals() const {
342 if (ForceEnableIntervals)
343 return true;
344
345 return SchedModel.EnableIntervals;
346}
347