1 use crate::{shim, util};
2 use rustc::mir::{BodyAndCache, ConstQualifs, MirPhase, Promoted};
3 use rustc::ty::query::Providers;
4 use rustc::ty::steal::Steal;
5 use rustc::ty::{InstanceDef, TyCtxt, TypeFoldable};
8 use rustc_hir::def_id::{CrateNum, DefId, DefIdSet, LOCAL_CRATE};
9 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
10 use rustc_index::vec::IndexVec;
14 pub mod add_call_guards;
15 pub mod add_moves_for_packed_drops;
18 pub mod check_unsafety;
19 pub mod cleanup_post_borrowck;
24 pub mod elaborate_drops;
25 pub mod erase_regions;
29 pub mod no_landing_pads;
30 pub mod promote_consts;
31 pub mod qualify_min_const_fn;
32 pub mod remove_noop_landing_pads;
35 pub mod simplify_branches;
37 pub mod uninhabited_enum_branching;
38 pub mod unreachable_prop;
40 pub(crate) fn provide(providers: &mut Providers<'_>) {
41 self::check_unsafety::provide(providers);
42 *providers = Providers {
54 fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
55 tcx.mir_keys(def_id.krate).contains(&def_id)
58 /// Finds the full set of `DefId`s within the current crate that have
59 /// MIR associated with them.
60 fn mir_keys(tcx: TyCtxt<'_>, krate: CrateNum) -> &DefIdSet {
61 assert_eq!(krate, LOCAL_CRATE);
63 let mut set = DefIdSet::default();
65 // All body-owners have MIR associated with them.
66 set.extend(tcx.body_owners());
68 // Additionally, tuple struct/variant constructors have MIR, but
69 // they don't have a BodyId, so we need to build them separately.
70 struct GatherCtors<'a, 'tcx> {
72 set: &'a mut DefIdSet,
74 impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
75 fn visit_variant_data(
77 v: &'tcx hir::VariantData<'tcx>,
79 _: &'tcx hir::Generics<'tcx>,
83 if let hir::VariantData::Tuple(_, hir_id) = *v {
84 self.set.insert(self.tcx.hir().local_def_id(hir_id));
86 intravisit::walk_struct_def(self, v)
88 type Map = intravisit::ErasedMap<'tcx>;
89 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
90 NestedVisitorMap::None
95 .visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
100 /// Where a specific `mir::Body` comes from.
101 #[derive(Debug, Copy, Clone)]
102 pub struct MirSource<'tcx> {
103 pub instance: InstanceDef<'tcx>,
105 /// If `Some`, this is a promoted rvalue within the parent function.
106 pub promoted: Option<Promoted>,
109 impl<'tcx> MirSource<'tcx> {
110 pub fn item(def_id: DefId) -> Self {
111 MirSource { instance: InstanceDef::Item(def_id), promoted: None }
115 pub fn def_id(&self) -> DefId {
116 self.instance.def_id()
120 /// Generates a default name for the pass based on the name of the
122 pub fn default_name<T: ?Sized>() -> Cow<'static, str> {
123 let name = ::std::any::type_name::<T>();
124 if let Some(tail) = name.rfind(':') { Cow::from(&name[tail + 1..]) } else { Cow::from(name) }
127 /// A streamlined trait that you can implement to create a pass; the
128 /// pass will be named after the type, and it will consist of a main
129 /// loop that goes over each available MIR and applies `run_pass`.
130 pub trait MirPass<'tcx> {
131 fn name(&self) -> Cow<'_, str> {
132 default_name::<Self>()
135 fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut BodyAndCache<'tcx>);
140 body: &mut BodyAndCache<'tcx>,
141 instance: InstanceDef<'tcx>,
142 promoted: Option<Promoted>,
144 passes: &[&dyn MirPass<'tcx>],
146 let phase_index = mir_phase.phase_index();
148 if body.phase >= mir_phase {
152 let source = MirSource { instance, promoted };
154 let mut run_pass = |pass: &dyn MirPass<'tcx>| {
155 let run_hooks = |body: &_, index, is_after| {
156 dump_mir::on_mir_pass(
158 &format_args!("{:03}-{:03}", phase_index, index),
165 run_hooks(body, index, false);
166 pass.run_pass(tcx, source, body);
167 run_hooks(body, index, true);
176 body.phase = mir_phase;
179 fn mir_const_qualif(tcx: TyCtxt<'_>, def_id: DefId) -> ConstQualifs {
180 let const_kind = check_consts::ConstKind::for_item(tcx, def_id);
182 // No need to const-check a non-const `fn`.
183 if const_kind.is_none() {
184 return Default::default();
187 // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
188 // cannot yet be stolen), because `mir_validated()`, which steals
189 // from `mir_const(), forces this query to execute before
190 // performing the steal.
191 let body = &tcx.mir_const(def_id).borrow();
193 if body.return_ty().references_error() {
194 tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
195 return Default::default();
198 let item = check_consts::Item {
199 body: body.unwrap_read_only(),
203 param_env: tcx.param_env(def_id),
206 let mut validator = check_consts::validation::Validator::new(&item);
207 validator.check_body();
209 // We return the qualifs in the return place for every MIR body, even though it is only used
210 // when deciding to promote a reference to a `const` for now.
211 validator.qualifs_in_return_place()
214 fn mir_const(tcx: TyCtxt<'_>, def_id: DefId) -> &Steal<BodyAndCache<'_>> {
215 // Unsafety check uses the raw mir, so make sure it is run
216 let _ = tcx.unsafety_check_result(def_id);
218 let mut body = tcx.mir_built(def_id).steal();
220 util::dump_mir(tcx, None, "mir_map", &0, MirSource::item(def_id), &body, |_, _| Ok(()));
225 InstanceDef::Item(def_id),
229 // What we need to do constant evaluation.
230 &simplify::SimplifyCfg::new("initial"),
231 &rustc_peek::SanityCheck,
234 body.ensure_predecessors();
235 tcx.alloc_steal_mir(body)
241 ) -> (&'tcx Steal<BodyAndCache<'tcx>>, &'tcx Steal<IndexVec<Promoted, BodyAndCache<'tcx>>>) {
242 // Ensure that we compute the `mir_const_qualif` for constants at
243 // this point, before we steal the mir-const result.
244 let _ = tcx.mir_const_qualif(def_id);
246 let mut body = tcx.mir_const(def_id).steal();
247 let promote_pass = promote_consts::PromoteTemps::default();
251 InstanceDef::Item(def_id),
255 // What we need to run borrowck etc.
257 &simplify::SimplifyCfg::new("qualify-consts"),
261 let promoted = promote_pass.promoted_fragments.into_inner();
262 (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
265 fn run_optimization_passes<'tcx>(
267 body: &mut BodyAndCache<'tcx>,
269 promoted: Option<Promoted>,
274 InstanceDef::Item(def_id),
278 // Remove all things only needed by analysis
279 &no_landing_pads::NoLandingPads::new(tcx),
280 &simplify_branches::SimplifyBranches::new("initial"),
281 &remove_noop_landing_pads::RemoveNoopLandingPads,
282 &cleanup_post_borrowck::CleanupNonCodegenStatements,
283 &simplify::SimplifyCfg::new("early-opt"),
284 // These next passes must be executed together
285 &add_call_guards::CriticalCallEdges,
286 &elaborate_drops::ElaborateDrops,
287 &no_landing_pads::NoLandingPads::new(tcx),
288 // AddMovesForPackedDrops needs to run after drop
290 &add_moves_for_packed_drops::AddMovesForPackedDrops,
291 // AddRetag needs to run after ElaborateDrops, and it needs
292 // an AllCallEdges pass right before it. Otherwise it should
293 // run fairly late, but before optimizations begin.
294 &add_call_guards::AllCallEdges,
295 &add_retag::AddRetag,
296 &simplify::SimplifyCfg::new("elaborate-drops"),
297 // No lifetime analysis based on borrowing can be done from here on out.
299 // From here on out, regions are gone.
300 &erase_regions::EraseRegions,
301 // Optimizations begin.
302 &unreachable_prop::UnreachablePropagation,
303 &uninhabited_enum_branching::UninhabitedEnumBranching,
304 &simplify::SimplifyCfg::new("after-uninhabited-enum-branching"),
306 // Lowering generator control-flow and variables
307 // has to happen before we do anything else to them.
308 &generator::StateTransform,
309 &instcombine::InstCombine,
310 &const_prop::ConstProp,
311 &simplify_branches::SimplifyBranches::new("after-const-prop"),
312 &deaggregator::Deaggregator,
313 ©_prop::CopyPropagation,
314 &simplify_branches::SimplifyBranches::new("after-copy-prop"),
315 &remove_noop_landing_pads::RemoveNoopLandingPads,
316 &simplify::SimplifyCfg::new("after-remove-noop-landing-pads"),
317 &simplify_try::SimplifyArmIdentity,
318 &simplify_try::SimplifyBranchSame,
319 &simplify::SimplifyCfg::new("final"),
320 &simplify::SimplifyLocals,
321 &add_call_guards::CriticalCallEdges,
322 &dump_mir::Marker("PreCodegen"),
327 fn optimized_mir(tcx: TyCtxt<'_>, def_id: DefId) -> &BodyAndCache<'_> {
328 if tcx.is_constructor(def_id) {
329 // There's no reason to run all of the MIR passes on constructors when
330 // we can just output the MIR we want directly. This also saves const
331 // qualification and borrow checking the trouble of special casing
333 return shim::build_adt_ctor(tcx, def_id);
336 // (Mir-)Borrowck uses `mir_validated`, so we have to force it to
337 // execute before we can steal.
338 tcx.ensure().mir_borrowck(def_id);
340 let (body, _) = tcx.mir_validated(def_id);
341 let mut body = body.steal();
342 run_optimization_passes(tcx, &mut body, def_id, None);
343 body.ensure_predecessors();
344 tcx.arena.alloc(body)
347 fn promoted_mir(tcx: TyCtxt<'_>, def_id: DefId) -> &IndexVec<Promoted, BodyAndCache<'_>> {
348 if tcx.is_constructor(def_id) {
349 return tcx.intern_promoted(IndexVec::new());
352 tcx.ensure().mir_borrowck(def_id);
353 let (_, promoted) = tcx.mir_validated(def_id);
354 let mut promoted = promoted.steal();
356 for (p, mut body) in promoted.iter_enumerated_mut() {
357 run_optimization_passes(tcx, &mut body, def_id, Some(p));
358 body.ensure_predecessors();
361 tcx.intern_promoted(promoted)