11 use counters::CoverageCounters;
12 use graph::{BasicCoverageBlock, BasicCoverageBlockData, CoverageGraph};
13 use spans::{CoverageSpan, CoverageSpans};
17 use rustc_data_structures::graph::WithNumNodes;
18 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
19 use rustc_data_structures::sync::Lrc;
20 use rustc_index::vec::IndexVec;
21 use rustc_middle::hir;
22 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
23 use rustc_middle::mir::coverage::*;
24 use rustc_middle::mir::dump_enabled;
25 use rustc_middle::mir::{
26 self, BasicBlock, BasicBlockData, Coverage, SourceInfo, Statement, StatementKind, Terminator,
29 use rustc_middle::ty::TyCtxt;
30 use rustc_span::def_id::DefId;
31 use rustc_span::source_map::SourceMap;
32 use rustc_span::{CharPos, ExpnKind, Pos, SourceFile, Span, Symbol};
34 /// A simple error message wrapper for `coverage::Error`s.
41 pub fn from_string<T>(message: String) -> Result<T, Error> {
46 /// Inserts `StatementKind::Coverage` statements that either instrument the binary with injected
47 /// counters, via intrinsic `llvm.instrprof.increment`, and/or inject metadata used during codegen
48 /// to construct the coverage map.
49 pub struct InstrumentCoverage;
51 impl<'tcx> MirPass<'tcx> for InstrumentCoverage {
52 fn run_pass(&self, tcx: TyCtxt<'tcx>, mir_body: &mut mir::Body<'tcx>) {
53 let mir_source = mir_body.source;
55 // If the InstrumentCoverage pass is called on promoted MIRs, skip them.
56 // See: https://github.com/rust-lang/rust/pull/73011#discussion_r438317601
57 if mir_source.promoted.is_some() {
59 "InstrumentCoverage skipped for {:?} (already promoted for Miri evaluation)",
65 let hir_id = tcx.hir().local_def_id_to_hir_id(mir_source.def_id().expect_local());
66 let is_fn_like = tcx.hir().get(hir_id).fn_kind().is_some();
68 // Only instrument functions, methods, and closures (not constants since they are evaluated
69 // at compile time by Miri).
70 // FIXME(#73156): Handle source code coverage in const eval, but note, if and when const
71 // expressions get coverage spans, we will probably have to "carve out" space for const
72 // expressions from coverage spans in enclosing MIR's, like we do for closures. (That might
73 // be tricky if const expressions have no corresponding statements in the enclosing MIR.
74 // Closures are carved out by their initial `Assign` statement.)
76 trace!("InstrumentCoverage skipped for {:?} (not an fn-like)", mir_source.def_id());
80 match mir_body.basic_blocks()[mir::START_BLOCK].terminator().kind {
81 TerminatorKind::Unreachable => {
82 trace!("InstrumentCoverage skipped for unreachable `START_BLOCK`");
88 let codegen_fn_attrs = tcx.codegen_fn_attrs(mir_source.def_id());
89 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_COVERAGE) {
93 trace!("InstrumentCoverage starting for {:?}", mir_source.def_id());
94 Instrumentor::new(&self.name(), tcx, mir_body).inject_counters();
95 trace!("InstrumentCoverage done for {:?}", mir_source.def_id());
99 struct Instrumentor<'a, 'tcx> {
102 mir_body: &'a mut mir::Body<'tcx>,
103 source_file: Lrc<SourceFile>,
106 basic_coverage_blocks: CoverageGraph,
107 coverage_counters: CoverageCounters,
110 impl<'a, 'tcx> Instrumentor<'a, 'tcx> {
111 fn new(pass_name: &'a str, tcx: TyCtxt<'tcx>, mir_body: &'a mut mir::Body<'tcx>) -> Self {
112 let source_map = tcx.sess.source_map();
113 let def_id = mir_body.source.def_id();
114 let (some_fn_sig, hir_body) = fn_sig_and_body(tcx, def_id);
116 let body_span = get_body_span(tcx, hir_body, mir_body);
118 let source_file = source_map.lookup_source_file(body_span.lo());
119 let fn_sig_span = match some_fn_sig.filter(|fn_sig| {
120 fn_sig.span.ctxt() == body_span.ctxt()
121 && Lrc::ptr_eq(&source_file, &source_map.lookup_source_file(fn_sig.span.lo()))
123 Some(fn_sig) => fn_sig.span.with_hi(body_span.lo()),
124 None => body_span.shrink_to_lo(),
128 "instrumenting {}: {:?}, fn sig span: {:?}, body span: {:?}",
129 if tcx.is_closure(def_id) { "closure" } else { "function" },
135 let function_source_hash = hash_mir_source(tcx, hir_body);
136 let basic_coverage_blocks = CoverageGraph::from_mir(mir_body);
144 basic_coverage_blocks,
145 coverage_counters: CoverageCounters::new(function_source_hash),
149 fn inject_counters(&'a mut self) {
151 let mir_source = self.mir_body.source;
152 let def_id = mir_source.def_id();
153 let fn_sig_span = self.fn_sig_span;
154 let body_span = self.body_span;
156 let mut graphviz_data = debug::GraphvizData::new();
157 let mut debug_used_expressions = debug::UsedExpressions::new();
159 let dump_mir = dump_enabled(tcx, self.pass_name, def_id);
160 let dump_graphviz = dump_mir && tcx.sess.opts.debugging_opts.dump_mir_graphviz;
161 let dump_spanview = dump_mir && tcx.sess.opts.debugging_opts.dump_mir_spanview.is_some();
164 graphviz_data.enable();
165 self.coverage_counters.enable_debug();
168 if dump_graphviz || level_enabled!(tracing::Level::DEBUG) {
169 debug_used_expressions.enable();
172 ////////////////////////////////////////////////////
173 // Compute `CoverageSpan`s from the `CoverageGraph`.
174 let coverage_spans = CoverageSpans::generate_coverage_spans(
178 &self.basic_coverage_blocks,
182 debug::dump_coverage_spanview(
185 &self.basic_coverage_blocks,
192 ////////////////////////////////////////////////////
193 // Create an optimized mix of `Counter`s and `Expression`s for the `CoverageGraph`. Ensure
194 // every `CoverageSpan` has a `Counter` or `Expression` assigned to its `BasicCoverageBlock`
195 // and all `Expression` dependencies (operands) are also generated, for any other
196 // `BasicCoverageBlock`s not already associated with a `CoverageSpan`.
198 // Intermediate expressions (used to compute other `Expression` values), which have no
199 // direct associate to any `BasicCoverageBlock`, are returned in the method `Result`.
200 let intermediate_expressions_or_error = self
202 .make_bcb_counters(&mut self.basic_coverage_blocks, &coverage_spans);
204 let (result, intermediate_expressions) = match intermediate_expressions_or_error {
205 Ok(intermediate_expressions) => {
206 // If debugging, add any intermediate expressions (which are not associated with any
207 // BCB) to the `debug_used_expressions` map.
208 if debug_used_expressions.is_enabled() {
209 for intermediate_expression in &intermediate_expressions {
210 debug_used_expressions.add_expression_operands(intermediate_expression);
214 ////////////////////////////////////////////////////
215 // Remove the counter or edge counter from of each `CoverageSpan`s associated
216 // `BasicCoverageBlock`, and inject a `Coverage` statement into the MIR.
218 // `Coverage` statements injected from `CoverageSpan`s will include the code regions
219 // (source code start and end positions) to be counted by the associated counter.
221 // These `CoverageSpan`-associated counters are removed from their associated
222 // `BasicCoverageBlock`s so that the only remaining counters in the `CoverageGraph`
223 // are indirect counters (to be injected next, without associated code regions).
224 self.inject_coverage_span_counters(
227 &mut debug_used_expressions,
230 ////////////////////////////////////////////////////
231 // For any remaining `BasicCoverageBlock` counters (that were not associated with
232 // any `CoverageSpan`), inject `Coverage` statements (_without_ code region `Span`s)
233 // to ensure `BasicCoverageBlock` counters that other `Expression`s may depend on
234 // are in fact counted, even though they don't directly contribute to counting
235 // their own independent code region's coverage.
236 self.inject_indirect_counters(&mut graphviz_data, &mut debug_used_expressions);
238 // Intermediate expressions will be injected as the final step, after generating
239 // debug output, if any.
240 ////////////////////////////////////////////////////
242 (Ok(()), intermediate_expressions)
244 Err(e) => (Err(e), Vec::new()),
247 if graphviz_data.is_enabled() {
248 // Even if there was an error, a partial CoverageGraph can still generate a useful
250 debug::dump_coverage_graphviz(
254 &self.basic_coverage_blocks,
255 &self.coverage_counters.debug_counters,
257 &intermediate_expressions,
258 &debug_used_expressions,
262 if let Err(e) = result {
263 bug!("Error processing: {:?}: {:?}", self.mir_body.source.def_id(), e.message)
266 // Depending on current `debug_options()`, `alert_on_unused_expressions()` could panic, so
267 // this check is performed as late as possible, to allow other debug output (logs and dump
268 // files), which might be helpful in analyzing unused expressions, to still be generated.
269 debug_used_expressions.alert_on_unused_expressions(&self.coverage_counters.debug_counters);
271 ////////////////////////////////////////////////////
272 // Finally, inject the intermediate expressions collected along the way.
273 for intermediate_expression in intermediate_expressions {
274 inject_intermediate_expression(self.mir_body, intermediate_expression);
278 /// Inject a counter for each `CoverageSpan`. There can be multiple `CoverageSpan`s for a given
279 /// BCB, but only one actual counter needs to be incremented per BCB. `bb_counters` maps each
280 /// `bcb` to its `Counter`, when injected. Subsequent `CoverageSpan`s for a BCB that already has
281 /// a `Counter` will inject an `Expression` instead, and compute its value by adding `ZERO` to
282 /// the BCB `Counter` value.
284 /// If debugging, add every BCB `Expression` associated with a `CoverageSpan`s to the
285 /// `used_expression_operands` map.
286 fn inject_coverage_span_counters(
288 coverage_spans: Vec<CoverageSpan>,
289 graphviz_data: &mut debug::GraphvizData,
290 debug_used_expressions: &mut debug::UsedExpressions,
293 let source_map = tcx.sess.source_map();
294 let body_span = self.body_span;
295 let file_name = Symbol::intern(&self.source_file.name.prefer_remapped().to_string_lossy());
297 let mut bcb_counters = IndexVec::from_elem_n(None, self.basic_coverage_blocks.num_nodes());
298 for covspan in coverage_spans {
299 let bcb = covspan.bcb;
300 let span = covspan.span;
301 let counter_kind = if let Some(&counter_operand) = bcb_counters[bcb].as_ref() {
302 self.coverage_counters.make_identity_counter(counter_operand)
303 } else if let Some(counter_kind) = self.bcb_data_mut(bcb).take_counter() {
304 bcb_counters[bcb] = Some(counter_kind.as_operand_id());
305 debug_used_expressions.add_expression_operands(&counter_kind);
308 bug!("Every BasicCoverageBlock should have a Counter or Expression");
310 graphviz_data.add_bcb_coverage_span_with_counter(bcb, &covspan, &counter_kind);
313 "Calling make_code_region(file_name={}, source_file={:?}, span={}, body_span={})",
316 source_map.span_to_diagnostic_string(span),
317 source_map.span_to_diagnostic_string(body_span)
323 self.bcb_leader_bb(bcb),
324 Some(make_code_region(source_map, file_name, &self.source_file, span, body_span)),
329 /// `inject_coverage_span_counters()` looped through the `CoverageSpan`s and injected the
330 /// counter from the `CoverageSpan`s `BasicCoverageBlock`, removing it from the BCB in the
331 /// process (via `take_counter()`).
333 /// Any other counter associated with a `BasicCoverageBlock`, or its incoming edge, but not
334 /// associated with a `CoverageSpan`, should only exist if the counter is an `Expression`
335 /// dependency (one of the expression operands). Collect them, and inject the additional
336 /// counters into the MIR, without a reportable coverage span.
337 fn inject_indirect_counters(
339 graphviz_data: &mut debug::GraphvizData,
340 debug_used_expressions: &mut debug::UsedExpressions,
342 let mut bcb_counters_without_direct_coverage_spans = Vec::new();
343 for (target_bcb, target_bcb_data) in self.basic_coverage_blocks.iter_enumerated_mut() {
344 if let Some(counter_kind) = target_bcb_data.take_counter() {
345 bcb_counters_without_direct_coverage_spans.push((None, target_bcb, counter_kind));
347 if let Some(edge_counters) = target_bcb_data.take_edge_counters() {
348 for (from_bcb, counter_kind) in edge_counters {
349 bcb_counters_without_direct_coverage_spans.push((
358 // If debug is enabled, validate that every BCB or edge counter not directly associated
359 // with a coverage span is at least indirectly associated (it is a dependency of a BCB
360 // counter that _is_ associated with a coverage span).
361 debug_used_expressions.validate(&bcb_counters_without_direct_coverage_spans);
363 for (edge_from_bcb, target_bcb, counter_kind) in bcb_counters_without_direct_coverage_spans
365 debug_used_expressions.add_unused_expression_if_not_found(
372 CoverageKind::Counter { .. } => {
373 let inject_to_bb = if let Some(from_bcb) = edge_from_bcb {
374 // The MIR edge starts `from_bb` (the outgoing / last BasicBlock in
375 // `from_bcb`) and ends at `to_bb` (the incoming / first BasicBlock in the
376 // `target_bcb`; also called the `leader_bb`).
377 let from_bb = self.bcb_last_bb(from_bcb);
378 let to_bb = self.bcb_leader_bb(target_bcb);
380 let new_bb = inject_edge_counter_basic_block(self.mir_body, from_bb, to_bb);
381 graphviz_data.set_edge_counter(from_bcb, new_bb, &counter_kind);
383 "Edge {:?} (last {:?}) -> {:?} (leader {:?}) requires a new MIR \
384 BasicBlock {:?}, for unclaimed edge counter {}",
390 self.format_counter(&counter_kind),
394 let target_bb = self.bcb_last_bb(target_bcb);
395 graphviz_data.add_bcb_dependency_counter(target_bcb, &counter_kind);
397 "{:?} ({:?}) gets a new Coverage statement for unclaimed counter {}",
400 self.format_counter(&counter_kind),
405 inject_statement(self.mir_body, counter_kind, inject_to_bb, None);
407 CoverageKind::Expression { .. } => {
408 inject_intermediate_expression(self.mir_body, counter_kind)
410 _ => bug!("CoverageKind should be a counter"),
416 fn bcb_leader_bb(&self, bcb: BasicCoverageBlock) -> BasicBlock {
417 self.bcb_data(bcb).leader_bb()
421 fn bcb_last_bb(&self, bcb: BasicCoverageBlock) -> BasicBlock {
422 self.bcb_data(bcb).last_bb()
426 fn bcb_data(&self, bcb: BasicCoverageBlock) -> &BasicCoverageBlockData {
427 &self.basic_coverage_blocks[bcb]
431 fn bcb_data_mut(&mut self, bcb: BasicCoverageBlock) -> &mut BasicCoverageBlockData {
432 &mut self.basic_coverage_blocks[bcb]
436 fn format_counter(&self, counter_kind: &CoverageKind) -> String {
437 self.coverage_counters.debug_counters.format_counter(counter_kind)
441 fn inject_edge_counter_basic_block(
442 mir_body: &mut mir::Body<'tcx>,
446 let span = mir_body[from_bb].terminator().source_info.span.shrink_to_hi();
447 let new_bb = mir_body.basic_blocks_mut().push(BasicBlockData {
448 statements: vec![], // counter will be injected here
449 terminator: Some(Terminator {
450 source_info: SourceInfo::outermost(span),
451 kind: TerminatorKind::Goto { target: to_bb },
455 let edge_ref = mir_body[from_bb]
458 .find(|successor| **successor == to_bb)
459 .expect("from_bb should have a successor for to_bb");
465 mir_body: &mut mir::Body<'tcx>,
466 counter_kind: CoverageKind,
468 some_code_region: Option<CodeRegion>,
471 " injecting statement {:?} for {:?} at code region: {:?}",
472 counter_kind, bb, some_code_region
474 let data = &mut mir_body[bb];
475 let source_info = data.terminator().source_info;
476 let statement = Statement {
478 kind: StatementKind::Coverage(Box::new(Coverage {
480 code_region: some_code_region,
483 data.statements.insert(0, statement);
486 // Non-code expressions are injected into the coverage map, without generating executable code.
487 fn inject_intermediate_expression(mir_body: &mut mir::Body<'tcx>, expression: CoverageKind) {
488 debug_assert!(if let CoverageKind::Expression { .. } = expression { true } else { false });
489 debug!(" injecting non-code expression {:?}", expression);
490 let inject_in_bb = mir::START_BLOCK;
491 let data = &mut mir_body[inject_in_bb];
492 let source_info = data.terminator().source_info;
493 let statement = Statement {
495 kind: StatementKind::Coverage(Box::new(Coverage { kind: expression, code_region: None })),
497 data.statements.push(statement);
500 /// Convert the Span into its file name, start line and column, and end line and column
502 source_map: &SourceMap,
504 source_file: &Lrc<SourceFile>,
508 let (start_line, mut start_col) = source_file.lookup_file_pos(span.lo());
509 let (end_line, end_col) = if span.hi() == span.lo() {
510 let (end_line, mut end_col) = (start_line, start_col);
511 // Extend an empty span by one character so the region will be counted.
512 let CharPos(char_pos) = start_col;
513 if span.hi() == body_span.hi() {
514 start_col = CharPos(char_pos - 1);
516 end_col = CharPos(char_pos + 1);
520 source_file.lookup_file_pos(span.hi())
522 let start_line = source_map.doctest_offset_line(&source_file.name, start_line);
523 let end_line = source_map.doctest_offset_line(&source_file.name, end_line);
526 start_line: start_line as u32,
527 start_col: start_col.to_u32() + 1,
528 end_line: end_line as u32,
529 end_col: end_col.to_u32() + 1,
533 fn fn_sig_and_body<'tcx>(
536 ) -> (Option<&'tcx rustc_hir::FnSig<'tcx>>, &'tcx rustc_hir::Body<'tcx>) {
537 // FIXME(#79625): Consider improving MIR to provide the information needed, to avoid going back
539 let hir_node = tcx.hir().get_if_local(def_id).expect("expected DefId is local");
540 let fn_body_id = hir::map::associated_body(hir_node).expect("HIR node is a function with body");
541 (hir::map::fn_sig(hir_node), tcx.hir().body(fn_body_id))
544 fn get_body_span<'tcx>(
546 hir_body: &rustc_hir::Body<'tcx>,
547 mir_body: &mut mir::Body<'tcx>,
549 let mut body_span = hir_body.value.span;
550 let def_id = mir_body.source.def_id();
552 if tcx.is_closure(def_id) {
553 // If the MIR function is a closure, and if the closure body span
554 // starts from a macro, but it's content is not in that macro, try
555 // to find a non-macro callsite, and instrument the spans there
558 let expn_data = body_span.ctxt().outer_expn_data();
559 if expn_data.is_root() {
562 if let ExpnKind::Macro { .. } = expn_data.kind {
563 body_span = expn_data.call_site;
573 fn hash_mir_source<'tcx>(tcx: TyCtxt<'tcx>, hir_body: &'tcx rustc_hir::Body<'tcx>) -> u64 {
574 // FIXME(cjgillot) Stop hashing HIR manually here.
575 let mut hcx = tcx.create_no_span_stable_hashing_context();
576 let mut stable_hasher = StableHasher::new();
577 let owner = hir_body.id().hir_id.owner;
578 let bodies = &tcx.hir_owner_nodes(owner).as_ref().unwrap().bodies;
579 hcx.with_hir_bodies(false, owner, bodies, |hcx| {
580 hir_body.value.hash_stable(hcx, &mut stable_hasher)
582 stable_hasher.finish()