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, did| {
52 mir_const_qualif(tcx, ty::WithOptConstParam::dummy(did.expect_local()))
54 mir_const_qualif_const_arg: |tcx, (did, param_did)| {
55 mir_const_qualif(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
58 mir_drops_elaborated_and_const_checked,
60 optimized_mir_of_const_arg,
62 promoted_mir: |tcx, def_id| {
63 promoted_mir(tcx, ty::WithOptConstParam::dummy(def_id.expect_local()))
65 promoted_mir_of_const_arg: |tcx, (did, param_did)| {
66 promoted_mir(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
70 instrument_coverage::provide(providers);
73 fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
74 tcx.mir_keys(def_id.krate).contains(&def_id.expect_local())
77 /// Finds the full set of `DefId`s within the current crate that have
78 /// MIR associated with them.
79 fn mir_keys(tcx: TyCtxt<'_>, krate: CrateNum) -> FxHashSet<LocalDefId> {
80 assert_eq!(krate, LOCAL_CRATE);
82 let mut set = FxHashSet::default();
84 // All body-owners have MIR associated with them.
85 set.extend(tcx.body_owners());
87 // Additionally, tuple struct/variant constructors have MIR, but
88 // they don't have a BodyId, so we need to build them separately.
89 struct GatherCtors<'a, 'tcx> {
91 set: &'a mut FxHashSet<LocalDefId>,
93 impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
94 fn visit_variant_data(
96 v: &'tcx hir::VariantData<'tcx>,
98 _: &'tcx hir::Generics<'tcx>,
102 if let hir::VariantData::Tuple(_, hir_id) = *v {
103 self.set.insert(self.tcx.hir().local_def_id(hir_id));
105 intravisit::walk_struct_def(self, v)
107 type Map = intravisit::ErasedMap<'tcx>;
108 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
109 NestedVisitorMap::None
114 .visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
119 /// Where a specific `mir::Body` comes from.
120 #[derive(Debug, Copy, Clone)]
121 pub struct MirSource<'tcx> {
122 pub instance: InstanceDef<'tcx>,
124 /// If `Some`, this is a promoted rvalue within the parent function.
125 pub promoted: Option<Promoted>,
128 impl<'tcx> MirSource<'tcx> {
129 pub fn item(def_id: DefId) -> Self {
131 instance: InstanceDef::Item(ty::WithOptConstParam::dummy(def_id)),
136 pub fn with_opt_param(self) -> ty::WithOptConstParam<DefId> {
137 self.instance.with_opt_param()
141 pub fn def_id(&self) -> DefId {
142 self.instance.def_id()
146 /// Generates a default name for the pass based on the name of the
148 pub fn default_name<T: ?Sized>() -> Cow<'static, str> {
149 let name = ::std::any::type_name::<T>();
150 if let Some(tail) = name.rfind(':') { Cow::from(&name[tail + 1..]) } else { Cow::from(name) }
153 /// A streamlined trait that you can implement to create a pass; the
154 /// pass will be named after the type, and it will consist of a main
155 /// loop that goes over each available MIR and applies `run_pass`.
156 pub trait MirPass<'tcx> {
157 fn name(&self) -> Cow<'_, str> {
158 default_name::<Self>()
161 fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>);
166 body: &mut Body<'tcx>,
167 instance: InstanceDef<'tcx>,
168 promoted: Option<Promoted>,
170 passes: &[&[&dyn MirPass<'tcx>]],
172 let phase_index = mir_phase.phase_index();
173 let source = MirSource { instance, promoted };
174 let validate = tcx.sess.opts.debugging_opts.validate_mir;
176 if body.phase >= mir_phase {
181 validate::Validator { when: format!("input to phase {:?}", mir_phase) }
182 .run_pass(tcx, source, body);
186 let mut run_pass = |pass: &dyn MirPass<'tcx>| {
187 let run_hooks = |body: &_, index, is_after| {
188 dump_mir::on_mir_pass(
190 &format_args!("{:03}-{:03}", phase_index, index),
197 run_hooks(body, index, false);
198 pass.run_pass(tcx, source, body);
199 run_hooks(body, index, true);
202 validate::Validator { when: format!("after {} in phase {:?}", pass.name(), mir_phase) }
203 .run_pass(tcx, source, body);
209 for pass_group in passes {
210 for pass in *pass_group {
215 body.phase = mir_phase;
217 if mir_phase == MirPhase::Optimized {
218 validate::Validator { when: format!("end of phase {:?}", mir_phase) }
219 .run_pass(tcx, source, body);
223 fn mir_const_qualif(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> ConstQualifs {
224 if def.const_param_did.is_none() {
225 if let Some(param_did) = tcx.opt_const_param_of(def.did) {
226 return tcx.mir_const_qualif_const_arg((def.did, param_did));
230 let const_kind = tcx.hir().body_const_context(def.did);
232 // No need to const-check a non-const `fn`.
233 if const_kind.is_none() {
234 return Default::default();
237 // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
238 // cannot yet be stolen), because `mir_validated()`, which steals
239 // from `mir_const(), forces this query to execute before
240 // performing the steal.
241 let body = &tcx.mir_const(def).borrow();
243 if body.return_ty().references_error() {
244 tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
245 return Default::default();
248 let ccx = check_consts::ConstCx {
253 param_env: tcx.param_env(def.did),
256 let mut validator = check_consts::validation::Validator::new(&ccx);
257 validator.check_body();
259 // We return the qualifs in the return place for every MIR body, even though it is only used
260 // when deciding to promote a reference to a `const` for now.
261 validator.qualifs_in_return_place()
264 /// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
267 def: ty::WithOptConstParam<LocalDefId>,
268 ) -> &'tcx Steal<Body<'tcx>> {
269 if def.const_param_did.is_none() {
270 if let const_param_did @ Some(_) = tcx.opt_const_param_of(def.did) {
271 return tcx.mir_const(ty::WithOptConstParam { const_param_did, ..def });
275 // Unsafety check uses the raw mir, so make sure it is run.
276 if let Some(param_did) = def.const_param_did {
277 tcx.ensure().unsafety_check_result_const_arg((def.did, param_did));
279 tcx.ensure().unsafety_check_result(def.did);
282 let mut body = tcx.mir_built(def).steal();
289 MirSource { instance: InstanceDef::Item(def.to_global()), promoted: None },
297 InstanceDef::Item(def.to_global()),
302 &check_packed_ref::CheckPackedRef,
303 // What we need to do constant evaluation.
304 &simplify::SimplifyCfg::new("initial"),
305 &rustc_peek::SanityCheck,
308 tcx.alloc_steal_mir(body)
313 def: ty::WithOptConstParam<LocalDefId>,
314 ) -> (&'tcx Steal<Body<'tcx>>, &'tcx Steal<IndexVec<Promoted, Body<'tcx>>>) {
315 if def.const_param_did.is_none() {
316 if let const_param_did @ Some(_) = tcx.opt_const_param_of(def.did) {
317 return tcx.mir_validated(ty::WithOptConstParam { const_param_did, ..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 counters
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 def.const_param_did.is_none() {
361 if let const_param_did @ Some(_) = tcx.opt_const_param_of(def.did) {
362 return tcx.mir_drops_elaborated_and_const_checked(ty::WithOptConstParam {
369 // (Mir-)Borrowck uses `mir_validated`, so we have to force it to
370 // execute before we can steal.
371 if let Some(param_did) = def.const_param_did {
372 tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
374 tcx.ensure().mir_borrowck(def.did);
377 let (body, _) = tcx.mir_validated(def);
378 let mut body = body.steal();
380 run_post_borrowck_cleanup_passes(tcx, &mut body, def.did, None);
381 check_consts::post_drop_elaboration::check_live_drops(tcx, def.did, &body);
382 tcx.alloc_steal_mir(body)
385 /// After this series of passes, no lifetime analysis based on borrowing can be done.
386 fn run_post_borrowck_cleanup_passes<'tcx>(
388 body: &mut Body<'tcx>,
390 promoted: Option<Promoted>,
392 debug!("post_borrowck_cleanup({:?})", def_id);
394 let post_borrowck_cleanup: &[&dyn MirPass<'tcx>] = &[
395 // Remove all things only needed by analysis
396 &no_landing_pads::NoLandingPads::new(tcx),
397 &simplify_branches::SimplifyBranches::new("initial"),
398 &remove_noop_landing_pads::RemoveNoopLandingPads,
399 &cleanup_post_borrowck::CleanupNonCodegenStatements,
400 &simplify::SimplifyCfg::new("early-opt"),
401 // These next passes must be executed together
402 &add_call_guards::CriticalCallEdges,
403 &elaborate_drops::ElaborateDrops,
404 &no_landing_pads::NoLandingPads::new(tcx),
405 // AddMovesForPackedDrops needs to run after drop
407 &add_moves_for_packed_drops::AddMovesForPackedDrops,
408 // `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late,
409 // but before optimizations begin.
410 &add_retag::AddRetag,
411 &simplify::SimplifyCfg::new("elaborate-drops"),
417 InstanceDef::Item(ty::WithOptConstParam::dummy(def_id.to_def_id())),
420 &[post_borrowck_cleanup],
424 fn run_optimization_passes<'tcx>(
426 body: &mut Body<'tcx>,
428 promoted: Option<Promoted>,
430 let optimizations: &[&dyn MirPass<'tcx>] = &[
431 &unreachable_prop::UnreachablePropagation,
432 &uninhabited_enum_branching::UninhabitedEnumBranching,
433 &simplify::SimplifyCfg::new("after-uninhabited-enum-branching"),
435 // Lowering generator control-flow and variables has to happen before we do anything else
436 // to them. We do this inside the "optimizations" block so that it can benefit from
437 // optimizations that run before, that might be harder to do on the state machine than MIR
438 // with async primitives.
439 &generator::StateTransform,
440 &instcombine::InstCombine,
441 &const_prop::ConstProp,
442 &simplify_branches::SimplifyBranches::new("after-const-prop"),
443 // Run deaggregation here because:
444 // 1. Some codegen backends require it
445 // 2. It creates additional possibilities for some MIR optimizations to trigger
446 // FIXME(#70073): Why is this done here and not in `post_borrowck_cleanup`?
447 &deaggregator::Deaggregator,
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,
464 // Even if we don't do optimizations, still run deaggregation because some backends assume
465 // that deaggregation always occurs.
466 &deaggregator::Deaggregator,
469 let pre_codegen_cleanup: &[&dyn MirPass<'tcx>] = &[
470 &add_call_guards::CriticalCallEdges,
471 // Dump the end result for testing and debugging purposes.
472 &dump_mir::Marker("PreCodegen"),
475 let mir_opt_level = tcx.sess.opts.debugging_opts.mir_opt_level;
481 InstanceDef::Item(ty::WithOptConstParam::dummy(def_id.to_def_id())),
485 if mir_opt_level > 0 { optimizations } else { no_optimizations },
491 fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx Body<'tcx> {
492 let did = did.expect_local();
493 if let Some(param_did) = tcx.opt_const_param_of(did) {
494 tcx.optimized_mir_of_const_arg((did, param_did))
496 tcx.arena.alloc(inner_optimized_mir(tcx, ty::WithOptConstParam::dummy(did)))
500 fn optimized_mir_of_const_arg<'tcx>(
502 (did, param_did): (LocalDefId, DefId),
503 ) -> &'tcx Body<'tcx> {
504 tcx.arena.alloc(inner_optimized_mir(
506 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
510 fn inner_optimized_mir(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
511 if tcx.is_constructor(def.did.to_def_id()) {
512 // There's no reason to run all of the MIR passes on constructors when
513 // we can just output the MIR we want directly. This also saves const
514 // qualification and borrow checking the trouble of special casing
516 return shim::build_adt_ctor(tcx, def.did.to_def_id());
519 let mut body = tcx.mir_drops_elaborated_and_const_checked(def).steal();
520 run_optimization_passes(tcx, &mut body, def.did, None);
522 debug_assert!(!body.has_free_regions(), "Free regions in optimized MIR");
527 fn promoted_mir<'tcx>(
529 def: ty::WithOptConstParam<LocalDefId>,
530 ) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
531 if def.const_param_did.is_none() {
532 if let Some(param_did) = tcx.opt_const_param_of(def.did) {
533 return tcx.promoted_mir_of_const_arg((def.did, param_did));
537 if tcx.is_constructor(def.did.to_def_id()) {
538 return tcx.arena.alloc(IndexVec::new());
541 if let Some(param_did) = def.const_param_did {
542 tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
544 tcx.ensure().mir_borrowck(def.did);
546 let (_, promoted) = tcx.mir_validated(def);
547 let mut promoted = promoted.steal();
549 for (p, mut body) in promoted.iter_enumerated_mut() {
550 run_post_borrowck_cleanup_passes(tcx, &mut body, def.did, Some(p));
551 run_optimization_passes(tcx, &mut body, def.did, Some(p));
554 debug_assert!(!promoted.has_free_regions(), "Free regions in promoted MIR");
556 tcx.arena.alloc(promoted)