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.
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.
11 use borrow_check::nll::type_check;
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;
19 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
20 use rustc::util::nodemap::DefIdSet;
21 use rustc_data_structures::sync::Lrc;
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;
32 pub mod erase_regions;
33 pub mod no_landing_pads;
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;
48 pub mod uniform_array_move_out;
50 pub(crate) fn provide(providers: &mut Providers) {
51 self::qualify_consts::provide(providers);
52 self::check_unsafety::provide(providers);
53 *providers = Providers {
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)
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)
72 assert_eq!(krate, LOCAL_CRATE);
74 let mut set = DefIdSet();
76 // All body-owners have MIR associated with them.
77 set.extend(tcx.body_owners());
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,
85 impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
86 fn visit_variant_data(&mut self,
87 v: &'tcx hir::VariantData,
89 _: &'tcx hir::Generics,
92 if let hir::VariantData::Tuple(_, node_id) = *v {
93 self.set.insert(self.tcx.hir.local_def_id(node_id));
95 intravisit::walk_struct_def(self, v)
97 fn nested_visit_map<'b>(&'b mut self) -> NestedVisitorMap<'b, 'tcx> {
98 NestedVisitorMap::None
101 tcx.hir.krate().visit_all_item_likes(&mut GatherCtors {
104 }.as_deep_visitor());
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)
114 /// Where a specific Mir comes from.
115 #[derive(Debug, Copy, Clone)]
116 pub struct MirSource {
119 /// If `Some`, this is a promoted rvalue within the parent function.
120 pub promoted: Option<Promoted>,
124 pub fn item(def_id: DefId) -> Self {
132 /// Generates a default name for the pass based on the name of the
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..])
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`.
147 fn name<'a>(&'a self) -> Cow<'a, str> {
148 default_name::<Self>()
151 fn run_pass<'a, 'tcx>(&self,
152 tcx: TyCtxt<'a, 'tcx, 'tcx>,
154 mir: &mut Mir<'tcx>);
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 {
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);
170 run_hooks(mir, index, false);
171 pass.run_pass($tcx, source, mir);
172 run_hooks(mir, index, true);
176 $(run_pass(&$pass);)*
179 run_passes(&mut $mir, None);
181 for (index, promoted_mir) in $mir.promoted.iter_enumerated_mut() {
182 run_passes(promoted_mir, Some(index));
184 // Let's make sure we don't miss any nested instances
185 assert!(promoted_mir.promoted.is_empty());
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);
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,
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,
204 tcx.alloc_steal_mir(mir)
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);
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"),
221 tcx.alloc_steal_mir(mir)
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);
229 if tcx.use_ast_borrowck() {
230 let _ = tcx.borrowck(def_id);
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,
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
253 add_moves_for_packed_drops::AddMovesForPackedDrops,
255 simplify::SimplifyCfg::new("elaborate-drops"),
257 // No lifetime analysis based on borrowing can be done from here on out.
259 // From here on out, regions are gone.
260 erase_regions::EraseRegions,
262 lower_128bit::Lower128Bit,
265 // Optimizations begin.
266 uniform_array_move_out::RestoreSubsliceArrayMoveOut,
269 // Lowering generator control-flow and variables
270 // has to happen before we do anything else to them.
271 generator::StateTransform,
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,
282 add_call_guards::CriticalCallEdges,
283 dump_mir::Marker("PreCodegen"),