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