rust/compiler/rustc_mir_transform/src/lib.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

803 lines
31 KiB
Rust
Raw Normal View History

// tidy-alphabetical-start
#![feature(array_windows)]
2023-05-20 08:54:16 +00:00
#![feature(assert_matches)]
#![feature(box_patterns)]
#![feature(const_type_name)]
2023-09-16 09:16:04 +00:00
#![feature(cow_is_borrowed)]
2024-09-24 14:25:16 -07:00
#![feature(file_buffered)]
#![feature(if_let_guard)]
#![feature(impl_trait_in_assoc_type)]
#![feature(let_chains)]
#![feature(map_try_insert)]
#![feature(never_type)]
#![feature(try_blocks)]
2022-05-29 01:19:52 -07:00
#![feature(yeet_expr)]
#![warn(unreachable_pub)]
// tidy-alphabetical-end
use hir::ConstContext;
use required_consts::RequiredConstsVisitor;
use rustc_const_eval::check_consts::{self, ConstCx};
2021-01-05 20:08:11 +01:00
use rustc_const_eval::util;
use rustc_data_structures::fx::FxIndexSet;
use rustc_data_structures::steal::Steal;
use rustc_hir as hir;
use rustc_hir::def::{CtorKind, DefKind};
2022-05-08 15:53:19 +02:00
use rustc_hir::def_id::LocalDefId;
use rustc_index::IndexVec;
2022-07-09 18:04:38 -07:00
use rustc_middle::mir::{
AnalysisPhase, Body, CallSource, ClearCrossCrate, ConstOperand, ConstQualifs, LocalDecl,
MirPhase, Operand, Place, ProjectionElem, Promoted, RuntimePhase, Rvalue, START_BLOCK,
SourceInfo, Statement, StatementKind, TerminatorKind,
2022-07-09 18:04:38 -07:00
};
2023-02-22 02:18:40 +00:00
use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt};
use rustc_middle::util::Providers;
use rustc_middle::{bug, query, span_bug};
use rustc_mir_build::builder::build_mir;
use rustc_span::source_map::Spanned;
use rustc_span::{DUMMY_SP, sym};
use tracing::debug;
2021-11-29 22:46:32 -08:00
#[macro_use]
mod pass_manager;
2024-11-11 15:32:25 +00:00
use std::sync::LazyLock;
use pass_manager::{self as pm, Lint, MirLint, MirPass, WithMinOptLevel};
2021-11-29 22:46:32 -08:00
mod check_pointers;
2023-01-17 21:00:07 +00:00
mod cost_checker;
mod cross_crate_inline;
Introduce deduced parameter attributes, and use them for deducing `readonly` on indirect immutable freeze by-value function parameters. Right now, `rustc` only examines function signatures and the platform ABI when determining the LLVM attributes to apply to parameters. This results in missed optimizations, because there are some attributes that can be determined via analysis of the MIR making up the function body. In particular, `readonly` could be applied to most indirectly-passed by-value function arguments (specifically, those that are freeze and are observed not to be mutated), but it currently is not. This patch introduces the machinery that allows `rustc` to determine those attributes. It consists of a query, `deduced_param_attrs`, that, when evaluated, analyzes the MIR of the function to determine supplementary attributes. The results of this query for each function are written into the crate metadata so that the deduced parameter attributes can be applied to cross-crate functions. In this patch, we simply check the parameter for mutations to determine whether the `readonly` attribute should be applied to parameters that are indirect immutable freeze by-value. More attributes could conceivably be deduced in the future: `nocapture` and `noalias` come to mind. Adding `readonly` to indirect function parameters where applicable enables some potential optimizations in LLVM that are discussed in [issue 103103] and [PR 103070] around avoiding stack-to-stack memory copies that appear in functions like `core::fmt::Write::write_fmt` and `core::panicking::assert_failed`. These functions pass a large structure unchanged by value to a subfunction that also doesn't mutate it. Since the structure in this case is passed as an indirect parameter, it's a pointer from LLVM's perspective. As a result, the intermediate copy of the structure that our codegen emits could be optimized away by LLVM's MemCpyOptimizer if it knew that the pointer is `readonly nocapture noalias` in both the caller and callee. We already pass `nocapture noalias`, but we're missing `readonly`, as we can't determine whether a by-value parameter is mutated by examining the signature in Rust. I didn't have much success with having LLVM infer the `readonly` attribute, even with fat LTO; it seems that deducing it at the MIR level is necessary. No large benefits should be expected from this optimization *now*; LLVM needs some changes (discussed in [PR 103070]) to more aggressively use the `noalias nocapture readonly` combination in its alias analysis. I have some LLVM patches for these optimizations and have had them looked over. With all the patches applied locally, I enabled LLVM to remove all the `memcpy`s from the following code: ```rust fn main() { println!("Hello {}", 3); } ``` which is a significant codegen improvement over the status quo. I expect that if this optimization kicks in in multiple places even for such a simple program, then it will apply to Rust code all over the place. [issue 103103]: https://github.com/rust-lang/rust/issues/103103 [PR 103070]: https://github.com/rust-lang/rust/pull/103070
2022-10-17 19:42:15 -07:00
mod deduce_param_attrs;
mod elaborate_drop;
mod errors;
mod ffi_unwind_calls;
mod lint;
mod lint_tail_expr_drop_order;
mod patch;
mod shim;
2023-01-19 22:23:41 +00:00
mod ssa;
2024-11-11 15:32:25 +00:00
/// We import passes via this macro so that we can have a static list of pass names
/// (used to verify CLI arguments). It takes a list of modules, followed by the passes
/// declared within them.
/// ```ignore,macro-test
/// declare_passes! {
/// // Declare a single pass from the module `abort_unwinding_calls`
/// mod abort_unwinding_calls : AbortUnwindingCalls;
/// // When passes are grouped together as an enum, declare the two constituent passes
/// mod add_call_guards : AddCallGuards {
/// AllCallEdges,
/// CriticalCallEdges
/// };
/// // Declares multiple pass groups, each containing their own constituent passes
/// mod simplify : SimplifyCfg {
/// Initial,
/// /* omitted */
/// }, SimplifyLocals {
/// BeforeConstProp,
/// /* omitted */
/// };
/// }
/// ```
macro_rules! declare_passes {
(
$(
$vis:vis mod $mod_name:ident : $($pass_name:ident $( { $($ident:ident),* } )?),+ $(,)?;
)*
) => {
$(
$vis mod $mod_name;
$(
// Make sure the type name is correct
#[allow(unused_imports)]
use $mod_name::$pass_name as _;
)+
)*
2024-11-11 16:43:49 +00:00
static PASS_NAMES: LazyLock<FxIndexSet<&str>> = LazyLock::new(|| [
2024-11-11 15:32:25 +00:00
// Fake marker pass
2024-11-11 16:43:49 +00:00
"PreCodegen",
2024-11-11 15:32:25 +00:00
$(
$(
2024-11-11 16:43:49 +00:00
stringify!($pass_name),
2024-11-11 15:32:25 +00:00
$(
$(
2024-11-11 16:43:49 +00:00
$mod_name::$pass_name::$ident.name(),
2024-11-11 15:32:25 +00:00
)*
)?
)+
)*
2024-11-11 16:43:49 +00:00
].into_iter().collect());
2024-11-11 15:32:25 +00:00
};
}
declare_passes! {
mod abort_unwinding_calls : AbortUnwindingCalls;
mod add_call_guards : AddCallGuards { AllCallEdges, CriticalCallEdges };
mod add_moves_for_packed_drops : AddMovesForPackedDrops;
mod add_retag : AddRetag;
mod add_subtyping_projections : Subtyper;
mod check_inline : CheckForceInline;
mod check_call_recursion : CheckCallRecursion, CheckDropRecursion;
2024-11-11 15:32:25 +00:00
mod check_alignment : CheckAlignment;
mod check_const_item_mutation : CheckConstItemMutation;
mod check_null : CheckNull;
2024-11-11 15:32:25 +00:00
mod check_packed_ref : CheckPackedRef;
mod check_undefined_transmutes : CheckUndefinedTransmutes;
// This pass is public to allow external drivers to perform MIR cleanup
pub mod cleanup_post_borrowck : CleanupPostBorrowck;
mod copy_prop : CopyProp;
mod coroutine : StateTransform;
mod coverage : InstrumentCoverage;
mod ctfe_limit : CtfeLimit;
mod dataflow_const_prop : DataflowConstProp;
mod dead_store_elimination : DeadStoreElimination {
Initial,
Final
};
mod deref_separator : Derefer;
mod dest_prop : DestinationPropagation;
pub mod dump_mir : Marker;
mod early_otherwise_branch : EarlyOtherwiseBranch;
mod elaborate_box_derefs : ElaborateBoxDerefs;
mod elaborate_drops : ElaborateDrops;
mod function_item_references : FunctionItemReferences;
mod gvn : GVN;
// Made public so that `mir_drops_elaborated_and_const_checked` can be overridden
// by custom rustc drivers, running all the steps by themselves. See #114628.
pub mod inline : Inline, ForceInline;
mod impossible_predicates : ImpossiblePredicates;
2024-11-11 15:32:25 +00:00
mod instsimplify : InstSimplify { BeforeInline, AfterSimplifyCfg };
mod jump_threading : JumpThreading;
mod known_panics_lint : KnownPanicsLint;
mod large_enums : EnumSizeOpt;
mod lower_intrinsics : LowerIntrinsics;
mod lower_slice_len : LowerSliceLenCalls;
mod match_branches : MatchBranchSimplification;
mod mentioned_items : MentionedItems;
mod multiple_return_terminators : MultipleReturnTerminators;
mod nrvo : RenameReturnPlace;
mod post_drop_elaboration : CheckLiveDrops;
mod prettify : ReorderBasicBlocks, ReorderLocals;
mod promote_consts : PromoteTemps;
mod ref_prop : ReferencePropagation;
mod remove_noop_landing_pads : RemoveNoopLandingPads;
mod remove_place_mention : RemovePlaceMention;
mod remove_storage_markers : RemoveStorageMarkers;
mod remove_uninit_drops : RemoveUninitDrops;
mod remove_unneeded_drops : RemoveUnneededDrops;
mod remove_zsts : RemoveZsts;
mod required_consts : RequiredConstsVisitor;
mod post_analysis_normalize : PostAnalysisNormalize;
2024-11-11 15:32:25 +00:00
mod sanity_check : SanityCheck;
// This pass is public to allow external drivers to perform MIR cleanup
pub mod simplify :
SimplifyCfg {
Initial,
PromoteConsts,
RemoveFalseEdges,
PostAnalysis,
PreOptimizations,
Final,
MakeShim,
AfterUnreachableEnumBranching
},
SimplifyLocals {
BeforeConstProp,
AfterGVN,
Final
};
mod simplify_branches : SimplifyConstCondition {
AfterConstProp,
Final
};
mod simplify_comparison_integral : SimplifyComparisonIntegral;
mod single_use_consts : SingleUseConsts;
mod sroa : ScalarReplacementOfAggregates;
mod strip_debuginfo : StripDebugInfo;
2024-11-11 15:32:25 +00:00
mod unreachable_enum_branching : UnreachableEnumBranching;
mod unreachable_prop : UnreachablePropagation;
mod validate : Validator;
}
rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
pub fn provide(providers: &mut Providers) {
coverage::query::provide(providers);
ffi_unwind_calls::provide(providers);
shim::provide(providers);
cross_crate_inline::provide(providers);
providers.queries = query::Providers {
mir_keys,
2024-03-20 09:05:22 +00:00
mir_built,
2022-05-08 15:53:19 +02:00
mir_const_qualif,
mir_promoted,
mir_drops_elaborated_and_const_checked,
mir_for_ctfe,
2023-10-19 21:46:28 +00:00
mir_coroutine_witnesses: coroutine::mir_coroutine_witnesses,
optimized_mir,
is_mir_available,
2024-08-28 08:18:30 +10:00
is_ctfe_mir_available: is_mir_available,
mir_callgraph_reachable: inline::cycle::mir_callgraph_reachable,
mir_inliner_callees: inline::cycle::mir_inliner_callees,
2022-05-08 15:53:19 +02:00
promoted_mir,
Introduce deduced parameter attributes, and use them for deducing `readonly` on indirect immutable freeze by-value function parameters. Right now, `rustc` only examines function signatures and the platform ABI when determining the LLVM attributes to apply to parameters. This results in missed optimizations, because there are some attributes that can be determined via analysis of the MIR making up the function body. In particular, `readonly` could be applied to most indirectly-passed by-value function arguments (specifically, those that are freeze and are observed not to be mutated), but it currently is not. This patch introduces the machinery that allows `rustc` to determine those attributes. It consists of a query, `deduced_param_attrs`, that, when evaluated, analyzes the MIR of the function to determine supplementary attributes. The results of this query for each function are written into the crate metadata so that the deduced parameter attributes can be applied to cross-crate functions. In this patch, we simply check the parameter for mutations to determine whether the `readonly` attribute should be applied to parameters that are indirect immutable freeze by-value. More attributes could conceivably be deduced in the future: `nocapture` and `noalias` come to mind. Adding `readonly` to indirect function parameters where applicable enables some potential optimizations in LLVM that are discussed in [issue 103103] and [PR 103070] around avoiding stack-to-stack memory copies that appear in functions like `core::fmt::Write::write_fmt` and `core::panicking::assert_failed`. These functions pass a large structure unchanged by value to a subfunction that also doesn't mutate it. Since the structure in this case is passed as an indirect parameter, it's a pointer from LLVM's perspective. As a result, the intermediate copy of the structure that our codegen emits could be optimized away by LLVM's MemCpyOptimizer if it knew that the pointer is `readonly nocapture noalias` in both the caller and callee. We already pass `nocapture noalias`, but we're missing `readonly`, as we can't determine whether a by-value parameter is mutated by examining the signature in Rust. I didn't have much success with having LLVM infer the `readonly` attribute, even with fat LTO; it seems that deducing it at the MIR level is necessary. No large benefits should be expected from this optimization *now*; LLVM needs some changes (discussed in [PR 103070]) to more aggressively use the `noalias nocapture readonly` combination in its alias analysis. I have some LLVM patches for these optimizations and have had them looked over. With all the patches applied locally, I enabled LLVM to remove all the `memcpy`s from the following code: ```rust fn main() { println!("Hello {}", 3); } ``` which is a significant codegen improvement over the status quo. I expect that if this optimization kicks in in multiple places even for such a simple program, then it will apply to Rust code all over the place. [issue 103103]: https://github.com/rust-lang/rust/issues/103103 [PR 103070]: https://github.com/rust-lang/rust/pull/103070
2022-10-17 19:42:15 -07:00
deduced_param_attrs: deduce_param_attrs::deduced_param_attrs,
coroutine_by_move_body_def_id: coroutine::coroutine_by_move_body_def_id,
..providers.queries
};
}
fn remap_mir_for_const_eval_select<'tcx>(
tcx: TyCtxt<'tcx>,
mut body: Body<'tcx>,
context: hir::Constness,
) -> Body<'tcx> {
for bb in body.basic_blocks.as_mut().iter_mut() {
let terminator = bb.terminator.as_mut().expect("invalid terminator");
match terminator.kind {
TerminatorKind::Call {
func: Operand::Constant(box ConstOperand { ref const_, .. }),
ref mut args,
destination,
target,
unwind,
fn_span,
..
} if let ty::FnDef(def_id, _) = *const_.ty().kind()
2024-02-19 22:51:45 +00:00
&& tcx.is_intrinsic(def_id, sym::const_eval_select) =>
{
let Ok([tupled_args, called_in_const, called_at_rt]) = take_array(args) else {
unreachable!()
};
let ty = tupled_args.node.ty(&body.local_decls, tcx);
let fields = ty.tuple_fields();
let num_args = fields.len();
let func =
if context == hir::Constness::Const { called_in_const } else { called_at_rt };
let (method, place): (fn(Place<'tcx>) -> Operand<'tcx>, Place<'tcx>) =
match tupled_args.node {
Operand::Constant(_) => {
// There is no good way of extracting a tuple arg from a constant
// (const generic stuff) so we just create a temporary and deconstruct
// that.
let local = body.local_decls.push(LocalDecl::new(ty, fn_span));
bb.statements.push(Statement {
source_info: SourceInfo::outermost(fn_span),
kind: StatementKind::Assign(Box::new((
local.into(),
Rvalue::Use(tupled_args.node.clone()),
))),
});
(Operand::Move, local.into())
}
Operand::Move(place) => (Operand::Move, place),
Operand::Copy(place) => (Operand::Copy, place),
};
let place_elems = place.projection;
let arguments = (0..num_args)
.map(|x| {
let mut place_elems = place_elems.to_vec();
place_elems.push(ProjectionElem::Field(x.into(), fields[x]));
let projection = tcx.mk_place_elems(&place_elems);
let place = Place { local: place.local, projection };
Spanned { node: method(place), span: DUMMY_SP }
2023-10-13 08:58:33 +00:00
})
.collect();
terminator.kind = TerminatorKind::Call {
func: func.node,
args: arguments,
destination,
target,
unwind,
call_source: CallSource::Misc,
fn_span,
2023-10-13 08:58:33 +00:00
};
}
_ => {}
}
}
body
}
fn take_array<T, const N: usize>(b: &mut Box<[T]>) -> Result<[T; N], Box<[T]>> {
let b: Box<[T; N]> = std::mem::take(b).try_into()?;
Ok(*b)
}
2023-03-13 18:54:05 +00:00
fn is_mir_available(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
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<'_>, (): ()) -> FxIndexSet<LocalDefId> {
// All body-owners have MIR associated with them.
let mut set: FxIndexSet<_> = tcx.hir_body_owners().collect();
// Coroutine-closures (e.g. async closures) have an additional by-move MIR
// body that isn't in the HIR.
for body_owner in tcx.hir_body_owners() {
if let DefKind::Closure = tcx.def_kind(body_owner)
&& tcx.needs_coroutine_by_move_body_def_id(body_owner.to_def_id())
{
set.insert(tcx.coroutine_by_move_body_def_id(body_owner).expect_local());
}
}
// tuple struct/variant constructors have MIR, but they don't have a BodyId,
// so we need to build them separately.
for item in tcx.hir_crate_items(()).free_items() {
if let DefKind::Struct | DefKind::Enum = tcx.def_kind(item.owner_id) {
for variant in tcx.adt_def(item.owner_id).variants() {
if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
set.insert(ctor_def_id.expect_local());
}
}
}
}
set
}
2022-05-08 15:53:19 +02:00
fn mir_const_qualif(tcx: TyCtxt<'_>, def: LocalDefId) -> ConstQualifs {
// N.B., this `borrow()` is guaranteed to be valid (i.e., the value
// cannot yet be stolen), because `mir_promoted()`, which steals
// from `mir_built()`, forces this query to execute before
// performing the steal.
let body = &tcx.mir_built(def).borrow();
let ccx = check_consts::ConstCx::new(tcx, body);
// No need to const-check a non-const `fn`.
match ccx.const_kind {
2024-08-28 08:25:52 +10:00
Some(ConstContext::Const { .. } | ConstContext::Static(_) | ConstContext::ConstFn) => {}
None => span_bug!(
tcx.def_span(def),
"`mir_const_qualif` should only be called on const fns and const items"
),
}
if body.return_ty().references_error() {
// It's possible to reach here without an error being emitted (#121103).
tcx.dcx().span_delayed_bug(body.span, "mir_const_qualif: MIR had errors");
return Default::default();
}
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()
}
2024-03-20 09:05:22 +00:00
fn mir_built(tcx: TyCtxt<'_>, def: LocalDefId) -> &Steal<Body<'_>> {
let mut body = build_mir(tcx, def);
pass_manager::dump_mir_for_phase_change(tcx, &body);
2021-12-02 14:20:03 -08:00
pm::run_passes(
tcx,
&mut body,
2021-12-02 14:20:03 -08:00
&[
// MIR-level lints.
&Lint(check_inline::CheckForceInline),
&Lint(check_call_recursion::CheckCallRecursion),
2021-12-02 09:17:32 -08:00
&Lint(check_packed_ref::CheckPackedRef),
&Lint(check_const_item_mutation::CheckConstItemMutation),
&Lint(function_item_references::FunctionItemReferences),
&Lint(check_undefined_transmutes::CheckUndefinedTransmutes),
// What we need to do constant evaluation.
&simplify::SimplifyCfg::Initial,
&Lint(sanity_check::SanityCheck),
2021-12-02 14:20:03 -08:00
],
2022-09-26 18:43:35 -07:00
None,
pm::Optimizations::Allowed,
);
tcx.alloc_steal_mir(body)
}
/// Compute the main MIR body and the list of MIR bodies of the promoteds.
2022-12-20 22:10:40 +01:00
fn mir_promoted(
tcx: TyCtxt<'_>,
2022-05-08 15:53:19 +02:00
def: LocalDefId,
2022-12-20 22:10:40 +01:00
) -> (&Steal<Body<'_>>, &Steal<IndexVec<Promoted, Body<'_>>>) {
// 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 const_qualifs = match tcx.def_kind(def) {
DefKind::Fn | DefKind::AssocFn | DefKind::Closure
if tcx.constness(def) == hir::Constness::Const
|| tcx.is_const_default_method(def.to_def_id()) =>
{
tcx.mir_const_qualif(def)
}
DefKind::AssocConst
| DefKind::Const
| DefKind::Static { .. }
| DefKind::InlineConst
| DefKind::AnonConst => tcx.mir_const_qualif(def),
_ => ConstQualifs::default(),
};
// the `has_ffi_unwind_calls` query uses the raw mir, so make sure it is run.
tcx.ensure_done().has_ffi_unwind_calls(def);
// the `by_move_body` query uses the raw mir, so make sure it is run.
if tcx.needs_coroutine_by_move_body_def_id(def.to_def_id()) {
tcx.ensure_done().coroutine_by_move_body_def_id(def);
}
2024-03-20 09:05:22 +00:00
let mut body = tcx.mir_built(def).steal();
2022-02-07 22:00:15 -08:00
if let Some(error_reported) = const_qualifs.tainted_by_errors {
body.tainted_by_errors = Some(error_reported);
}
// Collect `required_consts` *before* promotion, so if there are any consts being promoted
// we still add them to the list in the outer MIR body.
RequiredConstsVisitor::compute_required_consts(&mut body);
2021-12-02 14:20:03 -08:00
// What we need to run borrowck etc.
let promote_pass = promote_consts::PromoteTemps::default();
2021-12-02 14:20:03 -08:00
pm::run_passes(
tcx,
&mut body,
&[&promote_pass, &simplify::SimplifyCfg::PromoteConsts, &coverage::InstrumentCoverage],
2022-09-26 18:43:35 -07:00
Some(MirPhase::Analysis(AnalysisPhase::Initial)),
pm::Optimizations::Allowed,
2021-12-02 14:20:03 -08:00
);
lint_tail_expr_drop_order::run_lint(tcx, def, &body);
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)
2023-03-13 18:54:05 +00:00
fn mir_for_ctfe(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &Body<'_> {
2022-05-08 15:53:19 +02:00
tcx.arena.alloc(inner_mir_for_ctfe(tcx, def_id))
}
2022-05-08 15:53:19 +02:00
fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: LocalDefId) -> Body<'_> {
// FIXME: don't duplicate this between the optimized_mir/mir_for_ctfe queries
2022-05-08 15:53:19 +02:00
if tcx.is_constructor(def.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.
2022-05-08 15:53:19 +02:00
return shim::build_adt_ctor(tcx, def.to_def_id());
}
2023-08-05 07:55:57 +00:00
let body = tcx.mir_drops_elaborated_and_const_checked(def);
let body = match tcx.hir_body_const_context(def) {
2023-08-05 07:55:57 +00:00
// consts and statics do not have `optimized_mir`, so we can steal the body instead of
// cloning it.
Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => body.steal(),
2023-08-05 07:55:57 +00:00
Some(hir::ConstContext::ConstFn) => body.borrow().clone(),
None => bug!("`mir_for_ctfe` called on non-const {def:?}"),
};
let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::Const);
pm::run_passes(tcx, &mut body, &[&ctfe_limit::CtfeLimit], None, pm::Optimizations::Allowed);
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.
2022-05-08 15:53:19 +02:00
fn mir_drops_elaborated_and_const_checked(tcx: TyCtxt<'_>, def: LocalDefId) -> &Steal<Body<'_>> {
if tcx.is_coroutine(def.to_def_id()) {
tcx.ensure_done().mir_coroutine_witnesses(def);
}
// We only need to borrowck non-synthetic MIR.
let tainted_by_errors =
if !tcx.is_synthetic_mir(def) { tcx.mir_borrowck(def).tainted_by_errors } else { None };
2022-05-08 15:53:19 +02:00
let is_fn_like = tcx.def_kind(def).is_fn_like();
if is_fn_like {
// Do not compute the mir call graph without said call graph actually being used.
if pm::should_run_pass(tcx, &inline::Inline, pm::Optimizations::Allowed)
|| inline::ForceInline::should_run_pass_for_callee(tcx, def.to_def_id())
{
tcx.ensure_done().mir_inliner_callees(ty::InstanceKind::Item(def.to_def_id()));
}
}
let (body, _) = tcx.mir_promoted(def);
let mut body = body.steal();
if let Some(error_reported) = tainted_by_errors {
2022-02-07 22:00:15 -08:00
body.tainted_by_errors = Some(error_reported);
}
// Also taint the body if it's within a top-level item that is not well formed.
//
// We do this check here and not during `mir_promoted` because that may result
// in borrowck cycles if WF requires looking into an opaque hidden type.
let root = tcx.typeck_root_def_id(def.to_def_id());
match tcx.def_kind(root) {
DefKind::Fn
| DefKind::AssocFn
| DefKind::Static { .. }
| DefKind::Const
| DefKind::AssocConst => {
if let Err(guar) = tcx.check_well_formed(root.expect_local()) {
body.tainted_by_errors = Some(guar);
}
}
_ => {}
}
2022-07-09 18:04:38 -07:00
run_analysis_to_runtime_passes(tcx, &mut body);
tcx.alloc_steal_mir(body)
}
// Made public so that `mir_drops_elaborated_and_const_checked` can be overridden
// by custom rustc drivers, running all the steps by themselves. See #114628.
pub fn run_analysis_to_runtime_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
2022-07-09 18:04:38 -07:00
assert!(body.phase == MirPhase::Analysis(AnalysisPhase::Initial));
let did = body.source.def_id();
debug!("analysis_mir_cleanup({:?})", did);
run_analysis_cleanup_passes(tcx, body);
assert!(body.phase == MirPhase::Analysis(AnalysisPhase::PostCleanup));
// Do a little drop elaboration before const-checking if `const_precise_live_drops` is enabled.
if check_consts::post_drop_elaboration::checking_enabled(&ConstCx::new(tcx, body)) {
2021-12-02 14:20:03 -08:00
pm::run_passes(
tcx,
2022-07-09 18:04:38 -07:00
body,
&[
&remove_uninit_drops::RemoveUninitDrops,
&simplify::SimplifyCfg::RemoveFalseEdges,
&Lint(post_drop_elaboration::CheckLiveDrops),
],
2022-09-26 18:43:35 -07:00
None,
pm::Optimizations::Allowed,
2021-12-02 14:20:03 -08:00
);
}
2022-07-09 18:04:38 -07:00
debug!("runtime_mir_lowering({:?})", did);
run_runtime_lowering_passes(tcx, body);
assert!(body.phase == MirPhase::Runtime(RuntimePhase::Initial));
debug!("runtime_mir_cleanup({:?})", did);
run_runtime_cleanup_passes(tcx, body);
assert!(body.phase == MirPhase::Runtime(RuntimePhase::PostCleanup));
}
2022-07-09 18:04:38 -07:00
// FIXME(JakobDegen): Can we make these lists of passes consts?
2022-07-09 18:04:38 -07:00
/// After this series of passes, no lifetime analysis based on borrowing can be done.
fn run_analysis_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
let passes: &[&dyn MirPass<'tcx>] = &[
&impossible_predicates::ImpossiblePredicates,
&cleanup_post_borrowck::CleanupPostBorrowck,
&remove_noop_landing_pads::RemoveNoopLandingPads,
&simplify::SimplifyCfg::PostAnalysis,
2022-06-13 16:37:41 +03:00
&deref_separator::Derefer,
2022-07-09 18:04:38 -07:00
];
pm::run_passes(
tcx,
body,
passes,
Some(MirPhase::Analysis(AnalysisPhase::PostCleanup)),
pm::Optimizations::Allowed,
);
2022-07-09 18:04:38 -07:00
}
/// Returns the sequence of passes that lowers analysis to runtime MIR.
fn run_runtime_lowering_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
let passes: &[&dyn MirPass<'tcx>] = &[
// These next passes must be executed together.
&add_call_guards::CriticalCallEdges,
// Must be done before drop elaboration because we need to drop opaque types, too.
&post_analysis_normalize::PostAnalysisNormalize,
// Calling this after `PostAnalysisNormalize` ensures that we don't deal with opaque types.
&add_subtyping_projections::Subtyper,
&elaborate_drops::ElaborateDrops,
// Needs to happen after drop elaboration.
&Lint(check_call_recursion::CheckDropRecursion),
// This will remove extraneous landing pads which are no longer
2024-07-02 11:25:31 +08:00
// necessary 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` but before `ElaborateBoxDerefs`.
// Otherwise it should run fairly late, but before optimizations begin.
&add_retag::AddRetag,
2022-05-13 21:53:03 -07:00
&elaborate_box_derefs::ElaborateBoxDerefs,
2023-10-19 21:46:28 +00:00
&coroutine::StateTransform,
&Lint(known_panics_lint::KnownPanicsLint),
2022-07-09 18:04:38 -07:00
];
2022-09-26 18:43:35 -07:00
pm::run_passes_no_validate(tcx, body, passes, Some(MirPhase::Runtime(RuntimePhase::Initial)));
2022-07-09 18:04:38 -07:00
}
/// Returns the sequence of passes that do the initial cleanup of runtime MIR.
fn run_runtime_cleanup_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
let passes: &[&dyn MirPass<'tcx>] = &[
&lower_intrinsics::LowerIntrinsics,
&remove_place_mention::RemovePlaceMention,
&simplify::SimplifyCfg::PreOptimizations,
];
pm::run_passes(
tcx,
body,
passes,
Some(MirPhase::Runtime(RuntimePhase::PostCleanup)),
pm::Optimizations::Allowed,
);
// Clear this by anticipation. Optimizations and runtime MIR have no reason to look
// into this information, which is meant for borrowck diagnostics.
for decl in &mut body.local_decls {
decl.local_info = ClearCrossCrate::Clear;
}
}
fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
fn o1<T>(x: T) -> WithMinOptLevel<T> {
WithMinOptLevel(1, x)
}
let def_id = body.source.def_id();
let optimizations = if tcx.def_kind(def_id).has_codegen_attrs()
&& tcx.codegen_fn_attrs(def_id).optimize.do_not_optimize()
{
pm::Optimizations::Suppressed
} else {
pm::Optimizations::Allowed
};
2022-07-09 18:04:38 -07:00
// The main optimizations that we do on MIR.
2021-12-02 14:20:03 -08:00
pm::run_passes(
tcx,
body,
&[
// Add some UB checks before any UB gets optimized away.
&check_alignment::CheckAlignment,
&check_null::CheckNull,
2024-01-07 00:30:08 +00:00
// Before inlining: trim down MIR with passes to reduce inlining work.
// Has to be done before inlining, otherwise actual call will be almost always inlined.
// Also simple, so can just do first.
2024-01-07 00:30:08 +00:00
&lower_slice_len::LowerSliceLenCalls,
// Perform instsimplify before inline to eliminate some trivial calls (like clone
// shims).
&instsimplify::InstSimplify::BeforeInline,
// Perform inlining of `#[rustc_force_inline]`-annotated callees.
&inline::ForceInline,
2024-01-07 00:30:08 +00:00
// Perform inlining, which may add a lot of code.
2023-07-22 15:34:54 +00:00
&inline::Inline,
// Code from other crates may have storage markers, so this needs to happen after
// inlining.
2024-01-07 00:30:08 +00:00
&remove_storage_markers::RemoveStorageMarkers,
2024-02-12 15:39:32 +09:00
// Inlining and instantiation may introduce ZST and useless drops.
2024-01-07 00:30:08 +00:00
&remove_zsts::RemoveZsts,
&remove_unneeded_drops::RemoveUnneededDrops,
2024-02-12 15:39:32 +09:00
// Type instantiation may create uninhabited enums.
// Also eliminates some unreachable branches based on variants of enums.
&unreachable_enum_branching::UnreachableEnumBranching,
2023-07-22 15:34:54 +00:00
&unreachable_prop::UnreachablePropagation,
&o1(simplify::SimplifyCfg::AfterUnreachableEnumBranching),
2024-01-07 00:30:08 +00:00
// Inlining may have introduced a lot of redundant code and a large move pattern.
// Now, we need to shrink the generated MIR.
2023-03-12 14:10:30 +00:00
&ref_prop::ReferencePropagation,
2022-05-23 09:27:44 +02:00
&sroa::ScalarReplacementOfAggregates,
2021-12-02 14:20:03 -08:00
&match_branches::MatchBranchSimplification,
// inst combine is after MatchBranchSimplification to clean up Ne(_1, false)
&multiple_return_terminators::MultipleReturnTerminators,
// After simplifycfg, it allows us to discover new opportunities for peephole
// optimizations.
&instsimplify::InstSimplify::AfterSimplifyCfg,
&simplify::SimplifyLocals::BeforeConstProp,
&dead_store_elimination::DeadStoreElimination::Initial,
&gvn::GVN,
&simplify::SimplifyLocals::AfterGVN,
&dataflow_const_prop::DataflowConstProp,
2024-06-02 19:41:00 -07:00
&single_use_consts::SingleUseConsts,
&o1(simplify_branches::SimplifyConstCondition::AfterConstProp),
2023-01-16 22:12:36 +00:00
&jump_threading::JumpThreading,
2021-12-02 14:20:03 -08:00
&early_otherwise_branch::EarlyOtherwiseBranch,
&simplify_comparison_integral::SimplifyComparisonIntegral,
&dest_prop::DestinationPropagation,
&o1(simplify_branches::SimplifyConstCondition::Final),
&o1(remove_noop_landing_pads::RemoveNoopLandingPads),
&o1(simplify::SimplifyCfg::Final),
// After the last SimplifyCfg, because this wants one-block functions.
&strip_debuginfo::StripDebugInfo,
&copy_prop::CopyProp,
&dead_store_elimination::DeadStoreElimination::Final,
&nrvo::RenameReturnPlace,
&simplify::SimplifyLocals::Final,
2021-12-02 14:20:03 -08:00
&multiple_return_terminators::MultipleReturnTerminators,
2023-02-05 22:14:40 +00:00
&large_enums::EnumSizeOpt { discrepancy: 128 },
2021-12-02 14:20:03 -08:00
// Some cleanup necessary at least for LLVM and potentially other codegen backends.
&add_call_guards::CriticalCallEdges,
// Cleanup for human readability, off by default.
&prettify::ReorderBasicBlocks,
&prettify::ReorderLocals,
2021-12-02 14:20:03 -08:00
// Dump the end result for testing and debugging purposes.
&dump_mir::Marker("PreCodegen"),
],
2022-09-26 18:43:35 -07:00
Some(MirPhase::Runtime(RuntimePhase::Optimized)),
optimizations,
);
}
/// Optimize the MIR and prepare it for codegen.
2023-03-13 18:54:05 +00:00
fn optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> &Body<'_> {
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_done().mir_for_ctfe(did),
None => {}
Some(other) => panic!("do not use `optimized_mir` for constants: {other:?}"),
}
debug!("about to call mir_drops_elaborated...");
2022-05-08 15:53:19 +02:00
let body = tcx.mir_drops_elaborated_and_const_checked(did).steal();
let mut body = remap_mir_for_const_eval_select(tcx, body, hir::Constness::NotConst);
if body.tainted_by_errors.is_some() {
return body;
}
// Before doing anything, remember which items are being mentioned so that the set of items
// visited does not depend on the optimization level.
// We do not use `run_passes` for this as that might skip the pass if `injection_phase` is set.
mentioned_items::MentionedItems.run_pass(tcx, &mut body);
// If `mir_drops_elaborated_and_const_checked` found that the current body has unsatisfiable
// predicates, it will shrink the MIR to a single `unreachable` terminator.
// More generally, if MIR is a lone `unreachable`, there is nothing to optimize.
if let TerminatorKind::Unreachable = body.basic_blocks[START_BLOCK].terminator().kind
&& body.basic_blocks[START_BLOCK].statements.is_empty()
{
return body;
}
run_optimization_passes(tcx, &mut body);
body
}
/// Fetch all the promoteds of an item and prepare their MIR bodies to be ready for
2024-02-12 15:39:32 +09:00
/// constant evaluation once all generic parameters become known.
2022-05-08 15:53:19 +02:00
fn promoted_mir(tcx: TyCtxt<'_>, def: LocalDefId) -> &IndexVec<Promoted, Body<'_>> {
if tcx.is_constructor(def.to_def_id()) {
return tcx.arena.alloc(IndexVec::new());
}
if !tcx.is_synthetic_mir(def) {
tcx.ensure_done().mir_borrowck(def);
}
2022-02-07 22:00:15 -08:00
let mut promoted = tcx.mir_promoted(def).1.steal();
for body in &mut promoted {
2022-07-09 18:04:38 -07:00
run_analysis_to_runtime_passes(tcx, body);
}
tcx.arena.alloc(promoted)
}