about summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--Cargo.lock26
-rw-r--r--compiler/rustc_interface/Cargo.toml1
-rw-r--r--compiler/rustc_interface/src/passes.rs5
-rw-r--r--compiler/rustc_mir/Cargo.toml4
-rw-r--r--compiler/rustc_mir/src/dataflow/drop_flag_effects.rs10
-rw-r--r--compiler/rustc_mir/src/dataflow/mod.rs8
-rw-r--r--compiler/rustc_mir/src/interpret/intern.rs2
-rw-r--r--compiler/rustc_mir/src/interpret/operand.rs6
-rw-r--r--compiler/rustc_mir/src/interpret/step.rs2
-rw-r--r--compiler/rustc_mir/src/lib.rs5
-rw-r--r--compiler/rustc_mir/src/transform/mod.rs605
-rw-r--r--compiler/rustc_mir/src/util/mod.rs4
-rw-r--r--compiler/rustc_mir/src/util/pretty.rs2
-rw-r--r--compiler/rustc_mir_transform/Cargo.toml29
-rw-r--r--compiler/rustc_mir_transform/src/abort_unwinding_calls.rs (renamed from compiler/rustc_mir/src/transform/abort_unwinding_calls.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/add_call_guards.rs (renamed from compiler/rustc_mir/src/transform/add_call_guards.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/add_moves_for_packed_drops.rs (renamed from compiler/rustc_mir/src/transform/add_moves_for_packed_drops.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/add_retag.rs (renamed from compiler/rustc_mir/src/transform/add_retag.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/check_const_item_mutation.rs (renamed from compiler/rustc_mir/src/transform/check_const_item_mutation.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/check_packed_ref.rs (renamed from compiler/rustc_mir/src/transform/check_packed_ref.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/check_unsafety.rs (renamed from compiler/rustc_mir/src/transform/check_unsafety.rs)0
-rw-r--r--compiler/rustc_mir_transform/src/cleanup_post_borrowck.rs (renamed from compiler/rustc_mir/src/transform/cleanup_post_borrowck.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/const_debuginfo.rs (renamed from compiler/rustc_mir/src/transform/const_debuginfo.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/const_goto.rs (renamed from compiler/rustc_mir/src/transform/const_goto.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/const_prop.rs (renamed from compiler/rustc_mir/src/transform/const_prop.rs)6
-rw-r--r--compiler/rustc_mir_transform/src/coverage/counters.rs (renamed from compiler/rustc_mir/src/transform/coverage/counters.rs)0
-rw-r--r--compiler/rustc_mir_transform/src/coverage/debug.rs (renamed from compiler/rustc_mir/src/transform/coverage/debug.rs)16
-rw-r--r--compiler/rustc_mir_transform/src/coverage/graph.rs (renamed from compiler/rustc_mir/src/transform/coverage/graph.rs)0
-rw-r--r--compiler/rustc_mir_transform/src/coverage/mod.rs (renamed from compiler/rustc_mir/src/transform/coverage/mod.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/coverage/query.rs (renamed from compiler/rustc_mir/src/transform/coverage/query.rs)0
-rw-r--r--compiler/rustc_mir_transform/src/coverage/spans.rs (renamed from compiler/rustc_mir/src/transform/coverage/spans.rs)0
-rw-r--r--compiler/rustc_mir_transform/src/coverage/test_macros/Cargo.toml (renamed from compiler/rustc_mir/src/transform/coverage/test_macros/Cargo.toml)0
-rw-r--r--compiler/rustc_mir_transform/src/coverage/test_macros/src/lib.rs (renamed from compiler/rustc_mir/src/transform/coverage/test_macros/src/lib.rs)0
-rw-r--r--compiler/rustc_mir_transform/src/coverage/tests.rs (renamed from compiler/rustc_mir/src/transform/coverage/tests.rs)0
-rw-r--r--compiler/rustc_mir_transform/src/deaggregator.rs (renamed from compiler/rustc_mir/src/transform/deaggregator.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/deduplicate_blocks.rs (renamed from compiler/rustc_mir/src/transform/deduplicate_blocks.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/dest_prop.rs (renamed from compiler/rustc_mir/src/transform/dest_prop.rs)6
-rw-r--r--compiler/rustc_mir_transform/src/dump_mir.rs (renamed from compiler/rustc_mir/src/transform/dump_mir.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/early_otherwise_branch.rs (renamed from compiler/rustc_mir/src/transform/early_otherwise_branch.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/elaborate_drops.rs (renamed from compiler/rustc_mir/src/transform/elaborate_drops.rs)16
-rw-r--r--compiler/rustc_mir_transform/src/function_item_references.rs (renamed from compiler/rustc_mir/src/transform/function_item_references.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/generator.rs (renamed from compiler/rustc_mir/src/transform/generator.rs)12
-rw-r--r--compiler/rustc_mir_transform/src/inline.rs (renamed from compiler/rustc_mir/src/transform/inline.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/inline/cycle.rs (renamed from compiler/rustc_mir/src/transform/inline/cycle.rs)0
-rw-r--r--compiler/rustc_mir_transform/src/instcombine.rs (renamed from compiler/rustc_mir/src/transform/instcombine.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/lib.rs632
-rw-r--r--compiler/rustc_mir_transform/src/lower_intrinsics.rs (renamed from compiler/rustc_mir/src/transform/lower_intrinsics.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/lower_slice_len.rs (renamed from compiler/rustc_mir/src/transform/lower_slice_len.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/match_branches.rs (renamed from compiler/rustc_mir/src/transform/match_branches.rs)4
-rw-r--r--compiler/rustc_mir_transform/src/multiple_return_terminators.rs (renamed from compiler/rustc_mir/src/transform/multiple_return_terminators.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/nrvo.rs (renamed from compiler/rustc_mir/src/transform/nrvo.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/remove_noop_landing_pads.rs (renamed from compiler/rustc_mir/src/transform/remove_noop_landing_pads.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/remove_storage_markers.rs (renamed from compiler/rustc_mir/src/transform/remove_storage_markers.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/remove_unneeded_drops.rs (renamed from compiler/rustc_mir/src/transform/remove_unneeded_drops.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/remove_zsts.rs (renamed from compiler/rustc_mir/src/transform/remove_zsts.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/required_consts.rs (renamed from compiler/rustc_mir/src/transform/required_consts.rs)0
-rw-r--r--compiler/rustc_mir_transform/src/separate_const_switch.rs (renamed from compiler/rustc_mir/src/transform/separate_const_switch.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/shim.rs (renamed from compiler/rustc_mir/src/shim.rs)8
-rw-r--r--compiler/rustc_mir_transform/src/simplify.rs (renamed from compiler/rustc_mir/src/transform/simplify.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/simplify_branches.rs (renamed from compiler/rustc_mir/src/transform/simplify_branches.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/simplify_comparison_integral.rs (renamed from compiler/rustc_mir/src/transform/simplify_comparison_integral.rs)0
-rw-r--r--compiler/rustc_mir_transform/src/simplify_try.rs (renamed from compiler/rustc_mir/src/transform/simplify_try.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/uninhabited_enum_branching.rs (renamed from compiler/rustc_mir/src/transform/uninhabited_enum_branching.rs)2
-rw-r--r--compiler/rustc_mir_transform/src/unreachable_prop.rs (renamed from compiler/rustc_mir/src/transform/unreachable_prop.rs)4
64 files changed, 775 insertions, 698 deletions
diff --git a/Cargo.lock b/Cargo.lock
index 81549bd1d20..3ec143d2492 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3928,6 +3928,7 @@ dependencies = [
  "rustc_middle",
  "rustc_mir",
  "rustc_mir_build",
+ "rustc_mir_transform",
  "rustc_parse",
  "rustc_passes",
  "rustc_plugin_impl",
@@ -4071,10 +4072,8 @@ dependencies = [
 name = "rustc_mir"
 version = "0.0.0"
 dependencies = [
- "coverage_test_macros",
  "either",
  "gsgdt",
- "itertools 0.9.0",
  "polonius-engine",
  "regex",
  "rustc_apfloat",
@@ -4121,6 +4120,29 @@ dependencies = [
 ]
 
 [[package]]
+name = "rustc_mir_transform"
+version = "0.0.0"
+dependencies = [
+ "coverage_test_macros",
+ "itertools 0.9.0",
+ "rustc_ast",
+ "rustc_attr",
+ "rustc_data_structures",
+ "rustc_errors",
+ "rustc_hir",
+ "rustc_index",
+ "rustc_middle",
+ "rustc_mir",
+ "rustc_serialize",
+ "rustc_session",
+ "rustc_span",
+ "rustc_target",
+ "rustc_trait_selection",
+ "smallvec",
+ "tracing",
+]
+
+[[package]]
 name = "rustc_parse"
 version = "0.0.0"
 dependencies = [
diff --git a/compiler/rustc_interface/Cargo.toml b/compiler/rustc_interface/Cargo.toml
index 970267d626c..8b277269258 100644
--- a/compiler/rustc_interface/Cargo.toml
+++ b/compiler/rustc_interface/Cargo.toml
@@ -34,6 +34,7 @@ rustc_hir = { path = "../rustc_hir" }
 rustc_metadata = { path = "../rustc_metadata" }
 rustc_mir = { path = "../rustc_mir" }
 rustc_mir_build = { path = "../rustc_mir_build" }
+rustc_mir_transform = { path = "../rustc_mir_transform" }
 rustc_passes = { path = "../rustc_passes" }
 rustc_typeck = { path = "../rustc_typeck" }
 rustc_lint = { path = "../rustc_lint" }
diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs
index df03ff59f46..7d41db0d4ae 100644
--- a/compiler/rustc_interface/src/passes.rs
+++ b/compiler/rustc_interface/src/passes.rs
@@ -742,6 +742,7 @@ pub static DEFAULT_QUERY_PROVIDERS: SyncLazy<Providers> = SyncLazy::new(|| {
     mir::provide(providers);
     mir_borrowck::provide(providers);
     mir_build::provide(providers);
+    rustc_mir_transform::provide(providers);
     rustc_privacy::provide(providers);
     typeck::provide(providers);
     ty::provide(providers);
@@ -913,7 +914,7 @@ fn analysis(tcx: TyCtxt<'_>, (): ()) -> Result<()> {
         for def_id in tcx.body_owners() {
             tcx.ensure().thir_check_unsafety(def_id);
             if !tcx.sess.opts.debugging_opts.thir_unsafeck {
-                mir::transform::check_unsafety::check_unsafety(tcx, def_id);
+                rustc_mir_transform::check_unsafety::check_unsafety(tcx, def_id);
             }
 
             if tcx.hir().body_const_context(def_id).is_some() {
@@ -1061,7 +1062,7 @@ pub fn start_codegen<'tcx>(
     info!("Post-codegen\n{:?}", tcx.debug_stats());
 
     if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
-        if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, outputs) {
+        if let Err(e) = rustc_mir_transform::dump_mir::emit_mir(tcx, outputs) {
             tcx.sess.err(&format!("could not emit MIR: {}", e));
             tcx.sess.abort_if_errors();
         }
diff --git a/compiler/rustc_mir/Cargo.toml b/compiler/rustc_mir/Cargo.toml
index 43c7b681e05..0207d9c012e 100644
--- a/compiler/rustc_mir/Cargo.toml
+++ b/compiler/rustc_mir/Cargo.toml
@@ -9,7 +9,6 @@ doctest = false
 [dependencies]
 either = "1.5.0"
 gsgdt = "0.1.2"
-itertools = "0.9"
 polonius-engine = "0.13.0"
 regex = "1"
 smallvec = { version = "1.0", features = ["union", "may_dangle"] }
@@ -30,6 +29,3 @@ rustc_session = { path = "../rustc_session" }
 rustc_target = { path = "../rustc_target" }
 rustc_trait_selection = { path = "../rustc_trait_selection" }
 rustc_span = { path = "../rustc_span" }
-
-[dev-dependencies]
-coverage_test_macros = { path = "src/transform/coverage/test_macros" }
diff --git a/compiler/rustc_mir/src/dataflow/drop_flag_effects.rs b/compiler/rustc_mir/src/dataflow/drop_flag_effects.rs
index d4f8f994ae9..fa449a23688 100644
--- a/compiler/rustc_mir/src/dataflow/drop_flag_effects.rs
+++ b/compiler/rustc_mir/src/dataflow/drop_flag_effects.rs
@@ -79,7 +79,7 @@ fn place_contents_drop_state_cannot_differ<'tcx>(
     }
 }
 
-pub(crate) fn on_lookup_result_bits<'tcx, F>(
+pub fn on_lookup_result_bits<'tcx, F>(
     tcx: TyCtxt<'tcx>,
     body: &Body<'tcx>,
     move_data: &MoveData<'tcx>,
@@ -96,7 +96,7 @@ pub(crate) fn on_lookup_result_bits<'tcx, F>(
     }
 }
 
-pub(crate) fn on_all_children_bits<'tcx, F>(
+pub fn on_all_children_bits<'tcx, F>(
     tcx: TyCtxt<'tcx>,
     body: &Body<'tcx>,
     move_data: &MoveData<'tcx>,
@@ -138,7 +138,7 @@ pub(crate) fn on_all_children_bits<'tcx, F>(
     on_all_children_bits(tcx, body, move_data, move_path_index, &mut each_child);
 }
 
-pub(crate) fn on_all_drop_children_bits<'tcx, F>(
+pub fn on_all_drop_children_bits<'tcx, F>(
     tcx: TyCtxt<'tcx>,
     body: &Body<'tcx>,
     ctxt: &MoveDataParamEnv<'tcx>,
@@ -161,7 +161,7 @@ pub(crate) fn on_all_drop_children_bits<'tcx, F>(
     })
 }
 
-pub(crate) fn drop_flag_effects_for_function_entry<'tcx, F>(
+pub fn drop_flag_effects_for_function_entry<'tcx, F>(
     tcx: TyCtxt<'tcx>,
     body: &Body<'tcx>,
     ctxt: &MoveDataParamEnv<'tcx>,
@@ -179,7 +179,7 @@ pub(crate) fn drop_flag_effects_for_function_entry<'tcx, F>(
     }
 }
 
-pub(crate) fn drop_flag_effects_for_location<'tcx, F>(
+pub fn drop_flag_effects_for_location<'tcx, F>(
     tcx: TyCtxt<'tcx>,
     body: &Body<'tcx>,
     ctxt: &MoveDataParamEnv<'tcx>,
diff --git a/compiler/rustc_mir/src/dataflow/mod.rs b/compiler/rustc_mir/src/dataflow/mod.rs
index bb38f90a3ba..f388d41d317 100644
--- a/compiler/rustc_mir/src/dataflow/mod.rs
+++ b/compiler/rustc_mir/src/dataflow/mod.rs
@@ -3,7 +3,11 @@ use rustc_middle::ty;
 use rustc_session::Session;
 use rustc_span::symbol::{sym, Symbol};
 
-pub(crate) use self::drop_flag_effects::*;
+pub use self::drop_flag_effects::{
+    drop_flag_effects_for_function_entry, drop_flag_effects_for_location,
+    move_path_children_matching, on_all_children_bits, on_all_drop_children_bits,
+    on_lookup_result_bits,
+};
 pub use self::framework::{
     fmt, lattice, visit_results, Analysis, AnalysisDomain, Backward, Direction, Engine, Forward,
     GenKill, GenKillAnalysis, JoinSemiLattice, Results, ResultsCursor, ResultsRefCursor,
@@ -26,7 +30,7 @@ pub struct MoveDataParamEnv<'tcx> {
     pub param_env: ty::ParamEnv<'tcx>,
 }
 
-pub(crate) fn has_rustc_mir_with(
+pub fn has_rustc_mir_with(
     _sess: &Session,
     attrs: &[ast::Attribute],
     name: Symbol,
diff --git a/compiler/rustc_mir/src/interpret/intern.rs b/compiler/rustc_mir/src/interpret/intern.rs
index f2457d11d9e..84e79408397 100644
--- a/compiler/rustc_mir/src/interpret/intern.rs
+++ b/compiler/rustc_mir/src/interpret/intern.rs
@@ -420,7 +420,7 @@ impl<'mir, 'tcx: 'mir, M: super::intern::CompileTimeMachine<'mir, 'tcx, !>>
     /// A helper function that allocates memory for the layout given and gives you access to mutate
     /// it. Once your own mutation code is done, the backing `Allocation` is removed from the
     /// current `Memory` and returned.
-    pub(crate) fn intern_with_temp_alloc(
+    pub fn intern_with_temp_alloc(
         &mut self,
         layout: TyAndLayout<'tcx>,
         f: impl FnOnce(
diff --git a/compiler/rustc_mir/src/interpret/operand.rs b/compiler/rustc_mir/src/interpret/operand.rs
index e67a6690836..63aca67c944 100644
--- a/compiler/rustc_mir/src/interpret/operand.rs
+++ b/compiler/rustc_mir/src/interpret/operand.rs
@@ -296,7 +296,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
     /// Note that for a given layout, this operation will either always fail or always
     /// succeed!  Whether it succeeds depends on whether the layout can be represented
     /// in an `Immediate`, not on which data is stored there currently.
-    pub(crate) fn try_read_immediate(
+    pub fn try_read_immediate(
         &self,
         src: &OpTy<'tcx, M::PointerTag>,
     ) -> InterpResult<'tcx, Result<ImmTy<'tcx, M::PointerTag>, MPlaceTy<'tcx, M::PointerTag>>> {
@@ -547,7 +547,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
     // in patterns via the `const_eval` module
     /// The `val` and `layout` are assumed to already be in our interpreter
     /// "universe" (param_env).
-    crate fn const_to_op(
+    pub fn const_to_op(
         &self,
         val: &ty::Const<'tcx>,
         layout: Option<TyAndLayout<'tcx>>,
@@ -566,7 +566,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
         }
     }
 
-    crate fn mir_const_to_op(
+    pub fn mir_const_to_op(
         &self,
         val: &mir::ConstantKind<'tcx>,
         layout: Option<TyAndLayout<'tcx>>,
diff --git a/compiler/rustc_mir/src/interpret/step.rs b/compiler/rustc_mir/src/interpret/step.rs
index 1e96581c392..09bd07660a3 100644
--- a/compiler/rustc_mir/src/interpret/step.rs
+++ b/compiler/rustc_mir/src/interpret/step.rs
@@ -76,7 +76,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
 
     /// Runs the interpretation logic for the given `mir::Statement` at the current frame and
     /// statement counter. This also moves the statement counter forward.
-    crate fn statement(&mut self, stmt: &mir::Statement<'tcx>) -> InterpResult<'tcx> {
+    pub fn statement(&mut self, stmt: &mir::Statement<'tcx>) -> InterpResult<'tcx> {
         info!("{:?}", stmt);
 
         use rustc_middle::mir::StatementKind::*;
diff --git a/compiler/rustc_mir/src/lib.rs b/compiler/rustc_mir/src/lib.rs
index 16dddc949df..4c79c7da15c 100644
--- a/compiler/rustc_mir/src/lib.rs
+++ b/compiler/rustc_mir/src/lib.rs
@@ -37,7 +37,6 @@ pub mod const_eval;
 pub mod dataflow;
 pub mod interpret;
 pub mod monomorphize;
-mod shim;
 pub mod transform;
 pub mod util;
 
@@ -45,15 +44,11 @@ use rustc_middle::ty::query::Providers;
 
 pub fn provide(providers: &mut Providers) {
     const_eval::provide(providers);
-    shim::provide(providers);
-    transform::provide(providers);
     monomorphize::partitioning::provide(providers);
     monomorphize::polymorphize::provide(providers);
     providers.eval_to_const_value_raw = const_eval::eval_to_const_value_raw_provider;
     providers.eval_to_allocation_raw = const_eval::eval_to_allocation_raw_provider;
     providers.const_caller_location = const_eval::const_caller_location;
-    providers.mir_callgraph_reachable = transform::inline::cycle::mir_callgraph_reachable;
-    providers.mir_inliner_callees = transform::inline::cycle::mir_inliner_callees;
     providers.destructure_const = |tcx, param_env_and_value| {
         let (param_env, value) = param_env_and_value.into_parts();
         const_eval::destructure_const(tcx, param_env, value)
diff --git a/compiler/rustc_mir/src/transform/mod.rs b/compiler/rustc_mir/src/transform/mod.rs
index d4c2456e9a4..abf43dd1d23 100644
--- a/compiler/rustc_mir/src/transform/mod.rs
+++ b/compiler/rustc_mir/src/transform/mod.rs
@@ -1,149 +1,12 @@
-use crate::{shim, util};
-use required_consts::RequiredConstsVisitor;
-use rustc_data_structures::fx::FxHashSet;
-use rustc_data_structures::steal::Steal;
-use rustc_hir as hir;
-use rustc_hir::def_id::{DefId, LocalDefId};
-use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
-use rustc_index::vec::IndexVec;
-use rustc_middle::mir::visit::Visitor as _;
-use rustc_middle::mir::{traversal, Body, ConstQualifs, MirPhase, Promoted};
-use rustc_middle::ty::query::Providers;
-use rustc_middle::ty::{self, TyCtxt, TypeFoldable};
-use rustc_span::{Span, Symbol};
+use rustc_middle::mir::Body;
+use rustc_middle::ty::TyCtxt;
 use std::borrow::Cow;
 
-pub mod abort_unwinding_calls;
-pub mod add_call_guards;
-pub mod add_moves_for_packed_drops;
-pub mod add_retag;
-pub mod check_const_item_mutation;
 pub mod check_consts;
-pub mod check_packed_ref;
-pub mod check_unsafety;
-pub mod cleanup_post_borrowck;
-pub mod const_debuginfo;
-pub mod const_goto;
-pub mod const_prop;
-pub mod coverage;
-pub mod deaggregator;
-pub mod deduplicate_blocks;
-pub mod dest_prop;
-pub mod dump_mir;
-pub mod early_otherwise_branch;
-pub mod elaborate_drops;
-pub mod function_item_references;
-pub mod generator;
-pub mod inline;
-pub mod instcombine;
-pub mod lower_intrinsics;
-pub mod lower_slice_len;
-pub mod match_branches;
-pub mod multiple_return_terminators;
-pub mod nrvo;
 pub mod promote_consts;
-pub mod remove_noop_landing_pads;
-pub mod remove_storage_markers;
-pub mod remove_unneeded_drops;
-pub mod remove_zsts;
-pub mod required_consts;
 pub mod rustc_peek;
-pub mod separate_const_switch;
-pub mod simplify;
-pub mod simplify_branches;
-pub mod simplify_comparison_integral;
-pub mod simplify_try;
-pub mod uninhabited_enum_branching;
-pub mod unreachable_prop;
 pub mod validate;
 
-pub use rustc_middle::mir::MirSource;
-
-pub(crate) fn provide(providers: &mut Providers) {
-    self::check_unsafety::provide(providers);
-    self::check_packed_ref::provide(providers);
-    *providers = Providers {
-        mir_keys,
-        mir_const,
-        mir_const_qualif: |tcx, def_id| {
-            let def_id = def_id.expect_local();
-            if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
-                tcx.mir_const_qualif_const_arg(def)
-            } else {
-                mir_const_qualif(tcx, ty::WithOptConstParam::unknown(def_id))
-            }
-        },
-        mir_const_qualif_const_arg: |tcx, (did, param_did)| {
-            mir_const_qualif(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
-        },
-        mir_promoted,
-        mir_drops_elaborated_and_const_checked,
-        mir_for_ctfe,
-        mir_for_ctfe_of_const_arg,
-        optimized_mir,
-        is_mir_available,
-        is_ctfe_mir_available: |tcx, did| is_mir_available(tcx, did),
-        promoted_mir: |tcx, def_id| {
-            let def_id = def_id.expect_local();
-            if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
-                tcx.promoted_mir_of_const_arg(def)
-            } else {
-                promoted_mir(tcx, ty::WithOptConstParam::unknown(def_id))
-            }
-        },
-        promoted_mir_of_const_arg: |tcx, (did, param_did)| {
-            promoted_mir(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
-        },
-        ..*providers
-    };
-    coverage::query::provide(providers);
-}
-
-fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
-    let def_id = def_id.expect_local();
-    tcx.mir_keys(()).contains(&def_id)
-}
-
-/// Finds the full set of `DefId`s within the current crate that have
-/// MIR associated with them.
-fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxHashSet<LocalDefId> {
-    let mut set = FxHashSet::default();
-
-    // All body-owners have MIR associated with them.
-    set.extend(tcx.body_owners());
-
-    // Additionally, tuple struct/variant constructors have MIR, but
-    // they don't have a BodyId, so we need to build them separately.
-    struct GatherCtors<'a, 'tcx> {
-        tcx: TyCtxt<'tcx>,
-        set: &'a mut FxHashSet<LocalDefId>,
-    }
-    impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
-        fn visit_variant_data(
-            &mut self,
-            v: &'tcx hir::VariantData<'tcx>,
-            _: Symbol,
-            _: &'tcx hir::Generics<'tcx>,
-            _: hir::HirId,
-            _: Span,
-        ) {
-            if let hir::VariantData::Tuple(_, hir_id) = *v {
-                self.set.insert(self.tcx.hir().local_def_id(hir_id));
-            }
-            intravisit::walk_struct_def(self, v)
-        }
-        type Map = intravisit::ErasedMap<'tcx>;
-        fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
-            NestedVisitorMap::None
-        }
-    }
-    tcx.hir()
-        .krate()
-        .visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
-
-    set
-}
-
 /// Generates a default name for the pass based on the name of the
 /// type `T`.
 pub fn default_name<T: ?Sized>() -> Cow<'static, str> {
@@ -161,467 +24,3 @@ pub trait MirPass<'tcx> {
 
     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>);
 }
-
-pub fn run_passes(
-    tcx: TyCtxt<'tcx>,
-    body: &mut Body<'tcx>,
-    mir_phase: MirPhase,
-    passes: &[&[&dyn MirPass<'tcx>]],
-) {
-    let phase_index = mir_phase.phase_index();
-    let validate = tcx.sess.opts.debugging_opts.validate_mir;
-
-    if body.phase >= mir_phase {
-        return;
-    }
-
-    if validate {
-        validate::Validator { when: format!("input to phase {:?}", mir_phase), mir_phase }
-            .run_pass(tcx, body);
-    }
-
-    let mut index = 0;
-    let mut run_pass = |pass: &dyn MirPass<'tcx>| {
-        let run_hooks = |body: &_, index, is_after| {
-            dump_mir::on_mir_pass(
-                tcx,
-                &format_args!("{:03}-{:03}", phase_index, index),
-                &pass.name(),
-                body,
-                is_after,
-            );
-        };
-        run_hooks(body, index, false);
-        pass.run_pass(tcx, body);
-        run_hooks(body, index, true);
-
-        if validate {
-            validate::Validator {
-                when: format!("after {} in phase {:?}", pass.name(), mir_phase),
-                mir_phase,
-            }
-            .run_pass(tcx, body);
-        }
-
-        index += 1;
-    };
-
-    for pass_group in passes {
-        for pass in *pass_group {
-            run_pass(*pass);
-        }
-    }
-
-    body.phase = mir_phase;
-
-    if mir_phase == MirPhase::Optimization {
-        validate::Validator { when: format!("end of phase {:?}", mir_phase), mir_phase }
-            .run_pass(tcx, body);
-    }
-}
-
-fn mir_const_qualif(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> ConstQualifs {
-    let const_kind = tcx.hir().body_const_context(def.did);
-
-    // No need to const-check a non-const `fn`.
-    if const_kind.is_none() {
-        return Default::default();
-    }
-
-    // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
-    // cannot yet be stolen), because `mir_promoted()`, which steals
-    // from `mir_const(), forces this query to execute before
-    // performing the steal.
-    let body = &tcx.mir_const(def).borrow();
-
-    if body.return_ty().references_error() {
-        tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
-        return Default::default();
-    }
-
-    let ccx = check_consts::ConstCx { body, tcx, const_kind, param_env: tcx.param_env(def.did) };
-
-    let mut validator = check_consts::check::Checker::new(&ccx);
-    validator.check_body();
-
-    // We return the qualifs in the return place for every MIR body, even though it is only used
-    // when deciding to promote a reference to a `const` for now.
-    validator.qualifs_in_return_place()
-}
-
-/// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
-fn mir_const<'tcx>(
-    tcx: TyCtxt<'tcx>,
-    def: ty::WithOptConstParam<LocalDefId>,
-) -> &'tcx Steal<Body<'tcx>> {
-    if let Some(def) = def.try_upgrade(tcx) {
-        return tcx.mir_const(def);
-    }
-
-    // Unsafety check uses the raw mir, so make sure it is run.
-    if !tcx.sess.opts.debugging_opts.thir_unsafeck {
-        if let Some(param_did) = def.const_param_did {
-            tcx.ensure().unsafety_check_result_for_const_arg((def.did, param_did));
-        } else {
-            tcx.ensure().unsafety_check_result(def.did);
-        }
-    }
-
-    let mut body = tcx.mir_built(def).steal();
-
-    util::dump_mir(tcx, None, "mir_map", &0, &body, |_, _| Ok(()));
-
-    run_passes(
-        tcx,
-        &mut body,
-        MirPhase::Const,
-        &[&[
-            // MIR-level lints.
-            &check_packed_ref::CheckPackedRef,
-            &check_const_item_mutation::CheckConstItemMutation,
-            &function_item_references::FunctionItemReferences,
-            // What we need to do constant evaluation.
-            &simplify::SimplifyCfg::new("initial"),
-            &rustc_peek::SanityCheck,
-        ]],
-    );
-    tcx.alloc_steal_mir(body)
-}
-
-/// Compute the main MIR body and the list of MIR bodies of the promoteds.
-fn mir_promoted(
-    tcx: TyCtxt<'tcx>,
-    def: ty::WithOptConstParam<LocalDefId>,
-) -> (&'tcx Steal<Body<'tcx>>, &'tcx Steal<IndexVec<Promoted, Body<'tcx>>>) {
-    if let Some(def) = def.try_upgrade(tcx) {
-        return tcx.mir_promoted(def);
-    }
-
-    // Ensure that we compute the `mir_const_qualif` for constants at
-    // this point, before we steal the mir-const result.
-    // Also this means promotion can rely on all const checks having been done.
-    let _ = tcx.mir_const_qualif_opt_const_arg(def);
-    let _ = tcx.mir_abstract_const_opt_const_arg(def.to_global());
-    let mut body = tcx.mir_const(def).steal();
-
-    let mut required_consts = Vec::new();
-    let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
-    for (bb, bb_data) in traversal::reverse_postorder(&body) {
-        required_consts_visitor.visit_basic_block_data(bb, bb_data);
-    }
-    body.required_consts = required_consts;
-
-    let promote_pass = promote_consts::PromoteTemps::default();
-    let promote: &[&dyn MirPass<'tcx>] = &[
-        // What we need to run borrowck etc.
-        &promote_pass,
-        &simplify::SimplifyCfg::new("promote-consts"),
-    ];
-
-    let opt_coverage: &[&dyn MirPass<'tcx>] =
-        if tcx.sess.instrument_coverage() { &[&coverage::InstrumentCoverage] } else { &[] };
-
-    run_passes(tcx, &mut body, MirPhase::ConstPromotion, &[promote, opt_coverage]);
-
-    let promoted = promote_pass.promoted_fragments.into_inner();
-    (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
-}
-
-/// Compute the MIR that is used during CTFE (and thus has no optimizations run on it)
-fn mir_for_ctfe<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Body<'tcx> {
-    let did = def_id.expect_local();
-    if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
-        tcx.mir_for_ctfe_of_const_arg(def)
-    } else {
-        tcx.arena.alloc(inner_mir_for_ctfe(tcx, ty::WithOptConstParam::unknown(did)))
-    }
-}
-
-/// Same as `mir_for_ctfe`, but used to get the MIR of a const generic parameter.
-/// The docs on `WithOptConstParam` explain this a bit more, but the TLDR is that
-/// we'd get cycle errors with `mir_for_ctfe`, because typeck would need to typeck
-/// the const parameter while type checking the main body, which in turn would try
-/// to type check the main body again.
-fn mir_for_ctfe_of_const_arg<'tcx>(
-    tcx: TyCtxt<'tcx>,
-    (did, param_did): (LocalDefId, DefId),
-) -> &'tcx Body<'tcx> {
-    tcx.arena.alloc(inner_mir_for_ctfe(
-        tcx,
-        ty::WithOptConstParam { did, const_param_did: Some(param_did) },
-    ))
-}
-
-fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
-    // FIXME: don't duplicate this between the optimized_mir/mir_for_ctfe queries
-    if tcx.is_constructor(def.did.to_def_id()) {
-        // There's no reason to run all of the MIR passes on constructors when
-        // we can just output the MIR we want directly. This also saves const
-        // qualification and borrow checking the trouble of special casing
-        // constructors.
-        return shim::build_adt_ctor(tcx, def.did.to_def_id());
-    }
-
-    let context = tcx
-        .hir()
-        .body_const_context(def.did)
-        .expect("mir_for_ctfe should not be used for runtime functions");
-
-    let mut body = tcx.mir_drops_elaborated_and_const_checked(def).borrow().clone();
-
-    match context {
-        // Do not const prop functions, either they get executed at runtime or exported to metadata,
-        // so we run const prop on them, or they don't, in which case we const evaluate some control
-        // flow paths of the function and any errors in those paths will get emitted as const eval
-        // errors.
-        hir::ConstContext::ConstFn => {}
-        // Static items always get evaluated, so we can just let const eval see if any erroneous
-        // control flow paths get executed.
-        hir::ConstContext::Static(_) => {}
-        // Associated constants get const prop run so we detect common failure situations in the
-        // crate that defined the constant.
-        // Technically we want to not run on regular const items, but oli-obk doesn't know how to
-        // conveniently detect that at this point without looking at the HIR.
-        hir::ConstContext::Const => {
-            #[rustfmt::skip]
-            let optimizations: &[&dyn MirPass<'_>] = &[
-                &const_prop::ConstProp,
-            ];
-
-            #[rustfmt::skip]
-            run_passes(
-                tcx,
-                &mut body,
-                MirPhase::Optimization,
-                &[
-                    optimizations,
-                ],
-            );
-        }
-    }
-
-    debug_assert!(!body.has_free_regions(tcx), "Free regions in MIR for CTFE");
-
-    body
-}
-
-/// Obtain just the main MIR (no promoteds) and run some cleanups on it. This also runs
-/// mir borrowck *before* doing so in order to ensure that borrowck can be run and doesn't
-/// end up missing the source MIR due to stealing happening.
-fn mir_drops_elaborated_and_const_checked<'tcx>(
-    tcx: TyCtxt<'tcx>,
-    def: ty::WithOptConstParam<LocalDefId>,
-) -> &'tcx Steal<Body<'tcx>> {
-    if let Some(def) = def.try_upgrade(tcx) {
-        return tcx.mir_drops_elaborated_and_const_checked(def);
-    }
-
-    // (Mir-)Borrowck uses `mir_promoted`, so we have to force it to
-    // execute before we can steal.
-    if let Some(param_did) = def.const_param_did {
-        tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
-    } else {
-        tcx.ensure().mir_borrowck(def.did);
-    }
-
-    let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
-    use rustc_middle::hir::map::blocks::FnLikeNode;
-    let is_fn_like = FnLikeNode::from_node(tcx.hir().get(hir_id)).is_some();
-    if is_fn_like {
-        let did = def.did.to_def_id();
-        let def = ty::WithOptConstParam::unknown(did);
-
-        // Do not compute the mir call graph without said call graph actually being used.
-        if inline::is_enabled(tcx) {
-            let _ = tcx.mir_inliner_callees(ty::InstanceDef::Item(def));
-        }
-    }
-
-    let (body, _) = tcx.mir_promoted(def);
-    let mut body = body.steal();
-
-    run_post_borrowck_cleanup_passes(tcx, &mut body);
-    check_consts::post_drop_elaboration::check_live_drops(tcx, &body);
-    tcx.alloc_steal_mir(body)
-}
-
-/// After this series of passes, no lifetime analysis based on borrowing can be done.
-fn run_post_borrowck_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
-    debug!("post_borrowck_cleanup({:?})", body.source.def_id());
-
-    let post_borrowck_cleanup: &[&dyn MirPass<'tcx>] = &[
-        // Remove all things only needed by analysis
-        &simplify_branches::SimplifyBranches::new("initial"),
-        &remove_noop_landing_pads::RemoveNoopLandingPads,
-        &cleanup_post_borrowck::CleanupNonCodegenStatements,
-        &simplify::SimplifyCfg::new("early-opt"),
-        // These next passes must be executed together
-        &add_call_guards::CriticalCallEdges,
-        &elaborate_drops::ElaborateDrops,
-        // This will remove extraneous landing pads which are no longer
-        // necessary as well as well as forcing any call in a non-unwinding
-        // function calling a possibly-unwinding function to abort the process.
-        &abort_unwinding_calls::AbortUnwindingCalls,
-        // AddMovesForPackedDrops needs to run after drop
-        // elaboration.
-        &add_moves_for_packed_drops::AddMovesForPackedDrops,
-        // `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late,
-        // but before optimizations begin.
-        &add_retag::AddRetag,
-        &lower_intrinsics::LowerIntrinsics,
-        &simplify::SimplifyCfg::new("elaborate-drops"),
-        // `Deaggregator` is conceptually part of MIR building, some backends rely on it happening
-        // and it can help optimizations.
-        &deaggregator::Deaggregator,
-    ];
-
-    run_passes(tcx, body, MirPhase::DropLowering, &[post_borrowck_cleanup]);
-}
-
-fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
-    let mir_opt_level = tcx.sess.mir_opt_level();
-
-    // Lowering generator control-flow and variables has to happen before we do anything else
-    // to them. We run some optimizations before that, because they may be harder to do on the state
-    // machine than on MIR with async primitives.
-    let optimizations_with_generators: &[&dyn MirPass<'tcx>] = &[
-        &lower_slice_len::LowerSliceLenCalls, // has to be done before inlining, otherwise actual call will be almost always inlined. Also simple, so can just do first
-        &unreachable_prop::UnreachablePropagation,
-        &uninhabited_enum_branching::UninhabitedEnumBranching,
-        &simplify::SimplifyCfg::new("after-uninhabited-enum-branching"),
-        &inline::Inline,
-        &generator::StateTransform,
-    ];
-
-    // Even if we don't do optimizations, we still have to lower generators for codegen.
-    let no_optimizations_with_generators: &[&dyn MirPass<'tcx>] = &[&generator::StateTransform];
-
-    // The main optimizations that we do on MIR.
-    let optimizations: &[&dyn MirPass<'tcx>] = &[
-        &remove_storage_markers::RemoveStorageMarkers,
-        &remove_zsts::RemoveZsts,
-        &const_goto::ConstGoto,
-        &remove_unneeded_drops::RemoveUnneededDrops,
-        &match_branches::MatchBranchSimplification,
-        // inst combine is after MatchBranchSimplification to clean up Ne(_1, false)
-        &multiple_return_terminators::MultipleReturnTerminators,
-        &instcombine::InstCombine,
-        &separate_const_switch::SeparateConstSwitch,
-        &const_prop::ConstProp,
-        &simplify_branches::SimplifyBranches::new("after-const-prop"),
-        &early_otherwise_branch::EarlyOtherwiseBranch,
-        &simplify_comparison_integral::SimplifyComparisonIntegral,
-        &simplify_try::SimplifyArmIdentity,
-        &simplify_try::SimplifyBranchSame,
-        &dest_prop::DestinationPropagation,
-        &simplify_branches::SimplifyBranches::new("final"),
-        &remove_noop_landing_pads::RemoveNoopLandingPads,
-        &simplify::SimplifyCfg::new("final"),
-        &nrvo::RenameReturnPlace,
-        &const_debuginfo::ConstDebugInfo,
-        &simplify::SimplifyLocals,
-        &multiple_return_terminators::MultipleReturnTerminators,
-        &deduplicate_blocks::DeduplicateBlocks,
-    ];
-
-    // Optimizations to run even if mir optimizations have been disabled.
-    let no_optimizations: &[&dyn MirPass<'tcx>] = &[
-        // FIXME(#70073): This pass is responsible for both optimization as well as some lints.
-        &const_prop::ConstProp,
-    ];
-
-    // Some cleanup necessary at least for LLVM and potentially other codegen backends.
-    let pre_codegen_cleanup: &[&dyn MirPass<'tcx>] = &[
-        &add_call_guards::CriticalCallEdges,
-        // Dump the end result for testing and debugging purposes.
-        &dump_mir::Marker("PreCodegen"),
-    ];
-
-    // End of pass declarations, now actually run the passes.
-    // Generator Lowering
-    #[rustfmt::skip]
-    run_passes(
-        tcx,
-        body,
-        MirPhase::GeneratorLowering,
-        &[
-            if mir_opt_level > 0 {
-                optimizations_with_generators
-            } else {
-                no_optimizations_with_generators
-            }
-        ],
-    );
-
-    // Main optimization passes
-    #[rustfmt::skip]
-    run_passes(
-        tcx,
-        body,
-        MirPhase::Optimization,
-        &[
-            if mir_opt_level > 0 { optimizations } else { no_optimizations },
-            pre_codegen_cleanup,
-        ],
-    );
-}
-
-/// Optimize the MIR and prepare it for codegen.
-fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx Body<'tcx> {
-    let did = did.expect_local();
-    assert_eq!(ty::WithOptConstParam::try_lookup(did, tcx), None);
-    tcx.arena.alloc(inner_optimized_mir(tcx, did))
-}
-
-fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> {
-    if tcx.is_constructor(did.to_def_id()) {
-        // There's no reason to run all of the MIR passes on constructors when
-        // we can just output the MIR we want directly. This also saves const
-        // qualification and borrow checking the trouble of special casing
-        // constructors.
-        return shim::build_adt_ctor(tcx, did.to_def_id());
-    }
-
-    match tcx.hir().body_const_context(did) {
-        // Run the `mir_for_ctfe` query, which depends on `mir_drops_elaborated_and_const_checked`
-        // which we are going to steal below. Thus we need to run `mir_for_ctfe` first, so it
-        // computes and caches its result.
-        Some(hir::ConstContext::ConstFn) => tcx.ensure().mir_for_ctfe(did),
-        None => {}
-        Some(other) => panic!("do not use `optimized_mir` for constants: {:?}", other),
-    }
-    let mut body =
-        tcx.mir_drops_elaborated_and_const_checked(ty::WithOptConstParam::unknown(did)).steal();
-    run_optimization_passes(tcx, &mut body);
-
-    debug_assert!(!body.has_free_regions(tcx), "Free regions in optimized MIR");
-
-    body
-}
-
-/// Fetch all the promoteds of an item and prepare their MIR bodies to be ready for
-/// constant evaluation once all substitutions become known.
-fn promoted_mir<'tcx>(
-    tcx: TyCtxt<'tcx>,
-    def: ty::WithOptConstParam<LocalDefId>,
-) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
-    if tcx.is_constructor(def.did.to_def_id()) {
-        return tcx.arena.alloc(IndexVec::new());
-    }
-
-    if let Some(param_did) = def.const_param_did {
-        tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
-    } else {
-        tcx.ensure().mir_borrowck(def.did);
-    }
-    let (_, promoted) = tcx.mir_promoted(def);
-    let mut promoted = promoted.steal();
-
-    for body in &mut promoted {
-        run_post_borrowck_cleanup_passes(tcx, body);
-    }
-
-    debug_assert!(!promoted.has_free_regions(tcx), "Free regions in promoted MIR");
-
-    tcx.arena.alloc(promoted)
-}
diff --git a/compiler/rustc_mir/src/util/mod.rs b/compiler/rustc_mir/src/util/mod.rs
index 8f9db6daba7..741c1e6b2c6 100644
--- a/compiler/rustc_mir/src/util/mod.rs
+++ b/compiler/rustc_mir/src/util/mod.rs
@@ -7,10 +7,10 @@ mod alignment;
 pub mod collect_writes;
 mod find_self_call;
 mod generic_graph;
-pub(crate) mod generic_graphviz;
+pub mod generic_graphviz;
 mod graphviz;
 pub mod pretty;
-pub(crate) mod spanview;
+pub mod spanview;
 
 pub use self::aggregate::expand_aggregate;
 pub use self::alignment::is_disaligned;
diff --git a/compiler/rustc_mir/src/util/pretty.rs b/compiler/rustc_mir/src/util/pretty.rs
index ec1aa5b476b..db98cb76343 100644
--- a/compiler/rustc_mir/src/util/pretty.rs
+++ b/compiler/rustc_mir/src/util/pretty.rs
@@ -7,7 +7,6 @@ use std::path::{Path, PathBuf};
 
 use super::graphviz::write_mir_fn_graphviz;
 use super::spanview::write_mir_fn_spanview;
-use crate::transform::MirSource;
 use either::Either;
 use rustc_data_structures::fx::FxHashMap;
 use rustc_hir::def_id::DefId;
@@ -16,6 +15,7 @@ use rustc_middle::mir::interpret::{
     read_target_uint, AllocId, Allocation, ConstValue, GlobalAlloc, Pointer, Provenance,
 };
 use rustc_middle::mir::visit::Visitor;
+use rustc_middle::mir::MirSource;
 use rustc_middle::mir::*;
 use rustc_middle::ty::{self, TyCtxt, TyS, TypeFoldable, TypeVisitor};
 use rustc_target::abi::Size;
diff --git a/compiler/rustc_mir_transform/Cargo.toml b/compiler/rustc_mir_transform/Cargo.toml
new file mode 100644
index 00000000000..cba3ab5176e
--- /dev/null
+++ b/compiler/rustc_mir_transform/Cargo.toml
@@ -0,0 +1,29 @@
+[package]
+authors = ["The Rust Project Developers"]
+name = "rustc_mir_transform"
+version = "0.0.0"
+edition = "2018"
+
+[lib]
+doctest = false
+
+[dependencies]
+itertools = "0.9"
+smallvec = { version = "1.6.1", features = ["union", "may_dangle"] }
+tracing = "0.1"
+rustc_ast = { path = "../rustc_ast" }
+rustc_attr = { path = "../rustc_attr" }
+rustc_data_structures = { path = "../rustc_data_structures" }
+rustc_errors = { path = "../rustc_errors" }
+rustc_hir = { path = "../rustc_hir" }
+rustc_index = { path = "../rustc_index" }
+rustc_middle = { path = "../rustc_middle" }
+rustc_mir = { path = "../rustc_mir" }
+rustc_serialize = { path = "../rustc_serialize" }
+rustc_session = { path = "../rustc_session" }
+rustc_target = { path = "../rustc_target" }
+rustc_trait_selection = { path = "../rustc_trait_selection" }
+rustc_span = { path = "../rustc_span" }
+
+[dev-dependencies]
+coverage_test_macros = { path = "src/coverage/test_macros" }
diff --git a/compiler/rustc_mir/src/transform/abort_unwinding_calls.rs b/compiler/rustc_mir_transform/src/abort_unwinding_calls.rs
index aecb2373eaf..855dcbc431b 100644
--- a/compiler/rustc_mir/src/transform/abort_unwinding_calls.rs
+++ b/compiler/rustc_mir_transform/src/abort_unwinding_calls.rs
@@ -1,4 +1,4 @@
-use crate::transform::MirPass;
+use crate::MirPass;
 use rustc_hir::def::DefKind;
 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
 use rustc_middle::mir::*;
diff --git a/compiler/rustc_mir/src/transform/add_call_guards.rs b/compiler/rustc_mir_transform/src/add_call_guards.rs
index 12ee6bb4c67..cd6b671a0db 100644
--- a/compiler/rustc_mir/src/transform/add_call_guards.rs
+++ b/compiler/rustc_mir_transform/src/add_call_guards.rs
@@ -1,4 +1,4 @@
-use crate::transform::MirPass;
+use crate::MirPass;
 use rustc_index::vec::{Idx, IndexVec};
 use rustc_middle::mir::*;
 use rustc_middle::ty::TyCtxt;
diff --git a/compiler/rustc_mir/src/transform/add_moves_for_packed_drops.rs b/compiler/rustc_mir_transform/src/add_moves_for_packed_drops.rs
index 417e0a51aec..c48d0c8b8f2 100644
--- a/compiler/rustc_mir/src/transform/add_moves_for_packed_drops.rs
+++ b/compiler/rustc_mir_transform/src/add_moves_for_packed_drops.rs
@@ -1,9 +1,9 @@
 use rustc_middle::mir::*;
 use rustc_middle::ty::TyCtxt;
 
-use crate::transform::MirPass;
 use crate::util;
 use crate::util::patch::MirPatch;
+use crate::MirPass;
 
 // This pass moves values being dropped that are within a packed
 // struct to a separate local before dropping them, to ensure that
diff --git a/compiler/rustc_mir/src/transform/add_retag.rs b/compiler/rustc_mir_transform/src/add_retag.rs
index cb608819ea8..7a8dee09c29 100644
--- a/compiler/rustc_mir/src/transform/add_retag.rs
+++ b/compiler/rustc_mir_transform/src/add_retag.rs
@@ -4,7 +4,7 @@
 //! of MIR building, and only after this pass we think of the program has having the
 //! normal MIR semantics.
 
-use crate::transform::MirPass;
+use crate::MirPass;
 use rustc_middle::mir::*;
 use rustc_middle::ty::{self, Ty, TyCtxt};
 
diff --git a/compiler/rustc_mir/src/transform/check_const_item_mutation.rs b/compiler/rustc_mir_transform/src/check_const_item_mutation.rs
index e2d50ba034a..27fe80a456f 100644
--- a/compiler/rustc_mir/src/transform/check_const_item_mutation.rs
+++ b/compiler/rustc_mir_transform/src/check_const_item_mutation.rs
@@ -6,7 +6,7 @@ use rustc_middle::ty::TyCtxt;
 use rustc_session::lint::builtin::CONST_ITEM_MUTATION;
 use rustc_span::def_id::DefId;
 
-use crate::transform::MirPass;
+use crate::MirPass;
 
 pub struct CheckConstItemMutation;
 
diff --git a/compiler/rustc_mir/src/transform/check_packed_ref.rs b/compiler/rustc_mir_transform/src/check_packed_ref.rs
index 13b7221046b..49be34c7a28 100644
--- a/compiler/rustc_mir/src/transform/check_packed_ref.rs
+++ b/compiler/rustc_mir_transform/src/check_packed_ref.rs
@@ -6,8 +6,8 @@ use rustc_middle::ty::{self, TyCtxt};
 use rustc_session::lint::builtin::UNALIGNED_REFERENCES;
 use rustc_span::symbol::sym;
 
-use crate::transform::MirPass;
 use crate::util;
+use crate::MirPass;
 
 pub(crate) fn provide(providers: &mut Providers) {
     *providers = Providers { unsafe_derive_on_repr_packed, ..*providers };
diff --git a/compiler/rustc_mir/src/transform/check_unsafety.rs b/compiler/rustc_mir_transform/src/check_unsafety.rs
index 1ff9bd15721..1ff9bd15721 100644
--- a/compiler/rustc_mir/src/transform/check_unsafety.rs
+++ b/compiler/rustc_mir_transform/src/check_unsafety.rs
diff --git a/compiler/rustc_mir/src/transform/cleanup_post_borrowck.rs b/compiler/rustc_mir_transform/src/cleanup_post_borrowck.rs
index 8ff0fae7686..611d29a4ee2 100644
--- a/compiler/rustc_mir/src/transform/cleanup_post_borrowck.rs
+++ b/compiler/rustc_mir_transform/src/cleanup_post_borrowck.rs
@@ -18,7 +18,7 @@
 //! [`ForMatchGuard`]: rustc_middle::mir::FakeReadCause::ForMatchGuard
 //! [`Nop`]: rustc_middle::mir::StatementKind::Nop
 
-use crate::transform::MirPass;
+use crate::MirPass;
 use rustc_middle::mir::visit::MutVisitor;
 use rustc_middle::mir::{Body, BorrowKind, Location, Rvalue};
 use rustc_middle::mir::{Statement, StatementKind};
diff --git a/compiler/rustc_mir/src/transform/const_debuginfo.rs b/compiler/rustc_mir_transform/src/const_debuginfo.rs
index 3cdaf4c7dcd..b613634560f 100644
--- a/compiler/rustc_mir/src/transform/const_debuginfo.rs
+++ b/compiler/rustc_mir_transform/src/const_debuginfo.rs
@@ -9,7 +9,7 @@ use rustc_middle::{
     ty::TyCtxt,
 };
 
-use crate::transform::MirPass;
+use crate::MirPass;
 use rustc_index::{bit_set::BitSet, vec::IndexVec};
 
 pub struct ConstDebugInfo;
diff --git a/compiler/rustc_mir/src/transform/const_goto.rs b/compiler/rustc_mir_transform/src/const_goto.rs
index ba10b54c5ae..d319fdcaa6b 100644
--- a/compiler/rustc_mir/src/transform/const_goto.rs
+++ b/compiler/rustc_mir_transform/src/const_goto.rs
@@ -17,7 +17,7 @@
 //! }
 //! ```
 
-use crate::transform::MirPass;
+use crate::MirPass;
 use rustc_middle::mir::*;
 use rustc_middle::ty::TyCtxt;
 use rustc_middle::{mir::visit::Visitor, ty::ParamEnv};
diff --git a/compiler/rustc_mir/src/transform/const_prop.rs b/compiler/rustc_mir_transform/src/const_prop.rs
index 71c07be4c6d..51240ee0677 100644
--- a/compiler/rustc_mir/src/transform/const_prop.rs
+++ b/compiler/rustc_mir_transform/src/const_prop.rs
@@ -28,13 +28,13 @@ use rustc_target::abi::{HasDataLayout, Size, TargetDataLayout};
 use rustc_target::spec::abi::Abi;
 use rustc_trait_selection::traits;
 
-use crate::const_eval::ConstEvalErr;
-use crate::interpret::{
+use crate::MirPass;
+use rustc_mir::const_eval::ConstEvalErr;
+use rustc_mir::interpret::{
     self, compile_time_machine, AllocId, Allocation, ConstValue, CtfeValidationMode, Frame, ImmTy,
     Immediate, InterpCx, InterpResult, LocalState, LocalValue, MemPlace, MemoryKind, OpTy,
     Operand as InterpOperand, PlaceTy, Scalar, ScalarMaybeUninit, StackPopCleanup, StackPopUnwind,
 };
-use crate::transform::MirPass;
 
 /// The maximum number of bytes that we'll allocate space for a local or the return value.
 /// Needed for #66397, because otherwise we eval into large places and that can cause OOM or just
diff --git a/compiler/rustc_mir/src/transform/coverage/counters.rs b/compiler/rustc_mir_transform/src/coverage/counters.rs
index 6726b669ff2..6726b669ff2 100644
--- a/compiler/rustc_mir/src/transform/coverage/counters.rs
+++ b/compiler/rustc_mir_transform/src/coverage/counters.rs
diff --git a/compiler/rustc_mir/src/transform/coverage/debug.rs b/compiler/rustc_mir_transform/src/coverage/debug.rs
index 464079656f9..9de2f4a5f84 100644
--- a/compiler/rustc_mir/src/transform/coverage/debug.rs
+++ b/compiler/rustc_mir_transform/src/coverage/debug.rs
@@ -44,7 +44,7 @@
 //! points, which can be enabled via environment variable:
 //!
 //! ```shell
-//! RUSTC_LOG=rustc_mir::transform::coverage=debug
+//! RUSTC_LOG=rustc_mir_transform::transform::coverage=debug
 //! ```
 //!
 //! Other module paths with coverage-related debug logs may also be of interest, particularly for
@@ -52,7 +52,7 @@
 //! code generation pass). For example:
 //!
 //! ```shell
-//! RUSTC_LOG=rustc_mir::transform::coverage,rustc_codegen_ssa::coverageinfo,rustc_codegen_llvm::coverageinfo=debug
+//! RUSTC_LOG=rustc_mir_transform::transform::coverage,rustc_codegen_ssa::coverageinfo,rustc_codegen_llvm::coverageinfo=debug
 //! ```
 //!
 //! Coverage Debug Options
@@ -181,13 +181,11 @@ impl DebugOptions {
                             }
                         };
                     }
-                    _ => {
-                        bug!(
-                            "Unsupported setting `{}` in environment variable {}",
-                            option,
-                            RUSTC_COVERAGE_DEBUG_OPTIONS
-                        )
-                    }
+                    _ => bug!(
+                        "Unsupported setting `{}` in environment variable {}",
+                        option,
+                        RUSTC_COVERAGE_DEBUG_OPTIONS
+                    ),
                 };
             }
         }
diff --git a/compiler/rustc_mir/src/transform/coverage/graph.rs b/compiler/rustc_mir_transform/src/coverage/graph.rs
index d78ad6ce97f..d78ad6ce97f 100644
--- a/compiler/rustc_mir/src/transform/coverage/graph.rs
+++ b/compiler/rustc_mir_transform/src/coverage/graph.rs
diff --git a/compiler/rustc_mir/src/transform/coverage/mod.rs b/compiler/rustc_mir_transform/src/coverage/mod.rs
index f7fbea6ad53..f7f01915021 100644
--- a/compiler/rustc_mir/src/transform/coverage/mod.rs
+++ b/compiler/rustc_mir_transform/src/coverage/mod.rs
@@ -12,8 +12,8 @@ use counters::CoverageCounters;
 use graph::{BasicCoverageBlock, BasicCoverageBlockData, CoverageGraph};
 use spans::{CoverageSpan, CoverageSpans};
 
-use crate::transform::MirPass;
 use crate::util::pretty;
+use crate::MirPass;
 
 use rustc_data_structures::fingerprint::Fingerprint;
 use rustc_data_structures::graph::WithNumNodes;
diff --git a/compiler/rustc_mir/src/transform/coverage/query.rs b/compiler/rustc_mir_transform/src/coverage/query.rs
index 760f16eae6b..760f16eae6b 100644
--- a/compiler/rustc_mir/src/transform/coverage/query.rs
+++ b/compiler/rustc_mir_transform/src/coverage/query.rs
diff --git a/compiler/rustc_mir/src/transform/coverage/spans.rs b/compiler/rustc_mir_transform/src/coverage/spans.rs
index 08cc87ccc34..08cc87ccc34 100644
--- a/compiler/rustc_mir/src/transform/coverage/spans.rs
+++ b/compiler/rustc_mir_transform/src/coverage/spans.rs
diff --git a/compiler/rustc_mir/src/transform/coverage/test_macros/Cargo.toml b/compiler/rustc_mir_transform/src/coverage/test_macros/Cargo.toml
index cc93fd482b5..cc93fd482b5 100644
--- a/compiler/rustc_mir/src/transform/coverage/test_macros/Cargo.toml
+++ b/compiler/rustc_mir_transform/src/coverage/test_macros/Cargo.toml
diff --git a/compiler/rustc_mir/src/transform/coverage/test_macros/src/lib.rs b/compiler/rustc_mir_transform/src/coverage/test_macros/src/lib.rs
index 3d6095d2738..3d6095d2738 100644
--- a/compiler/rustc_mir/src/transform/coverage/test_macros/src/lib.rs
+++ b/compiler/rustc_mir_transform/src/coverage/test_macros/src/lib.rs
diff --git a/compiler/rustc_mir/src/transform/coverage/tests.rs b/compiler/rustc_mir_transform/src/coverage/tests.rs
index 14dd0a8b924..14dd0a8b924 100644
--- a/compiler/rustc_mir/src/transform/coverage/tests.rs
+++ b/compiler/rustc_mir_transform/src/coverage/tests.rs
diff --git a/compiler/rustc_mir/src/transform/deaggregator.rs b/compiler/rustc_mir_transform/src/deaggregator.rs
index 5bd7256c666..a5491f0ef4e 100644
--- a/compiler/rustc_mir/src/transform/deaggregator.rs
+++ b/compiler/rustc_mir_transform/src/deaggregator.rs
@@ -1,5 +1,5 @@
-use crate::transform::MirPass;
 use crate::util::expand_aggregate;
+use crate::MirPass;
 use rustc_middle::mir::*;
 use rustc_middle::ty::TyCtxt;
 
diff --git a/compiler/rustc_mir/src/transform/deduplicate_blocks.rs b/compiler/rustc_mir_transform/src/deduplicate_blocks.rs
index 912505c6598..8d2413433a9 100644
--- a/compiler/rustc_mir/src/transform/deduplicate_blocks.rs
+++ b/compiler/rustc_mir_transform/src/deduplicate_blocks.rs
@@ -3,7 +3,7 @@
 
 use std::{collections::hash_map::Entry, hash::Hash, hash::Hasher, iter};
 
-use crate::transform::MirPass;
+use crate::MirPass;
 
 use rustc_data_structures::fx::FxHashMap;
 use rustc_middle::mir::visit::MutVisitor;
diff --git a/compiler/rustc_mir/src/transform/dest_prop.rs b/compiler/rustc_mir_transform/src/dest_prop.rs
index 4f5a467a6ee..ec9279ff00c 100644
--- a/compiler/rustc_mir/src/transform/dest_prop.rs
+++ b/compiler/rustc_mir_transform/src/dest_prop.rs
@@ -96,11 +96,9 @@
 //! [previous attempt]: https://github.com/rust-lang/rust/pull/47954
 //! [subsequent approach]: https://github.com/rust-lang/rust/pull/71003
 
-use crate::dataflow::impls::{MaybeInitializedLocals, MaybeLiveLocals};
-use crate::dataflow::Analysis;
 use crate::{
-    transform::MirPass,
     util::{dump_mir, PassWhere},
+    MirPass,
 };
 use itertools::Itertools;
 use rustc_data_structures::unify::{InPlaceUnificationTable, UnifyKey};
@@ -115,6 +113,8 @@ use rustc_middle::mir::{
     Rvalue, Statement, StatementKind, Terminator, TerminatorKind,
 };
 use rustc_middle::ty::TyCtxt;
+use rustc_mir::dataflow::impls::{MaybeInitializedLocals, MaybeLiveLocals};
+use rustc_mir::dataflow::Analysis;
 
 // Empirical measurements have resulted in some observations:
 // - Running on a body with a single block and 500 locals takes barely any time
diff --git a/compiler/rustc_mir/src/transform/dump_mir.rs b/compiler/rustc_mir_transform/src/dump_mir.rs
index 5b6edf17d06..753948dacb3 100644
--- a/compiler/rustc_mir/src/transform/dump_mir.rs
+++ b/compiler/rustc_mir_transform/src/dump_mir.rs
@@ -5,8 +5,8 @@ use std::fmt;
 use std::fs::File;
 use std::io;
 
-use crate::transform::MirPass;
 use crate::util as mir_util;
+use crate::MirPass;
 use rustc_middle::mir::Body;
 use rustc_middle::ty::TyCtxt;
 use rustc_session::config::{OutputFilenames, OutputType};
diff --git a/compiler/rustc_mir/src/transform/early_otherwise_branch.rs b/compiler/rustc_mir_transform/src/early_otherwise_branch.rs
index e507bcb0f81..01d0c10eddc 100644
--- a/compiler/rustc_mir/src/transform/early_otherwise_branch.rs
+++ b/compiler/rustc_mir_transform/src/early_otherwise_branch.rs
@@ -1,4 +1,4 @@
-use crate::{transform::MirPass, util::patch::MirPatch};
+use crate::{util::patch::MirPatch, MirPass};
 use rustc_middle::mir::*;
 use rustc_middle::ty::{Ty, TyCtxt};
 use std::fmt::Debug;
diff --git a/compiler/rustc_mir/src/transform/elaborate_drops.rs b/compiler/rustc_mir_transform/src/elaborate_drops.rs
index 9b44af06b7d..5ed13a0268d 100644
--- a/compiler/rustc_mir/src/transform/elaborate_drops.rs
+++ b/compiler/rustc_mir_transform/src/elaborate_drops.rs
@@ -1,18 +1,18 @@
-use crate::dataflow;
-use crate::dataflow::impls::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
-use crate::dataflow::move_paths::{LookupResult, MoveData, MovePathIndex};
-use crate::dataflow::on_lookup_result_bits;
-use crate::dataflow::MoveDataParamEnv;
-use crate::dataflow::{on_all_children_bits, on_all_drop_children_bits};
-use crate::dataflow::{Analysis, ResultsCursor};
-use crate::transform::MirPass;
 use crate::util::elaborate_drops::{elaborate_drop, DropFlagState, Unwind};
 use crate::util::elaborate_drops::{DropElaborator, DropFlagMode, DropStyle};
 use crate::util::patch::MirPatch;
+use crate::MirPass;
 use rustc_data_structures::fx::FxHashMap;
 use rustc_index::bit_set::BitSet;
 use rustc_middle::mir::*;
 use rustc_middle::ty::{self, TyCtxt};
+use rustc_mir::dataflow;
+use rustc_mir::dataflow::impls::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
+use rustc_mir::dataflow::move_paths::{LookupResult, MoveData, MovePathIndex};
+use rustc_mir::dataflow::on_lookup_result_bits;
+use rustc_mir::dataflow::MoveDataParamEnv;
+use rustc_mir::dataflow::{on_all_children_bits, on_all_drop_children_bits};
+use rustc_mir::dataflow::{Analysis, ResultsCursor};
 use rustc_span::Span;
 use rustc_target::abi::VariantIdx;
 use std::fmt;
diff --git a/compiler/rustc_mir/src/transform/function_item_references.rs b/compiler/rustc_mir_transform/src/function_item_references.rs
index ba2c91a9347..d96a067fdda 100644
--- a/compiler/rustc_mir/src/transform/function_item_references.rs
+++ b/compiler/rustc_mir_transform/src/function_item_references.rs
@@ -11,7 +11,7 @@ use rustc_session::lint::builtin::FUNCTION_ITEM_REFERENCES;
 use rustc_span::{symbol::sym, Span};
 use rustc_target::spec::abi::Abi;
 
-use crate::transform::MirPass;
+use crate::MirPass;
 
 pub struct FunctionItemReferences;
 
diff --git a/compiler/rustc_mir/src/transform/generator.rs b/compiler/rustc_mir_transform/src/generator.rs
index acdaa5b4568..f2486b58aac 100644
--- a/compiler/rustc_mir/src/transform/generator.rs
+++ b/compiler/rustc_mir_transform/src/generator.rs
@@ -49,15 +49,11 @@
 //! For generators with state 1 (returned) and state 2 (poisoned) it does nothing.
 //! Otherwise it drops all the values in scope at the last suspension point.
 
-use crate::dataflow::impls::{
-    MaybeBorrowedLocals, MaybeLiveLocals, MaybeRequiresStorage, MaybeStorageLive,
-};
-use crate::dataflow::{self, Analysis};
-use crate::transform::simplify;
-use crate::transform::MirPass;
+use crate::simplify;
 use crate::util::dump_mir;
 use crate::util::expand_aggregate;
 use crate::util::storage;
+use crate::MirPass;
 use rustc_data_structures::fx::FxHashMap;
 use rustc_hir as hir;
 use rustc_hir::lang_items::LangItem;
@@ -68,6 +64,10 @@ use rustc_middle::mir::*;
 use rustc_middle::ty::subst::{Subst, SubstsRef};
 use rustc_middle::ty::GeneratorSubsts;
 use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt};
+use rustc_mir::dataflow::impls::{
+    MaybeBorrowedLocals, MaybeLiveLocals, MaybeRequiresStorage, MaybeStorageLive,
+};
+use rustc_mir::dataflow::{self, Analysis};
 use rustc_target::abi::VariantIdx;
 use rustc_target::spec::PanicStrategy;
 use std::{iter, ops};
diff --git a/compiler/rustc_mir/src/transform/inline.rs b/compiler/rustc_mir_transform/src/inline.rs
index 8e9da31eba1..d43528a1cf0 100644
--- a/compiler/rustc_mir/src/transform/inline.rs
+++ b/compiler/rustc_mir_transform/src/inline.rs
@@ -13,7 +13,7 @@ use rustc_span::{hygiene::ExpnKind, ExpnData, Span};
 use rustc_target::spec::abi::Abi;
 
 use super::simplify::{remove_dead_blocks, CfgSimplifier};
-use crate::transform::MirPass;
+use crate::MirPass;
 use std::iter;
 use std::ops::{Range, RangeFrom};
 
diff --git a/compiler/rustc_mir/src/transform/inline/cycle.rs b/compiler/rustc_mir_transform/src/inline/cycle.rs
index 385394ba67d..385394ba67d 100644
--- a/compiler/rustc_mir/src/transform/inline/cycle.rs
+++ b/compiler/rustc_mir_transform/src/inline/cycle.rs
diff --git a/compiler/rustc_mir/src/transform/instcombine.rs b/compiler/rustc_mir_transform/src/instcombine.rs
index 805f546104c..e15a69c95ae 100644
--- a/compiler/rustc_mir/src/transform/instcombine.rs
+++ b/compiler/rustc_mir_transform/src/instcombine.rs
@@ -1,6 +1,6 @@
 //! Performs various peephole optimizations.
 
-use crate::transform::MirPass;
+use crate::MirPass;
 use rustc_hir::Mutability;
 use rustc_middle::mir::{
     BinOp, Body, Constant, LocalDecls, Operand, Place, ProjectionElem, Rvalue, SourceInfo,
diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs
new file mode 100644
index 00000000000..93f0a7f3d04
--- /dev/null
+++ b/compiler/rustc_mir_transform/src/lib.rs
@@ -0,0 +1,632 @@
+#![feature(bindings_after_at)]
+#![feature(box_patterns)]
+#![feature(box_syntax)]
+#![feature(crate_visibility_modifier)]
+#![feature(const_panic)]
+#![feature(in_band_lifetimes)]
+#![feature(iter_zip)]
+#![feature(map_try_insert)]
+#![feature(min_specialization)]
+#![feature(option_get_or_insert_default)]
+#![feature(once_cell)]
+#![feature(never_type)]
+#![feature(trusted_step)]
+#![feature(try_blocks)]
+
+#[macro_use]
+extern crate tracing;
+#[macro_use]
+extern crate rustc_middle;
+
+use required_consts::RequiredConstsVisitor;
+use rustc_data_structures::fx::FxHashSet;
+use rustc_data_structures::steal::Steal;
+use rustc_hir as hir;
+use rustc_hir::def_id::{DefId, LocalDefId};
+use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
+use rustc_index::vec::IndexVec;
+use rustc_middle::mir::visit::Visitor as _;
+use rustc_middle::mir::{traversal, Body, ConstQualifs, MirPhase, Promoted};
+use rustc_middle::ty::query::Providers;
+use rustc_middle::ty::{self, TyCtxt, TypeFoldable};
+use rustc_mir::util;
+use rustc_span::{Span, Symbol};
+
+mod abort_unwinding_calls;
+mod add_call_guards;
+mod add_moves_for_packed_drops;
+mod add_retag;
+mod check_const_item_mutation;
+mod check_packed_ref;
+pub mod check_unsafety;
+mod cleanup_post_borrowck;
+mod const_debuginfo;
+mod const_goto;
+mod const_prop;
+mod coverage;
+mod deaggregator;
+mod deduplicate_blocks;
+mod dest_prop;
+pub mod dump_mir;
+mod early_otherwise_branch;
+mod elaborate_drops;
+mod function_item_references;
+mod generator;
+mod inline;
+mod instcombine;
+mod lower_intrinsics;
+mod lower_slice_len;
+mod match_branches;
+mod multiple_return_terminators;
+mod nrvo;
+mod remove_noop_landing_pads;
+mod remove_storage_markers;
+mod remove_unneeded_drops;
+mod remove_zsts;
+mod required_consts;
+mod separate_const_switch;
+mod shim;
+mod simplify;
+mod simplify_branches;
+mod simplify_comparison_integral;
+mod simplify_try;
+mod uninhabited_enum_branching;
+mod unreachable_prop;
+
+use rustc_mir::transform::check_consts;
+use rustc_mir::transform::promote_consts;
+use rustc_mir::transform::rustc_peek;
+use rustc_mir::transform::validate;
+use rustc_mir::transform::MirPass;
+
+pub fn provide(providers: &mut Providers) {
+    check_unsafety::provide(providers);
+    check_packed_ref::provide(providers);
+    coverage::query::provide(providers);
+    shim::provide(providers);
+    *providers = Providers {
+        mir_keys,
+        mir_const,
+        mir_const_qualif: |tcx, def_id| {
+            let def_id = def_id.expect_local();
+            if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
+                tcx.mir_const_qualif_const_arg(def)
+            } else {
+                mir_const_qualif(tcx, ty::WithOptConstParam::unknown(def_id))
+            }
+        },
+        mir_const_qualif_const_arg: |tcx, (did, param_did)| {
+            mir_const_qualif(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
+        },
+        mir_promoted,
+        mir_drops_elaborated_and_const_checked,
+        mir_for_ctfe,
+        mir_for_ctfe_of_const_arg,
+        optimized_mir,
+        is_mir_available,
+        is_ctfe_mir_available: |tcx, did| is_mir_available(tcx, did),
+        mir_callgraph_reachable: inline::cycle::mir_callgraph_reachable,
+        mir_inliner_callees: inline::cycle::mir_inliner_callees,
+        promoted_mir: |tcx, def_id| {
+            let def_id = def_id.expect_local();
+            if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
+                tcx.promoted_mir_of_const_arg(def)
+            } else {
+                promoted_mir(tcx, ty::WithOptConstParam::unknown(def_id))
+            }
+        },
+        promoted_mir_of_const_arg: |tcx, (did, param_did)| {
+            promoted_mir(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) })
+        },
+        ..*providers
+    };
+}
+
+fn is_mir_available(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
+    let def_id = def_id.expect_local();
+    tcx.mir_keys(()).contains(&def_id)
+}
+
+/// Finds the full set of `DefId`s within the current crate that have
+/// MIR associated with them.
+fn mir_keys(tcx: TyCtxt<'_>, (): ()) -> FxHashSet<LocalDefId> {
+    let mut set = FxHashSet::default();
+
+    // All body-owners have MIR associated with them.
+    set.extend(tcx.body_owners());
+
+    // Additionally, tuple struct/variant constructors have MIR, but
+    // they don't have a BodyId, so we need to build them separately.
+    struct GatherCtors<'a, 'tcx> {
+        tcx: TyCtxt<'tcx>,
+        set: &'a mut FxHashSet<LocalDefId>,
+    }
+    impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> {
+        fn visit_variant_data(
+            &mut self,
+            v: &'tcx hir::VariantData<'tcx>,
+            _: Symbol,
+            _: &'tcx hir::Generics<'tcx>,
+            _: hir::HirId,
+            _: Span,
+        ) {
+            if let hir::VariantData::Tuple(_, hir_id) = *v {
+                self.set.insert(self.tcx.hir().local_def_id(hir_id));
+            }
+            intravisit::walk_struct_def(self, v)
+        }
+        type Map = intravisit::ErasedMap<'tcx>;
+        fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
+            NestedVisitorMap::None
+        }
+    }
+    tcx.hir()
+        .krate()
+        .visit_all_item_likes(&mut GatherCtors { tcx, set: &mut set }.as_deep_visitor());
+
+    set
+}
+
+fn run_passes(
+    tcx: TyCtxt<'tcx>,
+    body: &mut Body<'tcx>,
+    mir_phase: MirPhase,
+    passes: &[&[&dyn MirPass<'tcx>]],
+) {
+    let phase_index = mir_phase.phase_index();
+    let validate = tcx.sess.opts.debugging_opts.validate_mir;
+
+    if body.phase >= mir_phase {
+        return;
+    }
+
+    if validate {
+        validate::Validator { when: format!("input to phase {:?}", mir_phase), mir_phase }
+            .run_pass(tcx, body);
+    }
+
+    let mut index = 0;
+    let mut run_pass = |pass: &dyn MirPass<'tcx>| {
+        let run_hooks = |body: &_, index, is_after| {
+            dump_mir::on_mir_pass(
+                tcx,
+                &format_args!("{:03}-{:03}", phase_index, index),
+                &pass.name(),
+                body,
+                is_after,
+            );
+        };
+        run_hooks(body, index, false);
+        pass.run_pass(tcx, body);
+        run_hooks(body, index, true);
+
+        if validate {
+            validate::Validator {
+                when: format!("after {} in phase {:?}", pass.name(), mir_phase),
+                mir_phase,
+            }
+            .run_pass(tcx, body);
+        }
+
+        index += 1;
+    };
+
+    for pass_group in passes {
+        for pass in *pass_group {
+            run_pass(*pass);
+        }
+    }
+
+    body.phase = mir_phase;
+
+    if mir_phase == MirPhase::Optimization {
+        validate::Validator { when: format!("end of phase {:?}", mir_phase), mir_phase }
+            .run_pass(tcx, body);
+    }
+}
+
+fn mir_const_qualif(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> ConstQualifs {
+    let const_kind = tcx.hir().body_const_context(def.did);
+
+    // No need to const-check a non-const `fn`.
+    if const_kind.is_none() {
+        return Default::default();
+    }
+
+    // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
+    // cannot yet be stolen), because `mir_promoted()`, which steals
+    // from `mir_const(), forces this query to execute before
+    // performing the steal.
+    let body = &tcx.mir_const(def).borrow();
+
+    if body.return_ty().references_error() {
+        tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
+        return Default::default();
+    }
+
+    let ccx = check_consts::ConstCx { body, tcx, const_kind, param_env: tcx.param_env(def.did) };
+
+    let mut validator = check_consts::check::Checker::new(&ccx);
+    validator.check_body();
+
+    // We return the qualifs in the return place for every MIR body, even though it is only used
+    // when deciding to promote a reference to a `const` for now.
+    validator.qualifs_in_return_place()
+}
+
+/// Make MIR ready for const evaluation. This is run on all MIR, not just on consts!
+fn mir_const<'tcx>(
+    tcx: TyCtxt<'tcx>,
+    def: ty::WithOptConstParam<LocalDefId>,
+) -> &'tcx Steal<Body<'tcx>> {
+    if let Some(def) = def.try_upgrade(tcx) {
+        return tcx.mir_const(def);
+    }
+
+    // Unsafety check uses the raw mir, so make sure it is run.
+    if !tcx.sess.opts.debugging_opts.thir_unsafeck {
+        if let Some(param_did) = def.const_param_did {
+            tcx.ensure().unsafety_check_result_for_const_arg((def.did, param_did));
+        } else {
+            tcx.ensure().unsafety_check_result(def.did);
+        }
+    }
+
+    let mut body = tcx.mir_built(def).steal();
+
+    util::dump_mir(tcx, None, "mir_map", &0, &body, |_, _| Ok(()));
+
+    run_passes(
+        tcx,
+        &mut body,
+        MirPhase::Const,
+        &[&[
+            // MIR-level lints.
+            &check_packed_ref::CheckPackedRef,
+            &check_const_item_mutation::CheckConstItemMutation,
+            &function_item_references::FunctionItemReferences,
+            // What we need to do constant evaluation.
+            &simplify::SimplifyCfg::new("initial"),
+            &rustc_peek::SanityCheck,
+        ]],
+    );
+    tcx.alloc_steal_mir(body)
+}
+
+/// Compute the main MIR body and the list of MIR bodies of the promoteds.
+fn mir_promoted(
+    tcx: TyCtxt<'tcx>,
+    def: ty::WithOptConstParam<LocalDefId>,
+) -> (&'tcx Steal<Body<'tcx>>, &'tcx Steal<IndexVec<Promoted, Body<'tcx>>>) {
+    if let Some(def) = def.try_upgrade(tcx) {
+        return tcx.mir_promoted(def);
+    }
+
+    // Ensure that we compute the `mir_const_qualif` for constants at
+    // this point, before we steal the mir-const result.
+    // Also this means promotion can rely on all const checks having been done.
+    let _ = tcx.mir_const_qualif_opt_const_arg(def);
+    let _ = tcx.mir_abstract_const_opt_const_arg(def.to_global());
+    let mut body = tcx.mir_const(def).steal();
+
+    let mut required_consts = Vec::new();
+    let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts);
+    for (bb, bb_data) in traversal::reverse_postorder(&body) {
+        required_consts_visitor.visit_basic_block_data(bb, bb_data);
+    }
+    body.required_consts = required_consts;
+
+    let promote_pass = promote_consts::PromoteTemps::default();
+    let promote: &[&dyn MirPass<'tcx>] = &[
+        // What we need to run borrowck etc.
+        &promote_pass,
+        &simplify::SimplifyCfg::new("promote-consts"),
+    ];
+
+    let opt_coverage: &[&dyn MirPass<'tcx>] =
+        if tcx.sess.instrument_coverage() { &[&coverage::InstrumentCoverage] } else { &[] };
+
+    run_passes(tcx, &mut body, MirPhase::ConstPromotion, &[promote, opt_coverage]);
+
+    let promoted = promote_pass.promoted_fragments.into_inner();
+    (tcx.alloc_steal_mir(body), tcx.alloc_steal_promoted(promoted))
+}
+
+/// Compute the MIR that is used during CTFE (and thus has no optimizations run on it)
+fn mir_for_ctfe<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Body<'tcx> {
+    let did = def_id.expect_local();
+    if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) {
+        tcx.mir_for_ctfe_of_const_arg(def)
+    } else {
+        tcx.arena.alloc(inner_mir_for_ctfe(tcx, ty::WithOptConstParam::unknown(did)))
+    }
+}
+
+/// Same as `mir_for_ctfe`, but used to get the MIR of a const generic parameter.
+/// The docs on `WithOptConstParam` explain this a bit more, but the TLDR is that
+/// we'd get cycle errors with `mir_for_ctfe`, because typeck would need to typeck
+/// the const parameter while type checking the main body, which in turn would try
+/// to type check the main body again.
+fn mir_for_ctfe_of_const_arg<'tcx>(
+    tcx: TyCtxt<'tcx>,
+    (did, param_did): (LocalDefId, DefId),
+) -> &'tcx Body<'tcx> {
+    tcx.arena.alloc(inner_mir_for_ctfe(
+        tcx,
+        ty::WithOptConstParam { did, const_param_did: Some(param_did) },
+    ))
+}
+
+fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
+    // FIXME: don't duplicate this between the optimized_mir/mir_for_ctfe queries
+    if tcx.is_constructor(def.did.to_def_id()) {
+        // There's no reason to run all of the MIR passes on constructors when
+        // we can just output the MIR we want directly. This also saves const
+        // qualification and borrow checking the trouble of special casing
+        // constructors.
+        return shim::build_adt_ctor(tcx, def.did.to_def_id());
+    }
+
+    let context = tcx
+        .hir()
+        .body_const_context(def.did)
+        .expect("mir_for_ctfe should not be used for runtime functions");
+
+    let mut body = tcx.mir_drops_elaborated_and_const_checked(def).borrow().clone();
+
+    match context {
+        // Do not const prop functions, either they get executed at runtime or exported to metadata,
+        // so we run const prop on them, or they don't, in which case we const evaluate some control
+        // flow paths of the function and any errors in those paths will get emitted as const eval
+        // errors.
+        hir::ConstContext::ConstFn => {}
+        // Static items always get evaluated, so we can just let const eval see if any erroneous
+        // control flow paths get executed.
+        hir::ConstContext::Static(_) => {}
+        // Associated constants get const prop run so we detect common failure situations in the
+        // crate that defined the constant.
+        // Technically we want to not run on regular const items, but oli-obk doesn't know how to
+        // conveniently detect that at this point without looking at the HIR.
+        hir::ConstContext::Const => {
+            #[rustfmt::skip]
+            let optimizations: &[&dyn MirPass<'_>] = &[
+                &const_prop::ConstProp,
+            ];
+
+            #[rustfmt::skip]
+            run_passes(
+                tcx,
+                &mut body,
+                MirPhase::Optimization,
+                &[
+                    optimizations,
+                ],
+            );
+        }
+    }
+
+    debug_assert!(!body.has_free_regions(tcx), "Free regions in MIR for CTFE");
+
+    body
+}
+
+/// Obtain just the main MIR (no promoteds) and run some cleanups on it. This also runs
+/// mir borrowck *before* doing so in order to ensure that borrowck can be run and doesn't
+/// end up missing the source MIR due to stealing happening.
+fn mir_drops_elaborated_and_const_checked<'tcx>(
+    tcx: TyCtxt<'tcx>,
+    def: ty::WithOptConstParam<LocalDefId>,
+) -> &'tcx Steal<Body<'tcx>> {
+    if let Some(def) = def.try_upgrade(tcx) {
+        return tcx.mir_drops_elaborated_and_const_checked(def);
+    }
+
+    // (Mir-)Borrowck uses `mir_promoted`, so we have to force it to
+    // execute before we can steal.
+    if let Some(param_did) = def.const_param_did {
+        tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
+    } else {
+        tcx.ensure().mir_borrowck(def.did);
+    }
+
+    let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
+    use rustc_middle::hir::map::blocks::FnLikeNode;
+    let is_fn_like = FnLikeNode::from_node(tcx.hir().get(hir_id)).is_some();
+    if is_fn_like {
+        let did = def.did.to_def_id();
+        let def = ty::WithOptConstParam::unknown(did);
+
+        // Do not compute the mir call graph without said call graph actually being used.
+        if inline::is_enabled(tcx) {
+            let _ = tcx.mir_inliner_callees(ty::InstanceDef::Item(def));
+        }
+    }
+
+    let (body, _) = tcx.mir_promoted(def);
+    let mut body = body.steal();
+
+    run_post_borrowck_cleanup_passes(tcx, &mut body);
+    check_consts::post_drop_elaboration::check_live_drops(tcx, &body);
+    tcx.alloc_steal_mir(body)
+}
+
+/// After this series of passes, no lifetime analysis based on borrowing can be done.
+fn run_post_borrowck_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
+    debug!("post_borrowck_cleanup({:?})", body.source.def_id());
+
+    let post_borrowck_cleanup: &[&dyn MirPass<'tcx>] = &[
+        // Remove all things only needed by analysis
+        &simplify_branches::SimplifyBranches::new("initial"),
+        &remove_noop_landing_pads::RemoveNoopLandingPads,
+        &cleanup_post_borrowck::CleanupNonCodegenStatements,
+        &simplify::SimplifyCfg::new("early-opt"),
+        // These next passes must be executed together
+        &add_call_guards::CriticalCallEdges,
+        &elaborate_drops::ElaborateDrops,
+        // This will remove extraneous landing pads which are no longer
+        // necessary as well as well as forcing any call in a non-unwinding
+        // function calling a possibly-unwinding function to abort the process.
+        &abort_unwinding_calls::AbortUnwindingCalls,
+        // AddMovesForPackedDrops needs to run after drop
+        // elaboration.
+        &add_moves_for_packed_drops::AddMovesForPackedDrops,
+        // `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late,
+        // but before optimizations begin.
+        &add_retag::AddRetag,
+        &lower_intrinsics::LowerIntrinsics,
+        &simplify::SimplifyCfg::new("elaborate-drops"),
+        // `Deaggregator` is conceptually part of MIR building, some backends rely on it happening
+        // and it can help optimizations.
+        &deaggregator::Deaggregator,
+    ];
+
+    run_passes(tcx, body, MirPhase::DropLowering, &[post_borrowck_cleanup]);
+}
+
+fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
+    let mir_opt_level = tcx.sess.mir_opt_level();
+
+    // Lowering generator control-flow and variables has to happen before we do anything else
+    // to them. We run some optimizations before that, because they may be harder to do on the state
+    // machine than on MIR with async primitives.
+    let optimizations_with_generators: &[&dyn MirPass<'tcx>] = &[
+        &lower_slice_len::LowerSliceLenCalls, // has to be done before inlining, otherwise actual call will be almost always inlined. Also simple, so can just do first
+        &unreachable_prop::UnreachablePropagation,
+        &uninhabited_enum_branching::UninhabitedEnumBranching,
+        &simplify::SimplifyCfg::new("after-uninhabited-enum-branching"),
+        &inline::Inline,
+        &generator::StateTransform,
+    ];
+
+    // Even if we don't do optimizations, we still have to lower generators for codegen.
+    let no_optimizations_with_generators: &[&dyn MirPass<'tcx>] = &[&generator::StateTransform];
+
+    // The main optimizations that we do on MIR.
+    let optimizations: &[&dyn MirPass<'tcx>] = &[
+        &remove_storage_markers::RemoveStorageMarkers,
+        &remove_zsts::RemoveZsts,
+        &const_goto::ConstGoto,
+        &remove_unneeded_drops::RemoveUnneededDrops,
+        &match_branches::MatchBranchSimplification,
+        // inst combine is after MatchBranchSimplification to clean up Ne(_1, false)
+        &multiple_return_terminators::MultipleReturnTerminators,
+        &instcombine::InstCombine,
+        &separate_const_switch::SeparateConstSwitch,
+        &const_prop::ConstProp,
+        &simplify_branches::SimplifyBranches::new("after-const-prop"),
+        &early_otherwise_branch::EarlyOtherwiseBranch,
+        &simplify_comparison_integral::SimplifyComparisonIntegral,
+        &simplify_try::SimplifyArmIdentity,
+        &simplify_try::SimplifyBranchSame,
+        &dest_prop::DestinationPropagation,
+        &simplify_branches::SimplifyBranches::new("final"),
+        &remove_noop_landing_pads::RemoveNoopLandingPads,
+        &simplify::SimplifyCfg::new("final"),
+        &nrvo::RenameReturnPlace,
+        &const_debuginfo::ConstDebugInfo,
+        &simplify::SimplifyLocals,
+        &multiple_return_terminators::MultipleReturnTerminators,
+        &deduplicate_blocks::DeduplicateBlocks,
+    ];
+
+    // Optimizations to run even if mir optimizations have been disabled.
+    let no_optimizations: &[&dyn MirPass<'tcx>] = &[
+        // FIXME(#70073): This pass is responsible for both optimization as well as some lints.
+        &const_prop::ConstProp,
+    ];
+
+    // Some cleanup necessary at least for LLVM and potentially other codegen backends.
+    let pre_codegen_cleanup: &[&dyn MirPass<'tcx>] = &[
+        &add_call_guards::CriticalCallEdges,
+        // Dump the end result for testing and debugging purposes.
+        &dump_mir::Marker("PreCodegen"),
+    ];
+
+    // End of pass declarations, now actually run the passes.
+    // Generator Lowering
+    #[rustfmt::skip]
+    run_passes(
+        tcx,
+        body,
+        MirPhase::GeneratorLowering,
+        &[
+            if mir_opt_level > 0 {
+                optimizations_with_generators
+            } else {
+                no_optimizations_with_generators
+            }
+        ],
+    );
+
+    // Main optimization passes
+    #[rustfmt::skip]
+    run_passes(
+        tcx,
+        body,
+        MirPhase::Optimization,
+        &[
+            if mir_opt_level > 0 { optimizations } else { no_optimizations },
+            pre_codegen_cleanup,
+        ],
+    );
+}
+
+/// Optimize the MIR and prepare it for codegen.
+fn optimized_mir<'tcx>(tcx: TyCtxt<'tcx>, did: DefId) -> &'tcx Body<'tcx> {
+    let did = did.expect_local();
+    assert_eq!(ty::WithOptConstParam::try_lookup(did, tcx), None);
+    tcx.arena.alloc(inner_optimized_mir(tcx, did))
+}
+
+fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> {
+    if tcx.is_constructor(did.to_def_id()) {
+        // There's no reason to run all of the MIR passes on constructors when
+        // we can just output the MIR we want directly. This also saves const
+        // qualification and borrow checking the trouble of special casing
+        // constructors.
+        return shim::build_adt_ctor(tcx, did.to_def_id());
+    }
+
+    match tcx.hir().body_const_context(did) {
+        // Run the `mir_for_ctfe` query, which depends on `mir_drops_elaborated_and_const_checked`
+        // which we are going to steal below. Thus we need to run `mir_for_ctfe` first, so it
+        // computes and caches its result.
+        Some(hir::ConstContext::ConstFn) => tcx.ensure().mir_for_ctfe(did),
+        None => {}
+        Some(other) => panic!("do not use `optimized_mir` for constants: {:?}", other),
+    }
+    let mut body =
+        tcx.mir_drops_elaborated_and_const_checked(ty::WithOptConstParam::unknown(did)).steal();
+    run_optimization_passes(tcx, &mut body);
+
+    debug_assert!(!body.has_free_regions(tcx), "Free regions in optimized MIR");
+
+    body
+}
+
+/// Fetch all the promoteds of an item and prepare their MIR bodies to be ready for
+/// constant evaluation once all substitutions become known.
+fn promoted_mir<'tcx>(
+    tcx: TyCtxt<'tcx>,
+    def: ty::WithOptConstParam<LocalDefId>,
+) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
+    if tcx.is_constructor(def.did.to_def_id()) {
+        return tcx.arena.alloc(IndexVec::new());
+    }
+
+    if let Some(param_did) = def.const_param_did {
+        tcx.ensure().mir_borrowck_const_arg((def.did, param_did));
+    } else {
+        tcx.ensure().mir_borrowck(def.did);
+    }
+    let (_, promoted) = tcx.mir_promoted(def);
+    let mut promoted = promoted.steal();
+
+    for body in &mut promoted {
+        run_post_borrowck_cleanup_passes(tcx, body);
+    }
+
+    debug_assert!(!promoted.has_free_regions(tcx), "Free regions in promoted MIR");
+
+    tcx.arena.alloc(promoted)
+}
diff --git a/compiler/rustc_mir/src/transform/lower_intrinsics.rs b/compiler/rustc_mir_transform/src/lower_intrinsics.rs
index e9f1d4f2ce8..2f89b041c27 100644
--- a/compiler/rustc_mir/src/transform/lower_intrinsics.rs
+++ b/compiler/rustc_mir_transform/src/lower_intrinsics.rs
@@ -1,6 +1,6 @@
 //! Lowers intrinsic calls
 
-use crate::transform::MirPass;
+use crate::MirPass;
 use rustc_middle::mir::*;
 use rustc_middle::ty::subst::SubstsRef;
 use rustc_middle::ty::{self, Ty, TyCtxt};
diff --git a/compiler/rustc_mir/src/transform/lower_slice_len.rs b/compiler/rustc_mir_transform/src/lower_slice_len.rs
index c3eb2d9f921..eac2b97a14c 100644
--- a/compiler/rustc_mir/src/transform/lower_slice_len.rs
+++ b/compiler/rustc_mir_transform/src/lower_slice_len.rs
@@ -1,11 +1,11 @@
 //! This pass lowers calls to core::slice::len to just Len op.
 //! It should run before inlining!
 
-use crate::transform::MirPass;
 use rustc_hir::def_id::DefId;
 use rustc_index::vec::IndexVec;
 use rustc_middle::mir::*;
 use rustc_middle::ty::{self, TyCtxt};
+use rustc_mir::transform::MirPass;
 
 pub struct LowerSliceLenCalls;
 
diff --git a/compiler/rustc_mir/src/transform/match_branches.rs b/compiler/rustc_mir_transform/src/match_branches.rs
index 37a3fa50a52..24eaf278977 100644
--- a/compiler/rustc_mir/src/transform/match_branches.rs
+++ b/compiler/rustc_mir_transform/src/match_branches.rs
@@ -1,4 +1,4 @@
-use crate::transform::MirPass;
+use crate::MirPass;
 use rustc_middle::mir::*;
 use rustc_middle::ty::TyCtxt;
 use std::iter;
@@ -134,7 +134,7 @@ impl<'tcx> MirPass<'tcx> for MatchBranchSimplification {
                             let const_cmp = Operand::const_from_scalar(
                                 tcx,
                                 switch_ty,
-                                crate::interpret::Scalar::from_uint(val, size),
+                                rustc_mir::interpret::Scalar::from_uint(val, size),
                                 rustc_span::DUMMY_SP,
                             );
                             let op = if f_b { BinOp::Eq } else { BinOp::Ne };
diff --git a/compiler/rustc_mir/src/transform/multiple_return_terminators.rs b/compiler/rustc_mir_transform/src/multiple_return_terminators.rs
index cd2db180552..b614917a883 100644
--- a/compiler/rustc_mir/src/transform/multiple_return_terminators.rs
+++ b/compiler/rustc_mir_transform/src/multiple_return_terminators.rs
@@ -1,7 +1,7 @@
 //! This pass removes jumps to basic blocks containing only a return, and replaces them with a
 //! return instead.
 
-use crate::transform::{simplify, MirPass};
+use crate::{simplify, MirPass};
 use rustc_index::bit_set::BitSet;
 use rustc_middle::mir::*;
 use rustc_middle::ty::TyCtxt;
diff --git a/compiler/rustc_mir/src/transform/nrvo.rs b/compiler/rustc_mir_transform/src/nrvo.rs
index 445dc12909c..3ac4e77cf9a 100644
--- a/compiler/rustc_mir/src/transform/nrvo.rs
+++ b/compiler/rustc_mir_transform/src/nrvo.rs
@@ -6,7 +6,7 @@ use rustc_middle::mir::visit::{MutVisitor, NonUseContext, PlaceContext, Visitor}
 use rustc_middle::mir::{self, BasicBlock, Local, Location};
 use rustc_middle::ty::TyCtxt;
 
-use crate::transform::MirPass;
+use crate::MirPass;
 
 /// This pass looks for MIR that always copies the same local into the return place and eliminates
 /// the copy by renaming all uses of that local to `_0`.
diff --git a/compiler/rustc_mir/src/transform/remove_noop_landing_pads.rs b/compiler/rustc_mir_transform/src/remove_noop_landing_pads.rs
index 5347846a4b3..52144cbaa87 100644
--- a/compiler/rustc_mir/src/transform/remove_noop_landing_pads.rs
+++ b/compiler/rustc_mir_transform/src/remove_noop_landing_pads.rs
@@ -1,5 +1,5 @@
-use crate::transform::MirPass;
 use crate::util::patch::MirPatch;
+use crate::MirPass;
 use rustc_index::bit_set::BitSet;
 use rustc_middle::mir::*;
 use rustc_middle::ty::TyCtxt;
diff --git a/compiler/rustc_mir/src/transform/remove_storage_markers.rs b/compiler/rustc_mir_transform/src/remove_storage_markers.rs
index 2d529feb072..0c7323cbac5 100644
--- a/compiler/rustc_mir/src/transform/remove_storage_markers.rs
+++ b/compiler/rustc_mir_transform/src/remove_storage_markers.rs
@@ -1,6 +1,6 @@
 //! This pass removes storage markers if they won't be emitted during codegen.
 
-use crate::transform::MirPass;
+use crate::MirPass;
 use rustc_middle::mir::*;
 use rustc_middle::ty::TyCtxt;
 
diff --git a/compiler/rustc_mir/src/transform/remove_unneeded_drops.rs b/compiler/rustc_mir_transform/src/remove_unneeded_drops.rs
index 02e45021a0a..5c9d04a08bf 100644
--- a/compiler/rustc_mir/src/transform/remove_unneeded_drops.rs
+++ b/compiler/rustc_mir_transform/src/remove_unneeded_drops.rs
@@ -1,6 +1,6 @@
 //! This pass replaces a drop of a type that does not need dropping, with a goto
 
-use crate::transform::MirPass;
+use crate::MirPass;
 use rustc_middle::mir::*;
 use rustc_middle::ty::TyCtxt;
 
diff --git a/compiler/rustc_mir/src/transform/remove_zsts.rs b/compiler/rustc_mir_transform/src/remove_zsts.rs
index 03277b1b2e0..25e3c52132c 100644
--- a/compiler/rustc_mir/src/transform/remove_zsts.rs
+++ b/compiler/rustc_mir_transform/src/remove_zsts.rs
@@ -1,6 +1,6 @@
 //! Removes assignments to ZST places.
 
-use crate::transform::MirPass;
+use crate::MirPass;
 use rustc_middle::mir::tcx::PlaceTy;
 use rustc_middle::mir::{Body, LocalDecls, Place, StatementKind};
 use rustc_middle::ty::{self, Ty, TyCtxt};
diff --git a/compiler/rustc_mir/src/transform/required_consts.rs b/compiler/rustc_mir_transform/src/required_consts.rs
index 8b64ad65ab3..8b64ad65ab3 100644
--- a/compiler/rustc_mir/src/transform/required_consts.rs
+++ b/compiler/rustc_mir_transform/src/required_consts.rs
diff --git a/compiler/rustc_mir/src/transform/separate_const_switch.rs b/compiler/rustc_mir_transform/src/separate_const_switch.rs
index 87cd27984a0..1945e551485 100644
--- a/compiler/rustc_mir/src/transform/separate_const_switch.rs
+++ b/compiler/rustc_mir_transform/src/separate_const_switch.rs
@@ -37,7 +37,7 @@
 //! simplicity rather than completeness (it notably
 //! sometimes duplicates abusively).
 
-use crate::transform::MirPass;
+use crate::MirPass;
 use rustc_middle::mir::*;
 use rustc_middle::ty::TyCtxt;
 use smallvec::SmallVec;
diff --git a/compiler/rustc_mir/src/shim.rs b/compiler/rustc_mir_transform/src/shim.rs
index 8083ec95447..c57c1e12416 100644
--- a/compiler/rustc_mir/src/shim.rs
+++ b/compiler/rustc_mir_transform/src/shim.rs
@@ -15,13 +15,13 @@ use rustc_target::spec::abi::Abi;
 use std::fmt;
 use std::iter;
 
-use crate::transform::{
-    abort_unwinding_calls, add_call_guards, add_moves_for_packed_drops, remove_noop_landing_pads,
-    run_passes, simplify,
-};
 use crate::util::elaborate_drops::{self, DropElaborator, DropFlagMode, DropStyle};
 use crate::util::expand_aggregate;
 use crate::util::patch::MirPatch;
+use crate::{
+    abort_unwinding_calls, add_call_guards, add_moves_for_packed_drops, remove_noop_landing_pads,
+    run_passes, simplify,
+};
 
 pub fn provide(providers: &mut Providers) {
     providers.mir_shims = make_shim;
diff --git a/compiler/rustc_mir/src/transform/simplify.rs b/compiler/rustc_mir_transform/src/simplify.rs
index 3ecb5133e3b..e3cfd1d0afc 100644
--- a/compiler/rustc_mir/src/transform/simplify.rs
+++ b/compiler/rustc_mir_transform/src/simplify.rs
@@ -27,7 +27,7 @@
 //! naively generate still contains the `_a = ()` write in the unreachable block "after" the
 //! return.
 
-use crate::transform::MirPass;
+use crate::MirPass;
 use rustc_index::vec::{Idx, IndexVec};
 use rustc_middle::mir::coverage::*;
 use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
diff --git a/compiler/rustc_mir/src/transform/simplify_branches.rs b/compiler/rustc_mir_transform/src/simplify_branches.rs
index a9a45e61a38..df90cfa318d 100644
--- a/compiler/rustc_mir/src/transform/simplify_branches.rs
+++ b/compiler/rustc_mir_transform/src/simplify_branches.rs
@@ -1,6 +1,6 @@
 //! A pass that simplifies branches when their condition is known.
 
-use crate::transform::MirPass;
+use crate::MirPass;
 use rustc_middle::mir::*;
 use rustc_middle::ty::TyCtxt;
 
diff --git a/compiler/rustc_mir/src/transform/simplify_comparison_integral.rs b/compiler/rustc_mir_transform/src/simplify_comparison_integral.rs
index 948fcd9f455..948fcd9f455 100644
--- a/compiler/rustc_mir/src/transform/simplify_comparison_integral.rs
+++ b/compiler/rustc_mir_transform/src/simplify_comparison_integral.rs
diff --git a/compiler/rustc_mir/src/transform/simplify_try.rs b/compiler/rustc_mir_transform/src/simplify_try.rs
index 7c35dab694f..fd36671b36f 100644
--- a/compiler/rustc_mir/src/transform/simplify_try.rs
+++ b/compiler/rustc_mir_transform/src/simplify_try.rs
@@ -9,7 +9,7 @@
 //!
 //! into just `x`.
 
-use crate::transform::{simplify, MirPass};
+use crate::{simplify, MirPass};
 use itertools::Itertools as _;
 use rustc_index::{bit_set::BitSet, vec::IndexVec};
 use rustc_middle::mir::visit::{NonUseContext, PlaceContext, Visitor};
diff --git a/compiler/rustc_mir/src/transform/uninhabited_enum_branching.rs b/compiler/rustc_mir_transform/src/uninhabited_enum_branching.rs
index 5c6c158d46e..5cef64d7786 100644
--- a/compiler/rustc_mir/src/transform/uninhabited_enum_branching.rs
+++ b/compiler/rustc_mir_transform/src/uninhabited_enum_branching.rs
@@ -1,6 +1,6 @@
 //! A pass that eliminates branches on uninhabited enum variants.
 
-use crate::transform::MirPass;
+use crate::MirPass;
 use rustc_data_structures::stable_set::FxHashSet;
 use rustc_middle::mir::{
     BasicBlock, BasicBlockData, Body, Local, Operand, Rvalue, StatementKind, SwitchTargets,
diff --git a/compiler/rustc_mir/src/transform/unreachable_prop.rs b/compiler/rustc_mir_transform/src/unreachable_prop.rs
index e7fb6b4f6b4..baf381081dd 100644
--- a/compiler/rustc_mir/src/transform/unreachable_prop.rs
+++ b/compiler/rustc_mir_transform/src/unreachable_prop.rs
@@ -2,8 +2,8 @@
 //! when all of their successors are unreachable. This is achieved through a
 //! post-order traversal of the blocks.
 
-use crate::transform::simplify;
-use crate::transform::MirPass;
+use crate::simplify;
+use crate::MirPass;
 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
 use rustc_middle::mir::*;
 use rustc_middle::ty::TyCtxt;