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::{self, FloatTy, ScalarInt, Ty, TyCtxt, TypeVisitableExt};
17use rustc_span::{Symbol, bug, kw, span_bug, sym};
18use tracing::trace;
19
20use super::memory::MemoryKind;
21use super::util::ensure_monomorphic_enough;
22use super::{
23    AllocId, AtomicRmwOp, CheckInAllocMsg, ImmTy, Immediate, InterpCx, InterpResult, Machine, OpTy,
24    PlaceTy, Pointer, PointerArithmetic, Projectable, Provenance, Scalar, err_ub_format,
25    err_unsup_format, interp_ok, 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]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for MulAddType {
}
#[automatically_derived]impl ::core::clone::Clone for MulAddType {
    #[inline]
    fn clone(&self) -> Self { *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::marker::StructuralPartialEq for
    MulAddType {
}
#[automatically_derived]impl ::core::cmp::PartialEq for MulAddType {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for MulAddType { }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]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for MinMax {
}
#[automatically_derived]impl ::core::clone::Clone for MinMax {
    #[inline]
    fn clone(&self) -> Self { *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`.
62pub enum 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    /// This is compatible only if the value can be represented in both 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_span::macros::bug_impl(Some(self.cur_span()),
    format_args!("unsized type for `size_of`"), Location::caller());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_span::macros::bug_impl(Some(self.cur_span()),
    format_args!("unsized type for `align_of`"), Location::caller());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            kw::OffsetOf => {
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::unreachable_default_msg()unreachable!(),
266                    ty::Bound(_, _) => ::rustc_span::macros::bug_impl(None, format_args!("bound ty during ctfe"),
    Location::caller())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.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_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())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_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())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::unchecked_funnel_shl | sym::unchecked_funnel_shr => {
379                let shift_left = intrinsic_name == sym::unchecked_funnel_shl;
380
381                let l = self.read_immediate(&args[0])?;
382                let r = self.read_immediate(&args[1])?;
383                let shift = self.read_immediate(&args[2])?;
384
385                let result = self.funnel_shift(&l, &r, &shift, shift_left)?;
386                self.write_scalar(result, dest)?;
387            }
388
389            sym::copy => {
390                self.copy_intrinsic(&args[0], &args[1], &args[2], /*nonoverlapping*/ false)?;
391            }
392            sym::write_bytes => {
393                self.write_bytes_intrinsic(&args[0], &args[1], &args[2], "write_bytes")?;
394            }
395            sym::compare_bytes => {
396                let result = self.compare_bytes_intrinsic(&args[0], &args[1], &args[2])?;
397                self.write_scalar(result, dest)?;
398            }
399            sym::arith_offset => {
400                let ptr = self.read_pointer(&args[0])?;
401                let offset_count = self.read_target_isize(&args[1])?;
402                let pointee_ty = instance_args.type_at(0);
403
404                let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
405                let offset_bytes = offset_count.wrapping_mul(pointee_size);
406                let offset_ptr = ptr.wrapping_signed_offset(offset_bytes, self);
407                self.write_pointer(offset_ptr, dest)?;
408            }
409            sym::ptr_offset_from | sym::ptr_offset_from_unsigned => {
410                let a = self.read_pointer(&args[0])?;
411                let b = self.read_pointer(&args[1])?;
412
413                let usize_layout = self.layout_of(self.tcx.types.usize)?;
414                let isize_layout = self.layout_of(self.tcx.types.isize)?;
415
416                // Get offsets for both that are at least relative to the same base.
417                // With `OFFSET_IS_ADDR` this is trivial; without it we need either
418                // two integers or two pointers into the same allocation.
419                let (a_offset, b_offset, is_addr) = if M::Provenance::OFFSET_IS_ADDR {
420                    (a.addr().bytes(), b.addr().bytes(), /*is_addr*/ true)
421                } else {
422                    match (self.ptr_try_get_alloc_id(a, 0), self.ptr_try_get_alloc_id(b, 0)) {
423                        (Err(a), Err(b)) => {
424                            // Neither pointer points to an allocation, so they are both absolute.
425                            (a, b, /*is_addr*/ true)
426                        }
427                        (Ok((a_alloc_id, a_offset, _)), Ok((b_alloc_id, b_offset, _)))
428                            if a_alloc_id == b_alloc_id =>
429                        {
430                            // Found allocation for both, and it's the same.
431                            // Use these offsets for distance calculation.
432                            (a_offset.bytes(), b_offset.bytes(), /*is_addr*/ false)
433                        }
434                        _ => {
435                            // Not into the same allocation -- this is UB.
436                            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!(
437                                "`{name}` called on two different pointers that are not both derived from the same allocation",
438                                name = intrinsic_name,
439                            );
440                        }
441                    }
442                };
443
444                // Compute distance: a - b.
445                let dist = {
446                    // Addresses are unsigned, so this is a `usize` computation. We have to do the
447                    // overflow check separately anyway.
448                    let (val, overflowed) = {
449                        let a_offset = ImmTy::from_uint(a_offset, usize_layout);
450                        let b_offset = ImmTy::from_uint(b_offset, usize_layout);
451                        self.binary_op(BinOp::SubWithOverflow, &a_offset, &b_offset)?
452                            .to_scalar_pair()
453                    };
454                    if overflowed.to_bool()? {
455                        // a < b
456                        if intrinsic_name == sym::ptr_offset_from_unsigned {
457                            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!(
458                                "`ptr_offset_from_unsigned` called when first pointer has smaller {is_addr} than second: {a_offset} < {b_offset}",
459                                a_offset = a_offset,
460                                b_offset = b_offset,
461                                is_addr = if is_addr { "address" } else { "offset" },
462                            );
463                        }
464                        // The signed form of the intrinsic allows this. If we interpret the
465                        // difference as isize, we'll get the proper signed difference. If that
466                        // seems *positive* or equal to isize::MIN, they were more than isize::MAX apart.
467                        let dist = val.to_target_isize(self)?;
468                        if dist >= 0 || i128::from(dist) == self.pointer_size().signed_int_min() {
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 before second",
                            intrinsic_name))
                })));throw_ub_format!(
470                                "`{intrinsic_name}` called when first pointer is too far before second"
471                            );
472                        }
473                        dist
474                    } else {
475                        // b >= a
476                        let dist = val.to_target_isize(self)?;
477                        // If converting to isize produced a *negative* result, we had an overflow
478                        // because they were more than isize::MAX apart.
479                        if dist < 0 {
480                            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!(
481                                "`{intrinsic_name}` called when first pointer is too far ahead of second"
482                            );
483                        }
484                        dist
485                    }
486                };
487
488                // Check that the memory between them is dereferenceable at all, starting from the
489                // origin pointer: `dist` is `a - b`, so it is based on `b`.
490                self.check_ptr_access_signed(b, dist, CheckInAllocMsg::Dereferenceable("pointer"))
491                    .map_err_kind(|_| {
492                        // This could mean they point to different allocations, or they point to the same allocation
493                        // but not the entire range between the pointers is in-bounds.
494                        if let Ok((a_alloc_id, ..)) = self.ptr_try_get_alloc_id(a, 0)
495                            && let Ok((b_alloc_id, ..)) = self.ptr_try_get_alloc_id(b, 0)
496                            && a_alloc_id == b_alloc_id
497                        {
498                            ::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!(
499                                "`{intrinsic_name}` called on two different pointers where the memory range between them is not in-bounds of an allocation"
500                            )
501                        } else {
502                            ::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!(
503                                "`{intrinsic_name}` called on two different pointers that are not both derived from the same allocation"
504                            )
505                        }
506                    })?;
507                // Then check that this is also dereferenceable from `a`. This ensures that they are
508                // derived from the same allocation.
509                self.check_ptr_access_signed(
510                    a,
511                    dist.checked_neg().unwrap(), // i64::MIN is impossible as no allocation can be that large
512                    CheckInAllocMsg::Dereferenceable("pointer"),
513                )
514                .map_err_kind(|_| {
515                    // Make the error more specific.
516                    ::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!(
517                        "`{intrinsic_name}` called on two different pointers that are not both derived from the same allocation"
518                    )
519                })?;
520
521                // Perform division by size to compute return value.
522                let ret_layout = if intrinsic_name == sym::ptr_offset_from_unsigned {
523                    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());
524                    usize_layout
525                } else {
526                    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());
527                    isize_layout
528                };
529                let pointee_layout = self.layout_of(instance_args.type_at(0))?;
530                // If ret_layout is unsigned, we checked that so is the distance, so we are good.
531                let val = ImmTy::from_int(dist, ret_layout);
532                let size = ImmTy::from_int(pointee_layout.size.bytes(), ret_layout);
533                self.exact_div(&val, &size, dest)?;
534            }
535
536            sym::black_box => {
537                // These just return their argument
538                self.copy_op(&args[0], dest)?;
539            }
540            sym::raw_eq => {
541                let result = self.raw_eq_intrinsic(&args[0], &args[1])?;
542                self.write_scalar(result, dest)?;
543            }
544            sym::typed_swap_nonoverlapping => {
545                self.typed_swap_nonoverlapping_intrinsic(&args[0], &args[1])?;
546            }
547
548            sym::volatile_load => {
549                let [ptr] = args else {
550                    ::rustc_span::macros::bug_impl(Some(self.cur_span()),
    format_args!("invalid `volatile_load` call"), Location::caller())span_bug!(self.cur_span(), "invalid `volatile_load` call")
551                };
552                let place = self.deref_pointer(ptr)?;
553                self.copy_op(&place, dest)?;
554            }
555            sym::volatile_store => {
556                let [ptr, val] = args else {
557                    ::rustc_span::macros::bug_impl(Some(self.cur_span()),
    format_args!("invalid `volatile_store` call"), Location::caller())span_bug!(self.cur_span(), "invalid `volatile_store` call")
558                };
559                let place = self.deref_pointer(ptr)?;
560                self.copy_op(val, &place)?;
561            }
562            sym::volatile_set_memory => {
563                let [ptr, val_byte, count] = args else {
564                    ::rustc_span::macros::bug_impl(Some(self.cur_span()),
    format_args!("invalid `volatile_set_memory` call"), Location::caller())span_bug!(self.cur_span(), "invalid `volatile_set_memory` call")
565                };
566                self.write_bytes_intrinsic(ptr, val_byte, count, "volatile_set_memory")?;
567            }
568
569            sym::vtable_size => {
570                let ptr = self.read_pointer(&args[0])?;
571                // `None` because we don't know which trait to expect here; any vtable is okay.
572                let (size, _align) = self.get_vtable_size_and_align(ptr, None)?;
573                self.write_scalar(Scalar::from_target_usize(size.bytes(), self), dest)?;
574            }
575            sym::vtable_align => {
576                let ptr = self.read_pointer(&args[0])?;
577                // `None` because we don't know which trait to expect here; any vtable is okay.
578                let (_size, align) = self.get_vtable_size_and_align(ptr, None)?;
579                self.write_scalar(Scalar::from_target_usize(align.bytes(), self), dest)?;
580            }
581
582            sym::minimum_number_nsz_f16 => {
583                self.float_minmax_intrinsic::<Half>(args, MinMax::MinimumNumberNsz, dest)?
584            }
585            sym::minimum_number_nsz_f32 => {
586                self.float_minmax_intrinsic::<Single>(args, MinMax::MinimumNumberNsz, dest)?
587            }
588            sym::minimum_number_nsz_f64 => {
589                self.float_minmax_intrinsic::<Double>(args, MinMax::MinimumNumberNsz, dest)?
590            }
591            sym::minimum_number_nsz_f128 => {
592                self.float_minmax_intrinsic::<Quad>(args, MinMax::MinimumNumberNsz, dest)?
593            }
594
595            sym::minimumf16 => self.float_minmax_intrinsic::<Half>(args, MinMax::Minimum, dest)?,
596            sym::minimumf32 => {
597                self.float_minmax_intrinsic::<Single>(args, MinMax::Minimum, dest)?
598            }
599            sym::minimumf64 => {
600                self.float_minmax_intrinsic::<Double>(args, MinMax::Minimum, dest)?
601            }
602            sym::minimumf128 => self.float_minmax_intrinsic::<Quad>(args, MinMax::Minimum, dest)?,
603
604            sym::maximum_number_nsz_f16 => {
605                self.float_minmax_intrinsic::<Half>(args, MinMax::MaximumNumberNsz, dest)?
606            }
607            sym::maximum_number_nsz_f32 => {
608                self.float_minmax_intrinsic::<Single>(args, MinMax::MaximumNumberNsz, dest)?
609            }
610            sym::maximum_number_nsz_f64 => {
611                self.float_minmax_intrinsic::<Double>(args, MinMax::MaximumNumberNsz, dest)?
612            }
613            sym::maximum_number_nsz_f128 => {
614                self.float_minmax_intrinsic::<Quad>(args, MinMax::MaximumNumberNsz, dest)?
615            }
616
617            sym::maximumf16 => self.float_minmax_intrinsic::<Half>(args, MinMax::Maximum, dest)?,
618            sym::maximumf32 => {
619                self.float_minmax_intrinsic::<Single>(args, MinMax::Maximum, dest)?
620            }
621            sym::maximumf64 => {
622                self.float_minmax_intrinsic::<Double>(args, MinMax::Maximum, dest)?
623            }
624            sym::maximumf128 => self.float_minmax_intrinsic::<Quad>(args, MinMax::Maximum, dest)?,
625
626            sym::copysignf16 => self.float_copysign_intrinsic::<Half>(args, dest)?,
627            sym::copysignf32 => self.float_copysign_intrinsic::<Single>(args, dest)?,
628            sym::copysignf64 => self.float_copysign_intrinsic::<Double>(args, dest)?,
629            sym::copysignf128 => self.float_copysign_intrinsic::<Quad>(args, dest)?,
630
631            sym::fabs | sym::floor | sym::ceil | sym::trunc | sym::round | sym::round_ties_even => {
632                let arg = self.read_immediate(&args[0])?;
633                let ty::Float(float_ty) = arg.layout.ty.kind() else {
634                    ::rustc_span::macros::bug_impl(Some(self.cur_span()),
    format_args!("non-float type for float intrinsic: {0}", arg.layout.ty),
    Location::caller());span_bug!(
635                        self.cur_span(),
636                        "non-float type for float intrinsic: {}",
637                        arg.layout.ty,
638                    );
639                };
640                let out_val = match float_ty {
641                    FloatTy::F16 => self.unop_float_intrinsic::<Half>(intrinsic_name, arg)?,
642                    FloatTy::F32 => self.unop_float_intrinsic::<Single>(intrinsic_name, arg)?,
643                    FloatTy::F64 => self.unop_float_intrinsic::<Double>(intrinsic_name, arg)?,
644                    FloatTy::F128 => self.unop_float_intrinsic::<Quad>(intrinsic_name, arg)?,
645                };
646                self.write_scalar(out_val, dest)?;
647            }
648
649            sym::fma | sym::fmuladd => {
650                let fma_type = if intrinsic_name == sym::fma {
651                    MulAddType::Fused
652                } else {
653                    MulAddType::Nondeterministic
654                };
655                let ty = args[0].layout.ty;
656                let ty::Float(float_ty) = ty.kind() else {
657                    ::rustc_span::macros::bug_impl(Some(self.cur_span()),
    format_args!("non-float type for float intrinsic: {0}", ty),
    Location::caller());span_bug!(self.cur_span(), "non-float type for float intrinsic: {ty}");
658                };
659                match float_ty {
660                    FloatTy::F16 => self.float_muladd_intrinsic::<Half>(args, dest, fma_type)?,
661                    FloatTy::F32 => self.float_muladd_intrinsic::<Single>(args, dest, fma_type)?,
662                    FloatTy::F64 => self.float_muladd_intrinsic::<Double>(args, dest, fma_type)?,
663                    FloatTy::F128 => self.float_muladd_intrinsic::<Quad>(args, dest, fma_type)?,
664                }
665            }
666
667            sym::va_copy => {
668                let va_list = self.deref_pointer(&args[0])?;
669
670                let key_mplace = self.va_list_key_field(&va_list)?;
671                let key = self.read_pointer(&key_mplace)?;
672
673                let varargs = self.get_ptr_va_list(key)?;
674                let copy_key = self.va_list_ptr(varargs.clone());
675
676                // Zero the destination VaList, so it is fully initialized.
677                let dest = self.force_allocation(dest)?;
678                let zeros = std::iter::repeat_n(0u8, dest.layout.size.bytes_usize());
679                self.write_bytes_ptr(dest.ptr(), zeros)?;
680
681                let copy_key_mplace = self.va_list_key_field(&dest)?;
682                self.write_pointer(copy_key, &copy_key_mplace)?;
683            }
684
685            sym::va_end => {
686                let va_list = self.deref_pointer(&args[0])?;
687                let key_mplace = self.va_list_key_field(&va_list)?;
688                let key = self.read_pointer(&key_mplace)?;
689
690                self.deallocate_va_list(key)?;
691            }
692
693            sym::va_arg => {
694                let va_list = self.deref_pointer(&args[0])?;
695                let key_mplace = self.va_list_key_field(&va_list)?;
696                let key = self.read_pointer(&key_mplace)?;
697
698                // Invalidate the old list and get its content. We'll recreate the
699                // new list (one element shorter) below.
700                let mut varargs = self.deallocate_va_list(key)?;
701
702                let Some(arg_mplace) = varargs.pop_front() else {
703                    do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::VaArgOutOfBounds);throw_ub!(VaArgOutOfBounds);
704                };
705
706                // Error when the caller's argument is not c-variadic compatible with the type
707                // requested by the callee.
708                self.validate_c_variadic_argument(&arg_mplace, dest.layout)?;
709
710                // Copy the argument, allowing a transmute and relying on the compatibility check
711                // rejecting conversions between types of different size.
712                self.copy_op_allow_transmute(&arg_mplace, dest)?;
713
714                // Update the VaList pointer.
715                let new_key = self.va_list_ptr(varargs);
716                self.write_pointer(new_key, &key_mplace)?;
717            }
718
719            // Unsupported intrinsic: skip the return_to_block below.
720            _ => return interp_ok(false),
721        }
722
723        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5b7b37aefcb5b2fba3c2392bc9065b9e4602d494/compiler/rustc_const_eval/src/interpret/intrinsics.rs:723",
                        "rustc_const_eval::interpret::intrinsics",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5b7b37aefcb5b2fba3c2392bc9065b9e4602d494/compiler/rustc_const_eval/src/interpret/intrinsics.rs"),
                        ::tracing_core::__macro_support::Option::Some(723u32),
                        ::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));
724        self.return_to_block(ret)?;
725        interp_ok(true)
726    }
727
728    /// Validate whether the value and type passed by the caller are compatible with the type
729    /// requested by the callee. Based on section 7.16.1.1 of the C23 specification.
730    ///
731    /// The callee requesting a value of a type is valid when that type is compatible with the type
732    /// provided by the caller (see `validate_c_variadic_compatible_ty`) and, if both types are
733    /// integers of the same size but different signedness, the passed value must be representable
734    /// in both types.
735    fn validate_c_variadic_argument(
736        &self,
737        arg_mplace: &MPlaceTy<'tcx, M::Provenance>,
738        callee_type: TyAndLayout<'tcx>,
739    ) -> InterpResult<'tcx> {
740        let callee_ty = callee_type.ty;
741        let caller_ty = arg_mplace.layout.ty;
742
743        match self.validate_c_variadic_compatible_ty(arg_mplace.layout.ty, callee_type.ty)? {
744            VarArgCompatible::Compatible => interp_ok(()),
745            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!(
746                "va_arg type mismatch: requested `{}` is incompatible with next argument of type `{}`",
747                callee_ty,
748                caller_ty,
749            ),
750            VarArgCompatible::CastIntTo { source_is_signed } => {
751                // Check that the value can be represented in the target type.
752                let size = arg_mplace.layout.size;
753                let scalar = self.read_scalar(arg_mplace)?;
754                if scalar.to_int(size)? < 0 {
755                    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!(
756                        "va_arg value mismatch: value `{value}_{caller_ty}` cannot be represented by type `{callee_ty}`",
757                        value = if source_is_signed {
758                            scalar.to_int(size)?.to_string()
759                        } else {
760                            scalar.to_uint(size)?.to_string()
761                        }
762                    )
763                }
764
765                interp_ok(())
766            }
767        }
768    }
769
770    /// Check whether the caller and callee type are compatible for c-variadic calls. Further
771    /// validation of the argument value may be needed to detect all UB.
772    ///
773    /// Types `T` and `U` are compatible when:
774    ///
775    /// - `T` and `U` are the same type.
776    /// - `T` and `U` are integer types of the same size.
777    /// - `T` and `U` are both pointers, and their target types are compatible.
778    /// - `T` is a pointer to [`std::ffi::c_void`] and `U` is a pointer to [`i8`] or [`u8`],
779    /// or vice versa.
780    ///
781    /// This is designed to match the C rules for variadics, it is incomparable to what we allow in
782    /// terms of ABI mismatches for regular (fixed) function arguments.
783    pub fn validate_c_variadic_compatible_ty(
784        &self,
785        caller_type: Ty<'tcx>,
786        callee_type: Ty<'tcx>,
787    ) -> InterpResult<'tcx, VarArgCompatible> {
788        // FIXME: Accepting two copies of the same repr(C) type as compatible is currently not
789        // guaranteed by our `VaList::next_arg` docs, but it is needed for Miri itself when it
790        // checks whether shims were called with the right arguments. We should eventually put this
791        // into the docs as well.
792        if self.identical_c_types(caller_type, callee_type) {
793            return interp_ok(VarArgCompatible::Compatible);
794        }
795
796        if self.layout_of(caller_type)?.size != self.layout_of(callee_type)?.size {
797            return interp_ok(VarArgCompatible::Incompatible);
798        }
799
800        // Any character type (`char`, `unsigned char` and `signed char`) is compatible with
801        // `void*`, so the signedness of `c_char` is irrelevant here.
802        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));
803
804        match (caller_type.kind(), callee_type.kind()) {
805            // Some types look different but are actually the same for ABI purposes.
806            (ty::Int(_), ty::Int(_)) | (ty::Uint(_), ty::Uint(_)) => {
807                // E.g. cast between `usize` and `u64` on a 64-bit platform.
808                interp_ok(VarArgCompatible::Compatible)
809            }
810            // C allows different types if...
811            // - "both types are pointers to qualified or unqualified versions of compatible types"
812            // - "one type is pointer to qualified or unqualified void and the other is a pointer to a qualified or
813            //   unqualified character type"
814            //
815            // As usual for the ABI, we treat references and raw pointers alike.
816            (
817                ty::RawPtr(caller_target_ty, _) | ty::Ref(_, caller_target_ty, _),
818                ty::RawPtr(callee_target_ty, _) | ty::Ref(_, callee_target_ty, _),
819            ) => {
820                // In C, types can be qualified by a combination of `const`, `volatile` and
821                // `restrict`. These properties are irrelevant for the ABI, and don't have an
822                // equivalent in rust.
823
824                // Accept the cast if one type is pointer to void, and the other is a pointer to
825                // a character type (`char`, `unsigned char` and `signed char`).
826                if caller_target_ty.is_c_void(self.tcx.tcx) && is_c_char(*callee_target_ty) {
827                    return interp_ok(VarArgCompatible::Compatible);
828                }
829                if callee_target_ty.is_c_void(self.tcx.tcx) && is_c_char(*caller_target_ty) {
830                    return interp_ok(VarArgCompatible::Compatible);
831                }
832
833                // Accept the cast if both types are pointers to compatible types.
834                match self
835                    .validate_c_variadic_compatible_ty(*caller_target_ty, *callee_target_ty)?
836                {
837                    VarArgCompatible::Incompatible => interp_ok(VarArgCompatible::Incompatible),
838                    VarArgCompatible::Compatible => interp_ok(VarArgCompatible::Compatible),
839                    VarArgCompatible::CastIntTo { source_is_signed: _ } => {
840                        // The integer cast check is not needed when the value is behind a pointer.
841                        interp_ok(VarArgCompatible::Compatible)
842                    }
843                }
844            }
845            // - "one type is a signed integer type, the other type is the corresponding unsigned integer type,
846            //   and the value is representable in both types"
847            (ty::Int(_), ty::Uint(_)) => {
848                interp_ok(VarArgCompatible::CastIntTo { source_is_signed: true })
849            }
850            (ty::Uint(_), ty::Int(_)) => {
851                interp_ok(VarArgCompatible::CastIntTo { source_is_signed: false })
852            }
853            // - "or, the type of the next argument is nullptr_t and type is a pointer type that has the same
854            //   representation and alignment requirements as a pointer to a character type"
855            //   This one does not have an equivalent form in Rust.
856            _ => interp_ok(VarArgCompatible::Incompatible),
857        }
858    }
859
860    pub(super) fn eval_nondiverging_intrinsic(
861        &mut self,
862        intrinsic: &NonDivergingIntrinsic<'tcx>,
863    ) -> InterpResult<'tcx> {
864        match intrinsic {
865            NonDivergingIntrinsic::Assume(op) => {
866                let op = self.eval_operand(op, None)?;
867                let cond = self.read_scalar(&op)?.to_bool()?;
868                if !cond {
869                    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`");
870                }
871                interp_ok(())
872            }
873            NonDivergingIntrinsic::CopyNonOverlapping(mir::CopyNonOverlapping {
874                count,
875                src,
876                dst,
877            }) => {
878                let src = self.eval_operand(src, None)?;
879                let dst = self.eval_operand(dst, None)?;
880                let count = self.eval_operand(count, None)?;
881                self.copy_intrinsic(&src, &dst, &count, /* nonoverlapping */ true)
882            }
883        }
884    }
885
886    pub fn numeric_intrinsic(
887        &self,
888        name: Symbol,
889        val: Scalar<M::Provenance>,
890        layout: TyAndLayout<'tcx>,
891        ret_layout: TyAndLayout<'tcx>,
892    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
893        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);
894        let bits = val.to_bits(layout.size)?; // these operations all ignore the sign
895        let extra = 128 - u128::from(layout.size.bits());
896        let bits_out = match name {
897            sym::ctpop => u128::from(bits.count_ones()),
898            sym::ctlz_nonzero | sym::cttz_nonzero if bits == 0 => {
899                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");
900            }
901            sym::ctlz | sym::ctlz_nonzero => u128::from(bits.leading_zeros()) - extra,
902            sym::cttz | sym::cttz_nonzero => u128::from((bits << extra).trailing_zeros()) - extra,
903            sym::bswap => {
904                {
    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);
905                (bits << extra).swap_bytes()
906            }
907            sym::bitreverse => {
908                {
    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);
909                (bits << extra).reverse_bits()
910            }
911            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("not a numeric intrinsic: {0}", name), Location::caller())bug!("not a numeric intrinsic: {}", name),
912        };
913        interp_ok(Scalar::from_uint(bits_out, ret_layout.size))
914    }
915
916    pub fn exact_div(
917        &mut self,
918        a: &ImmTy<'tcx, M::Provenance>,
919        b: &ImmTy<'tcx, M::Provenance>,
920        dest: &PlaceTy<'tcx, M::Provenance>,
921    ) -> InterpResult<'tcx> {
922        {
    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);
923        {
    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(..));
924
925        // Performs an exact division, resulting in undefined behavior where
926        // `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`.
927        // First, check x % y != 0 (or if that computation overflows).
928        let rem = self.binary_op(BinOp::Rem, a, b)?;
929        // sign does not matter for 0 test, so `to_bits` is fine
930        if rem.to_scalar().to_bits(a.layout.size)? != 0 {
931            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")
932        }
933        // `Rem` says this is all right, so we can let `Div` do its job.
934        let res = self.binary_op(BinOp::Div, a, b)?;
935        self.write_immediate(*res, dest)
936    }
937
938    pub fn saturating_arith(
939        &self,
940        mir_op: BinOp,
941        l: &ImmTy<'tcx, M::Provenance>,
942        r: &ImmTy<'tcx, M::Provenance>,
943    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
944        {
    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);
945        {
    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(..));
946        {
    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);
947
948        let (val, overflowed) =
949            self.binary_op(mir_op.wrapping_to_overflowing().unwrap(), l, r)?.to_scalar_pair();
950        interp_ok(if overflowed.to_bool()? {
951            let size = l.layout.size;
952            if l.layout.backend_repr.is_signed() {
953                // For signed ints the saturated value depends on the sign of the first
954                // term since the sign of the second term can be inferred from this and
955                // the fact that the operation has overflowed (if either is 0 no
956                // overflow can occur)
957                let first_term: i128 = l.to_scalar().to_int(l.layout.size)?;
958                if first_term >= 0 {
959                    // Negative overflow not possible since the positive first term
960                    // can only increase an (in range) negative term for addition
961                    // or corresponding negated positive term for subtraction.
962                    Scalar::from_int(size.signed_int_max(), size)
963                } else {
964                    // Positive overflow not possible for similar reason.
965                    Scalar::from_int(size.signed_int_min(), size)
966                }
967            } else {
968                // unsigned
969                if mir_op == BinOp::Add {
970                    // max unsigned
971                    Scalar::from_uint(size.unsigned_int_max(), size)
972                } else {
973                    // underflow to 0
974                    Scalar::from_uint(0u128, size)
975                }
976            }
977        } else {
978            val
979        })
980    }
981
982    pub fn funnel_shift(
983        &self,
984        left: &ImmTy<'tcx, M::Provenance>,
985        right: &ImmTy<'tcx, M::Provenance>,
986        shift_bits: &ImmTy<'tcx, M::Provenance>,
987        shift_left: bool,
988    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
989        let size = left.layout.size;
990        let left = left.to_scalar().to_bits(size)?;
991        let right = right.to_scalar().to_bits(size)?;
992        let shift_bits = shift_bits.to_scalar().to_bits(shift_bits.layout.size)?; // can have different size
993
994        if shift_bits >= size.bits().into() {
995            do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("overflowing shift by {1} in {0} funnel shift",
                            if shift_left { "left" } else { "right" }, shift_bits))
                })));throw_ub_format!(
996                "overflowing shift by {shift_bits} in {} funnel shift",
997                if shift_left { "left" } else { "right" }
998            );
999        }
1000        let inv_shift_bits = u32::try_from(u128::from(size.bits()) - shift_bits).unwrap();
1001
1002        // A funnel shift left by S can be implemented as `(x << S) | y.unbounded_shr(SIZE - S)`.
1003        // The `unbounded_shr` is needed because otherwise if `S = 0`, it would be `x | y`
1004        // when it should be `x`.
1005        //
1006        // This selects the least-significant `SIZE - S` bits of `x`, followed by the `S` most
1007        // significant bits of `y`. As `left` and `right` both occupy the lower `SIZE` bits,
1008        // we can treat the lower `SIZE` bits as an integer of the right width and use
1009        // the same implementation, but on a zero-extended `x` and `y`. This works because
1010        // `x << S` just pushes the `SIZE-S` MSBs out, and `y >> (SIZE - S)` shifts in
1011        // zeros, as it is zero-extended. To the lower `SIZE` bits, this looks just like a
1012        // funnel shift left.
1013        //
1014        // Note that the `unbounded_sh{l,r}`s are needed only in case we are using this on
1015        // `u128xN` and `inv_shift_bits == 128`.
1016        let result_bits = if shift_left {
1017            (left << shift_bits) | right.unbounded_shr(inv_shift_bits)
1018        } else {
1019            left.unbounded_shl(inv_shift_bits) | (right >> shift_bits)
1020        };
1021
1022        let (result, _overflow) = ScalarInt::truncate_from_uint(result_bits, size);
1023        interp_ok(result.into())
1024    }
1025
1026    /// Offsets a pointer by some multiple of its type, returning an error if the pointer leaves its
1027    /// allocation.
1028    pub fn ptr_offset_inbounds(
1029        &self,
1030        ptr: Pointer<Option<M::Provenance>>,
1031        offset_bytes: i64,
1032    ) -> InterpResult<'tcx, Pointer<Option<M::Provenance>>> {
1033        // The offset must be in bounds starting from `ptr`.
1034        self.check_ptr_access_signed(
1035            ptr,
1036            offset_bytes,
1037            CheckInAllocMsg::InboundsPointerArithmetic,
1038        )?;
1039        // This also implies that there is no overflow, so we are done.
1040        interp_ok(ptr.wrapping_signed_offset(offset_bytes, self))
1041    }
1042
1043    /// Copy `count*size_of::<T>()` many bytes from `*src` to `*dst`.
1044    pub(crate) fn copy_intrinsic(
1045        &mut self,
1046        src: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>, // pointer to source memory
1047        dst: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>, // pointer to destination memory
1048        count: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1049        nonoverlapping: bool,
1050    ) -> InterpResult<'tcx> {
1051        let count = self.read_target_usize(count)?;
1052        let layout = self.layout_of(src.layout.ty.builtin_deref(true).unwrap())?;
1053        let (size, align) = (layout.size, layout.align);
1054
1055        let size = self.compute_size_in_bytes(size, count).ok_or_else(|| {
1056            ::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!(
1057                "overflow computing total size of `{name}`",
1058                name = if nonoverlapping { "copy_nonoverlapping" } else { "copy" }
1059            )
1060        })?;
1061
1062        let src = self.read_pointer(src)?;
1063        let dst = self.read_pointer(dst)?;
1064
1065        self.check_ptr_align(src, align)?;
1066        self.check_ptr_align(dst, align)?;
1067
1068        self.mem_copy(src, dst, size, nonoverlapping)
1069    }
1070
1071    /// Does a *typed* swap of `*left` and `*right`.
1072    fn typed_swap_nonoverlapping_intrinsic(
1073        &mut self,
1074        left: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1075        right: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1076    ) -> InterpResult<'tcx> {
1077        let left = self.deref_pointer(left)?;
1078        let right = self.deref_pointer(right)?;
1079        {
    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);
1080        if !left.layout.is_sized() {
    ::core::panicking::panic("assertion failed: left.layout.is_sized()")
};assert!(left.layout.is_sized());
1081        let kind = MemoryKind::Stack;
1082        let temp = self.allocate(left.layout, kind)?;
1083        self.copy_op(&left, &temp)?; // checks alignment of `left`
1084
1085        // We want to always enforce non-overlapping, even if this is a scalar type.
1086        // Therefore we directly use the underlying `mem_copy` here.
1087        self.mem_copy(right.ptr(), left.ptr(), left.layout.size, /*nonoverlapping*/ true)?;
1088        // This means we also need to do the validation of the value that used to be in `right`
1089        // ourselves. This value is now in `left.` The one that started out in `left` already got
1090        // validated by the copy above.
1091        if M::enforce_validity(self, left.layout) {
1092            self.validate_place(
1093                &left.clone().into(),
1094                M::enforce_validity_recursively(self, left.layout),
1095                /*reset_provenance_and_padding*/ true,
1096            )?;
1097        }
1098
1099        self.copy_op(&temp, &right)?; // checks alignment of `right`
1100
1101        self.deallocate_ptr(temp.ptr(), None, kind)?;
1102        interp_ok(())
1103    }
1104
1105    pub fn write_bytes_intrinsic(
1106        &mut self,
1107        dst: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>, // pointer to destination memory
1108        byte: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1109        count: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1110        name: &'static str,
1111    ) -> InterpResult<'tcx> {
1112        let layout = self.layout_of(dst.layout.ty.builtin_deref(true).unwrap())?;
1113
1114        let dst = self.read_pointer(dst)?;
1115        let byte = self.read_scalar(byte)?.to_u8()?;
1116        let count = self.read_target_usize(count)?;
1117
1118        // `checked_mul` enforces a too small bound (the correct one would probably be target_isize_max),
1119        // but no actual allocation can be big enough for the difference to be noticeable.
1120        let len = self
1121            .compute_size_in_bytes(layout.size, count)
1122            .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}`"))?;
1123
1124        // Check alignment as well. We set the attribute in LLVM.
1125        self.check_ptr_align(dst, layout.align)?;
1126
1127        let bytes = std::iter::repeat_n(byte, len.bytes_usize());
1128        self.write_bytes_ptr(dst, bytes)
1129    }
1130
1131    pub(crate) fn compare_bytes_intrinsic(
1132        &mut self,
1133        left: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1134        right: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1135        byte_count: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1136    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
1137        let left = self.read_pointer(left)?;
1138        let right = self.read_pointer(right)?;
1139        let n = Size::from_bytes(self.read_target_usize(byte_count)?);
1140
1141        let left_bytes = self.read_bytes_ptr_strip_provenance(left, n)?;
1142        let right_bytes = self.read_bytes_ptr_strip_provenance(right, n)?;
1143
1144        // `Ordering`'s discriminants are -1/0/+1, so casting does the right thing.
1145        let result = Ord::cmp(left_bytes, right_bytes) as i32;
1146        interp_ok(Scalar::from_i32(result))
1147    }
1148
1149    pub(crate) fn raw_eq_intrinsic(
1150        &mut self,
1151        lhs: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1152        rhs: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>,
1153    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
1154        let layout = self.layout_of(lhs.layout.ty.builtin_deref(true).unwrap())?;
1155        if !layout.is_sized() {
    ::core::panicking::panic("assertion failed: layout.is_sized()")
};assert!(layout.is_sized());
1156
1157        let get_bytes = |this: &InterpCx<'tcx, M>,
1158                         op: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>|
1159         -> InterpResult<'tcx, &[u8]> {
1160            let ptr = this.read_pointer(op)?;
1161            this.check_ptr_align(ptr, layout.align)?;
1162            let Some(alloc_ref) = self.get_ptr_alloc(ptr, layout.size)? else {
1163                // zero-sized access
1164                return interp_ok(&[]);
1165            };
1166            alloc_ref.get_bytes_strip_provenance()
1167        };
1168
1169        let lhs_bytes = get_bytes(self, lhs)?;
1170        let rhs_bytes = get_bytes(self, rhs)?;
1171        interp_ok(Scalar::from_bool(lhs_bytes == rhs_bytes))
1172    }
1173
1174    fn unop_float_intrinsic<F>(
1175        &mut self,
1176        name: Symbol,
1177        arg: ImmTy<'tcx, M::Provenance>,
1178    ) -> InterpResult<'tcx, Scalar<M::Provenance>>
1179    where
1180        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1181    {
1182        let x: F = arg.to_scalar().to_float()?;
1183        match name {
1184            // bitwise, no NaN adjustments
1185            sym::fabs => interp_ok(x.abs().into()),
1186
1187            sym::floor => self.float_round(x, rustc_apfloat::Round::TowardNegative),
1188            sym::ceil => self.float_round(x, rustc_apfloat::Round::TowardPositive),
1189            sym::trunc => self.float_round(x, rustc_apfloat::Round::TowardZero),
1190            sym::round => self.float_round(x, rustc_apfloat::Round::NearestTiesToAway),
1191            sym::round_ties_even => self.float_round(x, rustc_apfloat::Round::NearestTiesToEven),
1192
1193            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("not a unary float intrinsic: {0}", name),
    Location::caller())bug!("not a unary float intrinsic: {}", name),
1194        }
1195    }
1196
1197    fn float_minmax<F>(
1198        &self,
1199        a: Scalar<M::Provenance>,
1200        b: Scalar<M::Provenance>,
1201        op: MinMax,
1202    ) -> InterpResult<'tcx, Scalar<M::Provenance>>
1203    where
1204        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1205    {
1206        let a: F = a.to_float()?;
1207        let b: F = b.to_float()?;
1208        let res = if #[allow(non_exhaustive_omitted_patterns)] match op {
    MinMax::MinimumNumberNsz | MinMax::MaximumNumberNsz => true,
    _ => false,
}matches!(op, MinMax::MinimumNumberNsz | MinMax::MaximumNumberNsz) && a == b {
1209            // They are definitely not NaN (those are never equal), but they could be `+0` and `-0`.
1210            // Let the machine decide which one to return.
1211            M::equal_float_min_max(self, a, b)
1212        } else {
1213            let result = match op {
1214                MinMax::Minimum => a.minimum(b),
1215                MinMax::MinimumNumberNsz => a.min(b),
1216                MinMax::Maximum => a.maximum(b),
1217                MinMax::MaximumNumberNsz => a.max(b),
1218            };
1219            self.adjust_nan(result, &[a, b])
1220        };
1221
1222        interp_ok(res.into())
1223    }
1224
1225    fn float_minmax_intrinsic<F>(
1226        &mut self,
1227        args: &[OpTy<'tcx, M::Provenance>],
1228        op: MinMax,
1229        dest: &PlaceTy<'tcx, M::Provenance>,
1230    ) -> InterpResult<'tcx, ()>
1231    where
1232        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1233    {
1234        let res =
1235            self.float_minmax::<F>(self.read_scalar(&args[0])?, self.read_scalar(&args[1])?, op)?;
1236        self.write_scalar(res, dest)?;
1237        interp_ok(())
1238    }
1239
1240    fn float_copysign_intrinsic<F>(
1241        &mut self,
1242        args: &[OpTy<'tcx, M::Provenance>],
1243        dest: &PlaceTy<'tcx, M::Provenance>,
1244    ) -> InterpResult<'tcx, ()>
1245    where
1246        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1247    {
1248        let a: F = self.read_scalar(&args[0])?.to_float()?;
1249        let b: F = self.read_scalar(&args[1])?.to_float()?;
1250        // bitwise, no NaN adjustments
1251        self.write_scalar(a.copy_sign(b), dest)?;
1252        interp_ok(())
1253    }
1254
1255    fn float_round<F>(
1256        &mut self,
1257        x: F,
1258        mode: rustc_apfloat::Round,
1259    ) -> InterpResult<'tcx, Scalar<M::Provenance>>
1260    where
1261        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1262    {
1263        let res = x.round_to_integral(mode).value;
1264        let res = self.adjust_nan(res, &[x]);
1265        interp_ok(res.into())
1266    }
1267
1268    fn float_muladd<F>(
1269        &self,
1270        a: Scalar<M::Provenance>,
1271        b: Scalar<M::Provenance>,
1272        c: Scalar<M::Provenance>,
1273        typ: MulAddType,
1274    ) -> InterpResult<'tcx, Scalar<M::Provenance>>
1275    where
1276        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1277    {
1278        let a: F = a.to_float()?;
1279        let b: F = b.to_float()?;
1280        let c: F = c.to_float()?;
1281
1282        let fuse = typ == MulAddType::Fused || M::float_fuse_mul_add(self);
1283
1284        let res = if fuse { a.mul_add(b, c).value } else { ((a * b).value + c).value };
1285        let res = self.adjust_nan(res, &[a, b, c]);
1286        interp_ok(res.into())
1287    }
1288
1289    fn float_muladd_intrinsic<F>(
1290        &mut self,
1291        args: &[OpTy<'tcx, M::Provenance>],
1292        dest: &PlaceTy<'tcx, M::Provenance>,
1293        typ: MulAddType,
1294    ) -> InterpResult<'tcx, ()>
1295    where
1296        F: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F> + Into<Scalar<M::Provenance>>,
1297    {
1298        let a = self.read_scalar(&args[0])?;
1299        let b = self.read_scalar(&args[1])?;
1300        let c = self.read_scalar(&args[2])?;
1301
1302        let res = self.float_muladd::<F>(a, b, c, typ)?;
1303        self.write_scalar(res, dest)?;
1304        interp_ok(())
1305    }
1306
1307    /// Converts `src` from floating point to integer type `dest_ty`
1308    /// after rounding with mode `round`.
1309    /// Returns `None` if `f` is NaN or out of range.
1310    pub fn float_to_int_checked(
1311        &self,
1312        src: &ImmTy<'tcx, M::Provenance>,
1313        cast_to: TyAndLayout<'tcx>,
1314        round: rustc_apfloat::Round,
1315    ) -> InterpResult<'tcx, Option<ImmTy<'tcx, M::Provenance>>> {
1316        fn float_to_int_inner<'tcx, F: rustc_apfloat::Float, M: Machine<'tcx>>(
1317            ecx: &InterpCx<'tcx, M>,
1318            src: F,
1319            cast_to: TyAndLayout<'tcx>,
1320            round: rustc_apfloat::Round,
1321        ) -> (Scalar<M::Provenance>, rustc_apfloat::Status) {
1322            let int_size = cast_to.layout.size;
1323            match cast_to.ty.kind() {
1324                // Unsigned
1325                ty::Uint(_) => {
1326                    let res = src.to_u128_r(int_size.bits_usize(), round, &mut false);
1327                    (Scalar::from_uint(res.value, int_size), res.status)
1328                }
1329                // Signed
1330                ty::Int(_) => {
1331                    let res = src.to_i128_r(int_size.bits_usize(), round, &mut false);
1332                    (Scalar::from_int(res.value, int_size), res.status)
1333                }
1334                // Nothing else
1335                _ => ::rustc_span::macros::bug_impl(Some(ecx.cur_span()),
    format_args!("attempted float-to-int conversion with non-int output type {0}",
        cast_to.ty), Location::caller())span_bug!(
1336                    ecx.cur_span(),
1337                    "attempted float-to-int conversion with non-int output type {}",
1338                    cast_to.ty,
1339                ),
1340            }
1341        }
1342
1343        let ty::Float(fty) = src.layout.ty.kind() else {
1344            ::rustc_span::macros::bug_impl(None,
    format_args!("float_to_int_checked: non-float input type {0}",
        src.layout.ty), Location::caller())bug!("float_to_int_checked: non-float input type {}", src.layout.ty)
1345        };
1346
1347        let (val, status) = match fty {
1348            FloatTy::F16 => float_to_int_inner(self, src.to_scalar().to_f16()?, cast_to, round),
1349            FloatTy::F32 => float_to_int_inner(self, src.to_scalar().to_f32()?, cast_to, round),
1350            FloatTy::F64 => float_to_int_inner(self, src.to_scalar().to_f64()?, cast_to, round),
1351            FloatTy::F128 => float_to_int_inner(self, src.to_scalar().to_f128()?, cast_to, round),
1352        };
1353
1354        if status.intersects(
1355            rustc_apfloat::Status::INVALID_OP
1356                | rustc_apfloat::Status::OVERFLOW
1357                | rustc_apfloat::Status::UNDERFLOW,
1358        ) {
1359            // Floating point value is NaN (flagged with INVALID_OP) or outside the range
1360            // of values of the integer type (flagged with OVERFLOW or UNDERFLOW).
1361            interp_ok(None)
1362        } else {
1363            // Floating point value can be represented by the integer type after rounding.
1364            // The INEXACT flag is ignored on purpose to allow rounding.
1365            interp_ok(Some(ImmTy::from_scalar(val, cast_to)))
1366        }
1367    }
1368
1369    /// Get the MPlace of the key from the place storing the VaList.
1370    pub(super) fn va_list_key_field<P: Projectable<'tcx, M::Provenance>>(
1371        &self,
1372        va_list: &P,
1373    ) -> InterpResult<'tcx, P> {
1374        // The struct wrapped by VaList.
1375        let va_list_inner = self.project_field(va_list, FieldIdx::ZERO)?;
1376
1377        // Find the first pointer field in this struct. The exact index is target-specific.
1378        let ty::Adt(adt, substs) = va_list_inner.layout().ty.kind() else {
1379            ::rustc_span::macros::bug_impl(None,
    format_args!("invalid VaListImpl layout"), Location::caller());bug!("invalid VaListImpl layout");
1380        };
1381
1382        for (i, field) in adt.non_enum_variant().fields.iter().enumerate() {
1383            if field.ty(*self.tcx, *substs).skip_norm_wip().is_raw_ptr() {
1384                return self.project_field(&va_list_inner, FieldIdx::from_usize(i));
1385            }
1386        }
1387
1388        ::rustc_span::macros::bug_impl(None,
    format_args!("no VaListImpl field is a pointer"), Location::caller());bug!("no VaListImpl field is a pointer");
1389    }
1390}