MachineTraceMetrics.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- lib/CodeGen/MachineTraceMetrics.h - Super-scalar metrics -*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the interface for the MachineTraceMetrics analysis pass
  15. // that estimates CPU resource usage and critical data dependency paths through
  16. // preferred traces. This is useful for super-scalar CPUs where execution speed
  17. // can be limited both by data dependencies and by limited execution resources.
  18. //
  19. // Out-of-order CPUs will often be executing instructions from multiple basic
  20. // blocks at the same time. This makes it difficult to estimate the resource
  21. // usage accurately in a single basic block. Resources can be estimated better
  22. // by looking at a trace through the current basic block.
  23. //
  24. // For every block, the MachineTraceMetrics pass will pick a preferred trace
  25. // that passes through the block. The trace is chosen based on loop structure,
  26. // branch probabilities, and resource usage. The intention is to pick likely
  27. // traces that would be the most affected by code transformations.
  28. //
  29. // It is expensive to compute a full arbitrary trace for every block, so to
  30. // save some computations, traces are chosen to be convergent. This means that
  31. // if the traces through basic blocks A and B ever cross when moving away from
  32. // A and B, they never diverge again. This applies in both directions - If the
  33. // traces meet above A and B, they won't diverge when going further back.
  34. //
  35. // Traces tend to align with loops. The trace through a block in an inner loop
  36. // will begin at the loop entry block and end at a back edge. If there are
  37. // nested loops, the trace may begin and end at those instead.
  38. //
  39. // For each trace, we compute the critical path length, which is the number of
  40. // cycles required to execute the trace when execution is limited by data
  41. // dependencies only. We also compute the resource height, which is the number
  42. // of cycles required to execute all instructions in the trace when ignoring
  43. // data dependencies.
  44. //
  45. // Every instruction in the current block has a slack - the number of cycles
  46. // execution of the instruction can be delayed without extending the critical
  47. // path.
  48. //
  49. //===----------------------------------------------------------------------===//
  50. #ifndef LLVM_CODEGEN_MACHINETRACEMETRICS_H
  51. #define LLVM_CODEGEN_MACHINETRACEMETRICS_H
  52. #include "llvm/ADT/SparseSet.h"
  53. #include "llvm/ADT/ArrayRef.h"
  54. #include "llvm/ADT/DenseMap.h"
  55. #include "llvm/ADT/None.h"
  56. #include "llvm/ADT/SmallVector.h"
  57. #include "llvm/CodeGen/MachineBasicBlock.h"
  58. #include "llvm/CodeGen/MachineFunctionPass.h"
  59. #include "llvm/CodeGen/TargetSchedule.h"
  60. namespace llvm {
  61. class AnalysisUsage;
  62. class MachineFunction;
  63. class MachineInstr;
  64. class MachineLoop;
  65. class MachineLoopInfo;
  66. class MachineRegisterInfo;
  67. struct MCSchedClassDesc;
  68. class raw_ostream;
  69. class TargetInstrInfo;
  70. class TargetRegisterInfo;
  71. // Keep track of physreg data dependencies by recording each live register unit.
  72. // Associate each regunit with an instruction operand. Depending on the
  73. // direction instructions are scanned, it could be the operand that defined the
  74. // regunit, or the highest operand to read the regunit.
  75. struct LiveRegUnit {
  76. unsigned RegUnit;
  77. unsigned Cycle = 0;
  78. const MachineInstr *MI = nullptr;
  79. unsigned Op = 0;
  80. unsigned getSparseSetIndex() const { return RegUnit; }
  81. LiveRegUnit(unsigned RU) : RegUnit(RU) {}
  82. };
  83. class MachineTraceMetrics : public MachineFunctionPass {
  84. const MachineFunction *MF = nullptr;
  85. const TargetInstrInfo *TII = nullptr;
  86. const TargetRegisterInfo *TRI = nullptr;
  87. const MachineRegisterInfo *MRI = nullptr;
  88. const MachineLoopInfo *Loops = nullptr;
  89. TargetSchedModel SchedModel;
  90. public:
  91. friend class Ensemble;
  92. friend class Trace;
  93. class Ensemble;
  94. static char ID;
  95. MachineTraceMetrics();
  96. void getAnalysisUsage(AnalysisUsage&) const override;
  97. bool runOnMachineFunction(MachineFunction&) override;
  98. void releaseMemory() override;
  99. void verifyAnalysis() const override;
  100. /// Per-basic block information that doesn't depend on the trace through the
  101. /// block.
  102. struct FixedBlockInfo {
  103. /// The number of non-trivial instructions in the block.
  104. /// Doesn't count PHI and COPY instructions that are likely to be removed.
  105. unsigned InstrCount = ~0u;
  106. /// True when the block contains calls.
  107. bool HasCalls = false;
  108. FixedBlockInfo() = default;
  109. /// Returns true when resource information for this block has been computed.
  110. bool hasResources() const { return InstrCount != ~0u; }
  111. /// Invalidate resource information.
  112. void invalidate() { InstrCount = ~0u; }
  113. };
  114. /// Get the fixed resource information about MBB. Compute it on demand.
  115. const FixedBlockInfo *getResources(const MachineBasicBlock*);
  116. /// Get the scaled number of cycles used per processor resource in MBB.
  117. /// This is an array with SchedModel.getNumProcResourceKinds() entries.
  118. /// The getResources() function above must have been called first.
  119. ///
  120. /// These numbers have already been scaled by SchedModel.getResourceFactor().
  121. ArrayRef<unsigned> getProcResourceCycles(unsigned MBBNum) const;
  122. /// A virtual register or regunit required by a basic block or its trace
  123. /// successors.
  124. struct LiveInReg {
  125. /// The virtual register required, or a register unit.
  126. Register Reg;
  127. /// For virtual registers: Minimum height of the defining instruction.
  128. /// For regunits: Height of the highest user in the trace.
  129. unsigned Height;
  130. LiveInReg(Register Reg, unsigned Height = 0) : Reg(Reg), Height(Height) {}
  131. };
  132. /// Per-basic block information that relates to a specific trace through the
  133. /// block. Convergent traces means that only one of these is required per
  134. /// block in a trace ensemble.
  135. struct TraceBlockInfo {
  136. /// Trace predecessor, or NULL for the first block in the trace.
  137. /// Valid when hasValidDepth().
  138. const MachineBasicBlock *Pred = nullptr;
  139. /// Trace successor, or NULL for the last block in the trace.
  140. /// Valid when hasValidHeight().
  141. const MachineBasicBlock *Succ = nullptr;
  142. /// The block number of the head of the trace. (When hasValidDepth()).
  143. unsigned Head;
  144. /// The block number of the tail of the trace. (When hasValidHeight()).
  145. unsigned Tail;
  146. /// Accumulated number of instructions in the trace above this block.
  147. /// Does not include instructions in this block.
  148. unsigned InstrDepth = ~0u;
  149. /// Accumulated number of instructions in the trace below this block.
  150. /// Includes instructions in this block.
  151. unsigned InstrHeight = ~0u;
  152. TraceBlockInfo() = default;
  153. /// Returns true if the depth resources have been computed from the trace
  154. /// above this block.
  155. bool hasValidDepth() const { return InstrDepth != ~0u; }
  156. /// Returns true if the height resources have been computed from the trace
  157. /// below this block.
  158. bool hasValidHeight() const { return InstrHeight != ~0u; }
  159. /// Invalidate depth resources when some block above this one has changed.
  160. void invalidateDepth() { InstrDepth = ~0u; HasValidInstrDepths = false; }
  161. /// Invalidate height resources when a block below this one has changed.
  162. void invalidateHeight() { InstrHeight = ~0u; HasValidInstrHeights = false; }
  163. /// Assuming that this is a dominator of TBI, determine if it contains
  164. /// useful instruction depths. A dominating block can be above the current
  165. /// trace head, and any dependencies from such a far away dominator are not
  166. /// expected to affect the critical path.
  167. ///
  168. /// Also returns true when TBI == this.
  169. bool isUsefulDominator(const TraceBlockInfo &TBI) const {
  170. // The trace for TBI may not even be calculated yet.
  171. if (!hasValidDepth() || !TBI.hasValidDepth())
  172. return false;
  173. // Instruction depths are only comparable if the traces share a head.
  174. if (Head != TBI.Head)
  175. return false;
  176. // It is almost always the case that TBI belongs to the same trace as
  177. // this block, but rare convoluted cases involving irreducible control
  178. // flow, a dominator may share a trace head without actually being on the
  179. // same trace as TBI. This is not a big problem as long as it doesn't
  180. // increase the instruction depth.
  181. return HasValidInstrDepths && InstrDepth <= TBI.InstrDepth;
  182. }
  183. // Data-dependency-related information. Per-instruction depth and height
  184. // are computed from data dependencies in the current trace, using
  185. // itinerary data.
  186. /// Instruction depths have been computed. This implies hasValidDepth().
  187. bool HasValidInstrDepths = false;
  188. /// Instruction heights have been computed. This implies hasValidHeight().
  189. bool HasValidInstrHeights = false;
  190. /// Critical path length. This is the number of cycles in the longest data
  191. /// dependency chain through the trace. This is only valid when both
  192. /// HasValidInstrDepths and HasValidInstrHeights are set.
  193. unsigned CriticalPath;
  194. /// Live-in registers. These registers are defined above the current block
  195. /// and used by this block or a block below it.
  196. /// This does not include PHI uses in the current block, but it does
  197. /// include PHI uses in deeper blocks.
  198. SmallVector<LiveInReg, 4> LiveIns;
  199. void print(raw_ostream&) const;
  200. };
  201. /// InstrCycles represents the cycle height and depth of an instruction in a
  202. /// trace.
  203. struct InstrCycles {
  204. /// Earliest issue cycle as determined by data dependencies and instruction
  205. /// latencies from the beginning of the trace. Data dependencies from
  206. /// before the trace are not included.
  207. unsigned Depth;
  208. /// Minimum number of cycles from this instruction is issued to the of the
  209. /// trace, as determined by data dependencies and instruction latencies.
  210. unsigned Height;
  211. };
  212. /// A trace represents a plausible sequence of executed basic blocks that
  213. /// passes through the current basic block one. The Trace class serves as a
  214. /// handle to internal cached data structures.
  215. class Trace {
  216. Ensemble &TE;
  217. TraceBlockInfo &TBI;
  218. unsigned getBlockNum() const { return &TBI - &TE.BlockInfo[0]; }
  219. public:
  220. explicit Trace(Ensemble &te, TraceBlockInfo &tbi) : TE(te), TBI(tbi) {}
  221. void print(raw_ostream&) const;
  222. /// Compute the total number of instructions in the trace.
  223. unsigned getInstrCount() const {
  224. return TBI.InstrDepth + TBI.InstrHeight;
  225. }
  226. /// Return the resource depth of the top/bottom of the trace center block.
  227. /// This is the number of cycles required to execute all instructions from
  228. /// the trace head to the trace center block. The resource depth only
  229. /// considers execution resources, it ignores data dependencies.
  230. /// When Bottom is set, instructions in the trace center block are included.
  231. unsigned getResourceDepth(bool Bottom) const;
  232. /// Return the resource length of the trace. This is the number of cycles
  233. /// required to execute the instructions in the trace if they were all
  234. /// independent, exposing the maximum instruction-level parallelism.
  235. ///
  236. /// Any blocks in Extrablocks are included as if they were part of the
  237. /// trace. Likewise, extra resources required by the specified scheduling
  238. /// classes are included. For the caller to account for extra machine
  239. /// instructions, it must first resolve each instruction's scheduling class.
  240. unsigned getResourceLength(
  241. ArrayRef<const MachineBasicBlock *> Extrablocks = None,
  242. ArrayRef<const MCSchedClassDesc *> ExtraInstrs = None,
  243. ArrayRef<const MCSchedClassDesc *> RemoveInstrs = None) const;
  244. /// Return the length of the (data dependency) critical path through the
  245. /// trace.
  246. unsigned getCriticalPath() const { return TBI.CriticalPath; }
  247. /// Return the depth and height of MI. The depth is only valid for
  248. /// instructions in or above the trace center block. The height is only
  249. /// valid for instructions in or below the trace center block.
  250. InstrCycles getInstrCycles(const MachineInstr &MI) const {
  251. return TE.Cycles.lookup(&MI);
  252. }
  253. /// Return the slack of MI. This is the number of cycles MI can be delayed
  254. /// before the critical path becomes longer.
  255. /// MI must be an instruction in the trace center block.
  256. unsigned getInstrSlack(const MachineInstr &MI) const;
  257. /// Return the Depth of a PHI instruction in a trace center block successor.
  258. /// The PHI does not have to be part of the trace.
  259. unsigned getPHIDepth(const MachineInstr &PHI) const;
  260. /// A dependence is useful if the basic block of the defining instruction
  261. /// is part of the trace of the user instruction. It is assumed that DefMI
  262. /// dominates UseMI (see also isUsefulDominator).
  263. bool isDepInTrace(const MachineInstr &DefMI,
  264. const MachineInstr &UseMI) const;
  265. };
  266. /// A trace ensemble is a collection of traces selected using the same
  267. /// strategy, for example 'minimum resource height'. There is one trace for
  268. /// every block in the function.
  269. class Ensemble {
  270. friend class Trace;
  271. SmallVector<TraceBlockInfo, 4> BlockInfo;
  272. DenseMap<const MachineInstr*, InstrCycles> Cycles;
  273. SmallVector<unsigned, 0> ProcResourceDepths;
  274. SmallVector<unsigned, 0> ProcResourceHeights;
  275. void computeTrace(const MachineBasicBlock*);
  276. void computeDepthResources(const MachineBasicBlock*);
  277. void computeHeightResources(const MachineBasicBlock*);
  278. unsigned computeCrossBlockCriticalPath(const TraceBlockInfo&);
  279. void computeInstrDepths(const MachineBasicBlock*);
  280. void computeInstrHeights(const MachineBasicBlock*);
  281. void addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
  282. ArrayRef<const MachineBasicBlock*> Trace);
  283. protected:
  284. MachineTraceMetrics &MTM;
  285. explicit Ensemble(MachineTraceMetrics*);
  286. virtual const MachineBasicBlock *pickTracePred(const MachineBasicBlock*) =0;
  287. virtual const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*) =0;
  288. const MachineLoop *getLoopFor(const MachineBasicBlock*) const;
  289. const TraceBlockInfo *getDepthResources(const MachineBasicBlock*) const;
  290. const TraceBlockInfo *getHeightResources(const MachineBasicBlock*) const;
  291. ArrayRef<unsigned> getProcResourceDepths(unsigned MBBNum) const;
  292. ArrayRef<unsigned> getProcResourceHeights(unsigned MBBNum) const;
  293. public:
  294. virtual ~Ensemble();
  295. virtual const char *getName() const = 0;
  296. void print(raw_ostream&) const;
  297. void invalidate(const MachineBasicBlock *MBB);
  298. void verify() const;
  299. /// Get the trace that passes through MBB.
  300. /// The trace is computed on demand.
  301. Trace getTrace(const MachineBasicBlock *MBB);
  302. /// Updates the depth of an machine instruction, given RegUnits.
  303. void updateDepth(TraceBlockInfo &TBI, const MachineInstr&,
  304. SparseSet<LiveRegUnit> &RegUnits);
  305. void updateDepth(const MachineBasicBlock *, const MachineInstr&,
  306. SparseSet<LiveRegUnit> &RegUnits);
  307. /// Updates the depth of the instructions from Start to End.
  308. void updateDepths(MachineBasicBlock::iterator Start,
  309. MachineBasicBlock::iterator End,
  310. SparseSet<LiveRegUnit> &RegUnits);
  311. };
  312. /// Strategies for selecting traces.
  313. enum Strategy {
  314. /// Select the trace through a block that has the fewest instructions.
  315. TS_MinInstrCount,
  316. TS_NumStrategies
  317. };
  318. /// Get the trace ensemble representing the given trace selection strategy.
  319. /// The returned Ensemble object is owned by the MachineTraceMetrics analysis,
  320. /// and valid for the lifetime of the analysis pass.
  321. Ensemble *getEnsemble(Strategy);
  322. /// Invalidate cached information about MBB. This must be called *before* MBB
  323. /// is erased, or the CFG is otherwise changed.
  324. ///
  325. /// This invalidates per-block information about resource usage for MBB only,
  326. /// and it invalidates per-trace information for any trace that passes
  327. /// through MBB.
  328. ///
  329. /// Call Ensemble::getTrace() again to update any trace handles.
  330. void invalidate(const MachineBasicBlock *MBB);
  331. private:
  332. // One entry per basic block, indexed by block number.
  333. SmallVector<FixedBlockInfo, 4> BlockInfo;
  334. // Cycles consumed on each processor resource per block.
  335. // The number of processor resource kinds is constant for a given subtarget,
  336. // but it is not known at compile time. The number of cycles consumed by
  337. // block B on processor resource R is at ProcResourceCycles[B*Kinds + R]
  338. // where Kinds = SchedModel.getNumProcResourceKinds().
  339. SmallVector<unsigned, 0> ProcResourceCycles;
  340. // One ensemble per strategy.
  341. Ensemble* Ensembles[TS_NumStrategies];
  342. // Convert scaled resource usage to a cycle count that can be compared with
  343. // latencies.
  344. unsigned getCycles(unsigned Scaled) {
  345. unsigned Factor = SchedModel.getLatencyFactor();
  346. return (Scaled + Factor - 1) / Factor;
  347. }
  348. };
  349. inline raw_ostream &operator<<(raw_ostream &OS,
  350. const MachineTraceMetrics::Trace &Tr) {
  351. Tr.print(OS);
  352. return OS;
  353. }
  354. inline raw_ostream &operator<<(raw_ostream &OS,
  355. const MachineTraceMetrics::Ensemble &En) {
  356. En.print(OS);
  357. return OS;
  358. }
  359. } // end namespace llvm
  360. #endif // LLVM_CODEGEN_MACHINETRACEMETRICS_H
  361. #ifdef __GNUC__
  362. #pragma GCC diagnostic pop
  363. #endif