1#![cfg_attr(bootstrap, feature(array_windows))]
3#![feature(assert_matches)]
4#![feature(box_patterns)]
5#![feature(const_type_name)]
6#![feature(cow_is_borrowed)]
7#![feature(file_buffered)]
8#![feature(gen_blocks)]
9#![feature(if_let_guard)]
10#![feature(impl_trait_in_assoc_type)]
11#![feature(try_blocks)]
12#![feature(yeet_expr)]
13use hir::ConstContext;
16use required_consts::RequiredConstsVisitor;
17use rustc_const_eval::check_consts::{self, ConstCx};
18use rustc_const_eval::util;
19use rustc_data_structures::fx::FxIndexSet;
20use rustc_data_structures::steal::Steal;
21use rustc_hir as hir;
22use rustc_hir::def::{CtorKind, DefKind};
23use rustc_hir::def_id::LocalDefId;
24use rustc_index::IndexVec;
25use rustc_middle::mir::{
26 AnalysisPhase, Body, CallSource, ClearCrossCrate, ConstOperand, ConstQualifs, LocalDecl,
27 MirPhase, Operand, Place, ProjectionElem, Promoted, RuntimePhase, Rvalue, START_BLOCK,
28 SourceInfo, Statement, StatementKind, TerminatorKind,
29};
30use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt};
31use rustc_middle::util::Providers;
32use rustc_middle::{bug, query, span_bug};
33use rustc_mir_build::builder::build_mir;
34use rustc_span::source_map::Spanned;
35use rustc_span::{DUMMY_SP, sym};
36use tracing::debug;
37
38#[macro_use]
39mod pass_manager;
40
41use std::sync::LazyLock;
42
43use pass_manager::{self as pm, Lint, MirLint, MirPass, WithMinOptLevel};
44
45mod check_pointers;
46mod cost_checker;
47mod cross_crate_inline;
48mod deduce_param_attrs;
49mod elaborate_drop;
50mod errors;
51mod ffi_unwind_calls;
52mod lint;
53mod lint_tail_expr_drop_order;
54mod liveness;
55mod patch;
56mod shim;
57mod ssa;
58mod trivial_const;
59
60macro_rules! declare_passes {
83 (
84 $(
85 $vis:vis mod $mod_name:ident : $($pass_name:ident $( { $($ident:ident),* } )?),+ $(,)?;
86 )*
87 ) => {
88 $(
89 $vis mod $mod_name;
90 $(
91 #[allow(unused_imports)]
93 use $mod_name::$pass_name as _;
94 )+
95 )*
96
97 static PASS_NAMES: LazyLock<FxIndexSet<&str>> = LazyLock::new(|| [
98 "PreCodegen",
100 $(
101 $(
102 stringify!($pass_name),
103 $(
104 $(
105 $mod_name::$pass_name::$ident.name(),
106 )*
107 )?
108 )+
109 )*
110 ].into_iter().collect());
111 };
112}
113
114declare_passes! {
115 mod abort_unwinding_calls : AbortUnwindingCalls;
116 mod add_call_guards : AddCallGuards { AllCallEdges, CriticalCallEdges };
117 mod add_moves_for_packed_drops : AddMovesForPackedDrops;
118 mod add_retag : AddRetag;
119 mod add_subtyping_projections : Subtyper;
120 mod check_inline : CheckForceInline;
121 mod check_call_recursion : CheckCallRecursion, CheckDropRecursion;
122 mod check_inline_always_target_features: CheckInlineAlwaysTargetFeature;
123 mod check_alignment : CheckAlignment;
124 mod check_enums : CheckEnums;
125 mod check_const_item_mutation : CheckConstItemMutation;
126 mod check_null : CheckNull;
127 mod check_packed_ref : CheckPackedRef;
128 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 erase_deref_temps : EraseDerefTemps;
145 mod elaborate_box_derefs : ElaborateBoxDerefs;
146 mod elaborate_drops : ElaborateDrops;
147 mod function_item_references : FunctionItemReferences;
148 mod gvn : GVN;
149 pub mod inline : Inline, ForceInline;
152 mod impossible_predicates : ImpossiblePredicates;
153 mod instsimplify : InstSimplify { BeforeInline, AfterSimplifyCfg };
154 mod jump_threading : JumpThreading;
155 mod known_panics_lint : KnownPanicsLint;
156 mod large_enums : EnumSizeOpt;
157 mod lower_intrinsics : LowerIntrinsics;
158 mod lower_slice_len : LowerSliceLenCalls;
159 mod match_branches : MatchBranchSimplification;
160 mod mentioned_items : MentionedItems;
161 mod multiple_return_terminators : MultipleReturnTerminators;
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 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 AfterInstSimplify,
194 AfterConstProp,
195 Final
196 };
197 mod simplify_comparison_integral : SimplifyComparisonIntegral;
198 mod single_use_consts : SingleUseConsts;
199 mod sroa : ScalarReplacementOfAggregates;
200 mod strip_debuginfo : StripDebugInfo;
201 mod unreachable_enum_branching : UnreachableEnumBranching;
202 mod unreachable_prop : UnreachablePropagation;
203 mod validate : Validator;
204}
205
206rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
207
208pub fn provide(providers: &mut Providers) {
209 coverage::query::provide(providers);
210 ffi_unwind_calls::provide(providers);
211 shim::provide(providers);
212 cross_crate_inline::provide(providers);
213 providers.queries = query::Providers {
214 mir_keys,
215 mir_built,
216 mir_const_qualif,
217 mir_promoted,
218 mir_drops_elaborated_and_const_checked,
219 mir_for_ctfe,
220 mir_coroutine_witnesses: coroutine::mir_coroutine_witnesses,
221 optimized_mir,
222 check_liveness: liveness::check_liveness,
223 is_mir_available,
224 is_ctfe_mir_available: is_mir_available,
225 mir_callgraph_cyclic: inline::cycle::mir_callgraph_cyclic,
226 mir_inliner_callees: inline::cycle::mir_inliner_callees,
227 promoted_mir,
228 deduced_param_attrs: deduce_param_attrs::deduced_param_attrs,
229 coroutine_by_move_body_def_id: coroutine::coroutine_by_move_body_def_id,
230 trivial_const: trivial_const::trivial_const_provider,
231 ..providers.queries
232 };
233}
234
235fn remap_mir_for_const_eval_select<'tcx>(
236 tcx: TyCtxt<'tcx>,
237 mut body: Body<'tcx>,
238 context: hir::Constness,
239) -> Body<'tcx> {
240 for bb in body.basic_blocks.as_mut().iter_mut() {
241 let terminator = bb.terminator.as_mut().expect("invalid terminator");
242 match terminator.kind {
243 TerminatorKind::Call {
244 func: Operand::Constant(box ConstOperand { ref const_, .. }),
245 ref mut args,
246 destination,
247 target,
248 unwind,
249 fn_span,
250 ..
251 } if let ty::FnDef(def_id, _) = *const_.ty().kind()
252 && tcx.is_intrinsic(def_id, sym::const_eval_select) =>
253 {
254 let Ok([tupled_args, called_in_const, called_at_rt]) = take_array(args) else {
255 unreachable!()
256 };
257 let ty = tupled_args.node.ty(&body.local_decls, tcx);
258 let fields = ty.tuple_fields();
259 let num_args = fields.len();
260 let func =
261 if context == hir::Constness::Const { called_in_const } else { called_at_rt };
262 let (method, place): (fn(Place<'tcx>) -> Operand<'tcx>, Place<'tcx>) =
263 match tupled_args.node {
264 Operand::Constant(_) => {
265 let local = body.local_decls.push(LocalDecl::new(ty, fn_span));
269 bb.statements.push(Statement::new(
270 SourceInfo::outermost(fn_span),
271 StatementKind::Assign(Box::new((
272 local.into(),
273 Rvalue::Use(tupled_args.node.clone()),
274 ))),
275 ));
276 (Operand::Move, local.into())
277 }
278 Operand::Move(place) => (Operand::Move, place),
279 Operand::Copy(place) => (Operand::Copy, place),
280 };
281 let place_elems = place.projection;
282 let arguments = (0..num_args)
283 .map(|x| {
284 let mut place_elems = place_elems.to_vec();
285 place_elems.push(ProjectionElem::Field(x.into(), fields[x]));
286 let projection = tcx.mk_place_elems(&place_elems);
287 let place = Place { local: place.local, projection };
288 Spanned { node: method(place), span: DUMMY_SP }
289 })
290 .collect();
291 terminator.kind = TerminatorKind::Call {
292 func: func.node,
293 args: arguments,
294 destination,
295 target,
296 unwind,
297 call_source: CallSource::Misc,
298 fn_span,
299 };
300 }
301 _ => {}
302 }
303 }
304 body
305}
306
307fn take_array<T, const N: usize>(b: &mut Box<[T]>) -> Result<[T; N], Box<[T]>> {
308 let b: Box<[T; N]> = std::mem::take(b).try_into()?;
309 Ok(*b)
310}
311
312fn is_mir_available(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
313 tcx.mir_keys(()).contains(&def_id)
314}
315
316fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet<LocalDefId> {
319 let mut set: FxIndexSet<_> = tcx.hir_body_owners().collect();
321
322 set.retain(|&def_id| !matches!(tcx.def_kind(def_id), DefKind::GlobalAsm));
325
326 for body_owner in tcx.hir_body_owners() {
329 if let DefKind::Closure = tcx.def_kind(body_owner)
330 && tcx.needs_coroutine_by_move_body_def_id(body_owner.to_def_id())
331 {
332 set.insert(tcx.coroutine_by_move_body_def_id(body_owner).expect_local());
333 }
334 }
335
336 for item in tcx.hir_crate_items(()).free_items() {
339 if let DefKind::Struct | DefKind::Enum = tcx.def_kind(item.owner_id) {
340 for variant in tcx.adt_def(item.owner_id).variants() {
341 if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
342 set.insert(ctor_def_id.expect_local());
343 }
344 }
345 }
346 }
347
348 set
349}
350
351fn mir_const_qualif(tcx: TyCtxt<'_>, def: LocalDefId) -> ConstQualifs {
352 let body = &tcx.mir_built(def).borrow();
357 let ccx = check_consts::ConstCx::new(tcx, body);
358 match ccx.const_kind {
360 Some(ConstContext::Const { .. } | ConstContext::Static(_) | ConstContext::ConstFn) => {}
361 None => span_bug!(
362 tcx.def_span(def),
363 "`mir_const_qualif` should only be called on const fns and const items"
364 ),
365 }
366
367 if body.return_ty().references_error() {
368 tcx.dcx().span_delayed_bug(body.span, "mir_const_qualif: MIR had errors");
370 return Default::default();
371 }
372
373 let mut validator = check_consts::check::Checker::new(&ccx);
374 validator.check_body();
375
376 validator.qualifs_in_return_place()
379}
380
381fn mir_built(tcx: TyCtxt<'_>, def: LocalDefId) -> &Steal<Body<'_>> {
382 let mut body = build_mir(tcx, def);
383
384 if trivial_const::trivial_const(tcx, def, || &body).is_some() {
388 let body = tcx.alloc_steal_mir(body);
390 pass_manager::dump_mir_for_phase_change(tcx, &body.borrow());
391 return body;
392 }
393
394 pass_manager::dump_mir_for_phase_change(tcx, &body);
395
396 pm::run_passes(
397 tcx,
398 &mut body,
399 &[
400 &Lint(check_inline::CheckForceInline),
402 &Lint(check_call_recursion::CheckCallRecursion),
403 &Lint(check_inline_always_target_features::CheckInlineAlwaysTargetFeature),
406 &Lint(check_packed_ref::CheckPackedRef),
407 &Lint(check_const_item_mutation::CheckConstItemMutation),
408 &Lint(function_item_references::FunctionItemReferences),
409 &simplify::SimplifyCfg::Initial,
411 &Lint(sanity_check::SanityCheck),
412 ],
413 None,
414 pm::Optimizations::Allowed,
415 );
416 tcx.alloc_steal_mir(body)
417}
418
419fn mir_promoted(
421 tcx: TyCtxt<'_>,
422 def: LocalDefId,
423) -> (&Steal<Body<'_>>, &Steal<IndexVec<Promoted, Body<'_>>>) {
424 debug_assert!(!tcx.is_trivial_const(def), "Tried to get mir_promoted of a trivial const");
425
426 let const_qualifs = match tcx.def_kind(def) {
431 DefKind::Fn | DefKind::AssocFn | DefKind::Closure
432 if tcx.constness(def) == hir::Constness::Const =>
433 {
434 tcx.mir_const_qualif(def)
435 }
436 DefKind::AssocConst
437 | DefKind::Const
438 | DefKind::Static { .. }
439 | DefKind::InlineConst
440 | DefKind::AnonConst => tcx.mir_const_qualif(def),
441 _ => ConstQualifs::default(),
442 };
443
444 tcx.ensure_done().has_ffi_unwind_calls(def);
446
447 if tcx.needs_coroutine_by_move_body_def_id(def.to_def_id()) {
449 tcx.ensure_done().coroutine_by_move_body_def_id(def);
450 }
451
452 tcx.ensure_done().trivial_const(def);
454
455 let mut body = tcx.mir_built(def).steal();
456 if let Some(error_reported) = const_qualifs.tainted_by_errors {
457 body.tainted_by_errors = Some(error_reported);
458 }
459
460 RequiredConstsVisitor::compute_required_consts(&mut body);
463
464 let promote_pass = promote_consts::PromoteTemps::default();
466 pm::run_passes(
467 tcx,
468 &mut body,
469 &[&promote_pass, &simplify::SimplifyCfg::PromoteConsts, &coverage::InstrumentCoverage],
470 Some(MirPhase::Analysis(AnalysisPhase::Initial)),
471 pm::Optimizations::Allowed,
472 );
473
474 lint_tail_expr_drop_order::run_lint(tcx, def, &body);
475
476 let promoted = promote_pass.promoted_fragments.into_inner();
477 (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
478}
479
480fn mir_for_ctfe(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &Body<'_> {
482 debug_assert!(!tcx.is_trivial_const(def_id), "Tried to get mir_for_ctfe of a trivial const");
483 tcx.arena.alloc(inner_mir_for_ctfe(tcx, def_id))
484}
485
486fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: LocalDefId) -> Body<'_> {
487 if tcx.is_constructor(def.to_def_id()) {
489 return shim::build_adt_ctor(tcx, def.to_def_id());
494 }
495
496 let body = tcx.mir_drops_elaborated_and_const_checked(def);
497 let body = match tcx.hir_body_const_context(def) {
498 Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => body.steal(),
501 Some(hir::ConstContext::ConstFn) => body.borrow().clone(),
502 None => bug!("`mir_for_ctfe` called on non-const {def:?}"),
503 };
504
505 let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::Const);
506 pm::run_passes(tcx, &mut body, &[&ctfe_limit::CtfeLimit], None, pm::Optimizations::Allowed);
507
508 body
509}
510
511fn mir_drops_elaborated_and_const_checked(tcx: TyCtxt<'_>, def: LocalDefId) -> &Steal<Body<'_>> {
515 if tcx.is_coroutine(def.to_def_id()) {
516 tcx.ensure_done().mir_coroutine_witnesses(def);
517 }
518
519 let tainted_by_errors = if !tcx.is_synthetic_mir(def) {
521 tcx.mir_borrowck(tcx.typeck_root_def_id(def.to_def_id()).expect_local()).err()
522 } else {
523 None
524 };
525
526 let is_fn_like = tcx.def_kind(def).is_fn_like();
527 if is_fn_like {
528 if pm::should_run_pass(tcx, &inline::Inline, pm::Optimizations::Allowed)
530 || inline::ForceInline::should_run_pass_for_callee(tcx, def.to_def_id())
531 {
532 tcx.ensure_done().mir_inliner_callees(ty::InstanceKind::Item(def.to_def_id()));
533 }
534 }
535
536 tcx.ensure_done().check_liveness(def);
537
538 let (body, _) = tcx.mir_promoted(def);
539 let mut body = body.steal();
540
541 if let Some(error_reported) = tainted_by_errors {
542 body.tainted_by_errors = Some(error_reported);
543 }
544
545 let root = tcx.typeck_root_def_id(def.to_def_id());
550 match tcx.def_kind(root) {
551 DefKind::Fn
552 | DefKind::AssocFn
553 | DefKind::Static { .. }
554 | DefKind::Const
555 | DefKind::AssocConst => {
556 if let Err(guar) = tcx.ensure_ok().check_well_formed(root.expect_local()) {
557 body.tainted_by_errors = Some(guar);
558 }
559 }
560 _ => {}
561 }
562
563 run_analysis_to_runtime_passes(tcx, &mut body);
564
565 tcx.alloc_steal_mir(body)
566}
567
568pub fn run_analysis_to_runtime_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
571 assert!(body.phase == MirPhase::Analysis(AnalysisPhase::Initial));
572 let did = body.source.def_id();
573
574 debug!("analysis_mir_cleanup({:?})", did);
575 run_analysis_cleanup_passes(tcx, body);
576 assert!(body.phase == MirPhase::Analysis(AnalysisPhase::PostCleanup));
577
578 if check_consts::post_drop_elaboration::checking_enabled(&ConstCx::new(tcx, body)) {
580 pm::run_passes(
581 tcx,
582 body,
583 &[
584 &remove_uninit_drops::RemoveUninitDrops,
585 &simplify::SimplifyCfg::RemoveFalseEdges,
586 &Lint(post_drop_elaboration::CheckLiveDrops),
587 ],
588 None,
589 pm::Optimizations::Allowed,
590 );
591 }
592
593 debug!("runtime_mir_lowering({:?})", did);
594 run_runtime_lowering_passes(tcx, body);
595 assert!(body.phase == MirPhase::Runtime(RuntimePhase::Initial));
596
597 debug!("runtime_mir_cleanup({:?})", did);
598 run_runtime_cleanup_passes(tcx, body);
599 assert!(body.phase == MirPhase::Runtime(RuntimePhase::PostCleanup));
600}
601
602fn run_analysis_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
606 let passes: &[&dyn MirPass<'tcx>] = &[
607 &impossible_predicates::ImpossiblePredicates,
608 &cleanup_post_borrowck::CleanupPostBorrowck,
609 &remove_noop_landing_pads::RemoveNoopLandingPads,
610 &simplify::SimplifyCfg::PostAnalysis,
611 &deref_separator::Derefer,
612 ];
613
614 pm::run_passes(
615 tcx,
616 body,
617 passes,
618 Some(MirPhase::Analysis(AnalysisPhase::PostCleanup)),
619 pm::Optimizations::Allowed,
620 );
621}
622
623fn run_runtime_lowering_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
625 let passes: &[&dyn MirPass<'tcx>] = &[
626 &add_call_guards::CriticalCallEdges,
628 &post_analysis_normalize::PostAnalysisNormalize,
630 &add_subtyping_projections::Subtyper,
632 &elaborate_drops::ElaborateDrops,
633 &Lint(check_call_recursion::CheckDropRecursion),
635 &abort_unwinding_calls::AbortUnwindingCalls,
639 &add_moves_for_packed_drops::AddMovesForPackedDrops,
642 &add_retag::AddRetag,
645 &erase_deref_temps::EraseDerefTemps,
646 &elaborate_box_derefs::ElaborateBoxDerefs,
647 &coroutine::StateTransform,
648 &Lint(known_panics_lint::KnownPanicsLint),
649 ];
650 pm::run_passes_no_validate(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::Initial)));
651}
652
653fn run_runtime_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
655 let passes: &[&dyn MirPass<'tcx>] = &[
656 &lower_intrinsics::LowerIntrinsics,
657 &remove_place_mention::RemovePlaceMention,
658 &simplify::SimplifyCfg::PreOptimizations,
659 ];
660
661 pm::run_passes(
662 tcx,
663 body,
664 passes,
665 Some(MirPhase::Runtime(RuntimePhase::PostCleanup)),
666 pm::Optimizations::Allowed,
667 );
668
669 for decl in &mut body.local_decls {
672 decl.local_info = ClearCrossCrate::Clear;
673 }
674}
675
676pub(crate) fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
677 fn o1<T>(x: T) -> WithMinOptLevel<T> {
678 WithMinOptLevel(1, x)
679 }
680
681 let def_id = body.source.def_id();
682 let optimizations = if tcx.def_kind(def_id).has_codegen_attrs()
683 && tcx.codegen_fn_attrs(def_id).optimize.do_not_optimize()
684 {
685 pm::Optimizations::Suppressed
686 } else {
687 pm::Optimizations::Allowed
688 };
689
690 pm::run_passes(
692 tcx,
693 body,
694 &[
695 &check_alignment::CheckAlignment,
697 &check_null::CheckNull,
698 &check_enums::CheckEnums,
699 &lower_slice_len::LowerSliceLenCalls,
704 &instsimplify::InstSimplify::BeforeInline,
707 &inline::ForceInline,
709 &inline::Inline,
711 &remove_storage_markers::RemoveStorageMarkers,
716 &remove_zsts::RemoveZsts,
718 &remove_unneeded_drops::RemoveUnneededDrops,
719 &unreachable_enum_branching::UnreachableEnumBranching,
722 &unreachable_prop::UnreachablePropagation,
723 &o1(simplify::SimplifyCfg::AfterUnreachableEnumBranching),
724 &multiple_return_terminators::MultipleReturnTerminators,
725 &instsimplify::InstSimplify::AfterSimplifyCfg,
729 &o1(simplify_branches::SimplifyConstCondition::AfterInstSimplify),
738 &ref_prop::ReferencePropagation,
739 &sroa::ScalarReplacementOfAggregates,
740 &simplify::SimplifyLocals::BeforeConstProp,
741 &dead_store_elimination::DeadStoreElimination::Initial,
742 &gvn::GVN,
743 &simplify::SimplifyLocals::AfterGVN,
744 &match_branches::MatchBranchSimplification,
745 &dataflow_const_prop::DataflowConstProp,
746 &single_use_consts::SingleUseConsts,
747 &o1(simplify_branches::SimplifyConstCondition::AfterConstProp),
748 &jump_threading::JumpThreading,
749 &early_otherwise_branch::EarlyOtherwiseBranch,
750 &simplify_comparison_integral::SimplifyComparisonIntegral,
751 &o1(simplify_branches::SimplifyConstCondition::Final),
752 &o1(remove_noop_landing_pads::RemoveNoopLandingPads),
753 &o1(simplify::SimplifyCfg::Final),
754 &strip_debuginfo::StripDebugInfo,
756 ©_prop::CopyProp,
757 &dead_store_elimination::DeadStoreElimination::Final,
758 &dest_prop::DestinationPropagation,
759 &simplify::SimplifyLocals::Final,
760 &multiple_return_terminators::MultipleReturnTerminators,
761 &large_enums::EnumSizeOpt { discrepancy: 128 },
762 &add_call_guards::CriticalCallEdges,
764 &prettify::ReorderBasicBlocks,
766 &prettify::ReorderLocals,
767 &dump_mir::Marker("PreCodegen"),
769 ],
770 Some(MirPhase::Runtime(RuntimePhase::Optimized)),
771 optimizations,
772 );
773}
774
775fn optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> &Body<'_> {
777 tcx.arena.alloc(inner_optimized_mir(tcx, did))
778}
779
780fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> {
781 if tcx.is_constructor(did.to_def_id()) {
782 return shim::build_adt_ctor(tcx, did.to_def_id());
787 }
788
789 match tcx.hir_body_const_context(did) {
790 Some(hir::ConstContext::ConstFn) => tcx.ensure_done().mir_for_ctfe(did),
794 None => {}
795 Some(other) => panic!("do not use `optimized_mir` for constants: {other:?}"),
796 }
797 debug!("about to call mir_drops_elaborated...");
798 let body = tcx.mir_drops_elaborated_and_const_checked(did).steal();
799 let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::NotConst);
800
801 if body.tainted_by_errors.is_some() {
802 return body;
803 }
804
805 mentioned_items::MentionedItems.run_pass(tcx, &mut body);
809
810 if let TerminatorKind::Unreachable = body.basic_blocks[START_BLOCK].terminator().kind
814 && body.basic_blocks[START_BLOCK].statements.is_empty()
815 {
816 return body;
817 }
818
819 run_optimization_passes(tcx, &mut body);
820
821 body
822}
823
824fn promoted_mir(tcx: TyCtxt<'_>, def: LocalDefId) -> &IndexVec<Promoted, Body<'_>> {
827 if tcx.is_constructor(def.to_def_id()) {
828 return tcx.arena.alloc(IndexVec::new());
829 }
830
831 if !tcx.is_synthetic_mir(def) {
832 tcx.ensure_done().mir_borrowck(tcx.typeck_root_def_id(def.to_def_id()).expect_local());
833 }
834 let mut promoted = tcx.mir_promoted(def).1.steal();
835
836 for body in &mut promoted {
837 run_analysis_to_runtime_passes(tcx, body);
838 }
839
840 tcx.arena.alloc(promoted)
841}