1//! Manages calling a concrete function (with known MIR body) with argument passing,
2//! and returning the return value to the caller.
34use std::assert_matches;
5use std::borrow::Cow;
67use either::{Left, Right};
8use rustc_abi::{selfas abi, ExternAbi, FieldIdx, Integer, VariantIdx};
9use rustc_hir::def_id::DefId;
10use rustc_hir::find_attr;
11use rustc_middle::ty::layout::{IntegerExt, TyAndLayout};
12use rustc_middle::ty::{self, AdtDef, Instance, Ty, VariantDef};
13use rustc_middle::{bug, mir, span_bug};
14use rustc_target::callconv::{ArgAbi, FnAbi};
15use tracing::field::Empty;
16use tracing::{info, instrument, trace};
1718use super::{
19CtfeProvenance, EnteredTraceSpan, FnVal, ImmTy, InterpCx, InterpResult, MPlaceTy, Machine,
20OpTy, PlaceTy, Projectable, Provenance, RetagMode, ReturnAction, ReturnContinuation, Scalar,
21interp_ok, throw_ub, throw_ub_format,
22};
23use crate::enter_trace_span;
2425/// An argument passed to a function.
26#[derive(#[automatically_derived]
impl<'tcx, Prov: ::core::clone::Clone + Provenance> ::core::clone::Clone for
FnArg<'tcx, Prov> {
#[inline]
fn clone(&self) -> FnArg<'tcx, Prov> {
match self {
FnArg::Copy(__self_0) =>
FnArg::Copy(::core::clone::Clone::clone(__self_0)),
FnArg::InPlace(__self_0) =>
FnArg::InPlace(::core::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]
impl<'tcx, Prov: ::core::fmt::Debug + Provenance> ::core::fmt::Debug for
FnArg<'tcx, Prov> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
FnArg::Copy(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Copy",
&__self_0),
FnArg::InPlace(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"InPlace", &__self_0),
}
}
}Debug)]
27pub enum FnArg<'tcx, Prov: Provenance = CtfeProvenance> {
28/// Pass a copy of the given operand.
29Copy(OpTy<'tcx, Prov>),
30/// Allow for the argument to be passed in-place: destroy the value originally stored at that
31 /// place and make the place inaccessible for the duration of the function call. This *must* be
32 /// an in-memory place so that we can do the proper alias checks.
33InPlace(MPlaceTy<'tcx, Prov>),
34}
3536impl<'tcx, Prov: Provenance> FnArg<'tcx, Prov> {
37pub fn layout(&self) -> &TyAndLayout<'tcx> {
38match self {
39 FnArg::Copy(op) => &op.layout,
40 FnArg::InPlace(mplace) => &mplace.layout,
41 }
42 }
4344/// Make a copy of the given fn_arg. Any `InPlace` are degenerated to copies, no protection of the
45 /// original memory occurs.
46pub fn copy_fn_arg(&self) -> OpTy<'tcx, Prov> {
47match self {
48 FnArg::Copy(op) => op.clone(),
49 FnArg::InPlace(mplace) => mplace.clone().into(),
50 }
51 }
52}
5354impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
55/// Make a copy of the given fn_args. Any `InPlace` are degenerated to copies, no protection of the
56 /// original memory occurs.
57pub fn copy_fn_args(args: &[FnArg<'tcx, M::Provenance>]) -> Vec<OpTy<'tcx, M::Provenance>> {
58args.iter().map(|fn_arg| fn_arg.copy_fn_arg()).collect()
59 }
6061/// Helper function for argument untupling.
62fn fn_arg_project_field(
63&self,
64 arg: &FnArg<'tcx, M::Provenance>,
65 field: FieldIdx,
66 ) -> InterpResult<'tcx, FnArg<'tcx, M::Provenance>> {
67interp_ok(match arg {
68 FnArg::Copy(op) => FnArg::Copy(self.project_field(op, field)?),
69 FnArg::InPlace(mplace) => FnArg::InPlace(self.project_field(mplace, field)?),
70 })
71 }
7273/// Returns whether the given type has trivial ABI.
74fn has_trivial_abi(&self, layout: TyAndLayout<'tcx>) -> InterpResult<'tcx, bool> {
75if !layout.is_1zst() {
76return interp_ok(false);
77 }
78match *layout.ty.kind() {
79// Trivially trivial-ABI types (because Rust makes no promises about their ABI).
80ty::Tuple(..)
81 | ty::Never82 | ty::FnDef(..)
83 | ty::Closure(..)
84 | ty::Coroutine(..)
85 | ty::CoroutineClosure(..) => interp_ok(true),
8687 ty::Array(elem, _len) => {
88// 0-length arrays are in general *not* okay, but arrays of trivial-ABI types are.
89self.has_trivial_abi(self.layout_of(elem)?)
90 }
91 ty::Adt(adt_def, _args) => {
92if adt_def.repr().transparent() {
93// All fields must have trivial ABI.
94(0..layout.fields.count()).try_fold(true, |acc, idx| {
95interp_ok(acc && self.has_trivial_abi(layout.field(self, idx))?)
96 })
97 } else if adt_def.repr().c() {
98interp_ok(false)
99 } else {
100// Can't be SIMD or Scalable (since this is a 1-ZST); only Rust is left.
101if !adt_def.repr().rust() {
::core::panicking::panic("assertion failed: adt_def.repr().rust()")
};assert!(adt_def.repr().rust());
102interp_ok(true)
103 }
104 }
105// Types that are considered transparent in `unfold_transparent` should also act
106 // like transparent types here.
107ty::Pat(base, _) => self.has_trivial_abi(self.layout_of(base)?),
108 ty::UnsafeBinder(bound_ty) => {
109let ty = self.tcx.instantiate_bound_regions_with_erased(bound_ty.into());
110self.has_trivial_abi(self.layout_of(ty)?)
111 }
112113 ty::Alias(..) => { ::core::panicking::panic_fmt(format_args!("non-normalized type")); }panic!("non-normalized type"),
114_ => interp_ok(false),
115 }
116 }
117118/// Find the wrapped inner type of a transparent wrapper by going for the unique
119 /// non-trivial-ABI field.
120 ///
121 /// We work with `TyAndLayout` here since that makes it much easier to iterate over all fields.
122fn unfold_transparent(
123&self,
124 layout: TyAndLayout<'tcx>,
125 may_unfold: impl Fn(AdtDef<'tcx>) -> bool,
126 ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
127match *layout.ty.kind() {
128 ty::Adt(adt_def, _) if adt_def.repr().transparent() && may_unfold(adt_def) => {
129{
match layout.variants {
rustc_abi::Variants::Single { .. } => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"rustc_abi::Variants::Single { .. }",
::core::option::Option::None);
}
}
};assert_matches!(layout.variants, rustc_abi::Variants::Single { .. });
130// Look for non-trivial-ABI field(s).
131let mut found = None;
132for idx in 0..layout.fields.count() {
133let field = layout.field(self, idx);
134if self.has_trivial_abi(field)? {
135continue;
136 }
137// Found a non-trivial ABI field!
138if found.is_some() {
139// There is more than one such field.
140 // FIXME: we should just panic here. But currently such repr(transparent)
141 // types are still accepted. We just don't treat them as transparent.
142return interp_ok(layout);
143 }
144 found = Some(field);
145 }
146let Some(field) = foundelse {
147// All fields have trivial ABI. That means this type is effectively `()`.
148return interp_ok(self.layout_of(self.tcx.types.unit)?);
149 };
150// Recurse.
151self.unfold_transparent(field, may_unfold)
152 }
153 ty::Pat(base, _) => self.unfold_transparent(self.layout_of(base)?, may_unfold),
154 ty::UnsafeBinder(bound_ty) => {
155let ty = self.tcx.instantiate_bound_regions_with_erased(bound_ty.into());
156self.unfold_transparent(self.layout_of(ty)?, may_unfold)
157 }
158// Not a transparent type, no further unfolding.
159_ => interp_ok(layout),
160 }
161 }
162163/// Unwrap types that are guaranteed a null-pointer-optimization
164fn unfold_npo(&self, layout: TyAndLayout<'tcx>) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
165// Check if this is an option-like type wrapping some type.
166let ty::Adt(def, args) = layout.ty.kind() else {
167// Not an ADT, so definitely no NPO.
168return interp_ok(layout);
169 };
170if def.variants().len() != 2 {
171// Not a 2-variant enum, so no NPO.
172return interp_ok(layout);
173 }
174if !def.is_enum() {
::core::panicking::panic("assertion failed: def.is_enum()")
};assert!(def.is_enum());
175176let all_fields_1zst = |variant: &VariantDef| -> InterpResult<'tcx, _> {
177for field in &variant.fields {
178let ty = field.ty(*self.tcx, args).skip_norm_wip();
179let layout = self.layout_of(ty)?;
180if !layout.is_1zst() {
181return interp_ok(false);
182 }
183 }
184interp_ok(true)
185 };
186187// If one variant consists entirely of 1-ZST, then the other variant
188 // is the only "relevant" one for this check.
189let var0 = VariantIdx::from_u32(0);
190let var1 = VariantIdx::from_u32(1);
191let relevant_variant = if all_fields_1zst(def.variant(var0))? {
192def.variant(var1)
193 } else if all_fields_1zst(def.variant(var1))? {
194def.variant(var0)
195 } else {
196// No variant is all-1-ZST, so no NPO.
197return interp_ok(layout);
198 };
199// The "relevant" variant must have exactly one field, and its type is the "inner" type.
200if relevant_variant.fields.len() != 1 {
201return interp_ok(layout);
202 }
203let inner =
204relevant_variant.fields[FieldIdx::from_u32(0)].ty(*self.tcx, args).skip_norm_wip();
205let inner = self.layout_of(inner)?;
206207// Check if the inner type is one of the NPO-guaranteed ones.
208 // For that we first unpeel transparent *structs* (but not unions).
209let is_npo =
210 |def: AdtDef<'tcx>| {
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(def.did(), &self.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcNonnullOptimizationGuaranteed)
=> {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(self.tcx, def.did(), RustcNonnullOptimizationGuaranteed);
211let inner = self.unfold_transparent(inner, /* may_unfold */ |def| {
212// Stop at NPO types so that we don't miss that attribute in the check below!
213def.is_struct() && !is_npo(def)
214 })?;
215interp_ok(match inner.ty.kind() {
216 ty::Ref(..) | ty::FnPtr(..) => {
217// Option<&T> behaves like &T, and same for fn()
218inner219 }
220 ty::Adt(def, _) if is_npo(*def) => {
221// Once we found a `nonnull_optimization_guaranteed` type, further strip off
222 // newtype structs from it to find the underlying ABI type.
223self.unfold_transparent(inner, /* may_unfold */ |def| def.is_struct())?
224}
225_ => {
226// Everything else we do not unfold.
227layout228 }
229 })
230 }
231232/// Check if these two layouts look like they are fn-ABI-compatible.
233 /// (We also compare the `PassMode`, so this doesn't have to check everything. But it turns out
234 /// that only checking the `PassMode` is insufficient.)
235fn layout_compat(
236&self,
237 caller: TyAndLayout<'tcx>,
238 callee: TyAndLayout<'tcx>,
239 ) -> InterpResult<'tcx, bool> {
240// Fast path: equal types are definitely compatible.
241if caller.ty == callee.ty {
242return interp_ok(true);
243 }
244// Handle trivial-ABI types.
245if self.has_trivial_abi(caller)? && self.has_trivial_abi(callee)? {
246return interp_ok(true);
247 }
248// Unfold newtypes and NPO optimizations.
249let unfold = |layout: TyAndLayout<'tcx>| {
250self.unfold_transparent(layout, /* may_unfold */ |_def| true)
251 .and_then(|f| self.unfold_npo(f))
252 };
253let caller = unfold(caller)?;
254let callee = unfold(callee)?;
255// Not-quite-so-fast path: if the types are equal now, they are compatible.
256if caller.ty == callee.ty {
257return interp_ok(true);
258 }
259// Now see if these inner types are compatible.
260261 // Compatible pointer types. For thin pointers, we have to accept even non-`repr(transparent)`
262 // things as compatible due to `DispatchFromDyn`. For instance, `Rc<i32>` and `*mut i32`
263 // must be compatible. So we just accept everything with Pointer ABI as compatible,
264 // even if this will accept some code that is not stably guaranteed to work.
265 // This also handles function pointers.
266let thin_pointer = |layout: TyAndLayout<'tcx>| match layout.backend_repr {
267 abi::BackendRepr::Scalar(s) => match s.primitive() {
268 abi::Primitive::Pointer(addr_space) => Some(addr_space),
269_ => None,
270 },
271_ => None,
272 };
273if let (Some(caller), Some(callee)) = (thin_pointer(caller), thin_pointer(callee)) {
274return interp_ok(caller == callee);
275 }
276// For wide pointers we have to get the pointee type.
277let pointee_ty = |ty: Ty<'tcx>| -> InterpResult<'tcx, Option<Ty<'tcx>>> {
278// We cannot use `builtin_deref` here since we need to reject `Box<T, MyAlloc>`.
279interp_ok(Some(match ty.kind() {
280 ty::Ref(_, ty, _) => *ty,
281 ty::RawPtr(ty, _) => *ty,
282// We only accept `Box` with the default allocator.
283_ if ty.is_box_global(*self.tcx) => ty.expect_boxed_ty(),
284_ => return interp_ok(None),
285 }))
286 };
287if let (Some(caller), Some(callee)) = (pointee_ty(caller.ty)?, pointee_ty(callee.ty)?) {
288// This is okay if they have the same metadata type.
289let meta_ty = |ty: Ty<'tcx>| {
290// Even if `ty` is normalized, the search for the unsized tail will project
291 // to fields, which can yield non-normalized types. So we need to provide a
292 // normalization function.
293let normalize = |ty| self.tcx.normalize_erasing_regions(self.typing_env, ty);
294ty.ptr_metadata_ty(*self.tcx, normalize)
295 };
296return interp_ok(meta_ty(caller) == meta_ty(callee));
297 }
298299// Compatible integer types (in particular, usize vs ptr-sized-u32/u64).
300 // `char` counts as `u32.`
301let int_ty = |ty: Ty<'tcx>| {
302Some(match ty.kind() {
303 ty::Int(ity) => (Integer::from_int_ty(&self.tcx, *ity), /* signed */ true),
304 ty::Uint(uty) => (Integer::from_uint_ty(&self.tcx, *uty), /* signed */ false),
305 ty::Char => (Integer::I32, /* signed */ false),
306_ => return None,
307 })
308 };
309if let (Some(caller), Some(callee)) = (int_ty(caller.ty), int_ty(callee.ty)) {
310// This is okay if they are the same integer type.
311return interp_ok(caller == callee);
312 }
313314// The rest is incompatible.
315interp_ok(false)
316 }
317318/// Returns a `bool` saying whether the two arguments are ABI-compatible.
319pub fn check_argument_compat(
320&self,
321 caller_abi: &ArgAbi<'tcx, Ty<'tcx>>,
322 callee_abi: &ArgAbi<'tcx, Ty<'tcx>>,
323 ) -> InterpResult<'tcx, bool> {
324// We do not want to accept things as ABI-compatible that just "happen to be" compatible on the current target,
325 // so we implement a type-based check that reflects the guaranteed rules for ABI compatibility.
326if self.layout_compat(caller_abi.layout, callee_abi.layout)? {
327// Ensure that our checks imply actual ABI compatibility for this concrete call.
328 // (This can fail e.g. if `#[rustc_nonnull_optimization_guaranteed]` is used incorrectly.)
329if !caller_abi.eq_abi(callee_abi) {
::core::panicking::panic("assertion failed: caller_abi.eq_abi(callee_abi)")
};assert!(caller_abi.eq_abi(callee_abi));
330interp_ok(true)
331 } else {
332{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs:332",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(332u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_argument_compat: incompatible ABIs:\ncaller: {0:?}\ncallee: {1:?}",
caller_abi, callee_abi) as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!(
333"check_argument_compat: incompatible ABIs:\ncaller: {:?}\ncallee: {:?}",
334 caller_abi, callee_abi
335 );
336interp_ok(false)
337 }
338 }
339340/// Initialize a single callee argument, checking the types for compatibility.
341fn pass_argument<'x, 'y>(
342&mut self,
343 caller_args: &mut impl Iterator<
344 Item = (&'x FnArg<'tcx, M::Provenance>, &'y ArgAbi<'tcx, Ty<'tcx>>),
345 >,
346 callee_args_abis: &mut impl Iterator<Item = (usize, &'y ArgAbi<'tcx, Ty<'tcx>>)>,
347 callee_arg: &mir::Place<'tcx>,
348 callee_ty: Ty<'tcx>,
349 already_live: bool,
350 ) -> InterpResult<'tcx>
351where
352'tcx: 'x,
353'tcx: 'y,
354 {
355// Get next callee arg.
356let (callee_arg_idx, callee_abi) = callee_args_abis.next().unwrap();
357{
match (&callee_ty, &callee_abi.layout.ty) {
(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!(callee_ty, callee_abi.layout.ty);
358// Get next caller arg.
359let Some((caller_arg, caller_abi)) = caller_args.next() else {
360do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("calling a function with fewer arguments than it requires"))
})));throw_ub_format!("calling a function with fewer arguments than it requires");
361 };
362{
match (&caller_arg.layout().layout, &caller_abi.layout.layout) {
(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!(caller_arg.layout().layout, caller_abi.layout.layout);
363// Sadly we cannot assert that `caller_arg.layout().ty` and `caller_abi.layout.ty` are
364 // equal; in closures the types sometimes differ. We just hope that `caller_abi` is the
365 // right type to print to the user.
366367 // Check compatibility
368if !self.check_argument_compat(caller_abi, callee_abi)? {
369do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::AbiMismatchArgument {
arg_idx: callee_arg_idx,
caller_ty: caller_abi.layout.ty,
callee_ty: callee_abi.layout.ty,
});throw_ub!(AbiMismatchArgument {
370 arg_idx: callee_arg_idx,
371 caller_ty: caller_abi.layout.ty,
372 callee_ty: callee_abi.layout.ty
373 });
374 }
375// We work with a copy of the argument for now; if this is in-place argument passing, we
376 // will later protect the source it comes from. This means the callee cannot observe if we
377 // did in-place of by-copy argument passing, except for pointer equality tests.
378let caller_arg_copy = caller_arg.copy_fn_arg();
379if !already_live {
380let local = callee_arg.as_local().unwrap();
381let meta = caller_arg_copy.meta();
382// `check_argument_compat` ensures that if metadata is needed, both have the same type,
383 // so we know they will use the metadata the same way.
384if !(!meta.has_meta() || caller_arg_copy.layout.ty == callee_ty) {
::core::panicking::panic("assertion failed: !meta.has_meta() || caller_arg_copy.layout.ty == callee_ty")
};assert!(!meta.has_meta() || caller_arg_copy.layout.ty == callee_ty);
385386self.storage_live_dyn(local, meta)?;
387 }
388// Now we can finally actually evaluate the callee place.
389let callee_arg =
390self.eval_place(*callee_arg, /* skip_validity_for_simple_deref */ false)?;
391// We allow some transmutes here.
392 // FIXME: Depending on the PassMode, this should reset some padding to uninitialized. (This
393 // is true for all `copy_op`, but there are a lot of special cases for argument passing
394 // specifically.)
395self.copy_op_allow_transmute(&caller_arg_copy, &callee_arg)?;
396// If this was an in-place pass, protect the place it comes from for the duration of the call.
397if let FnArg::InPlace(mplace) = caller_arg {
398 M::protect_in_place_function_argument(self, mplace)?;
399 }
400interp_ok(())
401 }
402403/// The main entry point for creating a new stack frame: performs ABI checks and initializes
404 /// arguments.
405{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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("init_stack_frame",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(405u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("instance")
}> =
::tracing::__macro_support::FieldName::new("instance");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("body")
}> =
::tracing::__macro_support::FieldName::new("body");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("caller_fn_abi")
}> =
::tracing::__macro_support::FieldName::new("caller_fn_abi");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("args")
}> =
::tracing::__macro_support::FieldName::new("args");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("with_caller_location")
}> =
::tracing::__macro_support::FieldName::new("with_caller_location");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("destination")
}> =
::tracing::__macro_support::FieldName::new("destination");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("cont")
}> =
::tracing::__macro_support::FieldName::new("cont");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&body)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&caller_fn_abi)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&with_caller_location
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&destination)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cont)
as &dyn ::tracing::field::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: InterpResult<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let _trace =
<M as
crate::interpret::Machine>::enter_trace_span(||
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("step",
"rustc_const_eval::interpret::call", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(416u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("step")
}> =
::tracing::__macro_support::FieldName::new("step");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("instance")
}> =
::tracing::__macro_support::FieldName::new("instance");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("tracing_separate_thread")
}> =
::tracing::__macro_support::FieldName::new("tracing_separate_thread");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::display(&"init_stack_frame")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::display(&instance)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&Empty as
&dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
});
let def_id = instance.def_id();
let extra_tys =
if caller_fn_abi.c_variadic {
let fixed_count =
usize::try_from(caller_fn_abi.fixed_count).unwrap();
let extra_tys =
args[fixed_count..].iter().map(|arg| arg.layout().ty);
self.tcx.mk_type_list_from_iter(extra_tys)
} else { ty::List::empty() };
let callee_fn_abi =
self.fn_abi_of_instance_no_deduced_attrs(instance,
extra_tys)?;
if caller_fn_abi.conv != callee_fn_abi.conv {
do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("calling a function with calling convention \"{0}\" using calling convention \"{1}\"",
callee_fn_abi.conv, caller_fn_abi.conv))
})))
}
if caller_fn_abi.c_variadic != callee_fn_abi.c_variadic {
do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::CVariadicMismatch {
caller_is_c_variadic: caller_fn_abi.c_variadic,
callee_is_c_variadic: callee_fn_abi.c_variadic,
});
}
if caller_fn_abi.c_variadic &&
caller_fn_abi.fixed_count != callee_fn_abi.fixed_count {
do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::CVariadicFixedCountMismatch {
caller: caller_fn_abi.fixed_count,
callee: callee_fn_abi.fixed_count,
});
}
M::check_fn_target_features(self, instance)?;
if !callee_fn_abi.can_unwind {
match &mut cont {
ReturnContinuation::Stop { .. } => {}
ReturnContinuation::Goto { unwind, .. } => {
*unwind = mir::UnwindAction::Unreachable;
}
}
}
let destination_mplace =
self.place_to_op(destination)?.as_mplace_or_imm().left();
self.push_stack_frame_raw(instance, body, destination, cont)?;
let preamble_span = self.frame().loc.unwrap_right();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs:478",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(478u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("caller ABI: {0:#?}, args: {1:#?}",
caller_fn_abi,
args.iter().map(|arg|
(arg.layout().ty,
match arg {
FnArg::Copy(op) =>
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("copy({0:?})", op))
}),
FnArg::InPlace(mplace) =>
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("in-place({0:?})",
mplace))
}),
})).collect::<Vec<_>>()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs:491",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(491u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("spread_arg: {0:?}, locals: {1:#?}",
body.spread_arg,
body.args_iter().map(|local|
(local,
self.layout_of_local(self.frame(), local,
None).unwrap().ty)).collect::<Vec<_>>()) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};
let va_list_arg =
callee_fn_abi.c_variadic.then(||
mir::Local::from_usize(body.arg_count));
let is_non_capturing_closure =
(#[allow(non_exhaustive_omitted_patterns)] match instance.def
{
ty::InstanceKind::Shim(ty::ShimKind::ClosureOnce { .. }) =>
true,
_ => false,
} || self.tcx.is_closure_like(def_id)) &&
{
let arg = &callee_fn_abi.args[0];
#[allow(non_exhaustive_omitted_patterns)]
match arg.layout.ty.kind() {
ty::Closure(_def, closure_args) if
{ closure_args.as_closure().upvar_tys().is_empty() } =>
true,
_ => false,
}
};
{
match (&(args.len() +
if with_caller_location { 1 } else { 0 }),
&caller_fn_abi.args.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!("mismatch between caller ABI and caller arguments")));
}
}
}
};
let mut caller_args = args.iter().zip(caller_fn_abi.args.iter());
let mut callee_args_abis = callee_fn_abi.args.iter().enumerate();
M::with_retag_mode(self, RetagMode::FnEntry,
|ecx|
{
for local in body.args_iter() {
ecx.frame_mut().loc =
Right(body.local_decls[local].source_info.span);
let dest = mir::Place::from(local);
let ty = ecx.layout_of_local(ecx.frame(), local, None)?.ty;
if is_non_capturing_closure && local == mir::Local::arg(0) {
if !va_list_arg.is_none() {
::core::panicking::panic("assertion failed: va_list_arg.is_none()")
};
if !(Some(local) != body.spread_arg) {
::core::panicking::panic("assertion failed: Some(local) != body.spread_arg")
};
let (callee_arg_idx, callee_abi) =
callee_args_abis.next().unwrap();
if !(callee_abi.layout.is_1zst() && callee_abi.is_ignore())
{
::core::panicking::panic("assertion failed: callee_abi.layout.is_1zst() && callee_abi.is_ignore()")
};
ecx.storage_live(local)?;
if caller_fn_abi.args.len() == callee_fn_abi.args.len() {
let (_caller_arg, caller_abi) = caller_args.next().unwrap();
if !caller_abi.layout.is_1zst() {
do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::AbiMismatchArgument {
arg_idx: callee_arg_idx,
caller_ty: caller_abi.layout.ty,
callee_ty: callee_abi.layout.ty,
});
}
if !caller_abi.is_ignore() {
::core::panicking::panic("assertion failed: caller_abi.is_ignore()")
};
}
} else if Some(local) == va_list_arg {
ecx.storage_live(local)?;
let place = ecx.eval_place(dest, false)?;
let mplace = ecx.force_allocation(&place)?;
let varargs =
M::with_retag_mode(ecx, RetagMode::None,
|ecx|
{
ecx.allocate_varargs(&mut caller_args,
&mut callee_args_abis)
})?;
ecx.frame_mut().va_list = varargs.clone();
let key = ecx.va_list_ptr(varargs.into());
ecx.write_bytes_ptr(mplace.ptr(),
(0..mplace.layout.size.bytes()).map(|_| 0u8))?;
let key_mplace = ecx.va_list_key_field(&mplace)?;
ecx.write_pointer(key, &key_mplace)?;
} else if Some(local) == body.spread_arg {
ecx.storage_live(local)?;
let ty::Tuple(fields) =
ty.kind() else {
::rustc_middle::util::bug::span_bug_fmt(ecx.cur_span(),
format_args!("non-tuple type for `spread_arg`: {0}", ty))
};
for (i, field_ty) in fields.iter().enumerate() {
let dest =
dest.project_deeper(&[mir::ProjectionElem::Field(FieldIdx::from_usize(i),
field_ty)], *ecx.tcx);
ecx.pass_argument(&mut caller_args, &mut callee_args_abis,
&dest, field_ty, true)?;
}
} else {
ecx.pass_argument(&mut caller_args, &mut callee_args_abis,
&dest, ty, false)?;
}
}
interp_ok(())
})?;
self.frame_mut().loc =
Right(body.local_decls[mir::RETURN_PLACE].source_info.span);
if !self.check_argument_compat(&caller_fn_abi.ret,
&callee_fn_abi.ret)? {
do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::AbiMismatchReturn {
caller_ty: caller_fn_abi.ret.layout.ty,
callee_ty: callee_fn_abi.ret.layout.ty,
});
}
if let Some(mplace) = destination_mplace {
M::protect_in_place_function_argument(self, &mplace)?;
}
self.frame_mut().loc = Right(preamble_span);
if instance.def.requires_caller_location(*self.tcx) {
callee_args_abis.next().unwrap();
}
if !callee_args_abis.next().is_none() {
{
::core::panicking::panic_fmt(format_args!("mismatch between callee ABI and callee body arguments"));
}
};
if caller_args.next().is_some() {
do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("calling a function with more arguments than it expected"))
})));
}
self.push_stack_frame_done()
}
}
}#[instrument(skip(self), level = "trace")]406pub fn init_stack_frame(
407&mut self,
408 instance: Instance<'tcx>,
409 body: &'tcx mir::Body<'tcx>,
410 caller_fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
411 args: &[FnArg<'tcx, M::Provenance>],
412 with_caller_location: bool,
413 destination: &PlaceTy<'tcx, M::Provenance>,
414mut cont: ReturnContinuation,
415 ) -> InterpResult<'tcx> {
416let _trace = enter_trace_span!(M, step::init_stack_frame, %instance, tracing_separate_thread = Empty);
417let def_id = instance.def_id();
418419// The first order of business is to figure out the callee signature.
420 // However, that requires the list of variadic arguments.
421 // We use the *caller* information to determine where to split the list of arguments,
422 // and then later check that the callee indeed has the same number of fixed arguments.
423let extra_tys = if caller_fn_abi.c_variadic {
424let fixed_count = usize::try_from(caller_fn_abi.fixed_count).unwrap();
425let extra_tys = args[fixed_count..].iter().map(|arg| arg.layout().ty);
426self.tcx.mk_type_list_from_iter(extra_tys)
427 } else {
428 ty::List::empty()
429 };
430let callee_fn_abi = self.fn_abi_of_instance_no_deduced_attrs(instance, extra_tys)?;
431432if caller_fn_abi.conv != callee_fn_abi.conv {
433throw_ub_format!(
434"calling a function with calling convention \"{callee_conv}\" using calling convention \"{caller_conv}\"",
435 callee_conv = callee_fn_abi.conv,
436 caller_conv = caller_fn_abi.conv,
437 )
438 }
439440if caller_fn_abi.c_variadic != callee_fn_abi.c_variadic {
441throw_ub!(CVariadicMismatch {
442 caller_is_c_variadic: caller_fn_abi.c_variadic,
443 callee_is_c_variadic: callee_fn_abi.c_variadic,
444 });
445 }
446if caller_fn_abi.c_variadic && caller_fn_abi.fixed_count != callee_fn_abi.fixed_count {
447throw_ub!(CVariadicFixedCountMismatch {
448 caller: caller_fn_abi.fixed_count,
449 callee: callee_fn_abi.fixed_count,
450 });
451 }
452453// Check that all target features required by the callee (i.e., from
454 // the attribute `#[target_feature(enable = ...)]`) are enabled at
455 // compile time.
456M::check_fn_target_features(self, instance)?;
457458// If the signature says this cannot unwind, reflect this in the unwind destination so that
459 // we don't have to check this later. (`init_fn_call` already did this for the caller so
460 // here we only have to check the callee.)
461if !callee_fn_abi.can_unwind {
462match &mut cont {
463 ReturnContinuation::Stop { .. } => {}
464 ReturnContinuation::Goto { unwind, .. } => {
465*unwind = mir::UnwindAction::Unreachable;
466 }
467 }
468 }
469470// *Before* pushing the new frame, determine whether the return destination is in memory.
471 // Need to use `place_to_op` to be *sure* we get the mplace if there is one.
472let destination_mplace = self.place_to_op(destination)?.as_mplace_or_imm().left();
473474// Push the "raw" frame -- this leaves locals uninitialized.
475self.push_stack_frame_raw(instance, body, destination, cont)?;
476let preamble_span = self.frame().loc.unwrap_right(); // the span used for preamble errors
477478trace!(
479"caller ABI: {:#?}, args: {:#?}",
480 caller_fn_abi,
481 args.iter()
482 .map(|arg| (
483 arg.layout().ty,
484match arg {
485 FnArg::Copy(op) => format!("copy({op:?})"),
486 FnArg::InPlace(mplace) => format!("in-place({mplace:?})"),
487 }
488 ))
489 .collect::<Vec<_>>()
490 );
491trace!(
492"spread_arg: {:?}, locals: {:#?}",
493 body.spread_arg,
494 body.args_iter()
495 .map(|local| (local, self.layout_of_local(self.frame(), local, None).unwrap().ty))
496 .collect::<Vec<_>>()
497 );
498499// Determine whether there is a special VaList argument. This is always the
500 // last argument, and since arguments start at index 1 that's `arg_count`.
501let va_list_arg = callee_fn_abi.c_variadic.then(|| mir::Local::from_usize(body.arg_count));
502// Determine whether this is a non-capturing closure. That's relevant as their first
503 // argument can be skipped (and that's the only kind of argument skipping we allow).
504let is_non_capturing_closure =
505 (matches!(instance.def, ty::InstanceKind::Shim(ty::ShimKind::ClosureOnce { .. }))
506 || self.tcx.is_closure_like(def_id))
507 && {
508let arg = &callee_fn_abi.args[0];
509matches!(arg.layout.ty.kind(), ty::Closure (_def, closure_args) if {
510 closure_args.as_closure().upvar_tys().is_empty()
511 })
512 };
513514// In principle, we have two iterators: Where the arguments come from, and where
515 // they go to.
516517 // The "where they come from" part is easy, we expect the caller to do any special handling
518 // that might be required here (e.g. for untupling).
519 // If `with_caller_location` is set we pretend there is an extra argument (that
520 // we will not pass; our `caller_location` intrinsic implementation walks the stack instead).
521assert_eq!(
522 args.len() + if with_caller_location { 1 } else { 0 },
523 caller_fn_abi.args.len(),
524"mismatch between caller ABI and caller arguments",
525 );
526let mut caller_args = args.iter().zip(caller_fn_abi.args.iter());
527528// Now we have to spread them out across the callee's locals,
529 // taking into account the `spread_arg`. If we could write
530 // this is a single iterator (that handles `spread_arg`), then
531 // `pass_argument` would be the loop body.
532let mut callee_args_abis = callee_fn_abi.args.iter().enumerate();
533// During argument passing, we want retagging with protectors.
534M::with_retag_mode(self, RetagMode::FnEntry, |ecx| {
535for local in body.args_iter() {
536// Update the span that we show in case of an error to point to this argument.
537ecx.frame_mut().loc = Right(body.local_decls[local].source_info.span);
538// Construct the destination place for this argument. At this point all
539 // locals are still dead, so we cannot construct a `PlaceTy`.
540let dest = mir::Place::from(local);
541// `layout_of_local` does more than just the instantiation we need to get the
542 // type, but the result gets cached so this avoids calling the instantiation
543 // query *again* the next time this local is accessed.
544let ty = ecx.layout_of_local(ecx.frame(), local, None)?.ty;
545546// Some arguments are special: the first (`self`) argument of a non-capturing
547 // closure; the va_list argument; and the spread_arg.
548if is_non_capturing_closure && local == mir::Local::arg(0) {
549assert!(va_list_arg.is_none());
550assert!(Some(local) != body.spread_arg);
551// This argument might be missing on the caller side. So just initialize it in
552 // the callee.
553let (callee_arg_idx, callee_abi) = callee_args_abis.next().unwrap();
554assert!(callee_abi.layout.is_1zst() && callee_abi.is_ignore());
555 ecx.storage_live(local)?;
556// And skip it in the caller, if present. We can tell whether it is present by
557 // comparing the number of arguments on the caller and callee side.
558if caller_fn_abi.args.len() == callee_fn_abi.args.len() {
559let (_caller_arg, caller_abi) = caller_args.next().unwrap();
560if !caller_abi.layout.is_1zst() {
561// The caller gave us some other, non-ignorable argument.
562throw_ub!(AbiMismatchArgument {
563 arg_idx: callee_arg_idx,
564 caller_ty: caller_abi.layout.ty,
565 callee_ty: callee_abi.layout.ty
566 });
567 }
568assert!(caller_abi.is_ignore());
569 }
570 } else if Some(local) == va_list_arg {
571// This is the last callee-side argument of a variadic function.
572 // This argument is a VaList holding the remaining caller-side arguments.
573ecx.storage_live(local)?;
574575let place =
576 ecx.eval_place(dest, /* skip_validity_for_simple_deref */ false)?;
577let mplace = ecx.force_allocation(&place)?;
578579// Consume the remaining arguments by putting them into the variable argument
580 // list. We disable retagging to avoid creating protected tags. Protection should
581 // only use callee-side information, and the varargs have no static callee-side type.
582let varargs = M::with_retag_mode(ecx, RetagMode::None, |ecx| {
583 ecx.allocate_varargs(&mut caller_args, &mut callee_args_abis)
584 })?;
585586// When the frame is dropped, these variable arguments are deallocated.
587ecx.frame_mut().va_list = varargs.clone();
588let key = ecx.va_list_ptr(varargs.into());
589590// Zero the VaList, so it is fully initialized.
591ecx.write_bytes_ptr(
592 mplace.ptr(),
593 (0..mplace.layout.size.bytes()).map(|_| 0u8),
594 )?;
595596// Store the "key" pointer in the right field.
597let key_mplace = ecx.va_list_key_field(&mplace)?;
598 ecx.write_pointer(key, &key_mplace)?;
599 } else if Some(local) == body.spread_arg {
600// Make the local live once, then fill in the value field by field.
601ecx.storage_live(local)?;
602// Must be a tuple
603let ty::Tuple(fields) = ty.kind() else {
604span_bug!(ecx.cur_span(), "non-tuple type for `spread_arg`: {ty}")
605 };
606for (i, field_ty) in fields.iter().enumerate() {
607let dest = dest.project_deeper(
608&[mir::ProjectionElem::Field(FieldIdx::from_usize(i), field_ty)],
609*ecx.tcx,
610 );
611 ecx.pass_argument(
612&mut caller_args,
613&mut callee_args_abis,
614&dest,
615 field_ty,
616/* already_live */ true,
617 )?;
618 }
619 } else {
620// Normal argument. Cannot mark it as live yet, it might be unsized!
621ecx.pass_argument(
622&mut caller_args,
623&mut callee_args_abis,
624&dest,
625 ty,
626/* already_live */ false,
627 )?;
628 }
629 }
630 interp_ok(())
631 })?;
632633// Don't forget to check the return type!
634self.frame_mut().loc = Right(body.local_decls[mir::RETURN_PLACE].source_info.span);
635if !self.check_argument_compat(&caller_fn_abi.ret, &callee_fn_abi.ret)? {
636throw_ub!(AbiMismatchReturn {
637 caller_ty: caller_fn_abi.ret.layout.ty,
638 callee_ty: callee_fn_abi.ret.layout.ty
639 });
640 }
641// Protect return place for in-place return value passing.
642 // We only need to protect anything if this is actually an in-memory place.
643if let Some(mplace) = destination_mplace {
644 M::protect_in_place_function_argument(self, &mplace)?;
645 }
646647// For the final checks, use same span as preamble since it is unclear what else to do.
648self.frame_mut().loc = Right(preamble_span);
649// If the callee needs a caller location, pretend we consume one more argument from the ABI.
650if instance.def.requires_caller_location(*self.tcx) {
651 callee_args_abis.next().unwrap();
652 }
653// Now we should have no more caller args or callee arg ABIs.
654assert!(
655 callee_args_abis.next().is_none(),
656"mismatch between callee ABI and callee body arguments"
657);
658if caller_args.next().is_some() {
659throw_ub_format!("calling a function with more arguments than it expected");
660 }
661662// Done!
663self.push_stack_frame_done()
664 }
665666/// Initiate a call to this function -- pushing the stack frame and initializing the arguments.
667 ///
668 /// `caller_fn_abi` is used to determine if all the arguments are passed the proper way.
669 /// However, we also need `caller_abi` to determine if we need to do untupling of arguments.
670 ///
671 /// `with_caller_location` indicates whether the caller passed a caller location. Miri
672 /// implements caller locations without argument passing, but to match `FnAbi` we need to know
673 /// when those arguments are present.
674pub(super) fn init_fn_call(
675&mut self,
676 fn_val: FnVal<'tcx, M::ExtraFnVal>,
677 (caller_abi, caller_fn_abi): (ExternAbi, Option<&FnAbi<'tcx, Ty<'tcx>>>),
678 args: &[FnArg<'tcx, M::Provenance>],
679 with_caller_location: bool,
680 destination: &PlaceTy<'tcx, M::Provenance>,
681 target: Option<mir::BasicBlock>,
682mut unwind: mir::UnwindAction,
683 ) -> InterpResult<'tcx> {
684let _trace =
685<M as
crate::interpret::Machine>::enter_trace_span(||
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("step",
"rustc_const_eval::interpret::call", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(685u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("step")
}> =
::tracing::__macro_support::FieldName::new("step");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("tracing_separate_thread")
}> =
::tracing::__macro_support::FieldName::new("tracing_separate_thread");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("fn_val")
}> =
::tracing::__macro_support::FieldName::new("fn_val");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::display(&"init_fn_call")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&Empty as
&dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_val)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
})enter_trace_span!(M, step::init_fn_call, tracing_separate_thread = Empty, ?fn_val)686 .or_if_tracing_disabled(|| {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs:686",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(686u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("init_fn_call: {0:#?}",
fn_val) as &dyn ::tracing::field::Value))])
});
} else { ; }
}trace!("init_fn_call: {:#?}", fn_val));
687688// If the signature says this cannot unwind, reflect this in the unwind destination
689 // so that we don't have to check this later.
690if caller_fn_abi.is_some_and(|abi| !abi.can_unwind) {
691unwind = mir::UnwindAction::Unreachable;
692 }
693694let instance = match fn_val {
695 FnVal::Instance(instance) => instance,
696 FnVal::Other(extra) => {
697let caller_fn_abi =
698caller_fn_abi.expect("FnAbi should have been computed for this call");
699return M::call_extra_fn(
700self,
701extra,
702caller_fn_abi,
703args,
704destination,
705target,
706unwind,
707 );
708 }
709 };
710711match instance.def {
712 ty::InstanceKind::Intrinsic(def_id) => {
713if !self.tcx.intrinsic(def_id).is_some() {
::core::panicking::panic("assertion failed: self.tcx.intrinsic(def_id).is_some()")
};assert!(self.tcx.intrinsic(def_id).is_some());
714// FIXME: Should `InPlace` arguments be reset to uninit?
715if let Some(fallback) = M::call_intrinsic(
716self,
717 instance,
718&Self::copy_fn_args(args),
719 destination,
720 target,
721 unwind,
722 )? {
723if !!self.tcx.intrinsic(fallback.def_id()).unwrap().must_be_overridden {
::core::panicking::panic("assertion failed: !self.tcx.intrinsic(fallback.def_id()).unwrap().must_be_overridden")
};assert!(!self.tcx.intrinsic(fallback.def_id()).unwrap().must_be_overridden);
724{
match fallback.def {
ty::InstanceKind::Item(_) => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"ty::InstanceKind::Item(_)", ::core::option::Option::None);
}
}
};assert_matches!(fallback.def, ty::InstanceKind::Item(_));
725return self.init_fn_call(
726 FnVal::Instance(fallback),
727 (caller_abi, caller_fn_abi),
728args,
729with_caller_location,
730destination,
731target,
732unwind,
733 );
734 } else {
735interp_ok(())
736 }
737 }
738 ty::InstanceKind::LlvmIntrinsic(_) => {
739// FIXME: Should `InPlace` arguments be reset to uninit?
740M::call_llvm_intrinsic(
741self,
742instance,
743&Self::copy_fn_args(args),
744destination,
745target,
746 )
747 }
748 ty::InstanceKind::Shim(ty::ShimKind::VTable(..))
749 | ty::InstanceKind::Shim(ty::ShimKind::Reify(..))
750 | ty::InstanceKind::Shim(ty::ShimKind::ClosureOnce { .. })
751 | ty::InstanceKind::Shim(ty::ShimKind::ConstructCoroutineInClosure { .. })
752 | ty::InstanceKind::Shim(ty::ShimKind::FnPtr(..))
753 | ty::InstanceKind::Shim(ty::ShimKind::DropGlue(..))
754 | ty::InstanceKind::Shim(ty::ShimKind::Clone(..))
755 | ty::InstanceKind::Shim(ty::ShimKind::FnPtrAsPtr(..))
756 | ty::InstanceKind::Shim(ty::ShimKind::FnPtrFromPtr(..))
757 | ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(..))
758 | ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlueCtor(..))
759 | ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlue(..))
760 | ty::InstanceKind::Shim(ty::ShimKind::FutureDropPoll(..))
761 | ty::InstanceKind::Item(_) => {
762// We need MIR for this fn.
763 // Note that this can be an intrinsic, if we are executing its fallback body.
764let caller_fn_abi =
765caller_fn_abi.expect("FnAbi should have been computed for this call");
766let Some((body, instance)) = M::find_mir_or_eval_fn(
767self,
768 instance,
769 caller_fn_abi,
770 args,
771 destination,
772 target,
773 unwind,
774 )?
775else {
776return interp_ok(());
777 };
778779// Special handling for the closure ABI: untuple the last argument.
780 // FIXME(splat): un-tuple splatted arguments that were tupled in typecheck
781let args: Cow<'_, [FnArg<'tcx, M::Provenance>]> =
782if caller_abi == ExternAbi::RustCall && !args.is_empty() {
783// Untuple
784let (untuple_arg, args) = args.split_last().unwrap();
785let ty::Tuple(untuple_fields) = untuple_arg.layout().ty.kind() else {
786::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
format_args!("untuple argument must be a tuple"))span_bug!(self.cur_span(), "untuple argument must be a tuple")787 };
788{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs:788",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(788u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("init_fn_call: Will pass last argument by untupling")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("init_fn_call: Will pass last argument by untupling");
789Cow::from(
790 args.iter()
791// The regular arguments.
792.map(|a| interp_ok(a.clone()))
793// The fields of the untupled argument.
794.chain((0..untuple_fields.len()).map(|i| {
795self.fn_arg_project_field(untuple_arg, FieldIdx::from_usize(i))
796 }))
797 .collect::<InterpResult<'_, Vec<_>>>()?,
798 )
799 } else {
800// Plain arg passing
801Cow::from(args)
802 };
803804self.init_stack_frame(
805instance,
806body,
807caller_fn_abi,
808&args,
809with_caller_location,
810destination,
811 ReturnContinuation::Goto { ret: target, unwind },
812 )
813 }
814// `InstanceKind::Virtual` does not have callable MIR. Calls to `Virtual` instances must be
815 // codegen'd / interpreted as virtual calls through the vtable.
816ty::InstanceKind::Virtual(def_id, idx) => {
817let caller_fn_abi =
818caller_fn_abi.expect("FnAbi should have been computed for this call");
819let mut args = args.to_vec();
820// We have to implement all "dyn-compatible receivers". So we have to go search for a
821 // pointer or `dyn Trait` type, but it could be wrapped in newtypes. So recursively
822 // unwrap those newtypes until we are there.
823 // An `InPlace` does nothing here, we keep the original receiver intact. We can't
824 // really pass the argument in-place anyway, and we are constructing a new
825 // `Immediate` receiver.
826let mut receiver = args[0].copy_fn_arg();
827let receiver_place = loop {
828match receiver.layout.ty.kind() {
829 ty::Ref(..) | ty::RawPtr(..) => {
830// We do *not* use `deref_pointer` here: we don't want to conceptually
831 // create a place that must be dereferenceable, since the receiver might
832 // be a raw pointer and (for `*const dyn Trait`) we don't need to
833 // actually access memory to resolve this method.
834 // Also see <https://github.com/rust-lang/miri/issues/2786>.
835let val = self.read_immediate(&receiver)?;
836break self.imm_ptr_to_mplace(&val)?;
837 }
838 ty::Dynamic(..) => break receiver.assert_mem_place(), // no immediate unsized values
839_ => {
840// Not there yet, search for the only non-ZST field.
841 // (The rules for `DispatchFromDyn` ensure there's exactly one such field.)
842let (idx, _) = receiver.layout.non_1zst_field(self).expect(
843"not exactly one non-1-ZST field in a `DispatchFromDyn` type",
844 );
845receiver = self.project_field(&receiver, idx)?;
846 }
847 }
848 };
849850// Obtain the underlying trait we are working on, and the adjusted receiver argument.
851 // Doesn't have to be a `dyn Trait`, but the unsized tail must be `dyn Trait`.
852 // (For that reason we also cannot use `unpack_dyn_trait`.)
853let receiver_tail =
854self.tcx.struct_tail_for_codegen(receiver_place.layout.ty, self.typing_env);
855let ty::Dynamic(receiver_trait, _) = receiver_tail.kind() else {
856::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
format_args!("dynamic call on non-`dyn` type {0}", receiver_tail))span_bug!(self.cur_span(), "dynamic call on non-`dyn` type {}", receiver_tail)857 };
858if !receiver_place.layout.is_unsized() {
::core::panicking::panic("assertion failed: receiver_place.layout.is_unsized()")
};assert!(receiver_place.layout.is_unsized());
859860// Get the required information from the vtable.
861let vptr = receiver_place.meta().unwrap_meta().to_pointer(self);
862let dyn_ty = self.get_ptr_vtable_ty(vptr, Some(receiver_trait))?;
863let adjusted_recv = receiver_place.ptr();
864865// Now determine the actual method to call. Usually we use the easy way of just
866 // looking up the method at index `idx`.
867let vtable_entries = self.vtable_entries(receiver_trait.principal(), dyn_ty);
868let Some(ty::VtblEntry::Method(fn_inst)) = vtable_entries.get(idx).copied() else {
869// FIXME(fee1-dead) these could be variants of the UB info enum instead of this
870do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`dyn` call trying to call something that is not a method"))
})));throw_ub_format!("`dyn` call trying to call something that is not a method");
871 };
872{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs:872",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(872u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Virtual call dispatches to {0:#?}",
fn_inst) as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("Virtual call dispatches to {fn_inst:#?}");
873// We can also do the lookup based on `def_id` and `dyn_ty`, and check that that
874 // produces the same result.
875self.assert_virtual_instance_matches_concrete(dyn_ty, def_id, instance, fn_inst);
876877// Adjust receiver argument. Layout can be any (thin) ptr.
878let receiver_ty = Ty::new_mut_ptr(self.tcx.tcx, dyn_ty);
879args[0] = FnArg::Copy(
880ImmTy::from_immediate(
881Scalar::from_maybe_pointer(adjusted_recv, self).into(),
882self.layout_of(receiver_ty)?,
883 )
884 .into(),
885 );
886{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs:886",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(886u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Patched receiver operand to {0:#?}",
args[0]) as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("Patched receiver operand to {:#?}", args[0]);
887// Need to also adjust the type in the ABI. Strangely, the layout there is actually
888 // already fine! Just the type is bogus. This is due to what `force_thin_self_ptr`
889 // does in `fn_abi_new_uncached`; supposedly, codegen relies on having the bogus
890 // type, so we just patch this up locally.
891let mut caller_fn_abi = caller_fn_abi.clone();
892caller_fn_abi.args[0].layout.ty = receiver_ty;
893894// recurse with concrete function
895self.init_fn_call(
896 FnVal::Instance(fn_inst),
897 (caller_abi, Some(&caller_fn_abi)),
898&args,
899with_caller_location,
900destination,
901target,
902unwind,
903 )
904 }
905 }
906 }
907908fn assert_virtual_instance_matches_concrete(
909&self,
910 dyn_ty: Ty<'tcx>,
911 def_id: DefId,
912 virtual_instance: ty::Instance<'tcx>,
913 concrete_instance: ty::Instance<'tcx>,
914 ) {
915let tcx = *self.tcx;
916917let trait_def_id = tcx.parent(def_id);
918let virtual_trait_ref = ty::TraitRef::from_assoc(tcx, trait_def_id, virtual_instance.args);
919let existential_trait_ref = ty::ExistentialTraitRef::erase_self_ty(tcx, virtual_trait_ref);
920let concrete_trait_ref = existential_trait_ref.with_self_ty(tcx, dyn_ty);
921922let concrete_method = {
923let _trace = <M as
crate::interpret::Machine>::enter_trace_span(||
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("resolve",
"rustc_const_eval::interpret::call", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(923u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("resolve")
}> =
::tracing::__macro_support::FieldName::new("resolve");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::display(&"expect_resolve_for_vtable")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
})enter_trace_span!(M, resolve::expect_resolve_for_vtable, ?def_id);
924Instance::expect_resolve_for_vtable(
925tcx,
926self.typing_env,
927def_id,
928virtual_instance.args.rebase_onto(tcx, trait_def_id, concrete_trait_ref.args),
929self.cur_span(),
930 )
931 };
932{
match (&concrete_instance, &concrete_method) {
(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!(concrete_instance, concrete_method);
933 }
934935/// Initiate a tail call to this function -- popping the current stack frame, pushing the new
936 /// stack frame and initializing the arguments.
937pub(super) fn init_fn_tail_call(
938&mut self,
939 fn_val: FnVal<'tcx, M::ExtraFnVal>,
940 (caller_abi, caller_fn_abi): (ExternAbi, Option<&FnAbi<'tcx, Ty<'tcx>>>),
941 args: &[FnArg<'tcx, M::Provenance>],
942 with_caller_location: bool,
943 ) -> InterpResult<'tcx> {
944{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs:944",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(944u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("init_fn_tail_call: {0:#?}",
fn_val) as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("init_fn_tail_call: {:#?}", fn_val);
945// This is the "canonical" implementation of tails calls,
946 // a pop of the current stack frame, followed by a normal call
947 // which pushes a new stack frame, with the return address from
948 // the popped stack frame.
949 //
950 // Note that we cannot use `return_from_current_stack_frame`,
951 // as that "executes" the goto to the return block, but we don't want to,
952 // only the tail called function should return to the current return block.
953954 // The arguments need to all be copied since the current stack frame will be removed
955 // before the callee even starts executing.
956 // FIXME(explicit_tail_calls,#144855): does this match what codegen does?
957let args = args.iter().map(|fn_arg| FnArg::Copy(fn_arg.copy_fn_arg())).collect::<Vec<_>>();
958// Remove the frame from the stack.
959let frame = self.pop_stack_frame_raw()?;
960// Remember where this frame would have returned to.
961let ReturnContinuation::Goto { ret, unwind } = frame.return_cont() else {
962::rustc_middle::util::bug::bug_fmt(format_args!("can\'t tailcall as root of the stack"));bug!("can't tailcall as root of the stack");
963 };
964// There's no return value to deal with! Instead, we forward the old return place
965 // to the new function.
966 // FIXME(explicit_tail_calls):
967 // we should check if both caller&callee can/n't unwind,
968 // see <https://github.com/rust-lang/rust/pull/113128#issuecomment-1614979803>
969970 // Now push the new stack frame.
971self.init_fn_call(
972 fn_val,
973 (caller_abi, caller_fn_abi),
974&*args,
975 with_caller_location,
976 frame.return_place(),
977 ret,
978 unwind,
979 )?;
980981// Finally, clear the local variables. Has to be done after pushing to support
982 // non-scalar arguments.
983 // FIXME(explicit_tail_calls,#144855): revisit this once codegen supports indirect
984 // arguments, to ensure the semantics are compatible.
985let return_action = self.cleanup_stack_frame(/* unwinding */ false, frame)?;
986{
match (&return_action, &ReturnAction::Normal) {
(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!(return_action, ReturnAction::Normal);
987988interp_ok(())
989 }
990991pub(super) fn init_drop_in_place_call(
992&mut self,
993 place: &PlaceTy<'tcx, M::Provenance>,
994 instance: ty::Instance<'tcx>,
995 target: mir::BasicBlock,
996 unwind: mir::UnwindAction,
997 ) -> InterpResult<'tcx> {
998{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs:998",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(998u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("init_drop_in_place_call: {0:?},\n instance={1:?}",
place, instance) as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("init_drop_in_place_call: {:?},\n instance={:?}", place, instance);
999// We take the address of the object. This may well be unaligned, which is fine
1000 // for us here. However, unaligned accesses will probably make the actual drop
1001 // implementation fail -- a problem shared by rustc.
1002let place = self.force_allocation(place)?;
10031004// We behave a bit different from codegen here.
1005 // Codegen creates an `InstanceKind::Virtual` with index 0 (the slot of the drop method) and
1006 // then dispatches that to the normal call machinery. However, our call machinery currently
1007 // only supports calling `VtblEntry::Method`; it would choke on a `MetadataDropInPlace`. So
1008 // instead we do the virtual call stuff ourselves. It's easier here than in `eval_fn_call`
1009 // since we can just get a place of the underlying type and use `mplace_to_imm_ptr`.
1010let place = match place.layout.ty.kind() {
1011 ty::Dynamic(data, _) => {
1012// Dropping a trait object. Need to find actual drop fn.
1013self.unpack_dyn_trait(&place, data)?
1014}
1015_ => {
1016if true {
{
match (&instance,
&ty::Instance::resolve_drop_glue(*self.tcx, place.layout.ty))
{
(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);
}
}
}
};
};debug_assert_eq!(
1017 instance,
1018 ty::Instance::resolve_drop_glue(*self.tcx, place.layout.ty)
1019 );
1020place1021 }
1022 };
10231024let instance = {
1025let _trace = <M as
crate::interpret::Machine>::enter_trace_span(||
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("resolve",
"rustc_const_eval::interpret::call", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(1025u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("resolve")
}> =
::tracing::__macro_support::FieldName::new("resolve");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ty")
}> =
::tracing::__macro_support::FieldName::new("ty");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::display(&"resolve_drop_glue")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place.layout.ty)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
})enter_trace_span!(M, resolve::resolve_drop_glue, ty = ?place.layout.ty);
1026 ty::Instance::resolve_drop_glue(*self.tcx, place.layout.ty)
1027 };
1028let fn_abi = self.fn_abi_of_instance_no_deduced_attrs(instance, ty::List::empty())?;
10291030let ref_ty = Ty::new_mut_ref(self.tcx.tcx, self.tcx.lifetimes.re_erased, place.layout.ty);
1031let arg = self.mplace_to_imm_ptr(&place, Some(ref_ty))?;
10321033let ret = MPlaceTy::fake_alloc_zst(self.layout_of(self.tcx.types.unit)?);
10341035self.init_fn_call(
1036 FnVal::Instance(instance),
1037 (ExternAbi::Rust, Some(fn_abi)),
1038&[FnArg::Copy(arg.into())],
1039false,
1040&ret.into(),
1041Some(target),
1042unwind,
1043 )
1044 }
10451046/// Pops the current frame from the stack, copies the return value to the caller, deallocates
1047 /// the memory for allocated locals, and jumps to an appropriate place.
1048 ///
1049 /// If `unwinding` is `false`, then we are performing a normal return
1050 /// from a function. In this case, we jump back into the frame of the caller,
1051 /// and continue execution as normal.
1052 ///
1053 /// If `unwinding` is `true`, then we are in the middle of a panic,
1054 /// and need to unwind this frame. In this case, we jump to the
1055 /// `cleanup` block for the function, which is responsible for running
1056 /// `Drop` impls for any locals that have been initialized at this point.
1057 /// The cleanup block ends with a special `Resume` terminator, which will
1058 /// cause us to continue unwinding.
1059{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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("return_from_current_stack_frame",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(1059u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("unwinding")
}> =
::tracing::__macro_support::FieldName::new("unwinding");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&unwinding
as &dyn ::tracing::field::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: InterpResult<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs:1064",
"rustc_const_eval::interpret::call", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(1064u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("popping stack frame ({0})",
if unwinding {
"during unwinding"
} else { "returning from function" }) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};
{
match (&unwinding,
&match self.frame().loc {
Left(loc) => self.body().basic_blocks[loc.block].is_cleanup,
Right(_) => true,
}) {
(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);
}
}
}
};
if unwinding && self.frame_idx() == 0 {
do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unwinding past the topmost frame of the stack"))
})));
}
let return_op =
self.local_to_op(mir::RETURN_PLACE,
None).expect("return place should always be live");
let frame = self.pop_stack_frame_raw()?;
if !unwinding {
self.copy_op_allow_transmute(&return_op,
frame.return_place())?;
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs:1090",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(1090u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::call"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("return value: {0:?}",
self.dump_place(frame.return_place())) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};
}
let return_cont = frame.return_cont();
let return_action = self.cleanup_stack_frame(unwinding, frame)?;
match return_action {
ReturnAction::Normal => {}
ReturnAction::NoJump => { return interp_ok(()); }
ReturnAction::NoCleanup => {
if !self.stack().is_empty() {
{
::core::panicking::panic_fmt(format_args!("only the topmost frame should ever be leaked"));
}
};
if !!unwinding {
{
::core::panicking::panic_fmt(format_args!("tried to skip cleanup during unwinding"));
}
};
return interp_ok(());
}
}
if unwinding {
match return_cont {
ReturnContinuation::Goto { unwind, .. } => {
self.unwind_to_block(unwind)
}
ReturnContinuation::Stop { .. } => {
{
::core::panicking::panic_fmt(format_args!("encountered ReturnContinuation::Stop when unwinding!"));
}
}
}
} else {
match return_cont {
ReturnContinuation::Goto { ret, .. } =>
self.return_to_block(ret),
ReturnContinuation::Stop { .. } => {
if !self.stack().is_empty() {
{
::core::panicking::panic_fmt(format_args!("only the bottommost frame can have ReturnContinuation::Stop"));
}
};
interp_ok(())
}
}
}
}
}
}#[instrument(skip(self), level = "trace")]1060pub(super) fn return_from_current_stack_frame(
1061&mut self,
1062 unwinding: bool,
1063 ) -> InterpResult<'tcx> {
1064info!(
1065"popping stack frame ({})",
1066if unwinding { "during unwinding" } else { "returning from function" }
1067 );
10681069// Check `unwinding`.
1070assert_eq!(
1071 unwinding,
1072match self.frame().loc {
1073 Left(loc) => self.body().basic_blocks[loc.block].is_cleanup,
1074 Right(_) => true,
1075 }
1076 );
1077if unwinding && self.frame_idx() == 0 {
1078throw_ub_format!("unwinding past the topmost frame of the stack");
1079 }
10801081// Get out the return value. Must happen *before* the frame is popped as we have to get the
1082 // local's value out.
1083let return_op =
1084self.local_to_op(mir::RETURN_PLACE, None).expect("return place should always be live");
1085// Remove the frame from the stack.
1086let frame = self.pop_stack_frame_raw()?;
1087// Copy the return value and remember the return continuation.
1088if !unwinding {
1089self.copy_op_allow_transmute(&return_op, frame.return_place())?;
1090trace!("return value: {:?}", self.dump_place(frame.return_place()));
1091 }
1092let return_cont = frame.return_cont();
1093// Finish popping the stack frame.
1094let return_action = self.cleanup_stack_frame(unwinding, frame)?;
1095// Jump to the next block.
1096match return_action {
1097 ReturnAction::Normal => {}
1098 ReturnAction::NoJump => {
1099// The hook already did everything.
1100return interp_ok(());
1101 }
1102 ReturnAction::NoCleanup => {
1103// If we are not doing cleanup, also skip everything else.
1104assert!(self.stack().is_empty(), "only the topmost frame should ever be leaked");
1105assert!(!unwinding, "tried to skip cleanup during unwinding");
1106// Don't jump anywhere.
1107return interp_ok(());
1108 }
1109 }
11101111// Normal return, figure out where to jump.
1112if unwinding {
1113// Follow the unwind edge.
1114match return_cont {
1115 ReturnContinuation::Goto { unwind, .. } => {
1116// This must be the very last thing that happens, since it can in fact push a new stack frame.
1117self.unwind_to_block(unwind)
1118 }
1119 ReturnContinuation::Stop { .. } => {
1120panic!("encountered ReturnContinuation::Stop when unwinding!")
1121 }
1122 }
1123 } else {
1124// Follow the normal return edge.
1125match return_cont {
1126 ReturnContinuation::Goto { ret, .. } => self.return_to_block(ret),
1127 ReturnContinuation::Stop { .. } => {
1128assert!(
1129self.stack().is_empty(),
1130"only the bottommost frame can have ReturnContinuation::Stop"
1131);
1132 interp_ok(())
1133 }
1134 }
1135 }
1136 }
1137}