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::{uabs, ConstValue, GlobalId, InterpResult, Scalar},
14 use rustc_middle::ty::subst::SubstsRef;
15 use rustc_middle::ty::{Ty, TyCtxt};
16 use rustc_span::symbol::{sym, Symbol};
17 use rustc_target::abi::{Abi, LayoutOf as _, Primitive, Size};
19 use super::{CheckInAllocMsg, ImmTy, InterpCx, Machine, OpTy, PlaceTy};
24 fn numeric_intrinsic<'tcx, Tag>(
28 ) -> InterpResult<'tcx, 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 Ok(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 let alloc = type_name::alloc_type_name(tcx, tp_ty);
58 ConstValue::Slice { data: alloc, start: 0, end: alloc.len() }
60 sym::needs_drop => ConstValue::from_bool(tp_ty.needs_drop(tcx, param_env)),
61 sym::size_of | sym::min_align_of | sym::pref_align_of => {
62 let layout = tcx.layout_of(param_env.and(tp_ty)).map_err(|e| err_inval!(Layout(e)))?;
64 sym::pref_align_of => layout.align.pref.bytes(),
65 sym::min_align_of => layout.align.abi.bytes(),
66 sym::size_of => layout.size.bytes(),
69 ConstValue::from_machine_usize(n, &tcx)
71 sym::type_id => ConstValue::from_u64(tcx.type_id_hash(tp_ty)),
72 other => bug!("`{}` is not a zero arg intrinsic", other),
76 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
77 /// Returns `true` if emulation happened.
78 pub fn emulate_intrinsic(
80 instance: ty::Instance<'tcx>,
81 args: &[OpTy<'tcx, M::PointerTag>],
82 ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
83 ) -> InterpResult<'tcx, bool> {
84 let substs = instance.substs;
85 let intrinsic_name = self.tcx.item_name(instance.def_id());
87 // First handle intrinsics without return place.
88 let (dest, ret) = match ret {
89 None => match intrinsic_name {
90 sym::transmute => throw_ub_format!("transmuting to uninhabited type"),
91 sym::abort => M::abort(self)?,
92 // Unsupported diverging intrinsic.
93 _ => return Ok(false),
98 // Keep the patterns in this match ordered the same as the list in
99 // `src/librustc_middle/ty/constness.rs`
100 match intrinsic_name {
101 sym::caller_location => {
102 let span = self.find_closest_untracked_caller_location();
103 let location = self.alloc_caller_location_for_span(span);
104 self.write_scalar(location.ptr, dest)?;
112 | sym::type_name => {
113 let gid = GlobalId { instance, promoted: None };
114 let ty = match intrinsic_name {
115 sym::min_align_of | sym::pref_align_of | sym::size_of => self.tcx.types.usize,
116 sym::needs_drop => self.tcx.types.bool,
117 sym::type_id => self.tcx.types.u64,
118 sym::type_name => self.tcx.mk_static_str(),
119 _ => bug!("already checked for nullary intrinsics"),
121 let val = self.const_eval(gid, ty)?;
122 self.copy_op(val, dest)?;
131 | sym::bitreverse => {
132 let ty = substs.type_at(0);
133 let layout_of = self.layout_of(ty)?;
134 let val = self.read_scalar(args[0])?.not_undef()?;
135 let bits = self.force_bits(val, layout_of.size)?;
136 let kind = match layout_of.abi {
137 Abi::Scalar(ref scalar) => scalar.value,
138 _ => bug!("{} called on invalid type {:?}", intrinsic_name, ty),
140 let (nonzero, intrinsic_name) = match intrinsic_name {
141 sym::cttz_nonzero => (true, sym::cttz),
142 sym::ctlz_nonzero => (true, sym::ctlz),
143 other => (false, other),
145 if nonzero && bits == 0 {
146 throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
148 let out_val = numeric_intrinsic(intrinsic_name, bits, kind)?;
149 self.write_scalar(out_val, dest)?;
154 | sym::add_with_overflow
155 | sym::sub_with_overflow
156 | sym::mul_with_overflow => {
157 let lhs = self.read_immediate(args[0])?;
158 let rhs = self.read_immediate(args[1])?;
159 let (bin_op, ignore_overflow) = match intrinsic_name {
160 sym::wrapping_add => (BinOp::Add, true),
161 sym::wrapping_sub => (BinOp::Sub, true),
162 sym::wrapping_mul => (BinOp::Mul, true),
163 sym::add_with_overflow => (BinOp::Add, false),
164 sym::sub_with_overflow => (BinOp::Sub, false),
165 sym::mul_with_overflow => (BinOp::Mul, false),
166 _ => bug!("Already checked for int ops"),
169 self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
171 self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
174 sym::saturating_add | sym::saturating_sub => {
175 let l = self.read_immediate(args[0])?;
176 let r = self.read_immediate(args[1])?;
177 let is_add = intrinsic_name == sym::saturating_add;
178 let (val, overflowed, _ty) =
179 self.overflowing_binary_op(if is_add { BinOp::Add } else { BinOp::Sub }, l, r)?;
180 let val = if overflowed {
181 let num_bits = l.layout.size.bits();
182 if l.layout.abi.is_signed() {
183 // For signed ints the saturated value depends on the sign of the first
184 // term since the sign of the second term can be inferred from this and
185 // the fact that the operation has overflowed (if either is 0 no
186 // overflow can occur)
187 let first_term: u128 = self.force_bits(l.to_scalar()?, l.layout.size)?;
188 let first_term_positive = first_term & (1 << (num_bits - 1)) == 0;
189 if first_term_positive {
190 // Negative overflow not possible since the positive first term
191 // can only increase an (in range) negative term for addition
192 // or corresponding negated positive term for subtraction
194 (1u128 << (num_bits - 1)) - 1, // max positive
195 Size::from_bits(num_bits),
198 // Positive overflow not possible for similar reason
200 Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
207 u128::MAX >> (128 - num_bits),
208 Size::from_bits(num_bits),
212 Scalar::from_uint(0u128, Size::from_bits(num_bits))
218 self.write_scalar(val, dest)?;
220 sym::discriminant_value => {
221 let place = self.deref_operand(args[0])?;
222 let discr_val = self.read_discriminant(place.into())?.0;
223 self.write_scalar(discr_val, dest)?;
231 | sym::unchecked_rem => {
232 let l = self.read_immediate(args[0])?;
233 let r = self.read_immediate(args[1])?;
234 let bin_op = match intrinsic_name {
235 sym::unchecked_shl => BinOp::Shl,
236 sym::unchecked_shr => BinOp::Shr,
237 sym::unchecked_add => BinOp::Add,
238 sym::unchecked_sub => BinOp::Sub,
239 sym::unchecked_mul => BinOp::Mul,
240 sym::unchecked_div => BinOp::Div,
241 sym::unchecked_rem => BinOp::Rem,
242 _ => bug!("Already checked for int ops"),
244 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
246 let layout = self.layout_of(substs.type_at(0))?;
247 let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
248 if let sym::unchecked_shl | sym::unchecked_shr = intrinsic_name {
249 throw_ub_format!("overflowing shift by {} in `{}`", r_val, intrinsic_name);
251 throw_ub_format!("overflow executing `{}`", intrinsic_name);
254 self.write_scalar(val, dest)?;
256 sym::rotate_left | sym::rotate_right => {
257 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
258 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
259 let layout = self.layout_of(substs.type_at(0))?;
260 let val = self.read_scalar(args[0])?.not_undef()?;
261 let val_bits = self.force_bits(val, layout.size)?;
262 let raw_shift = self.read_scalar(args[1])?.not_undef()?;
263 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
264 let width_bits = u128::from(layout.size.bits());
265 let shift_bits = raw_shift_bits % width_bits;
266 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
267 let result_bits = if intrinsic_name == sym::rotate_left {
268 (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
270 (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
272 let truncated_bits = self.truncate(result_bits, layout);
273 let result = Scalar::from_uint(truncated_bits, layout.size);
274 self.write_scalar(result, dest)?;
277 let ptr = self.read_scalar(args[0])?.not_undef()?;
278 let offset_count = self.read_scalar(args[1])?.to_machine_isize(self)?;
279 let pointee_ty = substs.type_at(0);
281 let offset_ptr = self.ptr_offset_inbounds(ptr, pointee_ty, offset_count)?;
282 self.write_scalar(offset_ptr, dest)?;
284 sym::arith_offset => {
285 let ptr = self.read_scalar(args[0])?.not_undef()?;
286 let offset_count = self.read_scalar(args[1])?.to_machine_isize(self)?;
287 let pointee_ty = substs.type_at(0);
289 let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
290 let offset_bytes = offset_count.wrapping_mul(pointee_size);
291 let offset_ptr = ptr.ptr_wrapping_signed_offset(offset_bytes, self);
292 self.write_scalar(offset_ptr, dest)?;
294 sym::ptr_offset_from => {
295 let a = self.read_immediate(args[0])?.to_scalar()?;
296 let b = self.read_immediate(args[1])?.to_scalar()?;
298 // Special case: if both scalars are *equal integers*
299 // and not NULL, we pretend there is an allocation of size 0 right there,
300 // and their offset is 0. (There's never a valid object at NULL, making it an
301 // exception from the exception.)
302 // This is the dual to the special exception for offset-by-0
303 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
305 // Control flow is weird because we cannot early-return (to reach the
306 // `go_to_block` at the end).
307 let done = if a.is_bits() && b.is_bits() {
308 let a = a.to_machine_usize(self)?;
309 let b = b.to_machine_usize(self)?;
310 if a == b && a != 0 {
311 self.write_scalar(Scalar::from_machine_isize(0, self), dest)?;
321 // General case: we need two pointers.
322 let a = self.force_ptr(a)?;
323 let b = self.force_ptr(b)?;
324 if a.alloc_id != b.alloc_id {
326 "ptr_offset_from cannot compute offset of pointers into different \
330 let usize_layout = self.layout_of(self.tcx.types.usize)?;
331 let isize_layout = self.layout_of(self.tcx.types.isize)?;
332 let a_offset = ImmTy::from_uint(a.offset.bytes(), usize_layout);
333 let b_offset = ImmTy::from_uint(b.offset.bytes(), usize_layout);
334 let (val, _overflowed, _ty) =
335 self.overflowing_binary_op(BinOp::Sub, a_offset, b_offset)?;
336 let pointee_layout = self.layout_of(substs.type_at(0))?;
337 let val = ImmTy::from_scalar(val, isize_layout);
338 let size = ImmTy::from_int(pointee_layout.size.bytes(), isize_layout);
339 self.exact_div(val, size, dest)?;
344 self.copy_op_transmute(args[0], dest)?;
346 sym::simd_insert => {
347 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
350 let (len, e_ty) = input.layout.ty.simd_size_and_type(*self.tcx);
353 "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
359 input.layout, dest.layout,
360 "Return type `{}` must match vector type `{}`",
361 dest.layout.ty, input.layout.ty
364 elem.layout.ty, e_ty,
365 "Scalar element type `{}` must match vector element type `{}`",
370 let place = self.place_index(dest, i)?;
371 let value = if i == index { elem } else { self.operand_index(input, i)? };
372 self.copy_op(value, place)?;
375 sym::simd_extract => {
376 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
377 let (len, e_ty) = args[0].layout.ty.simd_size_and_type(*self.tcx);
380 "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
386 e_ty, dest.layout.ty,
387 "Return type `{}` must match vector element type `{}`",
390 self.copy_op(self.operand_index(args[0], index)?, dest)?;
392 sym::count_code_region => (),
393 _ => return Ok(false),
396 self.dump_place(*dest);
397 self.go_to_block(ret);
403 a: ImmTy<'tcx, M::PointerTag>,
404 b: ImmTy<'tcx, M::PointerTag>,
405 dest: PlaceTy<'tcx, M::PointerTag>,
406 ) -> InterpResult<'tcx> {
407 // Performs an exact division, resulting in undefined behavior where
408 // `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`.
409 // First, check x % y != 0 (or if that computation overflows).
410 let (res, overflow, _ty) = self.overflowing_binary_op(BinOp::Rem, a, b)?;
411 if overflow || res.assert_bits(a.layout.size) != 0 {
412 // Then, check if `b` is -1, which is the "MIN / -1" case.
413 let minus1 = Scalar::from_int(-1, dest.layout.size);
414 let b_scalar = b.to_scalar().unwrap();
415 if b_scalar == minus1 {
416 throw_ub_format!("exact_div: result of dividing MIN by -1 cannot be represented")
418 throw_ub_format!("exact_div: {} cannot be divided by {} without remainder", a, b,)
421 // `Rem` says this is all right, so we can let `Div` do its job.
422 self.binop_ignore_overflow(BinOp::Div, a, b, dest)
425 /// Offsets a pointer by some multiple of its type, returning an error if the pointer leaves its
426 /// allocation. For integer pointers, we consider each of them their own tiny allocation of size
427 /// 0, so offset-by-0 (and only 0) is okay -- except that NULL cannot be offset by _any_ value.
428 pub fn ptr_offset_inbounds(
430 ptr: Scalar<M::PointerTag>,
431 pointee_ty: Ty<'tcx>,
433 ) -> InterpResult<'tcx, Scalar<M::PointerTag>> {
434 // We cannot overflow i64 as a type's size must be <= isize::MAX.
435 let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap();
436 // The computed offset, in bytes, cannot overflow an isize.
438 offset_count.checked_mul(pointee_size).ok_or(err_ub!(PointerArithOverflow))?;
439 // The offset being in bounds cannot rely on "wrapping around" the address space.
440 // So, first rule out overflows in the pointer arithmetic.
441 let offset_ptr = ptr.ptr_signed_offset(offset_bytes, self)?;
442 // ptr and offset_ptr must be in bounds of the same allocated object. This means all of the
443 // memory between these pointers must be accessible. Note that we do not require the
444 // pointers to be properly aligned (unlike a read/write operation).
445 let min_ptr = if offset_bytes >= 0 { ptr } else { offset_ptr };
446 let size: u64 = uabs(offset_bytes);
447 // This call handles checking for integer/NULL pointers.
448 self.memory.check_ptr_access_align(
450 Size::from_bytes(size),
452 CheckInAllocMsg::InboundsTest,