Skip to main content

rustc_codegen_llvm/coverageinfo/
mapgen.rs

1use std::assert_matches;
2
3use itertools::Itertools;
4use rustc_abi::Align;
5use rustc_codegen_ssa::traits::{BaseTypeCodegenMethods, ConstCodegenMethods};
6use rustc_data_structures::fx::FxIndexMap;
7use rustc_middle::ty::TyCtxt;
8use rustc_span::{FileName, RemapPathScopeComponents, SourceFile, StableSourceFileId};
9use tracing::debug;
10
11use crate::common::CodegenCx;
12use crate::coverageinfo::llvm_cov;
13use crate::coverageinfo::mapgen::covfun::prepare_covfun_record;
14use crate::{TryFromU32, llvm};
15
16mod covfun;
17mod spans;
18mod unused;
19
20/// Version number that will be included the `__llvm_covmap` section header.
21/// Corresponds to LLVM's `llvm::coverage::CovMapVersion` (in `CoverageMapping.h`),
22/// or at least the subset that we know and care about.
23///
24/// Note that version `n` is encoded as `(n-1)`.
25#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for CovmapVersion { }
#[automatically_derived]
impl ::core::clone::Clone for CovmapVersion {
    #[inline]
    fn clone(&self) -> CovmapVersion { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for CovmapVersion { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for CovmapVersion {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "Version7")
    }
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for CovmapVersion { }
#[automatically_derived]
impl ::core::cmp::PartialEq for CovmapVersion {
    #[inline]
    fn eq(&self, other: &CovmapVersion) -> bool { true }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for CovmapVersion {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for CovmapVersion {
    #[inline]
    fn partial_cmp(&self, other: &CovmapVersion)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ordering::Equal)
    }
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for CovmapVersion {
    #[inline]
    fn cmp(&self, other: &CovmapVersion) -> ::core::cmp::Ordering {
        ::core::cmp::Ordering::Equal
    }
}Ord, impl ::core::convert::TryFrom<u32> for CovmapVersion {
    type Error = u32;
    #[allow(deprecated)]
    fn try_from(value: u32)
        -> ::core::result::Result<CovmapVersion, Self::Error> {
        if value == const { CovmapVersion::Version7 as u32 } {
            return Ok(CovmapVersion::Version7)
        }
        Err(value)
    }
}TryFromU32)]
26enum CovmapVersion {
27    /// Used by LLVM 18 onwards.
28    Version7 = 6,
29}
30
31impl CovmapVersion {
32    fn to_u32(self) -> u32 {
33        self as u32
34    }
35}
36
37/// Generates and exports the coverage map, which is embedded in special
38/// linker sections in the final binary.
39///
40/// Those sections are then read and understood by LLVM's `llvm-cov` tool,
41/// which is distributed in the `llvm-tools` rustup component.
42pub(crate) fn finalize(cx: &mut CodegenCx<'_, '_>) {
43    let tcx = cx.tcx;
44
45    // Ensure that LLVM is using a version of the coverage mapping format that
46    // agrees with our Rust-side code. Expected versions are:
47    // - `Version7` (6) used by LLVM 18 onwards.
48    let covmap_version =
49        CovmapVersion::try_from(llvm_cov::mapping_version()).unwrap_or_else(|raw_version: u32| {
50            {
    ::core::panicking::panic_fmt(format_args!("unknown coverage mapping version reported by `llvm-wrapper`: {0}",
            raw_version));
}panic!("unknown coverage mapping version reported by `llvm-wrapper`: {raw_version}")
51        });
52    {
    match covmap_version {
        CovmapVersion::Version7 => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "CovmapVersion::Version7", ::core::option::Option::None);
        }
    }
};assert_matches!(covmap_version, CovmapVersion::Version7);
53
54    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs:54",
                        "rustc_codegen_llvm::coverageinfo::mapgen",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs"),
                        ::tracing_core::__macro_support::Option::Some(54u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::coverageinfo::mapgen"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Generating coverage map for CodegenUnit: `{0}`",
                                                    cx.codegen_unit.name()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("Generating coverage map for CodegenUnit: `{}`", cx.codegen_unit.name());
55
56    // FIXME(#132395): Can this be none even when coverage is enabled?
57    let Some(ref coverage_cx) = cx.coverage_cx else { return };
58
59    let mut covfun_records = coverage_cx
60        .instances_used()
61        .into_iter()
62        // Sort by symbol name, so that the global file table is built in an
63        // order that doesn't depend on the stable-hash-based order in which
64        // instances were visited during codegen.
65        .sorted_by_cached_key(|&instance| tcx.symbol_name(instance).name)
66        .filter_map(|instance| prepare_covfun_record(tcx, instance, true))
67        .collect::<Vec<_>>();
68
69    // In a single designated CGU, also prepare covfun records for functions
70    // in this crate that were instrumented for coverage, but are unused.
71    if cx.codegen_unit.is_code_coverage_dead_code_cgu() {
72        unused::prepare_covfun_records_for_unused_functions(cx, &mut covfun_records);
73    }
74
75    // If there are no covfun records for this CGU, don't emit a covmap record.
76    // Emitting a covmap record without any covfun records causes `llvm-cov` to
77    // fail when generating coverage reports, and if there are no covfun records
78    // then the covmap record isn't useful anyway.
79    // This should prevent a repeat of <https://github.com/rust-lang/rust/issues/133606>.
80    if covfun_records.is_empty() {
81        return;
82    }
83
84    // Prepare the global file table for this CGU, containing all paths needed
85    // by one or more covfun records.
86    let global_file_table =
87        GlobalFileTable::build(tcx, covfun_records.iter().flat_map(|c| c.all_source_files()));
88
89    for covfun in &covfun_records {
90        covfun::emit_covfun_record(cx, &global_file_table, covfun);
91    }
92
93    // Emit the coverage map header, which contains the filenames used by
94    // this CGU's coverage mappings, and store it in a well-known global.
95    // (This is skipped if we returned early due to having no covfun records.)
96    emit_covmap_record(cx, covmap_version, &global_file_table.filenames_buffer);
97}
98
99/// Maps "global" (per-CGU) file ID numbers to their underlying source file paths.
100#[derive(#[automatically_derived]
impl ::core::fmt::Debug for GlobalFileTable {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "GlobalFileTable", "raw_file_table", &self.raw_file_table,
            "filenames_buffer", &self.filenames_buffer, "filenames_hash",
            &&self.filenames_hash)
    }
}Debug)]
101struct GlobalFileTable {
102    /// This "raw" table doesn't include the working dir, so a file's
103    /// global ID is its index in this set **plus one**.
104    raw_file_table: FxIndexMap<StableSourceFileId, String>,
105
106    /// The file table in encoded form (possibly compressed), which can be
107    /// included directly in this CGU's `__llvm_covmap` record.
108    filenames_buffer: Vec<u8>,
109
110    /// Truncated hash of the bytes in `filenames_buffer`.
111    ///
112    /// The `llvm-cov` tool uses this hash to associate each covfun record with
113    /// its corresponding filenames table, since the final binary will typically
114    /// contain multiple covmap records from different compilation units.
115    filenames_hash: u64,
116}
117
118impl GlobalFileTable {
119    /// Builds a "global file table" for this CGU, mapping numeric IDs to
120    /// path strings.
121    fn build<'a>(tcx: TyCtxt<'_>, all_files: impl Iterator<Item = &'a SourceFile>) -> Self {
122        let mut raw_file_table = FxIndexMap::default();
123
124        for file in all_files {
125            raw_file_table.entry(file.stable_id).or_insert_with(|| {
126                // Prefer using the embeddable filename as this filename is going to
127                // end-up in the coverage artifacts (see rust-lang/rust#150020).
128                if let FileName::Real(real) = &file.name {
129                    let (_work_dir, abs_name) =
130                        real.embeddable_name(RemapPathScopeComponents::COVERAGE);
131
132                    abs_name.to_string_lossy().into_owned()
133                } else {
134                    file.name
135                        .display(RemapPathScopeComponents::COVERAGE)
136                        .to_string_lossy()
137                        .into_owned()
138                }
139            });
140        }
141
142        // FIXME(Zalathar): Consider sorting the file table here, but maybe
143        // only after adding filename support to coverage-dump, so that the
144        // table order isn't directly visible in `.coverage-map` snapshots.
145
146        let mut table = Vec::with_capacity(raw_file_table.len() + 1);
147
148        // Since version 6 of the LLVM coverage mapping format, the first entry
149        // in the global file table is treated as a base directory, used to
150        // resolve any other entries that are stored as relative paths.
151        let base_dir = tcx
152            .sess
153            .psess
154            .source_map()
155            .working_dir()
156            .path(RemapPathScopeComponents::COVERAGE)
157            .to_string_lossy();
158        table.push(base_dir.as_ref());
159
160        // Add the regular entries after the base directory.
161        table.extend(raw_file_table.values().map(|name| name.as_str()));
162
163        // Encode the file table into a buffer, and get the hash of its encoded
164        // bytes, so that we can embed that hash in `__llvm_covfun` records.
165        let filenames_buffer = llvm_cov::write_filenames_to_buffer(&table);
166        let filenames_hash = llvm_cov::hash_bytes(&filenames_buffer);
167
168        Self { raw_file_table, filenames_buffer, filenames_hash }
169    }
170
171    fn get_existing_id(&self, file: &SourceFile) -> Option<GlobalFileId> {
172        let raw_id = self.raw_file_table.get_index_of(&file.stable_id)?;
173        // The raw file table doesn't include an entry for the base dir
174        // (which has ID 0), so add 1 to get the correct ID.
175        Some(GlobalFileId::from_usize(raw_id + 1))
176    }
177}
178
179#[automatically_derived]
impl ::core::marker::Copy for GlobalFileId { }
impl GlobalFileId {
    #[doc = r" Maximum value the index can take, as a `u32`."]
    const MAX_AS_U32: u32 = 0xFFFF_FF00;
    #[doc = r" Maximum value the index can take."]
    const MAX: Self = Self::from_u32(0xFFFF_FF00);
    #[doc = r" Zero value of the index."]
    const ZERO: Self = Self::from_u32(0);
    #[doc = r" Creates a new index from a given `usize`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    const fn from_usize(value: usize) -> Self {
        if !(value <= (0xFFFF_FF00 as usize)) {
            ::core::panicking::panic("assertion failed: value <= (0xFFFF_FF00 as usize)")
        };
        unsafe { Self::from_u32_unchecked(value as u32) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    const fn from_u32(value: u32) -> Self {
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u16`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    const fn from_u16(value: u16) -> Self {
        let value = value as u32;
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc =
    r" The provided value must be less than or equal to the maximum value for the newtype."]
    #[doc =
    r" Providing a value outside this range is undefined due to layout restrictions."]
    #[doc = r""]
    #[doc = r" Prefer using `from_u32`."]
    #[inline]
    const unsafe fn from_u32_unchecked(value: u32) -> Self {
        Self {
            private_use_as_methods_instead: unsafe {
                std::mem::transmute(value)
            },
        }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    const fn index(self) -> usize { self.as_usize() }
    #[doc = r" Extracts the value of this index as a `u32`."]
    #[inline]
    const fn as_u32(self) -> u32 {
        unsafe { std::mem::transmute(self.private_use_as_methods_instead) }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    const fn as_usize(self) -> usize { self.as_u32() as usize }
}
impl std::ops::Add<usize> for GlobalFileId {
    type Output = Self;
    #[inline]
    fn add(self, other: usize) -> Self {
        Self::from_usize(self.index() + other)
    }
}
impl std::ops::AddAssign<usize> for GlobalFileId {
    #[inline]
    fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for GlobalFileId {
    #[inline]
    fn new(value: usize) -> Self { Self::from_usize(value) }
    #[inline]
    fn index(self) -> usize { self.as_usize() }
}
impl From<GlobalFileId> for u32 {
    #[inline]
    fn from(v: GlobalFileId) -> u32 { v.as_u32() }
}
impl From<GlobalFileId> for usize {
    #[inline]
    fn from(v: GlobalFileId) -> usize { v.as_usize() }
}
impl From<usize> for GlobalFileId {
    #[inline]
    fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for GlobalFileId {
    #[inline]
    fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for GlobalFileId {}
impl ::std::cmp::PartialEq for GlobalFileId {
    fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for GlobalFileId {}
impl ::std::hash::Hash for GlobalFileId {
    fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
        self.as_u32().hash(state)
    }
}
impl ::std::fmt::Debug for GlobalFileId {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        fmt.write_fmt(format_args!("{0}", self.as_u32()))
    }
}rustc_index::newtype_index! {
180    /// An index into the CGU's overall list of file paths. The underlying paths
181    /// will be embedded in the `__llvm_covmap` linker section.
182    struct GlobalFileId {}
183}
184#[automatically_derived]
impl ::core::marker::Copy for LocalFileId { }
impl LocalFileId {
    #[doc = r" Maximum value the index can take, as a `u32`."]
    const MAX_AS_U32: u32 = 0xFFFF_FF00;
    #[doc = r" Maximum value the index can take."]
    const MAX: Self = Self::from_u32(0xFFFF_FF00);
    #[doc = r" Zero value of the index."]
    const ZERO: Self = Self::from_u32(0);
    #[doc = r" Creates a new index from a given `usize`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    const fn from_usize(value: usize) -> Self {
        if !(value <= (0xFFFF_FF00 as usize)) {
            ::core::panicking::panic("assertion failed: value <= (0xFFFF_FF00 as usize)")
        };
        unsafe { Self::from_u32_unchecked(value as u32) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    const fn from_u32(value: u32) -> Self {
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u16`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    const fn from_u16(value: u16) -> Self {
        let value = value as u32;
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc =
    r" The provided value must be less than or equal to the maximum value for the newtype."]
    #[doc =
    r" Providing a value outside this range is undefined due to layout restrictions."]
    #[doc = r""]
    #[doc = r" Prefer using `from_u32`."]
    #[inline]
    const unsafe fn from_u32_unchecked(value: u32) -> Self {
        Self {
            private_use_as_methods_instead: unsafe {
                std::mem::transmute(value)
            },
        }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    const fn index(self) -> usize { self.as_usize() }
    #[doc = r" Extracts the value of this index as a `u32`."]
    #[inline]
    const fn as_u32(self) -> u32 {
        unsafe { std::mem::transmute(self.private_use_as_methods_instead) }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    const fn as_usize(self) -> usize { self.as_u32() as usize }
}
impl std::ops::Add<usize> for LocalFileId {
    type Output = Self;
    #[inline]
    fn add(self, other: usize) -> Self {
        Self::from_usize(self.index() + other)
    }
}
impl std::ops::AddAssign<usize> for LocalFileId {
    #[inline]
    fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for LocalFileId {
    #[inline]
    fn new(value: usize) -> Self { Self::from_usize(value) }
    #[inline]
    fn index(self) -> usize { self.as_usize() }
}
impl From<LocalFileId> for u32 {
    #[inline]
    fn from(v: LocalFileId) -> u32 { v.as_u32() }
}
impl From<LocalFileId> for usize {
    #[inline]
    fn from(v: LocalFileId) -> usize { v.as_usize() }
}
impl From<usize> for LocalFileId {
    #[inline]
    fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for LocalFileId {
    #[inline]
    fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for LocalFileId {}
impl ::std::cmp::PartialEq for LocalFileId {
    fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for LocalFileId {}
impl ::std::hash::Hash for LocalFileId {
    fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
        self.as_u32().hash(state)
    }
}
impl ::std::fmt::Debug for LocalFileId {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        fmt.write_fmt(format_args!("{0}", self.as_u32()))
    }
}rustc_index::newtype_index! {
185    /// An index into a function's list of global file IDs. That underlying list
186    /// of local-to-global mappings will be embedded in the function's record in
187    /// the `__llvm_covfun` linker section.
188    struct LocalFileId {}
189}
190
191/// Generates and emits the covmap record for this CGU, which mostly
192/// consists of a header and a list of filenames. The record is emitted
193/// as a global variable in the `__llvm_covmap` section.
194fn emit_covmap_record<'ll>(
195    cx: &mut CodegenCx<'ll, '_>,
196    version: CovmapVersion,
197    filenames_buffer: &[u8],
198) {
199    // A covmap record consists of four target-endian u32 values, followed by
200    // the encoded filenames table. Two of the header fields are unused in
201    // modern versions of the LLVM coverage mapping format, and are always 0.
202    // <https://llvm.org/docs/CoverageMappingFormat.html#llvm-ir-representation>
203    // See also `src/llvm-project/clang/lib/CodeGen/CoverageMappingGen.cpp`.
204    let covmap_header = cx.const_struct(
205        &[
206            cx.const_u32(0), // (unused)
207            cx.const_u32(filenames_buffer.len() as u32),
208            cx.const_u32(0), // (unused)
209            cx.const_u32(version.to_u32()),
210        ],
211        /* packed */ false,
212    );
213    let covmap_record = cx
214        .const_struct(&[covmap_header, cx.const_bytes(filenames_buffer)], /* packed */ false);
215
216    let covmap_global =
217        llvm::add_global(cx.llmod, cx.val_ty(covmap_record), &llvm_cov::covmap_var_name());
218    llvm::set_initializer(covmap_global, covmap_record);
219    llvm::set_global_constant(covmap_global, true);
220    llvm::set_linkage(covmap_global, llvm::Linkage::PrivateLinkage);
221    llvm::set_section(covmap_global, &llvm_cov::covmap_section_name(cx.llmod));
222    // LLVM's coverage mapping format specifies 8-byte alignment for items in this section.
223    // <https://llvm.org/docs/CoverageMappingFormat.html>
224    llvm::set_alignment(covmap_global, Align::EIGHT);
225
226    cx.add_used_global(covmap_global);
227}