3 use crate::builder::Builder;
4 use crate::common::CodegenCx;
8 use rustc_codegen_ssa::coverageinfo::map::*;
9 use rustc_codegen_ssa::traits::{
10 BaseTypeMethods, CoverageInfoBuilderMethods, CoverageInfoMethods, StaticMethods,
12 use rustc_data_structures::fx::FxHashMap;
13 use rustc_llvm::RustString;
14 use rustc_middle::ty::Instance;
16 use std::cell::RefCell;
17 use std::ffi::CString;
21 const COVMAP_VAR_ALIGN_BYTES: usize = 8;
23 /// A context object for maintaining all state needed by the coverageinfo module.
24 pub struct CrateCoverageContext<'tcx> {
25 // Coverage region data for each instrumented function identified by DefId.
26 pub(crate) function_coverage_map: RefCell<FxHashMap<Instance<'tcx>, FunctionCoverage<'tcx>>>,
29 impl<'tcx> CrateCoverageContext<'tcx> {
30 pub fn new() -> Self {
31 Self { function_coverage_map: Default::default() }
34 pub fn take_function_coverage_map(&self) -> FxHashMap<Instance<'tcx>, FunctionCoverage<'tcx>> {
35 self.function_coverage_map.replace(FxHashMap::default())
39 impl CoverageInfoMethods for CodegenCx<'ll, 'tcx> {
40 fn coverageinfo_finalize(&self) {
41 mapgen::finalize(self)
45 impl CoverageInfoBuilderMethods<'tcx> for Builder<'a, 'll, 'tcx> {
46 fn add_counter_region(
48 instance: Instance<'tcx>,
49 function_source_hash: u64,
55 "adding counter to coverage_regions: instance={:?}, function_source_hash={}, id={}, \
57 instance, function_source_hash, id, start_byte_pos, end_byte_pos,
59 let mut coverage_regions = self.coverage_context().function_coverage_map.borrow_mut();
62 .or_insert_with(|| FunctionCoverage::new(self.tcx, instance))
63 .add_counter(function_source_hash, id, start_byte_pos, end_byte_pos);
66 fn add_counter_expression_region(
68 instance: Instance<'tcx>,
69 id_descending_from_max: u32,
77 "adding counter expression to coverage_regions: instance={:?}, id={}, {} {:?} {}, \
79 instance, id_descending_from_max, lhs, op, rhs, start_byte_pos, end_byte_pos,
81 let mut coverage_regions = self.coverage_context().function_coverage_map.borrow_mut();
84 .or_insert_with(|| FunctionCoverage::new(self.tcx, instance))
85 .add_counter_expression(
86 id_descending_from_max,
95 fn add_unreachable_region(
97 instance: Instance<'tcx>,
102 "adding unreachable code to coverage_regions: instance={:?}, byte range {}..{}",
103 instance, start_byte_pos, end_byte_pos,
105 let mut coverage_regions = self.coverage_context().function_coverage_map.borrow_mut();
108 .or_insert_with(|| FunctionCoverage::new(self.tcx, instance))
109 .add_unreachable_region(start_byte_pos, end_byte_pos);
113 /// Aligns to C++ struct llvm::coverage::Counter::CounterKind.
114 /// The order of discrimiators is important.
115 #[derive(Copy, Clone, Debug)]
118 /// A CodeRegion associates some code with a counter
121 /// An ExpansionRegion represents a file expansion region that associates
122 /// a source range with the expansion of a virtual source file, such as
123 /// for a macro instantiation or #include file.
126 /// A SkippedRegion represents a source range with code that was skipped
127 /// by a preprocessor or similar means.
130 /// A GapRegion is like a CodeRegion, but its count is only set as the
131 /// line execution count when its the only region in the line.
135 /// This struct provides LLVM's representation of a "CoverageMappingRegion", encoded into the
136 /// coverage map in accordance with LLVM's "Coverage Mapping Format". The struct composes fields
137 /// representing the `Counter` type and value(s) (injected counter ID, or expression type and
138 /// operands), the source file (an indirect index into a "filenames array", encoded separately),
139 /// and source location (start and end positions of the represented code region).
141 /// Aligns to C++ struct llvm::coverage::CounterMappingRegion.
142 /// The order of fields is important.
143 #[derive(Copy, Clone, Debug)]
145 pub struct CounterMappingRegion {
146 /// The counter type and type-dependent counter data, if any.
149 /// An indirect reference to the source filename. In the LLVM Coverage Mapping Format, the
150 /// file_id is an index into a function-specific `virtual_file_mapping` array of indexes that,
151 /// in turn, are used to look up the filename for this region.
154 /// If the `RegionKind` is an `ExpansionRegion`, the `expanded_file_id` can be used to find the
155 /// mapping regions created as a result of macro expansion, by checking if their file id matches
156 /// the expanded file id.
157 expanded_file_id: u32,
159 /// 1-based starting line of the mapping region.
162 /// 1-based starting column of the mapping region.
165 /// 1-based ending line of the mapping region.
168 /// 1-based ending column of the mapping region. If the high bit is set, the current mapping
169 /// region is a gap area.
175 impl CounterMappingRegion {
192 kind: RegionKind::CodeRegion,
196 pub fn expansion_region(
198 expanded_file_id: u32,
205 counter: Counter::zero(),
212 kind: RegionKind::ExpansionRegion,
216 pub fn skipped_region(
224 counter: Counter::zero(),
231 kind: RegionKind::SkippedRegion,
250 end_col: ((1 as u32) << 31) | end_col,
251 kind: RegionKind::GapRegion,
256 pub(crate) fn write_filenames_section_to_buffer(filenames: &Vec<CString>, buffer: &RustString) {
257 let c_str_vec = filenames.iter().map(|cstring| cstring.as_ptr()).collect::<Vec<_>>();
259 llvm::LLVMRustCoverageWriteFilenamesSectionToBuffer(
267 pub(crate) fn write_mapping_to_buffer(
268 virtual_file_mapping: Vec<u32>,
269 expressions: Vec<CounterExpression>,
270 mut mapping_regions: Vec<CounterMappingRegion>,
274 llvm::LLVMRustCoverageWriteMappingToBuffer(
275 virtual_file_mapping.as_ptr(),
276 virtual_file_mapping.len() as c_uint,
277 expressions.as_ptr(),
278 expressions.len() as c_uint,
279 mapping_regions.as_mut_ptr(),
280 mapping_regions.len() as c_uint,
286 pub(crate) fn compute_hash(name: &str) -> u64 {
287 let name = CString::new(name).expect("null error converting hashable name to C string");
288 unsafe { llvm::LLVMRustCoverageComputeHash(name.as_ptr()) }
291 pub(crate) fn mapping_version() -> u32 {
292 unsafe { llvm::LLVMRustCoverageMappingVersion() }
295 pub(crate) fn save_map_to_mod<'ll, 'tcx>(
296 cx: &CodegenCx<'ll, 'tcx>,
297 cov_data_val: &'ll llvm::Value,
299 let covmap_var_name = llvm::build_string(|s| unsafe {
300 llvm::LLVMRustCoverageWriteMappingVarNameToString(s);
302 .expect("Rust Coverage Mapping var name failed UTF-8 conversion");
303 debug!("covmap var name: {:?}", covmap_var_name);
305 let covmap_section_name = llvm::build_string(|s| unsafe {
306 llvm::LLVMRustCoverageWriteSectionNameToString(cx.llmod, s);
308 .expect("Rust Coverage section name failed UTF-8 conversion");
309 debug!("covmap section name: {:?}", covmap_section_name);
311 let llglobal = llvm::add_global(cx.llmod, cx.val_ty(cov_data_val), &covmap_var_name);
312 llvm::set_initializer(llglobal, cov_data_val);
313 llvm::set_global_constant(llglobal, true);
314 llvm::set_linkage(llglobal, llvm::Linkage::InternalLinkage);
315 llvm::set_section(llglobal, &covmap_section_name);
316 llvm::set_alignment(llglobal, COVMAP_VAR_ALIGN_BYTES);
317 cx.add_used_global(llglobal);