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