]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/mod.rs
`try_update` -> `try_upgrade`
[rust.git] / src / librustc_mir / transform / mod.rs
1 use crate::{shim, util};
2 use required_consts::RequiredConstsVisitor;
3 use rustc_data_structures::fx::FxHashSet;
4 use rustc_hir as hir;
5 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
6 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
7 use rustc_index::vec::IndexVec;
8 use rustc_middle::mir::visit::Visitor as _;
9 use rustc_middle::mir::{traversal, Body, ConstQualifs, MirPhase, Promoted};
10 use rustc_middle::ty::query::Providers;
11 use rustc_middle::ty::steal::Steal;
12 use rustc_middle::ty::{self, InstanceDef, TyCtxt, TypeFoldable};
13 use rustc_span::{Span, Symbol};
14 use std::borrow::Cow;
15
16 pub mod add_call_guards;
17 pub mod add_moves_for_packed_drops;
18 pub mod add_retag;
19 pub mod check_consts;
20 pub mod check_packed_ref;
21 pub mod check_unsafety;
22 pub mod cleanup_post_borrowck;
23 pub mod const_prop;
24 pub mod copy_prop;
25 pub mod deaggregator;
26 pub mod dump_mir;
27 pub mod elaborate_drops;
28 pub mod generator;
29 pub mod inline;
30 pub mod instcombine;
31 pub mod instrument_coverage;
32 pub mod no_landing_pads;
33 pub mod nrvo;
34 pub mod promote_consts;
35 pub mod qualify_min_const_fn;
36 pub mod remove_noop_landing_pads;
37 pub mod required_consts;
38 pub mod rustc_peek;
39 pub mod simplify;
40 pub mod simplify_branches;
41 pub mod simplify_try;
42 pub mod uninhabited_enum_branching;
43 pub mod unreachable_prop;
44 pub mod validate;
45
46 pub(crate) fn provide(providers: &mut Providers) {
47     self::check_unsafety::provide(providers);
48     *providers = Providers {
49         mir_keys,
50         mir_const,
51         mir_const_qualif: |tcx, def_id| {
52             let def_id = def_id.expect_local();
53             if let Some(def) = ty::WithOptConstParam::try_fetch(def_id, tcx) {
54                 tcx.mir_const_qualif_const_arg(def)
55             } else {
56                 mir_const_qualif(tcx, ty::WithOptConstParam::unknown(def_id))
57             }
58         },
59         mir_const_qualif_const_arg: |tcx, (did, param_did)| {
60             mir_const_qualif(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
61         },
62         mir_validated,
63         mir_drops_elaborated_and_const_checked,
64         optimized_mir,
65         optimized_mir_of_const_arg,
66         is_mir_available,
67         promoted_mir: |tcx, def_id| {
68             let def_id = def_id.expect_local();
69             if let Some(def) = ty::WithOptConstParam::try_fetch(def_id, tcx) {
70                 tcx.promoted_mir_of_const_arg(def)
71             } else {
72                 promoted_mir(tcx, ty::WithOptConstParam::unknown(def_id))
73             }
74         },
75         promoted_mir_of_const_arg: |tcx, (did, param_did)| {
76             promoted_mir(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
77         },
78         ..*providers
79     };
80     instrument_coverage::provide(providers);
81 }
82
83 fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
84     tcx.mir_keys(def_id.krate).contains(&def_id.expect_local())
85 }
86
87 /// Finds the full set of `DefId`s within the current crate that have
88 /// MIR associated with them.
89 fn mir_keys(tcx: TyCtxt<'_>, krate: CrateNum) -> FxHashSet<LocalDefId> {
90     assert_eq!(krate, LOCAL_CRATE);
91
92     let mut set = FxHashSet::default();
93
94     // All body-owners have MIR associated with them.
95     set.extend(tcx.body_owners());
96
97     // Additionally, tuple struct/variant constructors have MIR, but
98     // they don't have a BodyId, so we need to build them separately.
99     struct GatherCtors<'a, 'tcx> {
100         tcx: TyCtxt<'tcx>,
101         set: &'a mut FxHashSet<LocalDefId>,
102     }
103     impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
104         fn visit_variant_data(
105             &mut self,
106             v: &'tcx hir::VariantData<'tcx>,
107             _: Symbol,
108             _: &'tcx hir::Generics<'tcx>,
109             _: hir::HirId,
110             _: Span,
111         ) {
112             if let hir::VariantData::Tuple(_, hir_id) = *v {
113                 self.set.insert(self.tcx.hir().local_def_id(hir_id));
114             }
115             intravisit::walk_struct_def(self, v)
116         }
117         type Map = intravisit::ErasedMap<'tcx>;
118         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
119             NestedVisitorMap::None
120         }
121     }
122     tcx.hir()
123         .krate()
124         .visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
125
126     set
127 }
128
129 /// Where a specific `mir::Body` comes from.
130 #[derive(Debug, Copy, Clone)]
131 pub struct MirSource<'tcx> {
132     pub instance: InstanceDef<'tcx>,
133
134     /// If `Some`, this is a promoted rvalue within the parent function.
135     pub promoted: Option<Promoted>,
136 }
137
138 impl<'tcx> MirSource<'tcx> {
139     pub fn item(def_id: DefId) -> Self {
140         MirSource {
141             instance: InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)),
142             promoted: None,
143         }
144     }
145
146     pub fn with_opt_param(self) -> ty::WithOptConstParam<DefId> {
147         self.instance.with_opt_param()
148     }
149
150     #[inline]
151     pub fn def_id(&self) -> DefId {
152         self.instance.def_id()
153     }
154 }
155
156 /// Generates a default name for the pass based on the name of the
157 /// type `T`.
158 pub fn default_name<T: ?Sized>() -> Cow<'static, str> {
159     let name = ::std::any::type_name::<T>();
160     if let Some(tail) = name.rfind(':') { Cow::from(&name[tail + 1..]) } else { Cow::from(name) }
161 }
162
163 /// A streamlined trait that you can implement to create a pass; the
164 /// pass will be named after the type, and it will consist of a main
165 /// loop that goes over each available MIR and applies `run_pass`.
166 pub trait MirPass<'tcx> {
167     fn name(&self) -> Cow<'_, str> {
168         default_name::<Self>()
169     }
170
171     fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>);
172 }
173
174 pub fn run_passes(
175     tcx: TyCtxt<'tcx>,
176     body: &mut Body<'tcx>,
177     instance: InstanceDef<'tcx>,
178     promoted: Option<Promoted>,
179     mir_phase: MirPhase,
180     passes: &[&[&dyn MirPass<'tcx>]],
181 ) {
182     let phase_index = mir_phase.phase_index();
183     let source = MirSource { instance, promoted };
184     let validate = tcx.sess.opts.debugging_opts.validate_mir;
185
186     if body.phase >= mir_phase {
187         return;
188     }
189
190     if validate {
191         validate::Validator { when: format!("input to phase {:?}", mir_phase) }
192             .run_pass(tcx, source, body);
193     }
194
195     let mut index = 0;
196     let mut run_pass = |pass: &dyn MirPass<'tcx>| {
197         let run_hooks = |body: &_, index, is_after| {
198             dump_mir::on_mir_pass(
199                 tcx,
200                 &format_args!("{:03}-{:03}", phase_index, index),
201                 &pass.name(),
202                 source,
203                 body,
204                 is_after,
205             );
206         };
207         run_hooks(body, index, false);
208         pass.run_pass(tcx, source, body);
209         run_hooks(body, index, true);
210
211         if validate {
212             validate::Validator { when: format!("after {} in phase {:?}", pass.name(), mir_phase) }
213                 .run_pass(tcx, source, body);
214         }
215
216         index += 1;
217     };
218
219     for pass_group in passes {
220         for pass in *pass_group {
221             run_pass(*pass);
222         }
223     }
224
225     body.phase = mir_phase;
226
227     if mir_phase == MirPhase::Optimized {
228         validate::Validator { when: format!("end of phase {:?}", mir_phase) }
229             .run_pass(tcx, source, body);
230     }
231 }
232
233 fn mir_const_qualif(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> ConstQualifs {
234     let const_kind = tcx.hir().body_const_context(def.did);
235
236     // No need to const-check a non-const `fn`.
237     if const_kind.is_none() {
238         return Default::default();
239     }
240
241     // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
242     // cannot yet be stolen), because `mir_validated()`, which steals
243     // from `mir_const(), forces this query to execute before
244     // performing the steal.
245     let body = &tcx.mir_const(def).borrow();
246
247     if body.return_ty().references_error() {
248         tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
249         return Default::default();
250     }
251
252     let ccx = check_consts::ConstCx {
253         body,
254         tcx,
255         def_id: def.did,
256         const_kind,
257         param_env: tcx.param_env(def.did),
258     };
259
260     let mut validator = check_consts::validation::Validator::new(&ccx);
261     validator.check_body();
262
263     // We return the qualifs in the return place for every MIR body, even though it is only used
264     // when deciding to promote a reference to a `const` for now.
265     validator.qualifs_in_return_place()
266 }
267
268 /// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
269 fn mir_const<'tcx>(
270     tcx: TyCtxt<'tcx>,
271     def: ty::WithOptConstParam<LocalDefId>,
272 ) -> &'tcx Steal<Body<'tcx>> {
273     if let Some(def) = def.try_upgrade(tcx) {
274         return tcx.mir_const(def);
275     }
276
277     // Unsafety check uses the raw mir, so make sure it is run.
278     if let Some(param_did) = def.const_param_did {
279         tcx.ensure().unsafety_check_result_for_const_arg((def.did, param_did));
280     } else {
281         tcx.ensure().unsafety_check_result(def.did);
282     }
283
284     let mut body = tcx.mir_built(def).steal();
285
286     util::dump_mir(
287         tcx,
288         None,
289         "mir_map",
290         &0,
291         MirSource { instance: InstanceDef::Item(def.to_global()), promoted: None },
292         &body,
293         |_, _| Ok(()),
294     );
295
296     run_passes(
297         tcx,
298         &mut body,
299         InstanceDef::Item(def.to_global()),
300         None,
301         MirPhase::Const,
302         &[&[
303             // MIR-level lints.
304             &check_packed_ref::CheckPackedRef,
305             // What we need to do constant evaluation.
306             &simplify::SimplifyCfg::new("initial"),
307             &rustc_peek::SanityCheck,
308         ]],
309     );
310     tcx.alloc_steal_mir(body)
311 }
312
313 fn mir_validated(
314     tcx: TyCtxt<'tcx>,
315     def: ty::WithOptConstParam<LocalDefId>,
316 ) -> (&'tcx Steal<Body<'tcx>>, &'tcx Steal<IndexVec<Promoted, Body<'tcx>>>) {
317     if let Some(def) = def.try_upgrade(tcx) {
318         return tcx.mir_validated(def);
319     }
320
321     // Ensure that we compute the `mir_const_qualif` for constants at
322     // this point, before we steal the mir-const result.
323     let _ = tcx.mir_const_qualif_opt_const_arg(def);
324
325     let mut body = tcx.mir_const(def).steal();
326
327     let mut required_consts = Vec::new();
328     let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
329     for (bb, bb_data) in traversal::reverse_postorder(&body) {
330         required_consts_visitor.visit_basic_block_data(bb, bb_data);
331     }
332     body.required_consts = required_consts;
333
334     let promote_pass = promote_consts::PromoteTemps::default();
335     run_passes(
336         tcx,
337         &mut body,
338         InstanceDef::Item(def.to_global()),
339         None,
340         MirPhase::Validated,
341         &[&[
342             // What we need to run borrowck etc.
343             &promote_pass,
344             &simplify::SimplifyCfg::new("qualify-consts"),
345             // If the `instrument-coverage` option is enabled, analyze the CFG, identify each
346             // conditional branch, construct a coverage map to be passed to LLVM, and inject counters
347             // where needed.
348             &instrument_coverage::InstrumentCoverage,
349         ]],
350     );
351
352     let promoted = promote_pass.promoted_fragments.into_inner();
353     (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
354 }
355
356 fn mir_drops_elaborated_and_const_checked<'tcx>(
357     tcx: TyCtxt<'tcx>,
358     def: ty::WithOptConstParam<LocalDefId>,
359 ) -> &'tcx Steal<Body<'tcx>> {
360     if let Some(def) = def.try_upgrade(tcx) {
361         return tcx.mir_drops_elaborated_and_const_checked(def);
362     }
363
364     // (Mir-)Borrowck uses `mir_validated`, so we have to force it to
365     // execute before we can steal.
366     if let Some(param_did) = def.const_param_did {
367         tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
368     } else {
369         tcx.ensure().mir_borrowck(def.did);
370     }
371
372     let (body, _) = tcx.mir_validated(def);
373     let mut body = body.steal();
374
375     run_post_borrowck_cleanup_passes(tcx, &mut body, def.did, None);
376     check_consts::post_drop_elaboration::check_live_drops(tcx, def.did, &body);
377     tcx.alloc_steal_mir(body)
378 }
379
380 /// After this series of passes, no lifetime analysis based on borrowing can be done.
381 fn run_post_borrowck_cleanup_passes<'tcx>(
382     tcx: TyCtxt<'tcx>,
383     body: &mut Body<'tcx>,
384     def_id: LocalDefId,
385     promoted: Option<Promoted>,
386 ) {
387     debug!("post_borrowck_cleanup({:?})", def_id);
388
389     let post_borrowck_cleanup: &[&dyn MirPass<'tcx>] = &[
390         // Remove all things only needed by analysis
391         &no_landing_pads::NoLandingPads::new(tcx),
392         &simplify_branches::SimplifyBranches::new("initial"),
393         &remove_noop_landing_pads::RemoveNoopLandingPads,
394         &cleanup_post_borrowck::CleanupNonCodegenStatements,
395         &simplify::SimplifyCfg::new("early-opt"),
396         // These next passes must be executed together
397         &add_call_guards::CriticalCallEdges,
398         &elaborate_drops::ElaborateDrops,
399         &no_landing_pads::NoLandingPads::new(tcx),
400         // AddMovesForPackedDrops needs to run after drop
401         // elaboration.
402         &add_moves_for_packed_drops::AddMovesForPackedDrops,
403         // `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late,
404         // but before optimizations begin.
405         &add_retag::AddRetag,
406         &simplify::SimplifyCfg::new("elaborate-drops"),
407     ];
408
409     run_passes(
410         tcx,
411         body,
412         InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id())),
413         promoted,
414         MirPhase::DropElab,
415         &[post_borrowck_cleanup],
416     );
417 }
418
419 fn run_optimization_passes<'tcx>(
420     tcx: TyCtxt<'tcx>,
421     body: &mut Body<'tcx>,
422     def_id: LocalDefId,
423     promoted: Option<Promoted>,
424 ) {
425     let optimizations: &[&dyn MirPass<'tcx>] = &[
426         &unreachable_prop::UnreachablePropagation,
427         &uninhabited_enum_branching::UninhabitedEnumBranching,
428         &simplify::SimplifyCfg::new("after-uninhabited-enum-branching"),
429         &inline::Inline,
430         // Lowering generator control-flow and variables has to happen before we do anything else
431         // to them. We do this inside the "optimizations" block so that it can benefit from
432         // optimizations that run before, that might be harder to do on the state machine than MIR
433         // with async primitives.
434         &generator::StateTransform,
435         &instcombine::InstCombine,
436         &const_prop::ConstProp,
437         &simplify_branches::SimplifyBranches::new("after-const-prop"),
438         // Run deaggregation here because:
439         //   1. Some codegen backends require it
440         //   2. It creates additional possibilities for some MIR optimizations to trigger
441         // FIXME(#70073): Why is this done here and not in `post_borrowck_cleanup`?
442         &deaggregator::Deaggregator,
443         &simplify_try::SimplifyArmIdentity,
444         &simplify_try::SimplifyBranchSame,
445         &copy_prop::CopyPropagation,
446         &simplify_branches::SimplifyBranches::new("after-copy-prop"),
447         &remove_noop_landing_pads::RemoveNoopLandingPads,
448         &simplify::SimplifyCfg::new("after-remove-noop-landing-pads"),
449         &simplify::SimplifyCfg::new("final"),
450         &nrvo::RenameReturnPlace,
451         &simplify::SimplifyLocals,
452     ];
453
454     let no_optimizations: &[&dyn MirPass<'tcx>] = &[
455         // Even if we don't do optimizations, we still have to lower generators for codegen.
456         &generator::StateTransform,
457         // FIXME(#70073): This pass is responsible for both optimization as well as some lints.
458         &const_prop::ConstProp,
459         // Even if we don't do optimizations, still run deaggregation because some backends assume
460         // that deaggregation always occurs.
461         &deaggregator::Deaggregator,
462     ];
463
464     let pre_codegen_cleanup: &[&dyn MirPass<'tcx>] = &[
465         &add_call_guards::CriticalCallEdges,
466         // Dump the end result for testing and debugging purposes.
467         &dump_mir::Marker("PreCodegen"),
468     ];
469
470     let mir_opt_level = tcx.sess.opts.debugging_opts.mir_opt_level;
471
472     #[rustfmt::skip]
473     run_passes(
474         tcx,
475         body,
476         InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id())),
477         promoted,
478         MirPhase::Optimized,
479         &[
480             if mir_opt_level > 0 { optimizations } else { no_optimizations },
481             pre_codegen_cleanup,
482         ],
483     );
484 }
485
486 fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx Body<'tcx> {
487     let did = did.expect_local();
488     if let Some(def) = ty::WithOptConstParam::try_fetch(did, tcx) {
489         tcx.optimized_mir_of_const_arg(def)
490     } else {
491         tcx.arena.alloc(inner_optimized_mir(tcx, ty::WithOptConstParam::unknown(did)))
492     }
493 }
494
495 fn optimized_mir_of_const_arg<'tcx>(
496     tcx: TyCtxt<'tcx>,
497     (did, param_did): (LocalDefId, DefId),
498 ) -> &'tcx Body<'tcx> {
499     tcx.arena.alloc(inner_optimized_mir(
500         tcx,
501         ty::WithOptConstParam { did, const_param_did: Some(param_did) },
502     ))
503 }
504
505 fn inner_optimized_mir(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
506     if tcx.is_constructor(def.did.to_def_id()) {
507         // There's no reason to run all of the MIR passes on constructors when
508         // we can just output the MIR we want directly. This also saves const
509         // qualification and borrow checking the trouble of special casing
510         // constructors.
511         return shim::build_adt_ctor(tcx, def.did.to_def_id());
512     }
513
514     let mut body = tcx.mir_drops_elaborated_and_const_checked(def).steal();
515     run_optimization_passes(tcx, &mut body, def.did, None);
516
517     debug_assert!(!body.has_free_regions(), "Free regions in optimized MIR");
518
519     body
520 }
521
522 fn promoted_mir<'tcx>(
523     tcx: TyCtxt<'tcx>,
524     def: ty::WithOptConstParam<LocalDefId>,
525 ) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
526     if tcx.is_constructor(def.did.to_def_id()) {
527         return tcx.arena.alloc(IndexVec::new());
528     }
529
530     if let Some(param_did) = def.const_param_did {
531         tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
532     } else {
533         tcx.ensure().mir_borrowck(def.did);
534     }
535     let (_, promoted) = tcx.mir_validated(def);
536     let mut promoted = promoted.steal();
537
538     for (p, mut body) in promoted.iter_enumerated_mut() {
539         run_post_borrowck_cleanup_passes(tcx, &mut body, def.did, Some(p));
540         run_optimization_passes(tcx, &mut body, def.did, Some(p));
541     }
542
543     debug_assert!(!promoted.has_free_regions(), "Free regions in promoted MIR");
544
545     tcx.arena.alloc(promoted)
546 }