1use std::iter;
23use rustc_index::IndexVec;
4use rustc_index::bit_set::DenseBitSet;
5use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
6use rustc_middle::mir::{Body, Local, UnwindTerminateReason, traversal};
7use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, HasTypingEnv, TyAndLayout};
8use rustc_middle::ty::{self, Instance, Ty, TyCtxt, TypeFoldable, TypeVisitableExt};
9use rustc_middle::{bug, mir, span_bug};
10use rustc_target::callconv::{FnAbi, PassMode};
11use tracing::{debug, instrument};
1213use crate::base;
14use crate::traits::*;
1516mod analyze;
17mod block;
18mod constant;
19mod coverageinfo;
20pub mod debuginfo;
21mod intrinsic;
22mod locals;
23pub mod naked_asm;
24pub mod operand;
25pub mod place;
26mod rvalue;
27mod statement;
2829pub use self::block::store_cast;
30use self::debuginfo::{FunctionDebugContext, PerLocalVarDebugInfo};
31use self::operand::{OperandRef, OperandValue};
32use self::place::PlaceRef;
3334// Used for tracking the state of generated basic blocks.
35enum CachedLlbb<T> {
36/// Nothing created yet.
37None,
3839/// Has been created.
40Some(T),
4142/// Nothing created yet, and nothing should be.
43Skip,
44}
4546type PerLocalVarDebugInfoIndexVec<'tcx, V> =
47IndexVec<mir::Local, Vec<PerLocalVarDebugInfo<'tcx, V>>>;
4849/// Master context for codegenning from MIR.
50pub struct FunctionCx<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> {
51 instance: Instance<'tcx>,
5253 mir: &'tcx mir::Body<'tcx>,
5455 debug_context: Option<FunctionDebugContext<'tcx, Bx::DIScope, Bx::DILocation>>,
5657 llfn: Bx::Function,
5859 cx: &'a Bx::CodegenCx,
6061 fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
6263/// When unwinding is initiated, we have to store this personality
64 /// value somewhere so that we can load it and re-use it in the
65 /// resume instruction. The personality is (afaik) some kind of
66 /// value used for C++ unwinding, which must filter by type: we
67 /// don't really care about it very much. Anyway, this value
68 /// contains an alloca into which the personality is stored and
69 /// then later loaded when generating the DIVERGE_BLOCK.
70personality_slot: Option<PlaceRef<'tcx, Bx::Value>>,
7172/// A backend `BasicBlock` for each MIR `BasicBlock`, created lazily
73 /// as-needed (e.g. RPO reaching it or another block branching to it).
74// FIXME(eddyb) rename `llbbs` and other `ll`-prefixed things to use a
75 // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbbs`).
76cached_llbbs: IndexVec<mir::BasicBlock, CachedLlbb<Bx::BasicBlock>>,
7778/// The funclet status of each basic block
79cleanup_kinds: Option<IndexVec<mir::BasicBlock, analyze::CleanupKind>>,
8081/// When targeting MSVC, this stores the cleanup info for each funclet BB.
82 /// This is initialized at the same time as the `landing_pads` entry for the
83 /// funclets' head block, i.e. when needed by an unwind / `cleanup_ret` edge.
84funclets: IndexVec<mir::BasicBlock, Option<Bx::Funclet>>,
8586/// This stores the cached landing/cleanup pad block for a given BB.
87// FIXME(eddyb) rename this to `eh_pads`.
88landing_pads: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
8990/// Cached unreachable block
91unreachable_block: Option<Bx::BasicBlock>,
9293/// Cached terminate upon unwinding block and its reason. For non-wasm
94 /// targets, there is at most one such block per function, stored at index
95 /// `START_BLOCK`. For wasm targets, each funclet needs its own terminate
96 /// block, indexed by the cleanup block that is the funclet's head.
97terminate_blocks: IndexVec<mir::BasicBlock, Option<(Bx::BasicBlock, UnwindTerminateReason)>>,
9899/// A bool flag for each basic block indicating whether it is a cold block.
100 /// A cold block is a block that is unlikely to be executed at runtime.
101cold_blocks: IndexVec<mir::BasicBlock, bool>,
102103/// The location where each MIR arg/var/tmp/ret is stored. This is
104 /// usually an `PlaceRef` representing an alloca, but not always:
105 /// sometimes we can skip the alloca and just store the value
106 /// directly using an `OperandRef`, which makes for tighter LLVM
107 /// IR. The conditions for using an `OperandRef` are as follows:
108 ///
109 /// - the type of the local must be judged "immediate" by `is_llvm_immediate`
110 /// - the operand must never be referenced indirectly
111 /// - we should not take its address using the `&` operator
112 /// - nor should it appear in a place path like `tmp.a`
113 /// - the operand must be defined by an rvalue that can generate immediate
114 /// values
115 ///
116 /// Avoiding allocs can also be important for certain intrinsics,
117 /// notably `expect`.
118locals: locals::Locals<'tcx, Bx::Value>,
119120/// All `VarDebugInfo` from the MIR body, partitioned by `Local`.
121 /// This is `None` if no variable debuginfo/names are needed.
122per_local_var_debug_info: Option<PerLocalVarDebugInfoIndexVec<'tcx, Bx::DIVariable>>,
123124/// Caller location propagated if this function has `#[track_caller]`.
125caller_location: Option<OperandRef<'tcx, Bx::Value>>,
126}
127128impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
129pub fn monomorphize<T>(&self, value: T) -> T
130where
131T: Copy + TypeFoldable<TyCtxt<'tcx>>,
132 {
133{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/mod.rs:133",
"rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/mod.rs"),
::tracing_core::__macro_support::Option::Some(133u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("monomorphize: self.instance={0:?}",
self.instance) as &dyn Value))])
});
} else { ; }
};debug!("monomorphize: self.instance={:?}", self.instance);
134self.instance.instantiate_mir_and_normalize_erasing_regions(
135self.cx.tcx(),
136self.cx.typing_env(),
137 ty::EarlyBinder::bind(value),
138 )
139 }
140}
141142enum LocalRef<'tcx, V> {
143 Place(PlaceRef<'tcx, V>),
144/// `UnsizedPlace(p)`: `p` itself is a thin pointer (indirect place).
145 /// `*p` is the wide pointer that references the actual unsized place.
146 ///
147 /// MIR only supports unsized args, not dynamically-sized locals, so
148 /// new unsized temps don't exist and we must reuse the referred-to place.
149 ///
150 /// FIXME: Since the removal of unsized locals in <https://github.com/rust-lang/rust/pull/142911>,
151 /// can we maybe use `Place` here? Or refactor it in another way? There are quite a few
152 /// `UnsizedPlace => bug` branches now.
153UnsizedPlace(PlaceRef<'tcx, V>),
154/// The backend [`OperandValue`] has already been generated.
155Operand(OperandRef<'tcx, V>),
156/// Will be a `Self::Operand` once we get to its definition.
157PendingOperand,
158}
159160impl<'tcx, V: CodegenObject> LocalRef<'tcx, V> {
161fn new_operand(layout: TyAndLayout<'tcx>) -> LocalRef<'tcx, V> {
162if layout.is_zst() {
163// Zero-size temporaries aren't always initialized, which
164 // doesn't matter because they don't contain data, but
165 // we need something sufficiently aligned in the operand.
166LocalRef::Operand(OperandRef::zero_sized(layout))
167 } else {
168 LocalRef::PendingOperand169 }
170 }
171}
172173///////////////////////////////////////////////////////////////////////////
174175#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("codegen_mir",
"rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/mod.rs"),
::tracing_core::__macro_support::Option::Some(175u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
::tracing_core::field::FieldSet::new(&["instance"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
if !!instance.args.has_infer() {
::core::panicking::panic("assertion failed: !instance.args.has_infer()")
};
let tcx = cx.tcx();
let llfn = cx.get_fn(instance);
let mut mir = tcx.instance_mir(instance.def);
let fn_abi = cx.fn_abi_of_instance(instance, ty::List::empty());
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/mod.rs:191",
"rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/mod.rs"),
::tracing_core::__macro_support::Option::Some(191u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("fn_abi: {0:?}",
fn_abi) as &dyn Value))])
});
} else { ; }
};
if tcx.features().ergonomic_clones() {
let monomorphized_mir =
instance.instantiate_mir_and_normalize_erasing_regions(tcx,
ty::TypingEnv::fully_monomorphized(),
ty::EarlyBinder::bind(mir.clone()));
mir =
tcx.arena.alloc(optimize_use_clone::<Bx>(cx,
monomorphized_mir));
}
let debug_context =
cx.create_function_debug_context(instance, fn_abi, llfn,
&mir);
let start_llbb = Bx::append_block(cx, llfn, "start");
let mut start_bx = Bx::build(cx, start_llbb);
if mir.basic_blocks.iter().any(|bb|
{
bb.is_cleanup ||
#[allow(non_exhaustive_omitted_patterns)] match bb.terminator().unwind()
{
Some(mir::UnwindAction::Terminate(_)) => true,
_ => false,
}
}) {
start_bx.set_personality_fn(cx.eh_personality());
}
let cleanup_kinds =
base::wants_new_eh_instructions(tcx.sess).then(||
analyze::cleanup_kinds(&mir));
let cached_llbbs:
IndexVec<mir::BasicBlock, CachedLlbb<Bx::BasicBlock>> =
mir.basic_blocks.indices().map(|bb|
{
if bb == mir::START_BLOCK {
CachedLlbb::Some(start_llbb)
} else { CachedLlbb::None }
}).collect();
let mut fx =
FunctionCx {
instance,
mir,
llfn,
fn_abi,
cx,
personality_slot: None,
cached_llbbs,
unreachable_block: None,
terminate_blocks: IndexVec::from_elem(None,
&mir.basic_blocks),
cleanup_kinds,
landing_pads: IndexVec::from_elem(None, &mir.basic_blocks),
funclets: IndexVec::from_fn_n(|_| None,
mir.basic_blocks.len()),
cold_blocks: find_cold_blocks(tcx, mir),
locals: locals::Locals::empty(),
debug_context,
per_local_var_debug_info: None,
caller_location: None,
};
let (per_local_var_debug_info, consts_debug_info) =
fx.compute_per_local_var_debug_info(&mut start_bx).unzip();
fx.per_local_var_debug_info = per_local_var_debug_info;
let traversal_order =
traversal::mono_reachable_reverse_postorder(mir, tcx,
instance);
let memory_locals =
analyze::non_ssa_locals(&fx, &traversal_order);
let local_values =
{
let args =
arg_local_refs(&mut start_bx, &mut fx, &memory_locals);
let mut allocate_local =
|local: Local|
{
let decl = &mir.local_decls[local];
let layout = start_bx.layout_of(fx.monomorphize(decl.ty));
if !!layout.ty.has_erasable_regions() {
::core::panicking::panic("assertion failed: !layout.ty.has_erasable_regions()")
};
if local == mir::RETURN_PLACE {
match fx.fn_abi.ret.mode {
PassMode::Indirect { .. } => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/mod.rs:268",
"rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/mod.rs"),
::tracing_core::__macro_support::Option::Some(268u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("alloc: {0:?} (return place) -> place",
local) as &dyn Value))])
});
} else { ; }
};
let llretptr = start_bx.get_param(0);
return LocalRef::Place(PlaceRef::new_sized(llretptr,
layout));
}
PassMode::Cast { ref cast, .. } => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/mod.rs:273",
"rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/mod.rs"),
::tracing_core::__macro_support::Option::Some(273u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("alloc: {0:?} (return place) -> place",
local) as &dyn Value))])
});
} else { ; }
};
let size = cast.size(&start_bx).max(layout.size);
return LocalRef::Place(PlaceRef::alloca_size(&mut start_bx,
size, layout));
}
_ => {}
};
}
if memory_locals.contains(local) {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/mod.rs:282",
"rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/mod.rs"),
::tracing_core::__macro_support::Option::Some(282u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("alloc: {0:?} -> place",
local) as &dyn Value))])
});
} else { ; }
};
if layout.is_unsized() {
LocalRef::UnsizedPlace(PlaceRef::alloca_unsized_indirect(&mut start_bx,
layout))
} else {
LocalRef::Place(PlaceRef::alloca(&mut start_bx, layout))
}
} else {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/mod.rs:289",
"rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/mod.rs"),
::tracing_core::__macro_support::Option::Some(289u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("alloc: {0:?} -> operand",
local) as &dyn Value))])
});
} else { ; }
};
LocalRef::new_operand(layout)
}
};
let retptr = allocate_local(mir::RETURN_PLACE);
iter::once(retptr).chain(args.into_iter()).chain(mir.vars_and_temps_iter().map(allocate_local)).collect()
};
fx.initialize_locals(local_values);
fx.debug_introduce_locals(&mut start_bx,
consts_debug_info.unwrap_or_default());
drop(start_bx);
let mut unreached_blocks =
DenseBitSet::new_filled(mir.basic_blocks.len());
for bb in traversal_order {
fx.codegen_block(bb);
unreached_blocks.remove(bb);
}
for bb in unreached_blocks.iter() {
fx.codegen_block_as_unreachable(bb);
}
}
}
}#[instrument(level = "debug", skip(cx))]176pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
177 cx: &'a Bx::CodegenCx,
178 instance: Instance<'tcx>,
179) {
180assert!(!instance.args.has_infer());
181182let tcx = cx.tcx();
183let llfn = cx.get_fn(instance);
184185let mut mir = tcx.instance_mir(instance.def);
186// Note that the ABI logic has deduced facts about the functions' parameters based on the MIR we
187 // got here (`deduce_param_attrs`). That means we can *not* apply arbitrary further MIR
188 // transforms as that may invalidate those deduced facts!
189190let fn_abi = cx.fn_abi_of_instance(instance, ty::List::empty());
191debug!("fn_abi: {:?}", fn_abi);
192193if tcx.features().ergonomic_clones() {
194let monomorphized_mir = instance.instantiate_mir_and_normalize_erasing_regions(
195 tcx,
196 ty::TypingEnv::fully_monomorphized(),
197 ty::EarlyBinder::bind(mir.clone()),
198 );
199 mir = tcx.arena.alloc(optimize_use_clone::<Bx>(cx, monomorphized_mir));
200 }
201202let debug_context = cx.create_function_debug_context(instance, fn_abi, llfn, &mir);
203204let start_llbb = Bx::append_block(cx, llfn, "start");
205let mut start_bx = Bx::build(cx, start_llbb);
206207if mir.basic_blocks.iter().any(|bb| {
208 bb.is_cleanup || matches!(bb.terminator().unwind(), Some(mir::UnwindAction::Terminate(_)))
209 }) {
210 start_bx.set_personality_fn(cx.eh_personality());
211 }
212213let cleanup_kinds =
214 base::wants_new_eh_instructions(tcx.sess).then(|| analyze::cleanup_kinds(&mir));
215216let cached_llbbs: IndexVec<mir::BasicBlock, CachedLlbb<Bx::BasicBlock>> =
217 mir.basic_blocks
218 .indices()
219 .map(|bb| {
220if bb == mir::START_BLOCK { CachedLlbb::Some(start_llbb) } else { CachedLlbb::None }
221 })
222 .collect();
223224let mut fx = FunctionCx {
225 instance,
226 mir,
227 llfn,
228 fn_abi,
229 cx,
230 personality_slot: None,
231 cached_llbbs,
232 unreachable_block: None,
233 terminate_blocks: IndexVec::from_elem(None, &mir.basic_blocks),
234 cleanup_kinds,
235 landing_pads: IndexVec::from_elem(None, &mir.basic_blocks),
236 funclets: IndexVec::from_fn_n(|_| None, mir.basic_blocks.len()),
237 cold_blocks: find_cold_blocks(tcx, mir),
238 locals: locals::Locals::empty(),
239 debug_context,
240 per_local_var_debug_info: None,
241 caller_location: None,
242 };
243244// It may seem like we should iterate over `required_consts` to ensure they all successfully
245 // evaluate; however, the `MirUsedCollector` already did that during the collection phase of
246 // monomorphization, and if there is an error during collection then codegen never starts -- so
247 // we don't have to do it again.
248249let (per_local_var_debug_info, consts_debug_info) =
250 fx.compute_per_local_var_debug_info(&mut start_bx).unzip();
251 fx.per_local_var_debug_info = per_local_var_debug_info;
252253let traversal_order = traversal::mono_reachable_reverse_postorder(mir, tcx, instance);
254let memory_locals = analyze::non_ssa_locals(&fx, &traversal_order);
255256// Allocate variable and temp allocas
257let local_values = {
258let args = arg_local_refs(&mut start_bx, &mut fx, &memory_locals);
259260let mut allocate_local = |local: Local| {
261let decl = &mir.local_decls[local];
262let layout = start_bx.layout_of(fx.monomorphize(decl.ty));
263assert!(!layout.ty.has_erasable_regions());
264265if local == mir::RETURN_PLACE {
266match fx.fn_abi.ret.mode {
267 PassMode::Indirect { .. } => {
268debug!("alloc: {:?} (return place) -> place", local);
269let llretptr = start_bx.get_param(0);
270return LocalRef::Place(PlaceRef::new_sized(llretptr, layout));
271 }
272 PassMode::Cast { ref cast, .. } => {
273debug!("alloc: {:?} (return place) -> place", local);
274let size = cast.size(&start_bx).max(layout.size);
275return LocalRef::Place(PlaceRef::alloca_size(&mut start_bx, size, layout));
276 }
277_ => {}
278 };
279 }
280281if memory_locals.contains(local) {
282debug!("alloc: {:?} -> place", local);
283if layout.is_unsized() {
284 LocalRef::UnsizedPlace(PlaceRef::alloca_unsized_indirect(&mut start_bx, layout))
285 } else {
286 LocalRef::Place(PlaceRef::alloca(&mut start_bx, layout))
287 }
288 } else {
289debug!("alloc: {:?} -> operand", local);
290 LocalRef::new_operand(layout)
291 }
292 };
293294let retptr = allocate_local(mir::RETURN_PLACE);
295 iter::once(retptr)
296 .chain(args.into_iter())
297 .chain(mir.vars_and_temps_iter().map(allocate_local))
298 .collect()
299 };
300 fx.initialize_locals(local_values);
301302// Apply debuginfo to the newly allocated locals.
303fx.debug_introduce_locals(&mut start_bx, consts_debug_info.unwrap_or_default());
304305// The builders will be created separately for each basic block at `codegen_block`.
306 // So drop the builder of `start_llbb` to avoid having two at the same time.
307drop(start_bx);
308309let mut unreached_blocks = DenseBitSet::new_filled(mir.basic_blocks.len());
310// Codegen the body of each reachable block using our reverse postorder list.
311for bb in traversal_order {
312 fx.codegen_block(bb);
313 unreached_blocks.remove(bb);
314 }
315316// FIXME: These empty unreachable blocks are *mostly* a waste. They are occasionally
317 // targets for a SwitchInt terminator, but the reimplementation of the mono-reachable
318 // simplification in SwitchInt lowering sometimes misses cases that
319 // mono_reachable_reverse_postorder manages to figure out.
320 // The solution is to do something like post-mono GVN. But for now we have this hack.
321for bb in unreached_blocks.iter() {
322 fx.codegen_block_as_unreachable(bb);
323 }
324}
325326/// Replace `clone` calls that come from `use` statements with direct copies if possible.
327// FIXME: Move this function to mir::transform when post-mono MIR passes land.
328fn optimize_use_clone<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
329 cx: &'a Bx::CodegenCx,
330mut mir: Body<'tcx>,
331) -> Body<'tcx> {
332let tcx = cx.tcx();
333334if tcx.features().ergonomic_clones() {
335for bb in mir.basic_blocks.as_mut() {
336let mir::TerminatorKind::Call {
337 args,
338 destination,
339 target,
340 call_source: mir::CallSource::Use,
341 ..
342 } = &bb.terminator().kind
343else {
344continue;
345 };
346347// CallSource::Use calls always use 1 argument.
348match (&args.len(), &1) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(args.len(), 1);
349let arg = &args[0];
350351// These types are easily available from locals, so check that before
352 // doing DefId lookups to figure out what we're actually calling.
353let arg_ty = arg.node.ty(&mir.local_decls, tcx);
354355let ty::Ref(_region, inner_ty, mir::Mutability::Not) = *arg_ty.kind() else { continue };
356357if !tcx.type_is_copy_modulo_regions(cx.typing_env(), inner_ty) {
358continue;
359 }
360361let Some(arg_place) = arg.node.place() else { continue };
362363let destination_block = target.unwrap();
364365 bb.statements.push(mir::Statement::new(
366 bb.terminator().source_info,
367 mir::StatementKind::Assign(Box::new((
368*destination,
369 mir::Rvalue::Use(mir::Operand::Copy(
370 arg_place.project_deeper(&[mir::ProjectionElem::Deref], tcx),
371 )),
372 ))),
373 ));
374375 bb.terminator_mut().kind = mir::TerminatorKind::Goto { target: destination_block };
376 }
377 }
378379mir380}
381382/// Produces, for each argument, a `Value` pointing at the
383/// argument's value. As arguments are places, these are always
384/// indirect.
385fn arg_local_refs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
386 bx: &mut Bx,
387 fx: &mut FunctionCx<'a, 'tcx, Bx>,
388 memory_locals: &DenseBitSet<mir::Local>,
389) -> Vec<LocalRef<'tcx, Bx::Value>> {
390let mir = fx.mir;
391let mut idx = 0;
392let mut llarg_idx = fx.fn_abi.ret.is_indirect() as usize;
393394let mut num_untupled = None;
395396let codegen_fn_attrs = bx.tcx().codegen_instance_attrs(fx.instance.def);
397if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
398return ::alloc::vec::Vec::new()vec![];
399 }
400401let args = mir402 .args_iter()
403 .enumerate()
404 .map(|(arg_index, local)| {
405let arg_decl = &mir.local_decls[local];
406let arg_ty = fx.monomorphize(arg_decl.ty);
407408if Some(local) == mir.spread_arg {
409// This argument (e.g., the last argument in the "rust-call" ABI)
410 // is a tuple that was spread at the ABI level and now we have
411 // to reconstruct it into a tuple local variable, from multiple
412 // individual LLVM function arguments.
413let ty::Tuple(tupled_arg_tys) = arg_ty.kind() else {
414::rustc_middle::util::bug::bug_fmt(format_args!("spread argument isn\'t a tuple?!"));bug!("spread argument isn't a tuple?!");
415 };
416417let layout = bx.layout_of(arg_ty);
418419// FIXME: support unsized params in "rust-call" ABI
420if layout.is_unsized() {
421::rustc_middle::util::bug::span_bug_fmt(arg_decl.source_info.span,
format_args!("\"rust-call\" ABI does not support unsized params"));span_bug!(
422arg_decl.source_info.span,
423"\"rust-call\" ABI does not support unsized params",
424 );
425 }
426427let place = PlaceRef::alloca(bx, layout);
428for i in 0..tupled_arg_tys.len() {
429let arg = &fx.fn_abi.args[idx];
430 idx += 1;
431if let PassMode::Cast { pad_i32: true, .. } = arg.mode {
432 llarg_idx += 1;
433 }
434let pr_field = place.project_field(bx, i);
435 bx.store_fn_arg(arg, &mut llarg_idx, pr_field);
436 }
437match (&None, &num_untupled.replace(tupled_arg_tys.len())) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::Some(format_args!("Replaced existing num_tupled")));
}
}
};assert_eq!(
438None,
439 num_untupled.replace(tupled_arg_tys.len()),
440"Replaced existing num_tupled"
441);
442443return LocalRef::Place(place);
444 }
445446if fx.fn_abi.c_variadic && arg_index == fx.fn_abi.args.len() {
447let va_list = PlaceRef::alloca(bx, bx.layout_of(arg_ty));
448449// Explicitly start the lifetime of the `va_list`, improves LLVM codegen.
450bx.lifetime_start(va_list.val.llval, va_list.layout.size);
451452bx.va_start(va_list.val.llval);
453454return LocalRef::Place(va_list);
455 }
456457let arg = &fx.fn_abi.args[idx];
458idx += 1;
459if let PassMode::Cast { pad_i32: true, .. } = arg.mode {
460llarg_idx += 1;
461 }
462463if !memory_locals.contains(local) {
464// We don't have to cast or keep the argument in the alloca.
465 // FIXME(eddyb): We should figure out how to use llvm.dbg.value instead
466 // of putting everything in allocas just so we can use llvm.dbg.declare.
467let local = |op| LocalRef::Operand(op);
468match arg.mode {
469 PassMode::Ignore => {
470return local(OperandRef::zero_sized(arg.layout));
471 }
472 PassMode::Direct(_) => {
473let llarg = bx.get_param(llarg_idx);
474llarg_idx += 1;
475return local(OperandRef::from_immediate_or_packed_pair(
476bx, llarg, arg.layout,
477 ));
478 }
479 PassMode::Pair(..) => {
480let (a, b) = (bx.get_param(llarg_idx), bx.get_param(llarg_idx + 1));
481llarg_idx += 2;
482483return local(OperandRef {
484 val: OperandValue::Pair(a, b),
485 layout: arg.layout,
486 move_annotation: None,
487 });
488 }
489_ => {}
490 }
491 }
492493match arg.mode {
494// Sized indirect arguments
495PassMode::Indirect { attrs, meta_attrs: None, on_stack: _ } => {
496// Don't copy an indirect argument to an alloca, the caller already put it
497 // in a temporary alloca and gave it up.
498 // FIXME: lifetimes
499if let Some(pointee_align) = attrs.pointee_align
500 && pointee_align < arg.layout.align.abi
501 {
502// ...unless the argument is underaligned, then we need to copy it to
503 // a higher-aligned alloca.
504let tmp = PlaceRef::alloca(bx, arg.layout);
505bx.store_fn_arg(arg, &mut llarg_idx, tmp);
506 LocalRef::Place(tmp)
507 } else {
508let llarg = bx.get_param(llarg_idx);
509llarg_idx += 1;
510 LocalRef::Place(PlaceRef::new_sized(llarg, arg.layout))
511 }
512 }
513// Unsized indirect arguments
514PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } => {
515// As the storage for the indirect argument lives during
516 // the whole function call, we just copy the wide pointer.
517let llarg = bx.get_param(llarg_idx);
518llarg_idx += 1;
519let llextra = bx.get_param(llarg_idx);
520llarg_idx += 1;
521let indirect_operand = OperandValue::Pair(llarg, llextra);
522523let tmp = PlaceRef::alloca_unsized_indirect(bx, arg.layout);
524indirect_operand.store(bx, tmp);
525 LocalRef::UnsizedPlace(tmp)
526 }
527_ => {
528let tmp = PlaceRef::alloca(bx, arg.layout);
529bx.store_fn_arg(arg, &mut llarg_idx, tmp);
530 LocalRef::Place(tmp)
531 }
532 }
533 })
534 .collect::<Vec<_>>();
535536if fx.instance.def.requires_caller_location(bx.tcx()) {
537let mir_args = if let Some(num_untupled) = num_untupled {
538// Subtract off the tupled argument that gets 'expanded'
539args.len() - 1 + num_untupled540 } else {
541args.len()
542 };
543match (&fx.fn_abi.args.len(), &(mir_args + 1)) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::Some(format_args!("#[track_caller] instance {0:?} must have 1 more argument in their ABI than in their MIR",
fx.instance)));
}
}
};assert_eq!(
544 fx.fn_abi.args.len(),
545 mir_args + 1,
546"#[track_caller] instance {:?} must have 1 more argument in their ABI than in their MIR",
547 fx.instance
548 );
549550let arg = fx.fn_abi.args.last().unwrap();
551match arg.mode {
552 PassMode::Direct(_) => (),
553_ => ::rustc_middle::util::bug::bug_fmt(format_args!("caller location must be PassMode::Direct, found {0:?}",
arg.mode))bug!("caller location must be PassMode::Direct, found {:?}", arg.mode),
554 }
555556fx.caller_location = Some(OperandRef {
557 val: OperandValue::Immediate(bx.get_param(llarg_idx)),
558 layout: arg.layout,
559 move_annotation: None,
560 });
561 }
562563args564}
565566fn find_cold_blocks<'tcx>(
567 tcx: TyCtxt<'tcx>,
568 mir: &mir::Body<'tcx>,
569) -> IndexVec<mir::BasicBlock, bool> {
570let local_decls = &mir.local_decls;
571572let mut cold_blocks: IndexVec<mir::BasicBlock, bool> =
573IndexVec::from_elem(false, &mir.basic_blocks);
574575// Traverse all basic blocks from end of the function to the start.
576for (bb, bb_data) in traversal::postorder(mir) {
577let terminator = bb_data.terminator();
578579match terminator.kind {
580// If a BB ends with a call to a cold function, mark it as cold.
581mir::TerminatorKind::Call { ref func, .. }
582 | mir::TerminatorKind::TailCall { ref func, .. }
583if let ty::FnDef(def_id, ..) = *func.ty(local_decls, tcx).kind()
584 && let attrs = tcx.codegen_fn_attrs(def_id)
585 && attrs.flags.contains(CodegenFnAttrFlags::COLD) =>
586 {
587 cold_blocks[bb] = true;
588continue;
589 }
590591// If a BB ends with an `unreachable`, also mark it as cold.
592mir::TerminatorKind::Unreachable => {
593 cold_blocks[bb] = true;
594continue;
595 }
596597_ => {}
598 }
599600// If all successors of a BB are cold and there's at least one of them, mark this BB as cold
601let mut succ = terminator.successors();
602if let Some(first) = succ.next()
603 && cold_blocks[first]
604 && succ.all(|s| cold_blocks[s])
605 {
606 cold_blocks[bb] = true;
607 }
608 }
609610cold_blocks611}