1 //! Intrinsics and other functions that the miri engine executes without
2 //! looking at their MIR. Intrinsics/functions supported here are shared by CTFE
7 interpret::{ConstValue, GlobalId, InterpResult, Scalar},
11 use rustc::ty::layout::{LayoutOf, Primitive, Size};
12 use rustc::ty::subst::SubstsRef;
13 use rustc::ty::TyCtxt;
14 use rustc_hir::def_id::DefId;
15 use rustc_span::symbol::{sym, Symbol};
18 use super::{ImmTy, InterpCx, Machine, OpTy, PlaceTy};
23 fn numeric_intrinsic<'tcx, Tag>(
27 ) -> InterpResult<'tcx, Scalar<Tag>> {
28 let size = match kind {
29 Primitive::Int(integer, _) => integer.size(),
30 _ => bug!("invalid `{}` argument: {:?}", name, bits),
32 let extra = 128 - size.bits() as u128;
33 let bits_out = match name {
34 sym::ctpop => bits.count_ones() as u128,
35 sym::ctlz => bits.leading_zeros() as u128 - extra,
36 sym::cttz => (bits << extra).trailing_zeros() as u128 - extra,
37 sym::bswap => (bits << extra).swap_bytes(),
38 sym::bitreverse => (bits << extra).reverse_bits(),
39 _ => bug!("not a numeric intrinsic: {}", name),
41 Ok(Scalar::from_uint(bits_out, size))
44 /// The logic for all nullary intrinsics is implemented here. These intrinsics don't get evaluated
45 /// inside an `InterpCx` and instead have their value computed directly from rustc internal info.
46 crate fn eval_nullary_intrinsic<'tcx>(
48 param_env: ty::ParamEnv<'tcx>,
50 substs: SubstsRef<'tcx>,
51 ) -> InterpResult<'tcx, ConstValue<'tcx>> {
52 let tp_ty = substs.type_at(0);
53 let name = tcx.item_name(def_id);
56 let alloc = type_name::alloc_type_name(tcx, tp_ty);
57 ConstValue::Slice { data: alloc, start: 0, end: alloc.len() }
59 sym::needs_drop => ConstValue::from_bool(tp_ty.needs_drop(tcx, param_env)),
60 sym::size_of | sym::min_align_of | sym::pref_align_of => {
61 let layout = tcx.layout_of(param_env.and(tp_ty)).map_err(|e| err_inval!(Layout(e)))?;
63 sym::pref_align_of => layout.align.pref.bytes(),
64 sym::min_align_of => layout.align.abi.bytes(),
65 sym::size_of => layout.size.bytes(),
68 ConstValue::from_machine_usize(n, &tcx)
70 sym::type_id => ConstValue::from_u64(tcx.type_id_hash(tp_ty)),
71 other => bug!("`{}` is not a zero arg intrinsic", other),
75 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
76 /// Returns `true` if emulation happened.
77 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/ty/constness.rs`
100 match intrinsic_name {
101 sym::caller_location => {
102 let span = self.find_closest_untracked_caller_location().unwrap_or(span);
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 _ => span_bug!(span, "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 ty::layout::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(Scalar::from_uint(discr_val, dest.layout.size), 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 = layout.size.bits() as u128;
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 sym::ptr_offset_from => {
278 let isize_layout = self.layout_of(self.tcx.types.isize)?;
279 let a = self.read_immediate(args[0])?.to_scalar()?;
280 let b = self.read_immediate(args[1])?.to_scalar()?;
282 // Special case: if both scalars are *equal integers*
283 // and not NULL, we pretend there is an allocation of size 0 right there,
284 // and their offset is 0. (There's never a valid object at NULL, making it an
285 // exception from the exception.)
286 // This is the dual to the special exception for offset-by-0
287 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
289 // Control flow is weird because we cannot early-return (to reach the
290 // `go_to_block` at the end).
291 let done = if a.is_bits() && b.is_bits() {
292 let a = a.to_machine_usize(self)?;
293 let b = b.to_machine_usize(self)?;
294 if a == b && a != 0 {
295 self.write_scalar(Scalar::from_int(0, isize_layout.size), dest)?;
305 // General case: we need two pointers.
306 let a = self.force_ptr(a)?;
307 let b = self.force_ptr(b)?;
308 if a.alloc_id != b.alloc_id {
310 "ptr_offset_from cannot compute offset of pointers into different \
314 let usize_layout = self.layout_of(self.tcx.types.usize)?;
315 let a_offset = ImmTy::from_uint(a.offset.bytes(), usize_layout);
316 let b_offset = ImmTy::from_uint(b.offset.bytes(), usize_layout);
317 let (val, _overflowed, _ty) =
318 self.overflowing_binary_op(BinOp::Sub, a_offset, b_offset)?;
319 let pointee_layout = self.layout_of(substs.type_at(0))?;
320 let val = ImmTy::from_scalar(val, isize_layout);
321 let size = ImmTy::from_int(pointee_layout.size.bytes(), isize_layout);
322 self.exact_div(val, size, dest)?;
327 self.copy_op_transmute(args[0], dest)?;
329 sym::simd_insert => {
330 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
333 let (len, e_ty) = input.layout.ty.simd_size_and_type(self.tcx.tcx);
336 "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
342 input.layout, dest.layout,
343 "Return type `{}` must match vector type `{}`",
344 dest.layout.ty, input.layout.ty
347 elem.layout.ty, e_ty,
348 "Scalar element type `{}` must match vector element type `{}`",
353 let place = self.place_field(dest, i)?;
354 let value = if i == index { elem } else { self.operand_field(input, i)? };
355 self.copy_op(value, place)?;
358 sym::simd_extract => {
359 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
360 let (len, e_ty) = args[0].layout.ty.simd_size_and_type(self.tcx.tcx);
363 "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
369 e_ty, dest.layout.ty,
370 "Return type `{}` must match vector element type `{}`",
373 self.copy_op(self.operand_field(args[0], index)?, dest)?;
375 _ => return Ok(false),
378 self.dump_place(*dest);
379 self.go_to_block(ret);
385 a: ImmTy<'tcx, M::PointerTag>,
386 b: ImmTy<'tcx, M::PointerTag>,
387 dest: PlaceTy<'tcx, M::PointerTag>,
388 ) -> InterpResult<'tcx> {
389 // Performs an exact division, resulting in undefined behavior where
390 // `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`.
391 // First, check x % y != 0 (or if that computation overflows).
392 let (res, overflow, _ty) = self.overflowing_binary_op(BinOp::Rem, a, b)?;
393 if overflow || res.assert_bits(a.layout.size) != 0 {
394 // Then, check if `b` is -1, which is the "MIN / -1" case.
395 let minus1 = Scalar::from_int(-1, dest.layout.size);
396 let b_scalar = b.to_scalar().unwrap();
397 if b_scalar == minus1 {
398 throw_ub_format!("exact_div: result of dividing MIN by -1 cannot be represented")
400 throw_ub_format!("exact_div: {} cannot be divided by {} without remainder", a, b,)
403 // `Rem` says this is all right, so we can let `Div` do its job.
404 self.binop_ignore_overflow(BinOp::Div, a, b, dest)