2024-12-18 10:19:30 +00:00
|
|
|
use std::sync::Arc;
|
2024-10-18 10:43:37 +00:00
|
|
|
|
2024-12-13 11:40:45 +00:00
|
|
|
use itertools::Itertools;
|
2024-10-24 11:47:45 +00:00
|
|
|
use rustc_abi::Align;
|
|
|
|
use rustc_codegen_ssa::traits::{
|
|
|
|
BaseTypeCodegenMethods, ConstCodegenMethods, StaticCodegenMethods,
|
|
|
|
};
|
2025-03-21 04:07:05 +00:00
|
|
|
use rustc_data_structures::fx::FxIndexMap;
|
2023-09-03 05:52:49 +00:00
|
|
|
use rustc_index::IndexVec;
|
2025-03-21 04:07:05 +00:00
|
|
|
use rustc_middle::ty::TyCtxt;
|
2024-11-04 03:53:52 +00:00
|
|
|
use rustc_session::RemapFileNameExt;
|
|
|
|
use rustc_session::config::RemapPathScopeComponents;
|
2024-12-18 10:19:30 +00:00
|
|
|
use rustc_span::{SourceFile, StableSourceFileId};
|
2024-05-22 04:50:24 +00:00
|
|
|
use tracing::debug;
|
2020-07-02 18:27:15 +00:00
|
|
|
|
|
|
|
use crate::common::CodegenCx;
|
2024-12-11 03:28:55 +00:00
|
|
|
use crate::coverageinfo::llvm_cov;
|
2024-12-11 04:03:31 +00:00
|
|
|
use crate::coverageinfo::mapgen::covfun::prepare_covfun_record;
|
2024-11-01 09:32:20 +00:00
|
|
|
use crate::llvm;
|
2024-07-28 22:13:50 +00:00
|
|
|
|
2024-12-11 03:28:55 +00:00
|
|
|
mod covfun;
|
2024-12-18 10:00:51 +00:00
|
|
|
mod spans;
|
2025-03-21 04:07:05 +00:00
|
|
|
mod unused;
|
2024-12-11 03:28:55 +00:00
|
|
|
|
2024-10-11 10:44:36 +00:00
|
|
|
/// Generates and exports the coverage map, which is embedded in special
|
|
|
|
/// linker sections in the final binary.
|
2020-07-02 18:27:15 +00:00
|
|
|
///
|
2024-10-11 10:44:36 +00:00
|
|
|
/// Those sections are then read and understood by LLVM's `llvm-cov` tool,
|
|
|
|
/// which is distributed in the `llvm-tools` rustup component.
|
2024-07-06 12:26:42 +00:00
|
|
|
pub(crate) fn finalize(cx: &CodegenCx<'_, '_>) {
|
2020-12-01 07:58:08 +00:00
|
|
|
let tcx = cx.tcx;
|
coverage bug fixes and optimization support
Adjusted LLVM codegen for code compiled with `-Zinstrument-coverage` to
address multiple, somewhat related issues.
Fixed a significant flaw in prior coverage solution: Every counter
generated a new counter variable, but there should have only been one
counter variable per function. This appears to have bloated .profraw
files significantly. (For a small program, it increased the size by
about 40%. I have not tested large programs, but there is anecdotal
evidence that profraw files were way too large. This is a good fix,
regardless, but hopefully it also addresses related issues.
Fixes: #82144
Invalid LLVM coverage data produced when compiled with -C opt-level=1
Existing tests now work up to at least `opt-level=3`. This required a
detailed analysis of the LLVM IR, comparisons with Clang C++ LLVM IR
when compiled with coverage, and a lot of trial and error with codegen
adjustments.
The biggest hurdle was figuring out how to continue to support coverage
results for unused functions and generics. Rust's coverage results have
three advantages over Clang's coverage results:
1. Rust's coverage map does not include any overlapping code regions,
making coverage counting unambiguous.
2. Rust generates coverage results (showing zero counts) for all unused
functions, including generics. (Clang does not generate coverage for
uninstantiated template functions.)
3. Rust's unused functions produce minimal stubbed functions in LLVM IR,
sufficient for including in the coverage results; while Clang must
generate the complete LLVM IR for each unused function, even though
it will never be called.
This PR removes the previous hack of attempting to inject coverage into
some other existing function instance, and generates dedicated instances
for each unused function. This change, and a few other adjustments
(similar to what is required for `-C link-dead-code`, but with lower
impact), makes it possible to support LLVM optimizations.
Fixes: #79651
Coverage report: "Unexecuted instantiation:..." for a generic function
from multiple crates
Fixed by removing the aforementioned hack. Some "Unexecuted
instantiation" notices are unavoidable, as explained in the
`used_crate.rs` test, but `-Zinstrument-coverage` has new options to
back off support for either unused generics, or all unused functions,
which avoids the notice, at the cost of less coverage of unused
functions.
Fixes: #82875
Invalid LLVM coverage data produced with crate brotli_decompressor
Fixed by disabling the LLVM function attribute that forces inlining, if
`-Z instrument-coverage` is enabled. This attribute is applied to
Rust functions with `#[inline(always)], and in some cases, the forced
inlining breaks coverage instrumentation and reports.
2021-03-15 23:32:45 +00:00
|
|
|
|
2024-02-13 12:00:49 +00:00
|
|
|
// Ensure that LLVM is using a version of the coverage mapping format that
|
|
|
|
// agrees with our Rust-side code. Expected versions (encoded as n-1) are:
|
2024-10-11 10:44:36 +00:00
|
|
|
// - `CovMapVersion::Version7` (6) used by LLVM 18-19
|
2024-02-13 12:00:49 +00:00
|
|
|
let covmap_version = {
|
2024-11-01 09:32:20 +00:00
|
|
|
let llvm_covmap_version = llvm_cov::mapping_version();
|
2024-10-11 10:44:36 +00:00
|
|
|
let expected_versions = 6..=6;
|
2024-02-13 12:00:49 +00:00
|
|
|
assert!(
|
|
|
|
expected_versions.contains(&llvm_covmap_version),
|
|
|
|
"Coverage mapping version exposed by `llvm-wrapper` is out of sync; \
|
|
|
|
expected {expected_versions:?} but was {llvm_covmap_version}"
|
|
|
|
);
|
|
|
|
// This is the version number that we will embed in the covmap section:
|
|
|
|
llvm_covmap_version
|
|
|
|
};
|
2020-11-25 17:45:33 +00:00
|
|
|
|
2020-12-01 07:58:08 +00:00
|
|
|
debug!("Generating coverage map for CodegenUnit: `{}`", cx.codegen_unit.name());
|
|
|
|
|
2024-10-31 10:12:15 +00:00
|
|
|
// FIXME(#132395): Can this be none even when coverage is enabled?
|
2024-12-14 11:48:12 +00:00
|
|
|
let instances_used = match cx.coverage_cx {
|
|
|
|
Some(ref cx) => cx.instances_used.borrow(),
|
2024-10-31 10:12:15 +00:00
|
|
|
None => return,
|
|
|
|
};
|
2020-07-25 04:14:28 +00:00
|
|
|
|
2024-12-13 11:40:45 +00:00
|
|
|
// The order of entries in this global file table needs to be deterministic,
|
|
|
|
// and ideally should also be independent of the details of stable-hashing,
|
|
|
|
// because coverage tests snapshots (`.cov-map`) can observe the order and
|
|
|
|
// would need to be re-blessed if it changes. As long as those requirements
|
|
|
|
// are satisfied, the order can be arbitrary.
|
|
|
|
let mut global_file_table = GlobalFileTable::new();
|
2023-10-06 12:53:23 +00:00
|
|
|
|
2024-12-14 11:48:12 +00:00
|
|
|
let mut covfun_records = instances_used
|
|
|
|
.iter()
|
|
|
|
.copied()
|
2024-12-13 11:40:45 +00:00
|
|
|
// Sort by symbol name, so that the global file table is built in an
|
|
|
|
// order that doesn't depend on the stable-hash-based order in which
|
|
|
|
// instances were visited during codegen.
|
2024-12-14 11:48:12 +00:00
|
|
|
.sorted_by_cached_key(|&instance| tcx.symbol_name(instance).name)
|
|
|
|
.filter_map(|instance| prepare_covfun_record(tcx, &mut global_file_table, instance, true))
|
2024-12-11 04:03:31 +00:00
|
|
|
.collect::<Vec<_>>();
|
|
|
|
|
2024-12-14 11:48:12 +00:00
|
|
|
// In a single designated CGU, also prepare covfun records for functions
|
|
|
|
// in this crate that were instrumented for coverage, but are unused.
|
|
|
|
if cx.codegen_unit.is_code_coverage_dead_code_cgu() {
|
2025-03-21 04:14:22 +00:00
|
|
|
unused::prepare_covfun_records_for_unused_functions(
|
|
|
|
cx,
|
|
|
|
&mut global_file_table,
|
|
|
|
&mut covfun_records,
|
|
|
|
);
|
2024-12-14 11:48:12 +00:00
|
|
|
}
|
|
|
|
|
2024-12-11 04:12:23 +00:00
|
|
|
// If there are no covfun records for this CGU, don't generate a covmap record.
|
|
|
|
// Emitting a covmap record without any covfun records causes `llvm-cov` to
|
|
|
|
// fail when generating coverage reports, and if there are no covfun records
|
|
|
|
// then the covmap record isn't useful anyway.
|
|
|
|
// This should prevent a repeat of <https://github.com/rust-lang/rust/issues/133606>.
|
|
|
|
if covfun_records.is_empty() {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2024-12-13 11:40:45 +00:00
|
|
|
// Encode all filenames referenced by coverage mappings in this CGU.
|
|
|
|
let filenames_buffer = global_file_table.make_filenames_buffer(tcx);
|
|
|
|
// The `llvm-cov` tool uses this hash to associate each covfun record with
|
|
|
|
// its corresponding filenames table, since the final binary will typically
|
|
|
|
// contain multiple covmap records from different compilation units.
|
|
|
|
let filenames_hash = llvm_cov::hash_bytes(&filenames_buffer);
|
|
|
|
|
2024-12-11 04:03:31 +00:00
|
|
|
for covfun in &covfun_records {
|
2024-12-12 09:28:10 +00:00
|
|
|
covfun::generate_covfun_record(cx, filenames_hash, covfun)
|
2020-11-23 20:56:07 +00:00
|
|
|
}
|
|
|
|
|
2024-12-11 04:12:23 +00:00
|
|
|
// Generate the coverage map header, which contains the filenames used by
|
|
|
|
// this CGU's coverage mappings, and store it in a well-known global.
|
|
|
|
// (This is skipped if we returned early due to having no covfun records.)
|
2024-12-12 07:33:33 +00:00
|
|
|
generate_covmap_record(cx, covmap_version, &filenames_buffer);
|
2020-07-02 18:27:15 +00:00
|
|
|
}
|
|
|
|
|
2024-12-18 10:19:30 +00:00
|
|
|
/// Maps "global" (per-CGU) file ID numbers to their underlying source files.
|
2023-09-01 13:27:45 +00:00
|
|
|
struct GlobalFileTable {
|
2024-12-18 10:19:30 +00:00
|
|
|
/// This "raw" table doesn't include the working dir, so a file's
|
2023-10-03 10:40:50 +00:00
|
|
|
/// global ID is its index in this set **plus one**.
|
2024-12-18 10:19:30 +00:00
|
|
|
raw_file_table: FxIndexMap<StableSourceFileId, Arc<SourceFile>>,
|
2020-07-02 18:27:15 +00:00
|
|
|
}
|
|
|
|
|
2023-09-01 13:27:45 +00:00
|
|
|
impl GlobalFileTable {
|
2024-12-13 11:40:45 +00:00
|
|
|
fn new() -> Self {
|
2024-12-18 10:19:30 +00:00
|
|
|
Self { raw_file_table: FxIndexMap::default() }
|
2023-10-03 10:40:50 +00:00
|
|
|
}
|
|
|
|
|
2024-12-18 10:19:30 +00:00
|
|
|
fn global_file_id_for_file(&mut self, file: &Arc<SourceFile>) -> GlobalFileId {
|
2024-12-13 11:40:45 +00:00
|
|
|
// Ensure the given file has a table entry, and get its index.
|
2024-12-18 10:19:30 +00:00
|
|
|
let entry = self.raw_file_table.entry(file.stable_id);
|
|
|
|
let raw_id = entry.index();
|
|
|
|
entry.or_insert_with(|| Arc::clone(file));
|
|
|
|
|
2023-10-03 10:40:50 +00:00
|
|
|
// The raw file table doesn't include an entry for the working dir
|
|
|
|
// (which has ID 0), so add 1 to get the correct ID.
|
2024-08-29 05:56:21 +00:00
|
|
|
GlobalFileId::from_usize(raw_id + 1)
|
2023-10-03 10:40:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn make_filenames_buffer(&self, tcx: TyCtxt<'_>) -> Vec<u8> {
|
2024-12-18 10:19:30 +00:00
|
|
|
let mut table = Vec::with_capacity(self.raw_file_table.len() + 1);
|
|
|
|
|
2023-01-09 08:31:34 +00:00
|
|
|
// LLVM Coverage Mapping Format version 6 (zero-based encoded as 5)
|
|
|
|
// requires setting the first filename to the compilation directory.
|
|
|
|
// Since rustc generates coverage maps with relative paths, the
|
|
|
|
// compilation directory can be combined with the relative paths
|
|
|
|
// to get absolute paths, if needed.
|
2024-12-18 10:19:30 +00:00
|
|
|
table.push(
|
|
|
|
tcx.sess
|
|
|
|
.opts
|
|
|
|
.working_dir
|
|
|
|
.for_scope(tcx.sess, RemapPathScopeComponents::MACRO)
|
|
|
|
.to_string_lossy(),
|
|
|
|
);
|
|
|
|
|
|
|
|
// Add the regular entries after the base directory.
|
|
|
|
table.extend(self.raw_file_table.values().map(|file| {
|
|
|
|
file.name.for_scope(tcx.sess, RemapPathScopeComponents::MACRO).to_string_lossy()
|
|
|
|
}));
|
|
|
|
|
|
|
|
llvm_cov::write_filenames_to_buffer(&table)
|
2023-09-01 13:27:45 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-28 12:36:40 +00:00
|
|
|
rustc_index::newtype_index! {
|
2024-08-29 05:56:21 +00:00
|
|
|
/// An index into the CGU's overall list of file paths. The underlying paths
|
|
|
|
/// will be embedded in the `__llvm_covmap` linker section.
|
|
|
|
struct GlobalFileId {}
|
|
|
|
}
|
|
|
|
rustc_index::newtype_index! {
|
|
|
|
/// An index into a function's list of global file IDs. That underlying list
|
|
|
|
/// of local-to-global mappings will be embedded in the function's record in
|
|
|
|
/// the `__llvm_covfun` linker section.
|
2024-12-18 10:00:51 +00:00
|
|
|
struct LocalFileId {}
|
2023-09-28 12:36:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Holds a mapping from "local" (per-function) file IDs to "global" (per-CGU)
|
|
|
|
/// file IDs.
|
2024-12-11 04:41:02 +00:00
|
|
|
#[derive(Debug, Default)]
|
2023-09-28 12:36:40 +00:00
|
|
|
struct VirtualFileMapping {
|
2024-08-29 05:56:21 +00:00
|
|
|
local_to_global: IndexVec<LocalFileId, GlobalFileId>,
|
|
|
|
global_to_local: FxIndexMap<GlobalFileId, LocalFileId>,
|
2023-09-28 12:36:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl VirtualFileMapping {
|
2024-08-29 05:56:21 +00:00
|
|
|
fn local_id_for_global(&mut self, global_file_id: GlobalFileId) -> LocalFileId {
|
2023-09-28 12:36:40 +00:00
|
|
|
*self
|
|
|
|
.global_to_local
|
|
|
|
.entry(global_file_id)
|
|
|
|
.or_insert_with(|| self.local_to_global.push(global_file_id))
|
2023-09-28 12:36:40 +00:00
|
|
|
}
|
|
|
|
|
2024-12-11 04:41:02 +00:00
|
|
|
fn to_vec(&self) -> Vec<u32> {
|
|
|
|
// This clone could be avoided by transmuting `&[GlobalFileId]` to `&[u32]`,
|
|
|
|
// but it isn't hot or expensive enough to justify the extra unsafety.
|
|
|
|
self.local_to_global.iter().map(|&global| GlobalFileId::as_u32(global)).collect()
|
2023-09-28 12:36:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-24 11:47:45 +00:00
|
|
|
/// Generates the contents of the covmap record for this CGU, which mostly
|
|
|
|
/// consists of a header and a list of filenames. The record is then stored
|
|
|
|
/// as a global variable in the `__llvm_covmap` section.
|
2024-12-12 07:33:33 +00:00
|
|
|
fn generate_covmap_record<'ll>(cx: &CodegenCx<'ll, '_>, version: u32, filenames_buffer: &[u8]) {
|
|
|
|
// A covmap record consists of four target-endian u32 values, followed by
|
|
|
|
// the encoded filenames table. Two of the header fields are unused in
|
|
|
|
// modern versions of the LLVM coverage mapping format, and are always 0.
|
|
|
|
// <https://llvm.org/docs/CoverageMappingFormat.html#llvm-ir-representation>
|
|
|
|
// See also `src/llvm-project/clang/lib/CodeGen/CoverageMappingGen.cpp`.
|
|
|
|
let covmap_header = cx.const_struct(
|
|
|
|
&[
|
|
|
|
cx.const_u32(0), // (unused)
|
|
|
|
cx.const_u32(filenames_buffer.len() as u32),
|
|
|
|
cx.const_u32(0), // (unused)
|
|
|
|
cx.const_u32(version),
|
|
|
|
],
|
|
|
|
/* packed */ false,
|
2023-09-01 13:27:45 +00:00
|
|
|
);
|
2024-12-12 07:33:33 +00:00
|
|
|
let covmap_record = cx
|
|
|
|
.const_struct(&[covmap_header, cx.const_bytes(filenames_buffer)], /* packed */ false);
|
|
|
|
|
|
|
|
let covmap_global =
|
|
|
|
llvm::add_global(cx.llmod, cx.val_ty(covmap_record), &llvm_cov::covmap_var_name());
|
|
|
|
llvm::set_initializer(covmap_global, covmap_record);
|
|
|
|
llvm::set_global_constant(covmap_global, true);
|
|
|
|
llvm::set_linkage(covmap_global, llvm::Linkage::PrivateLinkage);
|
|
|
|
llvm::set_section(covmap_global, &llvm_cov::covmap_section_name(cx.llmod));
|
2024-10-24 11:47:45 +00:00
|
|
|
// LLVM's coverage mapping format specifies 8-byte alignment for items in this section.
|
2024-10-26 06:37:04 +00:00
|
|
|
// <https://llvm.org/docs/CoverageMappingFormat.html>
|
2024-12-12 07:33:33 +00:00
|
|
|
llvm::set_alignment(covmap_global, Align::EIGHT);
|
|
|
|
|
|
|
|
cx.add_used_global(covmap_global);
|
2020-07-02 18:27:15 +00:00
|
|
|
}
|