]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs
Add 'src/tools/rust-analyzer/' from commit '977e12a0bdc3e329af179ef3a9d466af9eb613bb'
[rust.git] / compiler / rustc_codegen_llvm / src / coverageinfo / mapgen.rs
1 use crate::common::CodegenCx;
2 use crate::coverageinfo;
3 use crate::llvm;
4
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;
16
17 use std::ffi::CString;
18
19 use tracing::debug;
20
21 /// Generates and exports the Coverage Map.
22 ///
23 /// Rust Coverage Map generation supports LLVM Coverage Mapping Format versions
24 /// 5 (LLVM 12, only) and 6 (zero-based encoded as 4 and 5, respectively), as defined at
25 /// [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).
26 /// These versions are supported by the LLVM coverage tools (`llvm-profdata` and `llvm-cov`)
27 /// bundled with Rust's fork of LLVM.
28 ///
29 /// Consequently, Rust's bundled version of Clang also generates Coverage Maps compliant with
30 /// the same version. Clang's implementation of Coverage Map generation was referenced when
31 /// implementing this Rust version, and though the format documentation is very explicit and
32 /// detailed, some undocumented details in Clang's implementation (that may or may not be important)
33 /// were also replicated for Rust's Coverage Map.
34 pub fn finalize<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) {
35     let tcx = cx.tcx;
36
37     // Ensure the installed version of LLVM supports at least Coverage Map
38     // Version 5 (encoded as a zero-based value: 4), which was introduced with
39     // LLVM 12.
40     let version = coverageinfo::mapping_version();
41     if version < 4 {
42         tcx.sess.fatal("rustc option `-C instrument-coverage` requires LLVM 12 or higher.");
43     }
44
45     debug!("Generating coverage map for CodegenUnit: `{}`", cx.codegen_unit.name());
46
47     // In order to show that unused functions have coverage counts of zero (0), LLVM requires the
48     // functions exist. Generate synthetic functions with a (required) single counter, and add the
49     // MIR `Coverage` code regions to the `function_coverage_map`, before calling
50     // `ctx.take_function_coverage_map()`.
51     if cx.codegen_unit.is_code_coverage_dead_code_cgu() {
52         add_unused_functions(cx);
53     }
54
55     let function_coverage_map = match cx.coverage_context() {
56         Some(ctx) => ctx.take_function_coverage_map(),
57         None => return,
58     };
59
60     if function_coverage_map.is_empty() {
61         // This module has no functions with coverage instrumentation
62         return;
63     }
64
65     let mut mapgen = CoverageMapGenerator::new(tcx, version);
66
67     // Encode coverage mappings and generate function records
68     let mut function_data = Vec::new();
69     for (instance, function_coverage) in function_coverage_map {
70         debug!("Generate function coverage for {}, {:?}", cx.codegen_unit.name(), instance);
71         let mangled_function_name = tcx.symbol_name(instance).to_string();
72         let source_hash = function_coverage.source_hash();
73         let is_used = function_coverage.is_used();
74         let (expressions, counter_regions) =
75             function_coverage.get_expressions_and_counter_regions();
76
77         let coverage_mapping_buffer = llvm::build_byte_buffer(|coverage_mapping_buffer| {
78             mapgen.write_coverage_mapping(expressions, counter_regions, coverage_mapping_buffer);
79         });
80
81         if coverage_mapping_buffer.is_empty() {
82             if function_coverage.is_used() {
83                 bug!(
84                     "A used function should have had coverage mapping data but did not: {}",
85                     mangled_function_name
86                 );
87             } else {
88                 debug!("unused function had no coverage mapping data: {}", mangled_function_name);
89                 continue;
90             }
91         }
92
93         function_data.push((mangled_function_name, source_hash, is_used, coverage_mapping_buffer));
94     }
95
96     // Encode all filenames referenced by counters/expressions in this module
97     let filenames_buffer = llvm::build_byte_buffer(|filenames_buffer| {
98         coverageinfo::write_filenames_section_to_buffer(&mapgen.filenames, filenames_buffer);
99     });
100
101     let filenames_size = filenames_buffer.len();
102     let filenames_val = cx.const_bytes(&filenames_buffer);
103     let filenames_ref = coverageinfo::hash_bytes(filenames_buffer);
104
105     // Generate the LLVM IR representation of the coverage map and store it in a well-known global
106     let cov_data_val = mapgen.generate_coverage_map(cx, version, filenames_size, filenames_val);
107
108     for (mangled_function_name, source_hash, is_used, coverage_mapping_buffer) in function_data {
109         save_function_record(
110             cx,
111             mangled_function_name,
112             source_hash,
113             filenames_ref,
114             coverage_mapping_buffer,
115             is_used,
116         );
117     }
118
119     // Save the coverage data value to LLVM IR
120     coverageinfo::save_cov_data_to_mod(cx, cov_data_val);
121 }
122
123 struct CoverageMapGenerator {
124     filenames: FxIndexSet<CString>,
125 }
126
127 impl CoverageMapGenerator {
128     fn new(tcx: TyCtxt<'_>, version: u32) -> Self {
129         let mut filenames = FxIndexSet::default();
130         if version >= 5 {
131             // LLVM Coverage Mapping Format version 6 (zero-based encoded as 5)
132             // requires setting the first filename to the compilation directory.
133             // Since rustc generates coverage maps with relative paths, the
134             // compilation directory can be combined with the the relative paths
135             // to get absolute paths, if needed.
136             let working_dir = tcx
137                 .sess
138                 .opts
139                 .working_dir
140                 .remapped_path_if_available()
141                 .to_string_lossy()
142                 .to_string();
143             let c_filename =
144                 CString::new(working_dir).expect("null error converting filename to C string");
145             filenames.insert(c_filename);
146         }
147         Self { filenames }
148     }
149
150     /// Using the `expressions` and `counter_regions` collected for the current function, generate
151     /// the `mapping_regions` and `virtual_file_mapping`, and capture any new filenames. Then use
152     /// LLVM APIs to encode the `virtual_file_mapping`, `expressions`, and `mapping_regions` into
153     /// the given `coverage_mapping` byte buffer, compliant with the LLVM Coverage Mapping format.
154     fn write_coverage_mapping<'a>(
155         &mut self,
156         expressions: Vec<CounterExpression>,
157         counter_regions: impl Iterator<Item = (Counter, &'a CodeRegion)>,
158         coverage_mapping_buffer: &RustString,
159     ) {
160         let mut counter_regions = counter_regions.collect::<Vec<_>>();
161         if counter_regions.is_empty() {
162             return;
163         }
164
165         let mut virtual_file_mapping = Vec::new();
166         let mut mapping_regions = Vec::new();
167         let mut current_file_name = None;
168         let mut current_file_id = 0;
169
170         // Convert the list of (Counter, CodeRegion) pairs to an array of `CounterMappingRegion`, sorted
171         // by filename and position. Capture any new files to compute the `CounterMappingRegion`s
172         // `file_id` (indexing files referenced by the current function), and construct the
173         // function-specific `virtual_file_mapping` from `file_id` to its index in the module's
174         // `filenames` array.
175         counter_regions.sort_unstable_by_key(|(_counter, region)| *region);
176         for (counter, region) in counter_regions {
177             let CodeRegion { file_name, start_line, start_col, end_line, end_col } = *region;
178             let same_file = current_file_name.as_ref().map_or(false, |p| *p == file_name);
179             if !same_file {
180                 if current_file_name.is_some() {
181                     current_file_id += 1;
182                 }
183                 current_file_name = Some(file_name);
184                 let c_filename = CString::new(file_name.to_string())
185                     .expect("null error converting filename to C string");
186                 debug!("  file_id: {} = '{:?}'", current_file_id, c_filename);
187                 let (filenames_index, _) = self.filenames.insert_full(c_filename);
188                 virtual_file_mapping.push(filenames_index as u32);
189             }
190             debug!("Adding counter {:?} to map for {:?}", counter, region);
191             mapping_regions.push(CounterMappingRegion::code_region(
192                 counter,
193                 current_file_id,
194                 start_line,
195                 start_col,
196                 end_line,
197                 end_col,
198             ));
199         }
200
201         // Encode and append the current function's coverage mapping data
202         coverageinfo::write_mapping_to_buffer(
203             virtual_file_mapping,
204             expressions,
205             mapping_regions,
206             coverage_mapping_buffer,
207         );
208     }
209
210     /// Construct coverage map header and the array of function records, and combine them into the
211     /// coverage map. Save the coverage map data into the LLVM IR as a static global using a
212     /// specific, well-known section and name.
213     fn generate_coverage_map<'ll>(
214         self,
215         cx: &CodegenCx<'ll, '_>,
216         version: u32,
217         filenames_size: usize,
218         filenames_val: &'ll llvm::Value,
219     ) -> &'ll llvm::Value {
220         debug!("cov map: filenames_size = {}, 0-based version = {}", filenames_size, version);
221
222         // Create the coverage data header (Note, fields 0 and 2 are now always zero,
223         // as of `llvm::coverage::CovMapVersion::Version4`.)
224         let zero_was_n_records_val = cx.const_u32(0);
225         let filenames_size_val = cx.const_u32(filenames_size as u32);
226         let zero_was_coverage_size_val = cx.const_u32(0);
227         let version_val = cx.const_u32(version);
228         let cov_data_header_val = cx.const_struct(
229             &[zero_was_n_records_val, filenames_size_val, zero_was_coverage_size_val, version_val],
230             /*packed=*/ false,
231         );
232
233         // Create the complete LLVM coverage data value to add to the LLVM IR
234         cx.const_struct(&[cov_data_header_val, filenames_val], /*packed=*/ false)
235     }
236 }
237
238 /// Construct a function record and combine it with the function's coverage mapping data.
239 /// Save the function record into the LLVM IR as a static global using a
240 /// specific, well-known section and name.
241 fn save_function_record(
242     cx: &CodegenCx<'_, '_>,
243     mangled_function_name: String,
244     source_hash: u64,
245     filenames_ref: u64,
246     coverage_mapping_buffer: Vec<u8>,
247     is_used: bool,
248 ) {
249     // Concatenate the encoded coverage mappings
250     let coverage_mapping_size = coverage_mapping_buffer.len();
251     let coverage_mapping_val = cx.const_bytes(&coverage_mapping_buffer);
252
253     let func_name_hash = coverageinfo::hash_str(&mangled_function_name);
254     let func_name_hash_val = cx.const_u64(func_name_hash);
255     let coverage_mapping_size_val = cx.const_u32(coverage_mapping_size as u32);
256     let source_hash_val = cx.const_u64(source_hash);
257     let filenames_ref_val = cx.const_u64(filenames_ref);
258     let func_record_val = cx.const_struct(
259         &[
260             func_name_hash_val,
261             coverage_mapping_size_val,
262             source_hash_val,
263             filenames_ref_val,
264             coverage_mapping_val,
265         ],
266         /*packed=*/ true,
267     );
268
269     coverageinfo::save_func_record_to_mod(cx, func_name_hash, func_record_val, is_used);
270 }
271
272 /// When finalizing the coverage map, `FunctionCoverage` only has the `CodeRegion`s and counters for
273 /// the functions that went through codegen; such as public functions and "used" functions
274 /// (functions referenced by other "used" or public items). Any other functions considered unused,
275 /// or "Unreachable", were still parsed and processed through the MIR stage, but were not
276 /// codegenned. (Note that `-Clink-dead-code` can force some unused code to be codegenned, but
277 /// that flag is known to cause other errors, when combined with `-C instrument-coverage`; and
278 /// `-Clink-dead-code` will not generate code for unused generic functions.)
279 ///
280 /// We can find the unused functions (including generic functions) by the set difference of all MIR
281 /// `DefId`s (`tcx` query `mir_keys`) minus the codegenned `DefId`s (`tcx` query
282 /// `codegened_and_inlined_items`).
283 ///
284 /// These unused functions are then codegen'd in one of the CGUs which is marked as the
285 /// "code coverage dead code cgu" during the partitioning process. This prevents us from generating
286 /// code regions for the same function more than once which can lead to linker errors regarding
287 /// duplicate symbols.
288 fn add_unused_functions<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) {
289     assert!(cx.codegen_unit.is_code_coverage_dead_code_cgu());
290
291     let tcx = cx.tcx;
292
293     let ignore_unused_generics = tcx.sess.instrument_coverage_except_unused_generics();
294
295     let eligible_def_ids: DefIdSet = tcx
296         .mir_keys(())
297         .iter()
298         .filter_map(|local_def_id| {
299             let def_id = local_def_id.to_def_id();
300             let kind = tcx.def_kind(def_id);
301             // `mir_keys` will give us `DefId`s for all kinds of things, not
302             // just "functions", like consts, statics, etc. Filter those out.
303             // If `ignore_unused_generics` was specified, filter out any
304             // generic functions from consideration as well.
305             if !matches!(
306                 kind,
307                 DefKind::Fn | DefKind::AssocFn | DefKind::Closure | DefKind::Generator
308             ) {
309                 return None;
310             } else if ignore_unused_generics
311                 && tcx.generics_of(def_id).requires_monomorphization(tcx)
312             {
313                 return None;
314             }
315             Some(local_def_id.to_def_id())
316         })
317         .collect();
318
319     let codegenned_def_ids = tcx.codegened_and_inlined_items(());
320
321     for &non_codegenned_def_id in eligible_def_ids.difference(codegenned_def_ids) {
322         let codegen_fn_attrs = tcx.codegen_fn_attrs(non_codegenned_def_id);
323
324         // If a function is marked `#[no_coverage]`, then skip generating a
325         // dead code stub for it.
326         if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_COVERAGE) {
327             debug!("skipping unused fn marked #[no_coverage]: {:?}", non_codegenned_def_id);
328             continue;
329         }
330
331         debug!("generating unused fn: {:?}", non_codegenned_def_id);
332         cx.define_unused_fn(non_codegenned_def_id);
333     }
334 }