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 #include <numeric> 29 30 using namespace llvm; 31 32 static cl::opt<bool> EnableSchedModel("schedmodel", cl::Hidden, cl::init(true), 33 cl::desc("Use TargetSchedModel for latency lookup")); 34 35 static cl::opt<bool> EnableSchedItins("scheditins", cl::Hidden, cl::init(true), 36 cl::desc("Use InstrItineraryData for latency lookup")); 37 38 static cl::opt<bool> ForceEnableIntervals( 39 "sched-model-force-enable-intervals", cl::Hidden, cl::init(false), 40 cl::desc("Force the use of resource intervals in the schedule model")); 41 42 bool TargetSchedModel::hasInstrSchedModel() const { 43 return EnableSchedModel && SchedModel.hasInstrSchedModel(); 44 } 45 46 bool TargetSchedModel::hasInstrItineraries() const { 47 return EnableSchedItins && !InstrItins.isEmpty(); 48 } 49 50 void TargetSchedModel::init(const TargetSubtargetInfo *TSInfo) { 51 STI = TSInfo; 52 SchedModel = TSInfo->getSchedModel(); 53 TII = TSInfo->getInstrInfo(); 54 STI->initInstrItins(InstrItins); 55 56 unsigned NumRes = SchedModel.getNumProcResourceKinds(); 57 ResourceFactors.resize(NumRes); 58 ResourceLCM = SchedModel.IssueWidth; 59 for (unsigned Idx = 0; Idx < NumRes; ++Idx) { 60 unsigned NumUnits = SchedModel.getProcResource(Idx)->NumUnits; 61 if (NumUnits > 0) 62 ResourceLCM = std::lcm(ResourceLCM, NumUnits); 63 } 64 MicroOpFactor = ResourceLCM / SchedModel.IssueWidth; 65 for (unsigned Idx = 0; Idx < NumRes; ++Idx) { 66 unsigned NumUnits = SchedModel.getProcResource(Idx)->NumUnits; 67 ResourceFactors[Idx] = NumUnits ? (ResourceLCM / NumUnits) : 0; 68 } 69 } 70 71 /// Returns true only if instruction is specified as single issue. 72 bool TargetSchedModel::mustBeginGroup(const MachineInstr *MI, 73 const MCSchedClassDesc *SC) const { 74 if (hasInstrSchedModel()) { 75 if (!SC) 76 SC = resolveSchedClass(MI); 77 if (SC->isValid()) 78 return SC->BeginGroup; 79 } 80 return false; 81 } 82 83 bool TargetSchedModel::mustEndGroup(const MachineInstr *MI, 84 const MCSchedClassDesc *SC) const { 85 if (hasInstrSchedModel()) { 86 if (!SC) 87 SC = resolveSchedClass(MI); 88 if (SC->isValid()) 89 return SC->EndGroup; 90 } 91 return false; 92 } 93 94 unsigned TargetSchedModel::getNumMicroOps(const MachineInstr *MI, 95 const MCSchedClassDesc *SC) const { 96 if (hasInstrItineraries()) { 97 int UOps = InstrItins.getNumMicroOps(MI->getDesc().getSchedClass()); 98 return (UOps >= 0) ? UOps : TII->getNumMicroOps(&InstrItins, *MI); 99 } 100 if (hasInstrSchedModel()) { 101 if (!SC) 102 SC = resolveSchedClass(MI); 103 if (SC->isValid()) 104 return SC->NumMicroOps; 105 } 106 return MI->isTransient() ? 0 : 1; 107 } 108 109 // The machine model may explicitly specify an invalid latency, which 110 // effectively means infinite latency. Since users of the TargetSchedule API 111 // don't know how to handle this, we convert it to a very large latency that is 112 // easy to distinguish when debugging the DAG but won't induce overflow. 113 static unsigned capLatency(int Cycles) { 114 return Cycles >= 0 ? Cycles : 1000; 115 } 116 117 /// Return the MCSchedClassDesc for this instruction. Some SchedClasses require 118 /// evaluation of predicates that depend on instruction operands or flags. 119 const MCSchedClassDesc *TargetSchedModel:: 120 resolveSchedClass(const MachineInstr *MI) const { 121 // Get the definition's scheduling class descriptor from this machine model. 122 unsigned SchedClass = MI->getDesc().getSchedClass(); 123 const MCSchedClassDesc *SCDesc = SchedModel.getSchedClassDesc(SchedClass); 124 if (!SCDesc->isValid()) 125 return SCDesc; 126 127 #ifndef NDEBUG 128 unsigned NIter = 0; 129 #endif 130 while (SCDesc->isVariant()) { 131 assert(++NIter < 6 && "Variants are nested deeper than the magic number"); 132 133 SchedClass = STI->resolveSchedClass(SchedClass, MI, this); 134 SCDesc = SchedModel.getSchedClassDesc(SchedClass); 135 } 136 return SCDesc; 137 } 138 139 /// Find the def index of this operand. This index maps to the machine model and 140 /// is independent of use operands. Def operands may be reordered with uses or 141 /// merged with uses without affecting the def index (e.g. before/after 142 /// regalloc). However, an instruction's def operands must never be reordered 143 /// with respect to each other. 144 static unsigned findDefIdx(const MachineInstr *MI, unsigned DefOperIdx) { 145 unsigned DefIdx = 0; 146 for (unsigned i = 0; i != DefOperIdx; ++i) { 147 const MachineOperand &MO = MI->getOperand(i); 148 if (MO.isReg() && MO.isDef()) 149 ++DefIdx; 150 } 151 return DefIdx; 152 } 153 154 /// Find the use index of this operand. This is independent of the instruction's 155 /// def operands. 156 /// 157 /// Note that uses are not determined by the operand's isUse property, which 158 /// is simply the inverse of isDef. Here we consider any readsReg operand to be 159 /// a "use". The machine model allows an operand to be both a Def and Use. 160 static unsigned findUseIdx(const MachineInstr *MI, unsigned UseOperIdx) { 161 unsigned UseIdx = 0; 162 for (unsigned i = 0; i != UseOperIdx; ++i) { 163 const MachineOperand &MO = MI->getOperand(i); 164 if (MO.isReg() && MO.readsReg() && !MO.isDef()) 165 ++UseIdx; 166 } 167 return UseIdx; 168 } 169 170 // Top-level API for clients that know the operand indices. This doesn't need to 171 // return std::optional<unsigned>, as it always returns a valid latency. 172 unsigned TargetSchedModel::computeOperandLatency( 173 const MachineInstr *DefMI, unsigned DefOperIdx, 174 const MachineInstr *UseMI, unsigned UseOperIdx) const { 175 176 const unsigned InstrLatency = computeInstrLatency(DefMI); 177 const unsigned DefaultDefLatency = TII->defaultDefLatency(SchedModel, *DefMI); 178 179 if (!hasInstrSchedModel() && !hasInstrItineraries()) 180 return DefaultDefLatency; 181 182 if (hasInstrItineraries()) { 183 std::optional<unsigned> OperLatency; 184 if (UseMI) { 185 OperLatency = TII->getOperandLatency(&InstrItins, *DefMI, DefOperIdx, 186 *UseMI, UseOperIdx); 187 } 188 else { 189 unsigned DefClass = DefMI->getDesc().getSchedClass(); 190 OperLatency = InstrItins.getOperandCycle(DefClass, DefOperIdx); 191 } 192 193 // Expected latency is the max of InstrLatency and DefaultDefLatency, if we 194 // didn't find an operand latency. 195 return OperLatency ? *OperLatency 196 : std::max(InstrLatency, DefaultDefLatency); 197 } 198 199 // hasInstrSchedModel() 200 const MCSchedClassDesc *SCDesc = resolveSchedClass(DefMI); 201 unsigned DefIdx = findDefIdx(DefMI, DefOperIdx); 202 if (DefIdx < SCDesc->NumWriteLatencyEntries) { 203 // Lookup the definition's write latency in SubtargetInfo. 204 const MCWriteLatencyEntry *WLEntry = 205 STI->getWriteLatencyEntry(SCDesc, DefIdx); 206 unsigned WriteID = WLEntry->WriteResourceID; 207 unsigned Latency = capLatency(WLEntry->Cycles); 208 if (!UseMI) 209 return Latency; 210 211 // Lookup the use's latency adjustment in SubtargetInfo. 212 const MCSchedClassDesc *UseDesc = resolveSchedClass(UseMI); 213 if (UseDesc->NumReadAdvanceEntries == 0) 214 return Latency; 215 unsigned UseIdx = findUseIdx(UseMI, UseOperIdx); 216 int Advance = STI->getReadAdvanceCycles(UseDesc, UseIdx, WriteID); 217 if (Advance > 0 && (unsigned)Advance > Latency) // unsigned wrap 218 return 0; 219 return Latency - Advance; 220 } 221 // If DefIdx does not exist in the model (e.g. implicit defs), then return 222 // unit latency (defaultDefLatency may be too conservative). 223 #ifndef NDEBUG 224 if (SCDesc->isValid() && !DefMI->getOperand(DefOperIdx).isImplicit() && 225 !DefMI->getDesc().operands()[DefOperIdx].isOptionalDef() && 226 SchedModel.isComplete()) { 227 errs() << "DefIdx " << DefIdx << " exceeds machine model writes for " 228 << *DefMI << " (Try with MCSchedModel.CompleteModel set to false)"; 229 llvm_unreachable("incomplete machine model"); 230 } 231 #endif 232 // FIXME: Automatically giving all implicit defs defaultDefLatency is 233 // undesirable. We should only do it for defs that are known to the MC 234 // desc like flags. Truly implicit defs should get 1 cycle latency. 235 return DefMI->isTransient() ? 0 : DefaultDefLatency; 236 } 237 238 unsigned 239 TargetSchedModel::computeInstrLatency(const MCSchedClassDesc &SCDesc) const { 240 return capLatency(MCSchedModel::computeInstrLatency(*STI, SCDesc)); 241 } 242 243 unsigned TargetSchedModel::computeInstrLatency(unsigned Opcode) const { 244 assert(hasInstrSchedModel() && "Only call this function with a SchedModel"); 245 unsigned SCIdx = TII->get(Opcode).getSchedClass(); 246 return capLatency(SchedModel.computeInstrLatency(*STI, SCIdx)); 247 } 248 249 unsigned TargetSchedModel::computeInstrLatency(const MCInst &Inst) const { 250 if (hasInstrSchedModel()) 251 return capLatency(SchedModel.computeInstrLatency(*STI, *TII, Inst)); 252 return computeInstrLatency(Inst.getOpcode()); 253 } 254 255 unsigned 256 TargetSchedModel::computeInstrLatency(const MachineInstr *MI, 257 bool UseDefaultDefLatency) const { 258 // For the itinerary model, fall back to the old subtarget hook. 259 // Allow subtargets to compute Bundle latencies outside the machine model. 260 if (hasInstrItineraries() || MI->isBundle() || 261 (!hasInstrSchedModel() && !UseDefaultDefLatency)) 262 return TII->getInstrLatency(&InstrItins, *MI); 263 264 if (hasInstrSchedModel()) { 265 const MCSchedClassDesc *SCDesc = resolveSchedClass(MI); 266 if (SCDesc->isValid()) 267 return computeInstrLatency(*SCDesc); 268 } 269 return TII->defaultDefLatency(SchedModel, *MI); 270 } 271 272 unsigned TargetSchedModel:: 273 computeOutputLatency(const MachineInstr *DefMI, unsigned DefOperIdx, 274 const MachineInstr *DepMI) const { 275 if (!SchedModel.isOutOfOrder()) 276 return 1; 277 278 // Out-of-order processor can dispatch WAW dependencies in the same cycle. 279 280 // Treat predication as a data dependency for out-of-order cpus. In-order 281 // cpus do not need to treat predicated writes specially. 282 // 283 // TODO: The following hack exists because predication passes do not 284 // correctly append imp-use operands, and readsReg() strangely returns false 285 // for predicated defs. 286 Register Reg = DefMI->getOperand(DefOperIdx).getReg(); 287 const MachineFunction &MF = *DefMI->getMF(); 288 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 289 if (!DepMI->readsRegister(Reg, TRI) && TII->isPredicated(*DepMI)) 290 return computeInstrLatency(DefMI); 291 292 // If we have a per operand scheduling model, check if this def is writing 293 // an unbuffered resource. If so, it treated like an in-order cpu. 294 if (hasInstrSchedModel()) { 295 const MCSchedClassDesc *SCDesc = resolveSchedClass(DefMI); 296 if (SCDesc->isValid()) { 297 for (const MCWriteProcResEntry *PRI = STI->getWriteProcResBegin(SCDesc), 298 *PRE = STI->getWriteProcResEnd(SCDesc); PRI != PRE; ++PRI) { 299 if (!SchedModel.getProcResource(PRI->ProcResourceIdx)->BufferSize) 300 return 1; 301 } 302 } 303 } 304 return 0; 305 } 306 307 double 308 TargetSchedModel::computeReciprocalThroughput(const MachineInstr *MI) const { 309 if (hasInstrItineraries()) { 310 unsigned SchedClass = MI->getDesc().getSchedClass(); 311 return MCSchedModel::getReciprocalThroughput(SchedClass, 312 *getInstrItineraries()); 313 } 314 315 if (hasInstrSchedModel()) 316 return MCSchedModel::getReciprocalThroughput(*STI, *resolveSchedClass(MI)); 317 318 return 0.0; 319 } 320 321 double 322 TargetSchedModel::computeReciprocalThroughput(unsigned Opcode) const { 323 unsigned SchedClass = TII->get(Opcode).getSchedClass(); 324 if (hasInstrItineraries()) 325 return MCSchedModel::getReciprocalThroughput(SchedClass, 326 *getInstrItineraries()); 327 if (hasInstrSchedModel()) { 328 const MCSchedClassDesc &SCDesc = *SchedModel.getSchedClassDesc(SchedClass); 329 if (SCDesc.isValid() && !SCDesc.isVariant()) 330 return MCSchedModel::getReciprocalThroughput(*STI, SCDesc); 331 } 332 333 return 0.0; 334 } 335 336 double 337 TargetSchedModel::computeReciprocalThroughput(const MCInst &MI) const { 338 if (hasInstrSchedModel()) 339 return SchedModel.getReciprocalThroughput(*STI, *TII, MI); 340 return computeReciprocalThroughput(MI.getOpcode()); 341 } 342 343 bool TargetSchedModel::enableIntervals() const { 344 if (ForceEnableIntervals) 345 return true; 346 347 return SchedModel.EnableIntervals; 348 } 349