1 use crate::common::CodegenCx;
2 use crate::coverageinfo;
5 use llvm::coverageinfo::CounterMappingRegion;
6 use rustc_codegen_ssa::coverageinfo::map::{Counter, CounterExpression};
7 use rustc_codegen_ssa::traits::{ConstMethods, CoverageInfoMethods};
8 use rustc_data_structures::fx::FxIndexSet;
9 use rustc_hir::def::DefKind;
10 use rustc_hir::def_id::DefIdSet;
11 use rustc_llvm::RustString;
12 use rustc_middle::bug;
13 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
14 use rustc_middle::mir::coverage::CodeRegion;
15 use rustc_middle::ty::TyCtxt;
17 use std::ffi::CString;
19 /// Generates and exports the Coverage Map.
21 /// Rust Coverage Map generation supports LLVM Coverage Mapping Format versions
22 /// 5 (LLVM 12, only) and 6 (zero-based encoded as 4 and 5, respectively), as defined at
23 /// [LLVM Code Coverage Mapping Format](https://github.com/rust-lang/llvm-project/blob/rustc/13.0-2021-09-30/llvm/docs/CoverageMappingFormat.rst#llvm-code-coverage-mapping-format).
24 /// These versions are supported by the LLVM coverage tools (`llvm-profdata` and `llvm-cov`)
25 /// bundled with Rust's fork of LLVM.
27 /// Consequently, Rust's bundled version of Clang also generates Coverage Maps compliant with
28 /// the same version. Clang's implementation of Coverage Map generation was referenced when
29 /// implementing this Rust version, and though the format documentation is very explicit and
30 /// detailed, some undocumented details in Clang's implementation (that may or may not be important)
31 /// were also replicated for Rust's Coverage Map.
32 pub fn finalize<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) {
35 // Ensure the installed version of LLVM supports at least Coverage Map
36 // Version 5 (encoded as a zero-based value: 4), which was introduced with
38 let version = coverageinfo::mapping_version();
40 tcx.sess.fatal("rustc option `-C instrument-coverage` requires LLVM 12 or higher.");
43 debug!("Generating coverage map for CodegenUnit: `{}`", cx.codegen_unit.name());
45 // In order to show that unused functions have coverage counts of zero (0), LLVM requires the
46 // functions exist. Generate synthetic functions with a (required) single counter, and add the
47 // MIR `Coverage` code regions to the `function_coverage_map`, before calling
48 // `ctx.take_function_coverage_map()`.
49 if cx.codegen_unit.is_code_coverage_dead_code_cgu() {
50 add_unused_functions(cx);
53 let function_coverage_map = match cx.coverage_context() {
54 Some(ctx) => ctx.take_function_coverage_map(),
58 if function_coverage_map.is_empty() {
59 // This module has no functions with coverage instrumentation
63 let mut mapgen = CoverageMapGenerator::new(tcx, version);
65 // Encode coverage mappings and generate function records
66 let mut function_data = Vec::new();
67 for (instance, function_coverage) in function_coverage_map {
68 debug!("Generate function coverage for {}, {:?}", cx.codegen_unit.name(), instance);
69 let mangled_function_name = tcx.symbol_name(instance).to_string();
70 let source_hash = function_coverage.source_hash();
71 let is_used = function_coverage.is_used();
72 let (expressions, counter_regions) =
73 function_coverage.get_expressions_and_counter_regions();
75 let coverage_mapping_buffer = llvm::build_byte_buffer(|coverage_mapping_buffer| {
76 mapgen.write_coverage_mapping(expressions, counter_regions, coverage_mapping_buffer);
79 if coverage_mapping_buffer.is_empty() {
80 if function_coverage.is_used() {
82 "A used function should have had coverage mapping data but did not: {}",
86 debug!("unused function had no coverage mapping data: {}", mangled_function_name);
91 function_data.push((mangled_function_name, source_hash, is_used, coverage_mapping_buffer));
94 // Encode all filenames referenced by counters/expressions in this module
95 let filenames_buffer = llvm::build_byte_buffer(|filenames_buffer| {
96 coverageinfo::write_filenames_section_to_buffer(&mapgen.filenames, filenames_buffer);
99 let filenames_size = filenames_buffer.len();
100 let filenames_val = cx.const_bytes(&filenames_buffer);
101 let filenames_ref = coverageinfo::hash_bytes(filenames_buffer);
103 // Generate the LLVM IR representation of the coverage map and store it in a well-known global
104 let cov_data_val = mapgen.generate_coverage_map(cx, version, filenames_size, filenames_val);
106 for (mangled_function_name, source_hash, is_used, coverage_mapping_buffer) in function_data {
107 save_function_record(
109 mangled_function_name,
112 coverage_mapping_buffer,
117 // Save the coverage data value to LLVM IR
118 coverageinfo::save_cov_data_to_mod(cx, cov_data_val);
121 struct CoverageMapGenerator {
122 filenames: FxIndexSet<CString>,
125 impl CoverageMapGenerator {
126 fn new(tcx: TyCtxt<'_>, version: u32) -> Self {
127 let mut filenames = FxIndexSet::default();
129 // LLVM Coverage Mapping Format version 6 (zero-based encoded as 5)
130 // requires setting the first filename to the compilation directory.
131 // Since rustc generates coverage maps with relative paths, the
132 // compilation directory can be combined with the the relative paths
133 // to get absolute paths, if needed.
134 let working_dir = tcx
138 .remapped_path_if_available()
142 CString::new(working_dir).expect("null error converting filename to C string");
143 filenames.insert(c_filename);
148 /// Using the `expressions` and `counter_regions` collected for the current function, generate
149 /// the `mapping_regions` and `virtual_file_mapping`, and capture any new filenames. Then use
150 /// LLVM APIs to encode the `virtual_file_mapping`, `expressions`, and `mapping_regions` into
151 /// the given `coverage_mapping` byte buffer, compliant with the LLVM Coverage Mapping format.
152 fn write_coverage_mapping<'a>(
154 expressions: Vec<CounterExpression>,
155 counter_regions: impl Iterator<Item = (Counter, &'a CodeRegion)>,
156 coverage_mapping_buffer: &RustString,
158 let mut counter_regions = counter_regions.collect::<Vec<_>>();
159 if counter_regions.is_empty() {
163 let mut virtual_file_mapping = Vec::new();
164 let mut mapping_regions = Vec::new();
165 let mut current_file_name = None;
166 let mut current_file_id = 0;
168 // Convert the list of (Counter, CodeRegion) pairs to an array of `CounterMappingRegion`, sorted
169 // by filename and position. Capture any new files to compute the `CounterMappingRegion`s
170 // `file_id` (indexing files referenced by the current function), and construct the
171 // function-specific `virtual_file_mapping` from `file_id` to its index in the module's
172 // `filenames` array.
173 counter_regions.sort_unstable_by_key(|(_counter, region)| *region);
174 for (counter, region) in counter_regions {
175 let CodeRegion { file_name, start_line, start_col, end_line, end_col } = *region;
176 let same_file = current_file_name.as_ref().map_or(false, |p| *p == file_name);
178 if current_file_name.is_some() {
179 current_file_id += 1;
181 current_file_name = Some(file_name);
182 let c_filename = CString::new(file_name.to_string())
183 .expect("null error converting filename to C string");
184 debug!(" file_id: {} = '{:?}'", current_file_id, c_filename);
185 let (filenames_index, _) = self.filenames.insert_full(c_filename);
186 virtual_file_mapping.push(filenames_index as u32);
188 debug!("Adding counter {:?} to map for {:?}", counter, region);
189 mapping_regions.push(CounterMappingRegion::code_region(
199 // Encode and append the current function's coverage mapping data
200 coverageinfo::write_mapping_to_buffer(
201 virtual_file_mapping,
204 coverage_mapping_buffer,
208 /// Construct coverage map header and the array of function records, and combine them into the
209 /// coverage map. Save the coverage map data into the LLVM IR as a static global using a
210 /// specific, well-known section and name.
211 fn generate_coverage_map<'ll>(
213 cx: &CodegenCx<'ll, '_>,
215 filenames_size: usize,
216 filenames_val: &'ll llvm::Value,
217 ) -> &'ll llvm::Value {
218 debug!("cov map: filenames_size = {}, 0-based version = {}", filenames_size, version);
220 // Create the coverage data header (Note, fields 0 and 2 are now always zero,
221 // as of `llvm::coverage::CovMapVersion::Version4`.)
222 let zero_was_n_records_val = cx.const_u32(0);
223 let filenames_size_val = cx.const_u32(filenames_size as u32);
224 let zero_was_coverage_size_val = cx.const_u32(0);
225 let version_val = cx.const_u32(version);
226 let cov_data_header_val = cx.const_struct(
227 &[zero_was_n_records_val, filenames_size_val, zero_was_coverage_size_val, version_val],
231 // Create the complete LLVM coverage data value to add to the LLVM IR
232 cx.const_struct(&[cov_data_header_val, filenames_val], /*packed=*/ false)
236 /// Construct a function record and combine it with the function's coverage mapping data.
237 /// Save the function record into the LLVM IR as a static global using a
238 /// specific, well-known section and name.
239 fn save_function_record(
240 cx: &CodegenCx<'_, '_>,
241 mangled_function_name: String,
244 coverage_mapping_buffer: Vec<u8>,
247 // Concatenate the encoded coverage mappings
248 let coverage_mapping_size = coverage_mapping_buffer.len();
249 let coverage_mapping_val = cx.const_bytes(&coverage_mapping_buffer);
251 let func_name_hash = coverageinfo::hash_str(&mangled_function_name);
252 let func_name_hash_val = cx.const_u64(func_name_hash);
253 let coverage_mapping_size_val = cx.const_u32(coverage_mapping_size as u32);
254 let source_hash_val = cx.const_u64(source_hash);
255 let filenames_ref_val = cx.const_u64(filenames_ref);
256 let func_record_val = cx.const_struct(
259 coverage_mapping_size_val,
262 coverage_mapping_val,
267 coverageinfo::save_func_record_to_mod(cx, func_name_hash, func_record_val, is_used);
270 /// When finalizing the coverage map, `FunctionCoverage` only has the `CodeRegion`s and counters for
271 /// the functions that went through codegen; such as public functions and "used" functions
272 /// (functions referenced by other "used" or public items). Any other functions considered unused,
273 /// or "Unreachable", were still parsed and processed through the MIR stage, but were not
274 /// codegenned. (Note that `-Clink-dead-code` can force some unused code to be codegenned, but
275 /// that flag is known to cause other errors, when combined with `-C instrument-coverage`; and
276 /// `-Clink-dead-code` will not generate code for unused generic functions.)
278 /// We can find the unused functions (including generic functions) by the set difference of all MIR
279 /// `DefId`s (`tcx` query `mir_keys`) minus the codegenned `DefId`s (`tcx` query
280 /// `codegened_and_inlined_items`).
282 /// These unused functions are then codegen'd in one of the CGUs which is marked as the
283 /// "code coverage dead code cgu" during the partitioning process. This prevents us from generating
284 /// code regions for the same function more than once which can lead to linker errors regarding
285 /// duplicate symbols.
286 fn add_unused_functions<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) {
287 assert!(cx.codegen_unit.is_code_coverage_dead_code_cgu());
291 let ignore_unused_generics = tcx.sess.instrument_coverage_except_unused_generics();
293 let eligible_def_ids: DefIdSet = tcx
296 .filter_map(|local_def_id| {
297 let def_id = local_def_id.to_def_id();
298 let kind = tcx.def_kind(def_id);
299 // `mir_keys` will give us `DefId`s for all kinds of things, not
300 // just "functions", like consts, statics, etc. Filter those out.
301 // If `ignore_unused_generics` was specified, filter out any
302 // generic functions from consideration as well.
305 DefKind::Fn | DefKind::AssocFn | DefKind::Closure | DefKind::Generator
308 } else if ignore_unused_generics
309 && tcx.generics_of(def_id).requires_monomorphization(tcx)
313 Some(local_def_id.to_def_id())
317 let codegenned_def_ids = tcx.codegened_and_inlined_items(());
319 for &non_codegenned_def_id in eligible_def_ids.difference(codegenned_def_ids) {
320 let codegen_fn_attrs = tcx.codegen_fn_attrs(non_codegenned_def_id);
322 // If a function is marked `#[no_coverage]`, then skip generating a
323 // dead code stub for it.
324 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_COVERAGE) {
325 debug!("skipping unused fn marked #[no_coverage]: {:?}", non_codegenned_def_id);
329 debug!("generating unused fn: {:?}", non_codegenned_def_id);
330 cx.define_unused_fn(non_codegenned_def_id);