]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/interpret/intrinsics.rs
Auto merge of #99520 - matthiaskrgr:rollup-05uuv5s, r=matthiaskrgr
[rust.git] / compiler / rustc_const_eval / src / interpret / intrinsics.rs
1 //! Intrinsics and other functions that the miri engine executes without
2 //! looking at their MIR. Intrinsics/functions supported here are shared by CTFE
3 //! and miri.
4
5 use std::convert::TryFrom;
6
7 use rustc_hir::def_id::DefId;
8 use rustc_middle::mir::{
9     self,
10     interpret::{ConstValue, GlobalId, InterpResult, Scalar},
11     BinOp,
12 };
13 use rustc_middle::ty;
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};
19
20 use super::{
21     util::ensure_monomorphic_enough, CheckInAllocMsg, ImmTy, InterpCx, Machine, OpTy, PlaceTy,
22     Pointer,
23 };
24
25 mod caller_location;
26 mod type_name;
27
28 fn numeric_intrinsic<Prov>(name: Symbol, bits: u128, kind: Primitive) -> Scalar<Prov> {
29     let size = match kind {
30         Primitive::Int(integer, _) => integer.size(),
31         _ => bug!("invalid `{}` argument: {:?}", name, bits),
32     };
33     let extra = 128 - u128::from(size.bits());
34     let bits_out = match name {
35         sym::ctpop => u128::from(bits.count_ones()),
36         sym::ctlz => u128::from(bits.leading_zeros()) - extra,
37         sym::cttz => u128::from((bits << extra).trailing_zeros()) - extra,
38         sym::bswap => (bits << extra).swap_bytes(),
39         sym::bitreverse => (bits << extra).reverse_bits(),
40         _ => bug!("not a numeric intrinsic: {}", name),
41     };
42     Scalar::from_uint(bits_out, size)
43 }
44
45 /// The logic for all nullary intrinsics is implemented here. These intrinsics don't get evaluated
46 /// inside an `InterpCx` and instead have their value computed directly from rustc internal info.
47 pub(crate) fn eval_nullary_intrinsic<'tcx>(
48     tcx: TyCtxt<'tcx>,
49     param_env: ty::ParamEnv<'tcx>,
50     def_id: DefId,
51     substs: SubstsRef<'tcx>,
52 ) -> InterpResult<'tcx, ConstValue<'tcx>> {
53     let tp_ty = substs.type_at(0);
54     let name = tcx.item_name(def_id);
55     Ok(match name {
56         sym::type_name => {
57             ensure_monomorphic_enough(tcx, tp_ty)?;
58             let alloc = type_name::alloc_type_name(tcx, tp_ty);
59             ConstValue::Slice { data: alloc, start: 0, end: alloc.inner().len() }
60         }
61         sym::needs_drop => {
62             ensure_monomorphic_enough(tcx, tp_ty)?;
63             ConstValue::from_bool(tp_ty.needs_drop(tcx, param_env))
64         }
65         sym::pref_align_of => {
66             // Correctly handles non-monomorphic calls, so there is no need for ensure_monomorphic_enough.
67             let layout = tcx.layout_of(param_env.and(tp_ty)).map_err(|e| err_inval!(Layout(e)))?;
68             ConstValue::from_machine_usize(layout.align.pref.bytes(), &tcx)
69         }
70         sym::type_id => {
71             ensure_monomorphic_enough(tcx, tp_ty)?;
72             ConstValue::from_u64(tcx.type_id_hash(tp_ty))
73         }
74         sym::variant_count => match tp_ty.kind() {
75             // Correctly handles non-monomorphic calls, so there is no need for ensure_monomorphic_enough.
76             ty::Adt(ref adt, _) => {
77                 ConstValue::from_machine_usize(adt.variants().len() as u64, &tcx)
78             }
79             ty::Projection(_)
80             | ty::Opaque(_, _)
81             | ty::Param(_)
82             | ty::Bound(_, _)
83             | ty::Placeholder(_)
84             | ty::Infer(_) => throw_inval!(TooGeneric),
85             ty::Bool
86             | ty::Char
87             | ty::Int(_)
88             | ty::Uint(_)
89             | ty::Float(_)
90             | ty::Foreign(_)
91             | ty::Str
92             | ty::Array(_, _)
93             | ty::Slice(_)
94             | ty::RawPtr(_)
95             | ty::Ref(_, _, _)
96             | ty::FnDef(_, _)
97             | ty::FnPtr(_)
98             | ty::Dynamic(_, _)
99             | ty::Closure(_, _)
100             | ty::Generator(_, _, _)
101             | ty::GeneratorWitness(_)
102             | ty::Never
103             | ty::Tuple(_)
104             | ty::Error(_) => ConstValue::from_machine_usize(0u64, &tcx),
105         },
106         other => bug!("`{}` is not a zero arg intrinsic", other),
107     })
108 }
109
110 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
111     /// Returns `true` if emulation happened.
112     /// Here we implement the intrinsics that are common to all Miri instances; individual machines can add their own
113     /// intrinsic handling.
114     pub fn emulate_intrinsic(
115         &mut self,
116         instance: ty::Instance<'tcx>,
117         args: &[OpTy<'tcx, M::Provenance>],
118         dest: &PlaceTy<'tcx, M::Provenance>,
119         ret: Option<mir::BasicBlock>,
120     ) -> InterpResult<'tcx, bool> {
121         let substs = instance.substs;
122         let intrinsic_name = self.tcx.item_name(instance.def_id());
123
124         // First handle intrinsics without return place.
125         let ret = match ret {
126             None => match intrinsic_name {
127                 sym::transmute => throw_ub_format!("transmuting to uninhabited type"),
128                 sym::abort => M::abort(self, "the program aborted execution".to_owned())?,
129                 // Unsupported diverging intrinsic.
130                 _ => return Ok(false),
131             },
132             Some(p) => p,
133         };
134
135         match intrinsic_name {
136             sym::caller_location => {
137                 let span = self.find_closest_untracked_caller_location();
138                 let location = self.alloc_caller_location_for_span(span);
139                 self.write_immediate(location.to_ref(self), dest)?;
140             }
141
142             sym::min_align_of_val | sym::size_of_val => {
143                 // Avoid `deref_operand` -- this is not a deref, the ptr does not have to be
144                 // dereferenceable!
145                 let place = self.ref_to_mplace(&self.read_immediate(&args[0])?)?;
146                 let (size, align) = self
147                     .size_and_align_of_mplace(&place)?
148                     .ok_or_else(|| err_unsup_format!("`extern type` does not have known layout"))?;
149
150                 let result = match intrinsic_name {
151                     sym::min_align_of_val => align.bytes(),
152                     sym::size_of_val => size.bytes(),
153                     _ => bug!(),
154                 };
155
156                 self.write_scalar(Scalar::from_machine_usize(result, self), dest)?;
157             }
158
159             sym::pref_align_of
160             | sym::needs_drop
161             | sym::type_id
162             | sym::type_name
163             | sym::variant_count => {
164                 let gid = GlobalId { instance, promoted: None };
165                 let ty = match intrinsic_name {
166                     sym::pref_align_of | sym::variant_count => self.tcx.types.usize,
167                     sym::needs_drop => self.tcx.types.bool,
168                     sym::type_id => self.tcx.types.u64,
169                     sym::type_name => self.tcx.mk_static_str(),
170                     _ => bug!(),
171                 };
172                 let val =
173                     self.tcx.const_eval_global_id(self.param_env, gid, Some(self.tcx.span))?;
174                 let val = self.const_val_to_op(val, ty, Some(dest.layout))?;
175                 self.copy_op(&val, dest, /*allow_transmute*/ false)?;
176             }
177
178             sym::ctpop
179             | sym::cttz
180             | sym::cttz_nonzero
181             | sym::ctlz
182             | sym::ctlz_nonzero
183             | sym::bswap
184             | sym::bitreverse => {
185                 let ty = substs.type_at(0);
186                 let layout_of = self.layout_of(ty)?;
187                 let val = self.read_scalar(&args[0])?.check_init()?;
188                 let bits = val.to_bits(layout_of.size)?;
189                 let kind = match layout_of.abi {
190                     Abi::Scalar(scalar) => scalar.primitive(),
191                     _ => span_bug!(
192                         self.cur_span(),
193                         "{} called on invalid type {:?}",
194                         intrinsic_name,
195                         ty
196                     ),
197                 };
198                 let (nonzero, intrinsic_name) = match intrinsic_name {
199                     sym::cttz_nonzero => (true, sym::cttz),
200                     sym::ctlz_nonzero => (true, sym::ctlz),
201                     other => (false, other),
202                 };
203                 if nonzero && bits == 0 {
204                     throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
205                 }
206                 let out_val = numeric_intrinsic(intrinsic_name, bits, kind);
207                 self.write_scalar(out_val, dest)?;
208             }
209             sym::add_with_overflow | sym::sub_with_overflow | sym::mul_with_overflow => {
210                 let lhs = self.read_immediate(&args[0])?;
211                 let rhs = self.read_immediate(&args[1])?;
212                 let bin_op = match intrinsic_name {
213                     sym::add_with_overflow => BinOp::Add,
214                     sym::sub_with_overflow => BinOp::Sub,
215                     sym::mul_with_overflow => BinOp::Mul,
216                     _ => bug!(),
217                 };
218                 self.binop_with_overflow(
219                     bin_op, /*force_overflow_checks*/ true, &lhs, &rhs, dest,
220                 )?;
221             }
222             sym::saturating_add | sym::saturating_sub => {
223                 let l = self.read_immediate(&args[0])?;
224                 let r = self.read_immediate(&args[1])?;
225                 let val = self.saturating_arith(
226                     if intrinsic_name == sym::saturating_add { BinOp::Add } else { BinOp::Sub },
227                     &l,
228                     &r,
229                 )?;
230                 self.write_scalar(val, dest)?;
231             }
232             sym::discriminant_value => {
233                 let place = self.deref_operand(&args[0])?;
234                 let discr_val = self.read_discriminant(&place.into())?.0;
235                 self.write_scalar(discr_val, dest)?;
236             }
237             sym::unchecked_shl
238             | sym::unchecked_shr
239             | sym::unchecked_add
240             | sym::unchecked_sub
241             | sym::unchecked_mul
242             | sym::unchecked_div
243             | sym::unchecked_rem => {
244                 let l = self.read_immediate(&args[0])?;
245                 let r = self.read_immediate(&args[1])?;
246                 let bin_op = match intrinsic_name {
247                     sym::unchecked_shl => BinOp::Shl,
248                     sym::unchecked_shr => BinOp::Shr,
249                     sym::unchecked_add => BinOp::Add,
250                     sym::unchecked_sub => BinOp::Sub,
251                     sym::unchecked_mul => BinOp::Mul,
252                     sym::unchecked_div => BinOp::Div,
253                     sym::unchecked_rem => BinOp::Rem,
254                     _ => bug!(),
255                 };
256                 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, &l, &r)?;
257                 if overflowed {
258                     let layout = self.layout_of(substs.type_at(0))?;
259                     let r_val = r.to_scalar()?.to_bits(layout.size)?;
260                     if let sym::unchecked_shl | sym::unchecked_shr = intrinsic_name {
261                         throw_ub_format!("overflowing shift by {} in `{}`", r_val, intrinsic_name);
262                     } else {
263                         throw_ub_format!("overflow executing `{}`", intrinsic_name);
264                     }
265                 }
266                 self.write_scalar(val, dest)?;
267             }
268             sym::rotate_left | sym::rotate_right => {
269                 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
270                 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
271                 let layout = self.layout_of(substs.type_at(0))?;
272                 let val = self.read_scalar(&args[0])?.check_init()?;
273                 let val_bits = val.to_bits(layout.size)?;
274                 let raw_shift = self.read_scalar(&args[1])?.check_init()?;
275                 let raw_shift_bits = raw_shift.to_bits(layout.size)?;
276                 let width_bits = u128::from(layout.size.bits());
277                 let shift_bits = raw_shift_bits % width_bits;
278                 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
279                 let result_bits = if intrinsic_name == sym::rotate_left {
280                     (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
281                 } else {
282                     (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
283                 };
284                 let truncated_bits = self.truncate(result_bits, layout);
285                 let result = Scalar::from_uint(truncated_bits, layout.size);
286                 self.write_scalar(result, dest)?;
287             }
288             sym::copy => {
289                 self.copy_intrinsic(&args[0], &args[1], &args[2], /*nonoverlapping*/ false)?;
290             }
291             sym::write_bytes => {
292                 self.write_bytes_intrinsic(&args[0], &args[1], &args[2])?;
293             }
294             sym::offset => {
295                 let ptr = self.read_pointer(&args[0])?;
296                 let offset_count = self.read_scalar(&args[1])?.to_machine_isize(self)?;
297                 let pointee_ty = substs.type_at(0);
298
299                 let offset_ptr = self.ptr_offset_inbounds(ptr, pointee_ty, offset_count)?;
300                 self.write_pointer(offset_ptr, dest)?;
301             }
302             sym::arith_offset => {
303                 let ptr = self.read_pointer(&args[0])?;
304                 let offset_count = self.read_scalar(&args[1])?.to_machine_isize(self)?;
305                 let pointee_ty = substs.type_at(0);
306
307                 let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
308                 let offset_bytes = offset_count.wrapping_mul(pointee_size);
309                 let offset_ptr = ptr.wrapping_signed_offset(offset_bytes, self);
310                 self.write_pointer(offset_ptr, dest)?;
311             }
312             sym::ptr_offset_from | sym::ptr_offset_from_unsigned => {
313                 let a = self.read_pointer(&args[0])?;
314                 let b = self.read_pointer(&args[1])?;
315
316                 let usize_layout = self.layout_of(self.tcx.types.usize)?;
317                 let isize_layout = self.layout_of(self.tcx.types.isize)?;
318
319                 // Get offsets for both that are at least relative to the same base.
320                 let (a_offset, b_offset) =
321                     match (self.ptr_try_get_alloc_id(a), self.ptr_try_get_alloc_id(b)) {
322                         (Err(a), Err(b)) => {
323                             // Neither poiner points to an allocation.
324                             // If these are inequal or null, this *will* fail the deref check below.
325                             (a, b)
326                         }
327                         (Err(_), _) | (_, Err(_)) => {
328                             // We managed to find a valid allocation for one pointer, but not the other.
329                             // That means they are definitely not pointing to the same allocation.
330                             throw_ub_format!(
331                                 "{} called on pointers into different allocations",
332                                 intrinsic_name
333                             );
334                         }
335                         (Ok((a_alloc_id, a_offset, _)), Ok((b_alloc_id, b_offset, _))) => {
336                             // Found allocation for both. They must be into the same allocation.
337                             if a_alloc_id != b_alloc_id {
338                                 throw_ub_format!(
339                                     "{} called on pointers into different allocations",
340                                     intrinsic_name
341                                 );
342                             }
343                             // Use these offsets for distance calculation.
344                             (a_offset.bytes(), b_offset.bytes())
345                         }
346                     };
347
348                 // Compute distance.
349                 let distance = {
350                     // The subtraction is always done in `isize` to enforce
351                     // the "no more than `isize::MAX` apart" requirement.
352                     let a_offset = ImmTy::from_uint(a_offset, isize_layout);
353                     let b_offset = ImmTy::from_uint(b_offset, isize_layout);
354                     let (val, overflowed, _ty) =
355                         self.overflowing_binary_op(BinOp::Sub, &a_offset, &b_offset)?;
356                     if overflowed {
357                         throw_ub_format!("pointers were too far apart for {}", intrinsic_name);
358                     }
359                     val.to_machine_isize(self)?
360                 };
361
362                 // Check that the range between them is dereferenceable ("in-bounds or one past the
363                 // end of the same allocation"). This is like the check in ptr_offset_inbounds.
364                 let min_ptr = if distance >= 0 { b } else { a };
365                 self.check_ptr_access_align(
366                     min_ptr,
367                     Size::from_bytes(distance.unsigned_abs()),
368                     Align::ONE,
369                     CheckInAllocMsg::OffsetFromTest,
370                 )?;
371
372                 if intrinsic_name == sym::ptr_offset_from_unsigned && distance < 0 {
373                     throw_ub_format!(
374                         "{} called when first pointer has smaller offset than second: {} < {}",
375                         intrinsic_name,
376                         a_offset,
377                         b_offset,
378                     );
379                 }
380
381                 // Perform division by size to compute return value.
382                 let ret_layout = if intrinsic_name == sym::ptr_offset_from_unsigned {
383                     usize_layout
384                 } else {
385                     isize_layout
386                 };
387                 let pointee_layout = self.layout_of(substs.type_at(0))?;
388                 // If ret_layout is unsigned, we checked that so is the distance, so we are good.
389                 let val = ImmTy::from_int(distance, ret_layout);
390                 let size = ImmTy::from_int(pointee_layout.size.bytes(), ret_layout);
391                 self.exact_div(&val, &size, dest)?;
392             }
393
394             sym::transmute => {
395                 self.copy_op(&args[0], dest, /*allow_transmute*/ true)?;
396             }
397             sym::assert_inhabited | sym::assert_zero_valid | sym::assert_uninit_valid => {
398                 let ty = instance.substs.type_at(0);
399                 let layout = self.layout_of(ty)?;
400
401                 // For *all* intrinsics we first check `is_uninhabited` to give a more specific
402                 // error message.
403                 if layout.abi.is_uninhabited() {
404                     // The run-time intrinsic panics just to get a good backtrace; here we abort
405                     // since there is no problem showing a backtrace even for aborts.
406                     M::abort(
407                         self,
408                         format!(
409                             "aborted execution: attempted to instantiate uninhabited type `{}`",
410                             ty
411                         ),
412                     )?;
413                 }
414
415                 if intrinsic_name == sym::assert_zero_valid {
416                     let should_panic = !self.tcx.permits_zero_init(layout);
417
418                     if should_panic {
419                         M::abort(
420                             self,
421                             format!(
422                                 "aborted execution: attempted to zero-initialize type `{}`, which is invalid",
423                                 ty
424                             ),
425                         )?;
426                     }
427                 }
428
429                 if intrinsic_name == sym::assert_uninit_valid {
430                     let should_panic = !self.tcx.permits_uninit_init(layout);
431
432                     if should_panic {
433                         M::abort(
434                             self,
435                             format!(
436                                 "aborted execution: attempted to leave type `{}` uninitialized, which is invalid",
437                                 ty
438                             ),
439                         )?;
440                     }
441                 }
442             }
443             sym::simd_insert => {
444                 let index = u64::from(self.read_scalar(&args[1])?.to_u32()?);
445                 let elem = &args[2];
446                 let (input, input_len) = self.operand_to_simd(&args[0])?;
447                 let (dest, dest_len) = self.place_to_simd(dest)?;
448                 assert_eq!(input_len, dest_len, "Return vector length must match input length");
449                 assert!(
450                     index < dest_len,
451                     "Index `{}` must be in bounds of vector with length {}`",
452                     index,
453                     dest_len
454                 );
455
456                 for i in 0..dest_len {
457                     let place = self.mplace_index(&dest, i)?;
458                     let value = if i == index {
459                         elem.clone()
460                     } else {
461                         self.mplace_index(&input, i)?.into()
462                     };
463                     self.copy_op(&value, &place.into(), /*allow_transmute*/ false)?;
464                 }
465             }
466             sym::simd_extract => {
467                 let index = u64::from(self.read_scalar(&args[1])?.to_u32()?);
468                 let (input, input_len) = self.operand_to_simd(&args[0])?;
469                 assert!(
470                     index < input_len,
471                     "index `{}` must be in bounds of vector with length `{}`",
472                     index,
473                     input_len
474                 );
475                 self.copy_op(
476                     &self.mplace_index(&input, index)?.into(),
477                     dest,
478                     /*allow_transmute*/ false,
479                 )?;
480             }
481             sym::likely | sym::unlikely | sym::black_box => {
482                 // These just return their argument
483                 self.copy_op(&args[0], dest, /*allow_transmute*/ false)?;
484             }
485             sym::assume => {
486                 let cond = self.read_scalar(&args[0])?.check_init()?.to_bool()?;
487                 if !cond {
488                     throw_ub_format!("`assume` intrinsic called with `false`");
489                 }
490             }
491             sym::raw_eq => {
492                 let result = self.raw_eq_intrinsic(&args[0], &args[1])?;
493                 self.write_scalar(result, dest)?;
494             }
495             _ => return Ok(false),
496         }
497
498         trace!("{:?}", self.dump_place(**dest));
499         self.go_to_block(ret);
500         Ok(true)
501     }
502
503     pub fn exact_div(
504         &mut self,
505         a: &ImmTy<'tcx, M::Provenance>,
506         b: &ImmTy<'tcx, M::Provenance>,
507         dest: &PlaceTy<'tcx, M::Provenance>,
508     ) -> InterpResult<'tcx> {
509         // Performs an exact division, resulting in undefined behavior where
510         // `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`.
511         // First, check x % y != 0 (or if that computation overflows).
512         let (res, overflow, _ty) = self.overflowing_binary_op(BinOp::Rem, &a, &b)?;
513         assert!(!overflow); // All overflow is UB, so this should never return on overflow.
514         if res.assert_bits(a.layout.size) != 0 {
515             throw_ub_format!("exact_div: {} cannot be divided by {} without remainder", a, b)
516         }
517         // `Rem` says this is all right, so we can let `Div` do its job.
518         self.binop_ignore_overflow(BinOp::Div, &a, &b, dest)
519     }
520
521     pub fn saturating_arith(
522         &self,
523         mir_op: BinOp,
524         l: &ImmTy<'tcx, M::Provenance>,
525         r: &ImmTy<'tcx, M::Provenance>,
526     ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
527         assert!(matches!(mir_op, BinOp::Add | BinOp::Sub));
528         let (val, overflowed, _ty) = self.overflowing_binary_op(mir_op, l, r)?;
529         Ok(if overflowed {
530             let size = l.layout.size;
531             let num_bits = size.bits();
532             if l.layout.abi.is_signed() {
533                 // For signed ints the saturated value depends on the sign of the first
534                 // term since the sign of the second term can be inferred from this and
535                 // the fact that the operation has overflowed (if either is 0 no
536                 // overflow can occur)
537                 let first_term: u128 = l.to_scalar()?.to_bits(l.layout.size)?;
538                 let first_term_positive = first_term & (1 << (num_bits - 1)) == 0;
539                 if first_term_positive {
540                     // Negative overflow not possible since the positive first term
541                     // can only increase an (in range) negative term for addition
542                     // or corresponding negated positive term for subtraction
543                     Scalar::from_int(size.signed_int_max(), size)
544                 } else {
545                     // Positive overflow not possible for similar reason
546                     // max negative
547                     Scalar::from_int(size.signed_int_min(), size)
548                 }
549             } else {
550                 // unsigned
551                 if matches!(mir_op, BinOp::Add) {
552                     // max unsigned
553                     Scalar::from_uint(size.unsigned_int_max(), size)
554                 } else {
555                     // underflow to 0
556                     Scalar::from_uint(0u128, size)
557                 }
558             }
559         } else {
560             val
561         })
562     }
563
564     /// Offsets a pointer by some multiple of its type, returning an error if the pointer leaves its
565     /// allocation. For integer pointers, we consider each of them their own tiny allocation of size
566     /// 0, so offset-by-0 (and only 0) is okay -- except that null cannot be offset by _any_ value.
567     pub fn ptr_offset_inbounds(
568         &self,
569         ptr: Pointer<Option<M::Provenance>>,
570         pointee_ty: Ty<'tcx>,
571         offset_count: i64,
572     ) -> InterpResult<'tcx, Pointer<Option<M::Provenance>>> {
573         // We cannot overflow i64 as a type's size must be <= isize::MAX.
574         let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
575         // The computed offset, in bytes, must not overflow an isize.
576         // `checked_mul` enforces a too small bound, but no actual allocation can be big enough for
577         // the difference to be noticeable.
578         let offset_bytes =
579             offset_count.checked_mul(pointee_size).ok_or(err_ub!(PointerArithOverflow))?;
580         // The offset being in bounds cannot rely on "wrapping around" the address space.
581         // So, first rule out overflows in the pointer arithmetic.
582         let offset_ptr = ptr.signed_offset(offset_bytes, self)?;
583         // ptr and offset_ptr must be in bounds of the same allocated object. This means all of the
584         // memory between these pointers must be accessible. Note that we do not require the
585         // pointers to be properly aligned (unlike a read/write operation).
586         let min_ptr = if offset_bytes >= 0 { ptr } else { offset_ptr };
587         // This call handles checking for integer/null pointers.
588         self.check_ptr_access_align(
589             min_ptr,
590             Size::from_bytes(offset_bytes.unsigned_abs()),
591             Align::ONE,
592             CheckInAllocMsg::PointerArithmeticTest,
593         )?;
594         Ok(offset_ptr)
595     }
596
597     /// Copy `count*size_of::<T>()` many bytes from `*src` to `*dst`.
598     pub(crate) fn copy_intrinsic(
599         &mut self,
600         src: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
601         dst: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
602         count: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
603         nonoverlapping: bool,
604     ) -> InterpResult<'tcx> {
605         let count = self.read_scalar(&count)?.to_machine_usize(self)?;
606         let layout = self.layout_of(src.layout.ty.builtin_deref(true).unwrap().ty)?;
607         let (size, align) = (layout.size, layout.align.abi);
608         // `checked_mul` enforces a too small bound (the correct one would probably be machine_isize_max),
609         // but no actual allocation can be big enough for the difference to be noticeable.
610         let size = size.checked_mul(count, self).ok_or_else(|| {
611             err_ub_format!(
612                 "overflow computing total size of `{}`",
613                 if nonoverlapping { "copy_nonoverlapping" } else { "copy" }
614             )
615         })?;
616
617         let src = self.read_pointer(&src)?;
618         let dst = self.read_pointer(&dst)?;
619
620         self.mem_copy(src, align, dst, align, size, nonoverlapping)
621     }
622
623     pub(crate) fn write_bytes_intrinsic(
624         &mut self,
625         dst: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
626         byte: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
627         count: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
628     ) -> InterpResult<'tcx> {
629         let layout = self.layout_of(dst.layout.ty.builtin_deref(true).unwrap().ty)?;
630
631         let dst = self.read_pointer(&dst)?;
632         let byte = self.read_scalar(&byte)?.to_u8()?;
633         let count = self.read_scalar(&count)?.to_machine_usize(self)?;
634
635         // `checked_mul` enforces a too small bound (the correct one would probably be machine_isize_max),
636         // but no actual allocation can be big enough for the difference to be noticeable.
637         let len = layout
638             .size
639             .checked_mul(count, self)
640             .ok_or_else(|| err_ub_format!("overflow computing total size of `write_bytes`"))?;
641
642         let bytes = std::iter::repeat(byte).take(len.bytes_usize());
643         self.write_bytes_ptr(dst, bytes)
644     }
645
646     pub(crate) fn raw_eq_intrinsic(
647         &mut self,
648         lhs: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
649         rhs: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
650     ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
651         let layout = self.layout_of(lhs.layout.ty.builtin_deref(true).unwrap().ty)?;
652         assert!(!layout.is_unsized());
653
654         let lhs = self.read_pointer(lhs)?;
655         let rhs = self.read_pointer(rhs)?;
656         let lhs_bytes = self.read_bytes_ptr(lhs, layout.size)?;
657         let rhs_bytes = self.read_bytes_ptr(rhs, layout.size)?;
658         Ok(Scalar::from_bool(lhs_bytes == rhs_bytes))
659     }
660 }