]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/coverage/mod.rs
Replace FnLikeNode by FnKind.
[rust.git] / compiler / rustc_mir_transform / src / coverage / mod.rs
1 pub mod query;
2
3 mod counters;
4 mod debug;
5 mod graph;
6 mod spans;
7
8 #[cfg(test)]
9 mod tests;
10
11 use counters::CoverageCounters;
12 use graph::{BasicCoverageBlock, BasicCoverageBlockData, CoverageGraph};
13 use spans::{CoverageSpan, CoverageSpans};
14
15 use crate::MirPass;
16
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,
27     TerminatorKind,
28 };
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};
33
34 /// A simple error message wrapper for `coverage::Error`s.
35 #[derive(Debug)]
36 struct Error {
37     message: String,
38 }
39
40 impl Error {
41     pub fn from_string<T>(message: String) -> Result<T, Error> {
42         Err(Self { message })
43     }
44 }
45
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;
50
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;
54
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() {
58             trace!(
59                 "InstrumentCoverage skipped for {:?} (already promoted for Miri evaluation)",
60                 mir_source.def_id()
61             );
62             return;
63         }
64
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();
67
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.)
75         if !is_fn_like {
76             trace!("InstrumentCoverage skipped for {:?} (not an fn-like)", mir_source.def_id());
77             return;
78         }
79
80         match mir_body.basic_blocks()[mir::START_BLOCK].terminator().kind {
81             TerminatorKind::Unreachable => {
82                 trace!("InstrumentCoverage skipped for unreachable `START_BLOCK`");
83                 return;
84             }
85             _ => {}
86         }
87
88         let codegen_fn_attrs = tcx.codegen_fn_attrs(mir_source.def_id());
89         if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_COVERAGE) {
90             return;
91         }
92
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());
96     }
97 }
98
99 struct Instrumentor<'a, 'tcx> {
100     pass_name: &'a str,
101     tcx: TyCtxt<'tcx>,
102     mir_body: &'a mut mir::Body<'tcx>,
103     source_file: Lrc<SourceFile>,
104     fn_sig_span: Span,
105     body_span: Span,
106     basic_coverage_blocks: CoverageGraph,
107     coverage_counters: CoverageCounters,
108 }
109
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);
115
116         let body_span = get_body_span(tcx, hir_body, mir_body);
117
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()))
122         }) {
123             Some(fn_sig) => fn_sig.span.with_hi(body_span.lo()),
124             None => body_span.shrink_to_lo(),
125         };
126
127         debug!(
128             "instrumenting {}: {:?}, fn sig span: {:?}, body span: {:?}",
129             if tcx.is_closure(def_id) { "closure" } else { "function" },
130             def_id,
131             fn_sig_span,
132             body_span
133         );
134
135         let function_source_hash = hash_mir_source(tcx, hir_body);
136         let basic_coverage_blocks = CoverageGraph::from_mir(mir_body);
137         Self {
138             pass_name,
139             tcx,
140             mir_body,
141             source_file,
142             fn_sig_span,
143             body_span,
144             basic_coverage_blocks,
145             coverage_counters: CoverageCounters::new(function_source_hash),
146         }
147     }
148
149     fn inject_counters(&'a mut self) {
150         let tcx = self.tcx;
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;
155
156         let mut graphviz_data = debug::GraphvizData::new();
157         let mut debug_used_expressions = debug::UsedExpressions::new();
158
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();
162
163         if dump_graphviz {
164             graphviz_data.enable();
165             self.coverage_counters.enable_debug();
166         }
167
168         if dump_graphviz || level_enabled!(tracing::Level::DEBUG) {
169             debug_used_expressions.enable();
170         }
171
172         ////////////////////////////////////////////////////
173         // Compute `CoverageSpan`s from the `CoverageGraph`.
174         let coverage_spans = CoverageSpans::generate_coverage_spans(
175             &self.mir_body,
176             fn_sig_span,
177             body_span,
178             &self.basic_coverage_blocks,
179         );
180
181         if dump_spanview {
182             debug::dump_coverage_spanview(
183                 tcx,
184                 self.mir_body,
185                 &self.basic_coverage_blocks,
186                 self.pass_name,
187                 body_span,
188                 &coverage_spans,
189             );
190         }
191
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`.
197         //
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
201             .coverage_counters
202             .make_bcb_counters(&mut self.basic_coverage_blocks, &coverage_spans);
203
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);
211                     }
212                 }
213
214                 ////////////////////////////////////////////////////
215                 // Remove the counter or edge counter from of each `CoverageSpan`s associated
216                 // `BasicCoverageBlock`, and inject a `Coverage` statement into the MIR.
217                 //
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.
220                 //
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(
225                     coverage_spans,
226                     &mut graphviz_data,
227                     &mut debug_used_expressions,
228                 );
229
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);
237
238                 // Intermediate expressions will be injected as the final step, after generating
239                 // debug output, if any.
240                 ////////////////////////////////////////////////////
241
242                 (Ok(()), intermediate_expressions)
243             }
244             Err(e) => (Err(e), Vec::new()),
245         };
246
247         if graphviz_data.is_enabled() {
248             // Even if there was an error, a partial CoverageGraph can still generate a useful
249             // graphviz output.
250             debug::dump_coverage_graphviz(
251                 tcx,
252                 self.mir_body,
253                 self.pass_name,
254                 &self.basic_coverage_blocks,
255                 &self.coverage_counters.debug_counters,
256                 &graphviz_data,
257                 &intermediate_expressions,
258                 &debug_used_expressions,
259             );
260         }
261
262         if let Err(e) = result {
263             bug!("Error processing: {:?}: {:?}", self.mir_body.source.def_id(), e.message)
264         };
265
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);
270
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);
275         }
276     }
277
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.
283     ///
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(
287         &mut self,
288         coverage_spans: Vec<CoverageSpan>,
289         graphviz_data: &mut debug::GraphvizData,
290         debug_used_expressions: &mut debug::UsedExpressions,
291     ) {
292         let tcx = self.tcx;
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());
296
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);
306                 counter_kind
307             } else {
308                 bug!("Every BasicCoverageBlock should have a Counter or Expression");
309             };
310             graphviz_data.add_bcb_coverage_span_with_counter(bcb, &covspan, &counter_kind);
311
312             debug!(
313                 "Calling make_code_region(file_name={}, source_file={:?}, span={}, body_span={})",
314                 file_name,
315                 self.source_file,
316                 source_map.span_to_diagnostic_string(span),
317                 source_map.span_to_diagnostic_string(body_span)
318             );
319
320             inject_statement(
321                 self.mir_body,
322                 counter_kind,
323                 self.bcb_leader_bb(bcb),
324                 Some(make_code_region(source_map, file_name, &self.source_file, span, body_span)),
325             );
326         }
327     }
328
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()`).
332     ///
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(
338         &mut self,
339         graphviz_data: &mut debug::GraphvizData,
340         debug_used_expressions: &mut debug::UsedExpressions,
341     ) {
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));
346             }
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((
350                         Some(from_bcb),
351                         target_bcb,
352                         counter_kind,
353                     ));
354                 }
355             }
356         }
357
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);
362
363         for (edge_from_bcb, target_bcb, counter_kind) in bcb_counters_without_direct_coverage_spans
364         {
365             debug_used_expressions.add_unused_expression_if_not_found(
366                 &counter_kind,
367                 edge_from_bcb,
368                 target_bcb,
369             );
370
371             match counter_kind {
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);
379
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);
382                         debug!(
383                             "Edge {:?} (last {:?}) -> {:?} (leader {:?}) requires a new MIR \
384                             BasicBlock {:?}, for unclaimed edge counter {}",
385                             edge_from_bcb,
386                             from_bb,
387                             target_bcb,
388                             to_bb,
389                             new_bb,
390                             self.format_counter(&counter_kind),
391                         );
392                         new_bb
393                     } else {
394                         let target_bb = self.bcb_last_bb(target_bcb);
395                         graphviz_data.add_bcb_dependency_counter(target_bcb, &counter_kind);
396                         debug!(
397                             "{:?} ({:?}) gets a new Coverage statement for unclaimed counter {}",
398                             target_bcb,
399                             target_bb,
400                             self.format_counter(&counter_kind),
401                         );
402                         target_bb
403                     };
404
405                     inject_statement(self.mir_body, counter_kind, inject_to_bb, None);
406                 }
407                 CoverageKind::Expression { .. } => {
408                     inject_intermediate_expression(self.mir_body, counter_kind)
409                 }
410                 _ => bug!("CoverageKind should be a counter"),
411             }
412         }
413     }
414
415     #[inline]
416     fn bcb_leader_bb(&self, bcb: BasicCoverageBlock) -> BasicBlock {
417         self.bcb_data(bcb).leader_bb()
418     }
419
420     #[inline]
421     fn bcb_last_bb(&self, bcb: BasicCoverageBlock) -> BasicBlock {
422         self.bcb_data(bcb).last_bb()
423     }
424
425     #[inline]
426     fn bcb_data(&self, bcb: BasicCoverageBlock) -> &BasicCoverageBlockData {
427         &self.basic_coverage_blocks[bcb]
428     }
429
430     #[inline]
431     fn bcb_data_mut(&mut self, bcb: BasicCoverageBlock) -> &mut BasicCoverageBlockData {
432         &mut self.basic_coverage_blocks[bcb]
433     }
434
435     #[inline]
436     fn format_counter(&self, counter_kind: &CoverageKind) -> String {
437         self.coverage_counters.debug_counters.format_counter(counter_kind)
438     }
439 }
440
441 fn inject_edge_counter_basic_block(
442     mir_body: &mut mir::Body<'tcx>,
443     from_bb: BasicBlock,
444     to_bb: BasicBlock,
445 ) -> BasicBlock {
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 },
452         }),
453         is_cleanup: false,
454     });
455     let edge_ref = mir_body[from_bb]
456         .terminator_mut()
457         .successors_mut()
458         .find(|successor| **successor == to_bb)
459         .expect("from_bb should have a successor for to_bb");
460     *edge_ref = new_bb;
461     new_bb
462 }
463
464 fn inject_statement(
465     mir_body: &mut mir::Body<'tcx>,
466     counter_kind: CoverageKind,
467     bb: BasicBlock,
468     some_code_region: Option<CodeRegion>,
469 ) {
470     debug!(
471         "  injecting statement {:?} for {:?} at code region: {:?}",
472         counter_kind, bb, some_code_region
473     );
474     let data = &mut mir_body[bb];
475     let source_info = data.terminator().source_info;
476     let statement = Statement {
477         source_info,
478         kind: StatementKind::Coverage(Box::new(Coverage {
479             kind: counter_kind,
480             code_region: some_code_region,
481         })),
482     };
483     data.statements.insert(0, statement);
484 }
485
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 {
494         source_info,
495         kind: StatementKind::Coverage(Box::new(Coverage { kind: expression, code_region: None })),
496     };
497     data.statements.push(statement);
498 }
499
500 /// Convert the Span into its file name, start line and column, and end line and column
501 fn make_code_region(
502     source_map: &SourceMap,
503     file_name: Symbol,
504     source_file: &Lrc<SourceFile>,
505     span: Span,
506     body_span: Span,
507 ) -> CodeRegion {
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);
515         } else {
516             end_col = CharPos(char_pos + 1);
517         }
518         (end_line, end_col)
519     } else {
520         source_file.lookup_file_pos(span.hi())
521     };
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);
524     CodeRegion {
525         file_name,
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,
530     }
531 }
532
533 fn fn_sig_and_body<'tcx>(
534     tcx: TyCtxt<'tcx>,
535     def_id: DefId,
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
538     // to HIR for it.
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))
542 }
543
544 fn get_body_span<'tcx>(
545     tcx: TyCtxt<'tcx>,
546     hir_body: &rustc_hir::Body<'tcx>,
547     mir_body: &mut mir::Body<'tcx>,
548 ) -> Span {
549     let mut body_span = hir_body.value.span;
550     let def_id = mir_body.source.def_id();
551
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
556         // instead.
557         loop {
558             let expn_data = body_span.ctxt().outer_expn_data();
559             if expn_data.is_root() {
560                 break;
561             }
562             if let ExpnKind::Macro { .. } = expn_data.kind {
563                 body_span = expn_data.call_site;
564             } else {
565                 break;
566             }
567         }
568     }
569
570     body_span
571 }
572
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)
581     });
582     stable_hasher.finish()
583 }