1a530a361SVedant Kumar==========================
2a530a361SVedant KumarSource-based Code Coverage
3a530a361SVedant Kumar==========================
4a530a361SVedant Kumar
5a530a361SVedant Kumar.. contents::
6a530a361SVedant Kumar   :local:
7a530a361SVedant Kumar
8a530a361SVedant KumarIntroduction
9a530a361SVedant Kumar============
10a530a361SVedant Kumar
11a530a361SVedant KumarThis document explains how to use clang's source-based code coverage feature.
12a530a361SVedant KumarIt's called "source-based" because it operates on AST and preprocessor
13a530a361SVedant Kumarinformation directly. This allows it to generate very precise coverage data.
14a530a361SVedant Kumar
15a530a361SVedant KumarClang ships two other code coverage implementations:
16a530a361SVedant Kumar
17a530a361SVedant Kumar* :doc:`SanitizerCoverage` - A low-overhead tool meant for use alongside the
18a530a361SVedant Kumar  various sanitizers. It can provide up to edge-level coverage.
19a530a361SVedant Kumar
20a530a361SVedant Kumar* gcov - A GCC-compatible coverage implementation which operates on DebugInfo.
216eed0d5bSVedant Kumar  This is enabled by ``-ftest-coverage`` or ``--coverage``.
22a530a361SVedant Kumar
23a530a361SVedant KumarFrom this point onwards "code coverage" will refer to the source-based kind.
24a530a361SVedant Kumar
25a530a361SVedant KumarThe code coverage workflow
26a530a361SVedant Kumar==========================
27a530a361SVedant Kumar
28a530a361SVedant KumarThe code coverage workflow consists of three main steps:
29a530a361SVedant Kumar
300819f36dSVedant Kumar* Compiling with coverage enabled.
31a530a361SVedant Kumar
320819f36dSVedant Kumar* Running the instrumented program.
33a530a361SVedant Kumar
340819f36dSVedant Kumar* Creating coverage reports.
35a530a361SVedant Kumar
36a530a361SVedant KumarThe next few sections work through a complete, copy-'n-paste friendly example
37a530a361SVedant Kumarbased on this program:
38a530a361SVedant Kumar
394c1112c3SVedant Kumar.. code-block:: cpp
40a530a361SVedant Kumar
41a530a361SVedant Kumar    % cat <<EOF > foo.cc
42a530a361SVedant Kumar    #define BAR(x) ((x) || (x))
43a530a361SVedant Kumar    template <typename T> void foo(T x) {
44a530a361SVedant Kumar      for (unsigned I = 0; I < 10; ++I) { BAR(I); }
45a530a361SVedant Kumar    }
46a530a361SVedant Kumar    int main() {
47a530a361SVedant Kumar      foo<int>(0);
48a530a361SVedant Kumar      foo<float>(0);
49a530a361SVedant Kumar      return 0;
50a530a361SVedant Kumar    }
51a530a361SVedant Kumar    EOF
52a530a361SVedant Kumar
53a530a361SVedant KumarCompiling with coverage enabled
54a530a361SVedant Kumar===============================
55a530a361SVedant Kumar
566c53d8f9SVedant KumarTo compile code with coverage enabled, pass ``-fprofile-instr-generate
57a530a361SVedant Kumar-fcoverage-mapping`` to the compiler:
58a530a361SVedant Kumar
59a530a361SVedant Kumar.. code-block:: console
60a530a361SVedant Kumar
61a530a361SVedant Kumar    # Step 1: Compile with coverage enabled.
62a530a361SVedant Kumar    % clang++ -fprofile-instr-generate -fcoverage-mapping foo.cc -o foo
63a530a361SVedant Kumar
64a530a361SVedant KumarNote that linking together code with and without coverage instrumentation is
6574c3fd17SVedant Kumarsupported. Uninstrumented code simply won't be accounted for in reports.
66a530a361SVedant Kumar
67a530a361SVedant KumarRunning the instrumented program
68a530a361SVedant Kumar================================
69a530a361SVedant Kumar
70a530a361SVedant KumarThe next step is to run the instrumented program. When the program exits it
71a530a361SVedant Kumarwill write a **raw profile** to the path specified by the ``LLVM_PROFILE_FILE``
720819f36dSVedant Kumarenvironment variable. If that variable does not exist, the profile is written
730819f36dSVedant Kumarto ``default.profraw`` in the current directory of the program. If
740819f36dSVedant Kumar``LLVM_PROFILE_FILE`` contains a path to a non-existent directory, the missing
750819f36dSVedant Kumardirectory structure will be created.  Additionally, the following special
760819f36dSVedant Kumar**pattern strings** are rewritten:
77a530a361SVedant Kumar
78a530a361SVedant Kumar* "%p" expands out to the process ID.
79a530a361SVedant Kumar
80a530a361SVedant Kumar* "%h" expands out to the hostname of the machine running the program.
81a530a361SVedant Kumar
8262c37277SVedant Kumar* "%t" expands out to the value of the ``TMPDIR`` environment variable. On
8362c37277SVedant Kumar  Darwin, this is typically set to a temporary scratch directory.
8462c37277SVedant Kumar
85f3300c9fSVedant Kumar* "%Nm" expands out to the instrumented binary's signature. When this pattern
86f3300c9fSVedant Kumar  is specified, the runtime creates a pool of N raw profiles which are used for
87f3300c9fSVedant Kumar  on-line profile merging. The runtime takes care of selecting a raw profile
88f3300c9fSVedant Kumar  from the pool, locking it, and updating it before the program exits.  If N is
89f3300c9fSVedant Kumar  not specified (i.e the pattern is "%m"), it's assumed that ``N = 1``. N must
90f3300c9fSVedant Kumar  be between 1 and 9. The merge pool specifier can only occur once per filename
91f3300c9fSVedant Kumar  pattern.
92f3300c9fSVedant Kumar
93d889d1efSVedant Kumar* "%c" expands out to nothing, but enables a mode in which profile counter
94d889d1efSVedant Kumar  updates are continuously synced to a file. This means that if the
95d889d1efSVedant Kumar  instrumented program crashes, or is killed by a signal, perfect coverage
962492b5a1SVedant Kumar  information can still be recovered. Continuous mode does not support value
972492b5a1SVedant Kumar  profiling for PGO, and is only supported on Darwin at the moment. Support for
98d3db13afSPetr Hosek  Linux may be mostly complete but requires testing, and support for Windows
99d3db13afSPetr Hosek  may require more extensive changes: please get involved if you are interested
100d3db13afSPetr Hosek  in porting this feature.
101d889d1efSVedant Kumar
102a530a361SVedant Kumar.. code-block:: console
103a530a361SVedant Kumar
104a530a361SVedant Kumar    # Step 2: Run the program.
105a530a361SVedant Kumar    % LLVM_PROFILE_FILE="foo.profraw" ./foo
106a530a361SVedant Kumar
107d3db13afSPetr HosekNote that continuous mode is also used on Fuchsia where it's the only supported
108d3db13afSPetr Hosekmode, but the implementation is different. The Darwin and Linux implementation
109d3db13afSPetr Hosekrelies on padding and the ability to map a file over the existing memory
110d3db13afSPetr Hosekmapping which is generally only available on POSIX systems and isn't suitable
111d3db13afSPetr Hosekfor other platforms.
112d3db13afSPetr Hosek
113b50431deSNico WeberOn Fuchsia, we rely on the ability to relocate counters at runtime using a
114d3db13afSPetr Hoseklevel of indirection. On every counter access, we add a bias to the counter
115d3db13afSPetr Hosekaddress. This bias is stored in ``__llvm_profile_counter_bias`` symbol that's
116d3db13afSPetr Hosekprovided by the profile runtime and is initially set to zero, meaning no
117b50431deSNico Weberrelocation. The runtime can map the profile into memory at arbitrary locations,
118d3db13afSPetr Hosekand set bias to the offset between the original and the new counter location,
119d3db13afSPetr Hosekat which point every subsequent counter access will be to the new location,
120b50431deSNico Weberwhich allows updating profile directly akin to the continuous mode.
121d3db13afSPetr Hosek
122d3db13afSPetr HosekThe advantage of this approach is that doesn't require any special OS support.
123d3db13afSPetr HosekThe disadvantage is the extra overhead due to additional instructions required
124d3db13afSPetr Hosekfor each counter access (overhead both in terms of binary size and performance)
125d3db13afSPetr Hosekplus duplication of counters (i.e. one copy in the binary itself and another
126d3db13afSPetr Hosekcopy that's mapped into memory). This implementation can be also enabled for
127d3db13afSPetr Hosekother platforms by passing the ``-runtime-counter-relocation`` option to the
128d3db13afSPetr Hosekbackend during compilation.
129d3db13afSPetr Hosek
130d3db13afSPetr Hosek.. code-block:: console
131d3db13afSPetr Hosek
132d3db13afSPetr Hosek    % clang++ -fprofile-instr-generate -fcoverage-mapping -mllvm -runtime-counter-relocation foo.cc -o foo
133d3db13afSPetr Hosek
134a530a361SVedant KumarCreating coverage reports
135a530a361SVedant Kumar=========================
136a530a361SVedant Kumar
1370819f36dSVedant KumarRaw profiles have to be **indexed** before they can be used to generate
13874c3fd17SVedant Kumarcoverage reports. This is done using the "merge" tool in ``llvm-profdata``
13974c3fd17SVedant Kumar(which can combine multiple raw profiles and index them at the same time):
140a530a361SVedant Kumar
141a530a361SVedant Kumar.. code-block:: console
142a530a361SVedant Kumar
143a530a361SVedant Kumar    # Step 3(a): Index the raw profile.
144a530a361SVedant Kumar    % llvm-profdata merge -sparse foo.profraw -o foo.profdata
145a530a361SVedant Kumar
14674c3fd17SVedant KumarThere are multiple different ways to render coverage reports. The simplest
14774c3fd17SVedant Kumaroption is to generate a line-oriented report:
148a530a361SVedant Kumar
149a530a361SVedant Kumar.. code-block:: console
150a530a361SVedant Kumar
151a530a361SVedant Kumar    # Step 3(b): Create a line-oriented coverage report.
152a530a361SVedant Kumar    % llvm-cov show ./foo -instr-profile=foo.profdata
153a530a361SVedant Kumar
154a530a361SVedant KumarThis report includes a summary view as well as dedicated sub-views for
155a530a361SVedant Kumartemplated functions and their instantiations. For our example program, we get
156a530a361SVedant Kumardistinct views for ``foo<int>(...)`` and ``foo<float>(...)``.  If
157a530a361SVedant Kumar``-show-line-counts-or-regions`` is enabled, ``llvm-cov`` displays sub-line
158a530a361SVedant Kumarregion counts (even in macro expansions):
159a530a361SVedant Kumar
160bc8cc5acSGeorge Burgess IV.. code-block:: none
161a530a361SVedant Kumar
1629ed58026SVedant Kumar        1|   20|#define BAR(x) ((x) || (x))
163a530a361SVedant Kumar                               ^20     ^2
164a530a361SVedant Kumar        2|    2|template <typename T> void foo(T x) {
1659ed58026SVedant Kumar        3|   22|  for (unsigned I = 0; I < 10; ++I) { BAR(I); }
166a530a361SVedant Kumar                                       ^22     ^20  ^20^20
1679ed58026SVedant Kumar        4|    2|}
168a530a361SVedant Kumar    ------------------
169a530a361SVedant Kumar    | void foo<int>(int):
1709ed58026SVedant Kumar    |      2|    1|template <typename T> void foo(T x) {
1719ed58026SVedant Kumar    |      3|   11|  for (unsigned I = 0; I < 10; ++I) { BAR(I); }
172a530a361SVedant Kumar    |                                     ^11     ^10  ^10^10
1739ed58026SVedant Kumar    |      4|    1|}
174a530a361SVedant Kumar    ------------------
175a530a361SVedant Kumar    | void foo<float>(int):
1769ed58026SVedant Kumar    |      2|    1|template <typename T> void foo(T x) {
1779ed58026SVedant Kumar    |      3|   11|  for (unsigned I = 0; I < 10; ++I) { BAR(I); }
178a530a361SVedant Kumar    |                                     ^11     ^10  ^10^10
1799ed58026SVedant Kumar    |      4|    1|}
180a530a361SVedant Kumar    ------------------
181a530a361SVedant Kumar
1829f2967bcSAlan PhippsIf ``--show-branches=count`` and ``--show-expansions`` are also enabled, the
1839f2967bcSAlan Phippssub-views will show detailed branch coverage information in addition to the
1849f2967bcSAlan Phippsregion counts:
1859f2967bcSAlan Phipps
1869f2967bcSAlan Phipps.. code-block:: none
1879f2967bcSAlan Phipps
1889f2967bcSAlan Phipps    ------------------
1899f2967bcSAlan Phipps    | void foo<float>(int):
1909f2967bcSAlan Phipps    |      2|    1|template <typename T> void foo(T x) {
1919f2967bcSAlan Phipps    |      3|   11|  for (unsigned I = 0; I < 10; ++I) { BAR(I); }
1929f2967bcSAlan Phipps    |                                     ^11     ^10  ^10^10
1939f2967bcSAlan Phipps    |  ------------------
1949f2967bcSAlan Phipps    |  |  |    1|     10|#define BAR(x) ((x) || (x))
1959f2967bcSAlan Phipps    |  |  |                             ^10     ^1
1969f2967bcSAlan Phipps    |  |  |  ------------------
1979f2967bcSAlan Phipps    |  |  |  |  Branch (1:17): [True: 9, False: 1]
1989f2967bcSAlan Phipps    |  |  |  |  Branch (1:24): [True: 0, False: 1]
1999f2967bcSAlan Phipps    |  |  |  ------------------
2009f2967bcSAlan Phipps    |  ------------------
2019f2967bcSAlan Phipps    |  |  Branch (3:23): [True: 10, False: 1]
2029f2967bcSAlan Phipps    |  ------------------
2039f2967bcSAlan Phipps    |      4|    1|}
2049f2967bcSAlan Phipps    ------------------
2059f2967bcSAlan Phipps
2069f2967bcSAlan Phipps
20774c3fd17SVedant KumarTo generate a file-level summary of coverage statistics instead of a
20874c3fd17SVedant Kumarline-oriented report, try:
209a530a361SVedant Kumar
210a530a361SVedant Kumar.. code-block:: console
211a530a361SVedant Kumar
212a530a361SVedant Kumar    # Step 3(c): Create a coverage summary.
213a530a361SVedant Kumar    % llvm-cov report ./foo -instr-profile=foo.profdata
2149f2967bcSAlan Phipps    Filename           Regions    Missed Regions     Cover   Functions  Missed Functions  Executed       Lines      Missed Lines     Cover     Branches    Missed Branches     Cover
2159f2967bcSAlan Phipps    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2169f2967bcSAlan Phipps    /tmp/foo.cc             13                 0   100.00%           3                 0   100.00%          13                 0   100.00%           12                  2    83.33%
2179f2967bcSAlan Phipps    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2189f2967bcSAlan Phipps    TOTAL                   13                 0   100.00%           3                 0   100.00%          13                 0   100.00%           12                  2    83.33%
219a530a361SVedant Kumar
22074c3fd17SVedant KumarThe ``llvm-cov`` tool supports specifying a custom demangler, writing out
22174c3fd17SVedant Kumarreports in a directory structure, and generating html reports. For the full
22274c3fd17SVedant Kumarlist of options, please refer to the `command guide
223bc5c3f57SSylvestre Ledru<https://llvm.org/docs/CommandGuide/llvm-cov.html>`_.
22474c3fd17SVedant Kumar
225a530a361SVedant KumarA few final notes:
226a530a361SVedant Kumar
227a530a361SVedant Kumar* The ``-sparse`` flag is optional but can result in dramatically smaller
228a530a361SVedant Kumar  indexed profiles. This option should not be used if the indexed profile will
229a530a361SVedant Kumar  be reused for PGO.
230a530a361SVedant Kumar
231a530a361SVedant Kumar* Raw profiles can be discarded after they are indexed. Advanced use of the
232a530a361SVedant Kumar  profile runtime library allows an instrumented program to merge profiling
233a530a361SVedant Kumar  information directly into an existing raw profile on disk. The details are
234a530a361SVedant Kumar  out of scope.
235a530a361SVedant Kumar
236a530a361SVedant Kumar* The ``llvm-profdata`` tool can be used to merge together multiple raw or
237a530a361SVedant Kumar  indexed profiles. To combine profiling data from multiple runs of a program,
238a530a361SVedant Kumar  try e.g:
239a530a361SVedant Kumar
240a530a361SVedant Kumar  .. code-block:: console
241a530a361SVedant Kumar
242a530a361SVedant Kumar      % llvm-profdata merge -sparse foo1.profraw foo2.profdata -o foo3.profdata
243a530a361SVedant Kumar
2446fe6eae7SVedant KumarExporting coverage data
2456fe6eae7SVedant Kumar=======================
2466fe6eae7SVedant Kumar
2476fe6eae7SVedant KumarCoverage data can be exported into JSON using the ``llvm-cov export``
2486fe6eae7SVedant Kumarsub-command. There is a comprehensive reference which defines the structure of
2496fe6eae7SVedant Kumarthe exported data at a high level in the llvm-cov source code.
2506fe6eae7SVedant Kumar
2519ed58026SVedant KumarInterpreting reports
2529ed58026SVedant Kumar====================
2539ed58026SVedant Kumar
2540c4935bbSVedant KumarThere are five statistics tracked in a coverage summary:
2559ed58026SVedant Kumar
2569ed58026SVedant Kumar* Function coverage is the percentage of functions which have been executed at
25774c3fd17SVedant Kumar  least once. A function is considered to be executed if any of its
2589ed58026SVedant Kumar  instantiations are executed.
2599ed58026SVedant Kumar
2609ed58026SVedant Kumar* Instantiation coverage is the percentage of function instantiations which
2616fe6eae7SVedant Kumar  have been executed at least once. Template functions and static inline
2626fe6eae7SVedant Kumar  functions from headers are two kinds of functions which may have multiple
2630c4935bbSVedant Kumar  instantiations. This statistic is hidden by default in reports, but can be
2640c4935bbSVedant Kumar  enabled via the ``-show-instantiation-summary`` option.
2659ed58026SVedant Kumar
2669ed58026SVedant Kumar* Line coverage is the percentage of code lines which have been executed at
2676fe6eae7SVedant Kumar  least once. Only executable lines within function bodies are considered to be
26874c3fd17SVedant Kumar  code lines.
2699ed58026SVedant Kumar
2709ed58026SVedant Kumar* Region coverage is the percentage of code regions which have been executed at
27174c3fd17SVedant Kumar  least once. A code region may span multiple lines (e.g in a large function
27274c3fd17SVedant Kumar  body with no control flow). However, it's also possible for a single line to
27374c3fd17SVedant Kumar  contain multiple code regions (e.g in "return x || y && z").
2746fe6eae7SVedant Kumar
2759f2967bcSAlan Phipps* Branch coverage is the percentage of "true" and "false" branches that have
2769f2967bcSAlan Phipps  been taken at least once. Each branch is tied to individual conditions in the
2779f2967bcSAlan Phipps  source code that may each evaluate to either "true" or "false".  These
2789f2967bcSAlan Phipps  conditions may comprise larger boolean expressions linked by boolean logical
2799f2967bcSAlan Phipps  operators. For example, "x = (y == 2) || (z < 10)" is a boolean expression
2809f2967bcSAlan Phipps  that is comprised of two individual conditions, each of which evaluates to
2819f2967bcSAlan Phipps  either true or false, producing four total branch outcomes.
2829f2967bcSAlan Phipps
2839f2967bcSAlan PhippsOf these five statistics, function coverage is usually the least granular while
2849f2967bcSAlan Phippsbranch coverage is the most granular. 100% branch coverage for a function
2859f2967bcSAlan Phippsimplies 100% region coverage for a function. The project-wide totals for each
2866fe6eae7SVedant Kumarstatistic are listed in the summary.
2879ed58026SVedant Kumar
288a530a361SVedant KumarFormat compatibility guarantees
289a530a361SVedant Kumar===============================
290a530a361SVedant Kumar
291a530a361SVedant Kumar* There are no backwards or forwards compatibility guarantees for the raw
292a530a361SVedant Kumar  profile format. Raw profiles may be dependent on the specific compiler
293a530a361SVedant Kumar  revision used to generate them. It's inadvisable to store raw profiles for
294a530a361SVedant Kumar  long periods of time.
295a530a361SVedant Kumar
296a530a361SVedant Kumar* Tools must retain **backwards** compatibility with indexed profile formats.
297a530a361SVedant Kumar  These formats are not forwards-compatible: i.e, a tool which uses format
298a530a361SVedant Kumar  version X will not be able to understand format version (X+k).
299a530a361SVedant Kumar
30074c3fd17SVedant Kumar* Tools must also retain **backwards** compatibility with the format of the
30174c3fd17SVedant Kumar  coverage mappings emitted into instrumented binaries. These formats are not
30274c3fd17SVedant Kumar  forwards-compatible.
303553a0d62SVedant Kumar
3046fe6eae7SVedant Kumar* The JSON coverage export format has a (major, minor, patch) version triple.
3056fe6eae7SVedant Kumar  Only a major version increment indicates a backwards-incompatible change. A
3066fe6eae7SVedant Kumar  minor version increment is for added functionality, and patch version
3076fe6eae7SVedant Kumar  increments are for bugfixes.
3086fe6eae7SVedant Kumar
30913bd6fb4SVedant KumarImpact of llvm optimizations on coverage reports
31013bd6fb4SVedant Kumar================================================
31113bd6fb4SVedant Kumar
31213bd6fb4SVedant Kumarllvm optimizations (such as inlining or CFG simplification) should have no
31313bd6fb4SVedant Kumarimpact on coverage report quality. This is due to the fact that the mapping
31413bd6fb4SVedant Kumarfrom source regions to profile counters is immutable, and is generated before
31513bd6fb4SVedant Kumarthe llvm optimizer kicks in. The optimizer can't prove that profile counter
31613bd6fb4SVedant Kumarinstrumentation is safe to delete (because it's not: it affects the profile the
31713bd6fb4SVedant Kumarprogram emits), and so leaves it alone.
31813bd6fb4SVedant Kumar
31913bd6fb4SVedant KumarNote that this coverage feature does not rely on information that can degrade
32013bd6fb4SVedant Kumarduring the course of optimization, such as debug info line tables.
32113bd6fb4SVedant Kumar
322b06294daSVedant KumarUsing the profiling runtime without static initializers
323b06294daSVedant Kumar=======================================================
324b06294daSVedant Kumar
325b06294daSVedant KumarBy default the compiler runtime uses a static initializer to determine the
326b06294daSVedant Kumarprofile output path and to register a writer function. To collect profiles
327b06294daSVedant Kumarwithout using static initializers, do this manually:
328b06294daSVedant Kumar
32932a9bfa4SVedant Kumar* Export a ``int __llvm_profile_runtime`` symbol from each instrumented shared
33032a9bfa4SVedant Kumar  library and executable. When the linker finds a definition of this symbol, it
33132a9bfa4SVedant Kumar  knows to skip loading the object which contains the profiling runtime's
33232a9bfa4SVedant Kumar  static initializer.
333b06294daSVedant Kumar
33432a9bfa4SVedant Kumar* Forward-declare ``void __llvm_profile_initialize_file(void)`` and call it
33532a9bfa4SVedant Kumar  once from each instrumented executable. This function parses
33632a9bfa4SVedant Kumar  ``LLVM_PROFILE_FILE``, sets the output path, and truncates any existing files
33732a9bfa4SVedant Kumar  at that path. To get the same behavior without truncating existing files,
33832a9bfa4SVedant Kumar  pass a filename pattern string to ``void __llvm_profile_set_filename(char
33932a9bfa4SVedant Kumar  *)``.  These calls can be placed anywhere so long as they precede all calls
34032a9bfa4SVedant Kumar  to ``__llvm_profile_write_file``.
341b06294daSVedant Kumar
34232a9bfa4SVedant Kumar* Forward-declare ``int __llvm_profile_write_file(void)`` and call it to write
34389262b69SVedant Kumar  out a profile. This function returns 0 when it succeeds, and a non-zero value
34489262b69SVedant Kumar  otherwise. Calling this function multiple times appends profile data to an
34589262b69SVedant Kumar  existing on-disk raw profile.
346b06294daSVedant Kumar
347b1706ca1SNico WeberIn C++ files, declare these as ``extern "C"``.
348b1706ca1SNico Weber
349*d4ee603cSDuncan P. N. Exon SmithUsing the profiling runtime without a filesystem
350*d4ee603cSDuncan P. N. Exon Smith------------------------------------------------
351*d4ee603cSDuncan P. N. Exon Smith
352*d4ee603cSDuncan P. N. Exon SmithThe profiling runtime also supports freestanding environments that lack a
353*d4ee603cSDuncan P. N. Exon Smithfilesystem. The runtime ships as a static archive that's structured to make
354*d4ee603cSDuncan P. N. Exon Smithdependencies on a hosted environment optional, depending on what features
355*d4ee603cSDuncan P. N. Exon Smiththe client application uses.
356*d4ee603cSDuncan P. N. Exon Smith
357*d4ee603cSDuncan P. N. Exon SmithThe first step is to export ``__llvm_profile_runtime``, as above, to disable
358*d4ee603cSDuncan P. N. Exon Smiththe default static initializers. Instead of calling the ``*_file()`` APIs
359*d4ee603cSDuncan P. N. Exon Smithdescribed above, use the following to save the profile directly to a buffer
360*d4ee603cSDuncan P. N. Exon Smithunder your control:
361*d4ee603cSDuncan P. N. Exon Smith
362*d4ee603cSDuncan P. N. Exon Smith* Forward-declare ``uint64_t __llvm_profile_get_size_for_buffer(void)`` and
363*d4ee603cSDuncan P. N. Exon Smith  call it to determine the size of the profile. You'll need to allocate a
364*d4ee603cSDuncan P. N. Exon Smith  buffer of this size.
365*d4ee603cSDuncan P. N. Exon Smith
366*d4ee603cSDuncan P. N. Exon Smith* Forward-declare ``int __llvm_profile_write_buffer(char *Buffer)`` and call it
367*d4ee603cSDuncan P. N. Exon Smith  to copy the current counters to ``Buffer``, which is expected to already be
368*d4ee603cSDuncan P. N. Exon Smith  allocated and big enough for the profile.
369*d4ee603cSDuncan P. N. Exon Smith
370*d4ee603cSDuncan P. N. Exon Smith* Optionally, forward-declare ``void __llvm_profile_reset_counters(void)`` and
371*d4ee603cSDuncan P. N. Exon Smith  call it to reset the counters before entering a specific section to be
372*d4ee603cSDuncan P. N. Exon Smith  profiled. This is only useful if there is some setup that should be excluded
373*d4ee603cSDuncan P. N. Exon Smith  from the profile.
374*d4ee603cSDuncan P. N. Exon Smith
375*d4ee603cSDuncan P. N. Exon SmithIn C++ files, declare these as ``extern "C"``.
376*d4ee603cSDuncan P. N. Exon Smith
3776fe6eae7SVedant KumarCollecting coverage reports for the llvm project
3786fe6eae7SVedant Kumar================================================
3796fe6eae7SVedant Kumar
3806fe6eae7SVedant KumarTo prepare a coverage report for llvm (and any of its sub-projects), add
3816fe6eae7SVedant Kumar``-DLLVM_BUILD_INSTRUMENTED_COVERAGE=On`` to the cmake configuration. Raw
3826fe6eae7SVedant Kumarprofiles will be written to ``$BUILD_DIR/profiles/``. To prepare an html
3836fe6eae7SVedant Kumarreport, run ``llvm/utils/prepare-code-coverage-artifact.py``.
3846fe6eae7SVedant Kumar
3856fe6eae7SVedant KumarTo specify an alternate directory for raw profiles, use
3866fe6eae7SVedant Kumar``-DLLVM_PROFILE_DATA_DIR``. To change the size of the profile merge pool, use
3876fe6eae7SVedant Kumar``-DLLVM_PROFILE_MERGE_POOL_SIZE``.
3886fe6eae7SVedant Kumar
389553a0d62SVedant KumarDrawbacks and limitations
390553a0d62SVedant Kumar=========================
391553a0d62SVedant Kumar
39282cd7709SVedant Kumar* Prior to version 2.26, the GNU binutils BFD linker is not able link programs
3931c5f312cSVedant Kumar  compiled with ``-fcoverage-mapping`` in its ``--gc-sections`` mode.  Possible
3941c5f312cSVedant Kumar  workarounds include disabling ``--gc-sections``, upgrading to a newer version
3951c5f312cSVedant Kumar  of BFD, or using the Gold linker.
39682cd7709SVedant Kumar
39762baa4c7SVedant Kumar* Code coverage does not handle unpredictable changes in control flow or stack
39862baa4c7SVedant Kumar  unwinding in the presence of exceptions precisely. Consider the following
39962baa4c7SVedant Kumar  function:
400553a0d62SVedant Kumar
401553a0d62SVedant Kumar  .. code-block:: cpp
402553a0d62SVedant Kumar
403553a0d62SVedant Kumar      int f() {
404553a0d62SVedant Kumar        may_throw();
405553a0d62SVedant Kumar        return 0;
406553a0d62SVedant Kumar      }
407553a0d62SVedant Kumar
40862baa4c7SVedant Kumar  If the call to ``may_throw()`` propagates an exception into ``f``, the code
409553a0d62SVedant Kumar  coverage tool may mark the ``return`` statement as executed even though it is
41062baa4c7SVedant Kumar  not. A call to ``longjmp()`` can have similar effects.
411859bf4d2SVedant Kumar
412859bf4d2SVedant KumarClang implementation details
413859bf4d2SVedant Kumar============================
414859bf4d2SVedant Kumar
415859bf4d2SVedant KumarThis section may be of interest to those wishing to understand or improve
416859bf4d2SVedant Kumarthe clang code coverage implementation.
417859bf4d2SVedant Kumar
418859bf4d2SVedant KumarGap regions
419859bf4d2SVedant Kumar-----------
420859bf4d2SVedant Kumar
421859bf4d2SVedant KumarGap regions are source regions with counts. A reporting tool cannot set a line
422859bf4d2SVedant Kumarexecution count to the count from a gap region unless that region is the only
423859bf4d2SVedant Kumarone on a line.
424859bf4d2SVedant Kumar
425859bf4d2SVedant KumarGap regions are used to eliminate unnatural artifacts in coverage reports, such
426859bf4d2SVedant Kumaras red "unexecuted" highlights present at the end of an otherwise covered line,
427859bf4d2SVedant Kumaror blue "executed" highlights present at the start of a line that is otherwise
428859bf4d2SVedant Kumarnot executed.
429859bf4d2SVedant Kumar
4309f2967bcSAlan PhippsBranch regions
4319f2967bcSAlan Phipps--------------
4329f2967bcSAlan PhippsWhen viewing branch coverage details in source-based file-level sub-views using
4339f2967bcSAlan Phipps``--show-branches``, it is recommended that users show all macro expansions
4349f2967bcSAlan Phipps(using option ``--show-expansions``) since macros may contain hidden branch
4359f2967bcSAlan Phippsconditions.  The coverage summary report will always include these macro-based
4369f2967bcSAlan Phippsboolean expressions in the overall branch coverage count for a function or
4379f2967bcSAlan Phippssource file.
4389f2967bcSAlan Phipps
4399f2967bcSAlan PhippsBranch coverage is not tracked for constant folded branch conditions since
4409f2967bcSAlan Phippsbranches are not generated for these cases.  In the source-based file-level
4419f2967bcSAlan Phippssub-view, these branches will simply be shown as ``[Folded - Ignored]`` so that
4429f2967bcSAlan Phippsusers are informed about what happened.
4439f2967bcSAlan Phipps
4449f2967bcSAlan PhippsBranch coverage is tied directly to branch-generating conditions in the source
4459f2967bcSAlan Phippscode.  Users should not see hidden branches that aren't actually tied to the
4469f2967bcSAlan Phippssource code.
4479f2967bcSAlan Phipps
4489f2967bcSAlan Phipps
449859bf4d2SVedant KumarSwitch statements
450859bf4d2SVedant Kumar-----------------
451859bf4d2SVedant Kumar
452859bf4d2SVedant KumarThe region mapping for a switch body consists of a gap region that covers the
453859bf4d2SVedant Kumarentire body (starting from the '{' in 'switch (...) {', and terminating where the
454859bf4d2SVedant Kumarlast case ends). This gap region has a zero count: this causes "gap" areas in
455859bf4d2SVedant Kumarbetween case statements, which contain no executable code, to appear uncovered.
456859bf4d2SVedant Kumar
457859bf4d2SVedant KumarWhen a switch case is visited, the parent region is extended: if the parent
458859bf4d2SVedant Kumarregion has no start location, its start location becomes the start of the case.
459859bf4d2SVedant KumarThis is used to support switch statements without a ``CompoundStmt`` body, in
460859bf4d2SVedant Kumarwhich the switch body and the single case share a count.
461859bf4d2SVedant Kumar
462859bf4d2SVedant KumarFor switches with ``CompoundStmt`` bodies, a new region is created at the start
463859bf4d2SVedant Kumarof each switch case.
4649f2967bcSAlan Phipps
4659f2967bcSAlan PhippsBranch regions are also generated for each switch case, including the default
4669f2967bcSAlan Phippscase. If there is no explicitly defined default case in the source code, a
4679f2967bcSAlan Phippsbranch region is generated to correspond to the implicit default case that is
4689f2967bcSAlan Phippsgenerated by the compiler.  The implicit branch region is tied to the line and
4699f2967bcSAlan Phippscolumn number of the switch statement condition since no source code for the
4709f2967bcSAlan Phippsimplicit case exists.
471