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