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