Skip to content

Commit 234447c

Browse files
authored
Unrolled build for rust-lang#136031
Rollup merge of rust-lang#136031 - lqd:polonius-debugger-episode-1, r=compiler-errors Expand polonius MIR dump This PR starts expanding the polonius MIR: - switches to an HTML file, to show graphs in the same document as the MIR dump, share them more easily since it's a single file that can be hosted as a gist, and also to allow for interactivity in the near future. - adds the regular NLL MIR + polonius constraints - embeds a mermaid version of the CFG, similar to the graphviz one, but that needs a smaller js than `dot`'s emscripten js from graphvizonline [Here's an example](https://gistpreview.github.io/?0c18f2a59b5e24ac0f96447aa34ffe00) of how it looks. --- In future PRs: mermaid graphs of the NLL region graph, of the NLL SCCs, of the polonius localized outlives constraints, and the interactive polonius MIR dump. r? ```@matthewjasper```
2 parents 2f0ad2a + 09fb70a commit 234447c

File tree

3 files changed

+216
-34
lines changed

3 files changed

+216
-34
lines changed

compiler/rustc_borrowck/src/polonius/dump.rs

+170-11
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
use std::io;
22

3-
use rustc_middle::mir::pretty::{PrettyPrintMirOptions, dump_mir_with_options};
4-
use rustc_middle::mir::{Body, ClosureRegionRequirements, PassWhere};
3+
use rustc_middle::mir::pretty::{
4+
PassWhere, PrettyPrintMirOptions, create_dump_file, dump_enabled, dump_mir_to_writer,
5+
};
6+
use rustc_middle::mir::{Body, ClosureRegionRequirements};
57
use rustc_middle::ty::TyCtxt;
68
use rustc_session::config::MirIncludeSpans;
79

@@ -10,9 +12,6 @@ use crate::polonius::{LocalizedOutlivesConstraint, LocalizedOutlivesConstraintSe
1012
use crate::{BorrowckInferCtxt, RegionInferenceContext};
1113

1214
/// `-Zdump-mir=polonius` dumps MIR annotated with NLL and polonius specific information.
13-
// Note: this currently duplicates most of NLL MIR, with some additions for the localized outlives
14-
// constraints. This is ok for now as this dump will change in the near future to an HTML file to
15-
// become more useful.
1615
pub(crate) fn dump_polonius_mir<'tcx>(
1716
infcx: &BorrowckInferCtxt<'tcx>,
1817
body: &Body<'tcx>,
@@ -26,25 +25,113 @@ pub(crate) fn dump_polonius_mir<'tcx>(
2625
return;
2726
}
2827

28+
if !dump_enabled(tcx, "polonius", body.source.def_id()) {
29+
return;
30+
}
31+
2932
let localized_outlives_constraints = localized_outlives_constraints
3033
.expect("missing localized constraints with `-Zpolonius=next`");
3134

32-
// We want the NLL extra comments printed by default in NLL MIR dumps (they were removed in
33-
// #112346). Specifying `-Z mir-include-spans` on the CLI still has priority: for example,
34-
// they're always disabled in mir-opt tests to make working with blessed dumps easier.
35+
let _: io::Result<()> = try {
36+
let mut file = create_dump_file(tcx, "html", false, "polonius", &0, body)?;
37+
emit_polonius_dump(
38+
tcx,
39+
body,
40+
regioncx,
41+
borrow_set,
42+
localized_outlives_constraints,
43+
closure_region_requirements,
44+
&mut file,
45+
)?;
46+
};
47+
}
48+
49+
/// The polonius dump consists of:
50+
/// - the NLL MIR
51+
/// - the list of polonius localized constraints
52+
/// - a mermaid graph of the CFG
53+
fn emit_polonius_dump<'tcx>(
54+
tcx: TyCtxt<'tcx>,
55+
body: &Body<'tcx>,
56+
regioncx: &RegionInferenceContext<'tcx>,
57+
borrow_set: &BorrowSet<'tcx>,
58+
localized_outlives_constraints: LocalizedOutlivesConstraintSet,
59+
closure_region_requirements: &Option<ClosureRegionRequirements<'tcx>>,
60+
out: &mut dyn io::Write,
61+
) -> io::Result<()> {
62+
// Prepare the HTML dump file prologue.
63+
writeln!(out, "<!DOCTYPE html>")?;
64+
writeln!(out, "<html>")?;
65+
writeln!(out, "<head><title>Polonius MIR dump</title></head>")?;
66+
writeln!(out, "<body>")?;
67+
68+
// Section 1: the NLL + Polonius MIR.
69+
writeln!(out, "<div>")?;
70+
writeln!(out, "Raw MIR dump")?;
71+
writeln!(out, "<code><pre>")?;
72+
emit_html_mir(
73+
tcx,
74+
body,
75+
regioncx,
76+
borrow_set,
77+
localized_outlives_constraints,
78+
closure_region_requirements,
79+
out,
80+
)?;
81+
writeln!(out, "</pre></code>")?;
82+
writeln!(out, "</div>")?;
83+
84+
// Section 2: mermaid visualization of the CFG.
85+
writeln!(out, "<div>")?;
86+
writeln!(out, "Control-flow graph")?;
87+
writeln!(out, "<code><pre class='mermaid'>")?;
88+
emit_mermaid_cfg(body, out)?;
89+
writeln!(out, "</pre></code>")?;
90+
writeln!(out, "</div>")?;
91+
92+
// Finalize the dump with the HTML epilogue.
93+
writeln!(
94+
out,
95+
"<script src='https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js'></script>"
96+
)?;
97+
writeln!(out, "<script>")?;
98+
writeln!(out, "mermaid.initialize({{ startOnLoad: false, maxEdges: 100 }});")?;
99+
writeln!(out, "mermaid.run({{ querySelector: '.mermaid' }})")?;
100+
writeln!(out, "</script>")?;
101+
writeln!(out, "</body>")?;
102+
writeln!(out, "</html>")?;
103+
104+
Ok(())
105+
}
106+
107+
/// Emits the polonius MIR, as escaped HTML.
108+
fn emit_html_mir<'tcx>(
109+
tcx: TyCtxt<'tcx>,
110+
body: &Body<'tcx>,
111+
regioncx: &RegionInferenceContext<'tcx>,
112+
borrow_set: &BorrowSet<'tcx>,
113+
localized_outlives_constraints: LocalizedOutlivesConstraintSet,
114+
closure_region_requirements: &Option<ClosureRegionRequirements<'tcx>>,
115+
out: &mut dyn io::Write,
116+
) -> io::Result<()> {
117+
// Buffer the regular MIR dump to be able to escape it.
118+
let mut buffer = Vec::new();
119+
120+
// We want the NLL extra comments printed by default in NLL MIR dumps. Specifying `-Z
121+
// mir-include-spans` on the CLI still has priority.
35122
let options = PrettyPrintMirOptions {
36123
include_extra_comments: matches!(
37124
tcx.sess.opts.unstable_opts.mir_include_spans,
38125
MirIncludeSpans::On | MirIncludeSpans::Nll
39126
),
40127
};
41128

42-
dump_mir_with_options(
129+
dump_mir_to_writer(
43130
tcx,
44-
false,
45131
"polonius",
46132
&0,
47133
body,
134+
&mut buffer,
48135
|pass_where, out| {
49136
emit_polonius_mir(
50137
tcx,
@@ -57,7 +144,27 @@ pub(crate) fn dump_polonius_mir<'tcx>(
57144
)
58145
},
59146
options,
60-
);
147+
)?;
148+
149+
// Escape the handful of characters that need it. We don't need to be particularly efficient:
150+
// we're actually writing into a buffered writer already. Note that MIR dumps are valid UTF-8.
151+
let buffer = String::from_utf8_lossy(&buffer);
152+
for ch in buffer.chars() {
153+
let escaped = match ch {
154+
'>' => "&gt;",
155+
'<' => "&lt;",
156+
'&' => "&amp;",
157+
'\'' => "&#39;",
158+
'"' => "&quot;",
159+
_ => {
160+
// The common case, no escaping needed.
161+
write!(out, "{}", ch)?;
162+
continue;
163+
}
164+
};
165+
write!(out, "{}", escaped)?;
166+
}
167+
Ok(())
61168
}
62169

63170
/// Produces the actual NLL + Polonius MIR sections to emit during the dumping process.
@@ -102,3 +209,55 @@ fn emit_polonius_mir<'tcx>(
102209

103210
Ok(())
104211
}
212+
213+
/// Emits a mermaid flowchart of the CFG blocks and edges, similar to the graphviz version.
214+
fn emit_mermaid_cfg(body: &Body<'_>, out: &mut dyn io::Write) -> io::Result<()> {
215+
use rustc_middle::mir::{TerminatorEdges, TerminatorKind};
216+
217+
// The mermaid chart type: a top-down flowchart.
218+
writeln!(out, "flowchart TD")?;
219+
220+
// Emit the block nodes.
221+
for (block_idx, block) in body.basic_blocks.iter_enumerated() {
222+
let block_idx = block_idx.as_usize();
223+
let cleanup = if block.is_cleanup { " (cleanup)" } else { "" };
224+
writeln!(out, "{block_idx}[\"bb{block_idx}{cleanup}\"]")?;
225+
}
226+
227+
// Emit the edges between blocks, from the terminator edges.
228+
for (block_idx, block) in body.basic_blocks.iter_enumerated() {
229+
let block_idx = block_idx.as_usize();
230+
let terminator = block.terminator();
231+
match terminator.edges() {
232+
TerminatorEdges::None => {}
233+
TerminatorEdges::Single(bb) => {
234+
writeln!(out, "{block_idx} --> {}", bb.as_usize())?;
235+
}
236+
TerminatorEdges::Double(bb1, bb2) => {
237+
if matches!(terminator.kind, TerminatorKind::FalseEdge { .. }) {
238+
writeln!(out, "{block_idx} --> {}", bb1.as_usize())?;
239+
writeln!(out, "{block_idx} -- imaginary --> {}", bb2.as_usize())?;
240+
} else {
241+
writeln!(out, "{block_idx} --> {}", bb1.as_usize())?;
242+
writeln!(out, "{block_idx} -- unwind --> {}", bb2.as_usize())?;
243+
}
244+
}
245+
TerminatorEdges::AssignOnReturn { return_, cleanup, .. } => {
246+
for to_idx in return_ {
247+
writeln!(out, "{block_idx} --> {}", to_idx.as_usize())?;
248+
}
249+
250+
if let Some(to_idx) = cleanup {
251+
writeln!(out, "{block_idx} -- unwind --> {}", to_idx.as_usize())?;
252+
}
253+
}
254+
TerminatorEdges::SwitchInt { targets, .. } => {
255+
for to_idx in targets.all_targets() {
256+
writeln!(out, "{block_idx} --> {}", to_idx.as_usize())?;
257+
}
258+
}
259+
}
260+
}
261+
262+
Ok(())
263+
}

compiler/rustc_middle/src/mir/pretty.rs

+42-21
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
use std::collections::BTreeSet;
22
use std::fmt::{Display, Write as _};
3-
use std::fs;
4-
use std::io::{self, Write as _};
53
use std::path::{Path, PathBuf};
4+
use std::{fs, io};
65

76
use rustc_abi::Size;
87
use rustc_ast::InlineAsmTemplatePiece;
@@ -149,37 +148,59 @@ pub fn dump_enabled(tcx: TyCtxt<'_>, pass_name: &str, def_id: DefId) -> bool {
149148
// `def_path_str()` would otherwise trigger `type_of`, and this can
150149
// run while we are already attempting to evaluate `type_of`.
151150

151+
/// Most use-cases of dumping MIR should use the [dump_mir] entrypoint instead, which will also
152+
/// check if dumping MIR is enabled, and if this body matches the filters passed on the CLI.
153+
///
154+
/// That being said, if the above requirements have been validated already, this function is where
155+
/// most of the MIR dumping occurs, if one needs to export it to a file they have created with
156+
/// [create_dump_file], rather than to a new file created as part of [dump_mir], or to stdout/stderr
157+
/// for debugging purposes.
158+
pub fn dump_mir_to_writer<'tcx, F>(
159+
tcx: TyCtxt<'tcx>,
160+
pass_name: &str,
161+
disambiguator: &dyn Display,
162+
body: &Body<'tcx>,
163+
w: &mut dyn io::Write,
164+
mut extra_data: F,
165+
options: PrettyPrintMirOptions,
166+
) -> io::Result<()>
167+
where
168+
F: FnMut(PassWhere, &mut dyn io::Write) -> io::Result<()>,
169+
{
170+
// see notes on #41697 above
171+
let def_path =
172+
ty::print::with_forced_impl_filename_line!(tcx.def_path_str(body.source.def_id()));
173+
// ignore-tidy-odd-backticks the literal below is fine
174+
write!(w, "// MIR for `{def_path}")?;
175+
match body.source.promoted {
176+
None => write!(w, "`")?,
177+
Some(promoted) => write!(w, "::{promoted:?}`")?,
178+
}
179+
writeln!(w, " {disambiguator} {pass_name}")?;
180+
if let Some(ref layout) = body.coroutine_layout_raw() {
181+
writeln!(w, "/* coroutine_layout = {layout:#?} */")?;
182+
}
183+
writeln!(w)?;
184+
extra_data(PassWhere::BeforeCFG, w)?;
185+
write_user_type_annotations(tcx, body, w)?;
186+
write_mir_fn(tcx, body, &mut extra_data, w, options)?;
187+
extra_data(PassWhere::AfterCFG, w)
188+
}
189+
152190
fn dump_matched_mir_node<'tcx, F>(
153191
tcx: TyCtxt<'tcx>,
154192
pass_num: bool,
155193
pass_name: &str,
156194
disambiguator: &dyn Display,
157195
body: &Body<'tcx>,
158-
mut extra_data: F,
196+
extra_data: F,
159197
options: PrettyPrintMirOptions,
160198
) where
161199
F: FnMut(PassWhere, &mut dyn io::Write) -> io::Result<()>,
162200
{
163201
let _: io::Result<()> = try {
164202
let mut file = create_dump_file(tcx, "mir", pass_num, pass_name, disambiguator, body)?;
165-
// see notes on #41697 above
166-
let def_path =
167-
ty::print::with_forced_impl_filename_line!(tcx.def_path_str(body.source.def_id()));
168-
// ignore-tidy-odd-backticks the literal below is fine
169-
write!(file, "// MIR for `{def_path}")?;
170-
match body.source.promoted {
171-
None => write!(file, "`")?,
172-
Some(promoted) => write!(file, "::{promoted:?}`")?,
173-
}
174-
writeln!(file, " {disambiguator} {pass_name}")?;
175-
if let Some(ref layout) = body.coroutine_layout_raw() {
176-
writeln!(file, "/* coroutine_layout = {layout:#?} */")?;
177-
}
178-
writeln!(file)?;
179-
extra_data(PassWhere::BeforeCFG, &mut file)?;
180-
write_user_type_annotations(tcx, body, &mut file)?;
181-
write_mir_fn(tcx, body, &mut extra_data, &mut file, options)?;
182-
extra_data(PassWhere::AfterCFG, &mut file)?;
203+
dump_mir_to_writer(tcx, pass_name, disambiguator, body, &mut file, extra_data, options)?;
183204
};
184205

185206
if tcx.sess.opts.unstable_opts.dump_mir_graphviz {

compiler/rustc_middle/src/mir/terminator.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -581,9 +581,11 @@ impl<'tcx> TerminatorKind<'tcx> {
581581
pub enum TerminatorEdges<'mir, 'tcx> {
582582
/// For terminators that have no successor, like `return`.
583583
None,
584-
/// For terminators that a single successor, like `goto`, and `assert` without cleanup block.
584+
/// For terminators that have a single successor, like `goto`, and `assert` without a cleanup
585+
/// block.
585586
Single(BasicBlock),
586-
/// For terminators that two successors, `assert` with cleanup block and `falseEdge`.
587+
/// For terminators that have two successors, like `assert` with a cleanup block, and
588+
/// `falseEdge`.
587589
Double(BasicBlock, BasicBlock),
588590
/// Special action for `Yield`, `Call` and `InlineAsm` terminators.
589591
AssignOnReturn {

0 commit comments

Comments
 (0)