1 ==========================
2 Source-based Code Coverage
3 ==========================
11 This document explains how to use clang's source-based code coverage feature.
12 It's called "source-based" because it operates on AST and preprocessor
13 information directly. This allows it to generate very precise coverage data.
15 Clang ships two other code coverage implementations:
17 * :doc:`SanitizerCoverage` - A low-overhead tool meant for use alongside the
18 various sanitizers. It can provide up to edge-level coverage.
20 * gcov - A GCC-compatible coverage implementation which operates on DebugInfo.
21 This is enabled by ``-ftest-coverage`` or ``--coverage``.
23 From this point onwards "code coverage" will refer to the source-based kind.
25 The code coverage workflow
26 ==========================
28 The code coverage workflow consists of three main steps:
30 * Compiling with coverage enabled.
32 * Running the instrumented program.
34 * Creating coverage reports.
36 The next few sections work through a complete, copy-'n-paste friendly example
37 based on this program:
42 #define BAR(x) ((x) || (x))
43 template <typename T> void foo(T x) {
44 for (unsigned I = 0; I < 10; ++I) { BAR(I); }
53 Compiling with coverage enabled
54 ===============================
56 To compile code with coverage enabled, pass ``-fprofile-instr-generate
57 -fcoverage-mapping`` to the compiler:
59 .. code-block:: console
61 # Step 1: Compile with coverage enabled.
62 % clang++ -fprofile-instr-generate -fcoverage-mapping foo.cc -o foo
64 Note that linking together code with and without coverage instrumentation is
65 supported. Uninstrumented code simply won't be accounted for in reports.
67 Running the instrumented program
68 ================================
70 The next step is to run the instrumented program. When the program exits it
71 will write a **raw profile** to the path specified by the ``LLVM_PROFILE_FILE``
72 environment variable. If that variable does not exist, the profile is written
73 to ``default.profraw`` in the current directory of the program. If
74 ``LLVM_PROFILE_FILE`` contains a path to a non-existent directory, the missing
75 directory structure will be created. Additionally, the following special
76 **pattern strings** are rewritten:
78 * "%p" expands out to the process ID.
80 * "%h" expands out to the hostname of the machine running the program.
82 * "%t" expands out to the value of the ``TMPDIR`` environment variable. On
83 Darwin, this is typically set to a temporary scratch directory.
85 * "%Nm" expands out to the instrumented binary's signature. When this pattern
86 is specified, the runtime creates a pool of N raw profiles which are used for
87 on-line profile merging. The runtime takes care of selecting a raw profile
88 from the pool, locking it, and updating it before the program exits. If N is
89 not specified (i.e the pattern is "%m"), it's assumed that ``N = 1``. The
90 merge pool specifier can only occur once per filename pattern.
92 * "%c" expands out to nothing, but enables a mode in which profile counter
93 updates are continuously synced to a file. This means that if the
94 instrumented program crashes, or is killed by a signal, perfect coverage
95 information can still be recovered. Continuous mode does not support value
96 profiling for PGO, and is only supported on Darwin at the moment. Support for
97 Linux may be mostly complete but requires testing, and support for Windows
98 may require more extensive changes: please get involved if you are interested
99 in porting this feature.
101 .. code-block:: console
103 # Step 2: Run the program.
104 % LLVM_PROFILE_FILE="foo.profraw" ./foo
106 Note that continuous mode is also used on Fuchsia where it's the only supported
107 mode, but the implementation is different. The Darwin and Linux implementation
108 relies on padding and the ability to map a file over the existing memory
109 mapping which is generally only available on POSIX systems and isn't suitable
112 On Fuchsia, we rely on the ability to relocate counters at runtime using a
113 level of indirection. On every counter access, we add a bias to the counter
114 address. This bias is stored in ``__llvm_profile_counter_bias`` symbol that's
115 provided by the profile runtime and is initially set to zero, meaning no
116 relocation. The runtime can map the profile into memory at arbitrary locations,
117 and set bias to the offset between the original and the new counter location,
118 at which point every subsequent counter access will be to the new location,
119 which allows updating profile directly akin to the continuous mode.
121 The advantage of this approach is that doesn't require any special OS support.
122 The disadvantage is the extra overhead due to additional instructions required
123 for each counter access (overhead both in terms of binary size and performance)
124 plus duplication of counters (i.e. one copy in the binary itself and another
125 copy that's mapped into memory). This implementation can be also enabled for
126 other platforms by passing the ``-runtime-counter-relocation`` option to the
127 backend during compilation.
129 For a program such as the `Lit <https://llvm.org/docs/CommandGuide/lit.html>`_
130 testing tool which invokes other programs, it may be necessary to set
131 ``LLVM_PROFILE_FILE`` for each invocation. The pattern strings "%p" or "%Nm"
132 may help to avoid corruption due to concurrency. Note that "%p" is also a Lit
133 token and needs to be escaped as "%%p".
135 .. code-block:: console
137 % clang++ -fprofile-instr-generate -fcoverage-mapping -mllvm -runtime-counter-relocation foo.cc -o foo
139 Creating coverage reports
140 =========================
142 Raw profiles have to be **indexed** before they can be used to generate
143 coverage reports. This is done using the "merge" tool in ``llvm-profdata``
144 (which can combine multiple raw profiles and index them at the same time):
146 .. code-block:: console
148 # Step 3(a): Index the raw profile.
149 % llvm-profdata merge -sparse foo.profraw -o foo.profdata
151 For an example of merging multiple profiles created by testing,
152 see the LLVM `coverage build script <https://github.com/llvm/llvm-zorg/blob/main/zorg/jenkins/jobs/jobs/llvm-coverage>`_.
154 There are multiple different ways to render coverage reports. The simplest
155 option is to generate a line-oriented report:
157 .. code-block:: console
159 # Step 3(b): Create a line-oriented coverage report.
160 % llvm-cov show ./foo -instr-profile=foo.profdata
162 This report includes a summary view as well as dedicated sub-views for
163 templated functions and their instantiations. For our example program, we get
164 distinct views for ``foo<int>(...)`` and ``foo<float>(...)``. If
165 ``-show-line-counts-or-regions`` is enabled, ``llvm-cov`` displays sub-line
166 region counts (even in macro expansions):
170 1| 20|#define BAR(x) ((x) || (x))
172 2| 2|template <typename T> void foo(T x) {
173 3| 22| for (unsigned I = 0; I < 10; ++I) { BAR(I); }
177 | void foo<int>(int):
178 | 2| 1|template <typename T> void foo(T x) {
179 | 3| 11| for (unsigned I = 0; I < 10; ++I) { BAR(I); }
183 | void foo<float>(int):
184 | 2| 1|template <typename T> void foo(T x) {
185 | 3| 11| for (unsigned I = 0; I < 10; ++I) { BAR(I); }
190 If ``--show-branches=count`` and ``--show-expansions`` are also enabled, the
191 sub-views will show detailed branch coverage information in addition to the
197 | void foo<float>(int):
198 | 2| 1|template <typename T> void foo(T x) {
199 | 3| 11| for (unsigned I = 0; I < 10; ++I) { BAR(I); }
202 | | | 1| 10|#define BAR(x) ((x) || (x))
204 | | | ------------------
205 | | | | Branch (1:17): [True: 9, False: 1]
206 | | | | Branch (1:24): [True: 0, False: 1]
207 | | | ------------------
209 | | Branch (3:23): [True: 10, False: 1]
215 To generate a file-level summary of coverage statistics instead of a
216 line-oriented report, try:
218 .. code-block:: console
220 # Step 3(c): Create a coverage summary.
221 % llvm-cov report ./foo -instr-profile=foo.profdata
222 Filename Regions Missed Regions Cover Functions Missed Functions Executed Lines Missed Lines Cover Branches Missed Branches Cover
223 --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
224 /tmp/foo.cc 13 0 100.00% 3 0 100.00% 13 0 100.00% 12 2 83.33%
225 --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
226 TOTAL 13 0 100.00% 3 0 100.00% 13 0 100.00% 12 2 83.33%
228 The ``llvm-cov`` tool supports specifying a custom demangler, writing out
229 reports in a directory structure, and generating html reports. For the full
230 list of options, please refer to the `command guide
231 <https://llvm.org/docs/CommandGuide/llvm-cov.html>`_.
235 * The ``-sparse`` flag is optional but can result in dramatically smaller
236 indexed profiles. This option should not be used if the indexed profile will
239 * Raw profiles can be discarded after they are indexed. Advanced use of the
240 profile runtime library allows an instrumented program to merge profiling
241 information directly into an existing raw profile on disk. The details are
244 * The ``llvm-profdata`` tool can be used to merge together multiple raw or
245 indexed profiles. To combine profiling data from multiple runs of a program,
248 .. code-block:: console
250 % llvm-profdata merge -sparse foo1.profraw foo2.profdata -o foo3.profdata
252 Exporting coverage data
253 =======================
255 Coverage data can be exported into JSON using the ``llvm-cov export``
256 sub-command. There is a comprehensive reference which defines the structure of
257 the exported data at a high level in the llvm-cov source code.
262 There are five statistics tracked in a coverage summary:
264 * Function coverage is the percentage of functions which have been executed at
265 least once. A function is considered to be executed if any of its
266 instantiations are executed.
268 * Instantiation coverage is the percentage of function instantiations which
269 have been executed at least once. Template functions and static inline
270 functions from headers are two kinds of functions which may have multiple
271 instantiations. This statistic is hidden by default in reports, but can be
272 enabled via the ``-show-instantiation-summary`` option.
274 * Line coverage is the percentage of code lines which have been executed at
275 least once. Only executable lines within function bodies are considered to be
278 * Region coverage is the percentage of code regions which have been executed at
279 least once. A code region may span multiple lines (e.g in a large function
280 body with no control flow). However, it's also possible for a single line to
281 contain multiple code regions (e.g in "return x || y && z").
283 * Branch coverage is the percentage of "true" and "false" branches that have
284 been taken at least once. Each branch is tied to individual conditions in the
285 source code that may each evaluate to either "true" or "false". These
286 conditions may comprise larger boolean expressions linked by boolean logical
287 operators. For example, "x = (y == 2) || (z < 10)" is a boolean expression
288 that is comprised of two individual conditions, each of which evaluates to
289 either true or false, producing four total branch outcomes.
291 Of these five statistics, function coverage is usually the least granular while
292 branch coverage is the most granular. 100% branch coverage for a function
293 implies 100% region coverage for a function. The project-wide totals for each
294 statistic are listed in the summary.
296 Format compatibility guarantees
297 ===============================
299 * There are no backwards or forwards compatibility guarantees for the raw
300 profile format. Raw profiles may be dependent on the specific compiler
301 revision used to generate them. It's inadvisable to store raw profiles for
302 long periods of time.
304 * Tools must retain **backwards** compatibility with indexed profile formats.
305 These formats are not forwards-compatible: i.e, a tool which uses format
306 version X will not be able to understand format version (X+k).
308 * Tools must also retain **backwards** compatibility with the format of the
309 coverage mappings emitted into instrumented binaries. These formats are not
312 * The JSON coverage export format has a (major, minor, patch) version triple.
313 Only a major version increment indicates a backwards-incompatible change. A
314 minor version increment is for added functionality, and patch version
315 increments are for bugfixes.
317 Impact of llvm optimizations on coverage reports
318 ================================================
320 llvm optimizations (such as inlining or CFG simplification) should have no
321 impact on coverage report quality. This is due to the fact that the mapping
322 from source regions to profile counters is immutable, and is generated before
323 the llvm optimizer kicks in. The optimizer can't prove that profile counter
324 instrumentation is safe to delete (because it's not: it affects the profile the
325 program emits), and so leaves it alone.
327 Note that this coverage feature does not rely on information that can degrade
328 during the course of optimization, such as debug info line tables.
330 Using the profiling runtime without static initializers
331 =======================================================
333 By default the compiler runtime uses a static initializer to determine the
334 profile output path and to register a writer function. To collect profiles
335 without using static initializers, do this manually:
337 * Export a ``int __llvm_profile_runtime`` symbol from each instrumented shared
338 library and executable. When the linker finds a definition of this symbol, it
339 knows to skip loading the object which contains the profiling runtime's
342 * Forward-declare ``void __llvm_profile_initialize_file(void)`` and call it
343 once from each instrumented executable. This function parses
344 ``LLVM_PROFILE_FILE``, sets the output path, and truncates any existing files
345 at that path. To get the same behavior without truncating existing files,
346 pass a filename pattern string to ``void __llvm_profile_set_filename(char
347 *)``. These calls can be placed anywhere so long as they precede all calls
348 to ``__llvm_profile_write_file``.
350 * Forward-declare ``int __llvm_profile_write_file(void)`` and call it to write
351 out a profile. This function returns 0 when it succeeds, and a non-zero value
352 otherwise. Calling this function multiple times appends profile data to an
353 existing on-disk raw profile.
355 In C++ files, declare these as ``extern "C"``.
357 Using the profiling runtime without a filesystem
358 ------------------------------------------------
360 The profiling runtime also supports freestanding environments that lack a
361 filesystem. The runtime ships as a static archive that's structured to make
362 dependencies on a hosted environment optional, depending on what features
363 the client application uses.
365 The first step is to export ``__llvm_profile_runtime``, as above, to disable
366 the default static initializers. Instead of calling the ``*_file()`` APIs
367 described above, use the following to save the profile directly to a buffer
370 * Forward-declare ``uint64_t __llvm_profile_get_size_for_buffer(void)`` and
371 call it to determine the size of the profile. You'll need to allocate a
374 * Forward-declare ``int __llvm_profile_write_buffer(char *Buffer)`` and call it
375 to copy the current counters to ``Buffer``, which is expected to already be
376 allocated and big enough for the profile.
378 * Optionally, forward-declare ``void __llvm_profile_reset_counters(void)`` and
379 call it to reset the counters before entering a specific section to be
380 profiled. This is only useful if there is some setup that should be excluded
383 In C++ files, declare these as ``extern "C"``.
385 Collecting coverage reports for the llvm project
386 ================================================
388 To prepare a coverage report for llvm (and any of its sub-projects), add
389 ``-DLLVM_BUILD_INSTRUMENTED_COVERAGE=On`` to the cmake configuration. Raw
390 profiles will be written to ``$BUILD_DIR/profiles/``. To prepare an html
391 report, run ``llvm/utils/prepare-code-coverage-artifact.py``.
393 To specify an alternate directory for raw profiles, use
394 ``-DLLVM_PROFILE_DATA_DIR``. To change the size of the profile merge pool, use
395 ``-DLLVM_PROFILE_MERGE_POOL_SIZE``.
397 Drawbacks and limitations
398 =========================
400 * Prior to version 2.26, the GNU binutils BFD linker is not able link programs
401 compiled with ``-fcoverage-mapping`` in its ``--gc-sections`` mode. Possible
402 workarounds include disabling ``--gc-sections``, upgrading to a newer version
403 of BFD, or using the Gold linker.
405 * Code coverage does not handle unpredictable changes in control flow or stack
406 unwinding in the presence of exceptions precisely. Consider the following
416 If the call to ``may_throw()`` propagates an exception into ``f``, the code
417 coverage tool may mark the ``return`` statement as executed even though it is
418 not. A call to ``longjmp()`` can have similar effects.
420 Clang implementation details
421 ============================
423 This section may be of interest to those wishing to understand or improve
424 the clang code coverage implementation.
429 Gap regions are source regions with counts. A reporting tool cannot set a line
430 execution count to the count from a gap region unless that region is the only
433 Gap regions are used to eliminate unnatural artifacts in coverage reports, such
434 as red "unexecuted" highlights present at the end of an otherwise covered line,
435 or blue "executed" highlights present at the start of a line that is otherwise
440 When viewing branch coverage details in source-based file-level sub-views using
441 ``--show-branches``, it is recommended that users show all macro expansions
442 (using option ``--show-expansions``) since macros may contain hidden branch
443 conditions. The coverage summary report will always include these macro-based
444 boolean expressions in the overall branch coverage count for a function or
447 Branch coverage is not tracked for constant folded branch conditions since
448 branches are not generated for these cases. In the source-based file-level
449 sub-view, these branches will simply be shown as ``[Folded - Ignored]`` so that
450 users are informed about what happened.
452 Branch coverage is tied directly to branch-generating conditions in the source
453 code. Users should not see hidden branches that aren't actually tied to the
460 The region mapping for a switch body consists of a gap region that covers the
461 entire body (starting from the '{' in 'switch (...) {', and terminating where the
462 last case ends). This gap region has a zero count: this causes "gap" areas in
463 between case statements, which contain no executable code, to appear uncovered.
465 When a switch case is visited, the parent region is extended: if the parent
466 region has no start location, its start location becomes the start of the case.
467 This is used to support switch statements without a ``CompoundStmt`` body, in
468 which the switch body and the single case share a count.
470 For switches with ``CompoundStmt`` bodies, a new region is created at the start
473 Branch regions are also generated for each switch case, including the default
474 case. If there is no explicitly defined default case in the source code, a
475 branch region is generated to correspond to the implicit default case that is
476 generated by the compiler. The implicit branch region is tied to the line and
477 column number of the switch statement condition since no source code for the
478 implicit case exists.