]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/lib.rs
Rollup merge of #104462 - notriddle:notriddle/rightside-padding-right, r=GuillaumeGomez
[rust.git] / compiler / rustc_mir_transform / src / lib.rs
1 #![allow(rustc::potential_query_instability)]
2 #![feature(box_patterns)]
3 #![feature(drain_filter)]
4 #![feature(let_chains)]
5 #![feature(map_try_insert)]
6 #![feature(min_specialization)]
7 #![feature(never_type)]
8 #![feature(once_cell)]
9 #![feature(option_get_or_insert_default)]
10 #![feature(trusted_step)]
11 #![feature(try_blocks)]
12 #![feature(yeet_expr)]
13 #![feature(if_let_guard)]
14 #![recursion_limit = "256"]
15
16 #[macro_use]
17 extern crate tracing;
18 #[macro_use]
19 extern crate rustc_middle;
20
21 use required_consts::RequiredConstsVisitor;
22 use rustc_const_eval::util;
23 use rustc_data_structures::fx::FxIndexSet;
24 use rustc_data_structures::steal::Steal;
25 use rustc_hir as hir;
26 use rustc_hir::def_id::{DefId, LocalDefId};
27 use rustc_hir::intravisit::{self, Visitor};
28 use rustc_index::vec::IndexVec;
29 use rustc_middle::mir::visit::Visitor as _;
30 use rustc_middle::mir::{
31     traversal, AnalysisPhase, Body, ConstQualifs, Constant, LocalDecl, MirPass, MirPhase, Operand,
32     Place, ProjectionElem, Promoted, RuntimePhase, Rvalue, SourceInfo, Statement, StatementKind,
33     TerminatorKind,
34 };
35 use rustc_middle::ty::query::Providers;
36 use rustc_middle::ty::{self, TyCtxt, TypeVisitable};
37 use rustc_span::sym;
38
39 #[macro_use]
40 mod pass_manager;
41
42 use pass_manager::{self as pm, Lint, MirLint, WithMinOptLevel};
43
44 mod abort_unwinding_calls;
45 mod add_call_guards;
46 mod add_moves_for_packed_drops;
47 mod add_retag;
48 mod check_const_item_mutation;
49 mod check_packed_ref;
50 pub mod check_unsafety;
51 // This pass is public to allow external drivers to perform MIR cleanup
52 pub mod cleanup_post_borrowck;
53 mod const_debuginfo;
54 mod const_goto;
55 mod const_prop;
56 mod const_prop_lint;
57 mod coverage;
58 mod dataflow_const_prop;
59 mod dead_store_elimination;
60 mod deaggregator;
61 mod deduce_param_attrs;
62 mod deduplicate_blocks;
63 mod deref_separator;
64 mod dest_prop;
65 pub mod dump_mir;
66 mod early_otherwise_branch;
67 mod elaborate_box_derefs;
68 mod elaborate_drops;
69 mod ffi_unwind_calls;
70 mod function_item_references;
71 mod generator;
72 mod inline;
73 mod instcombine;
74 mod lower_intrinsics;
75 mod lower_slice_len;
76 mod match_branches;
77 mod multiple_return_terminators;
78 mod normalize_array_len;
79 mod nrvo;
80 // This pass is public to allow external drivers to perform MIR cleanup
81 pub mod remove_false_edges;
82 mod remove_noop_landing_pads;
83 mod remove_storage_markers;
84 mod remove_uninit_drops;
85 mod remove_unneeded_drops;
86 mod remove_zsts;
87 mod required_consts;
88 mod reveal_all;
89 mod separate_const_switch;
90 mod shim;
91 // This pass is public to allow external drivers to perform MIR cleanup
92 pub mod simplify;
93 mod simplify_branches;
94 mod simplify_comparison_integral;
95 mod simplify_try;
96 mod sroa;
97 mod uninhabited_enum_branching;
98 mod unreachable_prop;
99
100 use rustc_const_eval::transform::check_consts::{self, ConstCx};
101 use rustc_const_eval::transform::promote_consts;
102 use rustc_const_eval::transform::validate;
103 use rustc_mir_dataflow::rustc_peek;
104
105 pub fn provide(providers: &mut Providers) {
106     check_unsafety::provide(providers);
107     check_packed_ref::provide(providers);
108     coverage::query::provide(providers);
109     ffi_unwind_calls::provide(providers);
110     shim::provide(providers);
111     *providers = Providers {
112         mir_keys,
113         mir_const,
114         mir_const_qualif: |tcx, def_id| {
115             let def_id = def_id.expect_local();
116             if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
117                 tcx.mir_const_qualif_const_arg(def)
118             } else {
119                 mir_const_qualif(tcx, ty::WithOptConstParam::unknown(def_id))
120             }
121         },
122         mir_const_qualif_const_arg: |tcx, (did, param_did)| {
123             mir_const_qualif(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
124         },
125         mir_promoted,
126         mir_drops_elaborated_and_const_checked,
127         mir_for_ctfe,
128         mir_for_ctfe_of_const_arg,
129         optimized_mir,
130         is_mir_available,
131         is_ctfe_mir_available: |tcx, did| is_mir_available(tcx, did),
132         mir_callgraph_reachable: inline::cycle::mir_callgraph_reachable,
133         mir_inliner_callees: inline::cycle::mir_inliner_callees,
134         promoted_mir: |tcx, def_id| {
135             let def_id = def_id.expect_local();
136             if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
137                 tcx.promoted_mir_of_const_arg(def)
138             } else {
139                 promoted_mir(tcx, ty::WithOptConstParam::unknown(def_id))
140             }
141         },
142         promoted_mir_of_const_arg: |tcx, (did, param_did)| {
143             promoted_mir(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
144         },
145         deduced_param_attrs: deduce_param_attrs::deduced_param_attrs,
146         ..*providers
147     };
148 }
149
150 fn remap_mir_for_const_eval_select<'tcx>(
151     tcx: TyCtxt<'tcx>,
152     mut body: Body<'tcx>,
153     context: hir::Constness,
154 ) -> Body<'tcx> {
155     for bb in body.basic_blocks.as_mut().iter_mut() {
156         let terminator = bb.terminator.as_mut().expect("invalid terminator");
157         match terminator.kind {
158             TerminatorKind::Call {
159                 func: Operand::Constant(box Constant { ref literal, .. }),
160                 ref mut args,
161                 destination,
162                 target,
163                 cleanup,
164                 fn_span,
165                 ..
166             } if let ty::FnDef(def_id, _) = *literal.ty().kind()
167                 && tcx.item_name(def_id) == sym::const_eval_select
168                 && tcx.is_intrinsic(def_id) =>
169             {
170                 let [tupled_args, called_in_const, called_at_rt]: [_; 3] = std::mem::take(args).try_into().unwrap();
171                 let ty = tupled_args.ty(&body.local_decls, tcx);
172                 let fields = ty.tuple_fields();
173                 let num_args = fields.len();
174                 let func = if context == hir::Constness::Const { called_in_const } else { called_at_rt };
175                 let (method, place): (fn(Place<'tcx>) -> Operand<'tcx>, Place<'tcx>) = match tupled_args {
176                     Operand::Constant(_) => {
177                         // there is no good way of extracting a tuple arg from a constant (const generic stuff)
178                         // so we just create a temporary and deconstruct that.
179                         let local = body.local_decls.push(LocalDecl::new(ty, fn_span));
180                         bb.statements.push(Statement {
181                             source_info: SourceInfo::outermost(fn_span),
182                             kind: StatementKind::Assign(Box::new((local.into(), Rvalue::Use(tupled_args.clone())))),
183                         });
184                         (Operand::Move, local.into())
185                     }
186                     Operand::Move(place) => (Operand::Move, place),
187                     Operand::Copy(place) => (Operand::Copy, place),
188                 };
189                 let place_elems = place.projection;
190                 let arguments = (0..num_args).map(|x| {
191                     let mut place_elems = place_elems.to_vec();
192                     place_elems.push(ProjectionElem::Field(x.into(), fields[x]));
193                     let projection = tcx.intern_place_elems(&place_elems);
194                     let place = Place {
195                         local: place.local,
196                         projection,
197                     };
198                     method(place)
199                 }).collect();
200                 terminator.kind = TerminatorKind::Call { func, args: arguments, destination, target, cleanup, from_hir_call: false, fn_span };
201             }
202             _ => {}
203         }
204     }
205     body
206 }
207
208 fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
209     let def_id = def_id.expect_local();
210     tcx.mir_keys(()).contains(&def_id)
211 }
212
213 /// Finds the full set of `DefId`s within the current crate that have
214 /// MIR associated with them.
215 fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxIndexSet<LocalDefId> {
216     let mut set = FxIndexSet::default();
217
218     // All body-owners have MIR associated with them.
219     set.extend(tcx.hir().body_owners());
220
221     // Additionally, tuple struct/variant constructors have MIR, but
222     // they don't have a BodyId, so we need to build them separately.
223     struct GatherCtors<'a, 'tcx> {
224         tcx: TyCtxt<'tcx>,
225         set: &'a mut FxIndexSet<LocalDefId>,
226     }
227     impl<'tcx> Visitor<'tcx> for GatherCtors<'_, 'tcx> {
228         fn visit_variant_data(&mut self, v: &'tcx hir::VariantData<'tcx>) {
229             if let hir::VariantData::Tuple(_, hir_id) = *v {
230                 self.set.insert(self.tcx.hir().local_def_id(hir_id));
231             }
232             intravisit::walk_struct_def(self, v)
233         }
234     }
235     tcx.hir().visit_all_item_likes_in_crate(&mut GatherCtors { tcx, set: &mut set });
236
237     set
238 }
239
240 fn mir_const_qualif(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> ConstQualifs {
241     let const_kind = tcx.hir().body_const_context(def.did);
242
243     // No need to const-check a non-const `fn`.
244     if const_kind.is_none() {
245         return Default::default();
246     }
247
248     // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
249     // cannot yet be stolen), because `mir_promoted()`, which steals
250     // from `mir_const(), forces this query to execute before
251     // performing the steal.
252     let body = &tcx.mir_const(def).borrow();
253
254     if body.return_ty().references_error() {
255         tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
256         return Default::default();
257     }
258
259     let ccx = check_consts::ConstCx { body, tcx, const_kind, param_env: tcx.param_env(def.did) };
260
261     let mut validator = check_consts::check::Checker::new(&ccx);
262     validator.check_body();
263
264     // We return the qualifs in the return place for every MIR body, even though it is only used
265     // when deciding to promote a reference to a `const` for now.
266     validator.qualifs_in_return_place()
267 }
268
269 /// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
270 /// FIXME(oli-obk): it's unclear whether we still need this phase (and its corresponding query).
271 /// We used to have this for pre-miri MIR based const eval.
272 fn mir_const<'tcx>(
273     tcx: TyCtxt<'tcx>,
274     def: ty::WithOptConstParam<LocalDefId>,
275 ) -> &'tcx Steal<Body<'tcx>> {
276     if let Some(def) = def.try_upgrade(tcx) {
277         return tcx.mir_const(def);
278     }
279
280     // Unsafety check uses the raw mir, so make sure it is run.
281     if !tcx.sess.opts.unstable_opts.thir_unsafeck {
282         if let Some(param_did) = def.const_param_did {
283             tcx.ensure().unsafety_check_result_for_const_arg((def.did, param_did));
284         } else {
285             tcx.ensure().unsafety_check_result(def.did);
286         }
287     }
288
289     // has_ffi_unwind_calls query uses the raw mir, so make sure it is run.
290     tcx.ensure().has_ffi_unwind_calls(def.did);
291
292     let mut body = tcx.mir_built(def).steal();
293
294     pass_manager::dump_mir_for_phase_change(tcx, &body);
295
296     pm::run_passes(
297         tcx,
298         &mut body,
299         &[
300             // MIR-level lints.
301             &Lint(check_packed_ref::CheckPackedRef),
302             &Lint(check_const_item_mutation::CheckConstItemMutation),
303             &Lint(function_item_references::FunctionItemReferences),
304             // What we need to do constant evaluation.
305             &simplify::SimplifyCfg::new("initial"),
306             &rustc_peek::SanityCheck, // Just a lint
307         ],
308         None,
309     );
310     tcx.alloc_steal_mir(body)
311 }
312
313 /// Compute the main MIR body and the list of MIR bodies of the promoteds.
314 fn mir_promoted<'tcx>(
315     tcx: TyCtxt<'tcx>,
316     def: ty::WithOptConstParam<LocalDefId>,
317 ) -> (&'tcx Steal<Body<'tcx>>, &'tcx Steal<IndexVec<Promoted, Body<'tcx>>>) {
318     if let Some(def) = def.try_upgrade(tcx) {
319         return tcx.mir_promoted(def);
320     }
321
322     // Ensure that we compute the `mir_const_qualif` for constants at
323     // this point, before we steal the mir-const result.
324     // Also this means promotion can rely on all const checks having been done.
325     let const_qualifs = tcx.mir_const_qualif_opt_const_arg(def);
326     let mut body = tcx.mir_const(def).steal();
327     if let Some(error_reported) = const_qualifs.tainted_by_errors {
328         body.tainted_by_errors = Some(error_reported);
329     }
330
331     let mut required_consts = Vec::new();
332     let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
333     for (bb, bb_data) in traversal::reverse_postorder(&body) {
334         required_consts_visitor.visit_basic_block_data(bb, bb_data);
335     }
336     body.required_consts = required_consts;
337
338     // What we need to run borrowck etc.
339     let promote_pass = promote_consts::PromoteTemps::default();
340     pm::run_passes(
341         tcx,
342         &mut body,
343         &[
344             &promote_pass,
345             &simplify::SimplifyCfg::new("promote-consts"),
346             &coverage::InstrumentCoverage,
347         ],
348         Some(MirPhase::Analysis(AnalysisPhase::Initial)),
349     );
350
351     let promoted = promote_pass.promoted_fragments.into_inner();
352     (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
353 }
354
355 /// Compute the MIR that is used during CTFE (and thus has no optimizations run on it)
356 fn mir_for_ctfe<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Body<'tcx> {
357     let did = def_id.expect_local();
358     if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
359         tcx.mir_for_ctfe_of_const_arg(def)
360     } else {
361         tcx.arena.alloc(inner_mir_for_ctfe(tcx, ty::WithOptConstParam::unknown(did)))
362     }
363 }
364
365 /// Same as `mir_for_ctfe`, but used to get the MIR of a const generic parameter.
366 /// The docs on `WithOptConstParam` explain this a bit more, but the TLDR is that
367 /// we'd get cycle errors with `mir_for_ctfe`, because typeck would need to typeck
368 /// the const parameter while type checking the main body, which in turn would try
369 /// to type check the main body again.
370 fn mir_for_ctfe_of_const_arg<'tcx>(
371     tcx: TyCtxt<'tcx>,
372     (did, param_did): (LocalDefId, DefId),
373 ) -> &'tcx Body<'tcx> {
374     tcx.arena.alloc(inner_mir_for_ctfe(
375         tcx,
376         ty::WithOptConstParam { did, const_param_did: Some(param_did) },
377     ))
378 }
379
380 fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
381     // FIXME: don't duplicate this between the optimized_mir/mir_for_ctfe queries
382     if tcx.is_constructor(def.did.to_def_id()) {
383         // There's no reason to run all of the MIR passes on constructors when
384         // we can just output the MIR we want directly. This also saves const
385         // qualification and borrow checking the trouble of special casing
386         // constructors.
387         return shim::build_adt_ctor(tcx, def.did.to_def_id());
388     }
389
390     let context = tcx
391         .hir()
392         .body_const_context(def.did)
393         .expect("mir_for_ctfe should not be used for runtime functions");
394
395     let body = tcx.mir_drops_elaborated_and_const_checked(def).borrow().clone();
396
397     let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::Const);
398
399     match context {
400         // Do not const prop functions, either they get executed at runtime or exported to metadata,
401         // so we run const prop on them, or they don't, in which case we const evaluate some control
402         // flow paths of the function and any errors in those paths will get emitted as const eval
403         // errors.
404         hir::ConstContext::ConstFn => {}
405         // Static items always get evaluated, so we can just let const eval see if any erroneous
406         // control flow paths get executed.
407         hir::ConstContext::Static(_) => {}
408         // Associated constants get const prop run so we detect common failure situations in the
409         // crate that defined the constant.
410         // Technically we want to not run on regular const items, but oli-obk doesn't know how to
411         // conveniently detect that at this point without looking at the HIR.
412         hir::ConstContext::Const => {
413             pm::run_passes(
414                 tcx,
415                 &mut body,
416                 &[&const_prop::ConstProp],
417                 Some(MirPhase::Runtime(RuntimePhase::Optimized)),
418             );
419         }
420     }
421
422     debug_assert!(!body.has_free_regions(), "Free regions in MIR for CTFE");
423
424     body
425 }
426
427 /// Obtain just the main MIR (no promoteds) and run some cleanups on it. This also runs
428 /// mir borrowck *before* doing so in order to ensure that borrowck can be run and doesn't
429 /// end up missing the source MIR due to stealing happening.
430 fn mir_drops_elaborated_and_const_checked<'tcx>(
431     tcx: TyCtxt<'tcx>,
432     def: ty::WithOptConstParam<LocalDefId>,
433 ) -> &'tcx Steal<Body<'tcx>> {
434     if let Some(def) = def.try_upgrade(tcx) {
435         return tcx.mir_drops_elaborated_and_const_checked(def);
436     }
437
438     let mir_borrowck = tcx.mir_borrowck_opt_const_arg(def);
439
440     let is_fn_like = tcx.def_kind(def.did).is_fn_like();
441     if is_fn_like {
442         let did = def.did.to_def_id();
443         let def = ty::WithOptConstParam::unknown(did);
444
445         // Do not compute the mir call graph without said call graph actually being used.
446         if inline::Inline.is_enabled(&tcx.sess) {
447             let _ = tcx.mir_inliner_callees(ty::InstanceDef::Item(def));
448         }
449     }
450
451     let (body, _) = tcx.mir_promoted(def);
452     let mut body = body.steal();
453     if let Some(error_reported) = mir_borrowck.tainted_by_errors {
454         body.tainted_by_errors = Some(error_reported);
455     }
456
457     run_analysis_to_runtime_passes(tcx, &mut body);
458
459     tcx.alloc_steal_mir(body)
460 }
461
462 fn run_analysis_to_runtime_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
463     assert!(body.phase == MirPhase::Analysis(AnalysisPhase::Initial));
464     let did = body.source.def_id();
465
466     debug!("analysis_mir_cleanup({:?})", did);
467     run_analysis_cleanup_passes(tcx, body);
468     assert!(body.phase == MirPhase::Analysis(AnalysisPhase::PostCleanup));
469
470     // Do a little drop elaboration before const-checking if `const_precise_live_drops` is enabled.
471     if check_consts::post_drop_elaboration::checking_enabled(&ConstCx::new(tcx, &body)) {
472         pm::run_passes(
473             tcx,
474             body,
475             &[
476                 &remove_uninit_drops::RemoveUninitDrops,
477                 &simplify::SimplifyCfg::new("remove-false-edges"),
478             ],
479             None,
480         );
481         check_consts::post_drop_elaboration::check_live_drops(tcx, &body); // FIXME: make this a MIR lint
482     }
483
484     debug!("runtime_mir_lowering({:?})", did);
485     run_runtime_lowering_passes(tcx, body);
486     assert!(body.phase == MirPhase::Runtime(RuntimePhase::Initial));
487
488     debug!("runtime_mir_cleanup({:?})", did);
489     run_runtime_cleanup_passes(tcx, body);
490     assert!(body.phase == MirPhase::Runtime(RuntimePhase::PostCleanup));
491 }
492
493 // FIXME(JakobDegen): Can we make these lists of passes consts?
494
495 /// After this series of passes, no lifetime analysis based on borrowing can be done.
496 fn run_analysis_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
497     let passes: &[&dyn MirPass<'tcx>] = &[
498         &remove_false_edges::RemoveFalseEdges,
499         &simplify_branches::SimplifyConstCondition::new("initial"),
500         &remove_noop_landing_pads::RemoveNoopLandingPads,
501         &cleanup_post_borrowck::CleanupNonCodegenStatements,
502         &simplify::SimplifyCfg::new("early-opt"),
503         &deref_separator::Derefer,
504     ];
505
506     pm::run_passes(tcx, body, passes, Some(MirPhase::Analysis(AnalysisPhase::PostCleanup)));
507 }
508
509 /// Returns the sequence of passes that lowers analysis to runtime MIR.
510 fn run_runtime_lowering_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
511     let passes: &[&dyn MirPass<'tcx>] = &[
512         // These next passes must be executed together
513         &add_call_guards::CriticalCallEdges,
514         &elaborate_drops::ElaborateDrops,
515         // This will remove extraneous landing pads which are no longer
516         // necessary as well as well as forcing any call in a non-unwinding
517         // function calling a possibly-unwinding function to abort the process.
518         &abort_unwinding_calls::AbortUnwindingCalls,
519         // AddMovesForPackedDrops needs to run after drop
520         // elaboration.
521         &add_moves_for_packed_drops::AddMovesForPackedDrops,
522         // `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late,
523         // but before optimizations begin.
524         &elaborate_box_derefs::ElaborateBoxDerefs,
525         &generator::StateTransform,
526         &add_retag::AddRetag,
527         // Deaggregator is necessary for const prop. We may want to consider implementing
528         // CTFE support for aggregates.
529         &deaggregator::Deaggregator,
530         &Lint(const_prop_lint::ConstProp),
531     ];
532     pm::run_passes_no_validate(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::Initial)));
533 }
534
535 /// Returns the sequence of passes that do the initial cleanup of runtime MIR.
536 fn run_runtime_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
537     let passes: &[&dyn MirPass<'tcx>] = &[
538         &elaborate_box_derefs::ElaborateBoxDerefs,
539         &lower_intrinsics::LowerIntrinsics,
540         &simplify::SimplifyCfg::new("elaborate-drops"),
541     ];
542
543     pm::run_passes(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::PostCleanup)));
544 }
545
546 fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
547     fn o1<T>(x: T) -> WithMinOptLevel<T> {
548         WithMinOptLevel(1, x)
549     }
550
551     // The main optimizations that we do on MIR.
552     pm::run_passes(
553         tcx,
554         body,
555         &[
556             &reveal_all::RevealAll, // has to be done before inlining, since inlined code is in RevealAll mode.
557             &lower_slice_len::LowerSliceLenCalls, // has to be done before inlining, otherwise actual call will be almost always inlined. Also simple, so can just do first
558             &normalize_array_len::NormalizeArrayLen, // has to run after `slice::len` lowering
559             &unreachable_prop::UnreachablePropagation,
560             &uninhabited_enum_branching::UninhabitedEnumBranching,
561             &o1(simplify::SimplifyCfg::new("after-uninhabited-enum-branching")),
562             &inline::Inline,
563             &remove_storage_markers::RemoveStorageMarkers,
564             &remove_zsts::RemoveZsts,
565             &const_goto::ConstGoto,
566             &remove_unneeded_drops::RemoveUnneededDrops,
567             &sroa::ScalarReplacementOfAggregates,
568             &match_branches::MatchBranchSimplification,
569             // inst combine is after MatchBranchSimplification to clean up Ne(_1, false)
570             &multiple_return_terminators::MultipleReturnTerminators,
571             &instcombine::InstCombine,
572             &separate_const_switch::SeparateConstSwitch,
573             //
574             // FIXME(#70073): This pass is responsible for both optimization as well as some lints.
575             &const_prop::ConstProp,
576             &dataflow_const_prop::DataflowConstProp,
577             //
578             // Const-prop runs unconditionally, but doesn't mutate the MIR at mir-opt-level=0.
579             &const_debuginfo::ConstDebugInfo,
580             &o1(simplify_branches::SimplifyConstCondition::new("after-const-prop")),
581             &early_otherwise_branch::EarlyOtherwiseBranch,
582             &simplify_comparison_integral::SimplifyComparisonIntegral,
583             &simplify_try::SimplifyArmIdentity,
584             &simplify_try::SimplifyBranchSame,
585             &dead_store_elimination::DeadStoreElimination,
586             &dest_prop::DestinationPropagation,
587             &o1(simplify_branches::SimplifyConstCondition::new("final")),
588             &o1(remove_noop_landing_pads::RemoveNoopLandingPads),
589             &o1(simplify::SimplifyCfg::new("final")),
590             &nrvo::RenameReturnPlace,
591             &simplify::SimplifyLocals,
592             &multiple_return_terminators::MultipleReturnTerminators,
593             &deduplicate_blocks::DeduplicateBlocks,
594             // Some cleanup necessary at least for LLVM and potentially other codegen backends.
595             &add_call_guards::CriticalCallEdges,
596             // Dump the end result for testing and debugging purposes.
597             &dump_mir::Marker("PreCodegen"),
598         ],
599         Some(MirPhase::Runtime(RuntimePhase::Optimized)),
600     );
601 }
602
603 /// Optimize the MIR and prepare it for codegen.
604 fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx Body<'tcx> {
605     let did = did.expect_local();
606     assert_eq!(ty::WithOptConstParam::try_lookup(did, tcx), None);
607     tcx.arena.alloc(inner_optimized_mir(tcx, did))
608 }
609
610 fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> {
611     if tcx.is_constructor(did.to_def_id()) {
612         // There's no reason to run all of the MIR passes on constructors when
613         // we can just output the MIR we want directly. This also saves const
614         // qualification and borrow checking the trouble of special casing
615         // constructors.
616         return shim::build_adt_ctor(tcx, did.to_def_id());
617     }
618
619     match tcx.hir().body_const_context(did) {
620         // Run the `mir_for_ctfe` query, which depends on `mir_drops_elaborated_and_const_checked`
621         // which we are going to steal below. Thus we need to run `mir_for_ctfe` first, so it
622         // computes and caches its result.
623         Some(hir::ConstContext::ConstFn) => tcx.ensure().mir_for_ctfe(did),
624         None => {}
625         Some(other) => panic!("do not use `optimized_mir` for constants: {:?}", other),
626     }
627     debug!("about to call mir_drops_elaborated...");
628     let body =
629         tcx.mir_drops_elaborated_and_const_checked(ty::WithOptConstParam::unknown(did)).steal();
630     let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::NotConst);
631     debug!("body: {:#?}", body);
632     run_optimization_passes(tcx, &mut body);
633
634     debug_assert!(!body.has_free_regions(), "Free regions in optimized MIR");
635
636     body
637 }
638
639 /// Fetch all the promoteds of an item and prepare their MIR bodies to be ready for
640 /// constant evaluation once all substitutions become known.
641 fn promoted_mir<'tcx>(
642     tcx: TyCtxt<'tcx>,
643     def: ty::WithOptConstParam<LocalDefId>,
644 ) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
645     if tcx.is_constructor(def.did.to_def_id()) {
646         return tcx.arena.alloc(IndexVec::new());
647     }
648
649     let tainted_by_errors = tcx.mir_borrowck_opt_const_arg(def).tainted_by_errors;
650     let mut promoted = tcx.mir_promoted(def).1.steal();
651
652     for body in &mut promoted {
653         if let Some(error_reported) = tainted_by_errors {
654             body.tainted_by_errors = Some(error_reported);
655         }
656         run_analysis_to_runtime_passes(tcx, body);
657     }
658
659     debug_assert!(!promoted.has_free_regions(), "Free regions in promoted MIR");
660
661     tcx.arena.alloc(promoted)
662 }