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-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)
|
2025-03-31 01:51:16 +00:00
|
|
|
.filter_map(|instance| prepare_covfun_record(tcx, 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-31 01:51:16 +00:00
|
|
|
unused::prepare_covfun_records_for_unused_functions(cx, &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;
|
|
|
|
}
|
|
|
|
|
2025-03-31 01:51:16 +00:00
|
|
|
// Prepare the global file table for this CGU, containing all paths needed
|
|
|
|
// by one or more covfun records.
|
|
|
|
let global_file_table =
|
|
|
|
GlobalFileTable::build(tcx, covfun_records.iter().flat_map(|c| c.all_source_files()));
|
2024-12-13 11:40:45 +00:00
|
|
|
|
2024-12-11 04:03:31 +00:00
|
|
|
for covfun in &covfun_records {
|
2025-03-31 01:51:16 +00:00
|
|
|
covfun::generate_covfun_record(cx, &global_file_table, 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.)
|
2025-03-31 01:51:16 +00:00
|
|
|
generate_covmap_record(cx, covmap_version, &global_file_table.filenames_buffer);
|
2020-07-02 18:27:15 +00:00
|
|
|
}
|
|
|
|
|
2025-03-31 01:51:16 +00:00
|
|
|
/// Maps "global" (per-CGU) file ID numbers to their underlying source file paths.
|
|
|
|
#[derive(Debug)]
|
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**.
|
2025-03-31 01:51:16 +00:00
|
|
|
raw_file_table: FxIndexMap<StableSourceFileId, String>,
|
|
|
|
|
|
|
|
/// The file table in encoded form (possibly compressed), which can be
|
|
|
|
/// included directly in this CGU's `__llvm_covmap` record.
|
|
|
|
filenames_buffer: Vec<u8>,
|
|
|
|
|
|
|
|
/// Truncated hash of the bytes in `filenames_buffer`.
|
|
|
|
///
|
|
|
|
/// 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.
|
|
|
|
filenames_hash: u64,
|
2020-07-02 18:27:15 +00:00
|
|
|
}
|
|
|
|
|
2023-09-01 13:27:45 +00:00
|
|
|
impl GlobalFileTable {
|
2025-03-31 01:51:16 +00:00
|
|
|
/// Builds a "global file table" for this CGU, mapping numeric IDs to
|
|
|
|
/// path strings.
|
|
|
|
fn build<'a>(tcx: TyCtxt<'_>, all_files: impl Iterator<Item = &'a SourceFile>) -> Self {
|
|
|
|
let mut raw_file_table = FxIndexMap::default();
|
|
|
|
|
|
|
|
for file in all_files {
|
|
|
|
raw_file_table.entry(file.stable_id).or_insert_with(|| {
|
|
|
|
file.name
|
|
|
|
.for_scope(tcx.sess, RemapPathScopeComponents::MACRO)
|
|
|
|
.to_string_lossy()
|
|
|
|
.into_owned()
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// FIXME(Zalathar): Consider sorting the file table here, but maybe
|
|
|
|
// only after adding filename support to coverage-dump, so that the
|
|
|
|
// table order isn't directly visible in `.coverage-map` snapshots.
|
|
|
|
|
|
|
|
let mut table = Vec::with_capacity(raw_file_table.len() + 1);
|
|
|
|
|
|
|
|
// Since version 6 of the LLVM coverage mapping format, the first entry
|
|
|
|
// in the global file table is treated as a base directory, used to
|
|
|
|
// resolve any other entries that are stored as relative paths.
|
|
|
|
let base_dir = tcx
|
|
|
|
.sess
|
|
|
|
.opts
|
|
|
|
.working_dir
|
|
|
|
.for_scope(tcx.sess, RemapPathScopeComponents::MACRO)
|
|
|
|
.to_string_lossy();
|
|
|
|
table.push(base_dir.as_ref());
|
2023-10-03 10:40:50 +00:00
|
|
|
|
2025-03-31 01:51:16 +00:00
|
|
|
// Add the regular entries after the base directory.
|
|
|
|
table.extend(raw_file_table.values().map(|name| name.as_str()));
|
2023-10-03 10:40:50 +00:00
|
|
|
|
2025-03-31 01:51:16 +00:00
|
|
|
// Encode the file table into a buffer, and get the hash of its encoded
|
|
|
|
// bytes, so that we can embed that hash in `__llvm_covfun` records.
|
|
|
|
let filenames_buffer = llvm_cov::write_filenames_to_buffer(&table);
|
|
|
|
let filenames_hash = llvm_cov::hash_bytes(&filenames_buffer);
|
2024-12-18 10:19:30 +00:00
|
|
|
|
2025-03-31 01:51:16 +00:00
|
|
|
Self { raw_file_table, filenames_buffer, filenames_hash }
|
|
|
|
}
|
2024-12-18 10:19:30 +00:00
|
|
|
|
2025-03-31 01:51:16 +00:00
|
|
|
fn get_existing_id(&self, file: &SourceFile) -> Option<GlobalFileId> {
|
|
|
|
let raw_id = self.raw_file_table.get_index_of(&file.stable_id)?;
|
|
|
|
// The raw file table doesn't include an entry for the base dir
|
|
|
|
// (which has ID 0), so add 1 to get the correct ID.
|
|
|
|
Some(GlobalFileId::from_usize(raw_id + 1))
|
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
|
|
|
}
|
|
|
|
|
2025-03-31 01:51:16 +00:00
|
|
|
/// Holds a mapping from "local" (per-function) file IDs to their corresponding
|
|
|
|
/// source files.
|
2024-12-11 04:41:02 +00:00
|
|
|
#[derive(Debug, Default)]
|
2023-09-28 12:36:40 +00:00
|
|
|
struct VirtualFileMapping {
|
2025-03-31 01:51:16 +00:00
|
|
|
local_file_table: IndexVec<LocalFileId, Arc<SourceFile>>,
|
2023-09-28 12:36:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl VirtualFileMapping {
|
2025-03-31 01:51:16 +00:00
|
|
|
fn push_file(&mut self, source_file: &Arc<SourceFile>) -> LocalFileId {
|
|
|
|
self.local_file_table.push(Arc::clone(source_file))
|
2023-09-28 12:36:40 +00:00
|
|
|
}
|
|
|
|
|
2025-03-31 01:51:16 +00:00
|
|
|
/// Resolves all of the filenames in this local file mapping to a list of
|
|
|
|
/// global file IDs in its CGU, for inclusion in this function's
|
|
|
|
/// `__llvm_covfun` record.
|
|
|
|
///
|
|
|
|
/// The global file IDs are returned as `u32` to make FFI easier.
|
|
|
|
fn resolve_all(&self, global_file_table: &GlobalFileTable) -> Option<Vec<u32>> {
|
|
|
|
self.local_file_table
|
|
|
|
.iter()
|
|
|
|
.map(|file| try {
|
|
|
|
let id = global_file_table.get_existing_id(file)?;
|
|
|
|
GlobalFileId::as_u32(id)
|
|
|
|
})
|
|
|
|
.collect::<Option<Vec<_>>>()
|
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
|
|
|
}
|