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