rustc_codegen_llvm/coverageinfo/
mapgen.rs

1use std::sync::Arc;
2
3use itertools::Itertools;
4use rustc_abi::Align;
5use rustc_codegen_ssa::traits::{
6    BaseTypeCodegenMethods, ConstCodegenMethods, StaticCodegenMethods,
7};
8use rustc_data_structures::fx::FxIndexMap;
9use rustc_index::IndexVec;
10use rustc_middle::ty::TyCtxt;
11use rustc_session::RemapFileNameExt;
12use rustc_session::config::RemapPathScopeComponents;
13use rustc_span::{SourceFile, StableSourceFileId};
14use tracing::debug;
15
16use crate::common::CodegenCx;
17use crate::coverageinfo::llvm_cov;
18use crate::coverageinfo::mapgen::covfun::prepare_covfun_record;
19use crate::llvm;
20
21mod covfun;
22mod spans;
23mod unused;
24
25/// Generates and exports the coverage map, which is embedded in special
26/// linker sections in the final binary.
27///
28/// Those sections are then read and understood by LLVM's `llvm-cov` tool,
29/// which is distributed in the `llvm-tools` rustup component.
30pub(crate) fn finalize(cx: &CodegenCx<'_, '_>) {
31    let tcx = cx.tcx;
32
33    // Ensure that LLVM is using a version of the coverage mapping format that
34    // agrees with our Rust-side code. Expected versions (encoded as n-1) are:
35    // - `CovMapVersion::Version7` (6) used by LLVM 18-19
36    let covmap_version = {
37        let llvm_covmap_version = llvm_cov::mapping_version();
38        let expected_versions = 6..=6;
39        assert!(
40            expected_versions.contains(&llvm_covmap_version),
41            "Coverage mapping version exposed by `llvm-wrapper` is out of sync; \
42            expected {expected_versions:?} but was {llvm_covmap_version}"
43        );
44        // This is the version number that we will embed in the covmap section:
45        llvm_covmap_version
46    };
47
48    debug!("Generating coverage map for CodegenUnit: `{}`", cx.codegen_unit.name());
49
50    // FIXME(#132395): Can this be none even when coverage is enabled?
51    let instances_used = match cx.coverage_cx {
52        Some(ref cx) => cx.instances_used.borrow(),
53        None => return,
54    };
55
56    let mut covfun_records = instances_used
57        .iter()
58        .copied()
59        // Sort by symbol name, so that the global file table is built in an
60        // order that doesn't depend on the stable-hash-based order in which
61        // instances were visited during codegen.
62        .sorted_by_cached_key(|&instance| tcx.symbol_name(instance).name)
63        .filter_map(|instance| prepare_covfun_record(tcx, instance, true))
64        .collect::<Vec<_>>();
65
66    // In a single designated CGU, also prepare covfun records for functions
67    // in this crate that were instrumented for coverage, but are unused.
68    if cx.codegen_unit.is_code_coverage_dead_code_cgu() {
69        unused::prepare_covfun_records_for_unused_functions(cx, &mut covfun_records);
70    }
71
72    // If there are no covfun records for this CGU, don't generate a covmap record.
73    // Emitting a covmap record without any covfun records causes `llvm-cov` to
74    // fail when generating coverage reports, and if there are no covfun records
75    // then the covmap record isn't useful anyway.
76    // This should prevent a repeat of <https://github.com/rust-lang/rust/issues/133606>.
77    if covfun_records.is_empty() {
78        return;
79    }
80
81    // Prepare the global file table for this CGU, containing all paths needed
82    // by one or more covfun records.
83    let global_file_table =
84        GlobalFileTable::build(tcx, covfun_records.iter().flat_map(|c| c.all_source_files()));
85
86    for covfun in &covfun_records {
87        covfun::generate_covfun_record(cx, &global_file_table, covfun)
88    }
89
90    // Generate the coverage map header, which contains the filenames used by
91    // this CGU's coverage mappings, and store it in a well-known global.
92    // (This is skipped if we returned early due to having no covfun records.)
93    generate_covmap_record(cx, covmap_version, &global_file_table.filenames_buffer);
94}
95
96/// Maps "global" (per-CGU) file ID numbers to their underlying source file paths.
97#[derive(Debug)]
98struct GlobalFileTable {
99    /// This "raw" table doesn't include the working dir, so a file's
100    /// global ID is its index in this set **plus one**.
101    raw_file_table: FxIndexMap<StableSourceFileId, String>,
102
103    /// The file table in encoded form (possibly compressed), which can be
104    /// included directly in this CGU's `__llvm_covmap` record.
105    filenames_buffer: Vec<u8>,
106
107    /// Truncated hash of the bytes in `filenames_buffer`.
108    ///
109    /// The `llvm-cov` tool uses this hash to associate each covfun record with
110    /// its corresponding filenames table, since the final binary will typically
111    /// contain multiple covmap records from different compilation units.
112    filenames_hash: u64,
113}
114
115impl GlobalFileTable {
116    /// Builds a "global file table" for this CGU, mapping numeric IDs to
117    /// path strings.
118    fn build<'a>(tcx: TyCtxt<'_>, all_files: impl Iterator<Item = &'a SourceFile>) -> Self {
119        let mut raw_file_table = FxIndexMap::default();
120
121        for file in all_files {
122            raw_file_table.entry(file.stable_id).or_insert_with(|| {
123                file.name
124                    .for_scope(tcx.sess, RemapPathScopeComponents::MACRO)
125                    .to_string_lossy()
126                    .into_owned()
127            });
128        }
129
130        // FIXME(Zalathar): Consider sorting the file table here, but maybe
131        // only after adding filename support to coverage-dump, so that the
132        // table order isn't directly visible in `.coverage-map` snapshots.
133
134        let mut table = Vec::with_capacity(raw_file_table.len() + 1);
135
136        // Since version 6 of the LLVM coverage mapping format, the first entry
137        // in the global file table is treated as a base directory, used to
138        // resolve any other entries that are stored as relative paths.
139        let base_dir = tcx
140            .sess
141            .opts
142            .working_dir
143            .for_scope(tcx.sess, RemapPathScopeComponents::MACRO)
144            .to_string_lossy();
145        table.push(base_dir.as_ref());
146
147        // Add the regular entries after the base directory.
148        table.extend(raw_file_table.values().map(|name| name.as_str()));
149
150        // Encode the file table into a buffer, and get the hash of its encoded
151        // bytes, so that we can embed that hash in `__llvm_covfun` records.
152        let filenames_buffer = llvm_cov::write_filenames_to_buffer(&table);
153        let filenames_hash = llvm_cov::hash_bytes(&filenames_buffer);
154
155        Self { raw_file_table, filenames_buffer, filenames_hash }
156    }
157
158    fn get_existing_id(&self, file: &SourceFile) -> Option<GlobalFileId> {
159        let raw_id = self.raw_file_table.get_index_of(&file.stable_id)?;
160        // The raw file table doesn't include an entry for the base dir
161        // (which has ID 0), so add 1 to get the correct ID.
162        Some(GlobalFileId::from_usize(raw_id + 1))
163    }
164}
165
166rustc_index::newtype_index! {
167    /// An index into the CGU's overall list of file paths. The underlying paths
168    /// will be embedded in the `__llvm_covmap` linker section.
169    struct GlobalFileId {}
170}
171rustc_index::newtype_index! {
172    /// An index into a function's list of global file IDs. That underlying list
173    /// of local-to-global mappings will be embedded in the function's record in
174    /// the `__llvm_covfun` linker section.
175    struct LocalFileId {}
176}
177
178/// Holds a mapping from "local" (per-function) file IDs to their corresponding
179/// source files.
180#[derive(Debug, Default)]
181struct VirtualFileMapping {
182    local_file_table: IndexVec<LocalFileId, Arc<SourceFile>>,
183}
184
185impl VirtualFileMapping {
186    fn push_file(&mut self, source_file: &Arc<SourceFile>) -> LocalFileId {
187        self.local_file_table.push(Arc::clone(source_file))
188    }
189
190    /// Resolves all of the filenames in this local file mapping to a list of
191    /// global file IDs in its CGU, for inclusion in this function's
192    /// `__llvm_covfun` record.
193    ///
194    /// The global file IDs are returned as `u32` to make FFI easier.
195    fn resolve_all(&self, global_file_table: &GlobalFileTable) -> Option<Vec<u32>> {
196        self.local_file_table
197            .iter()
198            .map(|file| try {
199                let id = global_file_table.get_existing_id(file)?;
200                GlobalFileId::as_u32(id)
201            })
202            .collect::<Option<Vec<_>>>()
203    }
204}
205
206/// Generates the contents of the covmap record for this CGU, which mostly
207/// consists of a header and a list of filenames. The record is then stored
208/// as a global variable in the `__llvm_covmap` section.
209fn generate_covmap_record<'ll>(cx: &CodegenCx<'ll, '_>, version: u32, filenames_buffer: &[u8]) {
210    // A covmap record consists of four target-endian u32 values, followed by
211    // the encoded filenames table. Two of the header fields are unused in
212    // modern versions of the LLVM coverage mapping format, and are always 0.
213    // <https://llvm.org/docs/CoverageMappingFormat.html#llvm-ir-representation>
214    // See also `src/llvm-project/clang/lib/CodeGen/CoverageMappingGen.cpp`.
215    let covmap_header = cx.const_struct(
216        &[
217            cx.const_u32(0), // (unused)
218            cx.const_u32(filenames_buffer.len() as u32),
219            cx.const_u32(0), // (unused)
220            cx.const_u32(version),
221        ],
222        /* packed */ false,
223    );
224    let covmap_record = cx
225        .const_struct(&[covmap_header, cx.const_bytes(filenames_buffer)], /* packed */ false);
226
227    let covmap_global =
228        llvm::add_global(cx.llmod, cx.val_ty(covmap_record), &llvm_cov::covmap_var_name());
229    llvm::set_initializer(covmap_global, covmap_record);
230    llvm::set_global_constant(covmap_global, true);
231    llvm::set_linkage(covmap_global, llvm::Linkage::PrivateLinkage);
232    llvm::set_section(covmap_global, &llvm_cov::covmap_section_name(cx.llmod));
233    // LLVM's coverage mapping format specifies 8-byte alignment for items in this section.
234    // <https://llvm.org/docs/CoverageMappingFormat.html>
235    llvm::set_alignment(covmap_global, Align::EIGHT);
236
237    cx.add_used_global(covmap_global);
238}