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