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