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