1 use crate::borrow_check::nll::type_check;
3 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
4 use rustc::mir::{Mir, MirPhase, Promoted};
5 use rustc::ty::{TyCtxt, InstanceDef};
6 use rustc::ty::query::Providers;
7 use rustc::ty::steal::Steal;
9 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
10 use rustc::util::nodemap::DefIdSet;
11 use rustc_data_structures::sync::Lrc;
17 pub mod add_moves_for_packed_drops;
18 pub mod cleanup_post_borrowck;
19 pub mod check_unsafety;
20 pub mod simplify_branches;
22 pub mod erase_regions;
23 pub mod no_landing_pads;
25 pub mod elaborate_drops;
26 pub mod add_call_guards;
27 pub mod promote_consts;
28 pub mod qualify_consts;
29 pub mod qualify_min_const_fn;
30 pub mod remove_noop_landing_pads;
39 pub mod uniform_array_move_out;
41 pub(crate) fn provide(providers: &mut Providers<'_>) {
42 self::qualify_consts::provide(providers);
43 self::check_unsafety::provide(providers);
44 *providers = Providers {
55 fn is_mir_available<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
56 tcx.mir_keys(def_id.krate).contains(&def_id)
59 /// Finds the full set of `DefId`s within the current crate that have
60 /// MIR associated with them.
61 fn mir_keys<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, krate: CrateNum)
63 assert_eq!(krate, LOCAL_CRATE);
65 let mut set = DefIdSet::default();
67 // All body-owners have MIR associated with them.
68 set.extend(tcx.body_owners());
70 // Additionally, tuple struct/variant constructors have MIR, but
71 // they don't have a BodyId, so we need to build them separately.
72 struct GatherCtors<'a, 'tcx: 'a> {
73 tcx: TyCtxt<'a, 'tcx, 'tcx>,
74 set: &'a mut DefIdSet,
76 impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
77 fn visit_variant_data(&mut self,
78 v: &'tcx hir::VariantData,
80 _: &'tcx hir::Generics,
83 if let hir::VariantData::Tuple(_, node_id, _) = *v {
84 self.set.insert(self.tcx.hir().local_def_id(node_id));
86 intravisit::walk_struct_def(self, v)
88 fn nested_visit_map<'b>(&'b mut self) -> NestedVisitorMap<'b, 'tcx> {
89 NestedVisitorMap::None
92 tcx.hir().krate().visit_all_item_likes(&mut GatherCtors {
100 fn mir_built<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx Steal<Mir<'tcx>> {
101 let mir = build::mir_build(tcx, def_id);
102 tcx.alloc_steal_mir(mir)
105 /// Where a specific Mir comes from.
106 #[derive(Debug, Copy, Clone)]
107 pub struct MirSource<'tcx> {
108 pub instance: InstanceDef<'tcx>,
110 /// If `Some`, this is a promoted rvalue within the parent function.
111 pub promoted: Option<Promoted>,
114 impl<'tcx> MirSource<'tcx> {
115 pub fn item(def_id: DefId) -> Self {
117 instance: InstanceDef::Item(def_id),
123 pub fn def_id(&self) -> DefId {
124 self.instance.def_id()
128 /// Generates a default name for the pass based on the name of the
130 pub fn default_name<T: ?Sized>() -> Cow<'static, str> {
131 let name = unsafe { ::std::intrinsics::type_name::<T>() };
132 if let Some(tail) = name.rfind(":") {
133 Cow::from(&name[tail+1..])
139 /// A streamlined trait that you can implement to create a pass; the
140 /// pass will be named after the type, and it will consist of a main
141 /// loop that goes over each available MIR and applies `run_pass`.
143 fn name<'a>(&'a self) -> Cow<'a, str> {
144 default_name::<Self>()
147 fn run_pass<'a, 'tcx>(&self,
148 tcx: TyCtxt<'a, 'tcx, 'tcx>,
149 source: MirSource<'tcx>,
150 mir: &mut Mir<'tcx>);
154 tcx: TyCtxt<'a, 'tcx, 'tcx>,
156 instance: InstanceDef<'tcx>,
158 passes: &[&dyn MirPass],
160 let phase_index = mir_phase.phase_index();
162 let run_passes = |mir: &mut Mir<'tcx>, promoted| {
163 if mir.phase >= mir_phase {
167 let source = MirSource {
172 let mut run_pass = |pass: &dyn MirPass| {
173 let run_hooks = |mir: &_, index, is_after| {
174 dump_mir::on_mir_pass(tcx, &format_args!("{:03}-{:03}", phase_index, index),
175 &pass.name(), source, mir, is_after);
177 run_hooks(mir, index, false);
178 pass.run_pass(tcx, source, mir);
179 run_hooks(mir, index, true);
188 mir.phase = mir_phase;
191 run_passes(mir, None);
193 for (index, promoted_mir) in mir.promoted.iter_enumerated_mut() {
194 run_passes(promoted_mir, Some(index));
196 //Let's make sure we don't miss any nested instances
197 assert!(promoted_mir.promoted.is_empty())
201 fn mir_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx Steal<Mir<'tcx>> {
202 // Unsafety check uses the raw mir, so make sure it is run
203 let _ = tcx.unsafety_check_result(def_id);
205 let mut mir = tcx.mir_built(def_id).steal();
206 run_passes(tcx, &mut mir, InstanceDef::Item(def_id), MirPhase::Const, &[
207 // What we need to do constant evaluation.
208 &simplify::SimplifyCfg::new("initial"),
209 &type_check::TypeckMir,
210 &rustc_peek::SanityCheck,
211 &uniform_array_move_out::UniformArrayMoveOut,
213 tcx.alloc_steal_mir(mir)
216 fn mir_validated<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx Steal<Mir<'tcx>> {
217 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
218 if let hir::BodyOwnerKind::Const = tcx.hir().body_owner_kind(node_id) {
219 // Ensure that we compute the `mir_const_qualif` for constants at
220 // this point, before we steal the mir-const result.
221 let _ = tcx.mir_const_qualif(def_id);
224 let mut mir = tcx.mir_const(def_id).steal();
225 run_passes(tcx, &mut mir, InstanceDef::Item(def_id), MirPhase::Validated, &[
226 // What we need to run borrowck etc.
227 &qualify_consts::QualifyAndPromoteConstants,
228 &simplify::SimplifyCfg::new("qualify-consts"),
230 tcx.alloc_steal_mir(mir)
233 fn optimized_mir<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx Mir<'tcx> {
234 // (Mir-)Borrowck uses `mir_validated`, so we have to force it to
235 // execute before we can steal.
236 tcx.ensure().mir_borrowck(def_id);
238 if tcx.use_ast_borrowck() {
239 tcx.ensure().borrowck(def_id);
242 let mut mir = tcx.mir_validated(def_id).steal();
243 run_passes(tcx, &mut mir, InstanceDef::Item(def_id), MirPhase::Optimized, &[
244 // Remove all things not needed by analysis
245 &no_landing_pads::NoLandingPads,
246 &simplify_branches::SimplifyBranches::new("initial"),
247 &remove_noop_landing_pads::RemoveNoopLandingPads,
248 // Remove all `AscribeUserType` statements.
249 &cleanup_post_borrowck::CleanAscribeUserType,
250 // Remove all `FakeRead` statements and the borrows that are only
251 // used for checking matches
252 &cleanup_post_borrowck::CleanFakeReadsAndBorrows,
254 &simplify::SimplifyCfg::new("early-opt"),
256 // These next passes must be executed together
257 &add_call_guards::CriticalCallEdges,
258 &elaborate_drops::ElaborateDrops,
259 &no_landing_pads::NoLandingPads,
260 // AddMovesForPackedDrops needs to run after drop
262 &add_moves_for_packed_drops::AddMovesForPackedDrops,
263 // AddRetag needs to run after ElaborateDrops, and it needs
264 // an AllCallEdges pass right before it. Otherwise it should
265 // run fairly late, but before optimizations begin.
266 &add_call_guards::AllCallEdges,
267 &add_retag::AddRetag,
269 &simplify::SimplifyCfg::new("elaborate-drops"),
271 // No lifetime analysis based on borrowing can be done from here on out.
273 // From here on out, regions are gone.
274 &erase_regions::EraseRegions,
276 &lower_128bit::Lower128Bit,
279 // Optimizations begin.
280 &uniform_array_move_out::RestoreSubsliceArrayMoveOut,
283 // Lowering generator control-flow and variables
284 // has to happen before we do anything else to them.
285 &generator::StateTransform,
287 &instcombine::InstCombine,
288 &const_prop::ConstProp,
289 &simplify_branches::SimplifyBranches::new("after-const-prop"),
290 &deaggregator::Deaggregator,
291 ©_prop::CopyPropagation,
292 &remove_noop_landing_pads::RemoveNoopLandingPads,
293 &simplify::SimplifyCfg::new("final"),
294 &simplify::SimplifyLocals,
296 &add_call_guards::CriticalCallEdges,
297 &dump_mir::Marker("PreCodegen"),