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_span::ErrorGuaranteed;
11use rustc_target::callconv::{FnAbi, PassMode};
12use tracing::{debug, instrument};
1314use crate::base;
15use crate::traits::*;
1617mod analyze;
18mod block;
19mod constant;
20mod coverageinfo;
21pub mod debuginfo;
22mod intrinsic;
23mod locals;
24pub mod naked_asm;
25pub mod operand;
26pub mod place;
27mod rvalue;
28mod statement;
2930pub use self::block::store_cast;
31use self::debuginfo::{FunctionDebugContext, PerLocalVarDebugInfo};
32use self::operand::{OperandRef, OperandValue};
33use self::place::PlaceRef;
3435// Used for tracking the state of generated basic blocks.
36enum CachedLlbb<T> {
37/// Nothing created yet.
38None,
3940/// Has been created.
41Some(T),
4243/// Nothing created yet, and nothing should be.
44Skip,
45}
4647type PerLocalVarDebugInfoIndexVec<'tcx, V> =
48IndexVec<mir::Local, Vec<PerLocalVarDebugInfo<'tcx, V>>>;
4950/// Master context for codegenning from MIR.
51pub struct FunctionCx<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> {
52 instance: Instance<'tcx>,
5354 mir: &'tcx mir::Body<'tcx>,
5556 debug_context: Option<FunctionDebugContext<'tcx, Bx::DIScope, Bx::DILocation>>,
5758 llfn: Bx::Function,
5960 cx: &'a Bx::CodegenCx,
6162 fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
6364/// When unwinding is initiated, we have to store this personality
65 /// value somewhere so that we can load it and re-use it in the
66 /// resume instruction. The personality is (afaik) some kind of
67 /// value used for C++ unwinding, which must filter by type: we
68 /// don't really care about it very much. Anyway, this value
69 /// contains an alloca into which the personality is stored and
70 /// then later loaded when generating the DIVERGE_BLOCK.
71personality_slot: Option<PlaceRef<'tcx, Bx::Value>>,
7273/// A backend `BasicBlock` for each MIR `BasicBlock`, created lazily
74 /// as-needed (e.g. RPO reaching it or another block branching to it).
75// FIXME(eddyb) rename `llbbs` and other `ll`-prefixed things to use a
76 // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbbs`).
77cached_llbbs: IndexVec<mir::BasicBlock, CachedLlbb<Bx::BasicBlock>>,
7879/// The funclet status of each basic block
80cleanup_kinds: Option<IndexVec<mir::BasicBlock, analyze::CleanupKind>>,
8182/// When targeting MSVC, this stores the cleanup info for each funclet BB.
83 /// This is initialized at the same time as the `landing_pads` entry for the
84 /// funclets' head block, i.e. when needed by an unwind / `cleanup_ret` edge.
85funclets: IndexVec<mir::BasicBlock, Option<Bx::Funclet>>,
8687/// This stores the cached landing/cleanup pad block for a given BB.
88// FIXME(eddyb) rename this to `eh_pads`.
89landing_pads: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
9091/// Cached unreachable block
92unreachable_block: Option<Bx::BasicBlock>,
9394/// Cached terminate upon unwinding block and its reason. For non-wasm
95 /// targets, there is at most one such block per function, stored at index
96 /// `START_BLOCK`. For wasm targets, each funclet needs its own terminate
97 /// block, indexed by the cleanup block that is the funclet's head.
98terminate_blocks: IndexVec<mir::BasicBlock, Option<(Bx::BasicBlock, UnwindTerminateReason)>>,
99100/// A bool flag for each basic block indicating whether it is a cold block.
101 /// A cold block is a block that is unlikely to be executed at runtime.
102cold_blocks: IndexVec<mir::BasicBlock, bool>,
103104/// The location where each MIR arg/var/tmp/ret is stored. This is
105 /// usually an `PlaceRef` representing an alloca, but not always:
106 /// sometimes we can skip the alloca and just store the value
107 /// directly using an `OperandRef`, which makes for tighter LLVM
108 /// IR. The conditions for using an `OperandRef` are as follows:
109 ///
110 /// - the type of the local must be judged "immediate" by `is_llvm_immediate`
111 /// - the operand must never be referenced indirectly
112 /// - we should not take its address using the `&` operator
113 /// - nor should it appear in a place path like `tmp.a`
114 /// - the operand must be defined by an rvalue that can generate immediate
115 /// values
116 ///
117 /// Avoiding allocs can also be important for certain intrinsics,
118 /// notably `expect`.
119locals: locals::Locals<'tcx, Bx::Value>,
120121/// All `VarDebugInfo` from the MIR body, partitioned by `Local`.
122 /// This is `None` if no variable debuginfo/names are needed.
123per_local_var_debug_info: Option<PerLocalVarDebugInfoIndexVec<'tcx, Bx::DIVariable>>,
124125/// Caller location propagated if this function has `#[track_caller]`.
126caller_location: Option<OperandRef<'tcx, Bx::Value>>,
127}
128129impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
130pub fn monomorphize<T>(&self, value: T) -> T
131where
132T: Copy + TypeFoldable<TyCtxt<'tcx>>,
133 {
134{
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:134",
"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(134u32),
::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);
135self.instance.instantiate_mir_and_normalize_erasing_regions(
136self.cx.tcx(),
137self.cx.typing_env(),
138 ty::EarlyBinder::bind(value),
139 )
140 }
141}
142143enum LocalRef<'tcx, V> {
144 Place(PlaceRef<'tcx, V>),
145/// `UnsizedPlace(p)`: `p` itself is a thin pointer (indirect place).
146 /// `*p` is the wide pointer that references the actual unsized place.
147 ///
148 /// MIR only supports unsized args, not dynamically-sized locals, so
149 /// new unsized temps don't exist and we must reuse the referred-to place.
150 ///
151 /// FIXME: Since the removal of unsized locals in <https://github.com/rust-lang/rust/pull/142911>,
152 /// can we maybe use `Place` here? Or refactor it in another way? There are quite a few
153 /// `UnsizedPlace => bug` branches now.
154UnsizedPlace(PlaceRef<'tcx, V>),
155/// The backend [`OperandValue`] has already been generated.
156Operand(OperandRef<'tcx, V>),
157/// Will be a `Self::Operand` once we get to its definition.
158PendingOperand,
159}
160161pub enum IntrinsicResult<'tcx, V> {
162/// This intrinsic created an operand without using the `result_place` argument.
163 ///
164 /// `codegen_call_terminator` will handle writing the result into the place,
165 /// if doing so is needed.
166 ///
167 /// The vast majority of intrinsics can do this, see MCP#970
168Operand(OperandValue<V>),
169170/// The intrinsic wrote its result into the `result_place` argument.
171 ///
172 /// Most things don't need to do this, but there are some: `volatile_load`
173 /// of a non-scalar type, for example, has to.
174WroteIntoPlace,
175176/// Another instance should be called instead. This is used to invoke intrinsic
177 /// default bodies in case an intrinsic is not implemented by the backend.
178Fallback(ty::Instance<'tcx>),
179180/// Arguably this shouldn't exist, per MCP#620, but a bunch do it.
181Err(ErrorGuaranteed),
182}
183184impl<'tcx, V: CodegenObject> LocalRef<'tcx, V> {
185fn new_operand(layout: TyAndLayout<'tcx>) -> LocalRef<'tcx, V> {
186if layout.is_zst() {
187// Zero-size temporaries aren't always initialized, which
188 // doesn't matter because they don't contain data, but
189 // we need something sufficiently aligned in the operand.
190LocalRef::Operand(OperandRef::zero_sized(layout))
191 } else {
192 LocalRef::PendingOperand193 }
194 }
195}
196197///////////////////////////////////////////////////////////////////////////
198199#[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(199u32),
::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:215",
"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(215u32),
::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:292",
"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(292u32),
::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:297",
"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(297u32),
::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:306",
"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(306u32),
::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:313",
"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(313u32),
::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))]200pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
201 cx: &'a Bx::CodegenCx,
202 instance: Instance<'tcx>,
203) {
204assert!(!instance.args.has_infer());
205206let tcx = cx.tcx();
207let llfn = cx.get_fn(instance);
208209let mut mir = tcx.instance_mir(instance.def);
210// Note that the ABI logic has deduced facts about the functions' parameters based on the MIR we
211 // got here (`deduce_param_attrs`). That means we can *not* apply arbitrary further MIR
212 // transforms as that may invalidate those deduced facts!
213214let fn_abi = cx.fn_abi_of_instance(instance, ty::List::empty());
215debug!("fn_abi: {:?}", fn_abi);
216217if tcx.features().ergonomic_clones() {
218let monomorphized_mir = instance.instantiate_mir_and_normalize_erasing_regions(
219 tcx,
220 ty::TypingEnv::fully_monomorphized(),
221 ty::EarlyBinder::bind(mir.clone()),
222 );
223 mir = tcx.arena.alloc(optimize_use_clone::<Bx>(cx, monomorphized_mir));
224 }
225226let debug_context = cx.create_function_debug_context(instance, fn_abi, llfn, &mir);
227228let start_llbb = Bx::append_block(cx, llfn, "start");
229let mut start_bx = Bx::build(cx, start_llbb);
230231if mir.basic_blocks.iter().any(|bb| {
232 bb.is_cleanup || matches!(bb.terminator().unwind(), Some(mir::UnwindAction::Terminate(_)))
233 }) {
234 start_bx.set_personality_fn(cx.eh_personality());
235 }
236237let cleanup_kinds =
238 base::wants_new_eh_instructions(tcx.sess).then(|| analyze::cleanup_kinds(&mir));
239240let cached_llbbs: IndexVec<mir::BasicBlock, CachedLlbb<Bx::BasicBlock>> =
241 mir.basic_blocks
242 .indices()
243 .map(|bb| {
244if bb == mir::START_BLOCK { CachedLlbb::Some(start_llbb) } else { CachedLlbb::None }
245 })
246 .collect();
247248let mut fx = FunctionCx {
249 instance,
250 mir,
251 llfn,
252 fn_abi,
253 cx,
254 personality_slot: None,
255 cached_llbbs,
256 unreachable_block: None,
257 terminate_blocks: IndexVec::from_elem(None, &mir.basic_blocks),
258 cleanup_kinds,
259 landing_pads: IndexVec::from_elem(None, &mir.basic_blocks),
260 funclets: IndexVec::from_fn_n(|_| None, mir.basic_blocks.len()),
261 cold_blocks: find_cold_blocks(tcx, mir),
262 locals: locals::Locals::empty(),
263 debug_context,
264 per_local_var_debug_info: None,
265 caller_location: None,
266 };
267268// It may seem like we should iterate over `required_consts` to ensure they all successfully
269 // evaluate; however, the `MirUsedCollector` already did that during the collection phase of
270 // monomorphization, and if there is an error during collection then codegen never starts -- so
271 // we don't have to do it again.
272273let (per_local_var_debug_info, consts_debug_info) =
274 fx.compute_per_local_var_debug_info(&mut start_bx).unzip();
275 fx.per_local_var_debug_info = per_local_var_debug_info;
276277let traversal_order = traversal::mono_reachable_reverse_postorder(mir, tcx, instance);
278let memory_locals = analyze::non_ssa_locals(&fx, &traversal_order);
279280// Allocate variable and temp allocas
281let local_values = {
282let args = arg_local_refs(&mut start_bx, &mut fx, &memory_locals);
283284let mut allocate_local = |local: Local| {
285let decl = &mir.local_decls[local];
286let layout = start_bx.layout_of(fx.monomorphize(decl.ty));
287assert!(!layout.ty.has_erasable_regions());
288289if local == mir::RETURN_PLACE {
290match fx.fn_abi.ret.mode {
291 PassMode::Indirect { .. } => {
292debug!("alloc: {:?} (return place) -> place", local);
293let llretptr = start_bx.get_param(0);
294return LocalRef::Place(PlaceRef::new_sized(llretptr, layout));
295 }
296 PassMode::Cast { ref cast, .. } => {
297debug!("alloc: {:?} (return place) -> place", local);
298let size = cast.size(&start_bx).max(layout.size);
299return LocalRef::Place(PlaceRef::alloca_size(&mut start_bx, size, layout));
300 }
301_ => {}
302 };
303 }
304305if memory_locals.contains(local) {
306debug!("alloc: {:?} -> place", local);
307if layout.is_unsized() {
308 LocalRef::UnsizedPlace(PlaceRef::alloca_unsized_indirect(&mut start_bx, layout))
309 } else {
310 LocalRef::Place(PlaceRef::alloca(&mut start_bx, layout))
311 }
312 } else {
313debug!("alloc: {:?} -> operand", local);
314 LocalRef::new_operand(layout)
315 }
316 };
317318let retptr = allocate_local(mir::RETURN_PLACE);
319 iter::once(retptr)
320 .chain(args.into_iter())
321 .chain(mir.vars_and_temps_iter().map(allocate_local))
322 .collect()
323 };
324 fx.initialize_locals(local_values);
325326// Apply debuginfo to the newly allocated locals.
327fx.debug_introduce_locals(&mut start_bx, consts_debug_info.unwrap_or_default());
328329// The builders will be created separately for each basic block at `codegen_block`.
330 // So drop the builder of `start_llbb` to avoid having two at the same time.
331drop(start_bx);
332333let mut unreached_blocks = DenseBitSet::new_filled(mir.basic_blocks.len());
334// Codegen the body of each reachable block using our reverse postorder list.
335for bb in traversal_order {
336 fx.codegen_block(bb);
337 unreached_blocks.remove(bb);
338 }
339340// FIXME: These empty unreachable blocks are *mostly* a waste. They are occasionally
341 // targets for a SwitchInt terminator, but the reimplementation of the mono-reachable
342 // simplification in SwitchInt lowering sometimes misses cases that
343 // mono_reachable_reverse_postorder manages to figure out.
344 // The solution is to do something like post-mono GVN. But for now we have this hack.
345for bb in unreached_blocks.iter() {
346 fx.codegen_block_as_unreachable(bb);
347 }
348}
349350/// Replace `clone` calls that come from `use` statements with direct copies if possible.
351// FIXME: Move this function to mir::transform when post-mono MIR passes land.
352fn optimize_use_clone<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
353 cx: &'a Bx::CodegenCx,
354mut mir: Body<'tcx>,
355) -> Body<'tcx> {
356let tcx = cx.tcx();
357358if tcx.features().ergonomic_clones() {
359for bb in mir.basic_blocks.as_mut() {
360let mir::TerminatorKind::Call {
361 args,
362 destination,
363 target,
364 call_source: mir::CallSource::Use,
365 ..
366 } = &bb.terminator().kind
367else {
368continue;
369 };
370371// CallSource::Use calls always use 1 argument.
372match (&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);
373let arg = &args[0];
374375// These types are easily available from locals, so check that before
376 // doing DefId lookups to figure out what we're actually calling.
377let arg_ty = arg.node.ty(&mir.local_decls, tcx);
378379let ty::Ref(_region, inner_ty, mir::Mutability::Not) = *arg_ty.kind() else { continue };
380381if !tcx.type_is_copy_modulo_regions(cx.typing_env(), inner_ty) {
382continue;
383 }
384385let Some(arg_place) = arg.node.place() else { continue };
386387let destination_block = target.unwrap();
388389 bb.statements.push(mir::Statement::new(
390 bb.terminator().source_info,
391 mir::StatementKind::Assign(Box::new((
392*destination,
393 mir::Rvalue::Use(
394 mir::Operand::Copy(
395 arg_place.project_deeper(&[mir::ProjectionElem::Deref], tcx),
396 ),
397 mir::WithRetag::Yes,
398 ),
399 ))),
400 ));
401402 bb.terminator_mut().kind = mir::TerminatorKind::Goto { target: destination_block };
403 }
404 }
405406mir407}
408409/// Produces, for each argument, a `Value` pointing at the
410/// argument's value. As arguments are places, these are always
411/// indirect.
412fn arg_local_refs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
413 bx: &mut Bx,
414 fx: &mut FunctionCx<'a, 'tcx, Bx>,
415 memory_locals: &DenseBitSet<mir::Local>,
416) -> Vec<LocalRef<'tcx, Bx::Value>> {
417let mir = fx.mir;
418let mut idx = 0;
419let mut llarg_idx = fx.fn_abi.ret.is_indirect() as usize;
420421let mut num_untupled = None;
422423let codegen_fn_attrs = bx.tcx().codegen_instance_attrs(fx.instance.def);
424if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
425return ::alloc::vec::Vec::new()vec![];
426 }
427428let args = mir429 .args_iter()
430 .enumerate()
431 .map(|(arg_index, local)| {
432let arg_decl = &mir.local_decls[local];
433let arg_ty = fx.monomorphize(arg_decl.ty);
434435if Some(local) == mir.spread_arg {
436// This argument (e.g., the last argument in the "rust-call" ABI)
437 // is a tuple that was spread at the ABI level and now we have
438 // to reconstruct it into a tuple local variable, from multiple
439 // individual LLVM function arguments.
440let ty::Tuple(tupled_arg_tys) = arg_ty.kind() else {
441::rustc_middle::util::bug::bug_fmt(format_args!("spread argument isn\'t a tuple?!"));bug!("spread argument isn't a tuple?!");
442 };
443444let layout = bx.layout_of(arg_ty);
445446// FIXME: support unsized params in "rust-call" ABI
447if layout.is_unsized() {
448::rustc_middle::util::bug::span_bug_fmt(arg_decl.source_info.span,
format_args!("\"rust-call\" ABI does not support unsized params"));span_bug!(
449 arg_decl.source_info.span,
450"\"rust-call\" ABI does not support unsized params",
451 );
452 }
453454let place = PlaceRef::alloca(bx, layout);
455for i in 0..tupled_arg_tys.len() {
456let arg = &fx.fn_abi.args[idx];
457 idx += 1;
458if let PassMode::Cast { pad_i32: true, .. } = arg.mode {
459 llarg_idx += 1;
460 }
461let pr_field = place.project_field(bx, i);
462 bx.store_fn_arg(arg, &mut llarg_idx, pr_field);
463 }
464match (&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_untupled")));
}
}
};assert_eq!(
465None,
466 num_untupled.replace(tupled_arg_tys.len()),
467"Replaced existing num_untupled"
468);
469470return LocalRef::Place(place);
471 }
472473if fx.fn_abi.c_variadic && arg_index == fx.fn_abi.args.len() {
474let va_list = PlaceRef::alloca(bx, bx.layout_of(arg_ty));
475476// Explicitly start the lifetime of the `va_list`, improves LLVM codegen.
477bx.lifetime_start(va_list.val.llval, va_list.layout.size);
478479bx.va_start(va_list.val.llval);
480481return LocalRef::Place(va_list);
482 }
483484let arg = &fx.fn_abi.args[idx];
485idx += 1;
486if let PassMode::Cast { pad_i32: true, .. } = arg.mode {
487llarg_idx += 1;
488 }
489490if !memory_locals.contains(local) {
491// We don't have to cast or keep the argument in the alloca.
492 // FIXME(eddyb): We should figure out how to use llvm.dbg.value instead
493 // of putting everything in allocas just so we can use llvm.dbg.declare.
494let local = |op| LocalRef::Operand(op);
495match arg.mode {
496 PassMode::Ignore => {
497return local(OperandRef::zero_sized(arg.layout));
498 }
499 PassMode::Direct(_) => {
500let llarg = bx.get_param(llarg_idx);
501llarg_idx += 1;
502return local(OperandRef::from_immediate_or_packed_pair(
503bx, llarg, arg.layout,
504 ));
505 }
506 PassMode::Pair(..) => {
507let (a, b) = (bx.get_param(llarg_idx), bx.get_param(llarg_idx + 1));
508llarg_idx += 2;
509510return local(OperandRef {
511 val: OperandValue::Pair(a, b),
512 layout: arg.layout,
513 move_annotation: None,
514 });
515 }
516_ => {}
517 }
518 }
519520match arg.mode {
521// Sized indirect arguments
522PassMode::Indirect { attrs, meta_attrs: None, on_stack: _ } => {
523// Don't copy an indirect argument to an alloca, the caller already put it
524 // in a temporary alloca and gave it up.
525 // FIXME: lifetimes
526if let Some(pointee_align) = attrs.pointee_align
527 && pointee_align < arg.layout.align.abi
528 {
529// ...unless the argument is underaligned, then we need to copy it to
530 // a higher-aligned alloca.
531let tmp = PlaceRef::alloca(bx, arg.layout);
532bx.store_fn_arg(arg, &mut llarg_idx, tmp);
533 LocalRef::Place(tmp)
534 } else {
535let llarg = bx.get_param(llarg_idx);
536llarg_idx += 1;
537 LocalRef::Place(PlaceRef::new_sized(llarg, arg.layout))
538 }
539 }
540// Unsized indirect arguments
541PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } => {
542// As the storage for the indirect argument lives during
543 // the whole function call, we just copy the wide pointer.
544let llarg = bx.get_param(llarg_idx);
545llarg_idx += 1;
546let llextra = bx.get_param(llarg_idx);
547llarg_idx += 1;
548let indirect_operand = OperandValue::Pair(llarg, llextra);
549550let tmp = PlaceRef::alloca_unsized_indirect(bx, arg.layout);
551indirect_operand.store(bx, tmp);
552 LocalRef::UnsizedPlace(tmp)
553 }
554_ => {
555let tmp = PlaceRef::alloca(bx, arg.layout);
556bx.store_fn_arg(arg, &mut llarg_idx, tmp);
557 LocalRef::Place(tmp)
558 }
559 }
560 })
561 .collect::<Vec<_>>();
562563if fx.instance.def.requires_caller_location(bx.tcx()) {
564let mir_args = if let Some(num_untupled) = num_untupled {
565// Subtract off the tupled argument that gets 'expanded'
566args.len() - 1 + num_untupled567 } else {
568args.len()
569 };
570match (&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!(
571 fx.fn_abi.args.len(),
572 mir_args + 1,
573"#[track_caller] instance {:?} must have 1 more argument in their ABI than in their MIR",
574 fx.instance
575 );
576577let arg = fx.fn_abi.args.last().unwrap();
578match arg.mode {
579 PassMode::Direct(_) => (),
580_ => ::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),
581 }
582583fx.caller_location = Some(OperandRef {
584 val: OperandValue::Immediate(bx.get_param(llarg_idx)),
585 layout: arg.layout,
586 move_annotation: None,
587 });
588 }
589590args591}
592593fn find_cold_blocks<'tcx>(
594 tcx: TyCtxt<'tcx>,
595 mir: &mir::Body<'tcx>,
596) -> IndexVec<mir::BasicBlock, bool> {
597let local_decls = &mir.local_decls;
598599let mut cold_blocks: IndexVec<mir::BasicBlock, bool> =
600IndexVec::from_elem(false, &mir.basic_blocks);
601602// Traverse all basic blocks from end of the function to the start.
603for (bb, bb_data) in traversal::postorder(mir) {
604let terminator = bb_data.terminator();
605606match terminator.kind {
607// If a BB ends with a call to a cold function, mark it as cold.
608mir::TerminatorKind::Call { ref func, .. }
609 | mir::TerminatorKind::TailCall { ref func, .. }
610if let ty::FnDef(def_id, ..) = *func.ty(local_decls, tcx).kind()
611 && let attrs = tcx.codegen_fn_attrs(def_id)
612 && attrs.flags.contains(CodegenFnAttrFlags::COLD) =>
613 {
614 cold_blocks[bb] = true;
615continue;
616 }
617618// If a BB ends with an `unreachable`, also mark it as cold.
619mir::TerminatorKind::Unreachable => {
620 cold_blocks[bb] = true;
621continue;
622 }
623624_ => {}
625 }
626627// If all successors of a BB are cold and there's at least one of them, mark this BB as cold
628let mut succ = terminator.successors();
629if let Some(first) = succ.next()
630 && cold_blocks[first]
631 && succ.all(|s| cold_blocks[s])
632 {
633 cold_blocks[bb] = true;
634 }
635 }
636637cold_blocks638}