blob: 805c98794804a4379f0c230c92325b05fb326ca2 [file] [log] [blame]
Vedant Kumara530a362016-06-02 00:51:50 +00001==========================
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.
Vedant Kumar6eed0d52017-02-09 21:33:21 +000021 This is enabled by ``-ftest-coverage`` or ``--coverage``.
Vedant Kumara530a362016-06-02 00:51:50 +000022
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
Vedant Kumar0819f362016-06-02 02:25:13 +000030* Compiling with coverage enabled.
Vedant Kumara530a362016-06-02 00:51:50 +000031
Vedant Kumar0819f362016-06-02 02:25:13 +000032* Running the instrumented program.
Vedant Kumara530a362016-06-02 00:51:50 +000033
Vedant Kumar0819f362016-06-02 02:25:13 +000034* Creating coverage reports.
Vedant Kumara530a362016-06-02 00:51:50 +000035
36The next few sections work through a complete, copy-'n-paste friendly example
37based on this program:
38
Vedant Kumar4c1112c2016-06-02 01:15:59 +000039.. code-block:: cpp
Vedant Kumara530a362016-06-02 00:51:50 +000040
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
Vedant Kumar6c53d8f2016-06-02 02:45:59 +000056To compile code with coverage enabled, pass ``-fprofile-instr-generate
Vedant Kumara530a362016-06-02 00:51:50 +000057-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
Vedant Kumar74c3fd12016-09-22 15:34:33 +000065supported. Uninstrumented code simply won't be accounted for in reports.
Vedant Kumara530a362016-06-02 00:51:50 +000066
67Running the instrumented program
68================================
69
70The next step is to run the instrumented program. When the program exits it
71will write a **raw profile** to the path specified by the ``LLVM_PROFILE_FILE``
Vedant Kumar0819f362016-06-02 02:25:13 +000072environment variable. If that variable does not exist, the profile is written
73to ``default.profraw`` in the current directory of the program. If
74``LLVM_PROFILE_FILE`` contains a path to a non-existent directory, the missing
75directory structure will be created. Additionally, the following special
76**pattern strings** are rewritten:
Vedant Kumara530a362016-06-02 00:51:50 +000077
78* "%p" expands out to the process ID.
79
80* "%h" expands out to the hostname of the machine running the program.
81
Vedant Kumarf3300c92016-06-14 00:42:12 +000082* "%Nm" expands out to the instrumented binary's signature. When this pattern
83 is specified, the runtime creates a pool of N raw profiles which are used for
84 on-line profile merging. The runtime takes care of selecting a raw profile
85 from the pool, locking it, and updating it before the program exits. If N is
86 not specified (i.e the pattern is "%m"), it's assumed that ``N = 1``. N must
87 be between 1 and 9. The merge pool specifier can only occur once per filename
88 pattern.
89
Vedant Kumara530a362016-06-02 00:51:50 +000090.. code-block:: console
91
92 # Step 2: Run the program.
93 % LLVM_PROFILE_FILE="foo.profraw" ./foo
94
95Creating coverage reports
96=========================
97
Vedant Kumar0819f362016-06-02 02:25:13 +000098Raw profiles have to be **indexed** before they can be used to generate
Vedant Kumar74c3fd12016-09-22 15:34:33 +000099coverage reports. This is done using the "merge" tool in ``llvm-profdata``
100(which can combine multiple raw profiles and index them at the same time):
Vedant Kumara530a362016-06-02 00:51:50 +0000101
102.. code-block:: console
103
104 # Step 3(a): Index the raw profile.
105 % llvm-profdata merge -sparse foo.profraw -o foo.profdata
106
Vedant Kumar74c3fd12016-09-22 15:34:33 +0000107There are multiple different ways to render coverage reports. The simplest
108option is to generate a line-oriented report:
Vedant Kumara530a362016-06-02 00:51:50 +0000109
110.. code-block:: console
111
112 # Step 3(b): Create a line-oriented coverage report.
113 % llvm-cov show ./foo -instr-profile=foo.profdata
114
Vedant Kumara530a362016-06-02 00:51:50 +0000115This report includes a summary view as well as dedicated sub-views for
116templated functions and their instantiations. For our example program, we get
117distinct views for ``foo<int>(...)`` and ``foo<float>(...)``. If
118``-show-line-counts-or-regions`` is enabled, ``llvm-cov`` displays sub-line
119region counts (even in macro expansions):
120
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000121.. code-block:: none
Vedant Kumara530a362016-06-02 00:51:50 +0000122
Vedant Kumar9ed58022016-09-19 01:42:38 +0000123 1| 20|#define BAR(x) ((x) || (x))
Vedant Kumara530a362016-06-02 00:51:50 +0000124 ^20 ^2
125 2| 2|template <typename T> void foo(T x) {
Vedant Kumar9ed58022016-09-19 01:42:38 +0000126 3| 22| for (unsigned I = 0; I < 10; ++I) { BAR(I); }
Vedant Kumara530a362016-06-02 00:51:50 +0000127 ^22 ^20 ^20^20
Vedant Kumar9ed58022016-09-19 01:42:38 +0000128 4| 2|}
Vedant Kumara530a362016-06-02 00:51:50 +0000129 ------------------
130 | void foo<int>(int):
Vedant Kumar9ed58022016-09-19 01:42:38 +0000131 | 2| 1|template <typename T> void foo(T x) {
132 | 3| 11| for (unsigned I = 0; I < 10; ++I) { BAR(I); }
Vedant Kumara530a362016-06-02 00:51:50 +0000133 | ^11 ^10 ^10^10
Vedant Kumar9ed58022016-09-19 01:42:38 +0000134 | 4| 1|}
Vedant Kumara530a362016-06-02 00:51:50 +0000135 ------------------
136 | void foo<float>(int):
Vedant Kumar9ed58022016-09-19 01:42:38 +0000137 | 2| 1|template <typename T> void foo(T x) {
138 | 3| 11| for (unsigned I = 0; I < 10; ++I) { BAR(I); }
Vedant Kumara530a362016-06-02 00:51:50 +0000139 | ^11 ^10 ^10^10
Vedant Kumar9ed58022016-09-19 01:42:38 +0000140 | 4| 1|}
Vedant Kumara530a362016-06-02 00:51:50 +0000141 ------------------
142
Vedant Kumar74c3fd12016-09-22 15:34:33 +0000143To generate a file-level summary of coverage statistics instead of a
144line-oriented report, try:
Vedant Kumara530a362016-06-02 00:51:50 +0000145
146.. code-block:: console
147
148 # Step 3(c): Create a coverage summary.
149 % llvm-cov report ./foo -instr-profile=foo.profdata
Vedant Kumar3f42b132016-07-28 23:18:48 +0000150 Filename Regions Missed Regions Cover Functions Missed Functions Executed Lines Missed Lines Cover
151 --------------------------------------------------------------------------------------------------------------------------------------
152 /tmp/foo.cc 13 0 100.00% 3 0 100.00% 13 0 100.00%
153 --------------------------------------------------------------------------------------------------------------------------------------
154 TOTAL 13 0 100.00% 3 0 100.00% 13 0 100.00%
Vedant Kumara530a362016-06-02 00:51:50 +0000155
Vedant Kumar74c3fd12016-09-22 15:34:33 +0000156The ``llvm-cov`` tool supports specifying a custom demangler, writing out
157reports in a directory structure, and generating html reports. For the full
158list of options, please refer to the `command guide
159<http://llvm.org/docs/CommandGuide/llvm-cov.html>`_.
160
Vedant Kumara530a362016-06-02 00:51:50 +0000161A few final notes:
162
163* The ``-sparse`` flag is optional but can result in dramatically smaller
164 indexed profiles. This option should not be used if the indexed profile will
165 be reused for PGO.
166
167* Raw profiles can be discarded after they are indexed. Advanced use of the
168 profile runtime library allows an instrumented program to merge profiling
169 information directly into an existing raw profile on disk. The details are
170 out of scope.
171
172* The ``llvm-profdata`` tool can be used to merge together multiple raw or
173 indexed profiles. To combine profiling data from multiple runs of a program,
174 try e.g:
175
Vedant Kumar553a0d62016-06-02 17:19:45 +0000176 .. code-block:: console
Vedant Kumara530a362016-06-02 00:51:50 +0000177
Vedant Kumar553a0d62016-06-02 17:19:45 +0000178 % llvm-profdata merge -sparse foo1.profraw foo2.profdata -o foo3.profdata
Vedant Kumara530a362016-06-02 00:51:50 +0000179
Vedant Kumar6fe6eae2016-09-20 17:11:18 +0000180Exporting coverage data
181=======================
182
183Coverage data can be exported into JSON using the ``llvm-cov export``
184sub-command. There is a comprehensive reference which defines the structure of
185the exported data at a high level in the llvm-cov source code.
186
Vedant Kumar9ed58022016-09-19 01:42:38 +0000187Interpreting reports
188====================
189
190There are four statistics tracked in a coverage summary:
191
192* Function coverage is the percentage of functions which have been executed at
Vedant Kumar74c3fd12016-09-22 15:34:33 +0000193 least once. A function is considered to be executed if any of its
Vedant Kumar9ed58022016-09-19 01:42:38 +0000194 instantiations are executed.
195
196* Instantiation coverage is the percentage of function instantiations which
Vedant Kumar6fe6eae2016-09-20 17:11:18 +0000197 have been executed at least once. Template functions and static inline
198 functions from headers are two kinds of functions which may have multiple
199 instantiations.
Vedant Kumar9ed58022016-09-19 01:42:38 +0000200
201* Line coverage is the percentage of code lines which have been executed at
Vedant Kumar6fe6eae2016-09-20 17:11:18 +0000202 least once. Only executable lines within function bodies are considered to be
Vedant Kumar74c3fd12016-09-22 15:34:33 +0000203 code lines.
Vedant Kumar9ed58022016-09-19 01:42:38 +0000204
205* Region coverage is the percentage of code regions which have been executed at
Vedant Kumar74c3fd12016-09-22 15:34:33 +0000206 least once. A code region may span multiple lines (e.g in a large function
207 body with no control flow). However, it's also possible for a single line to
208 contain multiple code regions (e.g in "return x || y && z").
Vedant Kumar6fe6eae2016-09-20 17:11:18 +0000209
210Of these four statistics, function coverage is usually the least granular while
211region coverage is the most granular. The project-wide totals for each
212statistic are listed in the summary.
Vedant Kumar9ed58022016-09-19 01:42:38 +0000213
Vedant Kumara530a362016-06-02 00:51:50 +0000214Format compatibility guarantees
215===============================
216
217* There are no backwards or forwards compatibility guarantees for the raw
218 profile format. Raw profiles may be dependent on the specific compiler
219 revision used to generate them. It's inadvisable to store raw profiles for
220 long periods of time.
221
222* Tools must retain **backwards** compatibility with indexed profile formats.
223 These formats are not forwards-compatible: i.e, a tool which uses format
224 version X will not be able to understand format version (X+k).
225
Vedant Kumar74c3fd12016-09-22 15:34:33 +0000226* Tools must also retain **backwards** compatibility with the format of the
227 coverage mappings emitted into instrumented binaries. These formats are not
228 forwards-compatible.
Vedant Kumar553a0d62016-06-02 17:19:45 +0000229
Vedant Kumar6fe6eae2016-09-20 17:11:18 +0000230* The JSON coverage export format has a (major, minor, patch) version triple.
231 Only a major version increment indicates a backwards-incompatible change. A
232 minor version increment is for added functionality, and patch version
233 increments are for bugfixes.
234
Vedant Kumarb06294d2016-06-07 22:25:29 +0000235Using the profiling runtime without static initializers
236=======================================================
237
238By default the compiler runtime uses a static initializer to determine the
239profile output path and to register a writer function. To collect profiles
240without using static initializers, do this manually:
241
Vedant Kumar32a9bfa2016-06-08 22:24:52 +0000242* Export a ``int __llvm_profile_runtime`` symbol from each instrumented shared
243 library and executable. When the linker finds a definition of this symbol, it
244 knows to skip loading the object which contains the profiling runtime's
245 static initializer.
Vedant Kumarb06294d2016-06-07 22:25:29 +0000246
Vedant Kumar32a9bfa2016-06-08 22:24:52 +0000247* Forward-declare ``void __llvm_profile_initialize_file(void)`` and call it
248 once from each instrumented executable. This function parses
249 ``LLVM_PROFILE_FILE``, sets the output path, and truncates any existing files
250 at that path. To get the same behavior without truncating existing files,
251 pass a filename pattern string to ``void __llvm_profile_set_filename(char
252 *)``. These calls can be placed anywhere so long as they precede all calls
253 to ``__llvm_profile_write_file``.
Vedant Kumarb06294d2016-06-07 22:25:29 +0000254
Vedant Kumar32a9bfa2016-06-08 22:24:52 +0000255* Forward-declare ``int __llvm_profile_write_file(void)`` and call it to write
Vedant Kumar89262b62016-06-08 22:32:03 +0000256 out a profile. This function returns 0 when it succeeds, and a non-zero value
257 otherwise. Calling this function multiple times appends profile data to an
258 existing on-disk raw profile.
Vedant Kumarb06294d2016-06-07 22:25:29 +0000259
Nico Weberb1706ca2017-01-25 16:01:32 +0000260In C++ files, declare these as ``extern "C"``.
261
Vedant Kumar6fe6eae2016-09-20 17:11:18 +0000262Collecting coverage reports for the llvm project
263================================================
264
265To prepare a coverage report for llvm (and any of its sub-projects), add
266``-DLLVM_BUILD_INSTRUMENTED_COVERAGE=On`` to the cmake configuration. Raw
267profiles will be written to ``$BUILD_DIR/profiles/``. To prepare an html
268report, run ``llvm/utils/prepare-code-coverage-artifact.py``.
269
270To specify an alternate directory for raw profiles, use
271``-DLLVM_PROFILE_DATA_DIR``. To change the size of the profile merge pool, use
272``-DLLVM_PROFILE_MERGE_POOL_SIZE``.
273
Vedant Kumar553a0d62016-06-02 17:19:45 +0000274Drawbacks and limitations
275=========================
276
Vedant Kumar82cd7702017-06-19 21:22:05 +0000277* Prior to version 2.26, the GNU binutils BFD linker is not able link programs
Vedant Kumar1c5f3122017-06-19 21:26:04 +0000278 compiled with ``-fcoverage-mapping`` in its ``--gc-sections`` mode. Possible
279 workarounds include disabling ``--gc-sections``, upgrading to a newer version
280 of BFD, or using the Gold linker.
Vedant Kumar82cd7702017-06-19 21:22:05 +0000281
Vedant Kumar62baa4c2016-06-06 15:44:40 +0000282* Code coverage does not handle unpredictable changes in control flow or stack
283 unwinding in the presence of exceptions precisely. Consider the following
284 function:
Vedant Kumar553a0d62016-06-02 17:19:45 +0000285
286 .. code-block:: cpp
287
288 int f() {
289 may_throw();
290 return 0;
291 }
292
Vedant Kumar62baa4c2016-06-06 15:44:40 +0000293 If the call to ``may_throw()`` propagates an exception into ``f``, the code
Vedant Kumar553a0d62016-06-02 17:19:45 +0000294 coverage tool may mark the ``return`` statement as executed even though it is
Vedant Kumar62baa4c2016-06-06 15:44:40 +0000295 not. A call to ``longjmp()`` can have similar effects.