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