Skip to main content

rustc_mir_transform/coverage/
query.rs

1use rustc_hir::attrs::CoverageAttrKind;
2use rustc_hir::find_attr;
3use rustc_index::bit_set::DenseBitSet;
4use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
5use rustc_middle::mir::coverage::{BasicCoverageBlock, CoverageIdsInfo, CoverageKind, MappingKind};
6use rustc_middle::mir::{Body, Statement, StatementKind};
7use rustc_middle::ty::{self, TyCtxt};
8use rustc_middle::util::Providers;
9use rustc_span::def_id::LocalDefId;
10use tracing::trace;
11
12use crate::coverage::counters::node_flow::make_node_counters;
13use crate::coverage::counters::{CoverageCounters, transcribe_counters};
14
15/// Registers query/hook implementations related to coverage.
16pub(crate) fn provide(providers: &mut Providers) {
17    providers.hooks.is_eligible_for_coverage = is_eligible_for_coverage;
18    providers.queries.coverage_attr_on = coverage_attr_on;
19    providers.queries.coverage_ids_info = coverage_ids_info;
20}
21
22/// Hook implementation for [`TyCtxt::is_eligible_for_coverage`].
23fn is_eligible_for_coverage(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
24    // Only instrument functions, methods, and closures (not constants since they are evaluated
25    // at compile time by Miri).
26    // FIXME(#73156): Handle source code coverage in const eval, but note, if and when const
27    // expressions get coverage spans, we will probably have to "carve out" space for const
28    // expressions from coverage spans in enclosing MIR's, like we do for closures. (That might
29    // be tricky if const expressions have no corresponding statements in the enclosing MIR.
30    // Closures are carved out by their initial `Assign` statement.)
31    if !tcx.def_kind(def_id).is_fn_like() {
32        trace!("InstrumentCoverage skipped for {def_id:?} (not an fn-like)");
33        return false;
34    }
35
36    if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::NAKED) {
37        trace!("InstrumentCoverage skipped for {def_id:?} (`#[naked]`)");
38        return false;
39    }
40
41    if !tcx.coverage_attr_on(def_id) {
42        trace!("InstrumentCoverage skipped for {def_id:?} (`#[coverage(off)]`)");
43        return false;
44    }
45
46    true
47}
48
49/// Query implementation for `coverage_attr_on`.
50fn coverage_attr_on(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
51    // Check for a `#[coverage(..)]` attribute on this def.
52    if let Some(kind) = find_attr!(tcx, def_id, Coverage(_sp, kind) => kind) {
53        match kind {
54            CoverageAttrKind::On => return true,
55            CoverageAttrKind::Off => return false,
56        }
57    };
58
59    // Treat `#[automatically_derived]` as an implied `#[coverage(off)]`, on
60    // the assumption that most users won't want coverage for derived impls.
61    //
62    // This affects not just the associated items of an impl block, but also
63    // any closures and other nested functions within those associated items.
64    if tcx.is_automatically_derived(def_id.to_def_id()) {
65        return false;
66    }
67
68    // Check the parent def (and so on recursively) until we find an
69    // enclosing attribute or reach the crate root.
70    match tcx.opt_local_parent(def_id) {
71        Some(parent) => tcx.coverage_attr_on(parent),
72        // We reached the crate root without seeing a coverage attribute, so
73        // allow coverage instrumentation by default.
74        None => true,
75    }
76}
77
78/// Query implementation for `coverage_ids_info`.
79fn coverage_ids_info<'tcx>(
80    tcx: TyCtxt<'tcx>,
81    instance_def: ty::InstanceKind<'tcx>,
82) -> Option<CoverageIdsInfo> {
83    let mir_body = tcx.instance_mir(instance_def);
84    let fn_cov_info = mir_body.function_coverage_info.as_deref()?;
85
86    // Scan through the final MIR to see which BCBs survived MIR opts.
87    // Any BCB not in this set was optimized away.
88    let mut bcbs_seen = DenseBitSet::new_empty(fn_cov_info.priority_list.len());
89    for kind in all_coverage_in_mir_body(mir_body) {
90        match *kind {
91            CoverageKind::VirtualCounter { bcb } => {
92                bcbs_seen.insert(bcb);
93            }
94            _ => {}
95        }
96    }
97
98    // Determine the set of BCBs that are referred to by mappings, and therefore
99    // need a counter. Any node not in this set will only get a counter if it
100    // is part of the counter expression for a node that is in the set.
101    let mut bcb_needs_counter =
102        DenseBitSet::<BasicCoverageBlock>::new_empty(fn_cov_info.priority_list.len());
103    for mapping in &fn_cov_info.mappings {
104        match mapping.kind {
105            MappingKind::Code { bcb } => {
106                bcb_needs_counter.insert(bcb);
107            }
108            MappingKind::Branch { true_bcb, false_bcb } => {
109                bcb_needs_counter.insert(true_bcb);
110                bcb_needs_counter.insert(false_bcb);
111            }
112        }
113    }
114
115    // Clone the priority list so that we can re-sort it.
116    let mut priority_list = fn_cov_info.priority_list.clone();
117    // The first ID in the priority list represents the synthetic "sink" node,
118    // and must remain first so that it _never_ gets a physical counter.
119    debug_assert_eq!(priority_list[0], priority_list.iter().copied().max().unwrap());
120    assert!(!bcbs_seen.contains(priority_list[0]));
121    // Partition the priority list, so that unreachable nodes (removed by MIR opts)
122    // are sorted later and therefore are _more_ likely to get a physical counter.
123    // This is counter-intuitive, but it means that `transcribe_counters` can
124    // easily skip those unused physical counters and replace them with zero.
125    // (The original ordering remains in effect within both partitions.)
126    priority_list[1..].sort_by_key(|&bcb| !bcbs_seen.contains(bcb));
127
128    let node_counters = make_node_counters(&fn_cov_info.node_flow_data, &priority_list);
129    let coverage_counters = transcribe_counters(&node_counters, &bcb_needs_counter, &bcbs_seen);
130
131    let CoverageCounters {
132        phys_counter_for_node, next_counter_id, node_counters, expressions, ..
133    } = coverage_counters;
134
135    Some(CoverageIdsInfo {
136        num_counters: next_counter_id.as_u32(),
137        phys_counter_for_node,
138        term_for_bcb: node_counters,
139        expressions,
140    })
141}
142
143fn all_coverage_in_mir_body<'a, 'tcx>(
144    body: &'a Body<'tcx>,
145) -> impl Iterator<Item = &'a CoverageKind> {
146    body.basic_blocks.iter().flat_map(|bb_data| &bb_data.statements).filter_map(|statement| {
147        match statement.kind {
148            StatementKind::Coverage(ref kind) if !is_inlined(body, statement) => Some(kind),
149            _ => None,
150        }
151    })
152}
153
154fn is_inlined(body: &Body<'_>, statement: &Statement<'_>) -> bool {
155    let scope_data = &body.source_scopes[statement.source_info.scope];
156    scope_data.inlined.is_some() || scope_data.inlined_parent_scope.is_some()
157}