• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! The `InstrumentCoverage` MIR pass implementation includes debugging tools and options
2 //! to help developers understand and/or improve the analysis and instrumentation of a MIR.
3 //!
4 //! To enable coverage, include the rustc command line option:
5 //!
6 //!   * `-C instrument-coverage`
7 //!
8 //! MIR Dump Files, with additional `CoverageGraph` graphviz and `CoverageSpan` spanview
9 //! ------------------------------------------------------------------------------------
10 //!
11 //! Additional debugging options include:
12 //!
13 //!   * `-Z dump-mir=InstrumentCoverage` - Generate `.mir` files showing the state of the MIR,
14 //!     before and after the `InstrumentCoverage` pass, for each compiled function.
15 //!
16 //!   * `-Z dump-mir-graphviz` - If `-Z dump-mir` is also enabled for the current MIR node path,
17 //!     each MIR dump is accompanied by a before-and-after graphical view of the MIR, in Graphviz
18 //!     `.dot` file format (which can be visually rendered as a graph using any of a number of free
19 //!     Graphviz viewers and IDE extensions).
20 //!
21 //!     For the `InstrumentCoverage` pass, this option also enables generation of an additional
22 //!     Graphviz `.dot` file for each function, rendering the `CoverageGraph`: the control flow
23 //!     graph (CFG) of `BasicCoverageBlocks` (BCBs), as nodes, internally labeled to show the
24 //!     `CoverageSpan`-based MIR elements each BCB represents (`BasicBlock`s, `Statement`s and
25 //!     `Terminator`s), assigned coverage counters and/or expressions, and edge counters, as needed.
26 //!
27 //!     (Note the additional option, `-Z graphviz-dark-mode`, can be added, to change the rendered
28 //!     output from its default black-on-white background to a dark color theme, if desired.)
29 //!
30 //!   * `-Z dump-mir-spanview` - If `-Z dump-mir` is also enabled for the current MIR node path,
31 //!     each MIR dump is accompanied by a before-and-after `.html` document showing the function's
32 //!     original source code, highlighted by it's MIR spans, at the `statement`-level (by default),
33 //!     `terminator` only, or encompassing span for the `Terminator` plus all `Statement`s, in each
34 //!     `block` (`BasicBlock`).
35 //!
36 //!     For the `InstrumentCoverage` pass, this option also enables generation of an additional
37 //!     spanview `.html` file for each function, showing the aggregated `CoverageSpan`s that will
38 //!     require counters (or counter expressions) for accurate coverage analysis.
39 //!
40 //! Debug Logging
41 //! -------------
42 //!
43 //! The `InstrumentCoverage` pass includes debug logging messages at various phases and decision
44 //! points, which can be enabled via environment variable:
45 //!
46 //! ```shell
47 //! RUSTC_LOG=rustc_mir_transform::transform::coverage=debug
48 //! ```
49 //!
50 //! Other module paths with coverage-related debug logs may also be of interest, particularly for
51 //! debugging the coverage map data, injected as global variables in the LLVM IR (during rustc's
52 //! code generation pass). For example:
53 //!
54 //! ```shell
55 //! RUSTC_LOG=rustc_mir_transform::transform::coverage,rustc_codegen_ssa::coverageinfo,rustc_codegen_llvm::coverageinfo=debug
56 //! ```
57 //!
58 //! Coverage Debug Options
59 //! ---------------------------------
60 //!
61 //! Additional debugging options can be enabled using the environment variable:
62 //!
63 //! ```shell
64 //! RUSTC_COVERAGE_DEBUG_OPTIONS=<options>
65 //! ```
66 //!
67 //! These options are comma-separated, and specified in the format `option-name=value`. For example:
68 //!
69 //! ```shell
70 //! $ RUSTC_COVERAGE_DEBUG_OPTIONS=counter-format=id+operation,allow-unused-expressions=yes cargo build
71 //! ```
72 //!
73 //! Coverage debug options include:
74 //!
75 //!   * `allow-unused-expressions=yes` or `no` (default: `no`)
76 //!
77 //!     The `InstrumentCoverage` algorithms _should_ only create and assign expressions to a
78 //!     `BasicCoverageBlock`, or an incoming edge, if that expression is either (a) required to
79 //!     count a `CoverageSpan`, or (b) a dependency of some other required counter expression.
80 //!
81 //!     If an expression is generated that does not map to a `CoverageSpan` or dependency, this
82 //!     probably indicates there was a bug in the algorithm that creates and assigns counters
83 //!     and expressions.
84 //!
85 //!     When this kind of bug is encountered, the rustc compiler will panic by default. Setting:
86 //!     `allow-unused-expressions=yes` will log a warning message instead of panicking (effectively
87 //!     ignoring the unused expressions), which may be helpful when debugging the root cause of
88 //!     the problem.
89 //!
90 //!   * `counter-format=<choices>`, where `<choices>` can be any plus-separated combination of `id`,
91 //!     `block`, and/or `operation` (default: `block+operation`)
92 //!
93 //!     This option effects both the `CoverageGraph` (graphviz `.dot` files) and debug logging, when
94 //!     generating labels for counters and expressions.
95 //!
96 //!     Depending on the values and combinations, counters can be labeled by:
97 //!
98 //!       * `id` - counter or expression ID (ascending counter IDs, starting at 1, or descending
99 //!         expression IDs, starting at `u32:MAX`)
100 //!       * `block` - the `BasicCoverageBlock` label (for example, `bcb0`) or edge label (for
101 //!         example `bcb0->bcb1`), for counters or expressions assigned to count a
102 //!         `BasicCoverageBlock` or edge. Intermediate expressions (not directly associated with
103 //!         a BCB or edge) will be labeled by their expression ID, unless `operation` is also
104 //!         specified.
105 //!       * `operation` - applied to expressions only, labels include the left-hand-side counter
106 //!         or expression label (lhs operand), the operator (`+` or `-`), and the right-hand-side
107 //!         counter or expression (rhs operand). Expression operand labels are generated
108 //!         recursively, generating labels with nested operations, enclosed in parentheses
109 //!         (for example: `bcb2 + (bcb0 - bcb1)`).
110 
111 use super::graph::{BasicCoverageBlock, BasicCoverageBlockData, CoverageGraph};
112 use super::spans::CoverageSpan;
113 
114 use itertools::Itertools;
115 use rustc_middle::mir::create_dump_file;
116 use rustc_middle::mir::generic_graphviz::GraphvizWriter;
117 use rustc_middle::mir::spanview::{self, SpanViewable};
118 
119 use rustc_data_structures::fx::FxHashMap;
120 use rustc_middle::mir::coverage::*;
121 use rustc_middle::mir::{self, BasicBlock};
122 use rustc_middle::ty::TyCtxt;
123 use rustc_span::Span;
124 
125 use std::iter;
126 use std::ops::Deref;
127 use std::sync::OnceLock;
128 
129 pub const NESTED_INDENT: &str = "    ";
130 
131 const RUSTC_COVERAGE_DEBUG_OPTIONS: &str = "RUSTC_COVERAGE_DEBUG_OPTIONS";
132 
debug_options<'a>() -> &'a DebugOptions133 pub(super) fn debug_options<'a>() -> &'a DebugOptions {
134     static DEBUG_OPTIONS: OnceLock<DebugOptions> = OnceLock::new();
135 
136     &DEBUG_OPTIONS.get_or_init(DebugOptions::from_env)
137 }
138 
139 /// Parses and maintains coverage-specific debug options captured from the environment variable
140 /// "RUSTC_COVERAGE_DEBUG_OPTIONS", if set.
141 #[derive(Debug, Clone)]
142 pub(super) struct DebugOptions {
143     pub allow_unused_expressions: bool,
144     counter_format: ExpressionFormat,
145 }
146 
147 impl DebugOptions {
from_env() -> Self148     fn from_env() -> Self {
149         let mut allow_unused_expressions = true;
150         let mut counter_format = ExpressionFormat::default();
151 
152         if let Ok(env_debug_options) = std::env::var(RUSTC_COVERAGE_DEBUG_OPTIONS) {
153             for setting_str in env_debug_options.replace(' ', "").replace('-', "_").split(',') {
154                 let (option, value) = match setting_str.split_once('=') {
155                     None => (setting_str, None),
156                     Some((k, v)) => (k, Some(v)),
157                 };
158                 match option {
159                     "allow_unused_expressions" => {
160                         allow_unused_expressions = bool_option_val(option, value);
161                         debug!(
162                             "{} env option `allow_unused_expressions` is set to {}",
163                             RUSTC_COVERAGE_DEBUG_OPTIONS, allow_unused_expressions
164                         );
165                     }
166                     "counter_format" => {
167                         match value {
168                             None => {
169                                 bug!(
170                                     "`{}` option in environment variable {} requires one or more \
171                                     plus-separated choices (a non-empty subset of \
172                                     `id+block+operation`)",
173                                     option,
174                                     RUSTC_COVERAGE_DEBUG_OPTIONS
175                                 );
176                             }
177                             Some(val) => {
178                                 counter_format = counter_format_option_val(val);
179                                 debug!(
180                                     "{} env option `counter_format` is set to {:?}",
181                                     RUSTC_COVERAGE_DEBUG_OPTIONS, counter_format
182                                 );
183                             }
184                         };
185                     }
186                     _ => bug!(
187                         "Unsupported setting `{}` in environment variable {}",
188                         option,
189                         RUSTC_COVERAGE_DEBUG_OPTIONS
190                     ),
191                 };
192             }
193         }
194 
195         Self { allow_unused_expressions, counter_format }
196     }
197 }
198 
bool_option_val(option: &str, some_strval: Option<&str>) -> bool199 fn bool_option_val(option: &str, some_strval: Option<&str>) -> bool {
200     if let Some(val) = some_strval {
201         if vec!["yes", "y", "on", "true"].contains(&val) {
202             true
203         } else if vec!["no", "n", "off", "false"].contains(&val) {
204             false
205         } else {
206             bug!(
207                 "Unsupported value `{}` for option `{}` in environment variable {}",
208                 option,
209                 val,
210                 RUSTC_COVERAGE_DEBUG_OPTIONS
211             )
212         }
213     } else {
214         true
215     }
216 }
217 
counter_format_option_val(strval: &str) -> ExpressionFormat218 fn counter_format_option_val(strval: &str) -> ExpressionFormat {
219     let mut counter_format = ExpressionFormat { id: false, block: false, operation: false };
220     let components = strval.splitn(3, '+');
221     for component in components {
222         match component {
223             "id" => counter_format.id = true,
224             "block" => counter_format.block = true,
225             "operation" => counter_format.operation = true,
226             _ => bug!(
227                 "Unsupported counter_format choice `{}` in environment variable {}",
228                 component,
229                 RUSTC_COVERAGE_DEBUG_OPTIONS
230             ),
231         }
232     }
233     counter_format
234 }
235 
236 #[derive(Debug, Clone)]
237 struct ExpressionFormat {
238     id: bool,
239     block: bool,
240     operation: bool,
241 }
242 
243 impl Default for ExpressionFormat {
default() -> Self244     fn default() -> Self {
245         Self { id: false, block: true, operation: true }
246     }
247 }
248 
249 /// If enabled, this struct maintains a map from `CoverageKind` IDs (as `ExpressionOperandId`) to
250 /// the `CoverageKind` data and optional label (normally, the counter's associated
251 /// `BasicCoverageBlock` format string, if any).
252 ///
253 /// Use `format_counter` to convert one of these `CoverageKind` counters to a debug output string,
254 /// as directed by the `DebugOptions`. This allows the format of counter labels in logs and dump
255 /// files (including the `CoverageGraph` graphviz file) to be changed at runtime, via environment
256 /// variable.
257 ///
258 /// `DebugCounters` supports a recursive rendering of `Expression` counters, so they can be
259 /// presented as nested expressions such as `(bcb3 - (bcb0 + bcb1))`.
260 pub(super) struct DebugCounters {
261     some_counters: Option<FxHashMap<ExpressionOperandId, DebugCounter>>,
262 }
263 
264 impl DebugCounters {
new() -> Self265     pub fn new() -> Self {
266         Self { some_counters: None }
267     }
268 
enable(&mut self)269     pub fn enable(&mut self) {
270         debug_assert!(!self.is_enabled());
271         self.some_counters.replace(FxHashMap::default());
272     }
273 
is_enabled(&self) -> bool274     pub fn is_enabled(&self) -> bool {
275         self.some_counters.is_some()
276     }
277 
add_counter(&mut self, counter_kind: &CoverageKind, some_block_label: Option<String>)278     pub fn add_counter(&mut self, counter_kind: &CoverageKind, some_block_label: Option<String>) {
279         if let Some(counters) = &mut self.some_counters {
280             let id = counter_kind.as_operand_id();
281             counters
282                 .try_insert(id, DebugCounter::new(counter_kind.clone(), some_block_label))
283                 .expect("attempt to add the same counter_kind to DebugCounters more than once");
284         }
285     }
286 
some_block_label(&self, operand: ExpressionOperandId) -> Option<&String>287     pub fn some_block_label(&self, operand: ExpressionOperandId) -> Option<&String> {
288         self.some_counters.as_ref().and_then(|counters| {
289             counters.get(&operand).and_then(|debug_counter| debug_counter.some_block_label.as_ref())
290         })
291     }
292 
format_counter(&self, counter_kind: &CoverageKind) -> String293     pub fn format_counter(&self, counter_kind: &CoverageKind) -> String {
294         match *counter_kind {
295             CoverageKind::Counter { .. } => {
296                 format!("Counter({})", self.format_counter_kind(counter_kind))
297             }
298             CoverageKind::Expression { .. } => {
299                 format!("Expression({})", self.format_counter_kind(counter_kind))
300             }
301             CoverageKind::Unreachable { .. } => "Unreachable".to_owned(),
302         }
303     }
304 
format_counter_kind(&self, counter_kind: &CoverageKind) -> String305     fn format_counter_kind(&self, counter_kind: &CoverageKind) -> String {
306         let counter_format = &debug_options().counter_format;
307         if let CoverageKind::Expression { id, lhs, op, rhs } = *counter_kind {
308             if counter_format.operation {
309                 return format!(
310                     "{}{} {} {}",
311                     if counter_format.id || self.some_counters.is_none() {
312                         format!("#{} = ", id.index())
313                     } else {
314                         String::new()
315                     },
316                     self.format_operand(lhs),
317                     match op {
318                         Op::Add => "+",
319                         Op::Subtract => "-",
320                     },
321                     self.format_operand(rhs),
322                 );
323             }
324         }
325 
326         let id = counter_kind.as_operand_id();
327         if self.some_counters.is_some() && (counter_format.block || !counter_format.id) {
328             let counters = self.some_counters.as_ref().unwrap();
329             if let Some(DebugCounter { some_block_label: Some(block_label), .. }) =
330                 counters.get(&id)
331             {
332                 return if counter_format.id {
333                     format!("{}#{}", block_label, id.index())
334                 } else {
335                     block_label.to_string()
336                 };
337             }
338         }
339         format!("#{}", id.index())
340     }
341 
format_operand(&self, operand: ExpressionOperandId) -> String342     fn format_operand(&self, operand: ExpressionOperandId) -> String {
343         if operand.index() == 0 {
344             return String::from("0");
345         }
346         if let Some(counters) = &self.some_counters {
347             if let Some(DebugCounter { counter_kind, some_block_label }) = counters.get(&operand) {
348                 if let CoverageKind::Expression { .. } = counter_kind {
349                     if let Some(label) = some_block_label && debug_options().counter_format.block {
350                         return format!(
351                             "{}:({})",
352                             label,
353                             self.format_counter_kind(counter_kind)
354                         );
355                     }
356                     return format!("({})", self.format_counter_kind(counter_kind));
357                 }
358                 return self.format_counter_kind(counter_kind);
359             }
360         }
361         format!("#{}", operand.index())
362     }
363 }
364 
365 /// A non-public support class to `DebugCounters`.
366 #[derive(Debug)]
367 struct DebugCounter {
368     counter_kind: CoverageKind,
369     some_block_label: Option<String>,
370 }
371 
372 impl DebugCounter {
new(counter_kind: CoverageKind, some_block_label: Option<String>) -> Self373     fn new(counter_kind: CoverageKind, some_block_label: Option<String>) -> Self {
374         Self { counter_kind, some_block_label }
375     }
376 }
377 
378 /// If enabled, this data structure captures additional debugging information used when generating
379 /// a Graphviz (.dot file) representation of the `CoverageGraph`, for debugging purposes.
380 pub(super) struct GraphvizData {
381     some_bcb_to_coverage_spans_with_counters:
382         Option<FxHashMap<BasicCoverageBlock, Vec<(CoverageSpan, CoverageKind)>>>,
383     some_bcb_to_dependency_counters: Option<FxHashMap<BasicCoverageBlock, Vec<CoverageKind>>>,
384     some_edge_to_counter: Option<FxHashMap<(BasicCoverageBlock, BasicBlock), CoverageKind>>,
385 }
386 
387 impl GraphvizData {
new() -> Self388     pub fn new() -> Self {
389         Self {
390             some_bcb_to_coverage_spans_with_counters: None,
391             some_bcb_to_dependency_counters: None,
392             some_edge_to_counter: None,
393         }
394     }
395 
enable(&mut self)396     pub fn enable(&mut self) {
397         debug_assert!(!self.is_enabled());
398         self.some_bcb_to_coverage_spans_with_counters = Some(FxHashMap::default());
399         self.some_bcb_to_dependency_counters = Some(FxHashMap::default());
400         self.some_edge_to_counter = Some(FxHashMap::default());
401     }
402 
is_enabled(&self) -> bool403     pub fn is_enabled(&self) -> bool {
404         self.some_bcb_to_coverage_spans_with_counters.is_some()
405     }
406 
add_bcb_coverage_span_with_counter( &mut self, bcb: BasicCoverageBlock, coverage_span: &CoverageSpan, counter_kind: &CoverageKind, )407     pub fn add_bcb_coverage_span_with_counter(
408         &mut self,
409         bcb: BasicCoverageBlock,
410         coverage_span: &CoverageSpan,
411         counter_kind: &CoverageKind,
412     ) {
413         if let Some(bcb_to_coverage_spans_with_counters) =
414             self.some_bcb_to_coverage_spans_with_counters.as_mut()
415         {
416             bcb_to_coverage_spans_with_counters
417                 .entry(bcb)
418                 .or_insert_with(Vec::new)
419                 .push((coverage_span.clone(), counter_kind.clone()));
420         }
421     }
422 
get_bcb_coverage_spans_with_counters( &self, bcb: BasicCoverageBlock, ) -> Option<&[(CoverageSpan, CoverageKind)]>423     pub fn get_bcb_coverage_spans_with_counters(
424         &self,
425         bcb: BasicCoverageBlock,
426     ) -> Option<&[(CoverageSpan, CoverageKind)]> {
427         if let Some(bcb_to_coverage_spans_with_counters) =
428             self.some_bcb_to_coverage_spans_with_counters.as_ref()
429         {
430             bcb_to_coverage_spans_with_counters.get(&bcb).map(Deref::deref)
431         } else {
432             None
433         }
434     }
435 
add_bcb_dependency_counter( &mut self, bcb: BasicCoverageBlock, counter_kind: &CoverageKind, )436     pub fn add_bcb_dependency_counter(
437         &mut self,
438         bcb: BasicCoverageBlock,
439         counter_kind: &CoverageKind,
440     ) {
441         if let Some(bcb_to_dependency_counters) = self.some_bcb_to_dependency_counters.as_mut() {
442             bcb_to_dependency_counters
443                 .entry(bcb)
444                 .or_insert_with(Vec::new)
445                 .push(counter_kind.clone());
446         }
447     }
448 
get_bcb_dependency_counters(&self, bcb: BasicCoverageBlock) -> Option<&[CoverageKind]>449     pub fn get_bcb_dependency_counters(&self, bcb: BasicCoverageBlock) -> Option<&[CoverageKind]> {
450         if let Some(bcb_to_dependency_counters) = self.some_bcb_to_dependency_counters.as_ref() {
451             bcb_to_dependency_counters.get(&bcb).map(Deref::deref)
452         } else {
453             None
454         }
455     }
456 
set_edge_counter( &mut self, from_bcb: BasicCoverageBlock, to_bb: BasicBlock, counter_kind: &CoverageKind, )457     pub fn set_edge_counter(
458         &mut self,
459         from_bcb: BasicCoverageBlock,
460         to_bb: BasicBlock,
461         counter_kind: &CoverageKind,
462     ) {
463         if let Some(edge_to_counter) = self.some_edge_to_counter.as_mut() {
464             edge_to_counter
465                 .try_insert((from_bcb, to_bb), counter_kind.clone())
466                 .expect("invalid attempt to insert more than one edge counter for the same edge");
467         }
468     }
469 
get_edge_counter( &self, from_bcb: BasicCoverageBlock, to_bb: BasicBlock, ) -> Option<&CoverageKind>470     pub fn get_edge_counter(
471         &self,
472         from_bcb: BasicCoverageBlock,
473         to_bb: BasicBlock,
474     ) -> Option<&CoverageKind> {
475         if let Some(edge_to_counter) = self.some_edge_to_counter.as_ref() {
476             edge_to_counter.get(&(from_bcb, to_bb))
477         } else {
478             None
479         }
480     }
481 }
482 
483 /// If enabled, this struct captures additional data used to track whether expressions were used,
484 /// directly or indirectly, to compute the coverage counts for all `CoverageSpan`s, and any that are
485 /// _not_ used are retained in the `unused_expressions` Vec, to be included in debug output (logs
486 /// and/or a `CoverageGraph` graphviz output).
487 pub(super) struct UsedExpressions {
488     some_used_expression_operands:
489         Option<FxHashMap<ExpressionOperandId, Vec<InjectedExpressionId>>>,
490     some_unused_expressions:
491         Option<Vec<(CoverageKind, Option<BasicCoverageBlock>, BasicCoverageBlock)>>,
492 }
493 
494 impl UsedExpressions {
new() -> Self495     pub fn new() -> Self {
496         Self { some_used_expression_operands: None, some_unused_expressions: None }
497     }
498 
enable(&mut self)499     pub fn enable(&mut self) {
500         debug_assert!(!self.is_enabled());
501         self.some_used_expression_operands = Some(FxHashMap::default());
502         self.some_unused_expressions = Some(Vec::new());
503     }
504 
is_enabled(&self) -> bool505     pub fn is_enabled(&self) -> bool {
506         self.some_used_expression_operands.is_some()
507     }
508 
add_expression_operands(&mut self, expression: &CoverageKind)509     pub fn add_expression_operands(&mut self, expression: &CoverageKind) {
510         if let Some(used_expression_operands) = self.some_used_expression_operands.as_mut() {
511             if let CoverageKind::Expression { id, lhs, rhs, .. } = *expression {
512                 used_expression_operands.entry(lhs).or_insert_with(Vec::new).push(id);
513                 used_expression_operands.entry(rhs).or_insert_with(Vec::new).push(id);
514             }
515         }
516     }
517 
expression_is_used(&self, expression: &CoverageKind) -> bool518     pub fn expression_is_used(&self, expression: &CoverageKind) -> bool {
519         if let Some(used_expression_operands) = self.some_used_expression_operands.as_ref() {
520             used_expression_operands.contains_key(&expression.as_operand_id())
521         } else {
522             false
523         }
524     }
525 
add_unused_expression_if_not_found( &mut self, expression: &CoverageKind, edge_from_bcb: Option<BasicCoverageBlock>, target_bcb: BasicCoverageBlock, )526     pub fn add_unused_expression_if_not_found(
527         &mut self,
528         expression: &CoverageKind,
529         edge_from_bcb: Option<BasicCoverageBlock>,
530         target_bcb: BasicCoverageBlock,
531     ) {
532         if let Some(used_expression_operands) = self.some_used_expression_operands.as_ref() {
533             if !used_expression_operands.contains_key(&expression.as_operand_id()) {
534                 self.some_unused_expressions.as_mut().unwrap().push((
535                     expression.clone(),
536                     edge_from_bcb,
537                     target_bcb,
538                 ));
539             }
540         }
541     }
542 
543     /// Return the list of unused counters (if any) as a tuple with the counter (`CoverageKind`),
544     /// optional `from_bcb` (if it was an edge counter), and `target_bcb`.
get_unused_expressions( &self, ) -> Vec<(CoverageKind, Option<BasicCoverageBlock>, BasicCoverageBlock)>545     pub fn get_unused_expressions(
546         &self,
547     ) -> Vec<(CoverageKind, Option<BasicCoverageBlock>, BasicCoverageBlock)> {
548         if let Some(unused_expressions) = self.some_unused_expressions.as_ref() {
549             unused_expressions.clone()
550         } else {
551             Vec::new()
552         }
553     }
554 
555     /// If enabled, validate that every BCB or edge counter not directly associated with a coverage
556     /// span is at least indirectly associated (it is a dependency of a BCB counter that _is_
557     /// associated with a coverage span).
validate( &mut self, bcb_counters_without_direct_coverage_spans: &[( Option<BasicCoverageBlock>, BasicCoverageBlock, CoverageKind, )], )558     pub fn validate(
559         &mut self,
560         bcb_counters_without_direct_coverage_spans: &[(
561             Option<BasicCoverageBlock>,
562             BasicCoverageBlock,
563             CoverageKind,
564         )],
565     ) {
566         if self.is_enabled() {
567             let mut not_validated = bcb_counters_without_direct_coverage_spans
568                 .iter()
569                 .map(|(_, _, counter_kind)| counter_kind)
570                 .collect::<Vec<_>>();
571             let mut validating_count = 0;
572             while not_validated.len() != validating_count {
573                 let to_validate = not_validated.split_off(0);
574                 validating_count = to_validate.len();
575                 for counter_kind in to_validate {
576                     if self.expression_is_used(counter_kind) {
577                         self.add_expression_operands(counter_kind);
578                     } else {
579                         not_validated.push(counter_kind);
580                     }
581                 }
582             }
583         }
584     }
585 
alert_on_unused_expressions(&self, debug_counters: &DebugCounters)586     pub fn alert_on_unused_expressions(&self, debug_counters: &DebugCounters) {
587         if let Some(unused_expressions) = self.some_unused_expressions.as_ref() {
588             for (counter_kind, edge_from_bcb, target_bcb) in unused_expressions {
589                 let unused_counter_message = if let Some(from_bcb) = edge_from_bcb.as_ref() {
590                     format!(
591                         "non-coverage edge counter found without a dependent expression, in \
592                         {:?}->{:?}; counter={}",
593                         from_bcb,
594                         target_bcb,
595                         debug_counters.format_counter(&counter_kind),
596                     )
597                 } else {
598                     format!(
599                         "non-coverage counter found without a dependent expression, in {:?}; \
600                         counter={}",
601                         target_bcb,
602                         debug_counters.format_counter(&counter_kind),
603                     )
604                 };
605 
606                 if debug_options().allow_unused_expressions {
607                     debug!("WARNING: {}", unused_counter_message);
608                 } else {
609                     bug!("{}", unused_counter_message);
610                 }
611             }
612         }
613     }
614 }
615 
616 /// Generates the MIR pass `CoverageSpan`-specific spanview dump file.
dump_coverage_spanview<'tcx>( tcx: TyCtxt<'tcx>, mir_body: &mir::Body<'tcx>, basic_coverage_blocks: &CoverageGraph, pass_name: &str, body_span: Span, coverage_spans: &[CoverageSpan], )617 pub(super) fn dump_coverage_spanview<'tcx>(
618     tcx: TyCtxt<'tcx>,
619     mir_body: &mir::Body<'tcx>,
620     basic_coverage_blocks: &CoverageGraph,
621     pass_name: &str,
622     body_span: Span,
623     coverage_spans: &[CoverageSpan],
624 ) {
625     let mir_source = mir_body.source;
626     let def_id = mir_source.def_id();
627 
628     let span_viewables = span_viewables(tcx, mir_body, basic_coverage_blocks, &coverage_spans);
629     let mut file = create_dump_file(tcx, "html", false, pass_name, &0i32, mir_body)
630         .expect("Unexpected error creating MIR spanview HTML file");
631     let crate_name = tcx.crate_name(def_id.krate);
632     let item_name = tcx.def_path(def_id).to_filename_friendly_no_crate();
633     let title = format!("{}.{} - Coverage Spans", crate_name, item_name);
634     spanview::write_document(tcx, body_span, span_viewables, &title, &mut file)
635         .expect("Unexpected IO error dumping coverage spans as HTML");
636 }
637 
638 /// Converts the computed `BasicCoverageBlockData`s into `SpanViewable`s.
span_viewables<'tcx>( tcx: TyCtxt<'tcx>, mir_body: &mir::Body<'tcx>, basic_coverage_blocks: &CoverageGraph, coverage_spans: &[CoverageSpan], ) -> Vec<SpanViewable>639 fn span_viewables<'tcx>(
640     tcx: TyCtxt<'tcx>,
641     mir_body: &mir::Body<'tcx>,
642     basic_coverage_blocks: &CoverageGraph,
643     coverage_spans: &[CoverageSpan],
644 ) -> Vec<SpanViewable> {
645     let mut span_viewables = Vec::new();
646     for coverage_span in coverage_spans {
647         let tooltip = coverage_span.format_coverage_statements(tcx, mir_body);
648         let CoverageSpan { span, bcb, .. } = coverage_span;
649         let bcb_data = &basic_coverage_blocks[*bcb];
650         let id = bcb_data.id();
651         let leader_bb = bcb_data.leader_bb();
652         span_viewables.push(SpanViewable { bb: leader_bb, span: *span, id, tooltip });
653     }
654     span_viewables
655 }
656 
657 /// Generates the MIR pass coverage-specific graphviz dump file.
dump_coverage_graphviz<'tcx>( tcx: TyCtxt<'tcx>, mir_body: &mir::Body<'tcx>, pass_name: &str, basic_coverage_blocks: &CoverageGraph, debug_counters: &DebugCounters, graphviz_data: &GraphvizData, intermediate_expressions: &[CoverageKind], debug_used_expressions: &UsedExpressions, )658 pub(super) fn dump_coverage_graphviz<'tcx>(
659     tcx: TyCtxt<'tcx>,
660     mir_body: &mir::Body<'tcx>,
661     pass_name: &str,
662     basic_coverage_blocks: &CoverageGraph,
663     debug_counters: &DebugCounters,
664     graphviz_data: &GraphvizData,
665     intermediate_expressions: &[CoverageKind],
666     debug_used_expressions: &UsedExpressions,
667 ) {
668     let mir_source = mir_body.source;
669     let def_id = mir_source.def_id();
670     let node_content = |bcb| {
671         bcb_to_string_sections(
672             tcx,
673             mir_body,
674             debug_counters,
675             &basic_coverage_blocks[bcb],
676             graphviz_data.get_bcb_coverage_spans_with_counters(bcb),
677             graphviz_data.get_bcb_dependency_counters(bcb),
678             // intermediate_expressions are injected into the mir::START_BLOCK, so
679             // include them in the first BCB.
680             if bcb.index() == 0 { Some(&intermediate_expressions) } else { None },
681         )
682     };
683     let edge_labels = |from_bcb| {
684         let from_bcb_data = &basic_coverage_blocks[from_bcb];
685         let from_terminator = from_bcb_data.terminator(mir_body);
686         let mut edge_labels = from_terminator.kind.fmt_successor_labels();
687         edge_labels.retain(|label| label != "unreachable");
688         let edge_counters = from_terminator
689             .successors()
690             .map(|successor_bb| graphviz_data.get_edge_counter(from_bcb, successor_bb));
691         iter::zip(&edge_labels, edge_counters)
692             .map(|(label, some_counter)| {
693                 if let Some(counter) = some_counter {
694                     format!("{}\n{}", label, debug_counters.format_counter(counter))
695                 } else {
696                     label.to_string()
697                 }
698             })
699             .collect::<Vec<_>>()
700     };
701     let graphviz_name = format!("Cov_{}_{}", def_id.krate.index(), def_id.index.index());
702     let mut graphviz_writer =
703         GraphvizWriter::new(basic_coverage_blocks, &graphviz_name, node_content, edge_labels);
704     let unused_expressions = debug_used_expressions.get_unused_expressions();
705     if unused_expressions.len() > 0 {
706         graphviz_writer.set_graph_label(&format!(
707             "Unused expressions:\n  {}",
708             unused_expressions
709                 .as_slice()
710                 .iter()
711                 .map(|(counter_kind, edge_from_bcb, target_bcb)| {
712                     if let Some(from_bcb) = edge_from_bcb.as_ref() {
713                         format!(
714                             "{:?}->{:?}: {}",
715                             from_bcb,
716                             target_bcb,
717                             debug_counters.format_counter(&counter_kind),
718                         )
719                     } else {
720                         format!(
721                             "{:?}: {}",
722                             target_bcb,
723                             debug_counters.format_counter(&counter_kind),
724                         )
725                     }
726                 })
727                 .join("\n  ")
728         ));
729     }
730     let mut file = create_dump_file(tcx, "dot", false, pass_name, &0i32, mir_body)
731         .expect("Unexpected error creating BasicCoverageBlock graphviz DOT file");
732     graphviz_writer
733         .write_graphviz(tcx, &mut file)
734         .expect("Unexpected error writing BasicCoverageBlock graphviz DOT file");
735 }
736 
bcb_to_string_sections<'tcx>( tcx: TyCtxt<'tcx>, mir_body: &mir::Body<'tcx>, debug_counters: &DebugCounters, bcb_data: &BasicCoverageBlockData, some_coverage_spans_with_counters: Option<&[(CoverageSpan, CoverageKind)]>, some_dependency_counters: Option<&[CoverageKind]>, some_intermediate_expressions: Option<&[CoverageKind]>, ) -> Vec<String>737 fn bcb_to_string_sections<'tcx>(
738     tcx: TyCtxt<'tcx>,
739     mir_body: &mir::Body<'tcx>,
740     debug_counters: &DebugCounters,
741     bcb_data: &BasicCoverageBlockData,
742     some_coverage_spans_with_counters: Option<&[(CoverageSpan, CoverageKind)]>,
743     some_dependency_counters: Option<&[CoverageKind]>,
744     some_intermediate_expressions: Option<&[CoverageKind]>,
745 ) -> Vec<String> {
746     let len = bcb_data.basic_blocks.len();
747     let mut sections = Vec::new();
748     if let Some(collect_intermediate_expressions) = some_intermediate_expressions {
749         sections.push(
750             collect_intermediate_expressions
751                 .iter()
752                 .map(|expression| {
753                     format!("Intermediate {}", debug_counters.format_counter(expression))
754                 })
755                 .join("\n"),
756         );
757     }
758     if let Some(coverage_spans_with_counters) = some_coverage_spans_with_counters {
759         sections.push(
760             coverage_spans_with_counters
761                 .iter()
762                 .map(|(covspan, counter)| {
763                     format!(
764                         "{} at {}",
765                         debug_counters.format_counter(counter),
766                         covspan.format(tcx, mir_body)
767                     )
768                 })
769                 .join("\n"),
770         );
771     }
772     if let Some(dependency_counters) = some_dependency_counters {
773         sections.push(format!(
774             "Non-coverage counters:\n  {}",
775             dependency_counters
776                 .iter()
777                 .map(|counter| debug_counters.format_counter(counter))
778                 .join("  \n"),
779         ));
780     }
781     if let Some(counter_kind) = &bcb_data.counter_kind {
782         sections.push(format!("{:?}", counter_kind));
783     }
784     let non_term_blocks = bcb_data.basic_blocks[0..len - 1]
785         .iter()
786         .map(|&bb| format!("{:?}: {}", bb, mir_body[bb].terminator().kind.name()))
787         .collect::<Vec<_>>();
788     if non_term_blocks.len() > 0 {
789         sections.push(non_term_blocks.join("\n"));
790     }
791     sections.push(format!(
792         "{:?}: {}",
793         bcb_data.basic_blocks.last().unwrap(),
794         bcb_data.terminator(mir_body).kind.name(),
795     ));
796     sections
797 }
798