]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/mod.rs
Rollup merge of #61750 - tmandry:fix-install, r=Mark-Simulacrum
[rust.git] / src / librustc_mir / transform / mod.rs
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;
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<'tcx>(tcx: TyCtxt<'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<'tcx>(tcx: TyCtxt<'tcx, 'tcx>, krate: CrateNum) -> &'tcx DefIdSet {
60     assert_eq!(krate, LOCAL_CRATE);
61
62     let mut set = DefIdSet::default();
63
64     // All body-owners have MIR associated with them.
65     set.extend(tcx.body_owners());
66
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,
72     }
73     impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
74         fn visit_variant_data(&mut self,
75                               v: &'tcx hir::VariantData,
76                               _: ast::Name,
77                               _: &'tcx hir::Generics,
78                               _: hir::HirId,
79                               _: Span) {
80             if let hir::VariantData::Tuple(_, hir_id) = *v {
81                 self.set.insert(self.tcx.hir().local_def_id_from_hir_id(hir_id));
82             }
83             intravisit::walk_struct_def(self, v)
84         }
85         fn nested_visit_map<'b>(&'b mut self) -> NestedVisitorMap<'b, 'tcx> {
86             NestedVisitorMap::None
87         }
88     }
89     tcx.hir().krate().visit_all_item_likes(&mut GatherCtors {
90         tcx,
91         set: &mut set,
92     }.as_deep_visitor());
93
94     tcx.arena.alloc(set)
95 }
96
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)
100 }
101
102 /// Where a specific `mir::Body` comes from.
103 #[derive(Debug, Copy, Clone)]
104 pub struct MirSource<'tcx> {
105     pub instance: InstanceDef<'tcx>,
106
107     /// If `Some`, this is a promoted rvalue within the parent function.
108     pub promoted: Option<Promoted>,
109 }
110
111 impl<'tcx> MirSource<'tcx> {
112     pub fn item(def_id: DefId) -> Self {
113         MirSource {
114             instance: InstanceDef::Item(def_id),
115             promoted: None
116         }
117     }
118
119     #[inline]
120     pub fn def_id(&self) -> DefId {
121         self.instance.def_id()
122     }
123 }
124
125 /// Generates a default name for the pass based on the name of the
126 /// type `T`.
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..])
131     } else {
132         Cow::from(name)
133     }
134 }
135
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`.
139 pub trait MirPass {
140     fn name<'a>(&'a self) -> Cow<'a, str> {
141         default_name::<Self>()
142     }
143
144     fn run_pass<'tcx>(
145         &self,
146         tcx: TyCtxt<'tcx, 'tcx>,
147         source: MirSource<'tcx>,
148         body: &mut Body<'tcx>,
149     );
150 }
151
152 pub fn run_passes(
153     tcx: TyCtxt<'tcx, 'tcx>,
154     body: &mut Body<'tcx>,
155     instance: InstanceDef<'tcx>,
156     mir_phase: MirPhase,
157     passes: &[&dyn MirPass],
158 ) {
159     let phase_index = mir_phase.phase_index();
160
161     let run_passes = |body: &mut Body<'tcx>, promoted| {
162         if body.phase >= mir_phase {
163             return;
164         }
165
166         let source = MirSource {
167             instance,
168             promoted,
169         };
170         let mut index = 0;
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);
175             };
176             run_hooks(body, index, false);
177             pass.run_pass(tcx, source, body);
178             run_hooks(body, index, true);
179
180             index += 1;
181         };
182
183         for pass in passes {
184             run_pass(*pass);
185         }
186
187         body.phase = mir_phase;
188     };
189
190     run_passes(body, None);
191
192     for (index, promoted_body) in body.promoted.iter_enumerated_mut() {
193         run_passes(promoted_body, Some(index));
194
195         //Let's make sure we don't miss any nested instances
196         assert!(promoted_body.promoted.is_empty())
197     }
198 }
199
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);
203
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,
210     ]);
211     tcx.alloc_steal_mir(body)
212 }
213
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);
220     }
221
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"),
227     ]);
228     tcx.alloc_steal_mir(body)
229 }
230
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
236         // constructors.
237         return shim::build_adt_ctor(tcx, def_id);
238     }
239
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);
243
244     if tcx.use_ast_borrowck() {
245         tcx.ensure().borrowck(def_id);
246     }
247
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,
255
256         &simplify::SimplifyCfg::new("early-opt"),
257
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
263         // elaboration.
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,
270
271         &simplify::SimplifyCfg::new("elaborate-drops"),
272
273         // No lifetime analysis based on borrowing can be done from here on out.
274
275         // From here on out, regions are gone.
276         &erase_regions::EraseRegions,
277
278         &lower_128bit::Lower128Bit,
279
280
281         // Optimizations begin.
282         &uniform_array_move_out::RestoreSubsliceArrayMoveOut,
283         &inline::Inline,
284
285         // Lowering generator control-flow and variables
286         // has to happen before we do anything else to them.
287         &generator::StateTransform,
288
289         &instcombine::InstCombine,
290         &const_prop::ConstProp,
291         &simplify_branches::SimplifyBranches::new("after-const-prop"),
292         &deaggregator::Deaggregator,
293         &copy_prop::CopyPropagation,
294         &simplify_branches::SimplifyBranches::new("after-copy-prop"),
295         &remove_noop_landing_pads::RemoveNoopLandingPads,
296         &simplify::SimplifyCfg::new("final"),
297         &simplify::SimplifyLocals,
298
299         &add_call_guards::CriticalCallEdges,
300         &dump_mir::Marker("PreCodegen"),
301     ]);
302     tcx.arena.alloc(body)
303 }