Skip to main content

rustc_mir_transform/
pass_manager.rs

1use std::cell::RefCell;
2use std::collections::hash_map::Entry;
3use std::sync::atomic::Ordering;
4
5use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
6use rustc_hir::attrs::OptimizeAttr;
7use rustc_hir::def_id::DefId;
8use rustc_middle::mir::{Body, MirDumper, MirPhase, RuntimePhase};
9use rustc_middle::ty::TyCtxt;
10use rustc_session::Session;
11use rustc_session::config::OptLevel;
12use rustc_span::bug;
13use tracing::trace;
14
15use crate::lint::lint_body;
16use crate::{diagnostics, validate};
17
18#[doc =
r" Maps MIR pass names to a snake case form to match profiling naming style"]
const PASS_TO_PROFILER_NAMES:
    ::std::thread::LocalKey<RefCell<FxHashMap<&'static str, &'static str>>> =
    {
        #[inline]
        fn __rust_std_internal_init_fn()
            -> RefCell<FxHashMap<&'static str, &'static str>> {
            { RefCell::new(FxHashMap::default()) }
        }
        unsafe {
            ::std::thread::LocalKey::new(const {
                        if ::std::mem::needs_drop::<RefCell<FxHashMap<&'static str,
                                    &'static str>>>() {
                            |__rust_std_internal_init|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL:
                                        ::std::thread::local_impl::LazyStorage<RefCell<FxHashMap<&'static str,
                                        &'static str>>, ()> =
                                        ::std::thread::local_impl::LazyStorage::new();
                                    __RUST_STD_INTERNAL_VAL.get_or_init(__rust_std_internal_init,
                                        __rust_std_internal_init_fn)
                                }
                        } else {
                            |__rust_std_internal_init|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL:
                                        ::std::thread::local_impl::LazyStorage<RefCell<FxHashMap<&'static str,
                                        &'static str>>, !> =
                                        ::std::thread::local_impl::LazyStorage::new();
                                    __RUST_STD_INTERNAL_VAL.get_or_init(__rust_std_internal_init,
                                        __rust_std_internal_init_fn)
                                }
                        }
                    })
        }
    };thread_local! {
19    /// Maps MIR pass names to a snake case form to match profiling naming style
20    static PASS_TO_PROFILER_NAMES: RefCell<FxHashMap<&'static str, &'static str>> = {
21        RefCell::new(FxHashMap::default())
22    };
23}
24
25/// Converts a MIR pass name into a snake case form to match the profiling naming style.
26fn to_profiler_name(type_name: &'static str) -> &'static str {
27    PASS_TO_PROFILER_NAMES.with(|names| match names.borrow_mut().entry(type_name) {
28        Entry::Occupied(e) => *e.get(),
29        Entry::Vacant(e) => {
30            let snake_case: String = type_name
31                .chars()
32                .flat_map(|c| {
33                    if c.is_ascii_uppercase() {
34                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        ['_', c.to_ascii_lowercase()]))vec!['_', c.to_ascii_lowercase()]
35                    } else if c == '-' {
36                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        ['_']))vec!['_']
37                    } else {
38                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [c]))vec![c]
39                    }
40                })
41                .collect();
42            let result = &*String::leak(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("mir_pass{0}", snake_case))
    })format!("mir_pass{}", snake_case));
43            e.insert(result);
44            result
45        }
46    })
47}
48
49// A function that simplifies a pass's type_name. E.g. `Baz`, `Baz<'_>`,
50// `foo::bar::Baz`, and `foo::bar::Baz<'a, 'b>` all become `Baz`.
51//
52// It's `const` for perf reasons: it's called a lot, and doing the string
53// operations at runtime causes a non-trivial slowdown. If
54// `split_once`/`rsplit_once` become `const` its body could be simplified to
55// this:
56// ```ignore (fragment)
57// let name = if let Some((_, tail)) = name.rsplit_once(':') { tail } else { name };
58// let name = if let Some((head, _)) = name.split_once('<') { head } else { name };
59// name
60// ```
61const fn simplify_pass_type_name(name: &'static str) -> &'static str {
62    // FIXME(const-hack) Simplify the implementation once more `str` methods get const-stable.
63
64    // Work backwards from the end. If a ':' is hit, strip it and everything before it.
65    let bytes = name.as_bytes();
66    let mut i = bytes.len();
67    while i > 0 && bytes[i - 1] != b':' {
68        i -= 1;
69    }
70    let (_, bytes) = bytes.split_at(i);
71
72    // Work forwards from the start of what's left. If a '<' is hit, strip it and everything after
73    // it.
74    let mut i = 0;
75    while i < bytes.len() && bytes[i] != b'<' {
76        i += 1;
77    }
78    let (bytes, _) = bytes.split_at(i);
79
80    match std::str::from_utf8(bytes) {
81        Ok(name) => name,
82        Err(_) => ::core::panicking::panic("explicit panic")panic!(),
83    }
84}
85
86/// Rules outlining when this pass may be overridden or suppressed.
87#[derive(#[automatically_derived]
impl ::core::marker::Copy for PassPolicy { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for PassPolicy { }
#[automatically_derived]
impl ::core::clone::Clone for PassPolicy {
    #[inline]
    fn clone(&self) -> PassPolicy {
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for PassPolicy {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            PassPolicy::Required =>
                ::core::fmt::Formatter::write_str(f, "Required"),
            PassPolicy::Optional { enabled_by_default: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Optional", "enabled_by_default", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for PassPolicy { }
#[automatically_derived]
impl ::core::cmp::PartialEq for PassPolicy {
    #[inline]
    fn eq(&self, other: &PassPolicy) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (PassPolicy::Optional { enabled_by_default: __self_0 },
                    PassPolicy::Optional { enabled_by_default: __arg1_0 }) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for PassPolicy {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<bool>;
    }
}Eq)]
88pub(crate) enum PassPolicy {
89    /// This pass implements a mandatory lowering step, either to implement parts of the MIR semantics
90    /// or to bring MIR into a shape that is easier to deal with for later passes/codegen.
91    /// Passes using this cannot be disabled via any means. They must not remove any UB, as they will
92    /// run in Miri. They must also come with a comment justifying why they must always run.
93    Required,
94    /// An optional pass that may be configured by `-Zmir-enable-passes`.
95    Optional {
96        /// Whether this pass should be enabled in the absence of an explicit
97        /// `-Zmir-enable-passes` override.
98        enabled_by_default: bool,
99    },
100}
101
102impl PassPolicy {
103    /// Create a [`PassPolicy::Optional`] enabled by default under the given condition.
104    pub(crate) fn optional(enabled_by_default: bool) -> Self {
105        Self::Optional { enabled_by_default }
106    }
107}
108
109/// A streamlined trait that you can implement to create a pass; the
110/// pass will be named after the type, and it will consist of a main
111/// loop that goes over each available MIR and applies `run_pass`.
112pub(super) trait MirPass<'tcx> {
113    fn name(&self) -> &'static str {
114        const { simplify_pass_type_name(std::any::type_name::<Self>()) }
115    }
116
117    fn profiler_name(&self) -> &'static str {
118        to_profiler_name(self.name())
119    }
120
121    /// Describes how this pass is enabled and which mechanisms may disable it.
122    fn policy(&self, ctx: &PassCtx<'_>) -> PassPolicy;
123
124    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>);
125
126    fn is_mir_dump_enabled(&self) -> bool {
127        true
128    }
129}
130
131#[derive(#[automatically_derived]
impl<'sess> ::core::marker::Copy for PassCtx<'sess> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'sess> ::core::clone::TrivialClone for PassCtx<'sess> { }
#[automatically_derived]
impl<'sess> ::core::clone::Clone for PassCtx<'sess> {
    #[inline]
    fn clone(&self) -> PassCtx<'sess> {
        let _: ::core::clone::AssertParamIsClone<&'sess Session>;
        let _: ::core::clone::AssertParamIsClone<usize>;
        *self
    }
}Clone)]
132pub(super) struct PassCtx<'sess> {
133    /// Prefer [`Self::mir_opt_level`] to [`Session::mir_opt_level`] to account for overrides.
134    session: &'sess Session,
135    /// The MIR optimization level for this body; may be overridden by `#[optimize]`.
136    body_mir_opt_level: usize,
137}
138
139impl<'sess> PassCtx<'sess> {
140    pub(super) fn for_body(tcx: TyCtxt<'sess>, def_id: DefId) -> Self {
141        let body_mir_opt_level = if !tcx.def_kind(def_id).has_codegen_attrs() {
142            tcx.sess.mir_opt_level()
143        } else {
144            match tcx.codegen_fn_attrs(def_id).optimize {
145                OptimizeAttr::Default => tcx.sess.mir_opt_level(),
146                OptimizeAttr::DoNotOptimize => OptLevel::No.mir_opt_level(),
147                OptimizeAttr::Speed => OptLevel::Aggressive.mir_opt_level(),
148                OptimizeAttr::Size => OptLevel::Size.mir_opt_level(),
149            }
150        };
151        Self { session: tcx.sess, body_mir_opt_level }
152    }
153
154    /// The effective MIR optimization level for this body, including `#[optimize]` overrides.
155    pub(super) fn mir_opt_level(&self) -> usize {
156        self.body_mir_opt_level
157    }
158}
159
160impl std::ops::Deref for PassCtx<'_> {
161    type Target = Session;
162
163    fn deref(&self) -> &Self::Target {
164        self.session
165    }
166}
167
168/// Just like `MirPass`, except it cannot mutate `Body`, and MIR dumping is
169/// disabled (via the `Lint` adapter).
170pub(super) trait MirLint<'tcx> {
171    fn name(&self) -> &'static str {
172        const { simplify_pass_type_name(std::any::type_name::<Self>()) }
173    }
174
175    fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>);
176}
177
178/// An adapter for `MirLint`s that implements `MirPass`.
179#[derive(#[automatically_derived]
impl<T: ::core::fmt::Debug> ::core::fmt::Debug for Lint<T> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Lint", &&self.0)
    }
}Debug, #[automatically_derived]
impl<T: ::core::clone::Clone> ::core::clone::Clone for Lint<T> {
    #[inline]
    fn clone(&self) -> Lint<T> { Lint(::core::clone::Clone::clone(&self.0)) }
}Clone)]
180pub(super) struct Lint<T>(pub T);
181
182impl<'tcx, T> MirPass<'tcx> for Lint<T>
183where
184    T: MirLint<'tcx>,
185{
186    fn name(&self) -> &'static str {
187        self.0.name()
188    }
189
190    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
191        self.0.run_lint(tcx, body)
192    }
193
194    fn is_mir_dump_enabled(&self) -> bool {
195        false
196    }
197
198    fn policy(&self, _ctx: &PassCtx<'_>) -> PassPolicy {
199        PassPolicy::optional(true)
200    }
201}
202
203pub(super) struct WithMinOptLevel<T>(pub usize, pub T);
204
205impl<'tcx, T> MirPass<'tcx> for WithMinOptLevel<T>
206where
207    T: MirPass<'tcx>,
208{
209    fn name(&self) -> &'static str {
210        self.1.name()
211    }
212
213    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
214        self.1.run_pass(tcx, body)
215    }
216
217    fn policy(&self, ctx: &PassCtx<'_>) -> PassPolicy {
218        let policy = self.1.policy(ctx);
219        match policy {
220            PassPolicy::Required => bug_impl(None, format_args!("required pass cannot be gated by an opt level"),
    Location::caller())bug!("required pass cannot be gated by an opt level"),
221            PassPolicy::Optional { enabled_by_default } => PassPolicy::Optional {
222                enabled_by_default: enabled_by_default && ctx.mir_opt_level() >= self.0,
223            },
224        }
225    }
226}
227
228/// Run the sequence of passes without validating the MIR after each pass. The MIR is still
229/// validated at the end.
230pub(super) fn run_passes_no_validate<'tcx>(
231    tcx: TyCtxt<'tcx>,
232    body: &mut Body<'tcx>,
233    passes: &[&dyn MirPass<'tcx>],
234    phase_change: Option<MirPhase>,
235) {
236    run_passes_inner(tcx, body, passes, phase_change, false);
237}
238
239/// The optional `phase_change` is applied after executing all the passes, if present
240pub(super) fn run_passes<'tcx>(
241    tcx: TyCtxt<'tcx>,
242    body: &mut Body<'tcx>,
243    passes: &[&dyn MirPass<'tcx>],
244    phase_change: Option<MirPhase>,
245) {
246    run_passes_inner(tcx, body, passes, phase_change, true);
247}
248
249pub(super) fn should_run_pass<'tcx, P>(pass: &P, ctx: &PassCtx<'_>) -> bool
250where
251    P: MirPass<'tcx> + ?Sized,
252{
253    let name = pass.name();
254    let pass_override = || {
255        ctx.opts
256            .unstable_opts
257            .mir_enable_passes
258            .iter()
259            .rev()
260            .find_map(|(name_, polarity)| if name == name_ { Some(*polarity) } else { None })
261    };
262
263    match pass.policy(ctx) {
264        PassPolicy::Required => true,
265        PassPolicy::Optional { enabled_by_default } => {
266            if let Some(o) = pass_override() {
267                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_transform/src/pass_manager.rs:267",
                        "rustc_mir_transform::pass_manager",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_transform/src/pass_manager.rs"),
                        ::tracing_core::__macro_support::Option::Some(267u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::pass_manager"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("pass")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("pass");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0} as requested by flag",
                                                    if o { "Running" } else { "Not running" }) as
                                            &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::display(&name)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!(
268                    pass = %name,
269                    "{} as requested by flag",
270                    if o { "Running" } else { "Not running" }
271                );
272                o
273            } else {
274                enabled_by_default
275            }
276        }
277    }
278}
279
280fn run_passes_inner<'tcx>(
281    tcx: TyCtxt<'tcx>,
282    body: &mut Body<'tcx>,
283    passes: &[&dyn MirPass<'tcx>],
284    phase_change: Option<MirPhase>,
285    validate_each: bool,
286) {
287    let overridden_passes = &tcx.sess.opts.unstable_opts.mir_enable_passes;
288    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_transform/src/pass_manager.rs:288",
                        "rustc_mir_transform::pass_manager",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_transform/src/pass_manager.rs"),
                        ::tracing_core::__macro_support::Option::Some(288u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::pass_manager"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("overridden_passes")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("overridden_passes");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&overridden_passes)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!(?overridden_passes);
289
290    let named_passes: FxIndexSet<_> =
291        overridden_passes.iter().map(|(name, _)| name.as_str()).collect();
292
293    let mut unknown_found = false;
294    for &name in named_passes.difference(&*crate::PASS_NAMES) {
295        tcx.dcx().emit_warn(diagnostics::UnknownPassName { name });
296        unknown_found = true;
297    }
298
299    if unknown_found {
300        let mut valid_pass_names = crate::PASS_NAMES.iter().copied().collect::<Vec<_>>();
301        valid_pass_names.sort();
302        tcx.dcx().emit_note(diagnostics::ValidPassNames { valid_passes: valid_pass_names.into() });
303    }
304
305    // Verify that no passes are missing from the `declare_passes` invocation
306    #[cfg(debug_assertions)]
307    {
308        let used_passes: FxIndexSet<_> = passes.iter().map(|p| p.name()).collect();
309
310        let undeclared = used_passes.difference(&*crate::PASS_NAMES).collect::<Vec<_>>();
311        if let Some((name, rest)) = undeclared.split_first() {
312            let mut err =
313                tcx.dcx().struct_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("pass `{0}` is not declared in `PASS_NAMES`",
                name))
    })format!("pass `{name}` is not declared in `PASS_NAMES`"));
314            for name in rest {
315                err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("pass `{0}` is also not declared in `PASS_NAMES`",
                name))
    })format!("pass `{name}` is also not declared in `PASS_NAMES`"));
316            }
317            err.emit();
318        }
319    }
320
321    let prof_arg = tcx.sess.prof.enabled().then(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", body.source.def_id()))
    })format!("{:?}", body.source.def_id()));
322
323    if !body.should_skip() {
324        let validate = validate_each & tcx.sess.opts.unstable_opts.validate_mir;
325        let lint = tcx.sess.opts.unstable_opts.lint_mir;
326
327        let ctx = PassCtx::for_body(tcx, body.source.def_id());
328
329        for pass in passes {
330            let pass_name = pass.name();
331
332            if !should_run_pass(*pass, &ctx) {
333                continue;
334            };
335
336            if body.phase == MirPhase::Runtime(RuntimePhase::PostCleanup)
337                && phase_change == Some(MirPhase::Runtime(RuntimePhase::Optimized))
338                && let Some(limit) = &tcx.sess.opts.unstable_opts.mir_opt_bisect_limit
339                && #[allow(non_exhaustive_omitted_patterns)] match pass.policy(&ctx) {
    PassPolicy::Optional { .. } => true,
    _ => false,
}matches!(pass.policy(&ctx), PassPolicy::Optional { .. })
340                && limited_by_opt_bisect(
341                    tcx,
342                    tcx.def_path_debug_str(body.source.def_id()),
343                    *limit,
344                    *pass,
345                )
346            {
347                continue;
348            }
349
350            let dumper = if pass.is_mir_dump_enabled()
351                && let Some(dumper) = MirDumper::new(tcx, pass_name, body)
352            {
353                Some(dumper.set_show_pass_num().set_disambiguator(&"before"))
354            } else {
355                None
356            };
357
358            if let Some(dumper) = dumper.as_ref() {
359                dumper.dump_mir(body);
360            }
361
362            if let Some(prof_arg) = &prof_arg {
363                tcx.sess
364                    .prof
365                    .generic_activity_with_arg(pass.profiler_name(), &**prof_arg)
366                    .run(|| pass.run_pass(tcx, body));
367            } else {
368                pass.run_pass(tcx, body);
369            }
370
371            if let Some(dumper) = dumper {
372                dumper.set_disambiguator(&"after").dump_mir(body);
373            }
374
375            if validate {
376                validate_body(tcx, body, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("after pass {0}", pass_name))
    })format!("after pass {pass_name}"));
377            }
378            if lint {
379                lint_body(tcx, body, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("after pass {0}", pass_name))
    })format!("after pass {pass_name}"));
380            }
381
382            body.pass_count += 1;
383        }
384    }
385
386    if let Some(new_phase) = phase_change {
387        if body.phase >= new_phase {
388            {
    ::core::panicking::panic_fmt(format_args!("Invalid MIR phase transition from {0:?} to {1:?}",
            body.phase, new_phase));
};panic!("Invalid MIR phase transition from {:?} to {:?}", body.phase, new_phase);
389        }
390
391        body.phase = new_phase;
392        body.pass_count = 0;
393
394        dump_mir_for_phase_change(tcx, body);
395
396        let validate =
397            (validate_each & tcx.sess.opts.unstable_opts.validate_mir & !body.should_skip())
398                || new_phase == MirPhase::Runtime(RuntimePhase::Optimized);
399        let lint = tcx.sess.opts.unstable_opts.lint_mir & !body.should_skip();
400        if validate {
401            validate_body(tcx, body, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("after phase change to {0}",
                new_phase.name()))
    })format!("after phase change to {}", new_phase.name()));
402        }
403        if lint {
404            lint_body(tcx, body, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("after phase change to {0}",
                new_phase.name()))
    })format!("after phase change to {}", new_phase.name()));
405        }
406
407        body.pass_count = 1;
408    }
409}
410
411pub(super) fn validate_body<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>, when: String) {
412    validate::Validator { when }.run_pass(tcx, body);
413}
414
415pub(super) fn dump_mir_for_phase_change<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
416    {
    match (&body.pass_count, &0) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(body.pass_count, 0);
417    if let Some(dumper) = MirDumper::new(tcx, body.phase.name(), body) {
418        dumper.set_show_pass_num().set_disambiguator(&"after").dump_mir(body)
419    }
420}
421
422fn limited_by_opt_bisect<'tcx, P>(
423    tcx: TyCtxt<'tcx>,
424    def_path: String,
425    limit: usize,
426    pass: &P,
427) -> bool
428where
429    P: MirPass<'tcx> + ?Sized,
430{
431    let current_opt_bisect_count =
432        tcx.sess.mir_opt_bisect_eval_count.fetch_add(1, Ordering::Relaxed);
433
434    let can_run = current_opt_bisect_count < limit;
435
436    if can_run {
437        {
    ::std::io::_eprint(format_args!("BISECT: running pass ({0}) {1} on {2}\n",
            current_opt_bisect_count + 1, pass.name(), def_path));
};eprintln!(
438            "BISECT: running pass ({}) {} on {}",
439            current_opt_bisect_count + 1,
440            pass.name(),
441            def_path
442        );
443    } else {
444        {
    ::std::io::_eprint(format_args!("BISECT: NOT running pass ({0}) {1} on {2}\n",
            current_opt_bisect_count + 1, pass.name(), def_path));
};eprintln!(
445            "BISECT: NOT running pass ({}) {} on {}",
446            current_opt_bisect_count + 1,
447            pass.name(),
448            def_path
449        );
450    }
451
452    !can_run
453}