]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/mod.rs
e933a6cd700dcb074c80e3e0af563154211751e8
[rust.git] / src / librustc_mir / transform / mod.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use borrow_check::nll::type_check;
12 use build;
13 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
14 use rustc::mir::{Mir, Promoted};
15 use rustc::ty::TyCtxt;
16 use rustc::ty::maps::Providers;
17 use rustc::ty::steal::Steal;
18 use rustc::hir;
19 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
20 use rustc::util::nodemap::DefIdSet;
21 use rustc_data_structures::sync::Lrc;
22 use std::borrow::Cow;
23 use syntax::ast;
24 use syntax_pos::Span;
25
26 pub mod add_validation;
27 pub mod add_moves_for_packed_drops;
28 pub mod clean_end_regions;
29 pub mod check_unsafety;
30 pub mod simplify_branches;
31 pub mod simplify;
32 pub mod erase_regions;
33 pub mod no_landing_pads;
34 pub mod rustc_peek;
35 pub mod elaborate_drops;
36 pub mod add_call_guards;
37 pub mod promote_consts;
38 pub mod qualify_consts;
39 pub mod remove_noop_landing_pads;
40 pub mod dump_mir;
41 pub mod deaggregator;
42 pub mod instcombine;
43 pub mod copy_prop;
44 pub mod generator;
45 pub mod inline;
46 pub mod lower_128bit;
47 pub mod uniform_array_move_out;
48
49 pub(crate) fn provide(providers: &mut Providers) {
50     self::qualify_consts::provide(providers);
51     self::check_unsafety::provide(providers);
52     *providers = Providers {
53         mir_keys,
54         mir_built,
55         mir_const,
56         mir_validated,
57         optimized_mir,
58         is_mir_available,
59         ..*providers
60     };
61 }
62
63 fn is_mir_available<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
64     tcx.mir_keys(def_id.krate).contains(&def_id)
65 }
66
67 /// Finds the full set of def-ids within the current crate that have
68 /// MIR associated with them.
69 fn mir_keys<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, krate: CrateNum)
70                       -> Lrc<DefIdSet> {
71     assert_eq!(krate, LOCAL_CRATE);
72
73     let mut set = DefIdSet();
74
75     // All body-owners have MIR associated with them.
76     set.extend(tcx.body_owners());
77
78     // Additionally, tuple struct/variant constructors have MIR, but
79     // they don't have a BodyId, so we need to build them separately.
80     struct GatherCtors<'a, 'tcx: 'a> {
81         tcx: TyCtxt<'a, 'tcx, 'tcx>,
82         set: &'a mut DefIdSet,
83     }
84     impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
85         fn visit_variant_data(&mut self,
86                               v: &'tcx hir::VariantData,
87                               _: ast::Name,
88                               _: &'tcx hir::Generics,
89                               _: ast::NodeId,
90                               _: Span) {
91             if let hir::VariantData::Tuple(_, node_id) = *v {
92                 self.set.insert(self.tcx.hir.local_def_id(node_id));
93             }
94             intravisit::walk_struct_def(self, v)
95         }
96         fn nested_visit_map<'b>(&'b mut self) -> NestedVisitorMap<'b, 'tcx> {
97             NestedVisitorMap::None
98         }
99     }
100     tcx.hir.krate().visit_all_item_likes(&mut GatherCtors {
101         tcx,
102         set: &mut set,
103     }.as_deep_visitor());
104
105     Lrc::new(set)
106 }
107
108 fn mir_built<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx Steal<Mir<'tcx>> {
109     let mir = build::mir_build(tcx, def_id);
110     tcx.alloc_steal_mir(mir)
111 }
112
113 /// Where a specific Mir comes from.
114 #[derive(Debug, Copy, Clone)]
115 pub struct MirSource {
116     pub def_id: DefId,
117
118     /// If `Some`, this is a promoted rvalue within the parent function.
119     pub promoted: Option<Promoted>,
120 }
121
122 impl MirSource {
123     pub fn item(def_id: DefId) -> Self {
124         MirSource {
125             def_id,
126             promoted: None
127         }
128     }
129 }
130
131 /// Generates a default name for the pass based on the name of the
132 /// type `T`.
133 pub fn default_name<T: ?Sized>() -> Cow<'static, str> {
134     let name = unsafe { ::std::intrinsics::type_name::<T>() };
135     if let Some(tail) = name.rfind(":") {
136         Cow::from(&name[tail+1..])
137     } else {
138         Cow::from(name)
139     }
140 }
141
142 /// A streamlined trait that you can implement to create a pass; the
143 /// pass will be named after the type, and it will consist of a main
144 /// loop that goes over each available MIR and applies `run_pass`.
145 pub trait MirPass {
146     fn name<'a>(&'a self) -> Cow<'a, str> {
147         default_name::<Self>()
148     }
149
150     fn run_pass<'a, 'tcx>(&self,
151                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
152                           source: MirSource,
153                           mir: &mut Mir<'tcx>);
154 }
155
156 pub macro run_passes($tcx:ident, $mir:ident, $def_id:ident, $suite_index:expr; $($pass:expr,)*) {{
157     let suite_index: usize = $suite_index;
158     let run_passes = |mir: &mut _, promoted| {
159         let source = MirSource {
160             def_id: $def_id,
161             promoted
162         };
163         let mut index = 0;
164         let mut run_pass = |pass: &MirPass| {
165             let run_hooks = |mir: &_, index, is_after| {
166                 dump_mir::on_mir_pass($tcx, &format_args!("{:03}-{:03}", suite_index, index),
167                                       &pass.name(), source, mir, is_after);
168             };
169             run_hooks(mir, index, false);
170             pass.run_pass($tcx, source, mir);
171             run_hooks(mir, index, true);
172
173             index += 1;
174         };
175         $(run_pass(&$pass);)*
176     };
177
178     run_passes(&mut $mir, None);
179
180     for (index, promoted_mir) in $mir.promoted.iter_enumerated_mut() {
181         run_passes(promoted_mir, Some(index));
182
183         // Let's make sure we don't miss any nested instances
184         assert!(promoted_mir.promoted.is_empty());
185     }
186 }}
187
188 fn mir_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx Steal<Mir<'tcx>> {
189     // Unsafety check uses the raw mir, so make sure it is run
190     let _ = tcx.unsafety_check_result(def_id);
191
192     let mut mir = tcx.mir_built(def_id).steal();
193     run_passes![tcx, mir, def_id, 0;
194         // Remove all `EndRegion` statements that are not involved in borrows.
195         clean_end_regions::CleanEndRegions,
196
197         // What we need to do constant evaluation.
198         simplify::SimplifyCfg::new("initial"),
199         type_check::TypeckMir,
200         rustc_peek::SanityCheck,
201         uniform_array_move_out::UniformArrayMoveOut,
202     ];
203     tcx.alloc_steal_mir(mir)
204 }
205
206 fn mir_validated<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx Steal<Mir<'tcx>> {
207     let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
208     if let hir::BodyOwnerKind::Const = tcx.hir.body_owner_kind(node_id) {
209         // Ensure that we compute the `mir_const_qualif` for constants at
210         // this point, before we steal the mir-const result.
211         let _ = tcx.mir_const_qualif(def_id);
212     }
213
214     let mut mir = tcx.mir_const(def_id).steal();
215     run_passes![tcx, mir, def_id, 1;
216         // What we need to run borrowck etc.
217         qualify_consts::QualifyAndPromoteConstants,
218         simplify::SimplifyCfg::new("qualify-consts"),
219     ];
220     tcx.alloc_steal_mir(mir)
221 }
222
223 fn optimized_mir<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx Mir<'tcx> {
224     // (Mir-)Borrowck uses `mir_validated`, so we have to force it to
225     // execute before we can steal.
226     let _ = tcx.mir_borrowck(def_id);
227     let _ = tcx.borrowck(def_id);
228
229     let mut mir = tcx.mir_validated(def_id).steal();
230     run_passes![tcx, mir, def_id, 2;
231         // Remove all things not needed by analysis
232         no_landing_pads::NoLandingPads,
233         simplify_branches::SimplifyBranches::new("initial"),
234         remove_noop_landing_pads::RemoveNoopLandingPads,
235         simplify::SimplifyCfg::new("early-opt"),
236
237         // These next passes must be executed together
238         add_call_guards::CriticalCallEdges,
239         elaborate_drops::ElaborateDrops,
240         no_landing_pads::NoLandingPads,
241         // AddValidation needs to run after ElaborateDrops and before EraseRegions, and it needs
242         // an AllCallEdges pass right before it.
243         add_call_guards::AllCallEdges,
244         add_validation::AddValidation,
245         // AddMovesForPackedDrops needs to run after drop
246         // elaboration.
247         add_moves_for_packed_drops::AddMovesForPackedDrops,
248
249         simplify::SimplifyCfg::new("elaborate-drops"),
250
251         // No lifetime analysis based on borrowing can be done from here on out.
252
253         // From here on out, regions are gone.
254         erase_regions::EraseRegions,
255
256         lower_128bit::Lower128Bit,
257
258
259         // Optimizations begin.
260         uniform_array_move_out::RestoreSubsliceArrayMoveOut,
261         inline::Inline,
262
263         // Lowering generator control-flow and variables
264         // has to happen before we do anything else to them.
265         generator::StateTransform,
266
267         instcombine::InstCombine,
268         deaggregator::Deaggregator,
269         copy_prop::CopyPropagation,
270         remove_noop_landing_pads::RemoveNoopLandingPads,
271         simplify::SimplifyCfg::new("final"),
272         simplify::SimplifyLocals,
273
274         add_call_guards::CriticalCallEdges,
275         dump_mir::Marker("PreTrans"),
276     ];
277     tcx.alloc_mir(mir)
278 }