Skip to content

Commit 6fc0fe7

Browse files
committed
coverage: Use a query to identify which counter/expression IDs are used
1 parent 121a17c commit 6fc0fe7

File tree

7 files changed

+93
-92
lines changed

7 files changed

+93
-92
lines changed

Diff for: compiler/rustc_codegen_llvm/src/coverageinfo/map_data.rs

+15-57
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
use rustc_data_structures::captures::Captures;
22
use rustc_data_structures::fx::FxIndexSet;
33
use rustc_index::bit_set::BitSet;
4+
use rustc_middle::mir::CoverageIdsInfo;
45
use rustc_middle::mir::coverage::{
56
CounterId, CovTerm, Expression, ExpressionId, FunctionCoverageInfo, Mapping, MappingKind, Op,
67
SourceRegion,
78
};
89
use rustc_middle::ty::Instance;
9-
use tracing::{debug, instrument};
10+
use tracing::debug;
1011

1112
use crate::coverageinfo::ffi::{Counter, CounterExpression, ExprKind};
1213

@@ -16,39 +17,33 @@ use crate::coverageinfo::ffi::{Counter, CounterExpression, ExprKind};
1617
pub(crate) struct FunctionCoverageCollector<'tcx> {
1718
/// Coverage info that was attached to this function by the instrumentor.
1819
function_coverage_info: &'tcx FunctionCoverageInfo,
20+
ids_info: &'tcx CoverageIdsInfo,
1921
is_used: bool,
20-
21-
/// Tracks which counters have been seen, so that we can identify mappings
22-
/// to counters that were optimized out, and set them to zero.
23-
counters_seen: BitSet<CounterId>,
24-
/// Contains all expression IDs that have been seen in an `ExpressionUsed`
25-
/// coverage statement, plus all expression IDs that aren't directly used
26-
/// by any mappings (and therefore do not have expression-used statements).
27-
/// After MIR traversal is finished, we can conclude that any IDs missing
28-
/// from this set must have had their statements deleted by MIR opts.
29-
expressions_seen: BitSet<ExpressionId>,
3022
}
3123

3224
impl<'tcx> FunctionCoverageCollector<'tcx> {
3325
/// Creates a new set of coverage data for a used (called) function.
3426
pub(crate) fn new(
3527
instance: Instance<'tcx>,
3628
function_coverage_info: &'tcx FunctionCoverageInfo,
29+
ids_info: &'tcx CoverageIdsInfo,
3730
) -> Self {
38-
Self::create(instance, function_coverage_info, true)
31+
Self::create(instance, function_coverage_info, ids_info, true)
3932
}
4033

4134
/// Creates a new set of coverage data for an unused (never called) function.
4235
pub(crate) fn unused(
4336
instance: Instance<'tcx>,
4437
function_coverage_info: &'tcx FunctionCoverageInfo,
38+
ids_info: &'tcx CoverageIdsInfo,
4539
) -> Self {
46-
Self::create(instance, function_coverage_info, false)
40+
Self::create(instance, function_coverage_info, ids_info, false)
4741
}
4842

4943
fn create(
5044
instance: Instance<'tcx>,
5145
function_coverage_info: &'tcx FunctionCoverageInfo,
46+
ids_info: &'tcx CoverageIdsInfo,
5247
is_used: bool,
5348
) -> Self {
5449
let num_counters = function_coverage_info.num_counters;
@@ -58,44 +53,7 @@ impl<'tcx> FunctionCoverageCollector<'tcx> {
5853
num_counters={num_counters}, num_expressions={num_expressions}, is_used={is_used}"
5954
);
6055

61-
// Create a filled set of expression IDs, so that expressions not
62-
// directly used by mappings will be treated as "seen".
63-
// (If they end up being unused, LLVM will delete them for us.)
64-
let mut expressions_seen = BitSet::new_filled(num_expressions);
65-
// For each expression ID that is directly used by one or more mappings,
66-
// mark it as not-yet-seen. This indicates that we expect to see a
67-
// corresponding `ExpressionUsed` statement during MIR traversal.
68-
for mapping in function_coverage_info.mappings.iter() {
69-
// Currently we only worry about ordinary code mappings.
70-
// For branch and MC/DC mappings, expressions might not correspond
71-
// to any particular point in the control-flow graph.
72-
// (Keep this in sync with the injection of `ExpressionUsed`
73-
// statements in the `InstrumentCoverage` MIR pass.)
74-
if let MappingKind::Code(term) = mapping.kind
75-
&& let CovTerm::Expression(id) = term
76-
{
77-
expressions_seen.remove(id);
78-
}
79-
}
80-
81-
Self {
82-
function_coverage_info,
83-
is_used,
84-
counters_seen: BitSet::new_empty(num_counters),
85-
expressions_seen,
86-
}
87-
}
88-
89-
/// Marks a counter ID as having been seen in a counter-increment statement.
90-
#[instrument(level = "debug", skip(self))]
91-
pub(crate) fn mark_counter_id_seen(&mut self, id: CounterId) {
92-
self.counters_seen.insert(id);
93-
}
94-
95-
/// Marks an expression ID as having been seen in an expression-used statement.
96-
#[instrument(level = "debug", skip(self))]
97-
pub(crate) fn mark_expression_id_seen(&mut self, id: ExpressionId) {
98-
self.expressions_seen.insert(id);
56+
Self { function_coverage_info, ids_info, is_used }
9957
}
10058

10159
/// Identify expressions that will always have a value of zero, and note
@@ -117,7 +75,7 @@ impl<'tcx> FunctionCoverageCollector<'tcx> {
11775
// (By construction, expressions can only refer to other expressions
11876
// that have lower IDs, so one pass is sufficient.)
11977
for (id, expression) in self.function_coverage_info.expressions.iter_enumerated() {
120-
if !self.is_used || !self.expressions_seen.contains(id) {
78+
if !self.is_used || !self.ids_info.expressions_seen.contains(id) {
12179
// If an expression was not seen, it must have been optimized away,
12280
// so any operand that refers to it can be replaced with zero.
12381
zero_expressions.insert(id);
@@ -146,7 +104,7 @@ impl<'tcx> FunctionCoverageCollector<'tcx> {
146104
assert_operand_expression_is_lower(id);
147105
}
148106

149-
if is_zero_term(&self.counters_seen, &zero_expressions, *operand) {
107+
if is_zero_term(&self.ids_info.counters_seen, &zero_expressions, *operand) {
150108
*operand = CovTerm::Zero;
151109
}
152110
};
@@ -172,17 +130,17 @@ impl<'tcx> FunctionCoverageCollector<'tcx> {
172130

173131
pub(crate) fn into_finished(self) -> FunctionCoverage<'tcx> {
174132
let zero_expressions = self.identify_zero_expressions();
175-
let FunctionCoverageCollector { function_coverage_info, is_used, counters_seen, .. } = self;
133+
let FunctionCoverageCollector { function_coverage_info, ids_info, is_used, .. } = self;
176134

177-
FunctionCoverage { function_coverage_info, is_used, counters_seen, zero_expressions }
135+
FunctionCoverage { function_coverage_info, ids_info, is_used, zero_expressions }
178136
}
179137
}
180138

181139
pub(crate) struct FunctionCoverage<'tcx> {
182140
pub(crate) function_coverage_info: &'tcx FunctionCoverageInfo,
141+
ids_info: &'tcx CoverageIdsInfo,
183142
is_used: bool,
184143

185-
counters_seen: BitSet<CounterId>,
186144
zero_expressions: ZeroExpressions,
187145
}
188146

@@ -238,7 +196,7 @@ impl<'tcx> FunctionCoverage<'tcx> {
238196
}
239197

240198
fn is_zero_term(&self, term: CovTerm) -> bool {
241-
!self.is_used || is_zero_term(&self.counters_seen, &self.zero_expressions, term)
199+
!self.is_used || is_zero_term(&self.ids_info.counters_seen, &self.zero_expressions, term)
242200
}
243201
}
244202

Diff for: compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -536,7 +536,11 @@ fn add_unused_function_coverage<'tcx>(
536536
);
537537

538538
// An unused function's mappings will all be rewritten to map to zero.
539-
let function_coverage = FunctionCoverageCollector::unused(instance, function_coverage_info);
539+
let function_coverage = FunctionCoverageCollector::unused(
540+
instance,
541+
function_coverage_info,
542+
tcx.coverage_ids_info(instance.def),
543+
);
540544

541545
cx.coverage_cx().function_coverage_map.borrow_mut().insert(instance, function_coverage);
542546
}

Diff for: compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs

+14-14
Original file line numberDiff line numberDiff line change
@@ -157,27 +157,28 @@ impl<'tcx> CoverageInfoBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> {
157157
return;
158158
};
159159

160-
let mut coverage_map = coverage_cx.function_coverage_map.borrow_mut();
161-
let func_coverage = coverage_map
162-
.entry(instance)
163-
.or_insert_with(|| FunctionCoverageCollector::new(instance, function_coverage_info));
160+
// Mark the instance as used in this CGU, for coverage purposes.
161+
// This includes functions that were not partitioned into this CGU,
162+
// but were MIR-inlined into one of this CGU's functions.
163+
coverage_cx.function_coverage_map.borrow_mut().entry(instance).or_insert_with(|| {
164+
FunctionCoverageCollector::new(
165+
instance,
166+
function_coverage_info,
167+
bx.tcx.coverage_ids_info(instance.def),
168+
)
169+
});
164170

165171
match *kind {
166172
CoverageKind::SpanMarker | CoverageKind::BlockMarker { .. } => unreachable!(
167173
"marker statement {kind:?} should have been removed by CleanupPostBorrowck"
168174
),
169175
CoverageKind::CounterIncrement { id } => {
170-
func_coverage.mark_counter_id_seen(id);
171-
// We need to explicitly drop the `RefMut` before calling into
172-
// `instrprof_increment`, as that needs an exclusive borrow.
173-
drop(coverage_map);
174-
175176
// The number of counters passed to `llvm.instrprof.increment` might
176177
// be smaller than the number originally inserted by the instrumentor,
177178
// if some high-numbered counters were removed by MIR optimizations.
178179
// If so, LLVM's profiler runtime will use fewer physical counters.
179180
let num_counters =
180-
bx.tcx().coverage_ids_info(instance.def).max_counter_id.as_u32() + 1;
181+
bx.tcx().coverage_ids_info(instance.def).num_counters_after_mir_opts();
181182
assert!(
182183
num_counters as usize <= function_coverage_info.num_counters,
183184
"num_counters disagreement: query says {num_counters} but function info only has {}",
@@ -194,19 +195,18 @@ impl<'tcx> CoverageInfoBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> {
194195
);
195196
bx.instrprof_increment(fn_name, hash, num_counters, index);
196197
}
197-
CoverageKind::ExpressionUsed { id } => {
198-
func_coverage.mark_expression_id_seen(id);
198+
CoverageKind::ExpressionUsed { id: _ } => {
199+
// Expression-used statements are markers that are handled by
200+
// `coverage_ids_info`, so there's nothing to codegen here.
199201
}
200202
CoverageKind::CondBitmapUpdate { index, decision_depth } => {
201-
drop(coverage_map);
202203
let cond_bitmap = coverage_cx
203204
.try_get_mcdc_condition_bitmap(&instance, decision_depth)
204205
.expect("mcdc cond bitmap should have been allocated for updating");
205206
let cond_index = bx.const_i32(index as i32);
206207
bx.mcdc_condbitmap_update(cond_index, cond_bitmap);
207208
}
208209
CoverageKind::TestVectorBitmapUpdate { bitmap_idx, decision_depth } => {
209-
drop(coverage_map);
210210
let cond_bitmap =
211211
coverage_cx.try_get_mcdc_condition_bitmap(&instance, decision_depth).expect(
212212
"mcdc cond bitmap should have been allocated for merging \

Diff for: compiler/rustc_middle/src/mir/query.rs

+13-3
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use rustc_abi::{FieldIdx, VariantIdx};
88
use rustc_data_structures::fx::FxIndexMap;
99
use rustc_errors::ErrorGuaranteed;
1010
use rustc_hir::def_id::LocalDefId;
11-
use rustc_index::bit_set::BitMatrix;
11+
use rustc_index::bit_set::{BitMatrix, BitSet};
1212
use rustc_index::{Idx, IndexVec};
1313
use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable};
1414
use rustc_span::Span;
@@ -358,12 +358,22 @@ pub struct DestructuredConstant<'tcx> {
358358
/// Used by the `coverage_ids_info` query.
359359
#[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable)]
360360
pub struct CoverageIdsInfo {
361-
/// Coverage codegen needs to know the highest counter ID that is ever
361+
pub counters_seen: BitSet<mir::coverage::CounterId>,
362+
pub expressions_seen: BitSet<mir::coverage::ExpressionId>,
363+
}
364+
365+
impl CoverageIdsInfo {
366+
/// Coverage codegen needs to know how many coverage counters are ever
362367
/// incremented within a function, so that it can set the `num-counters`
363368
/// argument of the `llvm.instrprof.increment` intrinsic.
364369
///
365370
/// This may be less than the highest counter ID emitted by the
366371
/// InstrumentCoverage MIR pass, if the highest-numbered counter increments
367372
/// were removed by MIR optimizations.
368-
pub max_counter_id: mir::coverage::CounterId,
373+
pub fn num_counters_after_mir_opts(&self) -> u32 {
374+
// FIXME(Zalathar): Currently this treats an unused counter as "used"
375+
// if its ID is less than that of the highest counter that really is
376+
// used. Fixing this would require adding a renumbering step somewhere.
377+
self.counters_seen.last_set_in(..).map_or(0, |max| max.as_u32() + 1)
378+
}
369379
}

Diff for: compiler/rustc_mir_transform/src/coverage/query.rs

+38-9
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use rustc_data_structures::captures::Captures;
2+
use rustc_index::bit_set::BitSet;
23
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
3-
use rustc_middle::mir::coverage::{CounterId, CoverageKind};
4+
use rustc_middle::mir::coverage::{CovTerm, CoverageKind, MappingKind};
45
use rustc_middle::mir::{Body, CoverageIdsInfo, Statement, StatementKind};
56
use rustc_middle::query::TyCtxtAt;
67
use rustc_middle::ty::{self, TyCtxt};
@@ -86,15 +87,43 @@ fn coverage_ids_info<'tcx>(
8687
) -> CoverageIdsInfo {
8788
let mir_body = tcx.instance_mir(instance_def);
8889

89-
let max_counter_id = all_coverage_in_mir_body(mir_body)
90-
.filter_map(|kind| match *kind {
91-
CoverageKind::CounterIncrement { id } => Some(id),
92-
_ => None,
93-
})
94-
.max()
95-
.unwrap_or(CounterId::ZERO);
90+
let Some(fn_cov_info) = mir_body.function_coverage_info.as_ref() else {
91+
return CoverageIdsInfo {
92+
counters_seen: BitSet::new_empty(0),
93+
expressions_seen: BitSet::new_empty(0),
94+
};
95+
};
96+
97+
let mut counters_seen = BitSet::new_empty(fn_cov_info.num_counters);
98+
let mut expressions_seen = BitSet::new_filled(fn_cov_info.expressions.len());
99+
100+
// For each expression ID that is directly used by one or more mappings,
101+
// mark it as not-yet-seen. This indicates that we expect to see a
102+
// corresponding `ExpressionUsed` statement during MIR traversal.
103+
for mapping in fn_cov_info.mappings.iter() {
104+
// Currently we only worry about ordinary code mappings.
105+
// For branch and MC/DC mappings, expressions might not correspond
106+
// to any particular point in the control-flow graph.
107+
// (Keep this in sync with the injection of `ExpressionUsed`
108+
// statements in the `InstrumentCoverage` MIR pass.)
109+
if let MappingKind::Code(CovTerm::Expression(id)) = mapping.kind {
110+
expressions_seen.remove(id);
111+
}
112+
}
113+
114+
for kind in all_coverage_in_mir_body(mir_body) {
115+
match *kind {
116+
CoverageKind::CounterIncrement { id } => {
117+
counters_seen.insert(id);
118+
}
119+
CoverageKind::ExpressionUsed { id } => {
120+
expressions_seen.insert(id);
121+
}
122+
_ => {}
123+
}
124+
}
96125

97-
CoverageIdsInfo { max_counter_id }
126+
CoverageIdsInfo { counters_seen, expressions_seen }
98127
}
99128

100129
fn all_coverage_in_mir_body<'a, 'tcx>(

Diff for: tests/coverage/inline-dead.cov-map

+5-5
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,18 @@ Number of file 0 mappings: 1
88
Highest counter ID seen: (none)
99

1010
Function name: inline_dead::live::<false>
11-
Raw bytes (26): 0x[01, 01, 01, 01, 00, 04, 01, 0e, 01, 01, 09, 00, 02, 09, 00, 0f, 02, 02, 09, 00, 0a, 01, 02, 01, 00, 02]
11+
Raw bytes (26): 0x[01, 01, 01, 01, 05, 04, 01, 0e, 01, 01, 09, 05, 02, 09, 00, 0f, 02, 02, 09, 00, 0a, 01, 02, 01, 00, 02]
1212
Number of files: 1
1313
- file 0 => global file 1
1414
Number of expressions: 1
15-
- expression 0 operands: lhs = Counter(0), rhs = Zero
15+
- expression 0 operands: lhs = Counter(0), rhs = Counter(1)
1616
Number of file 0 mappings: 4
1717
- Code(Counter(0)) at (prev + 14, 1) to (start + 1, 9)
18-
- Code(Zero) at (prev + 2, 9) to (start + 0, 15)
18+
- Code(Counter(1)) at (prev + 2, 9) to (start + 0, 15)
1919
- Code(Expression(0, Sub)) at (prev + 2, 9) to (start + 0, 10)
20-
= (c0 - Zero)
20+
= (c0 - c1)
2121
- Code(Counter(0)) at (prev + 2, 1) to (start + 0, 2)
22-
Highest counter ID seen: c0
22+
Highest counter ID seen: c1
2323

2424
Function name: inline_dead::main
2525
Raw bytes (14): 0x[01, 01, 00, 02, 01, 04, 01, 03, 0a, 01, 06, 05, 01, 02]

Diff for: tests/coverage/let_else_loop.cov-map

+3-3
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,13 @@ Number of file 0 mappings: 3
2121
Highest counter ID seen: (none)
2222

2323
Function name: let_else_loop::loopy
24-
Raw bytes (19): 0x[01, 01, 00, 03, 01, 09, 01, 01, 14, 00, 01, 1c, 00, 23, 05, 01, 01, 00, 02]
24+
Raw bytes (19): 0x[01, 01, 00, 03, 01, 09, 01, 01, 14, 09, 01, 1c, 00, 23, 05, 01, 01, 00, 02]
2525
Number of files: 1
2626
- file 0 => global file 1
2727
Number of expressions: 0
2828
Number of file 0 mappings: 3
2929
- Code(Counter(0)) at (prev + 9, 1) to (start + 1, 20)
30-
- Code(Zero) at (prev + 1, 28) to (start + 0, 35)
30+
- Code(Counter(2)) at (prev + 1, 28) to (start + 0, 35)
3131
- Code(Counter(1)) at (prev + 1, 1) to (start + 0, 2)
32-
Highest counter ID seen: c1
32+
Highest counter ID seen: c2
3333

0 commit comments

Comments
 (0)