Skip to content

Commit bed4ad6

Browse files
committed
Auto merge of rust-lang#102340 - JakobDegen:pass-manager-simplification, r=oli-obk
Split phase change from `MirPass` The main goal here is to simplify the pass manager logic. `MirPass` no longer contains the `phase_change` method, and `run_passes` instead accepts an `Option<PhaseChange>`. The hope is that this addresses the comments (and maybe perf regression) from rust-lang#99102 . r? `@oli-obk` cc `@RalfJung`
2 parents 85d089b + be2401b commit bed4ad6

File tree

6 files changed

+101
-76
lines changed

6 files changed

+101
-76
lines changed

compiler/rustc_const_eval/src/transform/promote_consts.rs

-4
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,6 @@ pub struct PromoteTemps<'tcx> {
4141
}
4242

4343
impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> {
44-
fn phase_change(&self) -> Option<MirPhase> {
45-
Some(MirPhase::Analysis(AnalysisPhase::Initial))
46-
}
47-
4844
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
4945
// There's not really any point in promoting errorful MIR.
5046
//

compiler/rustc_middle/src/mir/mod.rs

+34-5
Original file line numberDiff line numberDiff line change
@@ -116,11 +116,6 @@ pub trait MirPass<'tcx> {
116116

117117
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>);
118118

119-
/// If this pass causes the MIR to enter a new phase, return that phase.
120-
fn phase_change(&self) -> Option<MirPhase> {
121-
None
122-
}
123-
124119
fn is_mir_dump_enabled(&self) -> bool {
125120
true
126121
}
@@ -145,6 +140,35 @@ impl MirPhase {
145140
}
146141
}
147142

143+
impl Display for MirPhase {
144+
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
145+
match self {
146+
MirPhase::Built => write!(f, "built"),
147+
MirPhase::Analysis(p) => write!(f, "analysis-{}", p),
148+
MirPhase::Runtime(p) => write!(f, "runtime-{}", p),
149+
}
150+
}
151+
}
152+
153+
impl Display for AnalysisPhase {
154+
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
155+
match self {
156+
AnalysisPhase::Initial => write!(f, "initial"),
157+
AnalysisPhase::PostCleanup => write!(f, "post_cleanup"),
158+
}
159+
}
160+
}
161+
162+
impl Display for RuntimePhase {
163+
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
164+
match self {
165+
RuntimePhase::Initial => write!(f, "initial"),
166+
RuntimePhase::PostCleanup => write!(f, "post_cleanup"),
167+
RuntimePhase::Optimized => write!(f, "optimized"),
168+
}
169+
}
170+
}
171+
148172
/// Where a specific `mir::Body` comes from.
149173
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
150174
#[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable, TypeVisitable)]
@@ -207,6 +231,9 @@ pub struct Body<'tcx> {
207231
/// us to see the difference and forego optimization on the inlined promoted items.
208232
pub phase: MirPhase,
209233

234+
/// How many passses we have executed since starting the current phase. Used for debug output.
235+
pub pass_count: usize,
236+
210237
pub source: MirSource<'tcx>,
211238

212239
/// A list of source scopes; these are referenced by statements
@@ -292,6 +319,7 @@ impl<'tcx> Body<'tcx> {
292319

293320
let mut body = Body {
294321
phase: MirPhase::Built,
322+
pass_count: 1,
295323
source,
296324
basic_blocks: BasicBlocks::new(basic_blocks),
297325
source_scopes,
@@ -325,6 +353,7 @@ impl<'tcx> Body<'tcx> {
325353
pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
326354
let mut body = Body {
327355
phase: MirPhase::Built,
356+
pass_count: 1,
328357
source: MirSource::item(CRATE_DEF_ID.to_def_id()),
329358
basic_blocks: BasicBlocks::new(basic_blocks),
330359
source_scopes: IndexVec::new(),

compiler/rustc_mir_transform/src/lib.rs

+9-12
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,6 @@ mod inline;
7171
mod instcombine;
7272
mod lower_intrinsics;
7373
mod lower_slice_len;
74-
mod marker;
7574
mod match_branches;
7675
mod multiple_return_terminators;
7776
mod normalize_array_len;
@@ -303,6 +302,7 @@ fn mir_const<'tcx>(
303302
&simplify::SimplifyCfg::new("initial"),
304303
&rustc_peek::SanityCheck, // Just a lint
305304
],
305+
None,
306306
);
307307
tcx.alloc_steal_mir(body)
308308
}
@@ -342,6 +342,7 @@ fn mir_promoted<'tcx>(
342342
&simplify::SimplifyCfg::new("promote-consts"),
343343
&coverage::InstrumentCoverage,
344344
],
345+
Some(MirPhase::Analysis(AnalysisPhase::Initial)),
345346
);
346347

347348
let promoted = promote_pass.promoted_fragments.into_inner();
@@ -409,10 +410,8 @@ fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -
409410
pm::run_passes(
410411
tcx,
411412
&mut body,
412-
&[
413-
&const_prop::ConstProp,
414-
&marker::PhaseChange(MirPhase::Runtime(RuntimePhase::Optimized)),
415-
],
413+
&[&const_prop::ConstProp],
414+
Some(MirPhase::Runtime(RuntimePhase::Optimized)),
416415
);
417416
}
418417
}
@@ -474,6 +473,7 @@ fn run_analysis_to_runtime_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>
474473
&remove_uninit_drops::RemoveUninitDrops,
475474
&simplify::SimplifyCfg::new("remove-false-edges"),
476475
],
476+
None,
477477
);
478478
check_consts::post_drop_elaboration::check_live_drops(tcx, &body); // FIXME: make this a MIR lint
479479
}
@@ -498,10 +498,9 @@ fn run_analysis_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
498498
&cleanup_post_borrowck::CleanupNonCodegenStatements,
499499
&simplify::SimplifyCfg::new("early-opt"),
500500
&deref_separator::Derefer,
501-
&marker::PhaseChange(MirPhase::Analysis(AnalysisPhase::PostCleanup)),
502501
];
503502

504-
pm::run_passes(tcx, body, passes);
503+
pm::run_passes(tcx, body, passes, Some(MirPhase::Analysis(AnalysisPhase::PostCleanup)));
505504
}
506505

507506
/// Returns the sequence of passes that lowers analysis to runtime MIR.
@@ -526,9 +525,8 @@ fn run_runtime_lowering_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
526525
// CTFE support for aggregates.
527526
&deaggregator::Deaggregator,
528527
&Lint(const_prop_lint::ConstProp),
529-
&marker::PhaseChange(MirPhase::Runtime(RuntimePhase::Initial)),
530528
];
531-
pm::run_passes_no_validate(tcx, body, passes);
529+
pm::run_passes_no_validate(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::Initial)));
532530
}
533531

534532
/// Returns the sequence of passes that do the initial cleanup of runtime MIR.
@@ -537,10 +535,9 @@ fn run_runtime_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
537535
&elaborate_box_derefs::ElaborateBoxDerefs,
538536
&lower_intrinsics::LowerIntrinsics,
539537
&simplify::SimplifyCfg::new("elaborate-drops"),
540-
&marker::PhaseChange(MirPhase::Runtime(RuntimePhase::PostCleanup)),
541538
];
542539

543-
pm::run_passes(tcx, body, passes);
540+
pm::run_passes(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::PostCleanup)));
544541
}
545542

546543
fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
@@ -591,10 +588,10 @@ fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
591588
&deduplicate_blocks::DeduplicateBlocks,
592589
// Some cleanup necessary at least for LLVM and potentially other codegen backends.
593590
&add_call_guards::CriticalCallEdges,
594-
&marker::PhaseChange(MirPhase::Runtime(RuntimePhase::Optimized)),
595591
// Dump the end result for testing and debugging purposes.
596592
&dump_mir::Marker("PreCodegen"),
597593
],
594+
Some(MirPhase::Runtime(RuntimePhase::Optimized)),
598595
);
599596
}
600597

compiler/rustc_mir_transform/src/marker.rs

-20
This file was deleted.

compiler/rustc_mir_transform/src/pass_manager.rs

+56-33
Original file line numberDiff line numberDiff line change
@@ -66,10 +66,6 @@ where
6666
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
6767
self.1.run_pass(tcx, body)
6868
}
69-
70-
fn phase_change(&self) -> Option<MirPhase> {
71-
self.1.phase_change()
72-
}
7369
}
7470

7571
/// Run the sequence of passes without validating the MIR after each pass. The MIR is still
@@ -78,31 +74,35 @@ pub fn run_passes_no_validate<'tcx>(
7874
tcx: TyCtxt<'tcx>,
7975
body: &mut Body<'tcx>,
8076
passes: &[&dyn MirPass<'tcx>],
77+
phase_change: Option<MirPhase>,
8178
) {
82-
run_passes_inner(tcx, body, passes, false);
79+
run_passes_inner(tcx, body, passes, phase_change, false);
8380
}
8481

85-
pub fn run_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>, passes: &[&dyn MirPass<'tcx>]) {
86-
run_passes_inner(tcx, body, passes, true);
82+
/// The optional `phase_change` is applied after executing all the passes, if present
83+
pub fn run_passes<'tcx>(
84+
tcx: TyCtxt<'tcx>,
85+
body: &mut Body<'tcx>,
86+
passes: &[&dyn MirPass<'tcx>],
87+
phase_change: Option<MirPhase>,
88+
) {
89+
run_passes_inner(tcx, body, passes, phase_change, true);
8790
}
8891

8992
fn run_passes_inner<'tcx>(
9093
tcx: TyCtxt<'tcx>,
9194
body: &mut Body<'tcx>,
9295
passes: &[&dyn MirPass<'tcx>],
96+
phase_change: Option<MirPhase>,
9397
validate_each: bool,
9498
) {
95-
let start_phase = body.phase;
96-
let mut cnt = 0;
97-
9899
let validate = validate_each & tcx.sess.opts.unstable_opts.validate_mir;
99100
let overridden_passes = &tcx.sess.opts.unstable_opts.mir_enable_passes;
100101
trace!(?overridden_passes);
101102

102103
for pass in passes {
103104
let name = pass.name();
104105

105-
// Gather information about what we should be doing for this pass
106106
let overridden =
107107
overridden_passes.iter().rev().find(|(s, _)| s == &*name).map(|(_name, polarity)| {
108108
trace!(
@@ -112,55 +112,78 @@ fn run_passes_inner<'tcx>(
112112
);
113113
*polarity
114114
});
115-
let is_enabled = overridden.unwrap_or_else(|| pass.is_enabled(&tcx.sess));
116-
let new_phase = pass.phase_change();
117-
let dump_enabled = (is_enabled && pass.is_mir_dump_enabled()) || new_phase.is_some();
118-
let validate = (validate && is_enabled)
119-
|| new_phase == Some(MirPhase::Runtime(RuntimePhase::Optimized));
115+
if !overridden.unwrap_or_else(|| pass.is_enabled(&tcx.sess)) {
116+
continue;
117+
}
118+
119+
let dump_enabled = pass.is_mir_dump_enabled();
120120

121121
if dump_enabled {
122-
dump_mir(tcx, body, start_phase, &name, cnt, false);
123-
}
124-
if is_enabled {
125-
pass.run_pass(tcx, body);
122+
dump_mir_for_pass(tcx, body, &name, false);
126123
}
127-
if dump_enabled {
128-
dump_mir(tcx, body, start_phase, &name, cnt, true);
129-
cnt += 1;
124+
if validate {
125+
validate_body(tcx, body, format!("before pass {}", name));
130126
}
131-
if let Some(new_phase) = pass.phase_change() {
132-
if body.phase >= new_phase {
133-
panic!("Invalid MIR phase transition from {:?} to {:?}", body.phase, new_phase);
134-
}
135127

136-
body.phase = new_phase;
128+
pass.run_pass(tcx, body);
129+
130+
if dump_enabled {
131+
dump_mir_for_pass(tcx, body, &name, true);
137132
}
138133
if validate {
139134
validate_body(tcx, body, format!("after pass {}", name));
140135
}
136+
137+
body.pass_count += 1;
138+
}
139+
140+
if let Some(new_phase) = phase_change {
141+
if body.phase >= new_phase {
142+
panic!("Invalid MIR phase transition from {:?} to {:?}", body.phase, new_phase);
143+
}
144+
145+
body.phase = new_phase;
146+
147+
dump_mir_for_phase_change(tcx, body);
148+
if validate || new_phase == MirPhase::Runtime(RuntimePhase::Optimized) {
149+
validate_body(tcx, body, format!("after phase change to {}", new_phase));
150+
}
151+
152+
body.pass_count = 1;
141153
}
142154
}
143155

144156
pub fn validate_body<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>, when: String) {
145157
validate::Validator { when, mir_phase: body.phase }.run_pass(tcx, body);
146158
}
147159

148-
pub fn dump_mir<'tcx>(
160+
pub fn dump_mir_for_pass<'tcx>(
149161
tcx: TyCtxt<'tcx>,
150162
body: &Body<'tcx>,
151-
phase: MirPhase,
152163
pass_name: &str,
153-
cnt: usize,
154164
is_after: bool,
155165
) {
156-
let phase_index = phase.phase_index();
166+
let phase_index = body.phase.phase_index();
157167

158168
mir::dump_mir(
159169
tcx,
160-
Some(&format_args!("{:03}-{:03}", phase_index, cnt)),
170+
Some(&format_args!("{:03}-{:03}", phase_index, body.pass_count)),
161171
pass_name,
162172
if is_after { &"after" } else { &"before" },
163173
body,
164174
|_, _| Ok(()),
165175
);
166176
}
177+
178+
pub fn dump_mir_for_phase_change<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
179+
let phase_index = body.phase.phase_index();
180+
181+
mir::dump_mir(
182+
tcx,
183+
Some(&format_args!("{:03}-000", phase_index)),
184+
&format!("{}", body.phase),
185+
&"after",
186+
body,
187+
|_, _| Ok(()),
188+
)
189+
}

compiler/rustc_mir_transform/src/shim.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use std::iter;
1717

1818
use crate::util::expand_aggregate;
1919
use crate::{
20-
abort_unwinding_calls, add_call_guards, add_moves_for_packed_drops, deref_separator, marker,
20+
abort_unwinding_calls, add_call_guards, add_moves_for_packed_drops, deref_separator,
2121
pass_manager as pm, remove_noop_landing_pads, simplify,
2222
};
2323
use rustc_middle::mir::patch::MirPatch;
@@ -97,8 +97,8 @@ fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, instance: ty::InstanceDef<'tcx>) -> Body<'
9797
&simplify::SimplifyCfg::new("make_shim"),
9898
&add_call_guards::CriticalCallEdges,
9999
&abort_unwinding_calls::AbortUnwindingCalls,
100-
&marker::PhaseChange(MirPhase::Runtime(RuntimePhase::Optimized)),
101100
],
101+
Some(MirPhase::Runtime(RuntimePhase::Optimized)),
102102
);
103103

104104
debug!("make_shim({:?}) = {:?}", instance, result);

0 commit comments

Comments
 (0)