Skip to main content

rustc_const_eval/interpret/
intrinsics.rs

1//! Intrinsics and other functions that the interpreter executes without
2//! looking at their MIR. Intrinsics/functions supported here are shared by CTFE
3//! and miri.
4
5mod simd;
6
7use std::assert_matches;
8
9use rustc_abi::{FieldIdx, HasDataLayout, Size, VariantIdx};
10use rustc_apfloat::ieee::{Double, Half, Quad, Single};
11use rustc_ast::{IntTy, UintTy};
12use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, read_target_uint, write_target_uint};
13use rustc_middle::mir::{self, BinOp, ConstValue, NonDivergingIntrinsic};
14use rustc_middle::ty::layout::TyAndLayout;
15use rustc_middle::ty::{FloatTy, Ty, TyCtxt, TypeVisitableExt};
16use rustc_middle::{bug, span_bug, ty};
17use rustc_span::{Symbol, sym};
18use tracing::trace;
19
20use super::memory::MemoryKind;
21use super::util::ensure_monomorphic_enough;
22use super::{
23    AllocId, CheckInAllocMsg, ImmTy, InterpCx, InterpResult, Machine, OpTy, PlaceTy, Pointer,
24    PointerArithmetic, Projectable, Provenance, Scalar, err_ub_format, err_unsup_format, interp_ok,
25    throw_inval, throw_ub, throw_ub_format,
26};
27use crate::interpret::{MPlaceTy, Writeable};
28
29#[derive(#[automatically_derived]
impl ::core::marker::Copy for MulAddType { }Copy, #[automatically_derived]
impl ::core::clone::Clone for MulAddType {
    #[inline]
    fn clone(&self) -> MulAddType { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for MulAddType {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                MulAddType::Fused => "Fused",
                MulAddType::Nondeterministic => "Nondeterministic",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for MulAddType {
    #[inline]
    fn eq(&self, other: &MulAddType) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MulAddType {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
30enum MulAddType {
31    /// Used with `fma` and `simd_fma`, always uses fused-multiply-add
32    Fused,
33    /// Used with `fmuladd` and `simd_relaxed_fma`, nondeterministically determines whether to use
34    /// fma or simple multiply-add
35    Nondeterministic,
36}
37
38#[derive(#[automatically_derived]
impl ::core::marker::Copy for MinMax { }Copy, #[automatically_derived]
impl ::core::clone::Clone for MinMax {
    #[inline]
    fn clone(&self) -> MinMax { *self }
}Clone)]
39pub(crate) enum MinMax {
40    /// The IEEE-2019 `minimum` operation - see `f32::minimum` etc.
41    /// In particular, `-0.0` is considered smaller than `+0.0` and
42    /// if either input is NaN, the result is NaN.
43    Minimum,
44    /// The IEEE-2019 `minimumNumber` operation but with non-deterministic signed zero handling
45    /// (like in IEEE-2008 `minNum`) - see `f32::min` etc.
46    /// In particular, if the inputs are `-0.0` and `+0.0`, the result is non-deterministic,
47    /// and if one argument is NaN (quiet or signaling), the other one is returned.
48    MinimumNumberNsz,
49    /// The IEEE-2019 `maximum` operation - see `f32::maximum` etc.
50    /// In particular, `-0.0` is considered smaller than `+0.0` and
51    /// if either input is NaN, the result is NaN.
52    Maximum,
53    /// The IEEE-2019 `maximumNumber` operation but with non-deterministic signed zero handling
54    /// (like in IEEE-2008 `maxNum`) - see `f32::max` etc.
55    /// In particular, if the inputs are `-0.0` and `+0.0`, the result is non-deterministic,
56    /// and if one argument is NaN (quiet or signaling), the other one is returned.
57    MaximumNumberNsz,
58}
59
60/// Whether two types `T` and `U` are compatible when a value of type `T` is passed as a c-variadic
61/// argument and read as a value of type `U`.
62enum VarArgCompatible {
63    /// `T` and `U` are compatible, e.g.
64    ///
65    /// - They're the same type.
66    /// - One is `usize`/`isize`, the other an integer type of the same width
67    /// and sign on the current target.
68    /// - They are compatible pointer types (see the exact rules below).
69    Compatible,
70    /// `T` and `U` are definitely not compatible.
71    Incompatible,
72    /// `T` and `U` are corresponding signed and unsigned integer types.
73    CastIntTo { source_is_signed: bool },
74}
75
76/// Directly returns an `Allocation` containing an absolute path representation of the given type.
77pub(crate) fn alloc_type_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> (AllocId, u64) {
78    let path = crate::util::type_name(tcx, ty);
79    let bytes = path.into_bytes();
80    let len = bytes.len().try_into().unwrap();
81    (tcx.allocate_bytes_dedup(bytes, CTFE_ALLOC_SALT), len)
82}
83impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
84    /// Generates a value of `TypeId` for `ty` in-place.
85    pub(crate) fn write_type_id(
86        &mut self,
87        ty: Ty<'tcx>,
88        dest: &impl Writeable<'tcx, M::Provenance>,
89    ) -> InterpResult<'tcx, ()> {
90        if true {
    if !!ty.has_erasable_regions() {
        {
            ::core::panicking::panic_fmt(format_args!("type {0:?} has regions that need erasing before writing a TypeId",
                    ty));
        }
    };
};debug_assert!(
91            !ty.has_erasable_regions(),
92            "type {ty:?} has regions that need erasing before writing a TypeId",
93        );
94
95        let tcx = self.tcx;
96        let type_id_hash = tcx.type_id_hash(ty).as_u128();
97        let op = self.const_val_to_op(
98            ConstValue::Scalar(Scalar::from_u128(type_id_hash)),
99            tcx.types.u128,
100            None,
101        )?;
102        self.copy_op_allow_transmute(&op, dest)?;
103
104        // Give the each pointer-sized chunk provenance that knows about the type id.
105        // Here we rely on `TypeId` being a newtype around an array of pointers, so we
106        // first project to its only field and then the array elements.
107        let alloc_id = tcx.reserve_and_set_type_id_alloc(ty);
108        let arr = self.project_field(dest, FieldIdx::ZERO)?;
109        let mut elem_iter = self.project_array_fields(&arr)?;
110        while let Some((_, elem)) = elem_iter.next(self)? {
111            // Decorate this part of the hash with provenance; leave the integer part unchanged.
112            let hash_fragment = self.read_scalar(&elem)?.to_target_usize(&tcx)?;
113            let ptr = Pointer::new(alloc_id.into(), Size::from_bytes(hash_fragment));
114            let ptr = self.global_root_pointer(ptr)?;
115            let val = Scalar::from_pointer(ptr, &tcx);
116            self.write_scalar(val, &elem)?;
117        }
118        interp_ok(())
119    }
120
121    /// Read a value of type `TypeId`, returning the type it represents.
122    pub(crate) fn read_type_id(
123        &self,
124        op: &OpTy<'tcx, M::Provenance>,
125    ) -> InterpResult<'tcx, Ty<'tcx>> {
126        // `TypeId` is a newtype around an array of pointers. All pointers must have the same
127        // provenance, and that provenance represents the type.
128        let ptr_size = self.pointer_size().bytes_usize();
129        let arr = self.project_field(op, FieldIdx::ZERO)?;
130
131        let mut ty_and_hash = None;
132        let mut elem_iter = self.project_array_fields(&arr)?;
133        while let Some((idx, elem)) = elem_iter.next(self)? {
134            let elem = self.read_pointer(&elem)?;
135            let (elem_ty, elem_hash) = self.get_ptr_type_id(elem)?;
136            // If this is the first element, remember the type and its hash.
137            // If this is not the first element, ensure it is consistent with the previous ones.
138            let full_hash = match ty_and_hash {
139                None => {
140                    let hash = self.tcx.type_id_hash(elem_ty).as_u128();
141                    let mut hash_bytes = [0u8; 16];
142                    write_target_uint(self.data_layout().endian, &mut hash_bytes, hash).unwrap();
143                    ty_and_hash = Some((elem_ty, hash_bytes));
144                    hash_bytes
145                }
146                Some((ty, hash_bytes)) => {
147                    if ty != elem_ty {
148                        do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid `TypeId` value: not all bytes carry the same type id metadata"))
                })));throw_ub_format!(
149                            "invalid `TypeId` value: not all bytes carry the same type id metadata"
150                        );
151                    }
152                    hash_bytes
153                }
154            };
155            // Ensure the elem_hash matches the corresponding part of the full hash.
156            let hash_frag = &full_hash[(idx as usize) * ptr_size..][..ptr_size];
157            if read_target_uint(self.data_layout().endian, hash_frag).unwrap() != elem_hash.into() {
158                do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid `TypeId` value: the hash does not match the type id metadata"))
                })));throw_ub_format!(
159                    "invalid `TypeId` value: the hash does not match the type id metadata"
160                );
161            }
162        }
163
164        interp_ok(ty_and_hash.unwrap().0)
165    }
166
167    /// Returns `true` if emulation happened.
168    /// Here we implement the intrinsics that are common to all Miri instances; individual machines can add their own
169    /// intrinsic handling.
170    pub fn eval_intrinsic(
171        &mut self,
172        instance: ty::Instance<'tcx>,
173        args: &[OpTy<'tcx, M::Provenance>],
174        dest: &PlaceTy<'tcx, M::Provenance>,
175        ret: Option<mir::BasicBlock>,
176    ) -> InterpResult<'tcx, bool> {
177        let instance_args = instance.args;
178        let intrinsic_name = self.tcx.item_name(instance.def_id());
179
180        if intrinsic_name.as_str().starts_with("simd_") {
181            return self.eval_simd_intrinsic(intrinsic_name, instance_args, args, dest, ret);
182        }
183
184        let tcx = self.tcx.tcx;
185
186        match intrinsic_name {
187            sym::type_name => {
188                let tp_ty = instance.args.type_at(0);
189                ensure_monomorphic_enough(tcx, tp_ty)?;
190                let (alloc_id, meta) = alloc_type_name(tcx, tp_ty);
191                let val = ConstValue::Slice { alloc_id, meta };
192                let val = self.const_val_to_op(val, dest.layout.ty, Some(dest.layout))?;
193                self.copy_op(&val, dest)?;
194            }
195            sym::needs_drop => {
196                let tp_ty = instance.args.type_at(0);
197                ensure_monomorphic_enough(tcx, tp_ty)?;
198                let val = ConstValue::from_bool(tp_ty.needs_drop(tcx, self.typing_env));
199                let val = self.const_val_to_op(val, tcx.types.bool, Some(dest.layout))?;
200                self.copy_op(&val, dest)?;
201            }
202            sym::type_id => {
203                let tp_ty = instance.args.type_at(0);
204                ensure_monomorphic_enough(tcx, tp_ty)?;
205                self.write_type_id(tp_ty, dest)?;
206            }
207            sym::type_id_eq => {
208                let a_ty = self.read_type_id(&args[0])?;
209                let b_ty = self.read_type_id(&args[1])?;
210                self.write_scalar(Scalar::from_bool(a_ty == b_ty), dest)?;
211            }
212            sym::size_of => {
213                let tp_ty = instance.args.type_at(0);
214                let layout = self.layout_of(tp_ty)?;
215                if !layout.is_sized() {
216                    ::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
    format_args!("unsized type for `size_of`"));span_bug!(self.cur_span(), "unsized type for `size_of`");
217                }
218                let val = layout.size.bytes();
219                self.write_scalar(Scalar::from_target_usize(val, self), dest)?;
220            }
221            sym::align_of => {
222                let tp_ty = instance.args.type_at(0);
223                let layout = self.layout_of(tp_ty)?;
224                if !layout.is_sized() {
225                    ::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
    format_args!("unsized type for `align_of`"));span_bug!(self.cur_span(), "unsized type for `align_of`");
226                }
227                let val = layout.align.bytes();
228                self.write_scalar(Scalar::from_target_usize(val, self), dest)?;
229            }
230            sym::offset_of => {
231                let tp_ty = instance.args.type_at(0);
232
233                let variant = self.read_scalar(&args[0])?.to_u32()?;
234                let field = self.read_scalar(&args[1])?.to_u32()? as usize;
235
236                let layout = self.layout_of(tp_ty)?;
237                let cx = ty::layout::LayoutCx::new(*self.tcx, self.typing_env);
238
239                let layout = layout.for_variant(&cx, VariantIdx::from_u32(variant));
240                let offset = layout.fields.offset(field).bytes();
241
242                self.write_scalar(Scalar::from_target_usize(offset, self), dest)?;
243            }
244            sym::variant_count => {
245                let tp_ty = instance.args.type_at(0);
246                let ty = match tp_ty.kind() {
247                    // Pattern types have the same number of variants as their base type.
248                    // Even if we restrict e.g. which variants are valid, the variants are essentially just uninhabited.
249                    // And `Result<(), !>` still has two variants according to `variant_count`.
250                    ty::Pat(base, _) => *base,
251                    _ => tp_ty,
252                };
253                let val = match ty.kind() {
254                    // Correctly handles non-monomorphic calls, so there is no need for ensure_monomorphic_enough.
255                    ty::Adt(adt, _) => {
256                        ConstValue::from_target_usize(adt.variants().len() as u64, &tcx)
257                    }
258                    ty::Alias(..) | ty::Param(_) | ty::Placeholder(_) | ty::Infer(_) => {
259                        do yeet ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::TooGeneric)throw_inval!(TooGeneric)
260                    }
261                    ty::Pat(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
262                    ty::Bound(_, _) => ::rustc_middle::util::bug::bug_fmt(format_args!("bound ty during ctfe"))bug!("bound ty during ctfe"),
263                    ty::Bool
264                    | ty::Char
265                    | ty::Int(_)
266                    | ty::Uint(_)
267                    | ty::Float(_)
268                    | ty::Foreign(_)
269                    | ty::Str
270                    | ty::Array(_, _)
271                    | ty::Slice(_)
272                    | ty::RawPtr(_, _)
273                    | ty::Ref(_, _, _)
274                    | ty::FnDef(_, _)
275                    | ty::FnPtr(..)
276                    | ty::Dynamic(_, _)
277                    | ty::Closure(_, _)
278                    | ty::CoroutineClosure(_, _)
279                    | ty::Coroutine(_, _)
280                    | ty::CoroutineWitness(..)
281                    | ty::UnsafeBinder(_)
282                    | ty::Never
283                    | ty::Tuple(_)
284                    | ty::Error(_) => ConstValue::from_target_usize(0u64, &tcx),
285                };
286                let val = self.const_val_to_op(val, dest.layout.ty, Some(dest.layout))?;
287                self.copy_op(&val, dest)?;
288            }
289
290            sym::caller_location => {
291                let span = self.find_closest_untracked_caller_location();
292                let val = self.tcx.span_as_caller_location(span);
293                let val =
294                    self.const_val_to_op(val, self.tcx.caller_location_ty(), Some(dest.layout))?;
295                self.copy_op(&val, dest)?;
296            }
297
298            sym::align_of_val | sym::size_of_val => {
299                // Avoid `deref_pointer` -- this is not a deref, the ptr does not have to be
300                // dereferenceable!
301                let place = self.imm_ptr_to_mplace(&self.read_immediate(&args[0])?)?;
302                let (size, align) = self
303                    .size_and_align_of_val(&place)?
304                    .ok_or_else(|| ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("`extern type` does not have known layout"))
            })))err_unsup_format!("`extern type` does not have known layout"))?;
305
306                let result = match intrinsic_name {
307                    sym::align_of_val => align.bytes(),
308                    sym::size_of_val => size.bytes(),
309                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
310                };
311
312                self.write_scalar(Scalar::from_target_usize(result, self), dest)?;
313            }
314
315            sym::fadd_algebraic
316            | sym::fsub_algebraic
317            | sym::fmul_algebraic
318            | sym::fdiv_algebraic
319            | sym::frem_algebraic => {
320                let a = self.read_immediate(&args[0])?;
321                let b = self.read_immediate(&args[1])?;
322
323                let op = match intrinsic_name {
324                    sym::fadd_algebraic => BinOp::Add,
325                    sym::fsub_algebraic => BinOp::Sub,
326                    sym::fmul_algebraic => BinOp::Mul,
327                    sym::fdiv_algebraic => BinOp::Div,
328                    sym::frem_algebraic => BinOp::Rem,
329
330                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
331                };
332
333                let res = self.binary_op(op, &a, &b)?;
334                // `binary_op` already called `generate_nan` if needed.
335                let res = M::apply_float_nondet(self, res)?;
336                self.write_immediate(*res, dest)?;
337            }
338
339            sym::ctpop
340            | sym::cttz
341            | sym::cttz_nonzero
342            | sym::ctlz
343            | sym::ctlz_nonzero
344            | sym::bswap
345            | sym::bitreverse => {
346                let ty = instance_args.type_at(0);
347                let layout = self.layout_of(ty)?;
348                let val = self.read_scalar(&args[0])?;
349
350                let out_val = self.numeric_intrinsic(intrinsic_name, val, layout, dest.layout)?;
351                self.write_scalar(out_val, dest)?;
352            }
353            sym::saturating_add | sym::saturating_sub => {
354                let l = self.read_immediate(&args[0])?;
355                let r = self.read_immediate(&args[1])?;
356                let val = self.saturating_arith(
357                    if intrinsic_name == sym::saturating_add { BinOp::Add } else { BinOp::Sub },
358                    &l,
359                    &r,
360                )?;
361                self.write_scalar(val, dest)?;
362            }
363            sym::discriminant_value => {
364                let place = self.deref_pointer(&args[0])?;
365                let variant = self.read_discriminant(&place)?;
366                let discr = self.discriminant_for_variant(place.layout.ty, variant)?;
367                self.write_immediate(*discr, dest)?;
368            }
369            sym::exact_div => {
370                let l = self.read_immediate(&args[0])?;
371                let r = self.read_immediate(&args[1])?;
372                self.exact_div(&l, &r, dest)?;
373            }
374            sym::copy => {
375                self.copy_intrinsic(&args[0], &args[1], &args[2], /*nonoverlapping*/ false)?;
376            }
377            sym::write_bytes => {
378                self.write_bytes_intrinsic(&args[0], &args[1], &args[2], "write_bytes")?;
379            }
380            sym::compare_bytes => {
381                let result = self.compare_bytes_intrinsic(&args[0], &args[1], &args[2])?;
382                self.write_scalar(result, dest)?;
383            }
384            sym::arith_offset => {
385                let ptr = self.read_pointer(&args[0])?;
386                let offset_count = self.read_target_isize(&args[1])?;
387                let pointee_ty = instance_args.type_at(0);
388
389                let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
390                let offset_bytes = offset_count.wrapping_mul(pointee_size);
391                let offset_ptr = ptr.wrapping_signed_offset(offset_bytes, self);
392                self.write_pointer(offset_ptr, dest)?;
393            }
394            sym::ptr_offset_from | sym::ptr_offset_from_unsigned => {
395                let a = self.read_pointer(&args[0])?;
396                let b = self.read_pointer(&args[1])?;
397
398                let usize_layout = self.layout_of(self.tcx.types.usize)?;
399                let isize_layout = self.layout_of(self.tcx.types.isize)?;
400
401                // Get offsets for both that are at least relative to the same base.
402                // With `OFFSET_IS_ADDR` this is trivial; without it we need either
403                // two integers or two pointers into the same allocation.
404                let (a_offset, b_offset, is_addr) = if M::Provenance::OFFSET_IS_ADDR {
405                    (a.addr().bytes(), b.addr().bytes(), /*is_addr*/ true)
406                } else {
407                    match (self.ptr_try_get_alloc_id(a, 0), self.ptr_try_get_alloc_id(b, 0)) {
408                        (Err(a), Err(b)) => {
409                            // Neither pointer points to an allocation, so they are both absolute.
410                            (a, b, /*is_addr*/ true)
411                        }
412                        (Ok((a_alloc_id, a_offset, _)), Ok((b_alloc_id, b_offset, _)))
413                            if a_alloc_id == b_alloc_id =>
414                        {
415                            // Found allocation for both, and it's the same.
416                            // Use these offsets for distance calculation.
417                            (a_offset.bytes(), b_offset.bytes(), /*is_addr*/ false)
418                        }
419                        _ => {
420                            // Not into the same allocation -- this is UB.
421                            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}` called on two different pointers that are not both derived from the same allocation",
                            intrinsic_name))
                })));throw_ub_format!(
422                                "`{name}` called on two different pointers that are not both derived from the same allocation",
423                                name = intrinsic_name,
424                            );
425                        }
426                    }
427                };
428
429                // Compute distance: a - b.
430                let dist = {
431                    // Addresses are unsigned, so this is a `usize` computation. We have to do the
432                    // overflow check separately anyway.
433                    let (val, overflowed) = {
434                        let a_offset = ImmTy::from_uint(a_offset, usize_layout);
435                        let b_offset = ImmTy::from_uint(b_offset, usize_layout);
436                        self.binary_op(BinOp::SubWithOverflow, &a_offset, &b_offset)?
437                            .to_scalar_pair()
438                    };
439                    if overflowed.to_bool()? {
440                        // a < b
441                        if intrinsic_name == sym::ptr_offset_from_unsigned {
442                            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`ptr_offset_from_unsigned` called when first pointer has smaller {2} than second: {0} < {1}",
                            a_offset, b_offset,
                            if is_addr { "address" } else { "offset" }))
                })));throw_ub_format!(
443                                "`ptr_offset_from_unsigned` called when first pointer has smaller {is_addr} than second: {a_offset} < {b_offset}",
444                                a_offset = a_offset,
445                                b_offset = b_offset,
446                                is_addr = if is_addr { "address" } else { "offset" },
447                            );
448                        }
449                        // The signed form of the intrinsic allows this. If we interpret the
450                        // difference as isize, we'll get the proper signed difference. If that
451                        // seems *positive* or equal to isize::MIN, they were more than isize::MAX apart.
452                        let dist = val.to_target_isize(self)?;
453                        if dist >= 0 || i128::from(dist) == self.pointer_size().signed_int_min() {
454                            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}` called when first pointer is too far before second",
                            intrinsic_name))
                })));throw_ub_format!(
455                                "`{intrinsic_name}` called when first pointer is too far before second"
456                            );
457                        }
458                        dist
459                    } else {
460                        // b >= a
461                        let dist = val.to_target_isize(self)?;
462                        // If converting to isize produced a *negative* result, we had an overflow
463                        // because they were more than isize::MAX apart.
464                        if dist < 0 {
465                            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}` called when first pointer is too far ahead of second",
                            intrinsic_name))
                })));throw_ub_format!(
466                                "`{intrinsic_name}` called when first pointer is too far ahead of second"
467                            );
468                        }
469                        dist
470                    }
471                };
472
473                // Check that the memory between them is dereferenceable at all, starting from the
474                // origin pointer: `dist` is `a - b`, so it is based on `b`.
475                self.check_ptr_access_signed(b, dist, CheckInAllocMsg::Dereferenceable)
476                    .map_err_kind(|_| {
477                        // This could mean they point to different allocations, or they point to the same allocation
478                        // but not the entire range between the pointers is in-bounds.
479                        if let Ok((a_alloc_id, ..)) = self.ptr_try_get_alloc_id(a, 0)
480                            && let Ok((b_alloc_id, ..)) = self.ptr_try_get_alloc_id(b, 0)
481                            && a_alloc_id == b_alloc_id
482                        {
483                            ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("`{0}` called on two different pointers where the memory range between them is not in-bounds of an allocation",
                        intrinsic_name))
            })))err_ub_format!(
484                                "`{intrinsic_name}` called on two different pointers where the memory range between them is not in-bounds of an allocation"
485                            )
486                        } else {
487                            ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("`{0}` called on two different pointers that are not both derived from the same allocation",
                        intrinsic_name))
            })))err_ub_format!(
488                                "`{intrinsic_name}` called on two different pointers that are not both derived from the same allocation"
489                            )
490                        }
491                    })?;
492                // Then check that this is also dereferenceable from `a`. This ensures that they are
493                // derived from the same allocation.
494                self.check_ptr_access_signed(
495                    a,
496                    dist.checked_neg().unwrap(), // i64::MIN is impossible as no allocation can be that large
497                    CheckInAllocMsg::Dereferenceable,
498                )
499                .map_err_kind(|_| {
500                    // Make the error more specific.
501                    ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("`{0}` called on two different pointers that are not both derived from the same allocation",
                        intrinsic_name))
            })))err_ub_format!(
502                        "`{intrinsic_name}` called on two different pointers that are not both derived from the same allocation"
503                    )
504                })?;
505
506                // Perform division by size to compute return value.
507                let ret_layout = if intrinsic_name == sym::ptr_offset_from_unsigned {
508                    if !(0 <= dist && dist <= self.target_isize_max()) {
    ::core::panicking::panic("assertion failed: 0 <= dist && dist <= self.target_isize_max()")
};assert!(0 <= dist && dist <= self.target_isize_max());
509                    usize_layout
510                } else {
511                    if !(self.target_isize_min() <= dist && dist <= self.target_isize_max()) {
    ::core::panicking::panic("assertion failed: self.target_isize_min() <= dist && dist <= self.target_isize_max()")
};assert!(self.target_isize_min() <= dist && dist <= self.target_isize_max());
512                    isize_layout
513                };
514                let pointee_layout = self.layout_of(instance_args.type_at(0))?;
515                // If ret_layout is unsigned, we checked that so is the distance, so we are good.
516                let val = ImmTy::from_int(dist, ret_layout);
517                let size = ImmTy::from_int(pointee_layout.size.bytes(), ret_layout);
518                self.exact_div(&val, &size, dest)?;
519            }
520
521            sym::black_box => {
522                // These just return their argument
523                self.copy_op(&args[0], dest)?;
524            }
525            sym::raw_eq => {
526                let result = self.raw_eq_intrinsic(&args[0], &args[1])?;
527                self.write_scalar(result, dest)?;
528            }
529            sym::typed_swap_nonoverlapping => {
530                self.typed_swap_nonoverlapping_intrinsic(&args[0], &args[1])?;
531            }
532
533            sym::vtable_size => {
534                let ptr = self.read_pointer(&args[0])?;
535                // `None` because we don't know which trait to expect here; any vtable is okay.
536                let (size, _align) = self.get_vtable_size_and_align(ptr, None)?;
537                self.write_scalar(Scalar::from_target_usize(size.bytes(), self), dest)?;
538            }
539            sym::vtable_align => {
540                let ptr = self.read_pointer(&args[0])?;
541                // `None` because we don't know which trait to expect here; any vtable is okay.
542                let (_size, align) = self.get_vtable_size_and_align(ptr, None)?;
543                self.write_scalar(Scalar::from_target_usize(align.bytes(), self), dest)?;
544            }
545
546            sym::minimum_number_nsz_f16 => {
547                self.float_minmax_intrinsic::<Half>(args, MinMax::MinimumNumberNsz, dest)?
548            }
549            sym::minimum_number_nsz_f32 => {
550                self.float_minmax_intrinsic::<Single>(args, MinMax::MinimumNumberNsz, dest)?
551            }
552            sym::minimum_number_nsz_f64 => {
553                self.float_minmax_intrinsic::<Double>(args, MinMax::MinimumNumberNsz, dest)?
554            }
555            sym::minimum_number_nsz_f128 => {
556                self.float_minmax_intrinsic::<Quad>(args, MinMax::MinimumNumberNsz, dest)?
557            }
558
559            sym::minimumf16 => self.float_minmax_intrinsic::<Half>(args, MinMax::Minimum, dest)?,
560            sym::minimumf32 => {
561                self.float_minmax_intrinsic::<Single>(args, MinMax::Minimum, dest)?
562            }
563            sym::minimumf64 => {
564                self.float_minmax_intrinsic::<Double>(args, MinMax::Minimum, dest)?
565            }
566            sym::minimumf128 => self.float_minmax_intrinsic::<Quad>(args, MinMax::Minimum, dest)?,
567
568            sym::maximum_number_nsz_f16 => {
569                self.float_minmax_intrinsic::<Half>(args, MinMax::MaximumNumberNsz, dest)?
570            }
571            sym::maximum_number_nsz_f32 => {
572                self.float_minmax_intrinsic::<Single>(args, MinMax::MaximumNumberNsz, dest)?
573            }
574            sym::maximum_number_nsz_f64 => {
575                self.float_minmax_intrinsic::<Double>(args, MinMax::MaximumNumberNsz, dest)?
576            }
577            sym::maximum_number_nsz_f128 => {
578                self.float_minmax_intrinsic::<Quad>(args, MinMax::MaximumNumberNsz, dest)?
579            }
580
581            sym::maximumf16 => self.float_minmax_intrinsic::<Half>(args, MinMax::Maximum, dest)?,
582            sym::maximumf32 => {
583                self.float_minmax_intrinsic::<Single>(args, MinMax::Maximum, dest)?
584            }
585            sym::maximumf64 => {
586                self.float_minmax_intrinsic::<Double>(args, MinMax::Maximum, dest)?
587            }
588            sym::maximumf128 => self.float_minmax_intrinsic::<Quad>(args, MinMax::Maximum, dest)?,
589
590            sym::copysignf16 => self.float_copysign_intrinsic::<Half>(args, dest)?,
591            sym::copysignf32 => self.float_copysign_intrinsic::<Single>(args, dest)?,
592            sym::copysignf64 => self.float_copysign_intrinsic::<Double>(args, dest)?,
593            sym::copysignf128 => self.float_copysign_intrinsic::<Quad>(args, dest)?,
594
595            sym::fabs => {
596                let arg = self.read_immediate(&args[0])?;
597                let ty::Float(float_ty) = arg.layout.ty.kind() else {
598                    ::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
    format_args!("non-float type for float intrinsic: {0}", arg.layout.ty));span_bug!(
599                        self.cur_span(),
600                        "non-float type for float intrinsic: {}",
601                        arg.layout.ty,
602                    );
603                };
604                let out_val = match float_ty {
605                    FloatTy::F16 => self.unop_float_intrinsic::<Half>(intrinsic_name, arg)?,
606                    FloatTy::F32 => self.unop_float_intrinsic::<Single>(intrinsic_name, arg)?,
607                    FloatTy::F64 => self.unop_float_intrinsic::<Double>(intrinsic_name, arg)?,
608                    FloatTy::F128 => self.unop_float_intrinsic::<Quad>(intrinsic_name, arg)?,
609                };
610                self.write_scalar(out_val, dest)?;
611            }
612
613            sym::floorf16 => self.float_round_intrinsic::<Half>(
614                args,
615                dest,
616                rustc_apfloat::Round::TowardNegative,
617            )?,
618            sym::floorf32 => self.float_round_intrinsic::<Single>(
619                args,
620                dest,
621                rustc_apfloat::Round::TowardNegative,
622            )?,
623            sym::floorf64 => self.float_round_intrinsic::<Double>(
624                args,
625                dest,
626                rustc_apfloat::Round::TowardNegative,
627            )?,
628            sym::floorf128 => self.float_round_intrinsic::<Quad>(
629                args,
630                dest,
631                rustc_apfloat::Round::TowardNegative,
632            )?,
633
634            sym::ceilf16 => self.float_round_intrinsic::<Half>(
635                args,
636                dest,
637                rustc_apfloat::Round::TowardPositive,
638            )?,
639            sym::ceilf32 => self.float_round_intrinsic::<Single>(
640                args,
641                dest,
642                rustc_apfloat::Round::TowardPositive,
643            )?,
644            sym::ceilf64 => self.float_round_intrinsic::<Double>(
645                args,
646                dest,
647                rustc_apfloat::Round::TowardPositive,
648            )?,
649            sym::ceilf128 => self.float_round_intrinsic::<Quad>(
650                args,
651                dest,
652                rustc_apfloat::Round::TowardPositive,
653            )?,
654
655            sym::truncf16 => {
656                self.float_round_intrinsic::<Half>(args, dest, rustc_apfloat::Round::TowardZero)?
657            }
658            sym::truncf32 => {
659                self.float_round_intrinsic::<Single>(args, dest, rustc_apfloat::Round::TowardZero)?
660            }
661            sym::truncf64 => {
662                self.float_round_intrinsic::<Double>(args, dest, rustc_apfloat::Round::TowardZero)?
663            }
664            sym::truncf128 => {
665                self.float_round_intrinsic::<Quad>(args, dest, rustc_apfloat::Round::TowardZero)?
666            }
667
668            sym::roundf16 => self.float_round_intrinsic::<Half>(
669                args,
670                dest,
671                rustc_apfloat::Round::NearestTiesToAway,
672            )?,
673            sym::roundf32 => self.float_round_intrinsic::<Single>(
674                args,
675                dest,
676                rustc_apfloat::Round::NearestTiesToAway,
677            )?,
678            sym::roundf64 => self.float_round_intrinsic::<Double>(
679                args,
680                dest,
681                rustc_apfloat::Round::NearestTiesToAway,
682            )?,
683            sym::roundf128 => self.float_round_intrinsic::<Quad>(
684                args,
685                dest,
686                rustc_apfloat::Round::NearestTiesToAway,
687            )?,
688
689            sym::round_ties_even_f16 => self.float_round_intrinsic::<Half>(
690                args,
691                dest,
692                rustc_apfloat::Round::NearestTiesToEven,
693            )?,
694            sym::round_ties_even_f32 => self.float_round_intrinsic::<Single>(
695                args,
696                dest,
697                rustc_apfloat::Round::NearestTiesToEven,
698            )?,
699            sym::round_ties_even_f64 => self.float_round_intrinsic::<Double>(
700                args,
701                dest,
702                rustc_apfloat::Round::NearestTiesToEven,
703            )?,
704            sym::round_ties_even_f128 => self.float_round_intrinsic::<Quad>(
705                args,
706                dest,
707                rustc_apfloat::Round::NearestTiesToEven,
708            )?,
709            sym::fmaf16 => self.float_muladd_intrinsic::<Half>(args, dest, MulAddType::Fused)?,
710            sym::fmaf32 => self.float_muladd_intrinsic::<Single>(args, dest, MulAddType::Fused)?,
711            sym::fmaf64 => self.float_muladd_intrinsic::<Double>(args, dest, MulAddType::Fused)?,
712            sym::fmaf128 => self.float_muladd_intrinsic::<Quad>(args, dest, MulAddType::Fused)?,
713            sym::fmuladdf16 => {
714                self.float_muladd_intrinsic::<Half>(args, dest, MulAddType::Nondeterministic)?
715            }
716            sym::fmuladdf32 => {
717                self.float_muladd_intrinsic::<Single>(args, dest, MulAddType::Nondeterministic)?
718            }
719            sym::fmuladdf64 => {
720                self.float_muladd_intrinsic::<Double>(args, dest, MulAddType::Nondeterministic)?
721            }
722            sym::fmuladdf128 => {
723                self.float_muladd_intrinsic::<Quad>(args, dest, MulAddType::Nondeterministic)?
724            }
725
726            sym::va_copy => {
727                let va_list = self.deref_pointer(&args[0])?;
728                let key_mplace = self.va_list_key_field(&va_list)?;
729                let key = self.read_pointer(&key_mplace)?;
730
731                let varargs = self.get_ptr_va_list(key)?;
732                let copy_key = self.va_list_ptr(varargs.clone());
733
734                let copy_key_mplace = self.va_list_key_field(dest)?;
735                self.write_pointer(copy_key, &copy_key_mplace)?;
736            }
737
738            sym::va_end => {
739                let va_list = self.deref_pointer(&args[0])?;
740                let key_mplace = self.va_list_key_field(&va_list)?;
741                let key = self.read_pointer(&key_mplace)?;
742
743                self.deallocate_va_list(key)?;
744            }
745
746            sym::va_arg => {
747                let va_list = self.deref_pointer(&args[0])?;
748                let key_mplace = self.va_list_key_field(&va_list)?;
749                let key = self.read_pointer(&key_mplace)?;
750
751                // Invalidate the old list and get its content. We'll recreate the
752                // new list (one element shorter) below.
753                let mut varargs = self.deallocate_va_list(key)?;
754
755                let Some(arg_mplace) = varargs.pop_front() else {
756                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::VaArgOutOfBounds);throw_ub!(VaArgOutOfBounds);
757                };
758
759                // Error when the caller's argument is not c-variadic compatible with the type
760                // requested by the callee.
761                self.validate_c_variadic_argument(&arg_mplace, dest.layout)?;
762
763                // Copy the argument, allowing a transmute and relying on the compatibility check
764                // rejecting conversions between types of different size.
765                self.copy_op_allow_transmute(&arg_mplace, dest)?;
766
767                // Update the VaList pointer.
768                let new_key = self.va_list_ptr(varargs);
769                self.write_pointer(new_key, &key_mplace)?;
770            }
771
772            // Unsupported intrinsic: skip the return_to_block below.
773            _ => return interp_ok(false),
774        }
775
776        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/intrinsics.rs:776",
                        "rustc_const_eval::interpret::intrinsics",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/intrinsics.rs"),
                        ::tracing_core::__macro_support::Option::Some(776u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::intrinsics"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("{0:?}",
                                                    self.dump_place(&dest.clone().into())) as &dyn Value))])
            });
    } else { ; }
};trace!("{:?}", self.dump_place(&dest.clone().into()));
777        self.return_to_block(ret)?;
778        interp_ok(true)
779    }
780
781    /// Validate whether the value and type passed by the caller are compatible with the type
782    /// requested by the callee. Based on section 7.16.1.1 of the C23 specification.
783    ///
784    /// The callee requesting a value of a type is valid when that type is compatible with the type
785    /// provided by the caller (see `validate_c_variadic_compatible_ty`) and, if both types are
786    /// integers of the same size but different signedness, the passed value must be representable
787    /// in both types.
788    fn validate_c_variadic_argument(
789        &mut self,
790        arg_mplace: &MPlaceTy<'tcx, M::Provenance>,
791        callee_type: TyAndLayout<'tcx>,
792    ) -> InterpResult<'tcx> {
793        let callee_ty = callee_type.ty;
794        let caller_ty = arg_mplace.layout.ty;
795
796        // Identical types are clearly compatible.
797        if caller_ty == callee_ty {
798            return interp_ok(());
799        }
800
801        // Types of different sizes can never be compatible.
802        if arg_mplace.layout.size != callee_type.size {
803            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("va_arg type mismatch: requested `{0}` is incompatible with next argument of type `{1}`",
                            callee_ty, caller_ty))
                })))throw_ub_format!(
804                "va_arg type mismatch: requested `{}` is incompatible with next argument of type `{}`",
805                callee_ty,
806                caller_ty,
807            )
808        }
809
810        match self.validate_c_variadic_compatible_ty(arg_mplace.layout.ty, callee_type.ty)? {
811            VarArgCompatible::Compatible => interp_ok(()),
812            VarArgCompatible::Incompatible => do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("va_arg type mismatch: requested `{0}` is incompatible with next argument of type `{1}`",
                            callee_ty, caller_ty))
                })))throw_ub_format!(
813                "va_arg type mismatch: requested `{}` is incompatible with next argument of type `{}`",
814                callee_ty,
815                caller_ty,
816            ),
817            VarArgCompatible::CastIntTo { source_is_signed } => {
818                // Check that the value can be represented in the target type.
819                let size = arg_mplace.layout.size;
820                let scalar = self.read_scalar(arg_mplace)?;
821                if scalar.to_int(size)? < 0 {
822                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("va_arg value mismatch: value `{0}_{1}` cannot be represented by type `{2}`",
                            if source_is_signed {
                                scalar.to_int(size)?.to_string()
                            } else { scalar.to_uint(size)?.to_string() }, caller_ty,
                            callee_ty))
                })))throw_ub_format!(
823                        "va_arg value mismatch: value `{value}_{caller_ty}` cannot be represented by type `{callee_ty}`",
824                        value = if source_is_signed {
825                            scalar.to_int(size)?.to_string()
826                        } else {
827                            scalar.to_uint(size)?.to_string()
828                        }
829                    )
830                }
831
832                interp_ok(())
833            }
834        }
835    }
836
837    /// Check whether the caller and callee type are compatible for c-variadic calls. Further
838    /// validation of the argument value may be needed to detect all UB.
839    ///
840    /// Types `T` and `U` are compatible when:
841    ///
842    /// - `T` and `U` are the same type.
843    /// - `T` and `U` are integer types of the same size.
844    /// - `T` and `U` are both pointers, and their target types are compatible.
845    /// - `T` is a pointer to [`std::ffi::c_void`] and `U` is a pointer to [`i8`] or [`u8`],
846    /// or vice versa.
847    fn validate_c_variadic_compatible_ty(
848        &mut self,
849        caller_type: Ty<'tcx>,
850        callee_type: Ty<'tcx>,
851    ) -> InterpResult<'tcx, VarArgCompatible> {
852        if caller_type == callee_type {
853            return interp_ok(VarArgCompatible::Compatible);
854        }
855
856        if self.layout_of(caller_type)?.size != self.layout_of(callee_type)?.size {
857            return interp_ok(VarArgCompatible::Incompatible);
858        }
859
860        // Any character type (`char`, `unsigned char` and `signed char`) is compatible with
861        // `void*`, so the signedness of `c_char` is irrelevant here.
862        let is_c_char = |ty: Ty<'_>| #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Uint(UintTy::U8) | ty::Int(IntTy::I8) => true,
    _ => false,
}matches!(ty.kind(), ty::Uint(UintTy::U8) | ty::Int(IntTy::I8));
863
864        match (caller_type.kind(), callee_type.kind()) {
865            (ty::RawPtr(caller_target_ty, _), ty::RawPtr(callee_target_ty, _)) => {
866                // In C, types can be qualified by a combination of `const`, `volatile` and
867                // `restrict`. These properties are irrelevant for the ABI, and don't have an
868                // equivalent in rust.
869
870                // Accept the cast if one type is pointer to void, and the other is a pointer to
871                // a character type (`char`, `unsigned char` and `signed char`).
872                if caller_target_ty.is_c_void(self.tcx.tcx) && is_c_char(*callee_target_ty) {
873                    return interp_ok(VarArgCompatible::Compatible);
874                }
875                if callee_target_ty.is_c_void(self.tcx.tcx) && is_c_char(*caller_target_ty) {
876                    return interp_ok(VarArgCompatible::Compatible);
877                }
878
879                // Accept the cast if both types are pointers to compatible types.
880                match self
881                    .validate_c_variadic_compatible_ty(*caller_target_ty, *callee_target_ty)?
882                {
883                    VarArgCompatible::Incompatible => interp_ok(VarArgCompatible::Incompatible),
884                    VarArgCompatible::Compatible => interp_ok(VarArgCompatible::Compatible),
885                    VarArgCompatible::CastIntTo { source_is_signed: _ } => {
886                        // The integer cast check is not needed when the value is behind a pointer.
887                        interp_ok(VarArgCompatible::Compatible)
888                    }
889                }
890            }
891            (ty::Int(_), ty::Uint(_)) => {
892                interp_ok(VarArgCompatible::CastIntTo { source_is_signed: true })
893            }
894            (ty::Uint(_), ty::Int(_)) => {
895                interp_ok(VarArgCompatible::CastIntTo { source_is_signed: false })
896            }
897            (ty::Int(_), ty::Int(_)) | (ty::Uint(_), ty::Uint(_)) => {
898                // E.g. cast between `usize` and `u64` on a 64-bit platform.
899                interp_ok(VarArgCompatible::Compatible)
900            }
901            _ => interp_ok(VarArgCompatible::Incompatible),
902        }
903    }
904
905    pub(super) fn eval_nondiverging_intrinsic(
906        &mut self,
907        intrinsic: &NonDivergingIntrinsic<'tcx>,
908    ) -> InterpResult<'tcx> {
909        match intrinsic {
910            NonDivergingIntrinsic::Assume(op) => {
911                let op = self.eval_operand(op, None)?;
912                let cond = self.read_scalar(&op)?.to_bool()?;
913                if !cond {
914                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`assume` called with `false`"))
                })));throw_ub_format!("`assume` called with `false`");
915                }
916                interp_ok(())
917            }
918            NonDivergingIntrinsic::CopyNonOverlapping(mir::CopyNonOverlapping {
919                count,
920                src,
921                dst,
922            }) => {
923                let src = self.eval_operand(src, None)?;
924                let dst = self.eval_operand(dst, None)?;
925                let count = self.eval_operand(count, None)?;
926                self.copy_intrinsic(&src, &dst, &count, /* nonoverlapping */ true)
927            }
928        }
929    }
930
931    pub fn numeric_intrinsic(
932        &self,
933        name: Symbol,
934        val: Scalar<M::Provenance>,
935        layout: TyAndLayout<'tcx>,
936        ret_layout: TyAndLayout<'tcx>,
937    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
938        if !layout.ty.is_integral() {
    {
        ::core::panicking::panic_fmt(format_args!("invalid type for numeric intrinsic: {0}",
                layout.ty));
    }
};assert!(layout.ty.is_integral(), "invalid type for numeric intrinsic: {}", layout.ty);
939        let bits = val.to_bits(layout.size)?; // these operations all ignore the sign
940        let extra = 128 - u128::from(layout.size.bits());
941        let bits_out = match name {
942            sym::ctpop => u128::from(bits.count_ones()),
943            sym::ctlz_nonzero | sym::cttz_nonzero if bits == 0 => {
944                do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}` called on 0",
                            name))
                })));throw_ub_format!("`{name}` called on 0");
945            }
946            sym::ctlz | sym::ctlz_nonzero => u128::from(bits.leading_zeros()) - extra,
947            sym::cttz | sym::cttz_nonzero => u128::from((bits << extra).trailing_zeros()) - extra,
948            sym::bswap => {
949                match (&layout, &ret_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!(layout, ret_layout);
950                (bits << extra).swap_bytes()
951            }
952            sym::bitreverse => {
953                match (&layout, &ret_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!(layout, ret_layout);
954                (bits << extra).reverse_bits()
955            }
956            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("not a numeric intrinsic: {0}",
        name))bug!("not a numeric intrinsic: {}", name),
957        };
958        interp_ok(Scalar::from_uint(bits_out, ret_layout.size))
959    }
960
961    pub fn exact_div(
962        &mut self,
963        a: &ImmTy<'tcx, M::Provenance>,
964        b: &ImmTy<'tcx, M::Provenance>,
965        dest: &PlaceTy<'tcx, M::Provenance>,
966    ) -> InterpResult<'tcx> {
967        match (&a.layout.ty, &b.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!(a.layout.ty, b.layout.ty);
968        {
    match a.layout.ty.kind() {
        ty::Int(..) | ty::Uint(..) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "ty::Int(..) | ty::Uint(..)", ::core::option::Option::None);
        }
    }
};assert_matches!(a.layout.ty.kind(), ty::Int(..) | ty::Uint(..));
969
970        // Performs an exact division, resulting in undefined behavior where
971        // `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`.
972        // First, check x % y != 0 (or if that computation overflows).
973        let rem = self.binary_op(BinOp::Rem, a, b)?;
974        // sign does not matter for 0 test, so `to_bits` is fine
975        if rem.to_scalar().to_bits(a.layout.size)? != 0 {
976            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("exact_div: {0} cannot be divided by {1} without remainder",
                            a, b))
                })))throw_ub_format!("exact_div: {a} cannot be divided by {b} without remainder")
977        }
978        // `Rem` says this is all right, so we can let `Div` do its job.
979        let res = self.binary_op(BinOp::Div, a, b)?;
980        self.write_immediate(*res, dest)
981    }
982
983    pub fn saturating_arith(
984        &self,
985        mir_op: BinOp,
986        l: &ImmTy<'tcx, M::Provenance>,
987        r: &ImmTy<'tcx, M::Provenance>,
988    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
989        match (&l.layout.ty, &r.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!(l.layout.ty, r.layout.ty);
990        {
    match l.layout.ty.kind() {
        ty::Int(..) | ty::Uint(..) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "ty::Int(..) | ty::Uint(..)", ::core::option::Option::None);
        }
    }
};assert_matches!(l.layout.ty.kind(), ty::Int(..) | ty::Uint(..));
991        {
    match mir_op {
        BinOp::Add | BinOp::Sub => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BinOp::Add | BinOp::Sub", ::core::option::Option::None);
        }
    }
};assert_matches!(mir_op, BinOp::Add | BinOp::Sub);
992
993        let (val, overflowed) =
994            self.binary_op(mir_op.wrapping_to_overflowing().unwrap(), l, r)?.to_scalar_pair();
995        interp_ok(if overflowed.to_bool()? {
996            let size = l.layout.size;
997            if l.layout.backend_repr.is_signed() {
998                // For signed ints the saturated value depends on the sign of the first
999                // term since the sign of the second term can be inferred from this and
1000                // the fact that the operation has overflowed (if either is 0 no
1001                // overflow can occur)
1002                let first_term: i128 = l.to_scalar().to_int(l.layout.size)?;
1003                if first_term >= 0 {
1004                    // Negative overflow not possible since the positive first term
1005                    // can only increase an (in range) negative term for addition
1006                    // or corresponding negated positive term for subtraction.
1007                    Scalar::from_int(size.signed_int_max(), size)
1008                } else {
1009                    // Positive overflow not possible for similar reason.
1010                    Scalar::from_int(size.signed_int_min(), size)
1011                }
1012            } else {
1013                // unsigned
1014                if mir_op == BinOp::Add {
1015                    // max unsigned
1016                    Scalar::from_uint(size.unsigned_int_max(), size)
1017                } else {
1018                    // underflow to 0
1019                    Scalar::from_uint(0u128, size)
1020                }
1021            }
1022        } else {
1023            val
1024        })
1025    }
1026
1027    /// Offsets a pointer by some multiple of its type, returning an error if the pointer leaves its
1028    /// allocation.
1029    pub fn ptr_offset_inbounds(
1030        &self,
1031        ptr: Pointer<Option<M::Provenance>>,
1032        offset_bytes: i64,
1033    ) -> InterpResult<'tcx, Pointer<Option<M::Provenance>>> {
1034        // The offset must be in bounds starting from `ptr`.
1035        self.check_ptr_access_signed(
1036            ptr,
1037            offset_bytes,
1038            CheckInAllocMsg::InboundsPointerArithmetic,
1039        )?;
1040        // This also implies that there is no overflow, so we are done.
1041        interp_ok(ptr.wrapping_signed_offset(offset_bytes, self))
1042    }
1043
1044    /// Copy `count*size_of::<T>()` many bytes from `*src` to `*dst`.
1045    pub(crate) fn copy_intrinsic(
1046        &mut self,
1047        src: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1048        dst: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1049        count: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1050        nonoverlapping: bool,
1051    ) -> InterpResult<'tcx> {
1052        let count = self.read_target_usize(count)?;
1053        let layout = self.layout_of(src.layout.ty.builtin_deref(true).unwrap())?;
1054        let (size, align) = (layout.size, layout.align.abi);
1055
1056        let size = self.compute_size_in_bytes(size, count).ok_or_else(|| {
1057            ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("overflow computing total size of `{0}`",
                        if nonoverlapping {
                            "copy_nonoverlapping"
                        } else { "copy" }))
            })))err_ub_format!(
1058                "overflow computing total size of `{name}`",
1059                name = if nonoverlapping { "copy_nonoverlapping" } else { "copy" }
1060            )
1061        })?;
1062
1063        let src = self.read_pointer(src)?;
1064        let dst = self.read_pointer(dst)?;
1065
1066        self.check_ptr_align(src, align)?;
1067        self.check_ptr_align(dst, align)?;
1068
1069        self.mem_copy(src, dst, size, nonoverlapping)
1070    }
1071
1072    /// Does a *typed* swap of `*left` and `*right`.
1073    fn typed_swap_nonoverlapping_intrinsic(
1074        &mut self,
1075        left: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1076        right: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1077    ) -> InterpResult<'tcx> {
1078        let left = self.deref_pointer(left)?;
1079        let right = self.deref_pointer(right)?;
1080        match (&left.layout, &right.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!(left.layout, right.layout);
1081        if !left.layout.is_sized() {
    ::core::panicking::panic("assertion failed: left.layout.is_sized()")
};assert!(left.layout.is_sized());
1082        let kind = MemoryKind::Stack;
1083        let temp = self.allocate(left.layout, kind)?;
1084        self.copy_op(&left, &temp)?; // checks alignment of `left`
1085
1086        // We want to always enforce non-overlapping, even if this is a scalar type.
1087        // Therefore we directly use the underlying `mem_copy` here.
1088        self.mem_copy(right.ptr(), left.ptr(), left.layout.size, /*nonoverlapping*/ true)?;
1089        // This means we also need to do the validation of the value that used to be in `right`
1090        // ourselves. This value is now in `left.` The one that started out in `left` already got
1091        // validated by the copy above.
1092        if M::enforce_validity(self, left.layout) {
1093            self.validate_operand(
1094                &left.clone().into(),
1095                M::enforce_validity_recursively(self, left.layout),
1096                /*reset_provenance_and_padding*/ true,
1097            )?;
1098        }
1099
1100        self.copy_op(&temp, &right)?; // checks alignment of `right`
1101
1102        self.deallocate_ptr(temp.ptr(), None, kind)?;
1103        interp_ok(())
1104    }
1105
1106    pub fn write_bytes_intrinsic(
1107        &mut self,
1108        dst: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1109        byte: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1110        count: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1111        name: &'static str,
1112    ) -> InterpResult<'tcx> {
1113        let layout = self.layout_of(dst.layout.ty.builtin_deref(true).unwrap())?;
1114
1115        let dst = self.read_pointer(dst)?;
1116        let byte = self.read_scalar(byte)?.to_u8()?;
1117        let count = self.read_target_usize(count)?;
1118
1119        // `checked_mul` enforces a too small bound (the correct one would probably be target_isize_max),
1120        // but no actual allocation can be big enough for the difference to be noticeable.
1121        let len = self
1122            .compute_size_in_bytes(layout.size, count)
1123            .ok_or_else(|| ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("overflow computing total size of `{0}`",
                        name))
            })))err_ub_format!("overflow computing total size of `{name}`"))?;
1124
1125        let bytes = std::iter::repeat_n(byte, len.bytes_usize());
1126        self.write_bytes_ptr(dst, bytes)
1127    }
1128
1129    pub(crate) fn compare_bytes_intrinsic(
1130        &mut self,
1131        left: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1132        right: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1133        byte_count: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1134    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
1135        let left = self.read_pointer(left)?;
1136        let right = self.read_pointer(right)?;
1137        let n = Size::from_bytes(self.read_target_usize(byte_count)?);
1138
1139        let left_bytes = self.read_bytes_ptr_strip_provenance(left, n)?;
1140        let right_bytes = self.read_bytes_ptr_strip_provenance(right, n)?;
1141
1142        // `Ordering`'s discriminants are -1/0/+1, so casting does the right thing.
1143        let result = Ord::cmp(left_bytes, right_bytes) as i32;
1144        interp_ok(Scalar::from_i32(result))
1145    }
1146
1147    pub(crate) fn raw_eq_intrinsic(
1148        &mut self,
1149        lhs: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1150        rhs: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1151    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
1152        let layout = self.layout_of(lhs.layout.ty.builtin_deref(true).unwrap())?;
1153        if !layout.is_sized() {
    ::core::panicking::panic("assertion failed: layout.is_sized()")
};assert!(layout.is_sized());
1154
1155        let get_bytes = |this: &InterpCx<'tcx, M>,
1156                         op: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>|
1157         -> InterpResult<'tcx, &[u8]> {
1158            let ptr = this.read_pointer(op)?;
1159            this.check_ptr_align(ptr, layout.align.abi)?;
1160            let Some(alloc_ref) = self.get_ptr_alloc(ptr, layout.size)? else {
1161                // zero-sized access
1162                return interp_ok(&[]);
1163            };
1164            alloc_ref.get_bytes_strip_provenance()
1165        };
1166
1167        let lhs_bytes = get_bytes(self, lhs)?;
1168        let rhs_bytes = get_bytes(self, rhs)?;
1169        interp_ok(Scalar::from_bool(lhs_bytes == rhs_bytes))
1170    }
1171
1172    fn unop_float_intrinsic<F>(
1173        &self,
1174        name: Symbol,
1175        arg: ImmTy<'tcx, M::Provenance>,
1176    ) -> InterpResult<'tcx, Scalar<M::Provenance>>
1177    where
1178        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1179    {
1180        let x: F = arg.to_scalar().to_float()?;
1181        match name {
1182            // bitwise, no NaN adjustments
1183            sym::fabs => interp_ok(x.abs().into()),
1184            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("not a unary float intrinsic: {0}",
        name))bug!("not a unary float intrinsic: {}", name),
1185        }
1186    }
1187
1188    fn float_minmax<F>(
1189        &self,
1190        a: Scalar<M::Provenance>,
1191        b: Scalar<M::Provenance>,
1192        op: MinMax,
1193    ) -> InterpResult<'tcx, Scalar<M::Provenance>>
1194    where
1195        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1196    {
1197        let a: F = a.to_float()?;
1198        let b: F = b.to_float()?;
1199        let res = if #[allow(non_exhaustive_omitted_patterns)] match op {
    MinMax::MinimumNumberNsz | MinMax::MaximumNumberNsz => true,
    _ => false,
}matches!(op, MinMax::MinimumNumberNsz | MinMax::MaximumNumberNsz) && a == b {
1200            // They are definitely not NaN (those are never equal), but they could be `+0` and `-0`.
1201            // Let the machine decide which one to return.
1202            M::equal_float_min_max(self, a, b)
1203        } else {
1204            let result = match op {
1205                MinMax::Minimum => a.minimum(b),
1206                MinMax::MinimumNumberNsz => a.min(b),
1207                MinMax::Maximum => a.maximum(b),
1208                MinMax::MaximumNumberNsz => a.max(b),
1209            };
1210            self.adjust_nan(result, &[a, b])
1211        };
1212
1213        interp_ok(res.into())
1214    }
1215
1216    fn float_minmax_intrinsic<F>(
1217        &mut self,
1218        args: &[OpTy<'tcx, M::Provenance>],
1219        op: MinMax,
1220        dest: &PlaceTy<'tcx, M::Provenance>,
1221    ) -> InterpResult<'tcx, ()>
1222    where
1223        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1224    {
1225        let res =
1226            self.float_minmax::<F>(self.read_scalar(&args[0])?, self.read_scalar(&args[1])?, op)?;
1227        self.write_scalar(res, dest)?;
1228        interp_ok(())
1229    }
1230
1231    fn float_copysign_intrinsic<F>(
1232        &mut self,
1233        args: &[OpTy<'tcx, M::Provenance>],
1234        dest: &PlaceTy<'tcx, M::Provenance>,
1235    ) -> InterpResult<'tcx, ()>
1236    where
1237        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1238    {
1239        let a: F = self.read_scalar(&args[0])?.to_float()?;
1240        let b: F = self.read_scalar(&args[1])?.to_float()?;
1241        // bitwise, no NaN adjustments
1242        self.write_scalar(a.copy_sign(b), dest)?;
1243        interp_ok(())
1244    }
1245
1246    fn float_round<F>(
1247        &mut self,
1248        x: Scalar<M::Provenance>,
1249        mode: rustc_apfloat::Round,
1250    ) -> InterpResult<'tcx, Scalar<M::Provenance>>
1251    where
1252        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1253    {
1254        let x: F = x.to_float()?;
1255        let res = x.round_to_integral(mode).value;
1256        let res = self.adjust_nan(res, &[x]);
1257        interp_ok(res.into())
1258    }
1259
1260    fn float_round_intrinsic<F>(
1261        &mut self,
1262        args: &[OpTy<'tcx, M::Provenance>],
1263        dest: &PlaceTy<'tcx, M::Provenance>,
1264        mode: rustc_apfloat::Round,
1265    ) -> InterpResult<'tcx, ()>
1266    where
1267        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1268    {
1269        let res = self.float_round::<F>(self.read_scalar(&args[0])?, mode)?;
1270        self.write_scalar(res, dest)?;
1271        interp_ok(())
1272    }
1273
1274    fn float_muladd<F>(
1275        &self,
1276        a: Scalar<M::Provenance>,
1277        b: Scalar<M::Provenance>,
1278        c: Scalar<M::Provenance>,
1279        typ: MulAddType,
1280    ) -> InterpResult<'tcx, Scalar<M::Provenance>>
1281    where
1282        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1283    {
1284        let a: F = a.to_float()?;
1285        let b: F = b.to_float()?;
1286        let c: F = c.to_float()?;
1287
1288        let fuse = typ == MulAddType::Fused || M::float_fuse_mul_add(self);
1289
1290        let res = if fuse { a.mul_add(b, c).value } else { ((a * b).value + c).value };
1291        let res = self.adjust_nan(res, &[a, b, c]);
1292        interp_ok(res.into())
1293    }
1294
1295    fn float_muladd_intrinsic<F>(
1296        &mut self,
1297        args: &[OpTy<'tcx, M::Provenance>],
1298        dest: &PlaceTy<'tcx, M::Provenance>,
1299        typ: MulAddType,
1300    ) -> InterpResult<'tcx, ()>
1301    where
1302        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1303    {
1304        let a = self.read_scalar(&args[0])?;
1305        let b = self.read_scalar(&args[1])?;
1306        let c = self.read_scalar(&args[2])?;
1307
1308        let res = self.float_muladd::<F>(a, b, c, typ)?;
1309        self.write_scalar(res, dest)?;
1310        interp_ok(())
1311    }
1312
1313    /// Converts `src` from floating point to integer type `dest_ty`
1314    /// after rounding with mode `round`.
1315    /// Returns `None` if `f` is NaN or out of range.
1316    pub fn float_to_int_checked(
1317        &self,
1318        src: &ImmTy<'tcx, M::Provenance>,
1319        cast_to: TyAndLayout<'tcx>,
1320        round: rustc_apfloat::Round,
1321    ) -> InterpResult<'tcx, Option<ImmTy<'tcx, M::Provenance>>> {
1322        fn float_to_int_inner<'tcx, F: rustc_apfloat::Float, M: Machine<'tcx>>(
1323            ecx: &InterpCx<'tcx, M>,
1324            src: F,
1325            cast_to: TyAndLayout<'tcx>,
1326            round: rustc_apfloat::Round,
1327        ) -> (Scalar<M::Provenance>, rustc_apfloat::Status) {
1328            let int_size = cast_to.layout.size;
1329            match cast_to.ty.kind() {
1330                // Unsigned
1331                ty::Uint(_) => {
1332                    let res = src.to_u128_r(int_size.bits_usize(), round, &mut false);
1333                    (Scalar::from_uint(res.value, int_size), res.status)
1334                }
1335                // Signed
1336                ty::Int(_) => {
1337                    let res = src.to_i128_r(int_size.bits_usize(), round, &mut false);
1338                    (Scalar::from_int(res.value, int_size), res.status)
1339                }
1340                // Nothing else
1341                _ => ::rustc_middle::util::bug::span_bug_fmt(ecx.cur_span(),
    format_args!("attempted float-to-int conversion with non-int output type {0}",
        cast_to.ty))span_bug!(
1342                    ecx.cur_span(),
1343                    "attempted float-to-int conversion with non-int output type {}",
1344                    cast_to.ty,
1345                ),
1346            }
1347        }
1348
1349        let ty::Float(fty) = src.layout.ty.kind() else {
1350            ::rustc_middle::util::bug::bug_fmt(format_args!("float_to_int_checked: non-float input type {0}",
        src.layout.ty))bug!("float_to_int_checked: non-float input type {}", src.layout.ty)
1351        };
1352
1353        let (val, status) = match fty {
1354            FloatTy::F16 => float_to_int_inner(self, src.to_scalar().to_f16()?, cast_to, round),
1355            FloatTy::F32 => float_to_int_inner(self, src.to_scalar().to_f32()?, cast_to, round),
1356            FloatTy::F64 => float_to_int_inner(self, src.to_scalar().to_f64()?, cast_to, round),
1357            FloatTy::F128 => float_to_int_inner(self, src.to_scalar().to_f128()?, cast_to, round),
1358        };
1359
1360        if status.intersects(
1361            rustc_apfloat::Status::INVALID_OP
1362                | rustc_apfloat::Status::OVERFLOW
1363                | rustc_apfloat::Status::UNDERFLOW,
1364        ) {
1365            // Floating point value is NaN (flagged with INVALID_OP) or outside the range
1366            // of values of the integer type (flagged with OVERFLOW or UNDERFLOW).
1367            interp_ok(None)
1368        } else {
1369            // Floating point value can be represented by the integer type after rounding.
1370            // The INEXACT flag is ignored on purpose to allow rounding.
1371            interp_ok(Some(ImmTy::from_scalar(val, cast_to)))
1372        }
1373    }
1374
1375    /// Get the MPlace of the key from the place storing the VaList.
1376    pub(super) fn va_list_key_field<P: Projectable<'tcx, M::Provenance>>(
1377        &self,
1378        va_list: &P,
1379    ) -> InterpResult<'tcx, P> {
1380        // The struct wrapped by VaList.
1381        let va_list_inner = self.project_field(va_list, FieldIdx::ZERO)?;
1382
1383        // Find the first pointer field in this struct. The exact index is target-specific.
1384        let ty::Adt(adt, substs) = va_list_inner.layout().ty.kind() else {
1385            ::rustc_middle::util::bug::bug_fmt(format_args!("invalid VaListImpl layout"));bug!("invalid VaListImpl layout");
1386        };
1387
1388        for (i, field) in adt.non_enum_variant().fields.iter().enumerate() {
1389            if field.ty(*self.tcx, substs).is_raw_ptr() {
1390                return self.project_field(&va_list_inner, FieldIdx::from_usize(i));
1391            }
1392        }
1393
1394        ::rustc_middle::util::bug::bug_fmt(format_args!("no VaListImpl field is a pointer"));bug!("no VaListImpl field is a pointer");
1395    }
1396}