SourceBasedCodeCoverage.rst 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. ==========================
  2. Source-based Code Coverage
  3. ==========================
  4. .. contents::
  5. :local:
  6. Introduction
  7. ============
  8. This document explains how to use clang's source-based code coverage feature.
  9. It's called "source-based" because it operates on AST and preprocessor
  10. information directly. This allows it to generate very precise coverage data.
  11. Clang ships two other code coverage implementations:
  12. * :doc:`SanitizerCoverage` - A low-overhead tool meant for use alongside the
  13. various sanitizers. It can provide up to edge-level coverage.
  14. * gcov - A GCC-compatible coverage implementation which operates on DebugInfo.
  15. From this point onwards "code coverage" will refer to the source-based kind.
  16. The code coverage workflow
  17. ==========================
  18. The code coverage workflow consists of three main steps:
  19. * Compiling with coverage enabled.
  20. * Running the instrumented program.
  21. * Creating coverage reports.
  22. The next few sections work through a complete, copy-'n-paste friendly example
  23. based on this program:
  24. .. code-block:: cpp
  25. % cat <<EOF > foo.cc
  26. #define BAR(x) ((x) || (x))
  27. template <typename T> void foo(T x) {
  28. for (unsigned I = 0; I < 10; ++I) { BAR(I); }
  29. }
  30. int main() {
  31. foo<int>(0);
  32. foo<float>(0);
  33. return 0;
  34. }
  35. EOF
  36. Compiling with coverage enabled
  37. ===============================
  38. To compile code with coverage enabled, pass ``-fprofile-instr-generate
  39. -fcoverage-mapping`` to the compiler:
  40. .. code-block:: console
  41. # Step 1: Compile with coverage enabled.
  42. % clang++ -fprofile-instr-generate -fcoverage-mapping foo.cc -o foo
  43. Note that linking together code with and without coverage instrumentation is
  44. supported: any uninstrumented code simply won't be accounted for.
  45. Running the instrumented program
  46. ================================
  47. The next step is to run the instrumented program. When the program exits it
  48. will write a **raw profile** to the path specified by the ``LLVM_PROFILE_FILE``
  49. environment variable. If that variable does not exist, the profile is written
  50. to ``default.profraw`` in the current directory of the program. If
  51. ``LLVM_PROFILE_FILE`` contains a path to a non-existent directory, the missing
  52. directory structure will be created. Additionally, the following special
  53. **pattern strings** are rewritten:
  54. * "%p" expands out to the process ID.
  55. * "%h" expands out to the hostname of the machine running the program.
  56. * "%Nm" expands out to the instrumented binary's signature. When this pattern
  57. is specified, the runtime creates a pool of N raw profiles which are used for
  58. on-line profile merging. The runtime takes care of selecting a raw profile
  59. from the pool, locking it, and updating it before the program exits. If N is
  60. not specified (i.e the pattern is "%m"), it's assumed that ``N = 1``. N must
  61. be between 1 and 9. The merge pool specifier can only occur once per filename
  62. pattern.
  63. .. code-block:: console
  64. # Step 2: Run the program.
  65. % LLVM_PROFILE_FILE="foo.profraw" ./foo
  66. Creating coverage reports
  67. =========================
  68. Raw profiles have to be **indexed** before they can be used to generate
  69. coverage reports. This is done using the "merge" tool in ``llvm-profdata``, so
  70. named because it can combine and index profiles at the same time:
  71. .. code-block:: console
  72. # Step 3(a): Index the raw profile.
  73. % llvm-profdata merge -sparse foo.profraw -o foo.profdata
  74. There are multiple different ways to render coverage reports. One option is to
  75. generate a line-oriented report:
  76. .. code-block:: console
  77. # Step 3(b): Create a line-oriented coverage report.
  78. % llvm-cov show ./foo -instr-profile=foo.profdata
  79. To generate the same report in html with demangling turned on, use:
  80. .. code-block:: console
  81. % llvm-cov show ./foo -instr-profile=foo.profdata -format html -Xdemangler c++filt -Xdemangler -n
  82. This report includes a summary view as well as dedicated sub-views for
  83. templated functions and their instantiations. For our example program, we get
  84. distinct views for ``foo<int>(...)`` and ``foo<float>(...)``. If
  85. ``-show-line-counts-or-regions`` is enabled, ``llvm-cov`` displays sub-line
  86. region counts (even in macro expansions):
  87. .. code-block:: none
  88. 20| 1|#define BAR(x) ((x) || (x))
  89. ^20 ^2
  90. 2| 2|template <typename T> void foo(T x) {
  91. 22| 3| for (unsigned I = 0; I < 10; ++I) { BAR(I); }
  92. ^22 ^20 ^20^20
  93. 2| 4|}
  94. ------------------
  95. | void foo<int>(int):
  96. | 1| 2|template <typename T> void foo(T x) {
  97. | 11| 3| for (unsigned I = 0; I < 10; ++I) { BAR(I); }
  98. | ^11 ^10 ^10^10
  99. | 1| 4|}
  100. ------------------
  101. | void foo<float>(int):
  102. | 1| 2|template <typename T> void foo(T x) {
  103. | 11| 3| for (unsigned I = 0; I < 10; ++I) { BAR(I); }
  104. | ^11 ^10 ^10^10
  105. | 1| 4|}
  106. ------------------
  107. It's possible to generate a file-level summary of coverage statistics (instead
  108. of a line-oriented report) with:
  109. .. code-block:: console
  110. # Step 3(c): Create a coverage summary.
  111. % llvm-cov report ./foo -instr-profile=foo.profdata
  112. Filename Regions Missed Regions Cover Functions Missed Functions Executed Lines Missed Lines Cover
  113. --------------------------------------------------------------------------------------------------------------------------------------
  114. /tmp/foo.cc 13 0 100.00% 3 0 100.00% 13 0 100.00%
  115. --------------------------------------------------------------------------------------------------------------------------------------
  116. TOTAL 13 0 100.00% 3 0 100.00% 13 0 100.00%
  117. A few final notes:
  118. * The ``-sparse`` flag is optional but can result in dramatically smaller
  119. indexed profiles. This option should not be used if the indexed profile will
  120. be reused for PGO.
  121. * Raw profiles can be discarded after they are indexed. Advanced use of the
  122. profile runtime library allows an instrumented program to merge profiling
  123. information directly into an existing raw profile on disk. The details are
  124. out of scope.
  125. * The ``llvm-profdata`` tool can be used to merge together multiple raw or
  126. indexed profiles. To combine profiling data from multiple runs of a program,
  127. try e.g:
  128. .. code-block:: console
  129. % llvm-profdata merge -sparse foo1.profraw foo2.profdata -o foo3.profdata
  130. Format compatibility guarantees
  131. ===============================
  132. * There are no backwards or forwards compatibility guarantees for the raw
  133. profile format. Raw profiles may be dependent on the specific compiler
  134. revision used to generate them. It's inadvisable to store raw profiles for
  135. long periods of time.
  136. * Tools must retain **backwards** compatibility with indexed profile formats.
  137. These formats are not forwards-compatible: i.e, a tool which uses format
  138. version X will not be able to understand format version (X+k).
  139. * There is a third format in play: the format of the coverage mappings emitted
  140. into instrumented binaries. Tools must retain **backwards** compatibility
  141. with these formats. These formats are not forwards-compatible.
  142. Using the profiling runtime without static initializers
  143. =======================================================
  144. By default the compiler runtime uses a static initializer to determine the
  145. profile output path and to register a writer function. To collect profiles
  146. without using static initializers, do this manually:
  147. * Export a ``int __llvm_profile_runtime`` symbol from each instrumented shared
  148. library and executable. When the linker finds a definition of this symbol, it
  149. knows to skip loading the object which contains the profiling runtime's
  150. static initializer.
  151. * Forward-declare ``void __llvm_profile_initialize_file(void)`` and call it
  152. once from each instrumented executable. This function parses
  153. ``LLVM_PROFILE_FILE``, sets the output path, and truncates any existing files
  154. at that path. To get the same behavior without truncating existing files,
  155. pass a filename pattern string to ``void __llvm_profile_set_filename(char
  156. *)``. These calls can be placed anywhere so long as they precede all calls
  157. to ``__llvm_profile_write_file``.
  158. * Forward-declare ``int __llvm_profile_write_file(void)`` and call it to write
  159. out a profile. This function returns 0 when it succeeds, and a non-zero value
  160. otherwise. Calling this function multiple times appends profile data to an
  161. existing on-disk raw profile.
  162. Drawbacks and limitations
  163. =========================
  164. * Code coverage does not handle unpredictable changes in control flow or stack
  165. unwinding in the presence of exceptions precisely. Consider the following
  166. function:
  167. .. code-block:: cpp
  168. int f() {
  169. may_throw();
  170. return 0;
  171. }
  172. If the call to ``may_throw()`` propagates an exception into ``f``, the code
  173. coverage tool may mark the ``return`` statement as executed even though it is
  174. not. A call to ``longjmp()`` can have similar effects.