1 //! Intrinsics and other functions that the miri engine executes without
2 //! looking at their MIR. Intrinsics/functions supported here are shared by CTFE
5 use rustc_hir::def_id::DefId;
6 use rustc_middle::mir::{
9 Allocation, ConstAllocation, ConstValue, GlobalId, InterpResult, PointerArithmetic, Scalar,
11 BinOp, NonDivergingIntrinsic,
14 use rustc_middle::ty::layout::LayoutOf as _;
15 use rustc_middle::ty::subst::SubstsRef;
16 use rustc_middle::ty::{Ty, TyCtxt};
17 use rustc_span::symbol::{sym, Symbol};
18 use rustc_target::abi::{Abi, Align, Primitive, Size};
21 util::ensure_monomorphic_enough, CheckInAllocMsg, ImmTy, InterpCx, Machine, OpTy, PlaceTy,
27 fn numeric_intrinsic<Prov>(name: Symbol, bits: u128, kind: Primitive) -> Scalar<Prov> {
28 let size = match kind {
29 Primitive::Int(integer, _) => integer.size(),
30 _ => bug!("invalid `{}` argument: {:?}", name, bits),
32 let extra = 128 - u128::from(size.bits());
33 let bits_out = match name {
34 sym::ctpop => u128::from(bits.count_ones()),
35 sym::ctlz => u128::from(bits.leading_zeros()) - extra,
36 sym::cttz => u128::from((bits << extra).trailing_zeros()) - extra,
37 sym::bswap => (bits << extra).swap_bytes(),
38 sym::bitreverse => (bits << extra).reverse_bits(),
39 _ => bug!("not a numeric intrinsic: {}", name),
41 Scalar::from_uint(bits_out, size)
44 /// Directly returns an `Allocation` containing an absolute path representation of the given type.
45 pub(crate) fn alloc_type_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ConstAllocation<'tcx> {
46 let path = crate::util::type_name(tcx, ty);
47 let alloc = Allocation::from_bytes_byte_aligned_immutable(path.into_bytes());
48 tcx.intern_const_alloc(alloc)
51 /// The logic for all nullary intrinsics is implemented here. These intrinsics don't get evaluated
52 /// inside an `InterpCx` and instead have their value computed directly from rustc internal info.
53 pub(crate) fn eval_nullary_intrinsic<'tcx>(
55 param_env: ty::ParamEnv<'tcx>,
57 substs: SubstsRef<'tcx>,
58 ) -> InterpResult<'tcx, ConstValue<'tcx>> {
59 let tp_ty = substs.type_at(0);
60 let name = tcx.item_name(def_id);
63 ensure_monomorphic_enough(tcx, tp_ty)?;
64 let alloc = alloc_type_name(tcx, tp_ty);
65 ConstValue::Slice { data: alloc, start: 0, end: alloc.inner().len() }
68 ensure_monomorphic_enough(tcx, tp_ty)?;
69 ConstValue::from_bool(tp_ty.needs_drop(tcx, param_env))
71 sym::pref_align_of => {
72 // Correctly handles non-monomorphic calls, so there is no need for ensure_monomorphic_enough.
73 let layout = tcx.layout_of(param_env.and(tp_ty)).map_err(|e| err_inval!(Layout(e)))?;
74 ConstValue::from_machine_usize(layout.align.pref.bytes(), &tcx)
77 ensure_monomorphic_enough(tcx, tp_ty)?;
78 ConstValue::from_u64(tcx.type_id_hash(tp_ty))
80 sym::variant_count => match tp_ty.kind() {
81 // Correctly handles non-monomorphic calls, so there is no need for ensure_monomorphic_enough.
82 ty::Adt(ref adt, _) => {
83 ConstValue::from_machine_usize(adt.variants().len() as u64, &tcx)
85 ty::Alias(..) | ty::Param(_) | ty::Placeholder(_) | ty::Infer(_) => {
86 throw_inval!(TooGeneric)
88 ty::Bound(_, _) => bug!("bound ty during ctfe"),
102 | ty::Dynamic(_, _, _)
104 | ty::Generator(_, _, _)
105 | ty::GeneratorWitness(_)
108 | ty::Error(_) => ConstValue::from_machine_usize(0u64, &tcx),
110 other => bug!("`{}` is not a zero arg intrinsic", other),
114 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
115 /// Returns `true` if emulation happened.
116 /// Here we implement the intrinsics that are common to all Miri instances; individual machines can add their own
117 /// intrinsic handling.
118 pub fn emulate_intrinsic(
120 instance: ty::Instance<'tcx>,
121 args: &[OpTy<'tcx, M::Provenance>],
122 dest: &PlaceTy<'tcx, M::Provenance>,
123 ret: Option<mir::BasicBlock>,
124 ) -> InterpResult<'tcx, bool> {
125 let substs = instance.substs;
126 let intrinsic_name = self.tcx.item_name(instance.def_id());
128 // First handle intrinsics without return place.
129 let ret = match ret {
130 None => match intrinsic_name {
131 sym::transmute => throw_ub_format!("transmuting to uninhabited type"),
132 sym::abort => M::abort(self, "the program aborted execution".to_owned())?,
133 // Unsupported diverging intrinsic.
134 _ => return Ok(false),
139 match intrinsic_name {
140 sym::caller_location => {
141 let span = self.find_closest_untracked_caller_location();
142 let location = self.alloc_caller_location_for_span(span);
143 self.write_immediate(location.to_ref(self), dest)?;
146 sym::min_align_of_val | sym::size_of_val => {
147 // Avoid `deref_operand` -- this is not a deref, the ptr does not have to be
149 let place = self.ref_to_mplace(&self.read_immediate(&args[0])?)?;
150 let (size, align) = self
151 .size_and_align_of_mplace(&place)?
152 .ok_or_else(|| err_unsup_format!("`extern type` does not have known layout"))?;
154 let result = match intrinsic_name {
155 sym::min_align_of_val => align.bytes(),
156 sym::size_of_val => size.bytes(),
160 self.write_scalar(Scalar::from_machine_usize(result, self), dest)?;
167 | sym::variant_count => {
168 let gid = GlobalId { instance, promoted: None };
169 let ty = match intrinsic_name {
170 sym::pref_align_of | sym::variant_count => self.tcx.types.usize,
171 sym::needs_drop => self.tcx.types.bool,
172 sym::type_id => self.tcx.types.u64,
173 sym::type_name => self.tcx.mk_static_str(),
176 let val = self.ctfe_query(None, |tcx| {
177 tcx.const_eval_global_id(self.param_env, gid, Some(tcx.span))
179 let val = self.const_val_to_op(val, ty, Some(dest.layout))?;
180 self.copy_op(&val, dest, /*allow_transmute*/ false)?;
189 | sym::bitreverse => {
190 let ty = substs.type_at(0);
191 let layout_of = self.layout_of(ty)?;
192 let val = self.read_scalar(&args[0])?;
193 let bits = val.to_bits(layout_of.size)?;
194 let kind = match layout_of.abi {
195 Abi::Scalar(scalar) => scalar.primitive(),
198 "{} called on invalid type {:?}",
203 let (nonzero, intrinsic_name) = match intrinsic_name {
204 sym::cttz_nonzero => (true, sym::cttz),
205 sym::ctlz_nonzero => (true, sym::ctlz),
206 other => (false, other),
208 if nonzero && bits == 0 {
209 throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
211 let out_val = numeric_intrinsic(intrinsic_name, bits, kind);
212 self.write_scalar(out_val, dest)?;
214 sym::add_with_overflow | sym::sub_with_overflow | sym::mul_with_overflow => {
215 let lhs = self.read_immediate(&args[0])?;
216 let rhs = self.read_immediate(&args[1])?;
217 let bin_op = match intrinsic_name {
218 sym::add_with_overflow => BinOp::Add,
219 sym::sub_with_overflow => BinOp::Sub,
220 sym::mul_with_overflow => BinOp::Mul,
223 self.binop_with_overflow(
224 bin_op, /*force_overflow_checks*/ true, &lhs, &rhs, dest,
227 sym::saturating_add | sym::saturating_sub => {
228 let l = self.read_immediate(&args[0])?;
229 let r = self.read_immediate(&args[1])?;
230 let val = self.saturating_arith(
231 if intrinsic_name == sym::saturating_add { BinOp::Add } else { BinOp::Sub },
235 self.write_scalar(val, dest)?;
237 sym::discriminant_value => {
238 let place = self.deref_operand(&args[0])?;
239 let discr_val = self.read_discriminant(&place.into())?.0;
240 self.write_scalar(discr_val, dest)?;
243 let l = self.read_immediate(&args[0])?;
244 let r = self.read_immediate(&args[1])?;
245 self.exact_div(&l, &r, dest)?;
253 | sym::unchecked_rem => {
254 let l = self.read_immediate(&args[0])?;
255 let r = self.read_immediate(&args[1])?;
256 let bin_op = match intrinsic_name {
257 sym::unchecked_shl => BinOp::Shl,
258 sym::unchecked_shr => BinOp::Shr,
259 sym::unchecked_add => BinOp::Add,
260 sym::unchecked_sub => BinOp::Sub,
261 sym::unchecked_mul => BinOp::Mul,
262 sym::unchecked_div => BinOp::Div,
263 sym::unchecked_rem => BinOp::Rem,
266 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, &l, &r)?;
268 let layout = self.layout_of(substs.type_at(0))?;
269 let r_val = r.to_scalar().to_bits(layout.size)?;
270 if let sym::unchecked_shl | sym::unchecked_shr = intrinsic_name {
271 throw_ub_format!("overflowing shift by {} in `{}`", r_val, intrinsic_name);
273 throw_ub_format!("overflow executing `{}`", intrinsic_name);
276 self.write_scalar(val, dest)?;
278 sym::rotate_left | sym::rotate_right => {
279 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
280 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
281 let layout = self.layout_of(substs.type_at(0))?;
282 let val = self.read_scalar(&args[0])?;
283 let val_bits = val.to_bits(layout.size)?;
284 let raw_shift = self.read_scalar(&args[1])?;
285 let raw_shift_bits = raw_shift.to_bits(layout.size)?;
286 let width_bits = u128::from(layout.size.bits());
287 let shift_bits = raw_shift_bits % width_bits;
288 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
289 let result_bits = if intrinsic_name == sym::rotate_left {
290 (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
292 (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
294 let truncated_bits = self.truncate(result_bits, layout);
295 let result = Scalar::from_uint(truncated_bits, layout.size);
296 self.write_scalar(result, dest)?;
299 self.copy_intrinsic(&args[0], &args[1], &args[2], /*nonoverlapping*/ false)?;
301 sym::write_bytes => {
302 self.write_bytes_intrinsic(&args[0], &args[1], &args[2])?;
305 let ptr = self.read_pointer(&args[0])?;
306 let offset_count = self.read_scalar(&args[1])?.to_machine_isize(self)?;
307 let pointee_ty = substs.type_at(0);
309 let offset_ptr = self.ptr_offset_inbounds(ptr, pointee_ty, offset_count)?;
310 self.write_pointer(offset_ptr, dest)?;
312 sym::arith_offset => {
313 let ptr = self.read_pointer(&args[0])?;
314 let offset_count = self.read_scalar(&args[1])?.to_machine_isize(self)?;
315 let pointee_ty = substs.type_at(0);
317 let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
318 let offset_bytes = offset_count.wrapping_mul(pointee_size);
319 let offset_ptr = ptr.wrapping_signed_offset(offset_bytes, self);
320 self.write_pointer(offset_ptr, dest)?;
322 sym::ptr_offset_from | sym::ptr_offset_from_unsigned => {
323 let a = self.read_pointer(&args[0])?;
324 let b = self.read_pointer(&args[1])?;
326 let usize_layout = self.layout_of(self.tcx.types.usize)?;
327 let isize_layout = self.layout_of(self.tcx.types.isize)?;
329 // Get offsets for both that are at least relative to the same base.
330 let (a_offset, b_offset) =
331 match (self.ptr_try_get_alloc_id(a), self.ptr_try_get_alloc_id(b)) {
332 (Err(a), Err(b)) => {
333 // Neither pointer points to an allocation.
334 // If these are inequal or null, this *will* fail the deref check below.
337 (Err(_), _) | (_, Err(_)) => {
338 // We managed to find a valid allocation for one pointer, but not the other.
339 // That means they are definitely not pointing to the same allocation.
341 "`{}` called on pointers into different allocations",
345 (Ok((a_alloc_id, a_offset, _)), Ok((b_alloc_id, b_offset, _))) => {
346 // Found allocation for both. They must be into the same allocation.
347 if a_alloc_id != b_alloc_id {
349 "`{}` called on pointers into different allocations",
353 // Use these offsets for distance calculation.
354 (a_offset.bytes(), b_offset.bytes())
360 // Addresses are unsigned, so this is a `usize` computation. We have to do the
361 // overflow check separately anyway.
362 let (val, overflowed, _ty) = {
363 let a_offset = ImmTy::from_uint(a_offset, usize_layout);
364 let b_offset = ImmTy::from_uint(b_offset, usize_layout);
365 self.overflowing_binary_op(BinOp::Sub, &a_offset, &b_offset)?
369 if intrinsic_name == sym::ptr_offset_from_unsigned {
371 "`{}` called when first pointer has smaller offset than second: {} < {}",
377 // The signed form of the intrinsic allows this. If we interpret the
378 // difference as isize, we'll get the proper signed difference. If that
379 // seems *positive*, they were more than isize::MAX apart.
380 let dist = val.to_machine_isize(self)?;
383 "`{}` called when first pointer is too far before second",
390 let dist = val.to_machine_isize(self)?;
391 // If converting to isize produced a *negative* result, we had an overflow
392 // because they were more than isize::MAX apart.
395 "`{}` called when first pointer is too far ahead of second",
403 // Check that the range between them is dereferenceable ("in-bounds or one past the
404 // end of the same allocation"). This is like the check in ptr_offset_inbounds.
405 let min_ptr = if dist >= 0 { b } else { a };
406 self.check_ptr_access_align(
408 Size::from_bytes(dist.unsigned_abs()),
410 CheckInAllocMsg::OffsetFromTest,
413 // Perform division by size to compute return value.
414 let ret_layout = if intrinsic_name == sym::ptr_offset_from_unsigned {
415 assert!(0 <= dist && dist <= self.machine_isize_max());
418 assert!(self.machine_isize_min() <= dist && dist <= self.machine_isize_max());
421 let pointee_layout = self.layout_of(substs.type_at(0))?;
422 // If ret_layout is unsigned, we checked that so is the distance, so we are good.
423 let val = ImmTy::from_int(dist, ret_layout);
424 let size = ImmTy::from_int(pointee_layout.size.bytes(), ret_layout);
425 self.exact_div(&val, &size, dest)?;
429 self.copy_op(&args[0], dest, /*allow_transmute*/ true)?;
431 sym::assert_inhabited | sym::assert_zero_valid | sym::assert_uninit_valid => {
432 let ty = instance.substs.type_at(0);
433 let layout = self.layout_of(ty)?;
435 // For *all* intrinsics we first check `is_uninhabited` to give a more specific
437 if layout.abi.is_uninhabited() {
438 // The run-time intrinsic panics just to get a good backtrace; here we abort
439 // since there is no problem showing a backtrace even for aborts.
443 "aborted execution: attempted to instantiate uninhabited type `{}`",
449 if intrinsic_name == sym::assert_zero_valid {
450 let should_panic = !self.tcx.permits_zero_init(layout);
456 "aborted execution: attempted to zero-initialize type `{}`, which is invalid",
463 if intrinsic_name == sym::assert_uninit_valid {
464 let should_panic = !self.tcx.permits_uninit_init(layout);
470 "aborted execution: attempted to leave type `{}` uninitialized, which is invalid",
477 sym::simd_insert => {
478 let index = u64::from(self.read_scalar(&args[1])?.to_u32()?);
480 let (input, input_len) = self.operand_to_simd(&args[0])?;
481 let (dest, dest_len) = self.place_to_simd(dest)?;
482 assert_eq!(input_len, dest_len, "Return vector length must match input length");
485 "Index `{}` must be in bounds of vector with length {}`",
490 for i in 0..dest_len {
491 let place = self.mplace_index(&dest, i)?;
492 let value = if i == index {
495 self.mplace_index(&input, i)?.into()
497 self.copy_op(&value, &place.into(), /*allow_transmute*/ false)?;
500 sym::simd_extract => {
501 let index = u64::from(self.read_scalar(&args[1])?.to_u32()?);
502 let (input, input_len) = self.operand_to_simd(&args[0])?;
505 "index `{}` must be in bounds of vector with length `{}`",
510 &self.mplace_index(&input, index)?.into(),
512 /*allow_transmute*/ false,
515 sym::likely | sym::unlikely | sym::black_box => {
516 // These just return their argument
517 self.copy_op(&args[0], dest, /*allow_transmute*/ false)?;
520 let result = self.raw_eq_intrinsic(&args[0], &args[1])?;
521 self.write_scalar(result, dest)?;
524 sym::vtable_size => {
525 let ptr = self.read_pointer(&args[0])?;
526 let (size, _align) = self.get_vtable_size_and_align(ptr)?;
527 self.write_scalar(Scalar::from_machine_usize(size.bytes(), self), dest)?;
529 sym::vtable_align => {
530 let ptr = self.read_pointer(&args[0])?;
531 let (_size, align) = self.get_vtable_size_and_align(ptr)?;
532 self.write_scalar(Scalar::from_machine_usize(align.bytes(), self), dest)?;
535 _ => return Ok(false),
538 trace!("{:?}", self.dump_place(**dest));
539 self.go_to_block(ret);
543 pub(super) fn emulate_nondiverging_intrinsic(
545 intrinsic: &NonDivergingIntrinsic<'tcx>,
546 ) -> InterpResult<'tcx> {
548 NonDivergingIntrinsic::Assume(op) => {
549 let op = self.eval_operand(op, None)?;
550 let cond = self.read_scalar(&op)?.to_bool()?;
552 throw_ub_format!("`assume` called with `false`");
556 NonDivergingIntrinsic::CopyNonOverlapping(mir::CopyNonOverlapping {
561 let src = self.eval_operand(src, None)?;
562 let dst = self.eval_operand(dst, None)?;
563 let count = self.eval_operand(count, None)?;
564 self.copy_intrinsic(&src, &dst, &count, /* nonoverlapping */ true)
571 a: &ImmTy<'tcx, M::Provenance>,
572 b: &ImmTy<'tcx, M::Provenance>,
573 dest: &PlaceTy<'tcx, M::Provenance>,
574 ) -> InterpResult<'tcx> {
575 // Performs an exact division, resulting in undefined behavior where
576 // `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`.
577 // First, check x % y != 0 (or if that computation overflows).
578 let (res, overflow, _ty) = self.overflowing_binary_op(BinOp::Rem, &a, &b)?;
579 assert!(!overflow); // All overflow is UB, so this should never return on overflow.
580 if res.assert_bits(a.layout.size) != 0 {
581 throw_ub_format!("exact_div: {} cannot be divided by {} without remainder", a, b)
583 // `Rem` says this is all right, so we can let `Div` do its job.
584 self.binop_ignore_overflow(BinOp::Div, &a, &b, dest)
587 pub fn saturating_arith(
590 l: &ImmTy<'tcx, M::Provenance>,
591 r: &ImmTy<'tcx, M::Provenance>,
592 ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
593 assert!(matches!(mir_op, BinOp::Add | BinOp::Sub));
594 let (val, overflowed, _ty) = self.overflowing_binary_op(mir_op, l, r)?;
596 let size = l.layout.size;
597 let num_bits = size.bits();
598 if l.layout.abi.is_signed() {
599 // For signed ints the saturated value depends on the sign of the first
600 // term since the sign of the second term can be inferred from this and
601 // the fact that the operation has overflowed (if either is 0 no
602 // overflow can occur)
603 let first_term: u128 = l.to_scalar().to_bits(l.layout.size)?;
604 let first_term_positive = first_term & (1 << (num_bits - 1)) == 0;
605 if first_term_positive {
606 // Negative overflow not possible since the positive first term
607 // can only increase an (in range) negative term for addition
608 // or corresponding negated positive term for subtraction
609 Scalar::from_int(size.signed_int_max(), size)
611 // Positive overflow not possible for similar reason
613 Scalar::from_int(size.signed_int_min(), size)
617 if matches!(mir_op, BinOp::Add) {
619 Scalar::from_uint(size.unsigned_int_max(), size)
622 Scalar::from_uint(0u128, size)
630 /// Offsets a pointer by some multiple of its type, returning an error if the pointer leaves its
631 /// allocation. For integer pointers, we consider each of them their own tiny allocation of size
632 /// 0, so offset-by-0 (and only 0) is okay -- except that null cannot be offset by _any_ value.
633 pub fn ptr_offset_inbounds(
635 ptr: Pointer<Option<M::Provenance>>,
636 pointee_ty: Ty<'tcx>,
638 ) -> InterpResult<'tcx, Pointer<Option<M::Provenance>>> {
639 // We cannot overflow i64 as a type's size must be <= isize::MAX.
640 let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
641 // The computed offset, in bytes, must not overflow an isize.
642 // `checked_mul` enforces a too small bound, but no actual allocation can be big enough for
643 // the difference to be noticeable.
645 offset_count.checked_mul(pointee_size).ok_or(err_ub!(PointerArithOverflow))?;
646 // The offset being in bounds cannot rely on "wrapping around" the address space.
647 // So, first rule out overflows in the pointer arithmetic.
648 let offset_ptr = ptr.signed_offset(offset_bytes, self)?;
649 // ptr and offset_ptr must be in bounds of the same allocated object. This means all of the
650 // memory between these pointers must be accessible. Note that we do not require the
651 // pointers to be properly aligned (unlike a read/write operation).
652 let min_ptr = if offset_bytes >= 0 { ptr } else { offset_ptr };
653 // This call handles checking for integer/null pointers.
654 self.check_ptr_access_align(
656 Size::from_bytes(offset_bytes.unsigned_abs()),
658 CheckInAllocMsg::PointerArithmeticTest,
663 /// Copy `count*size_of::<T>()` many bytes from `*src` to `*dst`.
664 pub(crate) fn copy_intrinsic(
666 src: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
667 dst: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
668 count: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
669 nonoverlapping: bool,
670 ) -> InterpResult<'tcx> {
671 let count = self.read_scalar(&count)?.to_machine_usize(self)?;
672 let layout = self.layout_of(src.layout.ty.builtin_deref(true).unwrap().ty)?;
673 let (size, align) = (layout.size, layout.align.abi);
674 // `checked_mul` enforces a too small bound (the correct one would probably be machine_isize_max),
675 // but no actual allocation can be big enough for the difference to be noticeable.
676 let size = size.checked_mul(count, self).ok_or_else(|| {
678 "overflow computing total size of `{}`",
679 if nonoverlapping { "copy_nonoverlapping" } else { "copy" }
683 let src = self.read_pointer(&src)?;
684 let dst = self.read_pointer(&dst)?;
686 self.mem_copy(src, align, dst, align, size, nonoverlapping)
689 pub(crate) fn write_bytes_intrinsic(
691 dst: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
692 byte: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
693 count: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
694 ) -> InterpResult<'tcx> {
695 let layout = self.layout_of(dst.layout.ty.builtin_deref(true).unwrap().ty)?;
697 let dst = self.read_pointer(&dst)?;
698 let byte = self.read_scalar(&byte)?.to_u8()?;
699 let count = self.read_scalar(&count)?.to_machine_usize(self)?;
701 // `checked_mul` enforces a too small bound (the correct one would probably be machine_isize_max),
702 // but no actual allocation can be big enough for the difference to be noticeable.
705 .checked_mul(count, self)
706 .ok_or_else(|| err_ub_format!("overflow computing total size of `write_bytes`"))?;
708 let bytes = std::iter::repeat(byte).take(len.bytes_usize());
709 self.write_bytes_ptr(dst, bytes)
712 pub(crate) fn raw_eq_intrinsic(
714 lhs: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
715 rhs: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
716 ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
717 let layout = self.layout_of(lhs.layout.ty.builtin_deref(true).unwrap().ty)?;
718 assert!(layout.is_sized());
720 let get_bytes = |this: &InterpCx<'mir, 'tcx, M>,
721 op: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
723 -> InterpResult<'tcx, &[u8]> {
724 let ptr = this.read_pointer(op)?;
725 let Some(alloc_ref) = self.get_ptr_alloc(ptr, size, Align::ONE)? else {
729 if alloc_ref.has_provenance() {
730 throw_ub_format!("`raw_eq` on bytes with provenance");
732 alloc_ref.get_bytes_strip_provenance()
735 let lhs_bytes = get_bytes(self, lhs, layout.size)?;
736 let rhs_bytes = get_bytes(self, rhs, layout.size)?;
737 Ok(Scalar::from_bool(lhs_bytes == rhs_bytes))