1 use crate::{build, shim};
2 use rustc_data_structures::indexed_vec::IndexVec;
3 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
4 use rustc::mir::{Body, MirPhase, Promoted};
5 use rustc::ty::{TyCtxt, InstanceDef};
6 use rustc::ty::query::Providers;
7 use rustc::ty::steal::Steal;
9 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
10 use rustc::util::nodemap::DefIdSet;
16 pub mod add_moves_for_packed_drops;
17 pub mod cleanup_post_borrowck;
18 pub mod check_unsafety;
19 pub mod simplify_branches;
21 pub mod erase_regions;
22 pub mod no_landing_pads;
24 pub mod elaborate_drops;
25 pub mod add_call_guards;
26 pub mod promote_consts;
27 pub mod qualify_consts;
28 pub mod qualify_min_const_fn;
29 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 {
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(&mut self,
76 v: &'tcx hir::VariantData,
78 _: &'tcx hir::Generics,
81 if let hir::VariantData::Tuple(_, hir_id) = *v {
82 self.set.insert(self.tcx.hir().local_def_id(hir_id));
84 intravisit::walk_struct_def(self, v)
86 fn nested_visit_map<'b>(&'b mut self) -> NestedVisitorMap<'b, 'tcx> {
87 NestedVisitorMap::None
90 tcx.hir().krate().visit_all_item_likes(&mut GatherCtors {
98 fn mir_built(tcx: TyCtxt<'_>, def_id: DefId) -> &Steal<Body<'_>> {
99 let mir = build::mir_build(tcx, def_id);
100 tcx.alloc_steal_mir(mir)
103 /// Where a specific `mir::Body` comes from.
104 #[derive(Debug, Copy, Clone)]
105 pub struct MirSource<'tcx> {
106 pub instance: InstanceDef<'tcx>,
108 /// If `Some`, this is a promoted rvalue within the parent function.
109 pub promoted: Option<Promoted>,
112 impl<'tcx> MirSource<'tcx> {
113 pub fn item(def_id: DefId) -> Self {
115 instance: InstanceDef::Item(def_id),
121 pub fn def_id(&self) -> DefId {
122 self.instance.def_id()
126 /// Generates a default name for the pass based on the name of the
128 pub fn default_name<T: ?Sized>() -> Cow<'static, str> {
129 let name = ::std::any::type_name::<T>();
130 if let Some(tail) = name.rfind(":") {
131 Cow::from(&name[tail+1..])
137 /// A streamlined trait that you can implement to create a pass; the
138 /// pass will be named after the type, and it will consist of a main
139 /// loop that goes over each available MIR and applies `run_pass`.
141 fn name(&self) -> Cow<'_, str> {
142 default_name::<Self>()
145 fn run_pass<'tcx>(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>);
150 body: &mut Body<'tcx>,
151 instance: InstanceDef<'tcx>,
153 passes: &[&dyn MirPass],
155 let phase_index = mir_phase.phase_index();
157 let run_passes = |body: &mut Body<'tcx>, promoted| {
158 if body.phase >= mir_phase {
162 let source = MirSource {
167 let mut run_pass = |pass: &dyn MirPass| {
168 let run_hooks = |body: &_, index, is_after| {
169 dump_mir::on_mir_pass(tcx, &format_args!("{:03}-{:03}", phase_index, index),
170 &pass.name(), source, body, is_after);
172 run_hooks(body, index, false);
173 pass.run_pass(tcx, source, body);
174 run_hooks(body, index, true);
183 body.phase = mir_phase;
186 run_passes(body, None);
188 for (index, promoted_body) in body.promoted.iter_enumerated_mut() {
189 run_passes(promoted_body, Some(index));
191 //Let's make sure we don't miss any nested instances
192 assert!(promoted_body.promoted.is_empty())
196 fn mir_const(tcx: TyCtxt<'_>, def_id: DefId) -> &Steal<Body<'_>> {
197 // Unsafety check uses the raw mir, so make sure it is run
198 let _ = tcx.unsafety_check_result(def_id);
200 let mut body = tcx.mir_built(def_id).steal();
201 run_passes(tcx, &mut body, InstanceDef::Item(def_id), MirPhase::Const, &[
202 // What we need to do constant evaluation.
203 &simplify::SimplifyCfg::new("initial"),
204 &rustc_peek::SanityCheck,
205 &uniform_array_move_out::UniformArrayMoveOut,
207 tcx.alloc_steal_mir(body)
210 fn mir_validated(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Steal<Body<'tcx>> {
211 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
212 if let hir::BodyOwnerKind::Const = tcx.hir().body_owner_kind(hir_id) {
213 // Ensure that we compute the `mir_const_qualif` for constants at
214 // this point, before we steal the mir-const result.
215 let _ = tcx.mir_const_qualif(def_id);
218 let mut body = tcx.mir_const(def_id).steal();
219 run_passes(tcx, &mut body, InstanceDef::Item(def_id), MirPhase::Validated, &[
220 // What we need to run borrowck etc.
221 &qualify_consts::QualifyAndPromoteConstants,
222 &simplify::SimplifyCfg::new("qualify-consts"),
224 tcx.alloc_steal_mir(body)
227 fn optimized_mir(tcx: TyCtxt<'_>, def_id: DefId) -> &Body<'_> {
228 if tcx.is_constructor(def_id) {
229 // There's no reason to run all of the MIR passes on constructors when
230 // we can just output the MIR we want directly. This also saves const
231 // qualification and borrow checking the trouble of special casing
233 return shim::build_adt_ctor(tcx, def_id);
236 // (Mir-)Borrowck uses `mir_validated`, so we have to force it to
237 // execute before we can steal.
238 tcx.ensure().mir_borrowck(def_id);
240 if tcx.use_ast_borrowck() {
241 tcx.ensure().borrowck(def_id);
244 let mut body = tcx.mir_validated(def_id).steal();
245 run_passes(tcx, &mut body, InstanceDef::Item(def_id), MirPhase::Optimized, &[
246 // Remove all things only needed by analysis
247 &no_landing_pads::NoLandingPads,
248 &simplify_branches::SimplifyBranches::new("initial"),
249 &remove_noop_landing_pads::RemoveNoopLandingPads,
250 &cleanup_post_borrowck::CleanupNonCodegenStatements,
252 &simplify::SimplifyCfg::new("early-opt"),
254 // These next passes must be executed together
255 &add_call_guards::CriticalCallEdges,
256 &elaborate_drops::ElaborateDrops,
257 &no_landing_pads::NoLandingPads,
258 // AddMovesForPackedDrops needs to run after drop
260 &add_moves_for_packed_drops::AddMovesForPackedDrops,
261 // AddRetag needs to run after ElaborateDrops, and it needs
262 // an AllCallEdges pass right before it. Otherwise it should
263 // run fairly late, but before optimizations begin.
264 &add_call_guards::AllCallEdges,
265 &add_retag::AddRetag,
267 &simplify::SimplifyCfg::new("elaborate-drops"),
269 // No lifetime analysis based on borrowing can be done from here on out.
271 // From here on out, regions are gone.
272 &erase_regions::EraseRegions,
275 // Optimizations begin.
276 &uniform_array_move_out::RestoreSubsliceArrayMoveOut,
279 // Lowering generator control-flow and variables
280 // has to happen before we do anything else to them.
281 &generator::StateTransform,
283 &instcombine::InstCombine,
284 &const_prop::ConstProp,
285 &simplify_branches::SimplifyBranches::new("after-const-prop"),
286 &deaggregator::Deaggregator,
287 ©_prop::CopyPropagation,
288 &simplify_branches::SimplifyBranches::new("after-copy-prop"),
289 &remove_noop_landing_pads::RemoveNoopLandingPads,
290 &simplify::SimplifyCfg::new("final"),
291 &simplify::SimplifyLocals,
293 &add_call_guards::CriticalCallEdges,
294 &dump_mir::Marker("PreCodegen"),
296 tcx.arena.alloc(body)
299 fn promoted_mir<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
300 let body = tcx.optimized_mir(def_id);