Auto merge of #105121 - oli-obk:simpler-cheaper-dump_mir, r=nnethercote

Cheaper `dump_mir` take two

alternative to #105083

r? `@nnethercote`
This commit is contained in:
bors 2022-12-04 05:47:10 +00:00
commit fd02567705
13 changed files with 60 additions and 110 deletions

View File

@ -73,7 +73,7 @@ pub(crate) fn replace_regions_in_mir<'tcx>(
// Replace all remaining regions with fresh inference variables.
renumber::renumber_mir(infcx, body, promoted);
dump_mir(infcx.tcx, None, "renumber", &0, body, |_, _| Ok(()));
dump_mir(infcx.tcx, false, "renumber", &0, body, |_, _| Ok(()));
universal_regions
}
@ -331,7 +331,7 @@ pub(super) fn dump_mir_results<'tcx>(
return;
}
dump_mir(infcx.tcx, None, "nll", &0, body, |pass_where, out| {
dump_mir(infcx.tcx, false, "nll", &0, body, |pass_where, out| {
match pass_where {
// Before the CFG, dump out the values for each region variable.
PassWhere::BeforeCFG => {
@ -358,15 +358,13 @@ pub(super) fn dump_mir_results<'tcx>(
// Also dump the inference graph constraints as a graphviz file.
let _: io::Result<()> = try {
let mut file =
create_dump_file(infcx.tcx, "regioncx.all.dot", None, "nll", &0, body.source)?;
let mut file = create_dump_file(infcx.tcx, "regioncx.all.dot", false, "nll", &0, body)?;
regioncx.dump_graphviz_raw_constraints(&mut file)?;
};
// Also dump the inference graph constraints as a graphviz file.
let _: io::Result<()> = try {
let mut file =
create_dump_file(infcx.tcx, "regioncx.scc.dot", None, "nll", &0, body.source)?;
let mut file = create_dump_file(infcx.tcx, "regioncx.scc.dot", false, "nll", &0, body)?;
regioncx.dump_graphviz_scc_constraints(&mut file)?;
};
}

View File

@ -100,13 +100,9 @@ fn local_decls(&self) -> &LocalDecls<'tcx> {
/// pass will be named after the type, and it will consist of a main
/// loop that goes over each available MIR and applies `run_pass`.
pub trait MirPass<'tcx> {
fn name(&self) -> Cow<'_, str> {
fn name(&self) -> &str {
let name = std::any::type_name::<Self>();
if let Some(tail) = name.rfind(':') {
Cow::from(&name[tail + 1..])
} else {
Cow::from(name)
}
if let Some((_, tail)) = name.rsplit_once(':') { tail } else { name }
}
/// Returns `true` if this pass is enabled with the current combination of compiler flags.
@ -182,35 +178,6 @@ pub fn parse(phase: Option<String>) -> Self {
}
}
impl Display for MirPhase {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
MirPhase::Built => write!(f, "built"),
MirPhase::Analysis(p) => write!(f, "analysis-{}", p),
MirPhase::Runtime(p) => write!(f, "runtime-{}", p),
}
}
}
impl Display for AnalysisPhase {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
AnalysisPhase::Initial => write!(f, "initial"),
AnalysisPhase::PostCleanup => write!(f, "post_cleanup"),
}
}
}
impl Display for RuntimePhase {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
RuntimePhase::Initial => write!(f, "initial"),
RuntimePhase::PostCleanup => write!(f, "post_cleanup"),
RuntimePhase::Optimized => write!(f, "optimized"),
}
}
}
/// Where a specific `mir::Body` comes from.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable, TypeVisitable)]
@ -368,7 +335,7 @@ pub fn new(
let mut body = Body {
phase: MirPhase::Built,
pass_count: 1,
pass_count: 0,
source,
basic_blocks: BasicBlocks::new(basic_blocks),
source_scopes,
@ -403,7 +370,7 @@ pub fn new(
pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
let mut body = Body {
phase: MirPhase::Built,
pass_count: 1,
pass_count: 0,
source: MirSource::item(CRATE_DEF_ID.to_def_id()),
basic_blocks: BasicBlocks::new(basic_blocks),
source_scopes: IndexVec::new(),

View File

@ -16,7 +16,6 @@
Pointer, Provenance,
};
use rustc_middle::mir::visit::Visitor;
use rustc_middle::mir::MirSource;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, TyCtxt};
use rustc_target::abi::Size;
@ -74,7 +73,7 @@ pub enum PassWhere {
#[inline]
pub fn dump_mir<'tcx, F>(
tcx: TyCtxt<'tcx>,
pass_num: Option<&dyn Display>,
pass_num: bool,
pass_name: &str,
disambiguator: &dyn Display,
body: &Body<'tcx>,
@ -111,7 +110,7 @@ pub fn dump_enabled<'tcx>(tcx: TyCtxt<'tcx>, pass_name: &str, def_id: DefId) ->
fn dump_matched_mir_node<'tcx, F>(
tcx: TyCtxt<'tcx>,
pass_num: Option<&dyn Display>,
pass_num: bool,
pass_name: &str,
disambiguator: &dyn Display,
body: &Body<'tcx>,
@ -120,8 +119,7 @@ fn dump_matched_mir_node<'tcx, F>(
F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
{
let _: io::Result<()> = try {
let mut file =
create_dump_file(tcx, "mir", pass_num, pass_name, disambiguator, body.source)?;
let mut file = create_dump_file(tcx, "mir", pass_num, pass_name, disambiguator, body)?;
// see notes on #41697 above
let def_path =
ty::print::with_forced_impl_filename_line!(tcx.def_path_str(body.source.def_id()));
@ -143,16 +141,14 @@ fn dump_matched_mir_node<'tcx, F>(
if tcx.sess.opts.unstable_opts.dump_mir_graphviz {
let _: io::Result<()> = try {
let mut file =
create_dump_file(tcx, "dot", pass_num, pass_name, disambiguator, body.source)?;
let mut file = create_dump_file(tcx, "dot", pass_num, pass_name, disambiguator, body)?;
write_mir_fn_graphviz(tcx, body, false, &mut file)?;
};
}
if let Some(spanview) = tcx.sess.opts.unstable_opts.dump_mir_spanview {
let _: io::Result<()> = try {
let file_basename =
dump_file_basename(tcx, pass_num, pass_name, disambiguator, body.source);
let file_basename = dump_file_basename(tcx, pass_num, pass_name, disambiguator, body);
let mut file = create_dump_file_with_basename(tcx, &file_basename, "html")?;
if body.source.def_id().is_local() {
write_mir_fn_spanview(tcx, body, spanview, &file_basename, &mut file)?;
@ -165,11 +161,12 @@ fn dump_matched_mir_node<'tcx, F>(
/// where we should dump a MIR representation output files.
fn dump_file_basename<'tcx>(
tcx: TyCtxt<'tcx>,
pass_num: Option<&dyn Display>,
pass_num: bool,
pass_name: &str,
disambiguator: &dyn Display,
source: MirSource<'tcx>,
body: &Body<'tcx>,
) -> String {
let source = body.source;
let promotion_id = match source.promoted {
Some(id) => format!("-{:?}", id),
None => String::new(),
@ -178,9 +175,10 @@ fn dump_file_basename<'tcx>(
let pass_num = if tcx.sess.opts.unstable_opts.dump_mir_exclude_pass_number {
String::new()
} else {
match pass_num {
None => ".-------".to_string(),
Some(pass_num) => format!(".{}", pass_num),
if pass_num {
format!(".{:03}-{:03}", body.phase.phase_index(), body.pass_count)
} else {
".-------".to_string()
}
};
@ -250,14 +248,14 @@ fn create_dump_file_with_basename(
pub fn create_dump_file<'tcx>(
tcx: TyCtxt<'tcx>,
extension: &str,
pass_num: Option<&dyn Display>,
pass_num: bool,
pass_name: &str,
disambiguator: &dyn Display,
source: MirSource<'tcx>,
body: &Body<'tcx>,
) -> io::Result<io::BufWriter<fs::File>> {
create_dump_file_with_basename(
tcx,
&dump_file_basename(tcx, pass_num, pass_name, disambiguator, source),
&dump_file_basename(tcx, pass_num, pass_name, disambiguator, body),
extension,
)
}

View File

@ -89,6 +89,19 @@ pub enum MirPhase {
Runtime(RuntimePhase),
}
impl MirPhase {
pub fn name(&self) -> &'static str {
match *self {
MirPhase::Built => "built",
MirPhase::Analysis(AnalysisPhase::Initial) => "analysis",
MirPhase::Analysis(AnalysisPhase::PostCleanup) => "analysis-post-cleanup",
MirPhase::Runtime(RuntimePhase::Initial) => "runtime",
MirPhase::Runtime(RuntimePhase::PostCleanup) => "runtime-post-cleanup",
MirPhase::Runtime(RuntimePhase::Optimized) => "runtime-optimized",
}
}
}
/// See [`MirPhase::Analysis`].
#[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[derive(HashStable)]

View File

@ -57,7 +57,7 @@ pub(super) fn build_custom_mir<'tcx>(
is_polymorphic: false,
tainted_by_errors: None,
injection_phase: None,
pass_count: 1,
pass_count: 0,
};
body.local_decls.push(LocalDecl::new(return_ty, return_ty_span));

View File

@ -294,14 +294,7 @@ fn write_graphviz_results<'tcx, A>(
None if tcx.sess.opts.unstable_opts.dump_mir_dataflow
&& dump_enabled(tcx, A::NAME, def_id) =>
{
create_dump_file(
tcx,
".dot",
None,
A::NAME,
&pass_name.unwrap_or("-----"),
body.source,
)?
create_dump_file(tcx, ".dot", false, A::NAME, &pass_name.unwrap_or("-----"), body)?
}
_ => return Ok(()),

View File

@ -638,7 +638,7 @@ pub(super) fn dump_coverage_spanview<'tcx>(
let def_id = mir_source.def_id();
let span_viewables = span_viewables(tcx, mir_body, basic_coverage_blocks, &coverage_spans);
let mut file = create_dump_file(tcx, "html", None, pass_name, &0, mir_source)
let mut file = create_dump_file(tcx, "html", false, pass_name, &0, mir_body)
.expect("Unexpected error creating MIR spanview HTML file");
let crate_name = tcx.crate_name(def_id.krate);
let item_name = tcx.def_path(def_id).to_filename_friendly_no_crate();
@ -739,7 +739,7 @@ pub(super) fn dump_coverage_graphviz<'tcx>(
.join("\n ")
));
}
let mut file = create_dump_file(tcx, "dot", None, pass_name, &0, mir_source)
let mut file = create_dump_file(tcx, "dot", false, pass_name, &0, mir_body)
.expect("Unexpected error creating BasicCoverageBlock graphviz DOT file");
graphviz_writer
.write_graphviz(tcx, &mut file)

View File

@ -787,7 +787,7 @@ fn dest_prop_mir_dump<'body, 'tcx>(
round: usize,
) {
let mut reachable = None;
dump_mir(tcx, None, "DestinationPropagation-dataflow", &round, body, |pass_where, w| {
dump_mir(tcx, false, "DestinationPropagation-dataflow", &round, body, |pass_where, w| {
let reachable = reachable.get_or_insert_with(|| traversal::reachable_as_bitset(body));
match pass_where {

View File

@ -1,6 +1,5 @@
//! This pass just dumps MIR at a specified point.
use std::borrow::Cow;
use std::fs::File;
use std::io;
@ -13,8 +12,8 @@
pub struct Marker(pub &'static str);
impl<'tcx> MirPass<'tcx> for Marker {
fn name(&self) -> Cow<'_, str> {
Cow::Borrowed(self.0)
fn name(&self) -> &str {
self.0
}
fn run_pass(&self, _tcx: TyCtxt<'tcx>, _body: &mut Body<'tcx>) {}

View File

@ -1000,7 +1000,7 @@ fn create_generator_drop_shim<'tcx>(
// unrelated code from the resume part of the function
simplify::remove_dead_blocks(tcx, &mut body);
dump_mir(tcx, None, "generator_drop", &0, &body, |_, _| Ok(()));
dump_mir(tcx, false, "generator_drop", &0, &body, |_, _| Ok(()));
body
}
@ -1171,7 +1171,7 @@ fn create_generator_resume_function<'tcx>(
// unrelated code from the drop part of the function
simplify::remove_dead_blocks(tcx, body);
dump_mir(tcx, None, "generator_resume", &0, body, |_, _| Ok(()));
dump_mir(tcx, false, "generator_resume", &0, body, |_, _| Ok(()));
}
fn insert_clean_drop(body: &mut Body<'_>) -> BasicBlock {
@ -1394,14 +1394,14 @@ fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
// This is expanded to a drop ladder in `elaborate_generator_drops`.
let drop_clean = insert_clean_drop(body);
dump_mir(tcx, None, "generator_pre-elab", &0, body, |_, _| Ok(()));
dump_mir(tcx, false, "generator_pre-elab", &0, body, |_, _| Ok(()));
// Expand `drop(generator_struct)` to a drop ladder which destroys upvars.
// If any upvars are moved out of, drop elaboration will handle upvar destruction.
// However we need to also elaborate the code generated by `insert_clean_drop`.
elaborate_generator_drops(tcx, body);
dump_mir(tcx, None, "generator_post-transform", &0, body, |_, _| Ok(()));
dump_mir(tcx, false, "generator_post-transform", &0, body, |_, _| Ok(()));
// Create a copy of our MIR and use it to create the drop shim for the generator
let drop_shim = create_generator_drop_shim(tcx, &transform, gen_ty, body, drop_clean);

View File

@ -1,5 +1,3 @@
use std::borrow::Cow;
use rustc_middle::mir::{self, Body, MirPhase, RuntimePhase};
use rustc_middle::ty::TyCtxt;
use rustc_session::Session;
@ -8,13 +6,9 @@
/// Just like `MirPass`, except it cannot mutate `Body`.
pub trait MirLint<'tcx> {
fn name(&self) -> Cow<'_, str> {
fn name(&self) -> &str {
let name = std::any::type_name::<Self>();
if let Some(tail) = name.rfind(':') {
Cow::from(&name[tail + 1..])
} else {
Cow::from(name)
}
if let Some((_, tail)) = name.rsplit_once(':') { tail } else { name }
}
fn is_enabled(&self, _sess: &Session) -> bool {
@ -32,7 +26,7 @@ impl<'tcx, T> MirPass<'tcx> for Lint<T>
where
T: MirLint<'tcx>,
{
fn name(&self) -> Cow<'_, str> {
fn name(&self) -> &str {
self.0.name()
}
@ -55,7 +49,7 @@ impl<'tcx, T> MirPass<'tcx> for WithMinOptLevel<T>
where
T: MirPass<'tcx>,
{
fn name(&self) -> Cow<'_, str> {
fn name(&self) -> &str {
self.1.name()
}
@ -146,10 +140,11 @@ fn run_passes_inner<'tcx>(
}
body.phase = new_phase;
body.pass_count = 0;
dump_mir_for_phase_change(tcx, body);
if validate || new_phase == MirPhase::Runtime(RuntimePhase::Optimized) {
validate_body(tcx, body, format!("after phase change to {}", new_phase));
validate_body(tcx, body, format!("after phase change to {}", new_phase.name()));
}
body.pass_count = 1;
@ -166,11 +161,9 @@ pub fn dump_mir_for_pass<'tcx>(
pass_name: &str,
is_after: bool,
) {
let phase_index = body.phase.phase_index();
mir::dump_mir(
tcx,
Some(&format_args!("{:03}-{:03}", phase_index, body.pass_count)),
true,
pass_name,
if is_after { &"after" } else { &"before" },
body,
@ -179,14 +172,6 @@ pub fn dump_mir_for_pass<'tcx>(
}
pub fn dump_mir_for_phase_change<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
let phase_index = body.phase.phase_index();
mir::dump_mir(
tcx,
Some(&format_args!("{:03}-000", phase_index)),
&format!("{}", body.phase),
&"after",
body,
|_, _| Ok(()),
)
assert_eq!(body.pass_count, 0);
mir::dump_mir(tcx, true, body.phase.name(), &"after", body, |_, _| Ok(()))
}

View File

@ -35,7 +35,6 @@
use rustc_middle::mir::*;
use rustc_middle::ty::TyCtxt;
use smallvec::SmallVec;
use std::borrow::Cow;
use std::convert::TryInto;
pub struct SimplifyCfg {
@ -57,8 +56,8 @@ pub fn simplify_cfg<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
}
impl<'tcx> MirPass<'tcx> for SimplifyCfg {
fn name(&self) -> Cow<'_, str> {
Cow::Borrowed(&self.label)
fn name(&self) -> &str {
&self.label
}
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {

View File

@ -2,8 +2,6 @@
use rustc_middle::mir::*;
use rustc_middle::ty::TyCtxt;
use std::borrow::Cow;
/// A pass that replaces a branch with a goto when its condition is known.
pub struct SimplifyConstCondition {
label: String,
@ -16,8 +14,8 @@ pub fn new(label: &str) -> Self {
}
impl<'tcx> MirPass<'tcx> for SimplifyConstCondition {
fn name(&self) -> Cow<'_, str> {
Cow::Borrowed(&self.label)
fn name(&self) -> &str {
&self.label
}
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {