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