MachineTraceMetrics.h 17 KB

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