3 use rustc_middle::mir::{self, Body, MirPhase};
4 use rustc_middle::ty::TyCtxt;
5 use rustc_session::Session;
7 use crate::{validate, MirPass};
9 /// Just like `MirPass`, except it cannot mutate `Body`.
10 pub trait MirLint<'tcx> {
11 fn name(&self) -> Cow<'_, str> {
12 let name = std::any::type_name::<Self>();
13 if let Some(tail) = name.rfind(':') {
14 Cow::from(&name[tail + 1..])
20 fn is_enabled(&self, _sess: &Session) -> bool {
24 fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>);
27 /// An adapter for `MirLint`s that implements `MirPass`.
28 #[derive(Debug, Clone)]
29 pub struct Lint<T>(pub T);
31 impl<'tcx, T> MirPass<'tcx> for Lint<T>
35 fn name(&self) -> Cow<'_, str> {
39 fn is_enabled(&self, sess: &Session) -> bool {
40 self.0.is_enabled(sess)
43 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
44 self.0.run_lint(tcx, body)
47 fn is_mir_dump_enabled(&self) -> bool {
52 pub struct WithMinOptLevel<T>(pub u32, pub T);
54 impl<'tcx, T> MirPass<'tcx> for WithMinOptLevel<T>
58 fn name(&self) -> Cow<'_, str> {
62 fn is_enabled(&self, sess: &Session) -> bool {
63 sess.mir_opt_level() >= self.0 as usize
66 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
67 self.1.run_pass(tcx, body)
70 fn phase_change(&self) -> Option<MirPhase> {
75 pub fn run_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>, passes: &[&dyn MirPass<'tcx>]) {
76 let start_phase = body.phase;
79 let validate = tcx.sess.opts.debugging_opts.validate_mir;
82 validate_body(tcx, body, format!("start of phase transition from {:?}", start_phase));
86 if !pass.is_enabled(&tcx.sess) {
90 let name = pass.name();
91 let dump_enabled = pass.is_mir_dump_enabled();
94 dump_mir(tcx, body, start_phase, &name, cnt, false);
97 pass.run_pass(tcx, body);
100 dump_mir(tcx, body, start_phase, &name, cnt, true);
104 if let Some(new_phase) = pass.phase_change() {
105 if body.phase >= new_phase {
106 panic!("Invalid MIR phase transition from {:?} to {:?}", body.phase, new_phase);
109 body.phase = new_phase;
113 validate_body(tcx, body, format!("after pass {}", pass.name()));
117 if validate || body.phase == MirPhase::Optimization {
118 validate_body(tcx, body, format!("end of phase transition to {:?}", body.phase));
122 pub fn validate_body<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>, when: String) {
123 validate::Validator { when, mir_phase: body.phase }.run_pass(tcx, body);
126 pub fn dump_mir<'tcx>(
134 let phase_index = phase as u32;
138 Some(&format_args!("{:03}-{:03}", phase_index, cnt)),
140 if is_after { &"after" } else { &"before" },