1========================== 2Source-based Code Coverage 3========================== 4 5.. contents:: 6 :local: 7 8Introduction 9============ 10 11This document explains how to use clang's source-based code coverage feature. 12It's called "source-based" because it operates on AST and preprocessor 13information directly. This allows it to generate very precise coverage data. 14 15Clang ships two other code coverage implementations: 16 17* :doc:`SanitizerCoverage` - A low-overhead tool meant for use alongside the 18 various sanitizers. It can provide up to edge-level coverage. 19 20* gcov - A GCC-compatible coverage implementation which operates on DebugInfo. 21 This is enabled by ``-ftest-coverage`` or ``--coverage``. 22 23From this point onwards "code coverage" will refer to the source-based kind. 24 25The code coverage workflow 26========================== 27 28The code coverage workflow consists of three main steps: 29 30* Compiling with coverage enabled. 31 32* Running the instrumented program. 33 34* Creating coverage reports. 35 36The next few sections work through a complete, copy-'n-paste friendly example 37based on this program: 38 39.. code-block:: cpp 40 41 % cat <<EOF > foo.cc 42 #define BAR(x) ((x) || (x)) 43 template <typename T> void foo(T x) { 44 for (unsigned I = 0; I < 10; ++I) { BAR(I); } 45 } 46 int main() { 47 foo<int>(0); 48 foo<float>(0); 49 return 0; 50 } 51 EOF 52 53Compiling with coverage enabled 54=============================== 55 56To compile code with coverage enabled, pass ``-fprofile-instr-generate 57-fcoverage-mapping`` to the compiler: 58 59.. code-block:: console 60 61 # Step 1: Compile with coverage enabled. 62 % clang++ -fprofile-instr-generate -fcoverage-mapping foo.cc -o foo 63 64Note that linking together code with and without coverage instrumentation is 65supported. Uninstrumented code simply won't be accounted for in reports. 66 67Instrumenting only selected files or functions 68---------------------------------------------- 69 70Sometimes it's useful to only instrument certain files or functions. For 71example in automated testing infrastructure, it may be desirable to only 72instrument files or functions that were modified by a patch to reduce the 73overhead of instrumenting a full system. 74 75This can be done using the ``-fprofile-list=file.list`` option. The option 76can be specified multiple times to pass multiple files: 77 78.. code-block:: console 79 80 $ echo "!fun:*test*" > fun.list 81 $ echo "src:code.cc" > src.list 82 % clang++ -O2 -fprofile-instr-generate -fcoverage-mapping -fprofile-list=fun.list -fprofile-list=code.list code.cc -o code 83 84The file uses :doc:`SanitizerSpecialCaseList` format. To filter individual 85functions or entire source files using ``fun:<name>`` or ``src:<file>`` 86respectively. To exclude a function or a source file, use ``!fun:<name>`` or 87``!src:<file>`` respectively. The format also supports wildcard expansion. The 88compiler generated functions are assumed to be located in the main source file. 89It is also possible to restrict the filter to a particular instrumentation type 90by using a named section. For example: 91 92.. code-block:: none 93 94 # all functions whose name starts with foo will be instrumented. 95 fun:foo* 96 97 # except for foo1 which will be excluded from instrumentation. 98 !fun:foo1 99 100 # every function in path/to/foo.cc will be instrumented. 101 src:path/to/foo.cc 102 103 # bar will be instrumented only when using backend instrumentation. 104 # Recognized section names are clang, llvm and csllvm. 105 [llvm] 106 fun:bar 107 108When the file contains only excludes, all files and functions except for the 109excluded ones will be instrumented. Otherwise, only the files and functions 110specified will be instrumented. 111 112Running the instrumented program 113================================ 114 115The next step is to run the instrumented program. When the program exits it 116will write a **raw profile** to the path specified by the ``LLVM_PROFILE_FILE`` 117environment variable. If that variable does not exist, the profile is written 118to ``default.profraw`` in the current directory of the program. If 119``LLVM_PROFILE_FILE`` contains a path to a non-existent directory, the missing 120directory structure will be created. Additionally, the following special 121**pattern strings** are rewritten: 122 123* "%p" expands out to the process ID. 124 125* "%h" expands out to the hostname of the machine running the program. 126 127* "%t" expands out to the value of the ``TMPDIR`` environment variable. On 128 Darwin, this is typically set to a temporary scratch directory. 129 130* "%Nm" expands out to the instrumented binary's signature. When this pattern 131 is specified, the runtime creates a pool of N raw profiles which are used for 132 on-line profile merging. The runtime takes care of selecting a raw profile 133 from the pool, locking it, and updating it before the program exits. If N is 134 not specified (i.e the pattern is "%m"), it's assumed that ``N = 1``. N must 135 be between 1 and 9. The merge pool specifier can only occur once per filename 136 pattern. 137 138* "%c" expands out to nothing, but enables a mode in which profile counter 139 updates are continuously synced to a file. This means that if the 140 instrumented program crashes, or is killed by a signal, perfect coverage 141 information can still be recovered. Continuous mode does not support value 142 profiling for PGO, and is only supported on Darwin at the moment. Support for 143 Linux may be mostly complete but requires testing, and support for Windows 144 may require more extensive changes: please get involved if you are interested 145 in porting this feature. 146 147.. code-block:: console 148 149 # Step 2: Run the program. 150 % LLVM_PROFILE_FILE="foo.profraw" ./foo 151 152Note that continuous mode is also used on Fuchsia where it's the only supported 153mode, but the implementation is different. The Darwin and Linux implementation 154relies on padding and the ability to map a file over the existing memory 155mapping which is generally only available on POSIX systems and isn't suitable 156for other platforms. 157 158On Fuchsia, we rely on the ability to relocate counters at runtime using a 159level of indirection. On every counter access, we add a bias to the counter 160address. This bias is stored in ``__llvm_profile_counter_bias`` symbol that's 161provided by the profile runtime and is initially set to zero, meaning no 162relocation. The runtime can map the profile into memory at arbitrary locations, 163and set bias to the offset between the original and the new counter location, 164at which point every subsequent counter access will be to the new location, 165which allows updating profile directly akin to the continuous mode. 166 167The advantage of this approach is that doesn't require any special OS support. 168The disadvantage is the extra overhead due to additional instructions required 169for each counter access (overhead both in terms of binary size and performance) 170plus duplication of counters (i.e. one copy in the binary itself and another 171copy that's mapped into memory). This implementation can be also enabled for 172other platforms by passing the ``-runtime-counter-relocation`` option to the 173backend during compilation. 174 175.. code-block:: console 176 177 % clang++ -fprofile-instr-generate -fcoverage-mapping -mllvm -runtime-counter-relocation foo.cc -o foo 178 179Creating coverage reports 180========================= 181 182Raw profiles have to be **indexed** before they can be used to generate 183coverage reports. This is done using the "merge" tool in ``llvm-profdata`` 184(which can combine multiple raw profiles and index them at the same time): 185 186.. code-block:: console 187 188 # Step 3(a): Index the raw profile. 189 % llvm-profdata merge -sparse foo.profraw -o foo.profdata 190 191There are multiple different ways to render coverage reports. The simplest 192option is to generate a line-oriented report: 193 194.. code-block:: console 195 196 # Step 3(b): Create a line-oriented coverage report. 197 % llvm-cov show ./foo -instr-profile=foo.profdata 198 199This report includes a summary view as well as dedicated sub-views for 200templated functions and their instantiations. For our example program, we get 201distinct views for ``foo<int>(...)`` and ``foo<float>(...)``. If 202``-show-line-counts-or-regions`` is enabled, ``llvm-cov`` displays sub-line 203region counts (even in macro expansions): 204 205.. code-block:: none 206 207 1| 20|#define BAR(x) ((x) || (x)) 208 ^20 ^2 209 2| 2|template <typename T> void foo(T x) { 210 3| 22| for (unsigned I = 0; I < 10; ++I) { BAR(I); } 211 ^22 ^20 ^20^20 212 4| 2|} 213 ------------------ 214 | void foo<int>(int): 215 | 2| 1|template <typename T> void foo(T x) { 216 | 3| 11| for (unsigned I = 0; I < 10; ++I) { BAR(I); } 217 | ^11 ^10 ^10^10 218 | 4| 1|} 219 ------------------ 220 | void foo<float>(int): 221 | 2| 1|template <typename T> void foo(T x) { 222 | 3| 11| for (unsigned I = 0; I < 10; ++I) { BAR(I); } 223 | ^11 ^10 ^10^10 224 | 4| 1|} 225 ------------------ 226 227If ``--show-branches=count`` and ``--show-expansions`` are also enabled, the 228sub-views will show detailed branch coverage information in addition to the 229region counts: 230 231.. code-block:: none 232 233 ------------------ 234 | void foo<float>(int): 235 | 2| 1|template <typename T> void foo(T x) { 236 | 3| 11| for (unsigned I = 0; I < 10; ++I) { BAR(I); } 237 | ^11 ^10 ^10^10 238 | ------------------ 239 | | | 1| 10|#define BAR(x) ((x) || (x)) 240 | | | ^10 ^1 241 | | | ------------------ 242 | | | | Branch (1:17): [True: 9, False: 1] 243 | | | | Branch (1:24): [True: 0, False: 1] 244 | | | ------------------ 245 | ------------------ 246 | | Branch (3:23): [True: 10, False: 1] 247 | ------------------ 248 | 4| 1|} 249 ------------------ 250 251 252To generate a file-level summary of coverage statistics instead of a 253line-oriented report, try: 254 255.. code-block:: console 256 257 # Step 3(c): Create a coverage summary. 258 % llvm-cov report ./foo -instr-profile=foo.profdata 259 Filename Regions Missed Regions Cover Functions Missed Functions Executed Lines Missed Lines Cover Branches Missed Branches Cover 260 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 261 /tmp/foo.cc 13 0 100.00% 3 0 100.00% 13 0 100.00% 12 2 83.33% 262 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 263 TOTAL 13 0 100.00% 3 0 100.00% 13 0 100.00% 12 2 83.33% 264 265The ``llvm-cov`` tool supports specifying a custom demangler, writing out 266reports in a directory structure, and generating html reports. For the full 267list of options, please refer to the `command guide 268<https://llvm.org/docs/CommandGuide/llvm-cov.html>`_. 269 270A few final notes: 271 272* The ``-sparse`` flag is optional but can result in dramatically smaller 273 indexed profiles. This option should not be used if the indexed profile will 274 be reused for PGO. 275 276* Raw profiles can be discarded after they are indexed. Advanced use of the 277 profile runtime library allows an instrumented program to merge profiling 278 information directly into an existing raw profile on disk. The details are 279 out of scope. 280 281* The ``llvm-profdata`` tool can be used to merge together multiple raw or 282 indexed profiles. To combine profiling data from multiple runs of a program, 283 try e.g: 284 285 .. code-block:: console 286 287 % llvm-profdata merge -sparse foo1.profraw foo2.profdata -o foo3.profdata 288 289Exporting coverage data 290======================= 291 292Coverage data can be exported into JSON using the ``llvm-cov export`` 293sub-command. There is a comprehensive reference which defines the structure of 294the exported data at a high level in the llvm-cov source code. 295 296Interpreting reports 297==================== 298 299There are four statistics tracked in a coverage summary: 300 301* Function coverage is the percentage of functions which have been executed at 302 least once. A function is considered to be executed if any of its 303 instantiations are executed. 304 305* Instantiation coverage is the percentage of function instantiations which 306 have been executed at least once. Template functions and static inline 307 functions from headers are two kinds of functions which may have multiple 308 instantiations. 309 310* Line coverage is the percentage of code lines which have been executed at 311 least once. Only executable lines within function bodies are considered to be 312 code lines. 313 314* Region coverage is the percentage of code regions which have been executed at 315 least once. A code region may span multiple lines (e.g in a large function 316 body with no control flow). However, it's also possible for a single line to 317 contain multiple code regions (e.g in "return x || y && z"). 318 319* Branch coverage is the percentage of "true" and "false" branches that have 320 been taken at least once. Each branch is tied to individual conditions in the 321 source code that may each evaluate to either "true" or "false". These 322 conditions may comprise larger boolean expressions linked by boolean logical 323 operators. For example, "x = (y == 2) || (z < 10)" is a boolean expression 324 that is comprised of two individual conditions, each of which evaluates to 325 either true or false, producing four total branch outcomes. 326 327Of these five statistics, function coverage is usually the least granular while 328branch coverage is the most granular. 100% branch coverage for a function 329implies 100% region coverage for a function. The project-wide totals for each 330statistic are listed in the summary. 331 332Format compatibility guarantees 333=============================== 334 335* There are no backwards or forwards compatibility guarantees for the raw 336 profile format. Raw profiles may be dependent on the specific compiler 337 revision used to generate them. It's inadvisable to store raw profiles for 338 long periods of time. 339 340* Tools must retain **backwards** compatibility with indexed profile formats. 341 These formats are not forwards-compatible: i.e, a tool which uses format 342 version X will not be able to understand format version (X+k). 343 344* Tools must also retain **backwards** compatibility with the format of the 345 coverage mappings emitted into instrumented binaries. These formats are not 346 forwards-compatible. 347 348* The JSON coverage export format has a (major, minor, patch) version triple. 349 Only a major version increment indicates a backwards-incompatible change. A 350 minor version increment is for added functionality, and patch version 351 increments are for bugfixes. 352 353Using the profiling runtime without static initializers 354======================================================= 355 356By default the compiler runtime uses a static initializer to determine the 357profile output path and to register a writer function. To collect profiles 358without using static initializers, do this manually: 359 360* Export a ``int __llvm_profile_runtime`` symbol from each instrumented shared 361 library and executable. When the linker finds a definition of this symbol, it 362 knows to skip loading the object which contains the profiling runtime's 363 static initializer. 364 365* Forward-declare ``void __llvm_profile_initialize_file(void)`` and call it 366 once from each instrumented executable. This function parses 367 ``LLVM_PROFILE_FILE``, sets the output path, and truncates any existing files 368 at that path. To get the same behavior without truncating existing files, 369 pass a filename pattern string to ``void __llvm_profile_set_filename(char 370 *)``. These calls can be placed anywhere so long as they precede all calls 371 to ``__llvm_profile_write_file``. 372 373* Forward-declare ``int __llvm_profile_write_file(void)`` and call it to write 374 out a profile. This function returns 0 when it succeeds, and a non-zero value 375 otherwise. Calling this function multiple times appends profile data to an 376 existing on-disk raw profile. 377 378In C++ files, declare these as ``extern "C"``. 379 380Collecting coverage reports for the llvm project 381================================================ 382 383To prepare a coverage report for llvm (and any of its sub-projects), add 384``-DLLVM_BUILD_INSTRUMENTED_COVERAGE=On`` to the cmake configuration. Raw 385profiles will be written to ``$BUILD_DIR/profiles/``. To prepare an html 386report, run ``llvm/utils/prepare-code-coverage-artifact.py``. 387 388To specify an alternate directory for raw profiles, use 389``-DLLVM_PROFILE_DATA_DIR``. To change the size of the profile merge pool, use 390``-DLLVM_PROFILE_MERGE_POOL_SIZE``. 391 392Drawbacks and limitations 393========================= 394 395* Prior to version 2.26, the GNU binutils BFD linker is not able link programs 396 compiled with ``-fcoverage-mapping`` in its ``--gc-sections`` mode. Possible 397 workarounds include disabling ``--gc-sections``, upgrading to a newer version 398 of BFD, or using the Gold linker. 399 400* Code coverage does not handle unpredictable changes in control flow or stack 401 unwinding in the presence of exceptions precisely. Consider the following 402 function: 403 404 .. code-block:: cpp 405 406 int f() { 407 may_throw(); 408 return 0; 409 } 410 411 If the call to ``may_throw()`` propagates an exception into ``f``, the code 412 coverage tool may mark the ``return`` statement as executed even though it is 413 not. A call to ``longjmp()`` can have similar effects. 414 415Clang implementation details 416============================ 417 418This section may be of interest to those wishing to understand or improve 419the clang code coverage implementation. 420 421Gap regions 422----------- 423 424Gap regions are source regions with counts. A reporting tool cannot set a line 425execution count to the count from a gap region unless that region is the only 426one on a line. 427 428Gap regions are used to eliminate unnatural artifacts in coverage reports, such 429as red "unexecuted" highlights present at the end of an otherwise covered line, 430or blue "executed" highlights present at the start of a line that is otherwise 431not executed. 432 433Branch regions 434-------------- 435When viewing branch coverage details in source-based file-level sub-views using 436``--show-branches``, it is recommended that users show all macro expansions 437(using option ``--show-expansions``) since macros may contain hidden branch 438conditions. The coverage summary report will always include these macro-based 439boolean expressions in the overall branch coverage count for a function or 440source file. 441 442Branch coverage is not tracked for constant folded branch conditions since 443branches are not generated for these cases. In the source-based file-level 444sub-view, these branches will simply be shown as ``[Folded - Ignored]`` so that 445users are informed about what happened. 446 447Branch coverage is tied directly to branch-generating conditions in the source 448code. Users should not see hidden branches that aren't actually tied to the 449source code. 450 451 452Switch statements 453----------------- 454 455The region mapping for a switch body consists of a gap region that covers the 456entire body (starting from the '{' in 'switch (...) {', and terminating where the 457last case ends). This gap region has a zero count: this causes "gap" areas in 458between case statements, which contain no executable code, to appear uncovered. 459 460When a switch case is visited, the parent region is extended: if the parent 461region has no start location, its start location becomes the start of the case. 462This is used to support switch statements without a ``CompoundStmt`` body, in 463which the switch body and the single case share a count. 464 465For switches with ``CompoundStmt`` bodies, a new region is created at the start 466of each switch case. 467 468Branch regions are also generated for each switch case, including the default 469case. If there is no explicitly defined default case in the source code, a 470branch region is generated to correspond to the implicit default case that is 471generated by the compiler. The implicit branch region is tied to the line and 472column number of the switch statement condition since no source code for the 473implicit case exists. 474