MachineTraceMetrics.h 16 KB

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