1 use crate::{build, shim};
2 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
3 use rustc::mir::{Body, MirPhase, Promoted};
4 use rustc::ty::{TyCtxt, InstanceDef};
5 use rustc::ty::query::Providers;
6 use rustc::ty::steal::Steal;
8 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
9 use rustc::util::nodemap::DefIdSet;
15 pub mod add_moves_for_packed_drops;
16 pub mod cleanup_post_borrowck;
17 pub mod check_unsafety;
18 pub mod simplify_branches;
20 pub mod erase_regions;
21 pub mod no_landing_pads;
23 pub mod elaborate_drops;
24 pub mod add_call_guards;
25 pub mod promote_consts;
26 pub mod qualify_consts;
27 pub mod qualify_min_const_fn;
28 pub mod remove_noop_landing_pads;
37 pub mod uniform_array_move_out;
39 pub(crate) fn provide(providers: &mut Providers<'_>) {
40 self::qualify_consts::provide(providers);
41 self::check_unsafety::provide(providers);
42 *providers = Providers {
53 fn is_mir_available<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
54 tcx.mir_keys(def_id.krate).contains(&def_id)
57 /// Finds the full set of `DefId`s within the current crate that have
58 /// MIR associated with them.
59 fn mir_keys<'tcx>(tcx: TyCtxt<'tcx>, krate: CrateNum) -> &'tcx DefIdSet {
60 assert_eq!(krate, LOCAL_CRATE);
62 let mut set = DefIdSet::default();
64 // All body-owners have MIR associated with them.
65 set.extend(tcx.body_owners());
67 // Additionally, tuple struct/variant constructors have MIR, but
68 // they don't have a BodyId, so we need to build them separately.
69 struct GatherCtors<'a, 'tcx> {
71 set: &'a mut DefIdSet,
73 impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
74 fn visit_variant_data(&mut self,
75 v: &'tcx hir::VariantData,
77 _: &'tcx hir::Generics,
80 if let hir::VariantData::Tuple(_, hir_id) = *v {
81 self.set.insert(self.tcx.hir().local_def_id_from_hir_id(hir_id));
83 intravisit::walk_struct_def(self, v)
85 fn nested_visit_map<'b>(&'b mut self) -> NestedVisitorMap<'b, 'tcx> {
86 NestedVisitorMap::None
89 tcx.hir().krate().visit_all_item_likes(&mut GatherCtors {
97 fn mir_built<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Steal<Body<'tcx>> {
98 let mir = build::mir_build(tcx, def_id);
99 tcx.alloc_steal_mir(mir)
102 /// Where a specific `mir::Body` comes from.
103 #[derive(Debug, Copy, Clone)]
104 pub struct MirSource<'tcx> {
105 pub instance: InstanceDef<'tcx>,
107 /// If `Some`, this is a promoted rvalue within the parent function.
108 pub promoted: Option<Promoted>,
111 impl<'tcx> MirSource<'tcx> {
112 pub fn item(def_id: DefId) -> Self {
114 instance: InstanceDef::Item(def_id),
120 pub fn def_id(&self) -> DefId {
121 self.instance.def_id()
125 /// Generates a default name for the pass based on the name of the
127 pub fn default_name<T: ?Sized>() -> Cow<'static, str> {
128 let name = unsafe { ::std::intrinsics::type_name::<T>() };
129 if let Some(tail) = name.rfind(":") {
130 Cow::from(&name[tail+1..])
136 /// A streamlined trait that you can implement to create a pass; the
137 /// pass will be named after the type, and it will consist of a main
138 /// loop that goes over each available MIR and applies `run_pass`.
140 fn name<'a>(&'a self) -> Cow<'a, str> {
141 default_name::<Self>()
144 fn run_pass<'tcx>(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>);
149 body: &mut Body<'tcx>,
150 instance: InstanceDef<'tcx>,
152 passes: &[&dyn MirPass],
154 let phase_index = mir_phase.phase_index();
156 let run_passes = |body: &mut Body<'tcx>, promoted| {
157 if body.phase >= mir_phase {
161 let source = MirSource {
166 let mut run_pass = |pass: &dyn MirPass| {
167 let run_hooks = |body: &_, index, is_after| {
168 dump_mir::on_mir_pass(tcx, &format_args!("{:03}-{:03}", phase_index, index),
169 &pass.name(), source, body, is_after);
171 run_hooks(body, index, false);
172 pass.run_pass(tcx, source, body);
173 run_hooks(body, index, true);
182 body.phase = mir_phase;
185 run_passes(body, None);
187 for (index, promoted_body) in body.promoted.iter_enumerated_mut() {
188 run_passes(promoted_body, Some(index));
190 //Let's make sure we don't miss any nested instances
191 assert!(promoted_body.promoted.is_empty())
195 fn mir_const<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Steal<Body<'tcx>> {
196 // Unsafety check uses the raw mir, so make sure it is run
197 let _ = tcx.unsafety_check_result(def_id);
199 let mut body = tcx.mir_built(def_id).steal();
200 run_passes(tcx, &mut body, InstanceDef::Item(def_id), MirPhase::Const, &[
201 // What we need to do constant evaluation.
202 &simplify::SimplifyCfg::new("initial"),
203 &rustc_peek::SanityCheck,
204 &uniform_array_move_out::UniformArrayMoveOut,
206 tcx.alloc_steal_mir(body)
209 fn mir_validated(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Steal<Body<'tcx>> {
210 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
211 if let hir::BodyOwnerKind::Const = tcx.hir().body_owner_kind(hir_id) {
212 // Ensure that we compute the `mir_const_qualif` for constants at
213 // this point, before we steal the mir-const result.
214 let _ = tcx.mir_const_qualif(def_id);
217 let mut body = tcx.mir_const(def_id).steal();
218 run_passes(tcx, &mut body, InstanceDef::Item(def_id), MirPhase::Validated, &[
219 // What we need to run borrowck etc.
220 &qualify_consts::QualifyAndPromoteConstants,
221 &simplify::SimplifyCfg::new("qualify-consts"),
223 tcx.alloc_steal_mir(body)
226 fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Body<'tcx> {
227 if tcx.is_constructor(def_id) {
228 // There's no reason to run all of the MIR passes on constructors when
229 // we can just output the MIR we want directly. This also saves const
230 // qualification and borrow checking the trouble of special casing
232 return shim::build_adt_ctor(tcx, def_id);
235 // (Mir-)Borrowck uses `mir_validated`, so we have to force it to
236 // execute before we can steal.
237 tcx.ensure().mir_borrowck(def_id);
239 if tcx.use_ast_borrowck() {
240 tcx.ensure().borrowck(def_id);
243 let mut body = tcx.mir_validated(def_id).steal();
244 run_passes(tcx, &mut body, InstanceDef::Item(def_id), MirPhase::Optimized, &[
245 // Remove all things only needed by analysis
246 &no_landing_pads::NoLandingPads,
247 &simplify_branches::SimplifyBranches::new("initial"),
248 &remove_noop_landing_pads::RemoveNoopLandingPads,
249 &cleanup_post_borrowck::CleanupNonCodegenStatements,
251 &simplify::SimplifyCfg::new("early-opt"),
253 // These next passes must be executed together
254 &add_call_guards::CriticalCallEdges,
255 &elaborate_drops::ElaborateDrops,
256 &no_landing_pads::NoLandingPads,
257 // AddMovesForPackedDrops needs to run after drop
259 &add_moves_for_packed_drops::AddMovesForPackedDrops,
260 // AddRetag needs to run after ElaborateDrops, and it needs
261 // an AllCallEdges pass right before it. Otherwise it should
262 // run fairly late, but before optimizations begin.
263 &add_call_guards::AllCallEdges,
264 &add_retag::AddRetag,
266 &simplify::SimplifyCfg::new("elaborate-drops"),
268 // No lifetime analysis based on borrowing can be done from here on out.
270 // From here on out, regions are gone.
271 &erase_regions::EraseRegions,
273 &lower_128bit::Lower128Bit,
276 // Optimizations begin.
277 &uniform_array_move_out::RestoreSubsliceArrayMoveOut,
280 // Lowering generator control-flow and variables
281 // has to happen before we do anything else to them.
282 &generator::StateTransform,
284 &instcombine::InstCombine,
285 &const_prop::ConstProp,
286 &simplify_branches::SimplifyBranches::new("after-const-prop"),
287 &deaggregator::Deaggregator,
288 ©_prop::CopyPropagation,
289 &simplify_branches::SimplifyBranches::new("after-copy-prop"),
290 &remove_noop_landing_pads::RemoveNoopLandingPads,
291 &simplify::SimplifyCfg::new("final"),
292 &simplify::SimplifyLocals,
294 &add_call_guards::CriticalCallEdges,
295 &dump_mir::Marker("PreCodegen"),
297 tcx.arena.alloc(body)