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<'a, 'tcx>(tcx: TyCtxt<'a, '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<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, krate: CrateNum)
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: 'a> {
71 tcx: TyCtxt<'a, 'tcx, '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_from_hir_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<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx Steal<Body<'tcx>> {
99 let mir = build::mir_build(tcx, def_id);
100 tcx.alloc_steal_mir(mir)
103 /// Where a specific Mir 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 = unsafe { ::std::intrinsics::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<'a>(&'a self) -> Cow<'a, str> {
142 default_name::<Self>()
145 fn run_pass<'a, 'tcx>(&self,
146 tcx: TyCtxt<'a, 'tcx, 'tcx>,
147 source: MirSource<'tcx>,
148 mir: &mut Body<'tcx>);
152 tcx: TyCtxt<'a, 'tcx, 'tcx>,
153 mir: &mut Body<'tcx>,
154 instance: InstanceDef<'tcx>,
156 passes: &[&dyn MirPass],
158 let phase_index = mir_phase.phase_index();
160 let run_passes = |mir: &mut Body<'tcx>, promoted| {
161 if mir.phase >= mir_phase {
165 let source = MirSource {
170 let mut run_pass = |pass: &dyn MirPass| {
171 let run_hooks = |mir: &_, index, is_after| {
172 dump_mir::on_mir_pass(tcx, &format_args!("{:03}-{:03}", phase_index, index),
173 &pass.name(), source, mir, is_after);
175 run_hooks(mir, index, false);
176 pass.run_pass(tcx, source, mir);
177 run_hooks(mir, index, true);
186 mir.phase = mir_phase;
189 run_passes(mir, None);
191 for (index, promoted_mir) in mir.promoted.iter_enumerated_mut() {
192 run_passes(promoted_mir, Some(index));
194 //Let's make sure we don't miss any nested instances
195 assert!(promoted_mir.promoted.is_empty())
199 fn mir_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx Steal<Body<'tcx>> {
200 // Unsafety check uses the raw mir, so make sure it is run
201 let _ = tcx.unsafety_check_result(def_id);
203 let mut mir = tcx.mir_built(def_id).steal();
204 run_passes(tcx, &mut mir, InstanceDef::Item(def_id), MirPhase::Const, &[
205 // What we need to do constant evaluation.
206 &simplify::SimplifyCfg::new("initial"),
207 &rustc_peek::SanityCheck,
208 &uniform_array_move_out::UniformArrayMoveOut,
210 tcx.alloc_steal_mir(mir)
213 fn mir_validated<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx Steal<Body<'tcx>> {
214 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
215 if let hir::BodyOwnerKind::Const = tcx.hir().body_owner_kind_by_hir_id(hir_id) {
216 // Ensure that we compute the `mir_const_qualif` for constants at
217 // this point, before we steal the mir-const result.
218 let _ = tcx.mir_const_qualif(def_id);
221 let mut mir = tcx.mir_const(def_id).steal();
222 run_passes(tcx, &mut mir, InstanceDef::Item(def_id), MirPhase::Validated, &[
223 // What we need to run borrowck etc.
224 &qualify_consts::QualifyAndPromoteConstants,
225 &simplify::SimplifyCfg::new("qualify-consts"),
227 tcx.alloc_steal_mir(mir)
230 fn optimized_mir<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx Body<'tcx> {
231 // (Mir-)Borrowck uses `mir_validated`, so we have to force it to
232 // execute before we can steal.
233 tcx.ensure().mir_borrowck(def_id);
235 if tcx.use_ast_borrowck() {
236 tcx.ensure().borrowck(def_id);
239 let mut mir = tcx.mir_validated(def_id).steal();
240 run_passes(tcx, &mut mir, InstanceDef::Item(def_id), MirPhase::Optimized, &[
241 // Remove all things only needed by analysis
242 &no_landing_pads::NoLandingPads,
243 &simplify_branches::SimplifyBranches::new("initial"),
244 &remove_noop_landing_pads::RemoveNoopLandingPads,
245 &cleanup_post_borrowck::CleanupNonCodegenStatements,
247 &simplify::SimplifyCfg::new("early-opt"),
249 // These next passes must be executed together
250 &add_call_guards::CriticalCallEdges,
251 &elaborate_drops::ElaborateDrops,
252 &no_landing_pads::NoLandingPads,
253 // AddMovesForPackedDrops needs to run after drop
255 &add_moves_for_packed_drops::AddMovesForPackedDrops,
256 // AddRetag needs to run after ElaborateDrops, and it needs
257 // an AllCallEdges pass right before it. Otherwise it should
258 // run fairly late, but before optimizations begin.
259 &add_call_guards::AllCallEdges,
260 &add_retag::AddRetag,
262 &simplify::SimplifyCfg::new("elaborate-drops"),
264 // No lifetime analysis based on borrowing can be done from here on out.
266 // From here on out, regions are gone.
267 &erase_regions::EraseRegions,
269 &lower_128bit::Lower128Bit,
272 // Optimizations begin.
273 &uniform_array_move_out::RestoreSubsliceArrayMoveOut,
276 // Lowering generator control-flow and variables
277 // has to happen before we do anything else to them.
278 &generator::StateTransform,
280 &instcombine::InstCombine,
281 &const_prop::ConstProp,
282 &simplify_branches::SimplifyBranches::new("after-const-prop"),
283 &deaggregator::Deaggregator,
284 ©_prop::CopyPropagation,
285 &simplify_branches::SimplifyBranches::new("after-copy-prop"),
286 &remove_noop_landing_pads::RemoveNoopLandingPads,
287 &simplify::SimplifyCfg::new("final"),
288 &simplify::SimplifyLocals,
290 &add_call_guards::CriticalCallEdges,
291 &dump_mir::Marker("PreCodegen"),