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 no_landing_pads;
34 pub mod promote_consts;
35 pub mod qualify_min_const_fn;
36 pub mod remove_noop_landing_pads;
37 pub mod required_consts;
40 pub mod simplify_branches;
42 pub mod uninhabited_enum_branching;
43 pub mod unreachable_prop;
46 pub(crate) fn provide(providers: &mut Providers) {
47 self::check_unsafety::provide(providers);
48 *providers = Providers {
51 mir_const_qualif: |tcx, def_id| {
52 let def_id = def_id.expect_local();
53 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
54 tcx.mir_const_qualif_const_arg(def)
56 mir_const_qualif(tcx, ty::WithOptConstParam::unknown(def_id))
59 mir_const_qualif_const_arg: |tcx, (did, param_did)| {
60 mir_const_qualif(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
63 mir_drops_elaborated_and_const_checked,
65 optimized_mir_of_const_arg,
67 promoted_mir: |tcx, def_id| {
68 let def_id = def_id.expect_local();
69 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
70 tcx.promoted_mir_of_const_arg(def)
72 promoted_mir(tcx, ty::WithOptConstParam::unknown(def_id))
75 promoted_mir_of_const_arg: |tcx, (did, param_did)| {
76 promoted_mir(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
80 instrument_coverage::provide(providers);
83 fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
84 tcx.mir_keys(def_id.krate).contains(&def_id.expect_local())
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);
92 let mut set = FxHashSet::default();
94 // All body-owners have MIR associated with them.
95 set.extend(tcx.body_owners());
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> {
101 set: &'a mut FxHashSet<LocalDefId>,
103 impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
104 fn visit_variant_data(
106 v: &'tcx hir::VariantData<'tcx>,
108 _: &'tcx hir::Generics<'tcx>,
112 if let hir::VariantData::Tuple(_, hir_id) = *v {
113 self.set.insert(self.tcx.hir().local_def_id(hir_id));
115 intravisit::walk_struct_def(self, v)
117 type Map = intravisit::ErasedMap<'tcx>;
118 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
119 NestedVisitorMap::None
124 .visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
129 /// Where a specific `mir::Body` comes from.
130 #[derive(Debug, Copy, Clone)]
131 pub struct MirSource<'tcx> {
132 pub instance: InstanceDef<'tcx>,
134 /// If `Some`, this is a promoted rvalue within the parent function.
135 pub promoted: Option<Promoted>,
138 impl<'tcx> MirSource<'tcx> {
139 pub fn item(def_id: DefId) -> Self {
141 instance: InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)),
146 pub fn with_opt_param(self) -> ty::WithOptConstParam<DefId> {
147 self.instance.with_opt_param()
151 pub fn def_id(&self) -> DefId {
152 self.instance.def_id()
156 /// Generates a default name for the pass based on the name of the
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) }
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>()
171 fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>);
176 body: &mut Body<'tcx>,
177 instance: InstanceDef<'tcx>,
178 promoted: Option<Promoted>,
180 passes: &[&[&dyn MirPass<'tcx>]],
182 let phase_index = mir_phase.phase_index();
183 let source = MirSource { instance, promoted };
184 let validate = tcx.sess.opts.debugging_opts.validate_mir;
186 if body.phase >= mir_phase {
191 validate::Validator { when: format!("input to phase {:?}", mir_phase) }
192 .run_pass(tcx, source, body);
196 let mut run_pass = |pass: &dyn MirPass<'tcx>| {
197 let run_hooks = |body: &_, index, is_after| {
198 dump_mir::on_mir_pass(
200 &format_args!("{:03}-{:03}", phase_index, index),
207 run_hooks(body, index, false);
208 pass.run_pass(tcx, source, body);
209 run_hooks(body, index, true);
212 validate::Validator { when: format!("after {} in phase {:?}", pass.name(), mir_phase) }
213 .run_pass(tcx, source, body);
219 for pass_group in passes {
220 for pass in *pass_group {
225 body.phase = mir_phase;
227 if mir_phase == MirPhase::Optimized {
228 validate::Validator { when: format!("end of phase {:?}", mir_phase) }
229 .run_pass(tcx, source, body);
233 fn mir_const_qualif(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> ConstQualifs {
234 let const_kind = tcx.hir().body_const_context(def.did);
236 // No need to const-check a non-const `fn`.
237 if const_kind.is_none() {
238 return Default::default();
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();
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();
252 let ccx = check_consts::ConstCx {
257 param_env: tcx.param_env(def.did),
260 let mut validator = check_consts::validation::Validator::new(&ccx);
261 validator.check_body();
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()
268 /// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
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);
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));
281 tcx.ensure().unsafety_check_result(def.did);
284 let mut body = tcx.mir_built(def).steal();
291 MirSource { instance: InstanceDef::Item(def.to_global()), promoted: None },
299 InstanceDef::Item(def.to_global()),
304 &check_packed_ref::CheckPackedRef,
305 // What we need to do constant evaluation.
306 &simplify::SimplifyCfg::new("initial"),
307 &rustc_peek::SanityCheck,
310 tcx.alloc_steal_mir(body)
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);
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);
325 let mut body = tcx.mir_const(def).steal();
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);
332 body.required_consts = required_consts;
334 let promote_pass = promote_consts::PromoteTemps::default();
338 InstanceDef::Item(def.to_global()),
342 // What we need to run borrowck etc.
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
347 // counters where needed.
348 &instrument_coverage::InstrumentCoverage,
352 let promoted = promote_pass.promoted_fragments.into_inner();
353 (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
356 fn mir_drops_elaborated_and_const_checked<'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);
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));
369 tcx.ensure().mir_borrowck(def.did);
372 let (body, _) = tcx.mir_validated(def);
373 let mut body = body.steal();
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)
380 /// After this series of passes, no lifetime analysis based on borrowing can be done.
381 fn run_post_borrowck_cleanup_passes<'tcx>(
383 body: &mut Body<'tcx>,
385 promoted: Option<Promoted>,
387 debug!("post_borrowck_cleanup({:?})", def_id);
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
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"),
412 InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id())),
415 &[post_borrowck_cleanup],
419 fn run_optimization_passes<'tcx>(
421 body: &mut Body<'tcx>,
423 promoted: Option<Promoted>,
425 let optimizations: &[&dyn MirPass<'tcx>] = &[
426 &unreachable_prop::UnreachablePropagation,
427 &uninhabited_enum_branching::UninhabitedEnumBranching,
428 &simplify::SimplifyCfg::new("after-uninhabited-enum-branching"),
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 ©_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,
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,
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"),
470 let mir_opt_level = tcx.sess.opts.debugging_opts.mir_opt_level;
476 InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id())),
480 if mir_opt_level > 0 { optimizations } else { no_optimizations },
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_lookup(did, tcx) {
489 tcx.optimized_mir_of_const_arg(def)
491 tcx.arena.alloc(inner_optimized_mir(tcx, ty::WithOptConstParam::unknown(did)))
495 fn optimized_mir_of_const_arg<'tcx>(
497 (did, param_did): (LocalDefId, DefId),
498 ) -> &'tcx Body<'tcx> {
499 tcx.arena.alloc(inner_optimized_mir(
501 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
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
511 return shim::build_adt_ctor(tcx, def.did.to_def_id());
514 let mut body = tcx.mir_drops_elaborated_and_const_checked(def).steal();
515 run_optimization_passes(tcx, &mut body, def.did, None);
517 debug_assert!(!body.has_free_regions(), "Free regions in optimized MIR");
522 fn promoted_mir<'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());
530 if let Some(param_did) = def.const_param_did {
531 tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
533 tcx.ensure().mir_borrowck(def.did);
535 let (_, promoted) = tcx.mir_validated(def);
536 let mut promoted = promoted.steal();
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));
543 debug_assert!(!promoted.has_free_regions(), "Free regions in promoted MIR");
545 tcx.arena.alloc(promoted)