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, '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, '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: 'a> {
70 tcx: TyCtxt<'tcx, '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, '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>()
146 tcx: TyCtxt<'tcx, 'tcx>,
147 source: MirSource<'tcx>,
148 body: &mut Body<'tcx>,
153 tcx: TyCtxt<'tcx, 'tcx>,
154 body: &mut Body<'tcx>,
155 instance: InstanceDef<'tcx>,
157 passes: &[&dyn MirPass],
159 let phase_index = mir_phase.phase_index();
161 let run_passes = |body: &mut Body<'tcx>, promoted| {
162 if body.phase >= mir_phase {
166 let source = MirSource {
171 let mut run_pass = |pass: &dyn MirPass| {
172 let run_hooks = |body: &_, index, is_after| {
173 dump_mir::on_mir_pass(tcx, &format_args!("{:03}-{:03}", phase_index, index),
174 &pass.name(), source, body, is_after);
176 run_hooks(body, index, false);
177 pass.run_pass(tcx, source, body);
178 run_hooks(body, index, true);
187 body.phase = mir_phase;
190 run_passes(body, None);
192 for (index, promoted_body) in body.promoted.iter_enumerated_mut() {
193 run_passes(promoted_body, Some(index));
195 //Let's make sure we don't miss any nested instances
196 assert!(promoted_body.promoted.is_empty())
200 fn mir_const<'tcx>(tcx: TyCtxt<'tcx, 'tcx>, def_id: DefId) -> &'tcx Steal<Body<'tcx>> {
201 // Unsafety check uses the raw mir, so make sure it is run
202 let _ = tcx.unsafety_check_result(def_id);
204 let mut body = tcx.mir_built(def_id).steal();
205 run_passes(tcx, &mut body, InstanceDef::Item(def_id), MirPhase::Const, &[
206 // What we need to do constant evaluation.
207 &simplify::SimplifyCfg::new("initial"),
208 &rustc_peek::SanityCheck,
209 &uniform_array_move_out::UniformArrayMoveOut,
211 tcx.alloc_steal_mir(body)
214 fn mir_validated(tcx: TyCtxt<'tcx, 'tcx>, def_id: DefId) -> &'tcx Steal<Body<'tcx>> {
215 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
216 if let hir::BodyOwnerKind::Const = tcx.hir().body_owner_kind_by_hir_id(hir_id) {
217 // Ensure that we compute the `mir_const_qualif` for constants at
218 // this point, before we steal the mir-const result.
219 let _ = tcx.mir_const_qualif(def_id);
222 let mut body = tcx.mir_const(def_id).steal();
223 run_passes(tcx, &mut body, InstanceDef::Item(def_id), MirPhase::Validated, &[
224 // What we need to run borrowck etc.
225 &qualify_consts::QualifyAndPromoteConstants,
226 &simplify::SimplifyCfg::new("qualify-consts"),
228 tcx.alloc_steal_mir(body)
231 fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx, 'tcx>, def_id: DefId) -> &'tcx Body<'tcx> {
232 if tcx.is_constructor(def_id) {
233 // There's no reason to run all of the MIR passes on constructors when
234 // we can just output the MIR we want directly. This also saves const
235 // qualification and borrow checking the trouble of special casing
237 return shim::build_adt_ctor(tcx, def_id);
240 // (Mir-)Borrowck uses `mir_validated`, so we have to force it to
241 // execute before we can steal.
242 tcx.ensure().mir_borrowck(def_id);
244 if tcx.use_ast_borrowck() {
245 tcx.ensure().borrowck(def_id);
248 let mut body = tcx.mir_validated(def_id).steal();
249 run_passes(tcx, &mut body, InstanceDef::Item(def_id), MirPhase::Optimized, &[
250 // Remove all things only needed by analysis
251 &no_landing_pads::NoLandingPads,
252 &simplify_branches::SimplifyBranches::new("initial"),
253 &remove_noop_landing_pads::RemoveNoopLandingPads,
254 &cleanup_post_borrowck::CleanupNonCodegenStatements,
256 &simplify::SimplifyCfg::new("early-opt"),
258 // These next passes must be executed together
259 &add_call_guards::CriticalCallEdges,
260 &elaborate_drops::ElaborateDrops,
261 &no_landing_pads::NoLandingPads,
262 // AddMovesForPackedDrops needs to run after drop
264 &add_moves_for_packed_drops::AddMovesForPackedDrops,
265 // AddRetag needs to run after ElaborateDrops, and it needs
266 // an AllCallEdges pass right before it. Otherwise it should
267 // run fairly late, but before optimizations begin.
268 &add_call_guards::AllCallEdges,
269 &add_retag::AddRetag,
271 &simplify::SimplifyCfg::new("elaborate-drops"),
273 // No lifetime analysis based on borrowing can be done from here on out.
275 // From here on out, regions are gone.
276 &erase_regions::EraseRegions,
278 &lower_128bit::Lower128Bit,
281 // Optimizations begin.
282 &uniform_array_move_out::RestoreSubsliceArrayMoveOut,
285 // Lowering generator control-flow and variables
286 // has to happen before we do anything else to them.
287 &generator::StateTransform,
289 &instcombine::InstCombine,
290 &const_prop::ConstProp,
291 &simplify_branches::SimplifyBranches::new("after-const-prop"),
292 &deaggregator::Deaggregator,
293 ©_prop::CopyPropagation,
294 &simplify_branches::SimplifyBranches::new("after-copy-prop"),
295 &remove_noop_landing_pads::RemoveNoopLandingPads,
296 &simplify::SimplifyCfg::new("final"),
297 &simplify::SimplifyLocals,
299 &add_call_guards::CriticalCallEdges,
300 &dump_mir::Marker("PreCodegen"),
302 tcx.arena.alloc(body)