1 use crate::{shim, util};
2 use required_consts::RequiredConstsVisitor;
3 use rustc_data_structures::fx::FxHashSet;
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};
16 pub mod add_call_guards;
17 pub mod add_moves_for_packed_drops;
20 pub mod check_packed_ref;
21 pub mod check_unsafety;
22 pub mod cleanup_post_borrowck;
27 pub mod elaborate_drops;
31 pub mod instrument_coverage;
32 pub mod match_branches;
33 pub mod no_landing_pads;
35 pub mod promote_consts;
36 pub mod qualify_min_const_fn;
37 pub mod remove_noop_landing_pads;
38 pub mod required_consts;
41 pub mod simplify_branches;
43 pub mod uninhabited_enum_branching;
44 pub mod unreachable_prop;
47 pub(crate) fn provide(providers: &mut Providers) {
48 self::check_unsafety::provide(providers);
49 *providers = Providers {
52 mir_const_qualif: |tcx, def_id| {
53 let def_id = def_id.expect_local();
54 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
55 tcx.mir_const_qualif_const_arg(def)
57 mir_const_qualif(tcx, ty::WithOptConstParam::unknown(def_id))
60 mir_const_qualif_const_arg: |tcx, (did, param_did)| {
61 mir_const_qualif(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
64 mir_drops_elaborated_and_const_checked,
66 optimized_mir_of_const_arg,
68 promoted_mir: |tcx, def_id| {
69 let def_id = def_id.expect_local();
70 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
71 tcx.promoted_mir_of_const_arg(def)
73 promoted_mir(tcx, ty::WithOptConstParam::unknown(def_id))
76 promoted_mir_of_const_arg: |tcx, (did, param_did)| {
77 promoted_mir(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
81 instrument_coverage::provide(providers);
84 fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
85 tcx.mir_keys(def_id.krate).contains(&def_id.expect_local())
88 /// Finds the full set of `DefId`s within the current crate that have
89 /// MIR associated with them.
90 fn mir_keys(tcx: TyCtxt<'_>, krate: CrateNum) -> FxHashSet<LocalDefId> {
91 assert_eq!(krate, LOCAL_CRATE);
93 let mut set = FxHashSet::default();
95 // All body-owners have MIR associated with them.
96 set.extend(tcx.body_owners());
98 // Additionally, tuple struct/variant constructors have MIR, but
99 // they don't have a BodyId, so we need to build them separately.
100 struct GatherCtors<'a, 'tcx> {
102 set: &'a mut FxHashSet<LocalDefId>,
104 impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
105 fn visit_variant_data(
107 v: &'tcx hir::VariantData<'tcx>,
109 _: &'tcx hir::Generics<'tcx>,
113 if let hir::VariantData::Tuple(_, hir_id) = *v {
114 self.set.insert(self.tcx.hir().local_def_id(hir_id));
116 intravisit::walk_struct_def(self, v)
118 type Map = intravisit::ErasedMap<'tcx>;
119 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
120 NestedVisitorMap::None
125 .visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
130 /// Where a specific `mir::Body` comes from.
131 #[derive(Debug, Copy, Clone)]
132 pub struct MirSource<'tcx> {
133 pub instance: InstanceDef<'tcx>,
135 /// If `Some`, this is a promoted rvalue within the parent function.
136 pub promoted: Option<Promoted>,
139 impl<'tcx> MirSource<'tcx> {
140 pub fn item(def_id: DefId) -> Self {
142 instance: InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)),
147 pub fn with_opt_param(self) -> ty::WithOptConstParam<DefId> {
148 self.instance.with_opt_param()
152 pub fn def_id(&self) -> DefId {
153 self.instance.def_id()
157 /// Generates a default name for the pass based on the name of the
159 pub fn default_name<T: ?Sized>() -> Cow<'static, str> {
160 let name = ::std::any::type_name::<T>();
161 if let Some(tail) = name.rfind(':') { Cow::from(&name[tail + 1..]) } else { Cow::from(name) }
164 /// A streamlined trait that you can implement to create a pass; the
165 /// pass will be named after the type, and it will consist of a main
166 /// loop that goes over each available MIR and applies `run_pass`.
167 pub trait MirPass<'tcx> {
168 fn name(&self) -> Cow<'_, str> {
169 default_name::<Self>()
172 fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>);
177 body: &mut Body<'tcx>,
178 instance: InstanceDef<'tcx>,
179 promoted: Option<Promoted>,
181 passes: &[&[&dyn MirPass<'tcx>]],
183 let phase_index = mir_phase.phase_index();
184 let source = MirSource { instance, promoted };
185 let validate = tcx.sess.opts.debugging_opts.validate_mir;
187 if body.phase >= mir_phase {
192 validate::Validator { when: format!("input to phase {:?}", mir_phase) }
193 .run_pass(tcx, source, body);
197 let mut run_pass = |pass: &dyn MirPass<'tcx>| {
198 let run_hooks = |body: &_, index, is_after| {
199 dump_mir::on_mir_pass(
201 &format_args!("{:03}-{:03}", phase_index, index),
208 run_hooks(body, index, false);
209 pass.run_pass(tcx, source, body);
210 run_hooks(body, index, true);
213 validate::Validator { when: format!("after {} in phase {:?}", pass.name(), mir_phase) }
214 .run_pass(tcx, source, body);
220 for pass_group in passes {
221 for pass in *pass_group {
226 body.phase = mir_phase;
228 if mir_phase == MirPhase::Optimized {
229 validate::Validator { when: format!("end of phase {:?}", mir_phase) }
230 .run_pass(tcx, source, body);
234 fn mir_const_qualif(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> ConstQualifs {
235 let const_kind = tcx.hir().body_const_context(def.did);
237 // No need to const-check a non-const `fn`.
238 if const_kind.is_none() {
239 return Default::default();
242 // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
243 // cannot yet be stolen), because `mir_validated()`, which steals
244 // from `mir_const(), forces this query to execute before
245 // performing the steal.
246 let body = &tcx.mir_const(def).borrow();
248 if body.return_ty().references_error() {
249 tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
250 return Default::default();
253 let ccx = check_consts::ConstCx {
258 param_env: tcx.param_env(def.did),
261 let mut validator = check_consts::validation::Validator::new(&ccx);
262 validator.check_body();
264 // We return the qualifs in the return place for every MIR body, even though it is only used
265 // when deciding to promote a reference to a `const` for now.
266 validator.qualifs_in_return_place()
269 /// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
272 def: ty::WithOptConstParam<LocalDefId>,
273 ) -> &'tcx Steal<Body<'tcx>> {
274 if let Some(def) = def.try_upgrade(tcx) {
275 return tcx.mir_const(def);
278 // Unsafety check uses the raw mir, so make sure it is run.
279 if let Some(param_did) = def.const_param_did {
280 tcx.ensure().unsafety_check_result_for_const_arg((def.did, param_did));
282 tcx.ensure().unsafety_check_result(def.did);
285 let mut body = tcx.mir_built(def).steal();
292 MirSource { instance: InstanceDef::Item(def.to_global()), promoted: None },
300 InstanceDef::Item(def.to_global()),
305 &check_packed_ref::CheckPackedRef,
306 // What we need to do constant evaluation.
307 &simplify::SimplifyCfg::new("initial"),
308 &rustc_peek::SanityCheck,
311 tcx.alloc_steal_mir(body)
316 def: ty::WithOptConstParam<LocalDefId>,
317 ) -> (&'tcx Steal<Body<'tcx>>, &'tcx Steal<IndexVec<Promoted, Body<'tcx>>>) {
318 if let Some(def) = def.try_upgrade(tcx) {
319 return tcx.mir_validated(def);
322 // Ensure that we compute the `mir_const_qualif` for constants at
323 // this point, before we steal the mir-const result.
324 // Also this means promotion can rely on all const checks having been done.
325 let _ = tcx.mir_const_qualif_opt_const_arg(def);
327 let mut body = tcx.mir_const(def).steal();
329 let mut required_consts = Vec::new();
330 let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
331 for (bb, bb_data) in traversal::reverse_postorder(&body) {
332 required_consts_visitor.visit_basic_block_data(bb, bb_data);
334 body.required_consts = required_consts;
336 let promote_pass = promote_consts::PromoteTemps::default();
337 let promote: &[&dyn MirPass<'tcx>] = &[
338 // What we need to run borrowck etc.
340 &simplify::SimplifyCfg::new("promote-consts"),
343 let opt_coverage: &[&dyn MirPass<'tcx>] = if tcx.sess.opts.debugging_opts.instrument_coverage {
344 &[&instrument_coverage::InstrumentCoverage]
352 InstanceDef::Item(def.to_global()),
355 &[promote, opt_coverage],
358 let promoted = promote_pass.promoted_fragments.into_inner();
359 (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
362 fn mir_drops_elaborated_and_const_checked<'tcx>(
364 def: ty::WithOptConstParam<LocalDefId>,
365 ) -> &'tcx Steal<Body<'tcx>> {
366 if let Some(def) = def.try_upgrade(tcx) {
367 return tcx.mir_drops_elaborated_and_const_checked(def);
370 // (Mir-)Borrowck uses `mir_validated`, so we have to force it to
371 // execute before we can steal.
372 if let Some(param_did) = def.const_param_did {
373 tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
375 tcx.ensure().mir_borrowck(def.did);
378 let (body, _) = tcx.mir_validated(def);
379 let mut body = body.steal();
381 run_post_borrowck_cleanup_passes(tcx, &mut body, def.did, None);
382 check_consts::post_drop_elaboration::check_live_drops(tcx, def.did, &body);
383 tcx.alloc_steal_mir(body)
386 /// After this series of passes, no lifetime analysis based on borrowing can be done.
387 fn run_post_borrowck_cleanup_passes<'tcx>(
389 body: &mut Body<'tcx>,
391 promoted: Option<Promoted>,
393 debug!("post_borrowck_cleanup({:?})", def_id);
395 let post_borrowck_cleanup: &[&dyn MirPass<'tcx>] = &[
396 // Remove all things only needed by analysis
397 &no_landing_pads::NoLandingPads::new(tcx),
398 &simplify_branches::SimplifyBranches::new("initial"),
399 &remove_noop_landing_pads::RemoveNoopLandingPads,
400 &cleanup_post_borrowck::CleanupNonCodegenStatements,
401 &simplify::SimplifyCfg::new("early-opt"),
402 // These next passes must be executed together
403 &add_call_guards::CriticalCallEdges,
404 &elaborate_drops::ElaborateDrops,
405 &no_landing_pads::NoLandingPads::new(tcx),
406 // AddMovesForPackedDrops needs to run after drop
408 &add_moves_for_packed_drops::AddMovesForPackedDrops,
409 // `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late,
410 // but before optimizations begin.
411 &add_retag::AddRetag,
412 &simplify::SimplifyCfg::new("elaborate-drops"),
413 // `Deaggregator` is conceptually part of MIR building, some backends rely on it happening
414 // and it can help optimizations.
415 &deaggregator::Deaggregator,
421 InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id())),
424 &[post_borrowck_cleanup],
428 fn run_optimization_passes<'tcx>(
430 body: &mut Body<'tcx>,
432 promoted: Option<Promoted>,
434 let optimizations: &[&dyn MirPass<'tcx>] = &[
435 &unreachable_prop::UnreachablePropagation,
436 &uninhabited_enum_branching::UninhabitedEnumBranching,
437 &simplify::SimplifyCfg::new("after-uninhabited-enum-branching"),
439 // Lowering generator control-flow and variables has to happen before we do anything else
440 // to them. We do this inside the "optimizations" block so that it can benefit from
441 // optimizations that run before, that might be harder to do on the state machine than MIR
442 // with async primitives.
443 &generator::StateTransform,
444 &instcombine::InstCombine,
445 &match_branches::MatchBranchSimplification,
446 &const_prop::ConstProp,
447 &simplify_branches::SimplifyBranches::new("after-const-prop"),
448 &simplify_try::SimplifyArmIdentity,
449 &simplify_try::SimplifyBranchSame,
450 ©_prop::CopyPropagation,
451 &simplify_branches::SimplifyBranches::new("after-copy-prop"),
452 &remove_noop_landing_pads::RemoveNoopLandingPads,
453 &simplify::SimplifyCfg::new("after-remove-noop-landing-pads"),
454 &simplify::SimplifyCfg::new("final"),
455 &nrvo::RenameReturnPlace,
456 &simplify::SimplifyLocals,
459 let no_optimizations: &[&dyn MirPass<'tcx>] = &[
460 // Even if we don't do optimizations, we still have to lower generators for codegen.
461 &generator::StateTransform,
462 // FIXME(#70073): This pass is responsible for both optimization as well as some lints.
463 &const_prop::ConstProp,
466 let pre_codegen_cleanup: &[&dyn MirPass<'tcx>] = &[
467 &add_call_guards::CriticalCallEdges,
468 // Dump the end result for testing and debugging purposes.
469 &dump_mir::Marker("PreCodegen"),
472 let mir_opt_level = tcx.sess.opts.debugging_opts.mir_opt_level;
478 InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id())),
482 if mir_opt_level > 0 { optimizations } else { no_optimizations },
488 fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx Body<'tcx> {
489 let did = did.expect_local();
490 if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
491 tcx.optimized_mir_of_const_arg(def)
493 tcx.arena.alloc(inner_optimized_mir(tcx, ty::WithOptConstParam::unknown(did)))
497 fn optimized_mir_of_const_arg<'tcx>(
499 (did, param_did): (LocalDefId, DefId),
500 ) -> &'tcx Body<'tcx> {
501 tcx.arena.alloc(inner_optimized_mir(
503 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
507 fn inner_optimized_mir(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
508 if tcx.is_constructor(def.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
513 return shim::build_adt_ctor(tcx, def.did.to_def_id());
516 let mut body = tcx.mir_drops_elaborated_and_const_checked(def).steal();
517 run_optimization_passes(tcx, &mut body, def.did, None);
519 debug_assert!(!body.has_free_regions(), "Free regions in optimized MIR");
524 fn promoted_mir<'tcx>(
526 def: ty::WithOptConstParam<LocalDefId>,
527 ) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
528 if tcx.is_constructor(def.did.to_def_id()) {
529 return tcx.arena.alloc(IndexVec::new());
532 if let Some(param_did) = def.const_param_did {
533 tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
535 tcx.ensure().mir_borrowck(def.did);
537 let (_, promoted) = tcx.mir_validated(def);
538 let mut promoted = promoted.steal();
540 for (p, mut body) in promoted.iter_enumerated_mut() {
541 run_post_borrowck_cleanup_passes(tcx, &mut body, def.did, Some(p));
542 run_optimization_passes(tcx, &mut body, def.did, Some(p));
545 debug_assert!(!promoted.has_free_regions(), "Free regions in promoted MIR");
547 tcx.arena.alloc(promoted)