1#![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(if_let_guard)]
9#![feature(impl_trait_in_assoc_type)]
10#![feature(map_try_insert)]
11#![feature(never_type)]
12#![feature(try_blocks)]
13#![feature(vec_deque_pop_if)]
14#![feature(yeet_expr)]
15use hir::ConstContext;
18use required_consts::RequiredConstsVisitor;
19use rustc_const_eval::check_consts::{self, ConstCx};
20use rustc_const_eval::util;
21use rustc_data_structures::fx::FxIndexSet;
22use rustc_data_structures::steal::Steal;
23use rustc_hir as hir;
24use rustc_hir::def::{CtorKind, DefKind};
25use rustc_hir::def_id::LocalDefId;
26use rustc_index::IndexVec;
27use rustc_middle::mir::{
28 AnalysisPhase, Body, CallSource, ClearCrossCrate, ConstOperand, ConstQualifs, LocalDecl,
29 MirPhase, Operand, Place, ProjectionElem, Promoted, RuntimePhase, Rvalue, START_BLOCK,
30 SourceInfo, Statement, StatementKind, TerminatorKind,
31};
32use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt};
33use rustc_middle::util::Providers;
34use rustc_middle::{bug, query, span_bug};
35use rustc_mir_build::builder::build_mir;
36use rustc_span::source_map::Spanned;
37use rustc_span::{DUMMY_SP, sym};
38use tracing::debug;
39
40#[macro_use]
41mod pass_manager;
42
43use std::sync::LazyLock;
44
45use pass_manager::{self as pm, Lint, MirLint, MirPass, WithMinOptLevel};
46
47mod check_pointers;
48mod cost_checker;
49mod cross_crate_inline;
50mod deduce_param_attrs;
51mod elaborate_drop;
52mod errors;
53mod ffi_unwind_calls;
54mod lint;
55mod lint_tail_expr_drop_order;
56mod patch;
57mod shim;
58mod ssa;
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_alignment : CheckAlignment;
123 mod check_const_item_mutation : CheckConstItemMutation;
124 mod check_null : CheckNull;
125 mod check_packed_ref : CheckPackedRef;
126 mod check_undefined_transmutes : CheckUndefinedTransmutes;
127 mod check_unnecessary_transmutes: CheckUnnecessaryTransmutes;
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 elaborate_box_derefs : ElaborateBoxDerefs;
145 mod elaborate_drops : ElaborateDrops;
146 mod function_item_references : FunctionItemReferences;
147 mod gvn : GVN;
148 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 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 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
313fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet<LocalDefId> {
316 let mut set: FxIndexSet<_> = tcx.hir_body_owners().collect();
318
319 set.retain(|&def_id| !matches!(tcx.def_kind(def_id), DefKind::GlobalAsm));
322
323 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 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 let body = &tcx.mir_built(def).borrow();
354 let ccx = check_consts::ConstCx::new(tcx, body);
355 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 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 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 &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 &Lint(check_unnecessary_transmutes::CheckUnnecessaryTransmutes),
395 &simplify::SimplifyCfg::Initial,
397 &Lint(sanity_check::SanityCheck),
398 ],
399 None,
400 pm::Optimizations::Allowed,
401 );
402 tcx.alloc_steal_mir(body)
403}
404
405fn mir_promoted(
407 tcx: TyCtxt<'_>,
408 def: LocalDefId,
409) -> (&Steal<Body<'_>>, &Steal<IndexVec<Promoted, Body<'_>>>) {
410 let const_qualifs = match tcx.def_kind(def) {
415 DefKind::Fn | DefKind::AssocFn | DefKind::Closure
416 if tcx.constness(def) == hir::Constness::Const
417 || tcx.is_const_default_method(def.to_def_id()) =>
418 {
419 tcx.mir_const_qualif(def)
420 }
421 DefKind::AssocConst
422 | DefKind::Const
423 | DefKind::Static { .. }
424 | DefKind::InlineConst
425 | DefKind::AnonConst => tcx.mir_const_qualif(def),
426 _ => ConstQualifs::default(),
427 };
428
429 tcx.ensure_done().has_ffi_unwind_calls(def);
431
432 if tcx.needs_coroutine_by_move_body_def_id(def.to_def_id()) {
434 tcx.ensure_done().coroutine_by_move_body_def_id(def);
435 }
436
437 let mut body = tcx.mir_built(def).steal();
438 if let Some(error_reported) = const_qualifs.tainted_by_errors {
439 body.tainted_by_errors = Some(error_reported);
440 }
441
442 RequiredConstsVisitor::compute_required_consts(&mut body);
445
446 let promote_pass = promote_consts::PromoteTemps::default();
448 pm::run_passes(
449 tcx,
450 &mut body,
451 &[&promote_pass, &simplify::SimplifyCfg::PromoteConsts, &coverage::InstrumentCoverage],
452 Some(MirPhase::Analysis(AnalysisPhase::Initial)),
453 pm::Optimizations::Allowed,
454 );
455
456 lint_tail_expr_drop_order::run_lint(tcx, def, &body);
457
458 let promoted = promote_pass.promoted_fragments.into_inner();
459 (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
460}
461
462fn mir_for_ctfe(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &Body<'_> {
464 tcx.arena.alloc(inner_mir_for_ctfe(tcx, def_id))
465}
466
467fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: LocalDefId) -> Body<'_> {
468 if tcx.is_constructor(def.to_def_id()) {
470 return shim::build_adt_ctor(tcx, def.to_def_id());
475 }
476
477 let body = tcx.mir_drops_elaborated_and_const_checked(def);
478 let body = match tcx.hir_body_const_context(def) {
479 Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => body.steal(),
482 Some(hir::ConstContext::ConstFn) => body.borrow().clone(),
483 None => bug!("`mir_for_ctfe` called on non-const {def:?}"),
484 };
485
486 let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::Const);
487 pm::run_passes(tcx, &mut body, &[&ctfe_limit::CtfeLimit], None, pm::Optimizations::Allowed);
488
489 body
490}
491
492fn mir_drops_elaborated_and_const_checked(tcx: TyCtxt<'_>, def: LocalDefId) -> &Steal<Body<'_>> {
496 if tcx.is_coroutine(def.to_def_id()) {
497 tcx.ensure_done().mir_coroutine_witnesses(def);
498 }
499
500 let tainted_by_errors = if !tcx.is_synthetic_mir(def) {
502 tcx.mir_borrowck(tcx.typeck_root_def_id(def.to_def_id()).expect_local()).err()
503 } else {
504 None
505 };
506
507 let is_fn_like = tcx.def_kind(def).is_fn_like();
508 if is_fn_like {
509 if pm::should_run_pass(tcx, &inline::Inline, pm::Optimizations::Allowed)
511 || inline::ForceInline::should_run_pass_for_callee(tcx, def.to_def_id())
512 {
513 tcx.ensure_done().mir_inliner_callees(ty::InstanceKind::Item(def.to_def_id()));
514 }
515 }
516
517 let (body, _) = tcx.mir_promoted(def);
518 let mut body = body.steal();
519
520 if let Some(error_reported) = tainted_by_errors {
521 body.tainted_by_errors = Some(error_reported);
522 }
523
524 let root = tcx.typeck_root_def_id(def.to_def_id());
529 match tcx.def_kind(root) {
530 DefKind::Fn
531 | DefKind::AssocFn
532 | DefKind::Static { .. }
533 | DefKind::Const
534 | DefKind::AssocConst => {
535 if let Err(guar) = tcx.ensure_ok().check_well_formed(root.expect_local()) {
536 body.tainted_by_errors = Some(guar);
537 }
538 }
539 _ => {}
540 }
541
542 run_analysis_to_runtime_passes(tcx, &mut body);
543
544 tcx.alloc_steal_mir(body)
545}
546
547pub fn run_analysis_to_runtime_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
550 assert!(body.phase == MirPhase::Analysis(AnalysisPhase::Initial));
551 let did = body.source.def_id();
552
553 debug!("analysis_mir_cleanup({:?})", did);
554 run_analysis_cleanup_passes(tcx, body);
555 assert!(body.phase == MirPhase::Analysis(AnalysisPhase::PostCleanup));
556
557 if check_consts::post_drop_elaboration::checking_enabled(&ConstCx::new(tcx, body)) {
559 pm::run_passes(
560 tcx,
561 body,
562 &[
563 &remove_uninit_drops::RemoveUninitDrops,
564 &simplify::SimplifyCfg::RemoveFalseEdges,
565 &Lint(post_drop_elaboration::CheckLiveDrops),
566 ],
567 None,
568 pm::Optimizations::Allowed,
569 );
570 }
571
572 debug!("runtime_mir_lowering({:?})", did);
573 run_runtime_lowering_passes(tcx, body);
574 assert!(body.phase == MirPhase::Runtime(RuntimePhase::Initial));
575
576 debug!("runtime_mir_cleanup({:?})", did);
577 run_runtime_cleanup_passes(tcx, body);
578 assert!(body.phase == MirPhase::Runtime(RuntimePhase::PostCleanup));
579}
580
581fn run_analysis_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
585 let passes: &[&dyn MirPass<'tcx>] = &[
586 &impossible_predicates::ImpossiblePredicates,
587 &cleanup_post_borrowck::CleanupPostBorrowck,
588 &remove_noop_landing_pads::RemoveNoopLandingPads,
589 &simplify::SimplifyCfg::PostAnalysis,
590 &deref_separator::Derefer,
591 ];
592
593 pm::run_passes(
594 tcx,
595 body,
596 passes,
597 Some(MirPhase::Analysis(AnalysisPhase::PostCleanup)),
598 pm::Optimizations::Allowed,
599 );
600}
601
602fn run_runtime_lowering_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
604 let passes: &[&dyn MirPass<'tcx>] = &[
605 &add_call_guards::CriticalCallEdges,
607 &post_analysis_normalize::PostAnalysisNormalize,
609 &add_subtyping_projections::Subtyper,
611 &elaborate_drops::ElaborateDrops,
612 &Lint(check_call_recursion::CheckDropRecursion),
614 &abort_unwinding_calls::AbortUnwindingCalls,
618 &add_moves_for_packed_drops::AddMovesForPackedDrops,
621 &add_retag::AddRetag,
624 &elaborate_box_derefs::ElaborateBoxDerefs,
625 &coroutine::StateTransform,
626 &Lint(known_panics_lint::KnownPanicsLint),
627 ];
628 pm::run_passes_no_validate(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::Initial)));
629}
630
631fn run_runtime_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
633 let passes: &[&dyn MirPass<'tcx>] = &[
634 &lower_intrinsics::LowerIntrinsics,
635 &remove_place_mention::RemovePlaceMention,
636 &simplify::SimplifyCfg::PreOptimizations,
637 ];
638
639 pm::run_passes(
640 tcx,
641 body,
642 passes,
643 Some(MirPhase::Runtime(RuntimePhase::PostCleanup)),
644 pm::Optimizations::Allowed,
645 );
646
647 for decl in &mut body.local_decls {
650 decl.local_info = ClearCrossCrate::Clear;
651 }
652}
653
654pub(crate) fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
655 fn o1<T>(x: T) -> WithMinOptLevel<T> {
656 WithMinOptLevel(1, x)
657 }
658
659 let def_id = body.source.def_id();
660 let optimizations = if tcx.def_kind(def_id).has_codegen_attrs()
661 && tcx.codegen_fn_attrs(def_id).optimize.do_not_optimize()
662 {
663 pm::Optimizations::Suppressed
664 } else {
665 pm::Optimizations::Allowed
666 };
667
668 pm::run_passes(
670 tcx,
671 body,
672 &[
673 &check_alignment::CheckAlignment,
675 &check_null::CheckNull,
676 &lower_slice_len::LowerSliceLenCalls,
681 &instsimplify::InstSimplify::BeforeInline,
684 &inline::ForceInline,
686 &inline::Inline,
688 &remove_storage_markers::RemoveStorageMarkers,
691 &remove_zsts::RemoveZsts,
693 &remove_unneeded_drops::RemoveUnneededDrops,
694 &unreachable_enum_branching::UnreachableEnumBranching,
697 &unreachable_prop::UnreachablePropagation,
698 &o1(simplify::SimplifyCfg::AfterUnreachableEnumBranching),
699 &ref_prop::ReferencePropagation,
702 &sroa::ScalarReplacementOfAggregates,
703 &multiple_return_terminators::MultipleReturnTerminators,
704 &instsimplify::InstSimplify::AfterSimplifyCfg,
707 &simplify::SimplifyLocals::BeforeConstProp,
708 &dead_store_elimination::DeadStoreElimination::Initial,
709 &gvn::GVN,
710 &simplify::SimplifyLocals::AfterGVN,
711 &match_branches::MatchBranchSimplification,
712 &dataflow_const_prop::DataflowConstProp,
713 &single_use_consts::SingleUseConsts,
714 &o1(simplify_branches::SimplifyConstCondition::AfterConstProp),
715 &jump_threading::JumpThreading,
716 &early_otherwise_branch::EarlyOtherwiseBranch,
717 &simplify_comparison_integral::SimplifyComparisonIntegral,
718 &dest_prop::DestinationPropagation,
719 &o1(simplify_branches::SimplifyConstCondition::Final),
720 &o1(remove_noop_landing_pads::RemoveNoopLandingPads),
721 &o1(simplify::SimplifyCfg::Final),
722 &strip_debuginfo::StripDebugInfo,
724 ©_prop::CopyProp,
725 &dead_store_elimination::DeadStoreElimination::Final,
726 &nrvo::RenameReturnPlace,
727 &simplify::SimplifyLocals::Final,
728 &multiple_return_terminators::MultipleReturnTerminators,
729 &large_enums::EnumSizeOpt { discrepancy: 128 },
730 &add_call_guards::CriticalCallEdges,
732 &prettify::ReorderBasicBlocks,
734 &prettify::ReorderLocals,
735 &dump_mir::Marker("PreCodegen"),
737 ],
738 Some(MirPhase::Runtime(RuntimePhase::Optimized)),
739 optimizations,
740 );
741}
742
743fn optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> &Body<'_> {
745 tcx.arena.alloc(inner_optimized_mir(tcx, did))
746}
747
748fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> {
749 if tcx.is_constructor(did.to_def_id()) {
750 return shim::build_adt_ctor(tcx, did.to_def_id());
755 }
756
757 match tcx.hir_body_const_context(did) {
758 Some(hir::ConstContext::ConstFn) => tcx.ensure_done().mir_for_ctfe(did),
762 None => {}
763 Some(other) => panic!("do not use `optimized_mir` for constants: {other:?}"),
764 }
765 debug!("about to call mir_drops_elaborated...");
766 let body = tcx.mir_drops_elaborated_and_const_checked(did).steal();
767 let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::NotConst);
768
769 if body.tainted_by_errors.is_some() {
770 return body;
771 }
772
773 mentioned_items::MentionedItems.run_pass(tcx, &mut body);
777
778 if let TerminatorKind::Unreachable = body.basic_blocks[START_BLOCK].terminator().kind
782 && body.basic_blocks[START_BLOCK].statements.is_empty()
783 {
784 return body;
785 }
786
787 run_optimization_passes(tcx, &mut body);
788
789 body
790}
791
792fn promoted_mir(tcx: TyCtxt<'_>, def: LocalDefId) -> &IndexVec<Promoted, Body<'_>> {
795 if tcx.is_constructor(def.to_def_id()) {
796 return tcx.arena.alloc(IndexVec::new());
797 }
798
799 if !tcx.is_synthetic_mir(def) {
800 tcx.ensure_done().mir_borrowck(tcx.typeck_root_def_id(def.to_def_id()).expect_local());
801 }
802 let mut promoted = tcx.mir_promoted(def).1.steal();
803
804 for body in &mut promoted {
805 run_analysis_to_runtime_passes(tcx, body);
806 }
807
808 tcx.arena.alloc(promoted)
809}