]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/mod.rs
Changes the type `mir::Mir` into `mir::Body`
[rust.git] / src / librustc_mir / transform / mod.rs
1 use crate::build;
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;
7 use rustc::hir;
8 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
9 use rustc::util::nodemap::DefIdSet;
10 use std::borrow::Cow;
11 use syntax::ast;
12 use syntax_pos::Span;
13
14 pub mod add_retag;
15 pub mod add_moves_for_packed_drops;
16 pub mod cleanup_post_borrowck;
17 pub mod check_unsafety;
18 pub mod simplify_branches;
19 pub mod simplify;
20 pub mod erase_regions;
21 pub mod no_landing_pads;
22 pub mod rustc_peek;
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;
29 pub mod dump_mir;
30 pub mod deaggregator;
31 pub mod instcombine;
32 pub mod copy_prop;
33 pub mod const_prop;
34 pub mod generator;
35 pub mod inline;
36 pub mod lower_128bit;
37 pub mod uniform_array_move_out;
38
39 pub(crate) fn provide(providers: &mut Providers<'_>) {
40     self::qualify_consts::provide(providers);
41     self::check_unsafety::provide(providers);
42     *providers = Providers {
43         mir_keys,
44         mir_built,
45         mir_const,
46         mir_validated,
47         optimized_mir,
48         is_mir_available,
49         ..*providers
50     };
51 }
52
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)
55 }
56
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)
60                       -> &'tcx DefIdSet {
61     assert_eq!(krate, LOCAL_CRATE);
62
63     let mut set = DefIdSet::default();
64
65     // All body-owners have MIR associated with them.
66     set.extend(tcx.body_owners());
67
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,
73     }
74     impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
75         fn visit_variant_data(&mut self,
76                               v: &'tcx hir::VariantData,
77                               _: ast::Name,
78                               _: &'tcx hir::Generics,
79                               _: hir::HirId,
80                               _: Span) {
81             if let hir::VariantData::Tuple(_, hir_id) = *v {
82                 self.set.insert(self.tcx.hir().local_def_id_from_hir_id(hir_id));
83             }
84             intravisit::walk_struct_def(self, v)
85         }
86         fn nested_visit_map<'b>(&'b mut self) -> NestedVisitorMap<'b, 'tcx> {
87             NestedVisitorMap::None
88         }
89     }
90     tcx.hir().krate().visit_all_item_likes(&mut GatherCtors {
91         tcx,
92         set: &mut set,
93     }.as_deep_visitor());
94
95     tcx.arena.alloc(set)
96 }
97
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)
101 }
102
103 /// Where a specific Mir comes from.
104 #[derive(Debug, Copy, Clone)]
105 pub struct MirSource<'tcx> {
106     pub instance: InstanceDef<'tcx>,
107
108     /// If `Some`, this is a promoted rvalue within the parent function.
109     pub promoted: Option<Promoted>,
110 }
111
112 impl<'tcx> MirSource<'tcx> {
113     pub fn item(def_id: DefId) -> Self {
114         MirSource {
115             instance: InstanceDef::Item(def_id),
116             promoted: None
117         }
118     }
119
120     #[inline]
121     pub fn def_id(&self) -> DefId {
122         self.instance.def_id()
123     }
124 }
125
126 /// Generates a default name for the pass based on the name of the
127 /// type `T`.
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..])
132     } else {
133         Cow::from(name)
134     }
135 }
136
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`.
140 pub trait MirPass {
141     fn name<'a>(&'a self) -> Cow<'a, str> {
142         default_name::<Self>()
143     }
144
145     fn run_pass<'a, 'tcx>(&self,
146                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
147                           source: MirSource<'tcx>,
148                           mir: &mut Body<'tcx>);
149 }
150
151 pub fn run_passes(
152     tcx: TyCtxt<'a, 'tcx, 'tcx>,
153     mir: &mut Body<'tcx>,
154     instance: InstanceDef<'tcx>,
155     mir_phase: MirPhase,
156     passes: &[&dyn MirPass],
157 ) {
158     let phase_index = mir_phase.phase_index();
159
160     let run_passes = |mir: &mut Body<'tcx>, promoted| {
161         if mir.phase >= mir_phase {
162             return;
163         }
164
165         let source = MirSource {
166             instance,
167             promoted,
168         };
169         let mut index = 0;
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);
174             };
175             run_hooks(mir, index, false);
176             pass.run_pass(tcx, source, mir);
177             run_hooks(mir, index, true);
178
179             index += 1;
180         };
181
182         for pass in passes {
183             run_pass(*pass);
184         }
185
186         mir.phase = mir_phase;
187     };
188
189     run_passes(mir, None);
190
191     for (index, promoted_mir) in mir.promoted.iter_enumerated_mut() {
192         run_passes(promoted_mir, Some(index));
193
194         //Let's make sure we don't miss any nested instances
195         assert!(promoted_mir.promoted.is_empty())
196     }
197 }
198
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);
202
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,
209     ]);
210     tcx.alloc_steal_mir(mir)
211 }
212
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);
219     }
220
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"),
226     ]);
227     tcx.alloc_steal_mir(mir)
228 }
229
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);
234
235     if tcx.use_ast_borrowck() {
236         tcx.ensure().borrowck(def_id);
237     }
238
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,
246
247         &simplify::SimplifyCfg::new("early-opt"),
248
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
254         // elaboration.
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,
261
262         &simplify::SimplifyCfg::new("elaborate-drops"),
263
264         // No lifetime analysis based on borrowing can be done from here on out.
265
266         // From here on out, regions are gone.
267         &erase_regions::EraseRegions,
268
269         &lower_128bit::Lower128Bit,
270
271
272         // Optimizations begin.
273         &uniform_array_move_out::RestoreSubsliceArrayMoveOut,
274         &inline::Inline,
275
276         // Lowering generator control-flow and variables
277         // has to happen before we do anything else to them.
278         &generator::StateTransform,
279
280         &instcombine::InstCombine,
281         &const_prop::ConstProp,
282         &simplify_branches::SimplifyBranches::new("after-const-prop"),
283         &deaggregator::Deaggregator,
284         &copy_prop::CopyPropagation,
285         &simplify_branches::SimplifyBranches::new("after-copy-prop"),
286         &remove_noop_landing_pads::RemoveNoopLandingPads,
287         &simplify::SimplifyCfg::new("final"),
288         &simplify::SimplifyLocals,
289
290         &add_call_guards::CriticalCallEdges,
291         &dump_mir::Marker("PreCodegen"),
292     ]);
293     tcx.alloc_mir(mir)
294 }