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