BottleneckAnalysis.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. //===--------------------- BottleneckAnalysis.h -----------------*- 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. /// \file
  9. ///
  10. /// This file implements the bottleneck analysis view.
  11. ///
  12. /// This view internally observes backend pressure increase events in order to
  13. /// identify problematic data dependencies and processor resource interferences.
  14. ///
  15. /// Example of bottleneck analysis report for a dot-product on X86 btver2:
  16. ///
  17. /// Cycles with backend pressure increase [ 40.76% ]
  18. /// Throughput Bottlenecks:
  19. /// Resource Pressure [ 39.34% ]
  20. /// - JFPA [ 39.34% ]
  21. /// - JFPU0 [ 39.34% ]
  22. /// Data Dependencies: [ 1.42% ]
  23. /// - Register Dependencies [ 1.42% ]
  24. /// - Memory Dependencies [ 0.00% ]
  25. ///
  26. /// According to the example, backend pressure increased during the 40.76% of
  27. /// the simulated cycles. In particular, the major cause of backend pressure
  28. /// increases was the contention on floating point adder JFPA accessible from
  29. /// pipeline resource JFPU0.
  30. ///
  31. /// At the end of each cycle, if pressure on the simulated out-of-order buffers
  32. /// has increased, a backend pressure event is reported.
  33. /// In particular, this occurs when there is a delta between the number of uOps
  34. /// dispatched and the number of uOps issued to the underlying pipelines.
  35. ///
  36. /// The bottleneck analysis view is also responsible for identifying and printing
  37. /// the most "critical" sequence of dependent instructions according to the
  38. /// simulated run.
  39. ///
  40. /// Below is the critical sequence computed for the dot-product example on
  41. /// btver2:
  42. ///
  43. /// Instruction Dependency Information
  44. /// +----< 2. vhaddps %xmm3, %xmm3, %xmm4
  45. /// |
  46. /// | < loop carried >
  47. /// |
  48. /// | 0. vmulps %xmm0, %xmm0, %xmm2
  49. /// +----> 1. vhaddps %xmm2, %xmm2, %xmm3 ## RESOURCE interference: JFPA [ probability: 73% ]
  50. /// +----> 2. vhaddps %xmm3, %xmm3, %xmm4 ## REGISTER dependency: %xmm3
  51. /// |
  52. /// | < loop carried >
  53. /// |
  54. /// +----> 1. vhaddps %xmm2, %xmm2, %xmm3 ## RESOURCE interference: JFPA [ probability: 73% ]
  55. ///
  56. ///
  57. /// The algorithm that computes the critical sequence is very similar to a
  58. /// critical path analysis.
  59. ///
  60. /// A dependency graph is used internally to track dependencies between nodes.
  61. /// Nodes of the graph represent instructions from the input assembly sequence,
  62. /// and edges of the graph represent data dependencies or processor resource
  63. /// interferences.
  64. ///
  65. /// Edges are dynamically 'discovered' by observing instruction state transitions
  66. /// and backend pressure increase events. Edges are internally ranked based on
  67. /// their "criticality". A dependency is considered to be critical if it takes a
  68. /// long time to execute, and if it contributes to backend pressure increases.
  69. /// Criticality is internally measured in terms of cycles; it is computed for
  70. /// every edge in the graph as a function of the edge latency and the number of
  71. /// backend pressure increase cycles contributed by that edge.
  72. ///
  73. /// At the end of simulation, costs are propagated to nodes through the edges of
  74. /// the graph, and the most expensive path connecting the root-set (a
  75. /// set of nodes with no predecessors) to a leaf node is reported as critical
  76. /// sequence.
  77. //
  78. //===----------------------------------------------------------------------===//
  79. #ifndef LLVM_TOOLS_LLVM_MCA_BOTTLENECK_ANALYSIS_H
  80. #define LLVM_TOOLS_LLVM_MCA_BOTTLENECK_ANALYSIS_H
  81. #include "Views/InstructionView.h"
  82. #include "llvm/ADT/DenseMap.h"
  83. #include "llvm/ADT/SmallVector.h"
  84. #include "llvm/MC/MCInstPrinter.h"
  85. #include "llvm/MC/MCSchedule.h"
  86. #include "llvm/MC/MCSubtargetInfo.h"
  87. #include "llvm/Support/FormattedStream.h"
  88. #include "llvm/Support/raw_ostream.h"
  89. namespace llvm {
  90. namespace mca {
  91. class PressureTracker {
  92. const MCSchedModel &SM;
  93. // Resource pressure distribution. There is an element for every processor
  94. // resource declared by the scheduling model. Quantities are number of cycles.
  95. SmallVector<unsigned, 4> ResourcePressureDistribution;
  96. // Each processor resource is associated with a so-called processor resource
  97. // mask. This vector allows to correlate processor resource IDs with processor
  98. // resource masks. There is exactly one element per each processor resource
  99. // declared by the scheduling model.
  100. SmallVector<uint64_t, 4> ProcResID2Mask;
  101. // Maps processor resource state indices (returned by calls to
  102. // `getResourceStateIndex(Mask)` to processor resource identifiers.
  103. SmallVector<unsigned, 4> ResIdx2ProcResID;
  104. // Maps Processor Resource identifiers to ResourceUsers indices.
  105. SmallVector<unsigned, 4> ProcResID2ResourceUsersIndex;
  106. // Identifies the last user of a processor resource unit.
  107. // This vector is updated on every instruction issued event.
  108. // There is one entry for every processor resource unit declared by the
  109. // processor model. An all_ones value is treated like an invalid instruction
  110. // identifier.
  111. using User = std::pair<unsigned, unsigned>;
  112. SmallVector<User, 4> ResourceUsers;
  113. struct InstructionPressureInfo {
  114. unsigned RegisterPressureCycles;
  115. unsigned MemoryPressureCycles;
  116. unsigned ResourcePressureCycles;
  117. };
  118. DenseMap<unsigned, InstructionPressureInfo> IPI;
  119. void updateResourcePressureDistribution(uint64_t CumulativeMask);
  120. User getResourceUser(unsigned ProcResID, unsigned UnitID) const {
  121. unsigned Index = ProcResID2ResourceUsersIndex[ProcResID];
  122. return ResourceUsers[Index + UnitID];
  123. }
  124. public:
  125. PressureTracker(const MCSchedModel &Model);
  126. ArrayRef<unsigned> getResourcePressureDistribution() const {
  127. return ResourcePressureDistribution;
  128. }
  129. void getResourceUsers(uint64_t ResourceMask,
  130. SmallVectorImpl<User> &Users) const;
  131. unsigned getRegisterPressureCycles(unsigned IID) const {
  132. assert(IPI.find(IID) != IPI.end() && "Instruction is not tracked!");
  133. const InstructionPressureInfo &Info = IPI.find(IID)->second;
  134. return Info.RegisterPressureCycles;
  135. }
  136. unsigned getMemoryPressureCycles(unsigned IID) const {
  137. assert(IPI.find(IID) != IPI.end() && "Instruction is not tracked!");
  138. const InstructionPressureInfo &Info = IPI.find(IID)->second;
  139. return Info.MemoryPressureCycles;
  140. }
  141. unsigned getResourcePressureCycles(unsigned IID) const {
  142. assert(IPI.find(IID) != IPI.end() && "Instruction is not tracked!");
  143. const InstructionPressureInfo &Info = IPI.find(IID)->second;
  144. return Info.ResourcePressureCycles;
  145. }
  146. const char *resolveResourceName(uint64_t ResourceMask) const {
  147. unsigned Index = getResourceStateIndex(ResourceMask);
  148. unsigned ProcResID = ResIdx2ProcResID[Index];
  149. const MCProcResourceDesc &PRDesc = *SM.getProcResource(ProcResID);
  150. return PRDesc.Name;
  151. }
  152. void onInstructionDispatched(unsigned IID);
  153. void onInstructionExecuted(unsigned IID);
  154. void handlePressureEvent(const HWPressureEvent &Event);
  155. void handleInstructionIssuedEvent(const HWInstructionIssuedEvent &Event);
  156. };
  157. // A dependency edge.
  158. struct DependencyEdge {
  159. enum DependencyType { DT_INVALID, DT_REGISTER, DT_MEMORY, DT_RESOURCE };
  160. // Dependency edge descriptor.
  161. //
  162. // It specifies the dependency type, as well as the edge cost in cycles.
  163. struct Dependency {
  164. DependencyType Type;
  165. uint64_t ResourceOrRegID;
  166. uint64_t Cost;
  167. };
  168. Dependency Dep;
  169. unsigned FromIID;
  170. unsigned ToIID;
  171. // Used by the bottleneck analysis to compute the interference
  172. // probability for processor resources.
  173. unsigned Frequency;
  174. };
  175. // A dependency graph used by the bottleneck analysis to describe data
  176. // dependencies and processor resource interferences between instructions.
  177. //
  178. // There is a node (an instance of struct DGNode) for every instruction in the
  179. // input assembly sequence. Edges of the graph represent dependencies between
  180. // instructions.
  181. //
  182. // Each edge of the graph is associated with a cost value which is used
  183. // internally to rank dependency based on their impact on the runtime
  184. // performance (see field DependencyEdge::Dependency::Cost). In general, the
  185. // higher the cost of an edge, the higher the impact on performance.
  186. //
  187. // The cost of a dependency is a function of both the latency and the number of
  188. // cycles where the dependency has been seen as critical (i.e. contributing to
  189. // back-pressure increases).
  190. //
  191. // Loop carried dependencies are carefully expanded by the bottleneck analysis
  192. // to guarantee that the graph stays acyclic. To this end, extra nodes are
  193. // pre-allocated at construction time to describe instructions from "past and
  194. // future" iterations. The graph is kept acyclic mainly because it simplifies the
  195. // complexity of the algorithm that computes the critical sequence.
  196. class DependencyGraph {
  197. struct DGNode {
  198. unsigned NumPredecessors;
  199. unsigned NumVisitedPredecessors;
  200. uint64_t Cost;
  201. unsigned Depth;
  202. DependencyEdge CriticalPredecessor;
  203. SmallVector<DependencyEdge, 8> OutgoingEdges;
  204. };
  205. SmallVector<DGNode, 16> Nodes;
  206. DependencyGraph(const DependencyGraph &) = delete;
  207. DependencyGraph &operator=(const DependencyGraph &) = delete;
  208. void addDependency(unsigned From, unsigned To,
  209. DependencyEdge::Dependency &&DE);
  210. void pruneEdges(unsigned Iterations);
  211. void initializeRootSet(SmallVectorImpl<unsigned> &RootSet) const;
  212. void propagateThroughEdges(SmallVectorImpl<unsigned> &RootSet, unsigned Iterations);
  213. #ifndef NDEBUG
  214. void dumpDependencyEdge(raw_ostream &OS, const DependencyEdge &DE,
  215. MCInstPrinter &MCIP) const;
  216. #endif
  217. public:
  218. DependencyGraph(unsigned Size) : Nodes(Size) {}
  219. void addRegisterDep(unsigned From, unsigned To, unsigned RegID,
  220. unsigned Cost) {
  221. addDependency(From, To, {DependencyEdge::DT_REGISTER, RegID, Cost});
  222. }
  223. void addMemoryDep(unsigned From, unsigned To, unsigned Cost) {
  224. addDependency(From, To, {DependencyEdge::DT_MEMORY, /* unused */ 0, Cost});
  225. }
  226. void addResourceDep(unsigned From, unsigned To, uint64_t Mask,
  227. unsigned Cost) {
  228. addDependency(From, To, {DependencyEdge::DT_RESOURCE, Mask, Cost});
  229. }
  230. // Called by the bottleneck analysis at the end of simulation to propagate
  231. // costs through the edges of the graph, and compute a critical path.
  232. void finalizeGraph(unsigned Iterations) {
  233. SmallVector<unsigned, 16> RootSet;
  234. pruneEdges(Iterations);
  235. initializeRootSet(RootSet);
  236. propagateThroughEdges(RootSet, Iterations);
  237. }
  238. // Returns a sequence of edges representing the critical sequence based on the
  239. // simulated run. It assumes that the graph has already been finalized (i.e.
  240. // method `finalizeGraph()` has already been called on this graph).
  241. void getCriticalSequence(SmallVectorImpl<const DependencyEdge *> &Seq) const;
  242. #ifndef NDEBUG
  243. void dump(raw_ostream &OS, MCInstPrinter &MCIP) const;
  244. #endif
  245. };
  246. /// A view that collects and prints a few performance numbers.
  247. class BottleneckAnalysis : public InstructionView {
  248. PressureTracker Tracker;
  249. DependencyGraph DG;
  250. unsigned Iterations;
  251. unsigned TotalCycles;
  252. bool PressureIncreasedBecauseOfResources;
  253. bool PressureIncreasedBecauseOfRegisterDependencies;
  254. bool PressureIncreasedBecauseOfMemoryDependencies;
  255. // True if throughput was affected by dispatch stalls.
  256. bool SeenStallCycles;
  257. struct BackPressureInfo {
  258. // Cycles where backpressure increased.
  259. unsigned PressureIncreaseCycles;
  260. // Cycles where backpressure increased because of pipeline pressure.
  261. unsigned ResourcePressureCycles;
  262. // Cycles where backpressure increased because of data dependencies.
  263. unsigned DataDependencyCycles;
  264. // Cycles where backpressure increased because of register dependencies.
  265. unsigned RegisterDependencyCycles;
  266. // Cycles where backpressure increased because of memory dependencies.
  267. unsigned MemoryDependencyCycles;
  268. };
  269. BackPressureInfo BPI;
  270. // Used to populate the dependency graph DG.
  271. void addRegisterDep(unsigned From, unsigned To, unsigned RegID, unsigned Cy);
  272. void addMemoryDep(unsigned From, unsigned To, unsigned Cy);
  273. void addResourceDep(unsigned From, unsigned To, uint64_t Mask, unsigned Cy);
  274. void printInstruction(formatted_raw_ostream &FOS, const MCInst &MCI,
  275. bool UseDifferentColor = false) const;
  276. // Prints a bottleneck message to OS.
  277. void printBottleneckHints(raw_ostream &OS) const;
  278. void printCriticalSequence(raw_ostream &OS) const;
  279. public:
  280. BottleneckAnalysis(const MCSubtargetInfo &STI, MCInstPrinter &MCIP,
  281. ArrayRef<MCInst> Sequence, unsigned Iterations);
  282. void onCycleEnd() override;
  283. void onEvent(const HWStallEvent &Event) override { SeenStallCycles = true; }
  284. void onEvent(const HWPressureEvent &Event) override;
  285. void onEvent(const HWInstructionEvent &Event) override;
  286. void printView(raw_ostream &OS) const override;
  287. StringRef getNameAsString() const override { return "BottleneckAnalysis"; }
  288. json::Value toJSON() const override { return "not implemented"; }
  289. #ifndef NDEBUG
  290. void dump(raw_ostream &OS, MCInstPrinter &MCIP) const { DG.dump(OS, MCIP); }
  291. #endif
  292. };
  293. } // namespace mca
  294. } // namespace llvm
  295. #endif