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