Skip to main content

rustc_const_eval/interpret/
intrinsics.rs

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