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 std::convert::TryFrom;
7 use rustc_hir::def_id::DefId;
8 use rustc_middle::mir::{
10 interpret::{ConstValue, GlobalId, InterpResult, Scalar},
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,
28 fn numeric_intrinsic<Tag>(name: Symbol, bits: u128, kind: Primitive) -> Scalar<Tag> {
29 let size = match kind {
30 Primitive::Int(integer, _) => integer.size(),
31 _ => bug!("invalid `{}` argument: {:?}", name, bits),
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),
42 Scalar::from_uint(bits_out, size)
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 crate fn eval_nullary_intrinsic<'tcx>(
49 param_env: ty::ParamEnv<'tcx>,
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);
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() }
62 ensure_monomorphic_enough(tcx, tp_ty)?;
63 ConstValue::from_bool(tp_ty.needs_drop(tcx, param_env))
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)
71 ensure_monomorphic_enough(tcx, tp_ty)?;
72 ConstValue::from_u64(tcx.type_id_hash(tp_ty))
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, _) => ConstValue::from_machine_usize(adt.variants.len() as u64, &tcx),
82 | ty::Infer(_) => throw_inval!(TooGeneric),
98 | ty::Generator(_, _, _)
99 | ty::GeneratorWitness(_)
102 | ty::Error(_) => ConstValue::from_machine_usize(0u64, &tcx),
104 other => bug!("`{}` is not a zero arg intrinsic", other),
108 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
109 /// Returns `true` if emulation happened.
110 /// Here we implement the intrinsics that are common to all Miri instances; individual machines can add their own
111 /// intrinsic handling.
112 pub fn emulate_intrinsic(
114 instance: ty::Instance<'tcx>,
115 args: &[OpTy<'tcx, M::PointerTag>],
116 ret: Option<(&PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
117 ) -> InterpResult<'tcx, bool> {
118 let substs = instance.substs;
119 let intrinsic_name = self.tcx.item_name(instance.def_id());
121 // First handle intrinsics without return place.
122 let (dest, ret) = match ret {
123 None => match intrinsic_name {
124 sym::transmute => throw_ub_format!("transmuting to uninhabited type"),
125 sym::abort => M::abort(self, "the program aborted execution".to_owned())?,
126 // Unsupported diverging intrinsic.
127 _ => return Ok(false),
132 // Keep the patterns in this match ordered the same as the list in
133 // `src/librustc_middle/ty/constness.rs`
134 match intrinsic_name {
135 sym::caller_location => {
136 let span = self.find_closest_untracked_caller_location();
137 let location = self.alloc_caller_location_for_span(span);
138 self.write_immediate(location.to_ref(self), dest)?;
141 sym::min_align_of_val | sym::size_of_val => {
142 // Avoid `deref_operand` -- this is not a deref, the ptr does not have to be
144 let place = self.ref_to_mplace(&self.read_immediate(&args[0])?)?;
145 let (size, align) = self
146 .size_and_align_of_mplace(&place)?
147 .ok_or_else(|| err_unsup_format!("`extern type` does not have known layout"))?;
149 let result = match intrinsic_name {
150 sym::min_align_of_val => align.bytes(),
151 sym::size_of_val => size.bytes(),
155 self.write_scalar(Scalar::from_machine_usize(result, self), dest)?;
162 | sym::variant_count => {
163 let gid = GlobalId { instance, promoted: None };
164 let ty = match intrinsic_name {
165 sym::pref_align_of | sym::variant_count => self.tcx.types.usize,
166 sym::needs_drop => self.tcx.types.bool,
167 sym::type_id => self.tcx.types.u64,
168 sym::type_name => self.tcx.mk_static_str(),
169 _ => bug!("already checked for nullary intrinsics"),
172 self.tcx.const_eval_global_id(self.param_env, gid, Some(self.tcx.span))?;
173 let val = self.const_val_to_op(val, ty, Some(dest.layout))?;
174 self.copy_op(&val, dest)?;
183 | sym::bitreverse => {
184 let ty = substs.type_at(0);
185 let layout_of = self.layout_of(ty)?;
186 let val = self.read_scalar(&args[0])?.check_init()?;
187 let bits = val.to_bits(layout_of.size)?;
188 let kind = match layout_of.abi {
189 Abi::Scalar(scalar) => scalar.value,
192 "{} called on invalid type {:?}",
197 let (nonzero, intrinsic_name) = match intrinsic_name {
198 sym::cttz_nonzero => (true, sym::cttz),
199 sym::ctlz_nonzero => (true, sym::ctlz),
200 other => (false, other),
202 if nonzero && bits == 0 {
203 throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
205 let out_val = numeric_intrinsic(intrinsic_name, bits, kind);
206 self.write_scalar(out_val, dest)?;
208 sym::add_with_overflow | sym::sub_with_overflow | sym::mul_with_overflow => {
209 let lhs = self.read_immediate(&args[0])?;
210 let rhs = self.read_immediate(&args[1])?;
211 let bin_op = match intrinsic_name {
212 sym::add_with_overflow => BinOp::Add,
213 sym::sub_with_overflow => BinOp::Sub,
214 sym::mul_with_overflow => BinOp::Mul,
215 _ => bug!("Already checked for int ops"),
217 self.binop_with_overflow(bin_op, &lhs, &rhs, dest)?;
219 sym::saturating_add | sym::saturating_sub => {
220 let l = self.read_immediate(&args[0])?;
221 let r = self.read_immediate(&args[1])?;
222 let val = self.saturating_arith(
223 if intrinsic_name == sym::saturating_add { BinOp::Add } else { BinOp::Sub },
227 self.write_scalar(val, dest)?;
229 sym::discriminant_value => {
230 let place = self.deref_operand(&args[0])?;
231 let discr_val = self.read_discriminant(&place.into())?.0;
232 self.write_scalar(discr_val, dest)?;
240 | sym::unchecked_rem => {
241 let l = self.read_immediate(&args[0])?;
242 let r = self.read_immediate(&args[1])?;
243 let bin_op = match intrinsic_name {
244 sym::unchecked_shl => BinOp::Shl,
245 sym::unchecked_shr => BinOp::Shr,
246 sym::unchecked_add => BinOp::Add,
247 sym::unchecked_sub => BinOp::Sub,
248 sym::unchecked_mul => BinOp::Mul,
249 sym::unchecked_div => BinOp::Div,
250 sym::unchecked_rem => BinOp::Rem,
251 _ => bug!("Already checked for int ops"),
253 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, &l, &r)?;
255 let layout = self.layout_of(substs.type_at(0))?;
256 let r_val = r.to_scalar()?.to_bits(layout.size)?;
257 if let sym::unchecked_shl | sym::unchecked_shr = intrinsic_name {
258 throw_ub_format!("overflowing shift by {} in `{}`", r_val, intrinsic_name);
260 throw_ub_format!("overflow executing `{}`", intrinsic_name);
263 self.write_scalar(val, dest)?;
265 sym::rotate_left | sym::rotate_right => {
266 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
267 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
268 let layout = self.layout_of(substs.type_at(0))?;
269 let val = self.read_scalar(&args[0])?.check_init()?;
270 let val_bits = val.to_bits(layout.size)?;
271 let raw_shift = self.read_scalar(&args[1])?.check_init()?;
272 let raw_shift_bits = raw_shift.to_bits(layout.size)?;
273 let width_bits = u128::from(layout.size.bits());
274 let shift_bits = raw_shift_bits % width_bits;
275 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
276 let result_bits = if intrinsic_name == sym::rotate_left {
277 (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
279 (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
281 let truncated_bits = self.truncate(result_bits, layout);
282 let result = Scalar::from_uint(truncated_bits, layout.size);
283 self.write_scalar(result, dest)?;
286 self.copy_intrinsic(&args[0], &args[1], &args[2], /*nonoverlapping*/ false)?;
288 sym::write_bytes => {
289 self.write_bytes_intrinsic(&args[0], &args[1], &args[2])?;
292 let ptr = self.read_pointer(&args[0])?;
293 let offset_count = self.read_scalar(&args[1])?.to_machine_isize(self)?;
294 let pointee_ty = substs.type_at(0);
296 let offset_ptr = self.ptr_offset_inbounds(ptr, pointee_ty, offset_count)?;
297 self.write_pointer(offset_ptr, dest)?;
299 sym::arith_offset => {
300 let ptr = self.read_pointer(&args[0])?;
301 let offset_count = self.read_scalar(&args[1])?.to_machine_isize(self)?;
302 let pointee_ty = substs.type_at(0);
304 let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
305 let offset_bytes = offset_count.wrapping_mul(pointee_size);
306 let offset_ptr = ptr.wrapping_signed_offset(offset_bytes, self);
307 self.write_pointer(offset_ptr, dest)?;
309 sym::ptr_offset_from => {
310 let a = self.read_immediate(&args[0])?.to_scalar()?;
311 let b = self.read_immediate(&args[1])?.to_scalar()?;
313 // Special case: if both scalars are *equal integers*
314 // and not null, we pretend there is an allocation of size 0 right there,
315 // and their offset is 0. (There's never a valid object at null, making it an
316 // exception from the exception.)
317 // This is the dual to the special exception for offset-by-0
318 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
320 // Control flow is weird because we cannot early-return (to reach the
321 // `go_to_block` at the end).
322 let done = if let (Ok(a), Ok(b)) = (a.try_to_int(), b.try_to_int()) {
323 let a = a.try_to_machine_usize(*self.tcx).unwrap();
324 let b = b.try_to_machine_usize(*self.tcx).unwrap();
325 if a == b && a != 0 {
326 self.write_scalar(Scalar::from_machine_isize(0, self), dest)?;
336 // General case: we need two pointers.
337 let a = self.scalar_to_ptr(a);
338 let b = self.scalar_to_ptr(b);
339 let (a_alloc_id, a_offset, _) = self.memory.ptr_get_alloc(a)?;
340 let (b_alloc_id, b_offset, _) = self.memory.ptr_get_alloc(b)?;
341 if a_alloc_id != b_alloc_id {
343 "ptr_offset_from cannot compute offset of pointers into different \
347 let usize_layout = self.layout_of(self.tcx.types.usize)?;
348 let isize_layout = self.layout_of(self.tcx.types.isize)?;
349 let a_offset = ImmTy::from_uint(a_offset.bytes(), usize_layout);
350 let b_offset = ImmTy::from_uint(b_offset.bytes(), usize_layout);
351 let (val, _overflowed, _ty) =
352 self.overflowing_binary_op(BinOp::Sub, &a_offset, &b_offset)?;
353 let pointee_layout = self.layout_of(substs.type_at(0))?;
354 let val = ImmTy::from_scalar(val, isize_layout);
355 let size = ImmTy::from_int(pointee_layout.size.bytes(), isize_layout);
356 self.exact_div(&val, &size, dest)?;
361 self.copy_op_transmute(&args[0], dest)?;
363 sym::assert_inhabited | sym::assert_zero_valid | sym::assert_uninit_valid => {
364 let ty = instance.substs.type_at(0);
365 let layout = self.layout_of(ty)?;
367 // For *all* intrinsics we first check `is_uninhabited` to give a more specific
369 if layout.abi.is_uninhabited() {
370 // The run-time intrinsic panics just to get a good backtrace; here we abort
371 // since there is no problem showing a backtrace even for aborts.
375 "aborted execution: attempted to instantiate uninhabited type `{}`",
380 if intrinsic_name == sym::assert_zero_valid
381 && !layout.might_permit_raw_init(self, /*zero:*/ true)
386 "aborted execution: attempted to zero-initialize type `{}`, which is invalid",
391 if intrinsic_name == sym::assert_uninit_valid
392 && !layout.might_permit_raw_init(self, /*zero:*/ false)
397 "aborted execution: attempted to leave type `{}` uninitialized, which is invalid",
403 sym::simd_insert => {
404 let index = u64::from(self.read_scalar(&args[1])?.to_u32()?);
406 let (input, input_len) = self.operand_to_simd(&args[0])?;
407 let (dest, dest_len) = self.place_to_simd(dest)?;
408 assert_eq!(input_len, dest_len, "Return vector length must match input length");
411 "Index `{}` must be in bounds of vector with length {}`",
416 for i in 0..dest_len {
417 let place = self.mplace_index(&dest, i)?;
419 if i == index { *elem } else { self.mplace_index(&input, i)?.into() };
420 self.copy_op(&value, &place.into())?;
423 sym::simd_extract => {
424 let index = u64::from(self.read_scalar(&args[1])?.to_u32()?);
425 let (input, input_len) = self.operand_to_simd(&args[0])?;
428 "index `{}` must be in bounds of vector with length `{}`",
432 self.copy_op(&self.mplace_index(&input, index)?.into(), dest)?;
434 sym::likely | sym::unlikely | sym::black_box => {
435 // These just return their argument
436 self.copy_op(&args[0], dest)?;
439 let cond = self.read_scalar(&args[0])?.check_init()?.to_bool()?;
441 throw_ub_format!("`assume` intrinsic called with `false`");
445 let result = self.raw_eq_intrinsic(&args[0], &args[1])?;
446 self.write_scalar(result, dest)?;
448 _ => return Ok(false),
451 trace!("{:?}", self.dump_place(**dest));
452 self.go_to_block(ret);
458 a: &ImmTy<'tcx, M::PointerTag>,
459 b: &ImmTy<'tcx, M::PointerTag>,
460 dest: &PlaceTy<'tcx, M::PointerTag>,
461 ) -> InterpResult<'tcx> {
462 // Performs an exact division, resulting in undefined behavior where
463 // `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`.
464 // First, check x % y != 0 (or if that computation overflows).
465 let (res, overflow, _ty) = self.overflowing_binary_op(BinOp::Rem, &a, &b)?;
466 assert!(!overflow); // All overflow is UB, so this should never return on overflow.
467 if res.assert_bits(a.layout.size) != 0 {
468 throw_ub_format!("exact_div: {} cannot be divided by {} without remainder", a, b)
470 // `Rem` says this is all right, so we can let `Div` do its job.
471 self.binop_ignore_overflow(BinOp::Div, &a, &b, dest)
474 pub fn saturating_arith(
477 l: &ImmTy<'tcx, M::PointerTag>,
478 r: &ImmTy<'tcx, M::PointerTag>,
479 ) -> InterpResult<'tcx, Scalar<M::PointerTag>> {
480 assert!(matches!(mir_op, BinOp::Add | BinOp::Sub));
481 let (val, overflowed, _ty) = self.overflowing_binary_op(mir_op, l, r)?;
483 let size = l.layout.size;
484 let num_bits = size.bits();
485 if l.layout.abi.is_signed() {
486 // For signed ints the saturated value depends on the sign of the first
487 // term since the sign of the second term can be inferred from this and
488 // the fact that the operation has overflowed (if either is 0 no
489 // overflow can occur)
490 let first_term: u128 = l.to_scalar()?.to_bits(l.layout.size)?;
491 let first_term_positive = first_term & (1 << (num_bits - 1)) == 0;
492 if first_term_positive {
493 // Negative overflow not possible since the positive first term
494 // can only increase an (in range) negative term for addition
495 // or corresponding negated positive term for subtraction
496 Scalar::from_int(size.signed_int_max(), size)
498 // Positive overflow not possible for similar reason
500 Scalar::from_int(size.signed_int_min(), size)
504 if matches!(mir_op, BinOp::Add) {
506 Scalar::from_uint(size.unsigned_int_max(), size)
509 Scalar::from_uint(0u128, size)
517 /// Offsets a pointer by some multiple of its type, returning an error if the pointer leaves its
518 /// allocation. For integer pointers, we consider each of them their own tiny allocation of size
519 /// 0, so offset-by-0 (and only 0) is okay -- except that null cannot be offset by _any_ value.
520 pub fn ptr_offset_inbounds(
522 ptr: Pointer<Option<M::PointerTag>>,
523 pointee_ty: Ty<'tcx>,
525 ) -> InterpResult<'tcx, Pointer<Option<M::PointerTag>>> {
526 // We cannot overflow i64 as a type's size must be <= isize::MAX.
527 let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
528 // The computed offset, in bytes, cannot overflow an isize.
530 offset_count.checked_mul(pointee_size).ok_or(err_ub!(PointerArithOverflow))?;
531 // The offset being in bounds cannot rely on "wrapping around" the address space.
532 // So, first rule out overflows in the pointer arithmetic.
533 let offset_ptr = ptr.signed_offset(offset_bytes, self)?;
534 // ptr and offset_ptr must be in bounds of the same allocated object. This means all of the
535 // memory between these pointers must be accessible. Note that we do not require the
536 // pointers to be properly aligned (unlike a read/write operation).
537 let min_ptr = if offset_bytes >= 0 { ptr } else { offset_ptr };
538 let size = offset_bytes.unsigned_abs();
539 // This call handles checking for integer/null pointers.
540 self.memory.check_ptr_access_align(
542 Size::from_bytes(size),
544 CheckInAllocMsg::PointerArithmeticTest,
549 /// Copy `count*size_of::<T>()` many bytes from `*src` to `*dst`.
550 pub(crate) fn copy_intrinsic(
552 src: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::PointerTag>,
553 dst: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::PointerTag>,
554 count: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::PointerTag>,
555 nonoverlapping: bool,
556 ) -> InterpResult<'tcx> {
557 let count = self.read_scalar(&count)?.to_machine_usize(self)?;
558 let layout = self.layout_of(src.layout.ty.builtin_deref(true).unwrap().ty)?;
559 let (size, align) = (layout.size, layout.align.abi);
560 let size = size.checked_mul(count, self).ok_or_else(|| {
562 "overflow computing total size of `{}`",
563 if nonoverlapping { "copy_nonoverlapping" } else { "copy" }
567 let src = self.read_pointer(&src)?;
568 let dst = self.read_pointer(&dst)?;
570 self.memory.copy(src, align, dst, align, size, nonoverlapping)
573 pub(crate) fn write_bytes_intrinsic(
575 dst: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::PointerTag>,
576 byte: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::PointerTag>,
577 count: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::PointerTag>,
578 ) -> InterpResult<'tcx> {
579 let layout = self.layout_of(dst.layout.ty.builtin_deref(true).unwrap().ty)?;
581 let dst = self.read_pointer(&dst)?;
582 let byte = self.read_scalar(&byte)?.to_u8()?;
583 let count = self.read_scalar(&count)?.to_machine_usize(self)?;
587 .checked_mul(count, self)
588 .ok_or_else(|| err_ub_format!("overflow computing total size of `write_bytes`"))?;
590 let bytes = std::iter::repeat(byte).take(len.bytes_usize());
591 self.memory.write_bytes(dst, bytes)
594 pub(crate) fn raw_eq_intrinsic(
596 lhs: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::PointerTag>,
597 rhs: &OpTy<'tcx, <M as Machine<'mir, 'tcx>>::PointerTag>,
598 ) -> InterpResult<'tcx, Scalar<M::PointerTag>> {
599 let layout = self.layout_of(lhs.layout.ty.builtin_deref(true).unwrap().ty)?;
600 assert!(!layout.is_unsized());
602 let lhs = self.read_pointer(lhs)?;
603 let rhs = self.read_pointer(rhs)?;
604 let lhs_bytes = self.memory.read_bytes(lhs, layout.size)?;
605 let rhs_bytes = self.memory.read_bytes(rhs, layout.size)?;
606 Ok(Scalar::from_bool(lhs_bytes == rhs_bytes))