]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/interpret/intrinsics.rs
Rollup merge of #104672 - Voultapher:unify-sort-modules, r=thomcc
[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 rustc_hir::def_id::DefId;
6 use rustc_middle::mir::{
7     self,
8     interpret::{
9         Allocation, ConstAllocation, ConstValue, GlobalId, InterpResult, PointerArithmetic, Scalar,
10     },
11     BinOp, NonDivergingIntrinsic,
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
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),
31     };
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),
40     };
41     Scalar::from_uint(bits_out, size)
42 }
43
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)
49 }
50
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>(
54     tcx: TyCtxt<'tcx>,
55     param_env: ty::ParamEnv<'tcx>,
56     def_id: DefId,
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);
61     Ok(match name {
62         sym::type_name => {
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() }
66         }
67         sym::needs_drop => {
68             ensure_monomorphic_enough(tcx, tp_ty)?;
69             ConstValue::from_bool(tp_ty.needs_drop(tcx, param_env))
70         }
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)
75         }
76         sym::type_id => {
77             ensure_monomorphic_enough(tcx, tp_ty)?;
78             ConstValue::from_u64(tcx.type_id_hash(tp_ty))
79         }
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(adt, _) => ConstValue::from_machine_usize(adt.variants().len() as u64, &tcx),
83             ty::Alias(..) | ty::Param(_) | ty::Placeholder(_) | ty::Infer(_) => {
84                 throw_inval!(TooGeneric)
85             }
86             ty::Bound(_, _) => bug!("bound ty during ctfe"),
87             ty::Bool
88             | ty::Char
89             | ty::Int(_)
90             | ty::Uint(_)
91             | ty::Float(_)
92             | ty::Foreign(_)
93             | ty::Str
94             | ty::Array(_, _)
95             | ty::Slice(_)
96             | ty::RawPtr(_)
97             | ty::Ref(_, _, _)
98             | ty::FnDef(_, _)
99             | ty::FnPtr(_)
100             | ty::Dynamic(_, _, _)
101             | ty::Closure(_, _)
102             | ty::Generator(_, _, _)
103             | ty::GeneratorWitness(_)
104             | ty::Never
105             | ty::Tuple(_)
106             | ty::Error(_) => ConstValue::from_machine_usize(0u64, &tcx),
107         },
108         other => bug!("`{}` is not a zero arg intrinsic", other),
109     })
110 }
111
112 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
113     /// Returns `true` if emulation happened.
114     /// Here we implement the intrinsics that are common to all Miri instances; individual machines can add their own
115     /// intrinsic handling.
116     pub fn emulate_intrinsic(
117         &mut self,
118         instance: ty::Instance<'tcx>,
119         args: &[OpTy<'tcx, M::Provenance>],
120         dest: &PlaceTy<'tcx, M::Provenance>,
121         ret: Option<mir::BasicBlock>,
122     ) -> InterpResult<'tcx, bool> {
123         let substs = instance.substs;
124         let intrinsic_name = self.tcx.item_name(instance.def_id());
125
126         // First handle intrinsics without return place.
127         let ret = match ret {
128             None => match intrinsic_name {
129                 sym::transmute => throw_ub_format!("transmuting to uninhabited type"),
130                 sym::abort => M::abort(self, "the program aborted execution".to_owned())?,
131                 // Unsupported diverging intrinsic.
132                 _ => return Ok(false),
133             },
134             Some(p) => p,
135         };
136
137         match intrinsic_name {
138             sym::caller_location => {
139                 let span = self.find_closest_untracked_caller_location();
140                 let location = self.alloc_caller_location_for_span(span);
141                 self.write_immediate(location.to_ref(self), dest)?;
142             }
143
144             sym::min_align_of_val | sym::size_of_val => {
145                 // Avoid `deref_operand` -- this is not a deref, the ptr does not have to be
146                 // dereferenceable!
147                 let place = self.ref_to_mplace(&self.read_immediate(&args[0])?)?;
148                 let (size, align) = self
149                     .size_and_align_of_mplace(&place)?
150                     .ok_or_else(|| err_unsup_format!("`extern type` does not have known layout"))?;
151
152                 let result = match intrinsic_name {
153                     sym::min_align_of_val => align.bytes(),
154                     sym::size_of_val => size.bytes(),
155                     _ => bug!(),
156                 };
157
158                 self.write_scalar(Scalar::from_machine_usize(result, self), dest)?;
159             }
160
161             sym::pref_align_of
162             | sym::needs_drop
163             | sym::type_id
164             | sym::type_name
165             | sym::variant_count => {
166                 let gid = GlobalId { instance, promoted: None };
167                 let ty = match intrinsic_name {
168                     sym::pref_align_of | sym::variant_count => self.tcx.types.usize,
169                     sym::needs_drop => self.tcx.types.bool,
170                     sym::type_id => self.tcx.types.u64,
171                     sym::type_name => self.tcx.mk_static_str(),
172                     _ => bug!(),
173                 };
174                 let val = self.ctfe_query(None, |tcx| {
175                     tcx.const_eval_global_id(self.param_env, gid, Some(tcx.span))
176                 })?;
177                 let val = self.const_val_to_op(val, ty, Some(dest.layout))?;
178                 self.copy_op(&val, dest, /*allow_transmute*/ false)?;
179             }
180
181             sym::ctpop
182             | sym::cttz
183             | sym::cttz_nonzero
184             | sym::ctlz
185             | sym::ctlz_nonzero
186             | sym::bswap
187             | sym::bitreverse => {
188                 let ty = substs.type_at(0);
189                 let layout_of = self.layout_of(ty)?;
190                 let val = self.read_scalar(&args[0])?;
191                 let bits = val.to_bits(layout_of.size)?;
192                 let kind = match layout_of.abi {
193                     Abi::Scalar(scalar) => scalar.primitive(),
194                     _ => span_bug!(
195                         self.cur_span(),
196                         "{} called on invalid type {:?}",
197                         intrinsic_name,
198                         ty
199                     ),
200                 };
201                 let (nonzero, intrinsic_name) = match intrinsic_name {
202                     sym::cttz_nonzero => (true, sym::cttz),
203                     sym::ctlz_nonzero => (true, sym::ctlz),
204                     other => (false, other),
205                 };
206                 if nonzero && bits == 0 {
207                     throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
208                 }
209                 let out_val = numeric_intrinsic(intrinsic_name, bits, kind);
210                 self.write_scalar(out_val, dest)?;
211             }
212             sym::add_with_overflow | sym::sub_with_overflow | sym::mul_with_overflow => {
213                 let lhs = self.read_immediate(&args[0])?;
214                 let rhs = self.read_immediate(&args[1])?;
215                 let bin_op = match intrinsic_name {
216                     sym::add_with_overflow => BinOp::Add,
217                     sym::sub_with_overflow => BinOp::Sub,
218                     sym::mul_with_overflow => BinOp::Mul,
219                     _ => bug!(),
220                 };
221                 self.binop_with_overflow(
222                     bin_op, /*force_overflow_checks*/ true, &lhs, &rhs, dest,
223                 )?;
224             }
225             sym::saturating_add | sym::saturating_sub => {
226                 let l = self.read_immediate(&args[0])?;
227                 let r = self.read_immediate(&args[1])?;
228                 let val = self.saturating_arith(
229                     if intrinsic_name == sym::saturating_add { BinOp::Add } else { BinOp::Sub },
230                     &l,
231                     &r,
232                 )?;
233                 self.write_scalar(val, dest)?;
234             }
235             sym::discriminant_value => {
236                 let place = self.deref_operand(&args[0])?;
237                 let discr_val = self.read_discriminant(&place.into())?.0;
238                 self.write_scalar(discr_val, dest)?;
239             }
240             sym::exact_div => {
241                 let l = self.read_immediate(&args[0])?;
242                 let r = self.read_immediate(&args[1])?;
243                 self.exact_div(&l, &r, dest)?;
244             }
245             sym::unchecked_shl
246             | sym::unchecked_shr
247             | sym::unchecked_add
248             | sym::unchecked_sub
249             | sym::unchecked_mul
250             | sym::unchecked_div
251             | sym::unchecked_rem => {
252                 let l = self.read_immediate(&args[0])?;
253                 let r = self.read_immediate(&args[1])?;
254                 let bin_op = match intrinsic_name {
255                     sym::unchecked_shl => BinOp::Shl,
256                     sym::unchecked_shr => BinOp::Shr,
257                     sym::unchecked_add => BinOp::Add,
258                     sym::unchecked_sub => BinOp::Sub,
259                     sym::unchecked_mul => BinOp::Mul,
260                     sym::unchecked_div => BinOp::Div,
261                     sym::unchecked_rem => BinOp::Rem,
262                     _ => bug!(),
263                 };
264                 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, &l, &r)?;
265                 if overflowed {
266                     let layout = self.layout_of(substs.type_at(0))?;
267                     let r_val = r.to_scalar().to_bits(layout.size)?;
268                     if let sym::unchecked_shl | sym::unchecked_shr = intrinsic_name {
269                         throw_ub_format!("overflowing shift by {} in `{}`", r_val, intrinsic_name);
270                     } else {
271                         throw_ub_format!("overflow executing `{}`", intrinsic_name);
272                     }
273                 }
274                 self.write_scalar(val, dest)?;
275             }
276             sym::rotate_left | sym::rotate_right => {
277                 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
278                 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
279                 let layout = self.layout_of(substs.type_at(0))?;
280                 let val = self.read_scalar(&args[0])?;
281                 let val_bits = val.to_bits(layout.size)?;
282                 let raw_shift = self.read_scalar(&args[1])?;
283                 let raw_shift_bits = raw_shift.to_bits(layout.size)?;
284                 let width_bits = u128::from(layout.size.bits());
285                 let shift_bits = raw_shift_bits % width_bits;
286                 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
287                 let result_bits = if intrinsic_name == sym::rotate_left {
288                     (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
289                 } else {
290                     (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
291                 };
292                 let truncated_bits = self.truncate(result_bits, layout);
293                 let result = Scalar::from_uint(truncated_bits, layout.size);
294                 self.write_scalar(result, dest)?;
295             }
296             sym::copy => {
297                 self.copy_intrinsic(&args[0], &args[1], &args[2], /*nonoverlapping*/ false)?;
298             }
299             sym::write_bytes => {
300                 self.write_bytes_intrinsic(&args[0], &args[1], &args[2])?;
301             }
302             sym::offset => {
303                 let ptr = self.read_pointer(&args[0])?;
304                 let offset_count = self.read_machine_isize(&args[1])?;
305                 let pointee_ty = substs.type_at(0);
306
307                 let offset_ptr = self.ptr_offset_inbounds(ptr, pointee_ty, offset_count)?;
308                 self.write_pointer(offset_ptr, dest)?;
309             }
310             sym::arith_offset => {
311                 let ptr = self.read_pointer(&args[0])?;
312                 let offset_count = self.read_machine_isize(&args[1])?;
313                 let pointee_ty = substs.type_at(0);
314
315                 let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
316                 let offset_bytes = offset_count.wrapping_mul(pointee_size);
317                 let offset_ptr = ptr.wrapping_signed_offset(offset_bytes, self);
318                 self.write_pointer(offset_ptr, dest)?;
319             }
320             sym::ptr_offset_from | sym::ptr_offset_from_unsigned => {
321                 let a = self.read_pointer(&args[0])?;
322                 let b = self.read_pointer(&args[1])?;
323
324                 let usize_layout = self.layout_of(self.tcx.types.usize)?;
325                 let isize_layout = self.layout_of(self.tcx.types.isize)?;
326
327                 // Get offsets for both that are at least relative to the same base.
328                 let (a_offset, b_offset) =
329                     match (self.ptr_try_get_alloc_id(a), self.ptr_try_get_alloc_id(b)) {
330                         (Err(a), Err(b)) => {
331                             // Neither pointer points to an allocation.
332                             // If these are inequal or null, this *will* fail the deref check below.
333                             (a, b)
334                         }
335                         (Err(_), _) | (_, Err(_)) => {
336                             // We managed to find a valid allocation for one pointer, but not the other.
337                             // That means they are definitely not pointing to the same allocation.
338                             throw_ub_format!(
339                                 "`{}` called on pointers into different allocations",
340                                 intrinsic_name
341                             );
342                         }
343                         (Ok((a_alloc_id, a_offset, _)), Ok((b_alloc_id, b_offset, _))) => {
344                             // Found allocation for both. They must be into the same allocation.
345                             if a_alloc_id != b_alloc_id {
346                                 throw_ub_format!(
347                                     "`{}` called on pointers into different allocations",
348                                     intrinsic_name
349                                 );
350                             }
351                             // Use these offsets for distance calculation.
352                             (a_offset.bytes(), b_offset.bytes())
353                         }
354                     };
355
356                 // Compute distance.
357                 let dist = {
358                     // Addresses are unsigned, so this is a `usize` computation. We have to do the
359                     // overflow check separately anyway.
360                     let (val, overflowed, _ty) = {
361                         let a_offset = ImmTy::from_uint(a_offset, usize_layout);
362                         let b_offset = ImmTy::from_uint(b_offset, usize_layout);
363                         self.overflowing_binary_op(BinOp::Sub, &a_offset, &b_offset)?
364                     };
365                     if overflowed {
366                         // a < b
367                         if intrinsic_name == sym::ptr_offset_from_unsigned {
368                             throw_ub_format!(
369                                 "`{}` called when first pointer has smaller offset than second: {} < {}",
370                                 intrinsic_name,
371                                 a_offset,
372                                 b_offset,
373                             );
374                         }
375                         // The signed form of the intrinsic allows this. If we interpret the
376                         // difference as isize, we'll get the proper signed difference. If that
377                         // seems *positive*, they were more than isize::MAX apart.
378                         let dist = val.to_machine_isize(self)?;
379                         if dist >= 0 {
380                             throw_ub_format!(
381                                 "`{}` called when first pointer is too far before second",
382                                 intrinsic_name
383                             );
384                         }
385                         dist
386                     } else {
387                         // b >= a
388                         let dist = val.to_machine_isize(self)?;
389                         // If converting to isize produced a *negative* result, we had an overflow
390                         // because they were more than isize::MAX apart.
391                         if dist < 0 {
392                             throw_ub_format!(
393                                 "`{}` called when first pointer is too far ahead of second",
394                                 intrinsic_name
395                             );
396                         }
397                         dist
398                     }
399                 };
400
401                 // Check that the range between them is dereferenceable ("in-bounds or one past the
402                 // end of the same allocation"). This is like the check in ptr_offset_inbounds.
403                 let min_ptr = if dist >= 0 { b } else { a };
404                 self.check_ptr_access_align(
405                     min_ptr,
406                     Size::from_bytes(dist.unsigned_abs()),
407                     Align::ONE,
408                     CheckInAllocMsg::OffsetFromTest,
409                 )?;
410
411                 // Perform division by size to compute return value.
412                 let ret_layout = if intrinsic_name == sym::ptr_offset_from_unsigned {
413                     assert!(0 <= dist && dist <= self.machine_isize_max());
414                     usize_layout
415                 } else {
416                     assert!(self.machine_isize_min() <= dist && dist <= self.machine_isize_max());
417                     isize_layout
418                 };
419                 let pointee_layout = self.layout_of(substs.type_at(0))?;
420                 // If ret_layout is unsigned, we checked that so is the distance, so we are good.
421                 let val = ImmTy::from_int(dist, ret_layout);
422                 let size = ImmTy::from_int(pointee_layout.size.bytes(), ret_layout);
423                 self.exact_div(&val, &size, dest)?;
424             }
425
426             sym::transmute => {
427                 self.copy_op(&args[0], dest, /*allow_transmute*/ true)?;
428             }
429             sym::assert_inhabited
430             | sym::assert_zero_valid
431             | sym::assert_mem_uninitialized_valid => {
432                 let ty = instance.substs.type_at(0);
433                 let layout = self.layout_of(ty)?;
434
435                 // For *all* intrinsics we first check `is_uninhabited` to give a more specific
436                 // error message.
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.
440                     M::abort(
441                         self,
442                         format!(
443                             "aborted execution: attempted to instantiate uninhabited type `{}`",
444                             ty
445                         ),
446                     )?;
447                 }
448
449                 if intrinsic_name == sym::assert_zero_valid {
450                     let should_panic = !self.tcx.permits_zero_init(layout);
451
452                     if should_panic {
453                         M::abort(
454                             self,
455                             format!(
456                                 "aborted execution: attempted to zero-initialize type `{}`, which is invalid",
457                                 ty
458                             ),
459                         )?;
460                     }
461                 }
462
463                 if intrinsic_name == sym::assert_mem_uninitialized_valid {
464                     let should_panic = !self.tcx.permits_uninit_init(layout);
465
466                     if should_panic {
467                         M::abort(
468                             self,
469                             format!(
470                                 "aborted execution: attempted to leave type `{}` uninitialized, which is invalid",
471                                 ty
472                             ),
473                         )?;
474                     }
475                 }
476             }
477             sym::simd_insert => {
478                 let index = u64::from(self.read_scalar(&args[1])?.to_u32()?);
479                 let elem = &args[2];
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");
483                 assert!(
484                     index < dest_len,
485                     "Index `{}` must be in bounds of vector with length {}`",
486                     index,
487                     dest_len
488                 );
489
490                 for i in 0..dest_len {
491                     let place = self.mplace_index(&dest, i)?;
492                     let value = if i == index {
493                         elem.clone()
494                     } else {
495                         self.mplace_index(&input, i)?.into()
496                     };
497                     self.copy_op(&value, &place.into(), /*allow_transmute*/ false)?;
498                 }
499             }
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])?;
503                 assert!(
504                     index < input_len,
505                     "index `{}` must be in bounds of vector with length `{}`",
506                     index,
507                     input_len
508                 );
509                 self.copy_op(
510                     &self.mplace_index(&input, index)?.into(),
511                     dest,
512                     /*allow_transmute*/ false,
513                 )?;
514             }
515             sym::likely | sym::unlikely | sym::black_box => {
516                 // These just return their argument
517                 self.copy_op(&args[0], dest, /*allow_transmute*/ false)?;
518             }
519             sym::raw_eq => {
520                 let result = self.raw_eq_intrinsic(&args[0], &args[1])?;
521                 self.write_scalar(result, dest)?;
522             }
523
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)?;
528             }
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)?;
533             }
534
535             _ => return Ok(false),
536         }
537
538         trace!("{:?}", self.dump_place(**dest));
539         self.go_to_block(ret);
540         Ok(true)
541     }
542
543     pub(super) fn emulate_nondiverging_intrinsic(
544         &mut self,
545         intrinsic: &NonDivergingIntrinsic<'tcx>,
546     ) -> InterpResult<'tcx> {
547         match intrinsic {
548             NonDivergingIntrinsic::Assume(op) => {
549                 let op = self.eval_operand(op, None)?;
550                 let cond = self.read_scalar(&op)?.to_bool()?;
551                 if !cond {
552                     throw_ub_format!("`assume` called with `false`");
553                 }
554                 Ok(())
555             }
556             NonDivergingIntrinsic::CopyNonOverlapping(mir::CopyNonOverlapping {
557                 count,
558                 src,
559                 dst,
560             }) => {
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)
565             }
566         }
567     }
568
569     pub fn exact_div(
570         &mut self,
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)
582         }
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)
585     }
586
587     pub fn saturating_arith(
588         &self,
589         mir_op: BinOp,
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)?;
595         Ok(if overflowed {
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)
610                 } else {
611                     // Positive overflow not possible for similar reason
612                     // max negative
613                     Scalar::from_int(size.signed_int_min(), size)
614                 }
615             } else {
616                 // unsigned
617                 if matches!(mir_op, BinOp::Add) {
618                     // max unsigned
619                     Scalar::from_uint(size.unsigned_int_max(), size)
620                 } else {
621                     // underflow to 0
622                     Scalar::from_uint(0u128, size)
623                 }
624             }
625         } else {
626             val
627         })
628     }
629
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(
634         &self,
635         ptr: Pointer<Option<M::Provenance>>,
636         pointee_ty: Ty<'tcx>,
637         offset_count: i64,
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.
644         let offset_bytes =
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(
655             min_ptr,
656             Size::from_bytes(offset_bytes.unsigned_abs()),
657             Align::ONE,
658             CheckInAllocMsg::PointerArithmeticTest,
659         )?;
660         Ok(offset_ptr)
661     }
662
663     /// Copy `count*size_of::<T>()` many bytes from `*src` to `*dst`.
664     pub(crate) fn copy_intrinsic(
665         &mut self,
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_machine_usize(&count)?;
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(|| {
677             err_ub_format!(
678                 "overflow computing total size of `{}`",
679                 if nonoverlapping { "copy_nonoverlapping" } else { "copy" }
680             )
681         })?;
682
683         let src = self.read_pointer(&src)?;
684         let dst = self.read_pointer(&dst)?;
685
686         self.mem_copy(src, align, dst, align, size, nonoverlapping)
687     }
688
689     pub(crate) fn write_bytes_intrinsic(
690         &mut self,
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)?;
696
697         let dst = self.read_pointer(&dst)?;
698         let byte = self.read_scalar(&byte)?.to_u8()?;
699         let count = self.read_machine_usize(&count)?;
700
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.
703         let len = layout
704             .size
705             .checked_mul(count, self)
706             .ok_or_else(|| err_ub_format!("overflow computing total size of `write_bytes`"))?;
707
708         let bytes = std::iter::repeat(byte).take(len.bytes_usize());
709         self.write_bytes_ptr(dst, bytes)
710     }
711
712     pub(crate) fn raw_eq_intrinsic(
713         &mut self,
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());
719
720         let get_bytes = |this: &InterpCx<'mir, 'tcx, M>,
721                          op: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::Provenance>,
722                          size|
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 {
726                 // zero-sized access
727                 return Ok(&[]);
728             };
729             if alloc_ref.has_provenance() {
730                 throw_ub_format!("`raw_eq` on bytes with provenance");
731             }
732             alloc_ref.get_bytes_strip_provenance()
733         };
734
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))
738     }
739 }