XRayExample.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. ===================
  2. Debugging with XRay
  3. ===================
  4. This document shows an example of how you would go about analyzing applications
  5. built with XRay instrumentation. Here we will attempt to debug ``llc``
  6. compiling some sample LLVM IR generated by Clang.
  7. .. contents::
  8. :local:
  9. Building with XRay
  10. ------------------
  11. To debug an application with XRay instrumentation, we need to build it with a
  12. Clang that supports the ``-fxray-instrument`` option. See `XRay <XRay.html>`_
  13. for more technical details of how XRay works for background information.
  14. In our example, we need to add ``-fxray-instrument`` to the list of flags
  15. passed to Clang when building a binary. Note that we need to link with Clang as
  16. well to get the XRay runtime linked in appropriately. For building ``llc`` with
  17. XRay, we do something similar below for our LLVM build:
  18. ::
  19. $ mkdir -p llvm-build && cd llvm-build
  20. # Assume that the LLVM sources are at ../llvm
  21. $ cmake -GNinja ../llvm -DCMAKE_BUILD_TYPE=Release \
  22. -DCMAKE_C_FLAGS_RELEASE="-fxray-instrument" -DCMAKE_CXX_FLAGS="-fxray-instrument" \
  23. # Once this finishes, we should build llc
  24. $ ninja llc
  25. To verify that we have an XRay instrumented binary, we can use ``objdump`` to
  26. look for the ``xray_instr_map`` section.
  27. ::
  28. $ objdump -h -j xray_instr_map ./bin/llc
  29. ./bin/llc: file format elf64-x86-64
  30. Sections:
  31. Idx Name Size VMA LMA File off Algn
  32. 14 xray_instr_map 00002fc0 00000000041516c6 00000000041516c6 03d516c6 2**0
  33. CONTENTS, ALLOC, LOAD, READONLY, DATA
  34. Getting Traces
  35. --------------
  36. By default, XRay does not write out the trace files or patch the application
  37. before main starts. If we run ``llc`` it should work like a normally built
  38. binary. If we want to get a full trace of the application's operations (of the
  39. functions we do end up instrumenting with XRay) then we need to enable XRay
  40. at application start. To do this, XRay checks the ``XRAY_OPTIONS`` environment
  41. variable.
  42. ::
  43. # The following doesn't create an XRay trace by default.
  44. $ ./bin/llc input.ll
  45. # We need to set the XRAY_OPTIONS to enable some features.
  46. $ XRAY_OPTIONS="patch_premain=true xray_mode=xray-basic verbosity=1" ./bin/llc input.ll
  47. ==69819==XRay: Log file in 'xray-log.llc.m35qPB'
  48. At this point we now have an XRay trace we can start analysing.
  49. The ``llvm-xray`` Tool
  50. ----------------------
  51. Having a trace then allows us to do basic accounting of the functions that were
  52. instrumented, and how much time we're spending in parts of the code. To make
  53. sense of this data, we use the ``llvm-xray`` tool which has a few subcommands
  54. to help us understand our trace.
  55. One of the things we can do is to get an accounting of the functions that have
  56. been instrumented. We can see an example accounting with ``llvm-xray account``:
  57. ::
  58. $ llvm-xray account xray-log.llc.m35qPB -top=10 -sort=sum -sortorder=dsc -instr_map ./bin/llc
  59. Functions with latencies: 29
  60. funcid count [ min, med, 90p, 99p, max] sum function
  61. 187 360 [ 0.000000, 0.000001, 0.000014, 0.000032, 0.000075] 0.001596 LLLexer.cpp:446:0: llvm::LLLexer::LexIdentifier()
  62. 85 130 [ 0.000000, 0.000000, 0.000018, 0.000023, 0.000156] 0.000799 X86ISelDAGToDAG.cpp:1984:0: (anonymous namespace)::X86DAGToDAGISel::Select(llvm::SDNode*)
  63. 138 130 [ 0.000000, 0.000000, 0.000017, 0.000155, 0.000155] 0.000774 SelectionDAGISel.cpp:2963:0: llvm::SelectionDAGISel::SelectCodeCommon(llvm::SDNode*, unsigned char const*, unsigned int)
  64. 188 103 [ 0.000000, 0.000000, 0.000003, 0.000123, 0.000214] 0.000737 LLParser.cpp:2692:0: llvm::LLParser::ParseValID(llvm::ValID&, llvm::LLParser::PerFunctionState*)
  65. 88 1 [ 0.000562, 0.000562, 0.000562, 0.000562, 0.000562] 0.000562 X86ISelLowering.cpp:83:0: llvm::X86TargetLowering::X86TargetLowering(llvm::X86TargetMachine const&, llvm::X86Subtarget const&)
  66. 125 102 [ 0.000001, 0.000003, 0.000010, 0.000017, 0.000049] 0.000471 Verifier.cpp:3714:0: (anonymous namespace)::Verifier::visitInstruction(llvm::Instruction&)
  67. 90 8 [ 0.000023, 0.000035, 0.000106, 0.000106, 0.000106] 0.000342 X86ISelLowering.cpp:3363:0: llvm::X86TargetLowering::LowerCall(llvm::TargetLowering::CallLoweringInfo&, llvm::SmallVectorImpl<llvm::SDValue>&) const
  68. 124 32 [ 0.000003, 0.000007, 0.000016, 0.000041, 0.000041] 0.000310 Verifier.cpp:1967:0: (anonymous namespace)::Verifier::visitFunction(llvm::Function const&)
  69. 123 1 [ 0.000302, 0.000302, 0.000302, 0.000302, 0.000302] 0.000302 LLVMContextImpl.cpp:54:0: llvm::LLVMContextImpl::~LLVMContextImpl()
  70. 139 46 [ 0.000000, 0.000002, 0.000006, 0.000008, 0.000019] 0.000138 TargetLowering.cpp:506:0: llvm::TargetLowering::SimplifyDemandedBits(llvm::SDValue, llvm::APInt const&, llvm::APInt&, llvm::APInt&, llvm::TargetLowering::TargetLoweringOpt&, unsigned int, bool) const
  71. This shows us that for our input file, ``llc`` spent the most cumulative time
  72. in the lexer (a total of 1 millisecond). If we wanted for example to work with
  73. this data in a spreadsheet, we can output the results as CSV using the
  74. ``-format=csv`` option to the command for further analysis.
  75. If we want to get a textual representation of the raw trace we can use the
  76. ``llvm-xray convert`` tool to get YAML output. The first few lines of that
  77. output for an example trace would look like the following:
  78. ::
  79. $ llvm-xray convert -f yaml -symbolize -instr_map=./bin/llc xray-log.llc.m35qPB
  80. ---
  81. header:
  82. version: 1
  83. type: 0
  84. constant-tsc: true
  85. nonstop-tsc: true
  86. cycle-frequency: 2601000000
  87. records:
  88. - { type: 0, func-id: 110, function: __cxx_global_var_init.8, cpu: 37, thread: 69819, kind: function-enter, tsc: 5434426023268520 }
  89. - { type: 0, func-id: 110, function: __cxx_global_var_init.8, cpu: 37, thread: 69819, kind: function-exit, tsc: 5434426023523052 }
  90. - { type: 0, func-id: 164, function: __cxx_global_var_init, cpu: 37, thread: 69819, kind: function-enter, tsc: 5434426029925386 }
  91. - { type: 0, func-id: 164, function: __cxx_global_var_init, cpu: 37, thread: 69819, kind: function-exit, tsc: 5434426030031128 }
  92. - { type: 0, func-id: 142, function: '(anonymous namespace)::CommandLineParser::ParseCommandLineOptions(int, char const* const*, llvm::StringRef, llvm::raw_ostream*)', cpu: 37, thread: 69819, kind: function-enter, tsc: 5434426046951388 }
  93. - { type: 0, func-id: 142, function: '(anonymous namespace)::CommandLineParser::ParseCommandLineOptions(int, char const* const*, llvm::StringRef, llvm::raw_ostream*)', cpu: 37, thread: 69819, kind: function-exit, tsc: 5434426047282020 }
  94. - { type: 0, func-id: 187, function: 'llvm::LLLexer::LexIdentifier()', cpu: 37, thread: 69819, kind: function-enter, tsc: 5434426047857332 }
  95. - { type: 0, func-id: 187, function: 'llvm::LLLexer::LexIdentifier()', cpu: 37, thread: 69819, kind: function-exit, tsc: 5434426047984152 }
  96. - { type: 0, func-id: 187, function: 'llvm::LLLexer::LexIdentifier()', cpu: 37, thread: 69819, kind: function-enter, tsc: 5434426048036584 }
  97. - { type: 0, func-id: 187, function: 'llvm::LLLexer::LexIdentifier()', cpu: 37, thread: 69819, kind: function-exit, tsc: 5434426048042292 }
  98. - { type: 0, func-id: 187, function: 'llvm::LLLexer::LexIdentifier()', cpu: 37, thread: 69819, kind: function-enter, tsc: 5434426048055056 }
  99. - { type: 0, func-id: 187, function: 'llvm::LLLexer::LexIdentifier()', cpu: 37, thread: 69819, kind: function-exit, tsc: 5434426048067316 }
  100. Controlling Fidelity
  101. --------------------
  102. So far in our examples, we haven't been getting full coverage of the functions
  103. we have in the binary. To get that, we need to modify the compiler flags so
  104. that we can instrument more (if not all) the functions we have in the binary.
  105. We have two options for doing that, and we explore both of these below.
  106. Instruction Threshold
  107. `````````````````````
  108. The first "blunt" way of doing this is by setting the minimum threshold for
  109. function bodies to 1. We can do that with the
  110. ``-fxray-instruction-threshold=N`` flag when building our binary. We rebuild
  111. ``llc`` with this option and observe the results:
  112. ::
  113. $ rm CMakeCache.txt
  114. $ cmake -GNinja ../llvm -DCMAKE_BUILD_TYPE=Release \
  115. -DCMAKE_C_FLAGS_RELEASE="-fxray-instrument -fxray-instruction-threshold=1" \
  116. -DCMAKE_CXX_FLAGS="-fxray-instrument -fxray-instruction-threshold=1"
  117. $ ninja llc
  118. $ XRAY_OPTIONS="patch_premain=true" ./bin/llc input.ll
  119. ==69819==XRay: Log file in 'xray-log.llc.5rqxkU'
  120. $ llvm-xray account xray-log.llc.5rqxkU -top=10 -sort=sum -sortorder=dsc -instr_map ./bin/llc
  121. Functions with latencies: 36652
  122. funcid count [ min, med, 90p, 99p, max] sum function
  123. 75 1 [ 0.672368, 0.672368, 0.672368, 0.672368, 0.672368] 0.672368 llc.cpp:271:0: main
  124. 78 1 [ 0.626455, 0.626455, 0.626455, 0.626455, 0.626455] 0.626455 llc.cpp:381:0: compileModule(char**, llvm::LLVMContext&)
  125. 139617 1 [ 0.472618, 0.472618, 0.472618, 0.472618, 0.472618] 0.472618 LegacyPassManager.cpp:1723:0: llvm::legacy::PassManager::run(llvm::Module&)
  126. 139610 1 [ 0.472618, 0.472618, 0.472618, 0.472618, 0.472618] 0.472618 LegacyPassManager.cpp:1681:0: llvm::legacy::PassManagerImpl::run(llvm::Module&)
  127. 139612 1 [ 0.470948, 0.470948, 0.470948, 0.470948, 0.470948] 0.470948 LegacyPassManager.cpp:1564:0: (anonymous namespace)::MPPassManager::runOnModule(llvm::Module&)
  128. 139607 2 [ 0.147345, 0.315994, 0.315994, 0.315994, 0.315994] 0.463340 LegacyPassManager.cpp:1530:0: llvm::FPPassManager::runOnModule(llvm::Module&)
  129. 139605 21 [ 0.000002, 0.000002, 0.102593, 0.213336, 0.213336] 0.463331 LegacyPassManager.cpp:1491:0: llvm::FPPassManager::runOnFunction(llvm::Function&)
  130. 139563 26096 [ 0.000002, 0.000002, 0.000037, 0.000063, 0.000215] 0.225708 LegacyPassManager.cpp:1083:0: llvm::PMDataManager::findAnalysisPass(void const*, bool)
  131. 108055 188 [ 0.000002, 0.000120, 0.001375, 0.004523, 0.062624] 0.159279 MachineFunctionPass.cpp:38:0: llvm::MachineFunctionPass::runOnFunction(llvm::Function&)
  132. 62635 22 [ 0.000041, 0.000046, 0.000050, 0.126744, 0.126744] 0.127715 X86TargetMachine.cpp:242:0: llvm::X86TargetMachine::getSubtargetImpl(llvm::Function const&) const
  133. Instrumentation Attributes
  134. ``````````````````````````
  135. The other way is to use configuration files for selecting which functions
  136. should always be instrumented by the compiler. This gives us a way of ensuring
  137. that certain functions are either always or never instrumented by not having to
  138. add the attribute to the source.
  139. To use this feature, you can define one file for the functions to always
  140. instrument, and another for functions to never instrument. The format of these
  141. files are exactly the same as the SanitizerLists files that control similar
  142. things for the sanitizer implementations. For example:
  143. ::
  144. # xray-attr-list.txt
  145. # always instrument functions that match the following filters:
  146. [always]
  147. fun:main
  148. # never instrument functions that match the following filters:
  149. [never]
  150. fun:__cxx_*
  151. Given the file above we can re-build by providing it to the
  152. ``-fxray-attr-list=`` flag to clang. You can have multiple files, each defining
  153. different sets of attribute sets, to be combined into a single list by clang.
  154. The XRay stack tool
  155. -------------------
  156. Given a trace, and optionally an instrumentation map, the ``llvm-xray stack``
  157. command can be used to analyze a call stack graph constructed from the function
  158. call timeline.
  159. The way to use the command is to output the top stacks by call count and time spent.
  160. ::
  161. $ llvm-xray stack xray-log.llc.5rqxkU -instr_map ./bin/llc
  162. Unique Stacks: 3069
  163. Top 10 Stacks by leaf sum:
  164. Sum: 9633790
  165. lvl function count sum
  166. #0 main 1 58421550
  167. #1 compileModule(char**, llvm::LLVMContext&) 1 51440360
  168. #2 llvm::legacy::PassManagerImpl::run(llvm::Module&) 1 40535375
  169. #3 llvm::FPPassManager::runOnModule(llvm::Module&) 2 39337525
  170. #4 llvm::FPPassManager::runOnFunction(llvm::Function&) 6 39331465
  171. #5 llvm::PMDataManager::verifyPreservedAnalysis(llvm::Pass*) 399 16628590
  172. #6 llvm::PMTopLevelManager::findAnalysisPass(void const*) 4584 15155600
  173. #7 llvm::PMDataManager::findAnalysisPass(void const*, bool) 32088 9633790
  174. ..etc..
  175. In the default mode, identical stacks on different threads are independently
  176. aggregated. In a multithreaded program, you may end up having identical call
  177. stacks fill your list of top calls.
  178. To address this, you may specify the ``-aggregate-threads`` or
  179. ``-per-thread-stacks`` flags. ``-per-thread-stacks`` treats the thread id as an
  180. implicit root in each call stack tree, while ``-aggregate-threads`` combines
  181. identical stacks from all threads.
  182. Flame Graph Generation
  183. ----------------------
  184. The ``llvm-xray stack`` tool may also be used to generate flamegraphs for
  185. visualizing your instrumented invocations. The tool does not generate the graphs
  186. themselves, but instead generates a format that can be used with Brendan Gregg's
  187. FlameGraph tool, currently available on `github
  188. <https://github.com/brendangregg/FlameGraph>`_.
  189. To generate output for a flamegraph, a few more options are necessary.
  190. - ``-all-stacks`` - Emits all of the stacks.
  191. - ``-stack-format`` - Choose the flamegraph output format 'flame'.
  192. - ``-aggregation-type`` - Choose the metric to graph.
  193. You may pipe the command output directly to the flamegraph tool to obtain an
  194. svg file.
  195. ::
  196. $llvm-xray stack xray-log.llc.5rqxkU -instr_map ./bin/llc -stack-format=flame -aggregation-type=time -all-stacks | \
  197. /path/to/FlameGraph/flamegraph.pl > flamegraph.svg
  198. If you open the svg in a browser, mouse events allow exploring the call stacks.
  199. Chrome Trace Viewer Visualization
  200. ---------------------------------
  201. We can also generate a trace which can be loaded by the Chrome Trace Viewer
  202. from the same generated trace:
  203. ::
  204. $ llvm-xray convert -symbolize -instr_map=./bin/llc \
  205. -output-format=trace_event xray-log.llc.5rqxkU \
  206. | gzip > llc-trace.txt.gz
  207. From a Chrome browser, navigating to ``chrome:///tracing`` allows us to load
  208. the ``sample-trace.txt.gz`` file to visualize the execution trace.
  209. Further Exploration
  210. -------------------
  211. The ``llvm-xray`` tool has a few other subcommands that are in various stages
  212. of being developed. One interesting subcommand that can highlight a few
  213. interesting things is the ``graph`` subcommand. Given for example the following
  214. toy program that we build with XRay instrumentation, we can see how the
  215. generated graph may be a helpful indicator of where time is being spent for the
  216. application.
  217. .. code-block:: c++
  218. // sample.cc
  219. #include <iostream>
  220. #include <thread>
  221. [[clang::xray_always_instrument]] void f() {
  222. std::cerr << '.';
  223. }
  224. [[clang::xray_always_instrument]] void g() {
  225. for (int i = 0; i < 1 << 10; ++i) {
  226. std::cerr << '-';
  227. }
  228. }
  229. int main(int argc, char* argv[]) {
  230. std::thread t1([] {
  231. for (int i = 0; i < 1 << 10; ++i)
  232. f();
  233. });
  234. std::thread t2([] {
  235. g();
  236. });
  237. t1.join();
  238. t2.join();
  239. std::cerr << '\n';
  240. }
  241. We then build the above with XRay instrumentation:
  242. ::
  243. $ clang++ -o sample -O3 sample.cc -std=c++11 -fxray-instrument -fxray-instruction-threshold=1
  244. $ XRAY_OPTIONS="patch_premain=true xray_mode=xray-basic" ./sample
  245. We can then explore the graph rendering of the trace generated by this sample
  246. application. We assume you have the graphviz toosl available in your system,
  247. including both ``unflatten`` and ``dot``. If you prefer rendering or exploring
  248. the graph using another tool, then that should be feasible as well. ``llvm-xray
  249. graph`` will create DOT format graphs which should be usable in most graph
  250. rendering applications. One example invocation of the ``llvm-xray graph``
  251. command should yield some interesting insights to the workings of C++
  252. applications:
  253. ::
  254. $ llvm-xray graph xray-log.sample.* -m sample -color-edges=sum -edge-label=sum \
  255. | unflatten -f -l10 | dot -Tsvg -o sample.svg
  256. Next Steps
  257. ----------
  258. If you have some interesting analyses you'd like to implement as part of the
  259. llvm-xray tool, please feel free to propose them on the llvm-dev@ mailing list.
  260. The following are some ideas to inspire you in getting involved and potentially
  261. making things better.
  262. - Implement a query/filtering library that allows for finding patterns in the
  263. XRay traces.
  264. - Collecting function call stacks and how often they're encountered in the
  265. XRay trace.