rustc_mir_transform/coverage/
query.rs

1use rustc_hir::attrs::{AttributeKind, 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) =
53        find_attr!(tcx.get_all_attrs(def_id), AttributeKind::Coverage(_sp, kind) => kind)
54    {
55        match kind {
56            CoverageAttrKind::On => return true,
57            CoverageAttrKind::Off => return false,
58        }
59    };
60
61    // Treat `#[automatically_derived]` as an implied `#[coverage(off)]`, on
62    // the assumption that most users won't want coverage for derived impls.
63    //
64    // This affects not just the associated items of an impl block, but also
65    // any closures and other nested functions within those associated items.
66    if tcx.is_automatically_derived(def_id.to_def_id()) {
67        return false;
68    }
69
70    // Check the parent def (and so on recursively) until we find an
71    // enclosing attribute or reach the crate root.
72    match tcx.opt_local_parent(def_id) {
73        Some(parent) => tcx.coverage_attr_on(parent),
74        // We reached the crate root without seeing a coverage attribute, so
75        // allow coverage instrumentation by default.
76        None => true,
77    }
78}
79
80/// Query implementation for `coverage_ids_info`.
81fn coverage_ids_info<'tcx>(
82    tcx: TyCtxt<'tcx>,
83    instance_def: ty::InstanceKind<'tcx>,
84) -> Option<CoverageIdsInfo> {
85    let mir_body = tcx.instance_mir(instance_def);
86    let fn_cov_info = mir_body.function_coverage_info.as_deref()?;
87
88    // Scan through the final MIR to see which BCBs survived MIR opts.
89    // Any BCB not in this set was optimized away.
90    let mut bcbs_seen = DenseBitSet::new_empty(fn_cov_info.priority_list.len());
91    for kind in all_coverage_in_mir_body(mir_body) {
92        match *kind {
93            CoverageKind::VirtualCounter { bcb } => {
94                bcbs_seen.insert(bcb);
95            }
96            _ => {}
97        }
98    }
99
100    // Determine the set of BCBs that are referred to by mappings, and therefore
101    // need a counter. Any node not in this set will only get a counter if it
102    // is part of the counter expression for a node that is in the set.
103    let mut bcb_needs_counter =
104        DenseBitSet::<BasicCoverageBlock>::new_empty(fn_cov_info.priority_list.len());
105    for mapping in &fn_cov_info.mappings {
106        match mapping.kind {
107            MappingKind::Code { bcb } => {
108                bcb_needs_counter.insert(bcb);
109            }
110            MappingKind::Branch { true_bcb, false_bcb } => {
111                bcb_needs_counter.insert(true_bcb);
112                bcb_needs_counter.insert(false_bcb);
113            }
114            MappingKind::MCDCBranch { true_bcb, false_bcb, mcdc_params: _ } => {
115                bcb_needs_counter.insert(true_bcb);
116                bcb_needs_counter.insert(false_bcb);
117            }
118            MappingKind::MCDCDecision(_) => {}
119        }
120    }
121
122    // Clone the priority list so that we can re-sort it.
123    let mut priority_list = fn_cov_info.priority_list.clone();
124    // The first ID in the priority list represents the synthetic "sink" node,
125    // and must remain first so that it _never_ gets a physical counter.
126    debug_assert_eq!(priority_list[0], priority_list.iter().copied().max().unwrap());
127    assert!(!bcbs_seen.contains(priority_list[0]));
128    // Partition the priority list, so that unreachable nodes (removed by MIR opts)
129    // are sorted later and therefore are _more_ likely to get a physical counter.
130    // This is counter-intuitive, but it means that `transcribe_counters` can
131    // easily skip those unused physical counters and replace them with zero.
132    // (The original ordering remains in effect within both partitions.)
133    priority_list[1..].sort_by_key(|&bcb| !bcbs_seen.contains(bcb));
134
135    let node_counters = make_node_counters(&fn_cov_info.node_flow_data, &priority_list);
136    let coverage_counters = transcribe_counters(&node_counters, &bcb_needs_counter, &bcbs_seen);
137
138    let CoverageCounters {
139        phys_counter_for_node, next_counter_id, node_counters, expressions, ..
140    } = coverage_counters;
141
142    Some(CoverageIdsInfo {
143        num_counters: next_counter_id.as_u32(),
144        phys_counter_for_node,
145        term_for_bcb: node_counters,
146        expressions,
147    })
148}
149
150fn all_coverage_in_mir_body<'a, 'tcx>(
151    body: &'a Body<'tcx>,
152) -> impl Iterator<Item = &'a CoverageKind> {
153    body.basic_blocks.iter().flat_map(|bb_data| &bb_data.statements).filter_map(|statement| {
154        match statement.kind {
155            StatementKind::Coverage(ref kind) if !is_inlined(body, statement) => Some(kind),
156            _ => None,
157        }
158    })
159}
160
161fn is_inlined(body: &Body<'_>, statement: &Statement<'_>) -> bool {
162    let scope_data = &body.source_scopes[statement.source_info.scope];
163    scope_data.inlined.is_some() || scope_data.inlined_parent_scope.is_some()
164}