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_attr_ir::find_attr;
10use rustc_hir::def_id::DefId;
11use rustc_middle::mir;
12use rustc_middle::ty::layout::{IntegerExt, TyAndLayout};
13use rustc_middle::ty::{self, AdtDef, FieldDef, Instance, Ty, VariantDef};
14use rustc_span::{bug, span_bug};
15use rustc_target::callconv::{ArgAbi, FnAbi};
16use tracing::field::Empty;
17use tracing::{info, instrument, trace};
1819use super::{
20CtfeProvenance, EnteredTraceSpan, FnVal, ImmTy, InterpCx, InterpResult, MPlaceTy, Machine,
21OpTy, PlaceTy, Projectable, Provenance, RetagMode, ReturnAction, ReturnContinuation, Scalar,
22interp_ok, throw_ub, throw_ub_format,
23};
24use crate::enter_trace_span;
2526/// An argument passed to a function.
27#[derive(#[automatically_derived]impl<'tcx, Prov: ::core::clone::Clone + Provenance>
::core::clone::Clone for FnArg<'tcx, Prov> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
match self {
Self::Copy(__self_0) =>
FnArg::Copy(::core::clone::Clone::clone(__self_0)),
Self::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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Copy(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Copy",
&__self_0),
Self::InPlace(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"InPlace", &__self_0),
}
}
}Debug)]
28pub enum FnArg<'tcx, Prov: Provenance = CtfeProvenance> {
29/// Pass a copy of the given operand.
30Copy(OpTy<'tcx, Prov>),
31/// Allow for the argument to be passed in-place: destroy the value originally stored at that
32 /// place and make the place inaccessible for the duration of the function call. This *must* be
33 /// an in-memory place so that we can do the proper alias checks.
34InPlace(MPlaceTy<'tcx, Prov>),
35}
3637impl<'tcx, Prov: Provenance> FnArg<'tcx, Prov> {
38pub fn layout(&self) -> &TyAndLayout<'tcx> {
39match self {
40 FnArg::Copy(op) => &op.layout,
41 FnArg::InPlace(mplace) => &mplace.layout,
42 }
43 }
4445/// Make a copy of the given fn_arg. Any `InPlace` are degenerated to copies, no protection of the
46 /// original memory occurs.
47pub fn copy_fn_arg(&self) -> OpTy<'tcx, Prov> {
48match self {
49 FnArg::Copy(op) => op.clone(),
50 FnArg::InPlace(mplace) => mplace.clone().into(),
51 }
52 }
53}
5455impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
56/// Make a copy of the given fn_args. Any `InPlace` are degenerated to copies, no protection of the
57 /// original memory occurs.
58pub fn copy_fn_args(args: &[FnArg<'tcx, M::Provenance>]) -> Vec<OpTy<'tcx, M::Provenance>> {
59args.iter().map(|fn_arg| fn_arg.copy_fn_arg()).collect()
60 }
6162/// Helper function for argument untupling.
63fn fn_arg_project_field(
64&self,
65 arg: &FnArg<'tcx, M::Provenance>,
66 field: FieldIdx,
67 ) -> InterpResult<'tcx, FnArg<'tcx, M::Provenance>> {
68interp_ok(match arg {
69 FnArg::Copy(op) => FnArg::Copy(self.project_field(op, field)?),
70 FnArg::InPlace(mplace) => FnArg::InPlace(self.project_field(mplace, field)?),
71 })
72 }
7374/// Returns whether the given type has trivial ABI.
75fn has_trivial_abi(&self, layout: TyAndLayout<'tcx>) -> InterpResult<'tcx, bool> {
76if !layout.is_1zst() {
77return interp_ok(false);
78 }
79match *layout.ty.kind() {
80// Trivially trivial-ABI types (because Rust makes no promises about their ABI).
81ty::Tuple(..)
82 | ty::Never83 | ty::FnDef(..)
84 | ty::Closure(..)
85 | ty::Coroutine(..)
86 | ty::CoroutineClosure(..) => interp_ok(true),
8788 ty::Array(elem, _len) => {
89// 0-length arrays are in general *not* okay, but arrays of trivial-ABI types are.
90self.has_trivial_abi(self.layout_of(elem)?)
91 }
92 ty::Adt(adt_def, _args) => {
93if adt_def.repr().transparent() {
94// All fields must have trivial ABI.
95(0..layout.fields.count()).try_fold(true, |acc, idx| {
96interp_ok(acc && self.has_trivial_abi(layout.field(self, idx))?)
97 })
98 } else if adt_def.repr().c() {
99interp_ok(false)
100 } else {
101// Can't be SIMD or Scalable (since this is a 1-ZST); only Rust is left.
102if !adt_def.repr().rust() {
::core::panicking::panic("assertion failed: adt_def.repr().rust()")
};assert!(adt_def.repr().rust());
103interp_ok(true)
104 }
105 }
106// Types that are considered transparent in `unfold_transparent` should also act
107 // like transparent types here.
108ty::Pat(base, _) => self.has_trivial_abi(self.layout_of(base)?),
109 ty::UnsafeBinder(bound_ty) => {
110let ty = self.tcx.instantiate_bound_regions_with_erased(bound_ty.into());
111self.has_trivial_abi(self.layout_of(ty)?)
112 }
113114 ty::Alias(..) => { ::core::panicking::panic_fmt(format_args!("non-normalized type")); }panic!("non-normalized type"),
115_ => interp_ok(false),
116 }
117 }
118119/// Find the wrapped inner type of a transparent wrapper by going for the unique
120 /// non-trivial-ABI field.
121 ///
122 /// We work with `TyAndLayout` here since that makes it much easier to iterate over all fields.
123fn unfold_transparent(
124&self,
125 layout: TyAndLayout<'tcx>,
126 may_unfold: impl Fn(AdtDef<'tcx>) -> bool,
127 ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
128match *layout.ty.kind() {
129 ty::Adt(adt_def, _) if adt_def.repr().transparent() && may_unfold(adt_def) => {
130{
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 { .. });
131// Look for non-trivial-ABI field(s).
132let mut found = None;
133for idx in 0..layout.fields.count() {
134let field = layout.field(self, idx);
135if self.has_trivial_abi(field)? {
136continue;
137 }
138// Found a non-trivial ABI field!
139if found.is_some() {
140// There is more than one such field.
141 // FIXME: we should just panic here. But currently such repr(transparent)
142 // types are still accepted. We just don't treat them as transparent.
143return interp_ok(layout);
144 }
145 found = Some(field);
146 }
147let Some(field) = foundelse {
148// All fields have trivial ABI. That means this type is effectively `()`.
149return interp_ok(self.layout_of(self.tcx.types.unit)?);
150 };
151// Recurse.
152self.unfold_transparent(field, may_unfold)
153 }
154 ty::Pat(base, _) => self.unfold_transparent(self.layout_of(base)?, may_unfold),
155 ty::UnsafeBinder(bound_ty) => {
156let ty = self.tcx.instantiate_bound_regions_with_erased(bound_ty.into());
157self.unfold_transparent(self.layout_of(ty)?, may_unfold)
158 }
159// Not a transparent type, no further unfolding.
160_ => interp_ok(layout),
161 }
162 }
163164/// Unwrap types that are guaranteed a null-pointer-optimization
165fn unfold_npo(&self, layout: TyAndLayout<'tcx>) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
166// Check if this is an option-like type wrapping some type.
167let ty::Adt(def, args) = layout.ty.kind() else {
168// Not an ADT, so definitely no NPO.
169return interp_ok(layout);
170 };
171if def.variants().len() != 2 {
172// Not a 2-variant enum, so no NPO.
173return interp_ok(layout);
174 }
175if !def.is_enum() {
::core::panicking::panic("assertion failed: def.is_enum()")
};assert!(def.is_enum());
176177let all_fields_1zst = |variant: &VariantDef| -> InterpResult<'tcx, _> {
178for field in &variant.fields {
179let ty = field.ty(*self.tcx, *args).skip_norm_wip();
180let layout = self.layout_of(ty)?;
181if !layout.is_1zst() {
182return interp_ok(false);
183 }
184 }
185interp_ok(true)
186 };
187188// If one variant consists entirely of 1-ZST, then the other variant
189 // is the only "relevant" one for this check.
190let var0 = VariantIdx::from_u32(0);
191let var1 = VariantIdx::from_u32(1);
192let relevant_variant = if all_fields_1zst(def.variant(var0))? {
193def.variant(var1)
194 } else if all_fields_1zst(def.variant(var1))? {
195def.variant(var0)
196 } else {
197// No variant is all-1-ZST, so no NPO.
198return interp_ok(layout);
199 };
200// The "relevant" variant must have exactly one field, and its type is the "inner" type.
201if relevant_variant.fields.len() != 1 {
202return interp_ok(layout);
203 }
204let inner =
205relevant_variant.fields[FieldIdx::from_u32(0)].ty(*self.tcx, *args).skip_norm_wip();
206let inner = self.layout_of(inner)?;
207208// Check if the inner type is one of the NPO-guaranteed ones.
209 // For that we first unpeel transparent *structs* (but not unions).
210let is_npo =
211 |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::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(self.tcx, def.did(), RustcNonnullOptimizationGuaranteed);
212let inner = self.unfold_transparent(inner, /* may_unfold */ |def| {
213// Stop at NPO types so that we don't miss that attribute in the check below!
214def.is_struct() && !is_npo(def)
215 })?;
216interp_ok(match inner.ty.kind() {
217 ty::Ref(..) | ty::FnPtr(..) => {
218// Option<&T> behaves like &T, and same for fn()
219inner220 }
221 ty::Adt(def, _) if is_npo(*def) => {
222// Once we found a `nonnull_optimization_guaranteed` type, further strip off
223 // newtype structs from it to find the underlying ABI type.
224self.unfold_transparent(inner, /* may_unfold */ |def| def.is_struct())?
225}
226_ => {
227// Everything else we do not unfold.
228layout229 }
230 })
231 }
232233/// Determine whether the given types are identical types from the perspective of C.
234pub(super) fn identical_c_types(
235&self,
236 caller_type: Ty<'tcx>,
237 callee_type: Ty<'tcx>,
238 ) -> InterpResult<'tcx, bool> {
239if caller_type == callee_type {
240return interp_ok(true);
241 }
242243// C considers two structs to be the same if they have the same name and the same
244 // fields. We need a similar rules that that e.g. if caller and callee use the "same"
245 // type from two different versions of the same crate, that call is accepted.
246let ty::Adt(caller_adt, caller_args) = caller_type.kind() else { return interp_ok(false) };
247let ty::Adt(callee_adt, callee_args) = callee_type.kind() else { return interp_ok(false) };
248249// We want to reject compatibility between structs with and without `#[cfi_encoding]` attr,
250 // see https://github.com/rust-lang/rust/pull/164739#discussion_r4360457828
251#[derive(#[automatically_derived]impl ::core::marker::StructuralPartialEq for
AbiNameClass {
}
#[automatically_derived]impl ::core::cmp::PartialEq for AbiNameClass {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for AbiNameClass { }Eq)]
252enum AbiNameClass {
253 CfiEncoded,
254 Normal,
255 }
256257let abi_name = |adt: AdtDef<'tcx>| {
258{
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(adt.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(CfiEncoding { encoding })
=> {
break 'done Some((AbiNameClass::CfiEncoded, *encoding));
}
::rustc_attr_ir::Attribute::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(
259self.tcx,
260 adt.did(),
261 CfiEncoding { encoding } => (AbiNameClass::CfiEncoded, *encoding)
262 )263 .unwrap_or_else(|| (AbiNameClass::Normal, self.tcx.item_name(adt.did())))
264 };
265266if !(
267// They must both be structs.
268(caller_adt.is_struct() && callee_adt.is_struct())
269// They must have equal `repr`, and it must be `repr(C)`.
270&& (caller_adt.repr().c() && caller_adt.repr().equal_up_to_seed(&callee_adt.repr()))
271// They must have the same name.
272&& abi_name(*caller_adt) == abi_name(*callee_adt)
273 ) {
274return interp_ok(false);
275 }
276277// All fields must have the same names and types as well, where "same type" recursively
278 // uses this check.
279let caller_fields = &caller_adt.non_enum_variant().fields;
280let callee_fields = &callee_adt.non_enum_variant().fields;
281interp_ok(
282caller_fields.len() == callee_fields.len()
283 && caller_fields.iter().zip(callee_fields).try_fold(
284/* accumulator */ true,
285 |acc, (caller_field, callee_field)| {
286// We implement `all` via `try_fold` as there is no `try_all`.
287288 // Bail if we already accumulated a `false`, and on different name.
289if !acc || caller_field.name != callee_field.name {
290return interp_ok(false);
291 }
292// Ensure the normalized type is the same.
293 // We also unfold repr(transparent) wrappers as part of that.
294let normalized_field_ty =
295 |field: &FieldDef, args| -> InterpResult<'tcx, _> {
296// `layout_of` performs normalization, so we're not really skipping.
297let field =
298self.layout_of(field.ty(*self.tcx, args).skip_norm_wip())?;
299// `unfold_transparent` returns a normalized type
300interp_ok(self.unfold_transparent(field, |adt| adt.is_struct())?.ty)
301 };
302let caller_ty = normalized_field_ty(caller_field, *caller_args)?;
303let callee_ty = normalized_field_ty(callee_field, *callee_args)?;
304self.identical_c_types(caller_ty, callee_ty)
305 },
306 )?,
307 )
308 }
309310/// Check if these two layouts look like they are fn-ABI-compatible.
311 /// (We also compare the `PassMode`, so this doesn't have to check everything. But it turns out
312 /// that only checking the `PassMode` is insufficient.)
313fn layout_compat(
314&self,
315 caller: TyAndLayout<'tcx>,
316 callee: TyAndLayout<'tcx>,
317 ) -> InterpResult<'tcx, bool> {
318// Fast path: equal types are definitely compatible.
319if caller.ty == callee.ty {
320return interp_ok(true);
321 }
322// Handle trivial-ABI types.
323if self.has_trivial_abi(caller)? && self.has_trivial_abi(callee)? {
324return interp_ok(true);
325 }
326// Unfold newtypes and NPO optimizations.
327let unfold = |layout: TyAndLayout<'tcx>| {
328self.unfold_transparent(layout, /* may_unfold */ |_def| true)
329 .and_then(|f| self.unfold_npo(f))
330 };
331let caller = unfold(caller)?;
332let callee = unfold(callee)?;
333// Not-quite-so-fast path: if the types are c-equal now, they are compatible.
334 // FIXME: This is *not* currently guaranteed by our ABI compatibility docs, but it is needed
335 // for Miri itself when it checks whether shims were called with the right arguments.
336 // We should eventually put this into the docs as well.
337if self.identical_c_types(caller.ty, callee.ty)? {
338return interp_ok(true);
339 }
340// Now see if these inner types are compatible.
341342 // Compatible pointer types. For thin pointers, we have to accept even non-`repr(transparent)`
343 // things as compatible due to `DispatchFromDyn`. For instance, `Rc<i32>` and `*mut i32`
344 // must be compatible. So we just accept everything with Pointer ABI as compatible,
345 // even if this will accept some code that is not stably guaranteed to work.
346 // This also handles function pointers.
347let thin_pointer = |layout: TyAndLayout<'tcx>| match layout.backend_repr {
348 abi::BackendRepr::Scalar(s) => match s.primitive() {
349 abi::Primitive::Pointer(addr_space) => Some(addr_space),
350_ => None,
351 },
352_ => None,
353 };
354if let (Some(caller), Some(callee)) = (thin_pointer(caller), thin_pointer(callee)) {
355return interp_ok(caller == callee);
356 }
357// For wide pointers we have to get the pointee type.
358let pointee_ty = |ty: Ty<'tcx>| -> InterpResult<'tcx, Option<Ty<'tcx>>> {
359// We cannot use `builtin_deref` here since we need to reject `Box<T, MyAlloc>`.
360interp_ok(Some(match ty.kind() {
361 ty::Ref(_, ty, _) => *ty,
362 ty::RawPtr(ty, _) => *ty,
363// We only accept `Box` with the default allocator.
364_ if ty.is_box_global(*self.tcx) => ty.expect_boxed_ty(),
365_ => return interp_ok(None),
366 }))
367 };
368if let (Some(caller), Some(callee)) = (pointee_ty(caller.ty)?, pointee_ty(callee.ty)?) {
369// This is okay if they have the same metadata type.
370let meta_ty = |ty: Ty<'tcx>| {
371// Even if `ty` is normalized, the search for the unsized tail will project
372 // to fields, which can yield non-normalized types. So we need to provide a
373 // normalization function.
374let normalize = |ty| self.tcx.normalize_erasing_regions(self.typing_env, ty);
375ty.ptr_metadata_ty(*self.tcx, normalize)
376 };
377return interp_ok(meta_ty(caller) == meta_ty(callee));
378 }
379380// Compatible integer types (in particular, usize vs ptr-sized-u32/u64).
381 // `char` counts as `u32.`
382let int_ty = |ty: Ty<'tcx>| {
383Some(match ty.kind() {
384 ty::Int(ity) => (Integer::from_int_ty(&self.tcx, *ity), /* signed */ true),
385 ty::Uint(uty) => (Integer::from_uint_ty(&self.tcx, *uty), /* signed */ false),
386 ty::Char => (Integer::I32, /* signed */ false),
387_ => return None,
388 })
389 };
390if let (Some(caller), Some(callee)) = (int_ty(caller.ty), int_ty(callee.ty)) {
391// This is okay if they are the same integer type.
392return interp_ok(caller == callee);
393 }
394395// The rest is incompatible.
396interp_ok(false)
397 }
398399/// Returns a `bool` saying whether the two arguments are ABI-compatible.
400pub fn check_argument_compat(
401&self,
402 caller_abi: &ArgAbi<'tcx, Ty<'tcx>>,
403 callee_abi: &ArgAbi<'tcx, Ty<'tcx>>,
404 ) -> InterpResult<'tcx, bool> {
405// We do not want to accept things as ABI-compatible that just "happen to be" compatible on the current target,
406 // so we implement a type-based check that reflects the guaranteed rules for ABI compatibility.
407if self.layout_compat(caller_abi.layout, callee_abi.layout)? {
408// Ensure that our checks imply actual ABI compatibility for this concrete call.
409 // (This can fail e.g. if `#[rustc_nonnull_optimization_guaranteed]` is used incorrectly.)
410if !caller_abi.eq_abi(callee_abi) {
{
::core::panicking::panic_fmt(format_args!("these types were deemed ABI-compatible but do not actually have compatible `FnAbi`:\ncaller: {0:#?}\ncallee: {1:#?}",
caller_abi, callee_abi));
}
};assert!(
411 caller_abi.eq_abi(callee_abi),
412"these types were deemed ABI-compatible but do not actually have compatible `FnAbi`:\ncaller: {caller_abi:#?}\ncallee: {callee_abi:#?}"
413);
414interp_ok(true)
415 } else {
416{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs:416",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/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(&["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!(
417"check_argument_compat: incompatible ABIs:\ncaller: {:?}\ncallee: {:?}",
418 caller_abi, callee_abi
419 );
420interp_ok(false)
421 }
422 }
423424/// Initialize a single callee argument, checking the types for compatibility.
425fn pass_argument<'x, 'y>(
426&mut self,
427 caller_args: &mut impl Iterator<
428 Item = (&'x FnArg<'tcx, M::Provenance>, &'y ArgAbi<'tcx, Ty<'tcx>>),
429 >,
430 callee_args_abis: &mut impl Iterator<Item = (usize, &'y ArgAbi<'tcx, Ty<'tcx>>)>,
431 callee_arg: &mir::Place<'tcx>,
432 callee_ty: Ty<'tcx>,
433 already_live: bool,
434 ) -> InterpResult<'tcx>
435where
436'tcx: 'x,
437'tcx: 'y,
438 {
439// Get next callee arg.
440let (callee_arg_idx, callee_abi) = callee_args_abis.next().unwrap();
441{
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);
442// Get next caller arg.
443let Some((caller_arg, caller_abi)) = caller_args.next() else {
444do 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");
445 };
446{
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);
447// Sadly we cannot assert that `caller_arg.layout().ty` and `caller_abi.layout.ty` are
448 // equal; in closures the types sometimes differ. We just hope that `caller_abi` is the
449 // right type to print to the user.
450451 // Check compatibility
452if !self.check_argument_compat(caller_abi, callee_abi)? {
453do 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 {
454 arg_idx: callee_arg_idx,
455 caller_ty: caller_abi.layout.ty,
456 callee_ty: callee_abi.layout.ty
457 });
458 }
459// We work with a copy of the argument for now; if this is in-place argument passing, we
460 // will later protect the source it comes from. This means the callee cannot observe if we
461 // did in-place of by-copy argument passing, except for pointer equality tests.
462let caller_arg_copy = caller_arg.copy_fn_arg();
463if !already_live {
464let local = callee_arg.as_local().unwrap();
465let meta = caller_arg_copy.meta();
466// `check_argument_compat` ensures that if metadata is needed, both have the same type,
467 // so we know they will use the metadata the same way.
468if !(!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);
469470self.storage_live_dyn(local, meta)?;
471 }
472// Now we can finally actually evaluate the callee place.
473let callee_arg =
474self.eval_place(*callee_arg, /* skip_validity_for_simple_deref */ false)?;
475// We allow some transmutes here.
476 // FIXME: Depending on the PassMode, this should reset some padding to uninitialized. (This
477 // is true for all `copy_op`, but there are a lot of special cases for argument passing
478 // specifically.)
479self.copy_op_allow_transmute(&caller_arg_copy, &callee_arg)?;
480// If this was an in-place pass, protect the place it comes from for the duration of the call.
481if let FnArg::InPlace(mplace) = caller_arg {
482 M::protect_in_place_function_argument(self, mplace)?;
483 }
484interp_ok(())
485 }
486487/// The main entry point for creating a new stack frame: performs ABI checks and initializes
488 /// arguments.
489{}
#[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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(489u32),
::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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(500u32),
::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();
match (instance.def.requires_caller_location(*self.tcx),
with_caller_location) {
(false, true) => {
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 non-`#[track_caller]` function from a `#[track_caller]` declaration"))
})))
}
(true, false) => {
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 `#[track_caller]` function from a non-`#[track_caller]` declaration"))
})))
}
_ => {}
}
let caller_location =
with_caller_location.then(|| self.caller_location());
let extra_args = ty::List::empty();
let callee_fn_abi =
self.fn_abi_of_instance_no_deduced_attrs(instance,
extra_args)?;
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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs:571",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(571u32),
::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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs:584",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(584u32),
::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 { ; }
};
self.frame_mut().track_caller_arg = caller_location;
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)?;
if !callee_args_abis.next().is_none() {
::core::panicking::panic("assertion failed: callee_args_abis.next().is_none()")
};
let varargs =
M::with_retag_mode(ecx, RetagMode::None,
|ecx| { ecx.allocate_varargs(&mut caller_args) })?;
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_span::macros::bug_impl(Some(ecx.cur_span()),
format_args!("non-tuple type for `spread_arg`: {0}", ty),
Location::caller())
};
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"))
})));
}
M::after_stack_frame_init(self)?;
self.push_stack_frame_done()
}
}
}#[instrument(skip(self), level = "trace")]490pub fn init_stack_frame(
491&mut self,
492 instance: Instance<'tcx>,
493 body: &'tcx mir::Body<'tcx>,
494 caller_fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
495 args: &[FnArg<'tcx, M::Provenance>],
496 with_caller_location: bool,
497 destination: &PlaceTy<'tcx, M::Provenance>,
498mut cont: ReturnContinuation,
499 ) -> InterpResult<'tcx> {
500let _trace = enter_trace_span!(M, step::init_stack_frame, %instance, tracing_separate_thread = Empty);
501let def_id = instance.def_id();
502503match (instance.def.requires_caller_location(*self.tcx), with_caller_location) {
504 (false, true) => {
505throw_ub_format!(
506"calling a non-`#[track_caller]` function from a `#[track_caller]` declaration"
507)
508 }
509 (true, false) => {
510throw_ub_format!(
511"calling a `#[track_caller]` function from a non-`#[track_caller]` declaration"
512)
513 }
514_ => {}
515 }
516let caller_location = with_caller_location.then(|| self.caller_location());
517518// The first order of business is to figure out the callee signature.
519 // We leave the list of extra c-variadic args empty because the callee cannot know about
520 // them, and we don't need them in the `FnAbi`. This also avoids ICEs if the callee is
521 // not actually c-variadic.
522let extra_args = ty::List::empty();
523let callee_fn_abi = self.fn_abi_of_instance_no_deduced_attrs(instance, extra_args)?;
524525if caller_fn_abi.conv != callee_fn_abi.conv {
526throw_ub_format!(
527"calling a function with calling convention \"{callee_conv}\" using calling convention \"{caller_conv}\"",
528 callee_conv = callee_fn_abi.conv,
529 caller_conv = caller_fn_abi.conv,
530 )
531 }
532533if caller_fn_abi.c_variadic != callee_fn_abi.c_variadic {
534throw_ub!(CVariadicMismatch {
535 caller_is_c_variadic: caller_fn_abi.c_variadic,
536 callee_is_c_variadic: callee_fn_abi.c_variadic,
537 });
538 }
539if caller_fn_abi.c_variadic && caller_fn_abi.fixed_count != callee_fn_abi.fixed_count {
540throw_ub!(CVariadicFixedCountMismatch {
541 caller: caller_fn_abi.fixed_count,
542 callee: callee_fn_abi.fixed_count,
543 });
544 }
545546// Check that all target features required by the callee (i.e., from
547 // the attribute `#[target_feature(enable = ...)]`) are enabled at
548 // compile time.
549M::check_fn_target_features(self, instance)?;
550551// If the signature says this cannot unwind, reflect this in the unwind destination so that
552 // we don't have to check this later. (`init_fn_call` already did this for the caller so
553 // here we only have to check the callee.)
554if !callee_fn_abi.can_unwind {
555match &mut cont {
556 ReturnContinuation::Stop { .. } => {}
557 ReturnContinuation::Goto { unwind, .. } => {
558*unwind = mir::UnwindAction::Unreachable;
559 }
560 }
561 }
562563// *Before* pushing the new frame, determine whether the return destination is in memory.
564 // Need to use `place_to_op` to be *sure* we get the mplace if there is one.
565let destination_mplace = self.place_to_op(destination)?.as_mplace_or_imm().left();
566567// Push the "raw" frame -- this leaves locals uninitialized.
568self.push_stack_frame_raw(instance, body, destination, cont)?;
569let preamble_span = self.frame().loc.unwrap_right(); // the span used for preamble errors
570571trace!(
572"caller ABI: {:#?}, args: {:#?}",
573 caller_fn_abi,
574 args.iter()
575 .map(|arg| (
576 arg.layout().ty,
577match arg {
578 FnArg::Copy(op) => format!("copy({op:?})"),
579 FnArg::InPlace(mplace) => format!("in-place({mplace:?})"),
580 }
581 ))
582 .collect::<Vec<_>>()
583 );
584trace!(
585"spread_arg: {:?}, locals: {:#?}",
586 body.spread_arg,
587 body.args_iter()
588 .map(|local| (local, self.layout_of_local(self.frame(), local, None).unwrap().ty))
589 .collect::<Vec<_>>()
590 );
591592// Initialize special caller_location "local", if this function has it.
593self.frame_mut().track_caller_arg = caller_location;
594595// Determine whether there is a special VaList argument. This is always the
596 // last argument, and since arguments start at index 1 that's `arg_count`.
597let va_list_arg = callee_fn_abi.c_variadic.then(|| mir::Local::from_usize(body.arg_count));
598// Determine whether this is a non-capturing closure. That's relevant as their first
599 // argument can be skipped (and that's the only kind of argument skipping we allow).
600let is_non_capturing_closure =
601 (matches!(instance.def, ty::InstanceKind::Shim(ty::ShimKind::ClosureOnce { .. }))
602 || self.tcx.is_closure_like(def_id))
603 && {
604let arg = &callee_fn_abi.args[0];
605matches!(arg.layout.ty.kind(), ty::Closure (_def, closure_args) if {
606 closure_args.as_closure().upvar_tys().is_empty()
607 })
608 };
609610// In principle, we have two iterators: Where the arguments come from, and where
611 // they go to.
612613 // The "where they come from" part is easy, we expect the caller to do any special handling
614 // that might be required here (e.g. for untupling).
615 // If `with_caller_location` is set we pretend there is an extra argument (that
616 // we will not pass normally; our `caller_location` intrinsic implementation handles
617 // that separately).
618assert_eq!(
619 args.len() + if with_caller_location { 1 } else { 0 },
620 caller_fn_abi.args.len(),
621"mismatch between caller ABI and caller arguments",
622 );
623let mut caller_args = args.iter().zip(caller_fn_abi.args.iter());
624625// Now we have to spread them out across the callee's locals,
626 // taking into account the `spread_arg`. If we could write
627 // this is a single iterator (that handles `spread_arg`), then
628 // `pass_argument` would be the loop body.
629let mut callee_args_abis = callee_fn_abi.args.iter().enumerate();
630// During argument passing, we want retagging with protectors.
631M::with_retag_mode(self, RetagMode::FnEntry, |ecx| {
632for local in body.args_iter() {
633// Update the span that we show in case of an error to point to this argument.
634ecx.frame_mut().loc = Right(body.local_decls[local].source_info.span);
635// Construct the destination place for this argument. At this point all
636 // locals are still dead, so we cannot construct a `PlaceTy`.
637let dest = mir::Place::from(local);
638// `layout_of_local` does more than just the instantiation we need to get the
639 // type, but the result gets cached so this avoids calling the instantiation
640 // query *again* the next time this local is accessed.
641let ty = ecx.layout_of_local(ecx.frame(), local, None)?.ty;
642643// Some arguments are special: the first (`self`) argument of a non-capturing
644 // closure; the va_list argument; and the spread_arg.
645if is_non_capturing_closure && local == mir::Local::arg(0) {
646assert!(va_list_arg.is_none());
647assert!(Some(local) != body.spread_arg);
648// This argument might be missing on the caller side. So just initialize it in
649 // the callee.
650let (callee_arg_idx, callee_abi) = callee_args_abis.next().unwrap();
651assert!(callee_abi.layout.is_1zst() && callee_abi.is_ignore());
652 ecx.storage_live(local)?;
653// And skip it in the caller, if present. We can tell whether it is present by
654 // comparing the number of arguments on the caller and callee side.
655if caller_fn_abi.args.len() == callee_fn_abi.args.len() {
656let (_caller_arg, caller_abi) = caller_args.next().unwrap();
657if !caller_abi.layout.is_1zst() {
658// The caller gave us some other, non-ignorable argument.
659throw_ub!(AbiMismatchArgument {
660 arg_idx: callee_arg_idx,
661 caller_ty: caller_abi.layout.ty,
662 callee_ty: callee_abi.layout.ty
663 });
664 }
665assert!(caller_abi.is_ignore());
666 }
667 } else if Some(local) == va_list_arg {
668// This is the last callee-side argument of a variadic function.
669 // This argument is a VaList holding the remaining caller-side arguments.
670ecx.storage_live(local)?;
671672let place =
673 ecx.eval_place(dest, /* skip_validity_for_simple_deref */ false)?;
674let mplace = ecx.force_allocation(&place)?;
675676// There should be no more callee ABI arguments.
677assert!(callee_args_abis.next().is_none());
678// Consume the remaining arguments by putting them into the variable argument
679 // list. We disable retagging to avoid creating protected tags. Protection should
680 // only use callee-side information, and the varargs have no static callee-side type.
681let varargs = M::with_retag_mode(ecx, RetagMode::None, |ecx| {
682 ecx.allocate_varargs(&mut caller_args)
683 })?;
684685// When the frame is dropped, these variable arguments are deallocated.
686ecx.frame_mut().va_list = varargs.clone();
687let key = ecx.va_list_ptr(varargs.into());
688689// Zero the VaList, so it is fully initialized.
690ecx.write_bytes_ptr(
691 mplace.ptr(),
692 (0..mplace.layout.size.bytes()).map(|_| 0u8),
693 )?;
694695// Store the "key" pointer in the right field.
696let key_mplace = ecx.va_list_key_field(&mplace)?;
697 ecx.write_pointer(key, &key_mplace)?;
698 } else if Some(local) == body.spread_arg {
699// Make the local live once, then fill in the value field by field.
700ecx.storage_live(local)?;
701// Must be a tuple
702let ty::Tuple(fields) = ty.kind() else {
703span_bug!(ecx.cur_span(), "non-tuple type for `spread_arg`: {ty}")
704 };
705for (i, field_ty) in fields.iter().enumerate() {
706let dest = dest.project_deeper(
707&[mir::ProjectionElem::Field(FieldIdx::from_usize(i), field_ty)],
708*ecx.tcx,
709 );
710 ecx.pass_argument(
711&mut caller_args,
712&mut callee_args_abis,
713&dest,
714 field_ty,
715/* already_live */ true,
716 )?;
717 }
718 } else {
719// Normal argument. Cannot mark it as live yet, it might be unsized!
720ecx.pass_argument(
721&mut caller_args,
722&mut callee_args_abis,
723&dest,
724 ty,
725/* already_live */ false,
726 )?;
727 }
728 }
729 interp_ok(())
730 })?;
731732// Don't forget to check the return type!
733self.frame_mut().loc = Right(body.local_decls[mir::RETURN_PLACE].source_info.span);
734if !self.check_argument_compat(&caller_fn_abi.ret, &callee_fn_abi.ret)? {
735throw_ub!(AbiMismatchReturn {
736 caller_ty: caller_fn_abi.ret.layout.ty,
737 callee_ty: callee_fn_abi.ret.layout.ty
738 });
739 }
740// Protect return place for in-place return value passing.
741 // We only need to protect anything if this is actually an in-memory place.
742if let Some(mplace) = destination_mplace {
743 M::protect_in_place_function_argument(self, &mplace)?;
744 }
745746// For the final checks, use same span as preamble since it is unclear what else to do.
747self.frame_mut().loc = Right(preamble_span);
748// If the callee needs a caller location, pretend we consume one more argument from the ABI.
749if instance.def.requires_caller_location(*self.tcx) {
750 callee_args_abis.next().unwrap();
751 }
752// Now we should have no more caller args or callee arg ABIs.
753assert!(
754 callee_args_abis.next().is_none(),
755"mismatch between callee ABI and callee body arguments"
756);
757if caller_args.next().is_some() {
758throw_ub_format!("calling a function with more arguments than it expected");
759 }
760761// All function arguments have gotten initialized, call corresponding hook.
762M::after_stack_frame_init(self)?;
763764// Done!
765self.push_stack_frame_done()
766 }
767768/// Initiate a call to this function -- pushing the stack frame and initializing the arguments.
769 ///
770 /// `caller_fn_abi` is used to determine if all the arguments are passed the proper way.
771 /// However, we also need `caller_abi` to determine if we need to do untupling of arguments.
772 ///
773 /// `with_caller_location` indicates whether the caller passed a caller location. Miri
774 /// implements caller locations without argument passing, but to match `FnAbi` we need to know
775 /// when those arguments are present.
776pub(super) fn init_fn_call(
777&mut self,
778 fn_val: FnVal<'tcx, M::ExtraFnVal>,
779 (caller_abi, caller_fn_abi): (ExternAbi, Option<&FnAbi<'tcx, Ty<'tcx>>>),
780 args: &[FnArg<'tcx, M::Provenance>],
781 with_caller_location: bool,
782 destination: &PlaceTy<'tcx, M::Provenance>,
783 target: Option<mir::BasicBlock>,
784mut unwind: mir::UnwindAction,
785 ) -> InterpResult<'tcx> {
786let _trace =
787<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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(787u32),
::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)788 .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/c82ce15637153c025d29abbaff6035a177361788/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/c82ce15637153c025d29abbaff6035a177361788/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: {0:#?}",
fn_val) as &dyn ::tracing::field::Value))])
});
} else { ; }
}trace!("init_fn_call: {:#?}", fn_val));
789790// If the signature says this cannot unwind, reflect this in the unwind destination
791 // so that we don't have to check this later.
792if caller_fn_abi.is_some_and(|abi| !abi.can_unwind) {
793unwind = mir::UnwindAction::Unreachable;
794 }
795796let instance = match fn_val {
797 FnVal::Instance(instance) => instance,
798 FnVal::Other(extra) => {
799let caller_fn_abi =
800caller_fn_abi.expect("FnAbi should have been computed for this call");
801return M::call_extra_fn(
802self,
803extra,
804caller_fn_abi,
805args,
806destination,
807target,
808unwind,
809 );
810 }
811 };
812813match instance.def {
814 ty::InstanceKind::Intrinsic(def_id) => {
815if !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());
816if !!with_caller_location {
::core::panicking::panic("assertion failed: !with_caller_location")
};assert!(!with_caller_location);
817// FIXME: Should `InPlace` arguments be reset to uninit?
818if let Some(fallback) = M::call_intrinsic(
819self,
820 instance,
821&Self::copy_fn_args(args),
822 destination,
823 target,
824 unwind,
825 )? {
826if !!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);
827{
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(_));
828// For `#[rustc_intrinsic] fn`, two `Instance`s are involved:
829 // the original `InstanceKind::Intrinsic` (no caller location arg), and
830 // the fallback `InstanceKind::Item` (has caller location arg if
831 // it's `#[track_caller]`).
832 // We replace the former with the latter.
833return self.init_fn_call(
834 FnVal::Instance(fallback),
835 (caller_abi, caller_fn_abi),
836args,
837fallback.def.requires_caller_location(*self.tcx),
838destination,
839target,
840unwind,
841 );
842 } else {
843interp_ok(())
844 }
845 }
846 ty::InstanceKind::LlvmIntrinsic(_) => {
847// FIXME: Should `InPlace` arguments be reset to uninit?
848M::call_llvm_intrinsic(
849self,
850instance,
851&Self::copy_fn_args(args),
852destination,
853target,
854 )
855 }
856 ty::InstanceKind::Shim(ty::ShimKind::VTable(..))
857 | ty::InstanceKind::Shim(ty::ShimKind::Reify(..))
858 | ty::InstanceKind::Shim(ty::ShimKind::ClosureOnce { .. })
859 | ty::InstanceKind::Shim(ty::ShimKind::ConstructCoroutineInClosure { .. })
860 | ty::InstanceKind::Shim(ty::ShimKind::FnPtr(..))
861 | ty::InstanceKind::Shim(ty::ShimKind::DropGlue(..))
862 | ty::InstanceKind::Shim(ty::ShimKind::Clone(..))
863 | ty::InstanceKind::Shim(ty::ShimKind::FnAddrAsPtr(..))
864 | ty::InstanceKind::Shim(ty::ShimKind::FnPtrFromPtr(..))
865 | ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(..))
866 | ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlueCtor(..))
867 | ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlue(..))
868 | ty::InstanceKind::Shim(ty::ShimKind::FutureDropPoll(..))
869 | ty::InstanceKind::Item(_) => {
870// We need MIR for this fn.
871 // Note that this can be an intrinsic, if we are executing its fallback body.
872let caller_fn_abi =
873caller_fn_abi.expect("FnAbi should have been computed for this call");
874let Some((body, instance)) = M::find_mir_or_eval_fn(
875self,
876 instance,
877 caller_fn_abi,
878 args,
879 destination,
880 target,
881 unwind,
882 )?
883else {
884return interp_ok(());
885 };
886887// Special handling for the closure ABI: untuple the last argument.
888 // FIXME(splat): un-tuple splatted arguments that were tupled in typecheck
889let args: Cow<'_, [FnArg<'tcx, M::Provenance>]> =
890if caller_abi == ExternAbi::RustCall && !args.is_empty() {
891// Untuple
892let (untuple_arg, args) = args.split_last().unwrap();
893let ty::Tuple(untuple_fields) = untuple_arg.layout().ty.kind() else {
894::rustc_span::macros::bug_impl(Some(self.cur_span()),
format_args!("untuple argument must be a tuple"), Location::caller())span_bug!(self.cur_span(), "untuple argument must be a tuple")895 };
896{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs:896",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(896u32),
::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");
897Cow::from(
898 args.iter()
899// The regular arguments.
900.map(|a| interp_ok(a.clone()))
901// The fields of the untupled argument.
902.chain((0..untuple_fields.len()).map(|i| {
903self.fn_arg_project_field(untuple_arg, FieldIdx::from_usize(i))
904 }))
905 .collect::<InterpResult<'_, Vec<_>>>()?,
906 )
907 } else {
908// Plain arg passing
909Cow::from(args)
910 };
911912self.init_stack_frame(
913instance,
914body,
915caller_fn_abi,
916&args,
917with_caller_location,
918destination,
919 ReturnContinuation::Goto { ret: target, unwind },
920 )
921 }
922// `InstanceKind::Virtual` does not have callable MIR. Calls to `Virtual` instances must be
923 // codegen'd / interpreted as virtual calls through the vtable.
924ty::InstanceKind::Virtual(def_id, idx) => {
925let caller_fn_abi =
926caller_fn_abi.expect("FnAbi should have been computed for this call");
927let mut args = args.to_vec();
928// We have to implement all "dyn-compatible receivers". So we have to go search for a
929 // pointer or `dyn Trait` type, but it could be wrapped in newtypes. So recursively
930 // unwrap those newtypes until we are there.
931 // An `InPlace` does nothing here, we keep the original receiver intact. We can't
932 // really pass the argument in-place anyway, and we are constructing a new
933 // `Immediate` receiver.
934let mut receiver = args[0].copy_fn_arg();
935let receiver_place = loop {
936match receiver.layout.ty.kind() {
937 ty::Ref(..) | ty::RawPtr(..) => {
938// We do *not* use `deref_pointer` here: we don't want to conceptually
939 // create a place that must be dereferenceable, since the receiver might
940 // be a raw pointer and (for `*const dyn Trait`) we don't need to
941 // actually access memory to resolve this method.
942 // Also see <https://github.com/rust-lang/miri/issues/2786>.
943let val = self.read_immediate(&receiver)?;
944break self.imm_ptr_to_mplace(&val)?;
945 }
946 ty::Dynamic(..) => break receiver.assert_mem_place(), // no immediate unsized values
947_ => {
948// Not there yet, search for the only non-ZST field.
949 // (The rules for `DispatchFromDyn` ensure there's exactly one such field.)
950let (idx, _) = receiver.layout.non_1zst_field(self).expect(
951"not exactly one non-1-ZST field in a `DispatchFromDyn` type",
952 );
953receiver = self.project_field(&receiver, idx)?;
954 }
955 }
956 };
957958// Obtain the underlying trait we are working on, and the adjusted receiver argument.
959 // Doesn't have to be a `dyn Trait`, but the unsized tail must be `dyn Trait`.
960 // (For that reason we also cannot use `unpack_dyn_trait`.)
961let receiver_tail =
962self.tcx.struct_tail_for_codegen(receiver_place.layout.ty, self.typing_env);
963let ty::Dynamic(receiver_trait, _) = receiver_tail.kind() else {
964::rustc_span::macros::bug_impl(Some(self.cur_span()),
format_args!("dynamic call on non-`dyn` type {0}", receiver_tail),
Location::caller())span_bug!(self.cur_span(), "dynamic call on non-`dyn` type {}", receiver_tail)965 };
966if !receiver_place.layout.is_unsized() {
::core::panicking::panic("assertion failed: receiver_place.layout.is_unsized()")
};assert!(receiver_place.layout.is_unsized());
967968// Get the required information from the vtable.
969let vptr = receiver_place.meta().unwrap_meta().to_pointer(self);
970let dyn_ty = self.get_ptr_vtable_ty(vptr, Some(receiver_trait))?;
971let adjusted_recv = receiver_place.ptr();
972973// Now determine the actual method to call. Usually we use the easy way of just
974 // looking up the method at index `idx`.
975let vtable_entries = self.vtable_entries(receiver_trait.principal(), dyn_ty);
976let Some(ty::VtblEntry::Method(fn_inst)) = vtable_entries.get(idx).copied() else {
977// FIXME(fee1-dead) these could be variants of the UB info enum instead of this
978do 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");
979 };
980{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs:980",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(980u32),
::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:#?}");
981// We can also do the lookup based on `def_id` and `dyn_ty`, and check that that
982 // produces the same result.
983self.assert_virtual_instance_matches_concrete(dyn_ty, def_id, instance, fn_inst);
984985// Adjust receiver argument. Layout can be any (thin) ptr.
986let receiver_ty = Ty::new_mut_ptr(self.tcx.tcx, dyn_ty);
987args[0] = FnArg::Copy(
988ImmTy::from_immediate(
989Scalar::from_maybe_pointer(adjusted_recv, self).into(),
990self.layout_of(receiver_ty)?,
991 )
992 .into(),
993 );
994{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs:994",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(994u32),
::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]);
995// Need to also adjust the type in the ABI. Strangely, the layout there is actually
996 // already fine! Just the type is bogus. This is due to what `force_thin_self_ptr`
997 // does in `fn_abi_new_uncached`; supposedly, codegen relies on having the bogus
998 // type, so we just patch this up locally.
999let mut caller_fn_abi = caller_fn_abi.clone();
1000caller_fn_abi.args[0].layout.ty = receiver_ty;
10011002// recurse with concrete function
1003self.init_fn_call(
1004 FnVal::Instance(fn_inst),
1005 (caller_abi, Some(&caller_fn_abi)),
1006&args,
1007with_caller_location,
1008destination,
1009target,
1010unwind,
1011 )
1012 }
1013 }
1014 }
10151016fn assert_virtual_instance_matches_concrete(
1017&self,
1018 dyn_ty: Ty<'tcx>,
1019 def_id: DefId,
1020 virtual_instance: ty::Instance<'tcx>,
1021 concrete_instance: ty::Instance<'tcx>,
1022 ) {
1023let tcx = *self.tcx;
10241025let trait_def_id = tcx.parent(def_id);
1026let virtual_trait_ref = ty::TraitRef::from_assoc(tcx, trait_def_id, virtual_instance.args);
1027let existential_trait_ref = ty::ExistentialTraitRef::erase_self_ty(tcx, virtual_trait_ref);
1028let concrete_trait_ref = existential_trait_ref.with_self_ty(tcx, dyn_ty);
10291030let concrete_method = {
1031let _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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(1031u32),
::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);
1032Instance::expect_resolve_for_vtable(
1033tcx,
1034self.typing_env,
1035def_id,
1036virtual_instance.args.rebase_onto(tcx, trait_def_id, concrete_trait_ref.args),
1037self.cur_span(),
1038 )
1039 };
1040{
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);
1041 }
10421043/// Initiate a tail call to this function -- popping the current stack frame, pushing the new
1044 /// stack frame and initializing the arguments.
1045pub(super) fn init_fn_tail_call(
1046&mut self,
1047 fn_val: FnVal<'tcx, M::ExtraFnVal>,
1048 (caller_abi, caller_fn_abi): (ExternAbi, Option<&FnAbi<'tcx, Ty<'tcx>>>),
1049 args: &[FnArg<'tcx, M::Provenance>],
1050 with_caller_location: bool,
1051 ) -> InterpResult<'tcx> {
1052{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs:1052",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(1052u32),
::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);
1053// This is the "canonical" implementation of tails calls,
1054 // a pop of the current stack frame, followed by a normal call
1055 // which pushes a new stack frame, with the return address from
1056 // the popped stack frame.
1057 //
1058 // Note that we cannot use `return_from_current_stack_frame`,
1059 // as that "executes" the goto to the return block, but we don't want to,
1060 // only the tail called function should return to the current return block.
10611062 // The arguments need to all be copied since the current stack frame will be removed
1063 // before the callee even starts executing.
1064 // FIXME(explicit_tail_calls,#144855): does this match what codegen does?
1065let args = args.iter().map(|fn_arg| FnArg::Copy(fn_arg.copy_fn_arg())).collect::<Vec<_>>();
1066// Remove the frame from the stack.
1067let frame = self.pop_stack_frame_raw()?;
1068// Remember where this frame would have returned to.
1069let ReturnContinuation::Goto { ret, unwind } = frame.return_cont() else {
1070::rustc_span::macros::bug_impl(None,
format_args!("can\'t tailcall as root of the stack"), Location::caller());bug!("can't tailcall as root of the stack");
1071 };
1072// There's no return value to deal with! Instead, we forward the old return place
1073 // to the new function.
1074 // FIXME(explicit_tail_calls):
1075 // we should check if both caller&callee can/n't unwind,
1076 // see <https://github.com/rust-lang/rust/pull/113128#issuecomment-1614979803>
10771078 // Now push the new stack frame.
1079self.init_fn_call(
1080 fn_val,
1081 (caller_abi, caller_fn_abi),
1082&*args,
1083 with_caller_location,
1084 frame.return_place(),
1085 ret,
1086 unwind,
1087 )?;
10881089// Finally, clear the local variables. Has to be done after pushing to support
1090 // non-scalar arguments.
1091 // FIXME(explicit_tail_calls,#144855): revisit this once codegen supports indirect
1092 // arguments, to ensure the semantics are compatible.
1093let return_action = self.cleanup_stack_frame(/* unwinding */ false, frame)?;
1094{
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);
10951096interp_ok(())
1097 }
10981099pub(super) fn init_drop_in_place_call(
1100&mut self,
1101 place: &PlaceTy<'tcx, M::Provenance>,
1102 instance: ty::Instance<'tcx>,
1103 target: mir::BasicBlock,
1104 unwind: mir::UnwindAction,
1105 ) -> InterpResult<'tcx> {
1106{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs:1106",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(1106u32),
::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);
1107// We take the address of the object. This may well be unaligned, which is fine
1108 // for us here. However, unaligned accesses will probably make the actual drop
1109 // implementation fail -- a problem shared by rustc.
1110let place = self.force_allocation(place)?;
11111112// We behave a bit different from codegen here.
1113 // Codegen creates an `InstanceKind::Virtual` with index 0 (the slot of the drop method) and
1114 // then dispatches that to the normal call machinery. However, our call machinery currently
1115 // only supports calling `VtblEntry::Method`; it would choke on a `MetadataDropInPlace`. So
1116 // instead we do the virtual call stuff ourselves. It's easier here than in `eval_fn_call`
1117 // since we can just get a place of the underlying type and use `mplace_to_imm_ptr`.
1118let place = match place.layout.ty.kind() {
1119 ty::Dynamic(data, _) => {
1120// Dropping a trait object. Need to find actual drop fn.
1121self.unpack_dyn_trait(&place, data)?
1122}
1123_ => {
1124if 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!(
1125 instance,
1126 ty::Instance::resolve_drop_glue(*self.tcx, place.layout.ty)
1127 );
1128place1129 }
1130 };
11311132let instance = {
1133let _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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(1133u32),
::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);
1134 ty::Instance::resolve_drop_glue(*self.tcx, place.layout.ty)
1135 };
1136let fn_abi = self.fn_abi_of_instance_no_deduced_attrs(instance, ty::List::empty())?;
11371138let ref_ty = Ty::new_mut_ref(self.tcx.tcx, self.tcx.lifetimes.re_erased, place.layout.ty);
1139let arg = self.mplace_to_imm_ptr(&place, Some(ref_ty))?;
11401141let ret = MPlaceTy::fake_alloc_zst(self.layout_of(self.tcx.types.unit)?);
11421143self.init_fn_call(
1144 FnVal::Instance(instance),
1145 (ExternAbi::Rust, Some(fn_abi)),
1146&[FnArg::Copy(arg.into())],
1147false,
1148&ret.into(),
1149Some(target),
1150unwind,
1151 )
1152 }
11531154/// Pops the current frame from the stack, copies the return value to the caller, deallocates
1155 /// the memory for allocated locals, and jumps to an appropriate place.
1156 ///
1157 /// If `unwinding` is `false`, then we are performing a normal return
1158 /// from a function. In this case, we jump back into the frame of the caller,
1159 /// and continue execution as normal.
1160 ///
1161 /// If `unwinding` is `true`, then we are in the middle of a panic,
1162 /// and need to unwind this frame. In this case, we jump to the
1163 /// `cleanup` block for the function, which is responsible for running
1164 /// `Drop` impls for any locals that have been initialized at this point.
1165 /// The cleanup block ends with a special `Resume` terminator, which will
1166 /// cause us to continue unwinding.
1167{}
#[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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(1167u32),
::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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs:1172",
"rustc_const_eval::interpret::call", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(1172u32),
::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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs:1198",
"rustc_const_eval::interpret::call",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/interpret/call.rs"),
::tracing_core::__macro_support::Option::Some(1198u32),
::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")]1168pub(super) fn return_from_current_stack_frame(
1169&mut self,
1170 unwinding: bool,
1171 ) -> InterpResult<'tcx> {
1172info!(
1173"popping stack frame ({})",
1174if unwinding { "during unwinding" } else { "returning from function" }
1175 );
11761177// Check `unwinding`.
1178assert_eq!(
1179 unwinding,
1180match self.frame().loc {
1181 Left(loc) => self.body().basic_blocks[loc.block].is_cleanup,
1182 Right(_) => true,
1183 }
1184 );
1185if unwinding && self.frame_idx() == 0 {
1186throw_ub_format!("unwinding past the topmost frame of the stack");
1187 }
11881189// Get out the return value. Must happen *before* the frame is popped as we have to get the
1190 // local's value out.
1191let return_op =
1192self.local_to_op(mir::RETURN_PLACE, None).expect("return place should always be live");
1193// Remove the frame from the stack.
1194let frame = self.pop_stack_frame_raw()?;
1195// Copy the return value and remember the return continuation.
1196if !unwinding {
1197self.copy_op_allow_transmute(&return_op, frame.return_place())?;
1198trace!("return value: {:?}", self.dump_place(frame.return_place()));
1199 }
1200let return_cont = frame.return_cont();
1201// Finish popping the stack frame.
1202let return_action = self.cleanup_stack_frame(unwinding, frame)?;
1203// Jump to the next block.
1204match return_action {
1205 ReturnAction::Normal => {}
1206 ReturnAction::NoJump => {
1207// The hook already did everything.
1208return interp_ok(());
1209 }
1210 ReturnAction::NoCleanup => {
1211// If we are not doing cleanup, also skip everything else.
1212assert!(self.stack().is_empty(), "only the topmost frame should ever be leaked");
1213assert!(!unwinding, "tried to skip cleanup during unwinding");
1214// Don't jump anywhere.
1215return interp_ok(());
1216 }
1217 }
12181219// Normal return, figure out where to jump.
1220if unwinding {
1221// Follow the unwind edge.
1222match return_cont {
1223 ReturnContinuation::Goto { unwind, .. } => {
1224// This must be the very last thing that happens, since it can in fact push a new stack frame.
1225self.unwind_to_block(unwind)
1226 }
1227 ReturnContinuation::Stop { .. } => {
1228panic!("encountered ReturnContinuation::Stop when unwinding!")
1229 }
1230 }
1231 } else {
1232// Follow the normal return edge.
1233match return_cont {
1234 ReturnContinuation::Goto { ret, .. } => self.return_to_block(ret),
1235 ReturnContinuation::Stop { .. } => {
1236assert!(
1237self.stack().is_empty(),
1238"only the bottommost frame can have ReturnContinuation::Stop"
1239);
1240 interp_ok(())
1241 }
1242 }
1243 }
1244 }
1245}