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