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