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(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 || tcx.is_const_default_method(def.to_def_id()) =>
434 {
435 tcx.mir_const_qualif(def)
436 }
437 DefKind::AssocConst
438 | DefKind::Const
439 | DefKind::Static { .. }
440 | DefKind::InlineConst
441 | DefKind::AnonConst => tcx.mir_const_qualif(def),
442 _ => ConstQualifs::default(),
443 };
444
445 tcx.ensure_done().has_ffi_unwind_calls(def);
447
448 if tcx.needs_coroutine_by_move_body_def_id(def.to_def_id()) {
450 tcx.ensure_done().coroutine_by_move_body_def_id(def);
451 }
452
453 tcx.ensure_done().trivial_const(def);
455
456 let mut body = tcx.mir_built(def).steal();
457 if let Some(error_reported) = const_qualifs.tainted_by_errors {
458 body.tainted_by_errors = Some(error_reported);
459 }
460
461 RequiredConstsVisitor::compute_required_consts(&mut body);
464
465 let promote_pass = promote_consts::PromoteTemps::default();
467 pm::run_passes(
468 tcx,
469 &mut body,
470 &[&promote_pass, &simplify::SimplifyCfg::PromoteConsts, &coverage::InstrumentCoverage],
471 Some(MirPhase::Analysis(AnalysisPhase::Initial)),
472 pm::Optimizations::Allowed,
473 );
474
475 lint_tail_expr_drop_order::run_lint(tcx, def, &body);
476
477 let promoted = promote_pass.promoted_fragments.into_inner();
478 (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
479}
480
481fn mir_for_ctfe(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &Body<'_> {
483 debug_assert!(!tcx.is_trivial_const(def_id), "Tried to get mir_for_ctfe of a trivial const");
484 tcx.arena.alloc(inner_mir_for_ctfe(tcx, def_id))
485}
486
487fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: LocalDefId) -> Body<'_> {
488 if tcx.is_constructor(def.to_def_id()) {
490 return shim::build_adt_ctor(tcx, def.to_def_id());
495 }
496
497 let body = tcx.mir_drops_elaborated_and_const_checked(def);
498 let body = match tcx.hir_body_const_context(def) {
499 Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => body.steal(),
502 Some(hir::ConstContext::ConstFn) => body.borrow().clone(),
503 None => bug!("`mir_for_ctfe` called on non-const {def:?}"),
504 };
505
506 let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::Const);
507 pm::run_passes(tcx, &mut body, &[&ctfe_limit::CtfeLimit], None, pm::Optimizations::Allowed);
508
509 body
510}
511
512fn mir_drops_elaborated_and_const_checked(tcx: TyCtxt<'_>, def: LocalDefId) -> &Steal<Body<'_>> {
516 if tcx.is_coroutine(def.to_def_id()) {
517 tcx.ensure_done().mir_coroutine_witnesses(def);
518 }
519
520 let tainted_by_errors = if !tcx.is_synthetic_mir(def) {
522 tcx.mir_borrowck(tcx.typeck_root_def_id(def.to_def_id()).expect_local()).err()
523 } else {
524 None
525 };
526
527 let is_fn_like = tcx.def_kind(def).is_fn_like();
528 if is_fn_like {
529 if pm::should_run_pass(tcx, &inline::Inline, pm::Optimizations::Allowed)
531 || inline::ForceInline::should_run_pass_for_callee(tcx, def.to_def_id())
532 {
533 tcx.ensure_done().mir_inliner_callees(ty::InstanceKind::Item(def.to_def_id()));
534 }
535 }
536
537 tcx.ensure_done().check_liveness(def);
538
539 let (body, _) = tcx.mir_promoted(def);
540 let mut body = body.steal();
541
542 if let Some(error_reported) = tainted_by_errors {
543 body.tainted_by_errors = Some(error_reported);
544 }
545
546 let root = tcx.typeck_root_def_id(def.to_def_id());
551 match tcx.def_kind(root) {
552 DefKind::Fn
553 | DefKind::AssocFn
554 | DefKind::Static { .. }
555 | DefKind::Const
556 | DefKind::AssocConst => {
557 if let Err(guar) = tcx.ensure_ok().check_well_formed(root.expect_local()) {
558 body.tainted_by_errors = Some(guar);
559 }
560 }
561 _ => {}
562 }
563
564 run_analysis_to_runtime_passes(tcx, &mut body);
565
566 tcx.alloc_steal_mir(body)
567}
568
569pub fn run_analysis_to_runtime_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
572 assert!(body.phase == MirPhase::Analysis(AnalysisPhase::Initial));
573 let did = body.source.def_id();
574
575 debug!("analysis_mir_cleanup({:?})", did);
576 run_analysis_cleanup_passes(tcx, body);
577 assert!(body.phase == MirPhase::Analysis(AnalysisPhase::PostCleanup));
578
579 if check_consts::post_drop_elaboration::checking_enabled(&ConstCx::new(tcx, body)) {
581 pm::run_passes(
582 tcx,
583 body,
584 &[
585 &remove_uninit_drops::RemoveUninitDrops,
586 &simplify::SimplifyCfg::RemoveFalseEdges,
587 &Lint(post_drop_elaboration::CheckLiveDrops),
588 ],
589 None,
590 pm::Optimizations::Allowed,
591 );
592 }
593
594 debug!("runtime_mir_lowering({:?})", did);
595 run_runtime_lowering_passes(tcx, body);
596 assert!(body.phase == MirPhase::Runtime(RuntimePhase::Initial));
597
598 debug!("runtime_mir_cleanup({:?})", did);
599 run_runtime_cleanup_passes(tcx, body);
600 assert!(body.phase == MirPhase::Runtime(RuntimePhase::PostCleanup));
601}
602
603fn run_analysis_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
607 let passes: &[&dyn MirPass<'tcx>] = &[
608 &impossible_predicates::ImpossiblePredicates,
609 &cleanup_post_borrowck::CleanupPostBorrowck,
610 &remove_noop_landing_pads::RemoveNoopLandingPads,
611 &simplify::SimplifyCfg::PostAnalysis,
612 &deref_separator::Derefer,
613 ];
614
615 pm::run_passes(
616 tcx,
617 body,
618 passes,
619 Some(MirPhase::Analysis(AnalysisPhase::PostCleanup)),
620 pm::Optimizations::Allowed,
621 );
622}
623
624fn run_runtime_lowering_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
626 let passes: &[&dyn MirPass<'tcx>] = &[
627 &add_call_guards::CriticalCallEdges,
629 &post_analysis_normalize::PostAnalysisNormalize,
631 &add_subtyping_projections::Subtyper,
633 &elaborate_drops::ElaborateDrops,
634 &Lint(check_call_recursion::CheckDropRecursion),
636 &abort_unwinding_calls::AbortUnwindingCalls,
640 &add_moves_for_packed_drops::AddMovesForPackedDrops,
643 &add_retag::AddRetag,
646 &erase_deref_temps::EraseDerefTemps,
647 &elaborate_box_derefs::ElaborateBoxDerefs,
648 &coroutine::StateTransform,
649 &Lint(known_panics_lint::KnownPanicsLint),
650 ];
651 pm::run_passes_no_validate(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::Initial)));
652}
653
654fn run_runtime_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
656 let passes: &[&dyn MirPass<'tcx>] = &[
657 &lower_intrinsics::LowerIntrinsics,
658 &remove_place_mention::RemovePlaceMention,
659 &simplify::SimplifyCfg::PreOptimizations,
660 ];
661
662 pm::run_passes(
663 tcx,
664 body,
665 passes,
666 Some(MirPhase::Runtime(RuntimePhase::PostCleanup)),
667 pm::Optimizations::Allowed,
668 );
669
670 for decl in &mut body.local_decls {
673 decl.local_info = ClearCrossCrate::Clear;
674 }
675}
676
677pub(crate) fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
678 fn o1<T>(x: T) -> WithMinOptLevel<T> {
679 WithMinOptLevel(1, x)
680 }
681
682 let def_id = body.source.def_id();
683 let optimizations = if tcx.def_kind(def_id).has_codegen_attrs()
684 && tcx.codegen_fn_attrs(def_id).optimize.do_not_optimize()
685 {
686 pm::Optimizations::Suppressed
687 } else {
688 pm::Optimizations::Allowed
689 };
690
691 pm::run_passes(
693 tcx,
694 body,
695 &[
696 &check_alignment::CheckAlignment,
698 &check_null::CheckNull,
699 &check_enums::CheckEnums,
700 &lower_slice_len::LowerSliceLenCalls,
705 &instsimplify::InstSimplify::BeforeInline,
708 &inline::ForceInline,
710 &inline::Inline,
712 &remove_storage_markers::RemoveStorageMarkers,
717 &remove_zsts::RemoveZsts,
719 &remove_unneeded_drops::RemoveUnneededDrops,
720 &unreachable_enum_branching::UnreachableEnumBranching,
723 &unreachable_prop::UnreachablePropagation,
724 &o1(simplify::SimplifyCfg::AfterUnreachableEnumBranching),
725 &multiple_return_terminators::MultipleReturnTerminators,
726 &instsimplify::InstSimplify::AfterSimplifyCfg,
730 &o1(simplify_branches::SimplifyConstCondition::AfterInstSimplify),
739 &ref_prop::ReferencePropagation,
740 &sroa::ScalarReplacementOfAggregates,
741 &simplify::SimplifyLocals::BeforeConstProp,
742 &dead_store_elimination::DeadStoreElimination::Initial,
743 &gvn::GVN,
744 &simplify::SimplifyLocals::AfterGVN,
745 &match_branches::MatchBranchSimplification,
746 &dataflow_const_prop::DataflowConstProp,
747 &single_use_consts::SingleUseConsts,
748 &o1(simplify_branches::SimplifyConstCondition::AfterConstProp),
749 &jump_threading::JumpThreading,
750 &early_otherwise_branch::EarlyOtherwiseBranch,
751 &simplify_comparison_integral::SimplifyComparisonIntegral,
752 &o1(simplify_branches::SimplifyConstCondition::Final),
753 &o1(remove_noop_landing_pads::RemoveNoopLandingPads),
754 &o1(simplify::SimplifyCfg::Final),
755 &strip_debuginfo::StripDebugInfo,
757 ©_prop::CopyProp,
758 &dead_store_elimination::DeadStoreElimination::Final,
759 &dest_prop::DestinationPropagation,
760 &simplify::SimplifyLocals::Final,
761 &multiple_return_terminators::MultipleReturnTerminators,
762 &large_enums::EnumSizeOpt { discrepancy: 128 },
763 &add_call_guards::CriticalCallEdges,
765 &prettify::ReorderBasicBlocks,
767 &prettify::ReorderLocals,
768 &dump_mir::Marker("PreCodegen"),
770 ],
771 Some(MirPhase::Runtime(RuntimePhase::Optimized)),
772 optimizations,
773 );
774}
775
776fn optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> &Body<'_> {
778 tcx.arena.alloc(inner_optimized_mir(tcx, did))
779}
780
781fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> {
782 if tcx.is_constructor(did.to_def_id()) {
783 return shim::build_adt_ctor(tcx, did.to_def_id());
788 }
789
790 match tcx.hir_body_const_context(did) {
791 Some(hir::ConstContext::ConstFn) => tcx.ensure_done().mir_for_ctfe(did),
795 None => {}
796 Some(other) => panic!("do not use `optimized_mir` for constants: {other:?}"),
797 }
798 debug!("about to call mir_drops_elaborated...");
799 let body = tcx.mir_drops_elaborated_and_const_checked(did).steal();
800 let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::NotConst);
801
802 if body.tainted_by_errors.is_some() {
803 return body;
804 }
805
806 mentioned_items::MentionedItems.run_pass(tcx, &mut body);
810
811 if let TerminatorKind::Unreachable = body.basic_blocks[START_BLOCK].terminator().kind
815 && body.basic_blocks[START_BLOCK].statements.is_empty()
816 {
817 return body;
818 }
819
820 run_optimization_passes(tcx, &mut body);
821
822 body
823}
824
825fn promoted_mir(tcx: TyCtxt<'_>, def: LocalDefId) -> &IndexVec<Promoted, Body<'_>> {
828 if tcx.is_constructor(def.to_def_id()) {
829 return tcx.arena.alloc(IndexVec::new());
830 }
831
832 if !tcx.is_synthetic_mir(def) {
833 tcx.ensure_done().mir_borrowck(tcx.typeck_root_def_id(def.to_def_id()).expect_local());
834 }
835 let mut promoted = tcx.mir_promoted(def).1.steal();
836
837 for body in &mut promoted {
838 run_analysis_to_runtime_passes(tcx, body);
839 }
840
841 tcx.arena.alloc(promoted)
842}