TargetSchedule.cpp 13 KB

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