rustc_mir_transform/
lib.rs

1// tidy-alphabetical-start
2#![cfg_attr(doc, recursion_limit = "256")] // FIXME(nnethercote): will be removed by #124141
3#![feature(array_windows)]
4#![feature(assert_matches)]
5#![feature(box_patterns)]
6#![feature(const_type_name)]
7#![feature(cow_is_borrowed)]
8#![feature(file_buffered)]
9#![feature(if_let_guard)]
10#![feature(impl_trait_in_assoc_type)]
11#![feature(let_chains)]
12#![feature(map_try_insert)]
13#![feature(never_type)]
14#![feature(try_blocks)]
15#![feature(yeet_expr)]
16// tidy-alphabetical-end
17
18use hir::ConstContext;
19use required_consts::RequiredConstsVisitor;
20use rustc_const_eval::check_consts::{self, ConstCx};
21use rustc_const_eval::util;
22use rustc_data_structures::fx::FxIndexSet;
23use rustc_data_structures::steal::Steal;
24use rustc_hir as hir;
25use rustc_hir::def::{CtorKind, DefKind};
26use rustc_hir::def_id::LocalDefId;
27use rustc_index::IndexVec;
28use rustc_middle::mir::{
29    AnalysisPhase, Body, CallSource, ClearCrossCrate, ConstOperand, ConstQualifs, LocalDecl,
30    MirPhase, Operand, Place, ProjectionElem, Promoted, RuntimePhase, Rvalue, START_BLOCK,
31    SourceInfo, Statement, StatementKind, TerminatorKind,
32};
33use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt};
34use rustc_middle::util::Providers;
35use rustc_middle::{bug, query, span_bug};
36use rustc_mir_build::builder::build_mir;
37use rustc_span::source_map::Spanned;
38use rustc_span::{DUMMY_SP, sym};
39use tracing::debug;
40
41#[macro_use]
42mod pass_manager;
43
44use std::sync::LazyLock;
45
46use pass_manager::{self as pm, Lint, MirLint, MirPass, WithMinOptLevel};
47
48mod check_pointers;
49mod cost_checker;
50mod cross_crate_inline;
51mod deduce_param_attrs;
52mod elaborate_drop;
53mod errors;
54mod ffi_unwind_calls;
55mod lint;
56mod lint_tail_expr_drop_order;
57mod patch;
58mod shim;
59mod ssa;
60
61/// We import passes via this macro so that we can have a static list of pass names
62/// (used to verify CLI arguments). It takes a list of modules, followed by the passes
63/// declared within them.
64/// ```ignore,macro-test
65/// declare_passes! {
66///     // Declare a single pass from the module `abort_unwinding_calls`
67///     mod abort_unwinding_calls : AbortUnwindingCalls;
68///     // When passes are grouped together as an enum, declare the two constituent passes
69///     mod add_call_guards : AddCallGuards {
70///         AllCallEdges,
71///         CriticalCallEdges
72///     };
73///     // Declares multiple pass groups, each containing their own constituent passes
74///     mod simplify : SimplifyCfg {
75///         Initial,
76///         /* omitted */
77///     }, SimplifyLocals {
78///         BeforeConstProp,
79///         /* omitted */
80///     };
81/// }
82/// ```
83macro_rules! declare_passes {
84    (
85        $(
86            $vis:vis mod $mod_name:ident : $($pass_name:ident $( { $($ident:ident),* } )?),+ $(,)?;
87        )*
88    ) => {
89        $(
90            $vis mod $mod_name;
91            $(
92                // Make sure the type name is correct
93                #[allow(unused_imports)]
94                use $mod_name::$pass_name as _;
95            )+
96        )*
97
98        static PASS_NAMES: LazyLock<FxIndexSet<&str>> = LazyLock::new(|| [
99            // Fake marker pass
100            "PreCodegen",
101            $(
102                $(
103                    stringify!($pass_name),
104                    $(
105                        $(
106                            $mod_name::$pass_name::$ident.name(),
107                        )*
108                    )?
109                )+
110            )*
111        ].into_iter().collect());
112    };
113}
114
115declare_passes! {
116    mod abort_unwinding_calls : AbortUnwindingCalls;
117    mod add_call_guards : AddCallGuards { AllCallEdges, CriticalCallEdges };
118    mod add_moves_for_packed_drops : AddMovesForPackedDrops;
119    mod add_retag : AddRetag;
120    mod add_subtyping_projections : Subtyper;
121    mod check_inline : CheckForceInline;
122    mod check_call_recursion : CheckCallRecursion, CheckDropRecursion;
123    mod check_alignment : CheckAlignment;
124    mod check_const_item_mutation : CheckConstItemMutation;
125    mod check_null : CheckNull;
126    mod check_packed_ref : CheckPackedRef;
127    mod check_undefined_transmutes : CheckUndefinedTransmutes;
128    // This pass is public to allow external drivers to perform MIR cleanup
129    pub mod cleanup_post_borrowck : CleanupPostBorrowck;
130
131    mod copy_prop : CopyProp;
132    mod coroutine : StateTransform;
133    mod coverage : InstrumentCoverage;
134    mod ctfe_limit : CtfeLimit;
135    mod dataflow_const_prop : DataflowConstProp;
136    mod dead_store_elimination : DeadStoreElimination {
137        Initial,
138        Final
139    };
140    mod deref_separator : Derefer;
141    mod dest_prop : DestinationPropagation;
142    pub mod dump_mir : Marker;
143    mod early_otherwise_branch : EarlyOtherwiseBranch;
144    mod elaborate_box_derefs : ElaborateBoxDerefs;
145    mod elaborate_drops : ElaborateDrops;
146    mod function_item_references : FunctionItemReferences;
147    mod gvn : GVN;
148    // Made public so that `mir_drops_elaborated_and_const_checked` can be overridden
149    // by custom rustc drivers, running all the steps by themselves. See #114628.
150    pub mod inline : Inline, ForceInline;
151    mod impossible_predicates : ImpossiblePredicates;
152    mod instsimplify : InstSimplify { BeforeInline, AfterSimplifyCfg };
153    mod jump_threading : JumpThreading;
154    mod known_panics_lint : KnownPanicsLint;
155    mod large_enums : EnumSizeOpt;
156    mod lower_intrinsics : LowerIntrinsics;
157    mod lower_slice_len : LowerSliceLenCalls;
158    mod match_branches : MatchBranchSimplification;
159    mod mentioned_items : MentionedItems;
160    mod multiple_return_terminators : MultipleReturnTerminators;
161    mod nrvo : RenameReturnPlace;
162    mod post_drop_elaboration : CheckLiveDrops;
163    mod prettify : ReorderBasicBlocks, ReorderLocals;
164    mod promote_consts : PromoteTemps;
165    mod ref_prop : ReferencePropagation;
166    mod remove_noop_landing_pads : RemoveNoopLandingPads;
167    mod remove_place_mention : RemovePlaceMention;
168    mod remove_storage_markers : RemoveStorageMarkers;
169    mod remove_uninit_drops : RemoveUninitDrops;
170    mod remove_unneeded_drops : RemoveUnneededDrops;
171    mod remove_zsts : RemoveZsts;
172    mod required_consts : RequiredConstsVisitor;
173    mod post_analysis_normalize : PostAnalysisNormalize;
174    mod sanity_check : SanityCheck;
175    // This pass is public to allow external drivers to perform MIR cleanup
176    pub mod simplify :
177        SimplifyCfg {
178            Initial,
179            PromoteConsts,
180            RemoveFalseEdges,
181            PostAnalysis,
182            PreOptimizations,
183            Final,
184            MakeShim,
185            AfterUnreachableEnumBranching
186        },
187        SimplifyLocals {
188            BeforeConstProp,
189            AfterGVN,
190            Final
191        };
192    mod simplify_branches : SimplifyConstCondition {
193        AfterConstProp,
194        Final
195    };
196    mod simplify_comparison_integral : SimplifyComparisonIntegral;
197    mod single_use_consts : SingleUseConsts;
198    mod sroa : ScalarReplacementOfAggregates;
199    mod strip_debuginfo : StripDebugInfo;
200    mod unreachable_enum_branching : UnreachableEnumBranching;
201    mod unreachable_prop : UnreachablePropagation;
202    mod validate : Validator;
203}
204
205rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
206
207pub fn provide(providers: &mut Providers) {
208    coverage::query::provide(providers);
209    ffi_unwind_calls::provide(providers);
210    shim::provide(providers);
211    cross_crate_inline::provide(providers);
212    providers.queries = query::Providers {
213        mir_keys,
214        mir_built,
215        mir_const_qualif,
216        mir_promoted,
217        mir_drops_elaborated_and_const_checked,
218        mir_for_ctfe,
219        mir_coroutine_witnesses: coroutine::mir_coroutine_witnesses,
220        optimized_mir,
221        is_mir_available,
222        is_ctfe_mir_available: is_mir_available,
223        mir_callgraph_reachable: inline::cycle::mir_callgraph_reachable,
224        mir_inliner_callees: inline::cycle::mir_inliner_callees,
225        promoted_mir,
226        deduced_param_attrs: deduce_param_attrs::deduced_param_attrs,
227        coroutine_by_move_body_def_id: coroutine::coroutine_by_move_body_def_id,
228        ..providers.queries
229    };
230}
231
232fn remap_mir_for_const_eval_select<'tcx>(
233    tcx: TyCtxt<'tcx>,
234    mut body: Body<'tcx>,
235    context: hir::Constness,
236) -> Body<'tcx> {
237    for bb in body.basic_blocks.as_mut().iter_mut() {
238        let terminator = bb.terminator.as_mut().expect("invalid terminator");
239        match terminator.kind {
240            TerminatorKind::Call {
241                func: Operand::Constant(box ConstOperand { ref const_, .. }),
242                ref mut args,
243                destination,
244                target,
245                unwind,
246                fn_span,
247                ..
248            } if let ty::FnDef(def_id, _) = *const_.ty().kind()
249                && tcx.is_intrinsic(def_id, sym::const_eval_select) =>
250            {
251                let Ok([tupled_args, called_in_const, called_at_rt]) = take_array(args) else {
252                    unreachable!()
253                };
254                let ty = tupled_args.node.ty(&body.local_decls, tcx);
255                let fields = ty.tuple_fields();
256                let num_args = fields.len();
257                let func =
258                    if context == hir::Constness::Const { called_in_const } else { called_at_rt };
259                let (method, place): (fn(Place<'tcx>) -> Operand<'tcx>, Place<'tcx>) =
260                    match tupled_args.node {
261                        Operand::Constant(_) => {
262                            // There is no good way of extracting a tuple arg from a constant
263                            // (const generic stuff) so we just create a temporary and deconstruct
264                            // that.
265                            let local = body.local_decls.push(LocalDecl::new(ty, fn_span));
266                            bb.statements.push(Statement {
267                                source_info: SourceInfo::outermost(fn_span),
268                                kind: StatementKind::Assign(Box::new((
269                                    local.into(),
270                                    Rvalue::Use(tupled_args.node.clone()),
271                                ))),
272                            });
273                            (Operand::Move, local.into())
274                        }
275                        Operand::Move(place) => (Operand::Move, place),
276                        Operand::Copy(place) => (Operand::Copy, place),
277                    };
278                let place_elems = place.projection;
279                let arguments = (0..num_args)
280                    .map(|x| {
281                        let mut place_elems = place_elems.to_vec();
282                        place_elems.push(ProjectionElem::Field(x.into(), fields[x]));
283                        let projection = tcx.mk_place_elems(&place_elems);
284                        let place = Place { local: place.local, projection };
285                        Spanned { node: method(place), span: DUMMY_SP }
286                    })
287                    .collect();
288                terminator.kind = TerminatorKind::Call {
289                    func: func.node,
290                    args: arguments,
291                    destination,
292                    target,
293                    unwind,
294                    call_source: CallSource::Misc,
295                    fn_span,
296                };
297            }
298            _ => {}
299        }
300    }
301    body
302}
303
304fn take_array<T, const N: usize>(b: &mut Box<[T]>) -> Result<[T; N], Box<[T]>> {
305    let b: Box<[T; N]> = std::mem::take(b).try_into()?;
306    Ok(*b)
307}
308
309fn is_mir_available(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
310    tcx.mir_keys(()).contains(&def_id)
311}
312
313/// Finds the full set of `DefId`s within the current crate that have
314/// MIR associated with them.
315fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet<LocalDefId> {
316    // All body-owners have MIR associated with them.
317    let mut set: FxIndexSet<_> = tcx.hir_body_owners().collect();
318
319    // Remove the fake bodies for `global_asm!`, since they're not useful
320    // to be emitted (`--emit=mir`) or encoded (in metadata).
321    set.retain(|&def_id| !matches!(tcx.def_kind(def_id), DefKind::GlobalAsm));
322
323    // Coroutine-closures (e.g. async closures) have an additional by-move MIR
324    // body that isn't in the HIR.
325    for body_owner in tcx.hir_body_owners() {
326        if let DefKind::Closure = tcx.def_kind(body_owner)
327            && tcx.needs_coroutine_by_move_body_def_id(body_owner.to_def_id())
328        {
329            set.insert(tcx.coroutine_by_move_body_def_id(body_owner).expect_local());
330        }
331    }
332
333    // tuple struct/variant constructors have MIR, but they don't have a BodyId,
334    // so we need to build them separately.
335    for item in tcx.hir_crate_items(()).free_items() {
336        if let DefKind::Struct | DefKind::Enum = tcx.def_kind(item.owner_id) {
337            for variant in tcx.adt_def(item.owner_id).variants() {
338                if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
339                    set.insert(ctor_def_id.expect_local());
340                }
341            }
342        }
343    }
344
345    set
346}
347
348fn mir_const_qualif(tcx: TyCtxt<'_>, def: LocalDefId) -> ConstQualifs {
349    // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
350    // cannot yet be stolen), because `mir_promoted()`, which steals
351    // from `mir_built()`, forces this query to execute before
352    // performing the steal.
353    let body = &tcx.mir_built(def).borrow();
354    let ccx = check_consts::ConstCx::new(tcx, body);
355    // No need to const-check a non-const `fn`.
356    match ccx.const_kind {
357        Some(ConstContext::Const { .. } | ConstContext::Static(_) | ConstContext::ConstFn) => {}
358        None => span_bug!(
359            tcx.def_span(def),
360            "`mir_const_qualif` should only be called on const fns and const items"
361        ),
362    }
363
364    if body.return_ty().references_error() {
365        // It's possible to reach here without an error being emitted (#121103).
366        tcx.dcx().span_delayed_bug(body.span, "mir_const_qualif: MIR had errors");
367        return Default::default();
368    }
369
370    let mut validator = check_consts::check::Checker::new(&ccx);
371    validator.check_body();
372
373    // We return the qualifs in the return place for every MIR body, even though it is only used
374    // when deciding to promote a reference to a `const` for now.
375    validator.qualifs_in_return_place()
376}
377
378fn mir_built(tcx: TyCtxt<'_>, def: LocalDefId) -> &Steal<Body<'_>> {
379    let mut body = build_mir(tcx, def);
380
381    pass_manager::dump_mir_for_phase_change(tcx, &body);
382
383    pm::run_passes(
384        tcx,
385        &mut body,
386        &[
387            // MIR-level lints.
388            &Lint(check_inline::CheckForceInline),
389            &Lint(check_call_recursion::CheckCallRecursion),
390            &Lint(check_packed_ref::CheckPackedRef),
391            &Lint(check_const_item_mutation::CheckConstItemMutation),
392            &Lint(function_item_references::FunctionItemReferences),
393            &Lint(check_undefined_transmutes::CheckUndefinedTransmutes),
394            // What we need to do constant evaluation.
395            &simplify::SimplifyCfg::Initial,
396            &Lint(sanity_check::SanityCheck),
397        ],
398        None,
399        pm::Optimizations::Allowed,
400    );
401    tcx.alloc_steal_mir(body)
402}
403
404/// Compute the main MIR body and the list of MIR bodies of the promoteds.
405fn mir_promoted(
406    tcx: TyCtxt<'_>,
407    def: LocalDefId,
408) -> (&Steal<Body<'_>>, &Steal<IndexVec<Promoted, Body<'_>>>) {
409    // Ensure that we compute the `mir_const_qualif` for constants at
410    // this point, before we steal the mir-const result.
411    // Also this means promotion can rely on all const checks having been done.
412
413    let const_qualifs = match tcx.def_kind(def) {
414        DefKind::Fn | DefKind::AssocFn | DefKind::Closure
415            if tcx.constness(def) == hir::Constness::Const
416                || tcx.is_const_default_method(def.to_def_id()) =>
417        {
418            tcx.mir_const_qualif(def)
419        }
420        DefKind::AssocConst
421        | DefKind::Const
422        | DefKind::Static { .. }
423        | DefKind::InlineConst
424        | DefKind::AnonConst => tcx.mir_const_qualif(def),
425        _ => ConstQualifs::default(),
426    };
427
428    // the `has_ffi_unwind_calls` query uses the raw mir, so make sure it is run.
429    tcx.ensure_done().has_ffi_unwind_calls(def);
430
431    // the `by_move_body` query uses the raw mir, so make sure it is run.
432    if tcx.needs_coroutine_by_move_body_def_id(def.to_def_id()) {
433        tcx.ensure_done().coroutine_by_move_body_def_id(def);
434    }
435
436    let mut body = tcx.mir_built(def).steal();
437    if let Some(error_reported) = const_qualifs.tainted_by_errors {
438        body.tainted_by_errors = Some(error_reported);
439    }
440
441    // Collect `required_consts` *before* promotion, so if there are any consts being promoted
442    // we still add them to the list in the outer MIR body.
443    RequiredConstsVisitor::compute_required_consts(&mut body);
444
445    // What we need to run borrowck etc.
446    let promote_pass = promote_consts::PromoteTemps::default();
447    pm::run_passes(
448        tcx,
449        &mut body,
450        &[&promote_pass, &simplify::SimplifyCfg::PromoteConsts, &coverage::InstrumentCoverage],
451        Some(MirPhase::Analysis(AnalysisPhase::Initial)),
452        pm::Optimizations::Allowed,
453    );
454
455    lint_tail_expr_drop_order::run_lint(tcx, def, &body);
456
457    let promoted = promote_pass.promoted_fragments.into_inner();
458    (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
459}
460
461/// Compute the MIR that is used during CTFE (and thus has no optimizations run on it)
462fn mir_for_ctfe(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &Body<'_> {
463    tcx.arena.alloc(inner_mir_for_ctfe(tcx, def_id))
464}
465
466fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: LocalDefId) -> Body<'_> {
467    // FIXME: don't duplicate this between the optimized_mir/mir_for_ctfe queries
468    if tcx.is_constructor(def.to_def_id()) {
469        // There's no reason to run all of the MIR passes on constructors when
470        // we can just output the MIR we want directly. This also saves const
471        // qualification and borrow checking the trouble of special casing
472        // constructors.
473        return shim::build_adt_ctor(tcx, def.to_def_id());
474    }
475
476    let body = tcx.mir_drops_elaborated_and_const_checked(def);
477    let body = match tcx.hir_body_const_context(def) {
478        // consts and statics do not have `optimized_mir`, so we can steal the body instead of
479        // cloning it.
480        Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => body.steal(),
481        Some(hir::ConstContext::ConstFn) => body.borrow().clone(),
482        None => bug!("`mir_for_ctfe` called on non-const {def:?}"),
483    };
484
485    let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::Const);
486    pm::run_passes(tcx, &mut body, &[&ctfe_limit::CtfeLimit], None, pm::Optimizations::Allowed);
487
488    body
489}
490
491/// Obtain just the main MIR (no promoteds) and run some cleanups on it. This also runs
492/// mir borrowck *before* doing so in order to ensure that borrowck can be run and doesn't
493/// end up missing the source MIR due to stealing happening.
494fn mir_drops_elaborated_and_const_checked(tcx: TyCtxt<'_>, def: LocalDefId) -> &Steal<Body<'_>> {
495    if tcx.is_coroutine(def.to_def_id()) {
496        tcx.ensure_done().mir_coroutine_witnesses(def);
497    }
498
499    // We only need to borrowck non-synthetic MIR.
500    let tainted_by_errors =
501        if !tcx.is_synthetic_mir(def) { tcx.mir_borrowck(def).tainted_by_errors } else { None };
502
503    let is_fn_like = tcx.def_kind(def).is_fn_like();
504    if is_fn_like {
505        // Do not compute the mir call graph without said call graph actually being used.
506        if pm::should_run_pass(tcx, &inline::Inline, pm::Optimizations::Allowed)
507            || inline::ForceInline::should_run_pass_for_callee(tcx, def.to_def_id())
508        {
509            tcx.ensure_done().mir_inliner_callees(ty::InstanceKind::Item(def.to_def_id()));
510        }
511    }
512
513    let (body, _) = tcx.mir_promoted(def);
514    let mut body = body.steal();
515
516    if let Some(error_reported) = tainted_by_errors {
517        body.tainted_by_errors = Some(error_reported);
518    }
519
520    // Also taint the body if it's within a top-level item that is not well formed.
521    //
522    // We do this check here and not during `mir_promoted` because that may result
523    // in borrowck cycles if WF requires looking into an opaque hidden type.
524    let root = tcx.typeck_root_def_id(def.to_def_id());
525    match tcx.def_kind(root) {
526        DefKind::Fn
527        | DefKind::AssocFn
528        | DefKind::Static { .. }
529        | DefKind::Const
530        | DefKind::AssocConst => {
531            if let Err(guar) = tcx.check_well_formed(root.expect_local()) {
532                body.tainted_by_errors = Some(guar);
533            }
534        }
535        _ => {}
536    }
537
538    run_analysis_to_runtime_passes(tcx, &mut body);
539
540    tcx.alloc_steal_mir(body)
541}
542
543// Made public so that `mir_drops_elaborated_and_const_checked` can be overridden
544// by custom rustc drivers, running all the steps by themselves. See #114628.
545pub fn run_analysis_to_runtime_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
546    assert!(body.phase == MirPhase::Analysis(AnalysisPhase::Initial));
547    let did = body.source.def_id();
548
549    debug!("analysis_mir_cleanup({:?})", did);
550    run_analysis_cleanup_passes(tcx, body);
551    assert!(body.phase == MirPhase::Analysis(AnalysisPhase::PostCleanup));
552
553    // Do a little drop elaboration before const-checking if `const_precise_live_drops` is enabled.
554    if check_consts::post_drop_elaboration::checking_enabled(&ConstCx::new(tcx, body)) {
555        pm::run_passes(
556            tcx,
557            body,
558            &[
559                &remove_uninit_drops::RemoveUninitDrops,
560                &simplify::SimplifyCfg::RemoveFalseEdges,
561                &Lint(post_drop_elaboration::CheckLiveDrops),
562            ],
563            None,
564            pm::Optimizations::Allowed,
565        );
566    }
567
568    debug!("runtime_mir_lowering({:?})", did);
569    run_runtime_lowering_passes(tcx, body);
570    assert!(body.phase == MirPhase::Runtime(RuntimePhase::Initial));
571
572    debug!("runtime_mir_cleanup({:?})", did);
573    run_runtime_cleanup_passes(tcx, body);
574    assert!(body.phase == MirPhase::Runtime(RuntimePhase::PostCleanup));
575}
576
577// FIXME(JakobDegen): Can we make these lists of passes consts?
578
579/// After this series of passes, no lifetime analysis based on borrowing can be done.
580fn run_analysis_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
581    let passes: &[&dyn MirPass<'tcx>] = &[
582        &impossible_predicates::ImpossiblePredicates,
583        &cleanup_post_borrowck::CleanupPostBorrowck,
584        &remove_noop_landing_pads::RemoveNoopLandingPads,
585        &simplify::SimplifyCfg::PostAnalysis,
586        &deref_separator::Derefer,
587    ];
588
589    pm::run_passes(
590        tcx,
591        body,
592        passes,
593        Some(MirPhase::Analysis(AnalysisPhase::PostCleanup)),
594        pm::Optimizations::Allowed,
595    );
596}
597
598/// Returns the sequence of passes that lowers analysis to runtime MIR.
599fn run_runtime_lowering_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
600    let passes: &[&dyn MirPass<'tcx>] = &[
601        // These next passes must be executed together.
602        &add_call_guards::CriticalCallEdges,
603        // Must be done before drop elaboration because we need to drop opaque types, too.
604        &post_analysis_normalize::PostAnalysisNormalize,
605        // Calling this after `PostAnalysisNormalize` ensures that we don't deal with opaque types.
606        &add_subtyping_projections::Subtyper,
607        &elaborate_drops::ElaborateDrops,
608        // Needs to happen after drop elaboration.
609        &Lint(check_call_recursion::CheckDropRecursion),
610        // This will remove extraneous landing pads which are no longer
611        // necessary as well as forcing any call in a non-unwinding
612        // function calling a possibly-unwinding function to abort the process.
613        &abort_unwinding_calls::AbortUnwindingCalls,
614        // AddMovesForPackedDrops needs to run after drop
615        // elaboration.
616        &add_moves_for_packed_drops::AddMovesForPackedDrops,
617        // `AddRetag` needs to run after `ElaborateDrops` but before `ElaborateBoxDerefs`.
618        // Otherwise it should run fairly late, but before optimizations begin.
619        &add_retag::AddRetag,
620        &elaborate_box_derefs::ElaborateBoxDerefs,
621        &coroutine::StateTransform,
622        &Lint(known_panics_lint::KnownPanicsLint),
623    ];
624    pm::run_passes_no_validate(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::Initial)));
625}
626
627/// Returns the sequence of passes that do the initial cleanup of runtime MIR.
628fn run_runtime_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
629    let passes: &[&dyn MirPass<'tcx>] = &[
630        &lower_intrinsics::LowerIntrinsics,
631        &remove_place_mention::RemovePlaceMention,
632        &simplify::SimplifyCfg::PreOptimizations,
633    ];
634
635    pm::run_passes(
636        tcx,
637        body,
638        passes,
639        Some(MirPhase::Runtime(RuntimePhase::PostCleanup)),
640        pm::Optimizations::Allowed,
641    );
642
643    // Clear this by anticipation. Optimizations and runtime MIR have no reason to look
644    // into this information, which is meant for borrowck diagnostics.
645    for decl in &mut body.local_decls {
646        decl.local_info = ClearCrossCrate::Clear;
647    }
648}
649
650fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
651    fn o1<T>(x: T) -> WithMinOptLevel<T> {
652        WithMinOptLevel(1, x)
653    }
654
655    let def_id = body.source.def_id();
656    let optimizations = if tcx.def_kind(def_id).has_codegen_attrs()
657        && tcx.codegen_fn_attrs(def_id).optimize.do_not_optimize()
658    {
659        pm::Optimizations::Suppressed
660    } else {
661        pm::Optimizations::Allowed
662    };
663
664    // The main optimizations that we do on MIR.
665    pm::run_passes(
666        tcx,
667        body,
668        &[
669            // Add some UB checks before any UB gets optimized away.
670            &check_alignment::CheckAlignment,
671            &check_null::CheckNull,
672            // Before inlining: trim down MIR with passes to reduce inlining work.
673
674            // Has to be done before inlining, otherwise actual call will be almost always inlined.
675            // Also simple, so can just do first.
676            &lower_slice_len::LowerSliceLenCalls,
677            // Perform instsimplify before inline to eliminate some trivial calls (like clone
678            // shims).
679            &instsimplify::InstSimplify::BeforeInline,
680            // Perform inlining of `#[rustc_force_inline]`-annotated callees.
681            &inline::ForceInline,
682            // Perform inlining, which may add a lot of code.
683            &inline::Inline,
684            // Code from other crates may have storage markers, so this needs to happen after
685            // inlining.
686            &remove_storage_markers::RemoveStorageMarkers,
687            // Inlining and instantiation may introduce ZST and useless drops.
688            &remove_zsts::RemoveZsts,
689            &remove_unneeded_drops::RemoveUnneededDrops,
690            // Type instantiation may create uninhabited enums.
691            // Also eliminates some unreachable branches based on variants of enums.
692            &unreachable_enum_branching::UnreachableEnumBranching,
693            &unreachable_prop::UnreachablePropagation,
694            &o1(simplify::SimplifyCfg::AfterUnreachableEnumBranching),
695            // Inlining may have introduced a lot of redundant code and a large move pattern.
696            // Now, we need to shrink the generated MIR.
697            &ref_prop::ReferencePropagation,
698            &sroa::ScalarReplacementOfAggregates,
699            &match_branches::MatchBranchSimplification,
700            // inst combine is after MatchBranchSimplification to clean up Ne(_1, false)
701            &multiple_return_terminators::MultipleReturnTerminators,
702            // After simplifycfg, it allows us to discover new opportunities for peephole
703            // optimizations.
704            &instsimplify::InstSimplify::AfterSimplifyCfg,
705            &simplify::SimplifyLocals::BeforeConstProp,
706            &dead_store_elimination::DeadStoreElimination::Initial,
707            &gvn::GVN,
708            &simplify::SimplifyLocals::AfterGVN,
709            &dataflow_const_prop::DataflowConstProp,
710            &single_use_consts::SingleUseConsts,
711            &o1(simplify_branches::SimplifyConstCondition::AfterConstProp),
712            &jump_threading::JumpThreading,
713            &early_otherwise_branch::EarlyOtherwiseBranch,
714            &simplify_comparison_integral::SimplifyComparisonIntegral,
715            &dest_prop::DestinationPropagation,
716            &o1(simplify_branches::SimplifyConstCondition::Final),
717            &o1(remove_noop_landing_pads::RemoveNoopLandingPads),
718            &o1(simplify::SimplifyCfg::Final),
719            // After the last SimplifyCfg, because this wants one-block functions.
720            &strip_debuginfo::StripDebugInfo,
721            &copy_prop::CopyProp,
722            &dead_store_elimination::DeadStoreElimination::Final,
723            &nrvo::RenameReturnPlace,
724            &simplify::SimplifyLocals::Final,
725            &multiple_return_terminators::MultipleReturnTerminators,
726            &large_enums::EnumSizeOpt { discrepancy: 128 },
727            // Some cleanup necessary at least for LLVM and potentially other codegen backends.
728            &add_call_guards::CriticalCallEdges,
729            // Cleanup for human readability, off by default.
730            &prettify::ReorderBasicBlocks,
731            &prettify::ReorderLocals,
732            // Dump the end result for testing and debugging purposes.
733            &dump_mir::Marker("PreCodegen"),
734        ],
735        Some(MirPhase::Runtime(RuntimePhase::Optimized)),
736        optimizations,
737    );
738}
739
740/// Optimize the MIR and prepare it for codegen.
741fn optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> &Body<'_> {
742    tcx.arena.alloc(inner_optimized_mir(tcx, did))
743}
744
745fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> {
746    if tcx.is_constructor(did.to_def_id()) {
747        // There's no reason to run all of the MIR passes on constructors when
748        // we can just output the MIR we want directly. This also saves const
749        // qualification and borrow checking the trouble of special casing
750        // constructors.
751        return shim::build_adt_ctor(tcx, did.to_def_id());
752    }
753
754    match tcx.hir_body_const_context(did) {
755        // Run the `mir_for_ctfe` query, which depends on `mir_drops_elaborated_and_const_checked`
756        // which we are going to steal below. Thus we need to run `mir_for_ctfe` first, so it
757        // computes and caches its result.
758        Some(hir::ConstContext::ConstFn) => tcx.ensure_done().mir_for_ctfe(did),
759        None => {}
760        Some(other) => panic!("do not use `optimized_mir` for constants: {other:?}"),
761    }
762    debug!("about to call mir_drops_elaborated...");
763    let body = tcx.mir_drops_elaborated_and_const_checked(did).steal();
764    let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::NotConst);
765
766    if body.tainted_by_errors.is_some() {
767        return body;
768    }
769
770    // Before doing anything, remember which items are being mentioned so that the set of items
771    // visited does not depend on the optimization level.
772    // We do not use `run_passes` for this as that might skip the pass if `injection_phase` is set.
773    mentioned_items::MentionedItems.run_pass(tcx, &mut body);
774
775    // If `mir_drops_elaborated_and_const_checked` found that the current body has unsatisfiable
776    // predicates, it will shrink the MIR to a single `unreachable` terminator.
777    // More generally, if MIR is a lone `unreachable`, there is nothing to optimize.
778    if let TerminatorKind::Unreachable = body.basic_blocks[START_BLOCK].terminator().kind
779        && body.basic_blocks[START_BLOCK].statements.is_empty()
780    {
781        return body;
782    }
783
784    run_optimization_passes(tcx, &mut body);
785
786    body
787}
788
789/// Fetch all the promoteds of an item and prepare their MIR bodies to be ready for
790/// constant evaluation once all generic parameters become known.
791fn promoted_mir(tcx: TyCtxt<'_>, def: LocalDefId) -> &IndexVec<Promoted, Body<'_>> {
792    if tcx.is_constructor(def.to_def_id()) {
793        return tcx.arena.alloc(IndexVec::new());
794    }
795
796    if !tcx.is_synthetic_mir(def) {
797        tcx.ensure_done().mir_borrowck(def);
798    }
799    let mut promoted = tcx.mir_promoted(def).1.steal();
800
801    for body in &mut promoted {
802        run_analysis_to_runtime_passes(tcx, body);
803    }
804
805    tcx.arena.alloc(promoted)
806}