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, &'tcx ty::Const<'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 tcx.mk_const(ty::Const {
58 val: ty::ConstKind::Value(ConstValue::Slice {
63 ty: tcx.mk_static_str(),
66 sym::needs_drop => ty::Const::from_bool(tcx, tp_ty.needs_drop(tcx, param_env)),
67 sym::size_of | sym::min_align_of | sym::pref_align_of => {
68 let layout = tcx.layout_of(param_env.and(tp_ty)).map_err(|e| err_inval!(Layout(e)))?;
70 sym::pref_align_of => layout.align.pref.bytes(),
71 sym::min_align_of => layout.align.abi.bytes(),
72 sym::size_of => layout.size.bytes(),
75 ty::Const::from_usize(tcx, n)
78 ty::Const::from_bits(tcx, tcx.type_id_hash(tp_ty).into(), param_env.and(tcx.types.u64))
80 other => bug!("`{}` is not a zero arg intrinsic", other),
84 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
85 /// Returns `true` if emulation happened.
86 pub fn emulate_intrinsic(
89 instance: ty::Instance<'tcx>,
90 args: &[OpTy<'tcx, M::PointerTag>],
91 ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
92 ) -> InterpResult<'tcx, bool> {
93 let substs = instance.substs;
94 let intrinsic_name = self.tcx.item_name(instance.def_id());
96 // We currently do not handle any intrinsics that are *allowed* to diverge,
97 // but `transmute` could lack a return place in case of UB.
98 let (dest, ret) = match ret {
100 None => match intrinsic_name {
101 sym::transmute => throw_ub!(Unreachable),
102 _ => return Ok(false),
106 // Keep the patterns in this match ordered the same as the list in
107 // `src/librustc/ty/constness.rs`
108 match intrinsic_name {
109 sym::caller_location => {
110 let span = self.find_closest_untracked_caller_location().unwrap_or(span);
111 let location = self.alloc_caller_location_for_span(span);
112 self.write_scalar(location.ptr, dest)?;
120 | sym::type_name => {
121 let gid = GlobalId { instance, promoted: None };
122 let val = self.const_eval(gid)?;
123 self.copy_op(val, dest)?;
132 | sym::bitreverse => {
133 let ty = substs.type_at(0);
134 let layout_of = self.layout_of(ty)?;
135 let val = self.read_scalar(args[0])?.not_undef()?;
136 let bits = self.force_bits(val, layout_of.size)?;
137 let kind = match layout_of.abi {
138 ty::layout::Abi::Scalar(ref scalar) => scalar.value,
139 _ => throw_unsup!(TypeNotPrimitive(ty)),
141 let (nonzero, intrinsic_name) = match intrinsic_name {
142 sym::cttz_nonzero => (true, sym::cttz),
143 sym::ctlz_nonzero => (true, sym::ctlz),
144 other => (false, other),
146 if nonzero && bits == 0 {
147 throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
149 let out_val = numeric_intrinsic(intrinsic_name, bits, kind)?;
150 self.write_scalar(out_val, dest)?;
155 | sym::add_with_overflow
156 | sym::sub_with_overflow
157 | sym::mul_with_overflow => {
158 let lhs = self.read_immediate(args[0])?;
159 let rhs = self.read_immediate(args[1])?;
160 let (bin_op, ignore_overflow) = match intrinsic_name {
161 sym::wrapping_add => (BinOp::Add, true),
162 sym::wrapping_sub => (BinOp::Sub, true),
163 sym::wrapping_mul => (BinOp::Mul, true),
164 sym::add_with_overflow => (BinOp::Add, false),
165 sym::sub_with_overflow => (BinOp::Sub, false),
166 sym::mul_with_overflow => (BinOp::Mul, false),
167 _ => bug!("Already checked for int ops"),
170 self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
172 self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
175 sym::saturating_add | sym::saturating_sub => {
176 let l = self.read_immediate(args[0])?;
177 let r = self.read_immediate(args[1])?;
178 let is_add = intrinsic_name == sym::saturating_add;
179 let (val, overflowed, _ty) =
180 self.overflowing_binary_op(if is_add { BinOp::Add } else { BinOp::Sub }, l, r)?;
181 let val = if overflowed {
182 let num_bits = l.layout.size.bits();
183 if l.layout.abi.is_signed() {
184 // For signed ints the saturated value depends on the sign of the first
185 // term since the sign of the second term can be inferred from this and
186 // the fact that the operation has overflowed (if either is 0 no
187 // overflow can occur)
188 let first_term: u128 = self.force_bits(l.to_scalar()?, l.layout.size)?;
189 let first_term_positive = first_term & (1 << (num_bits - 1)) == 0;
190 if first_term_positive {
191 // Negative overflow not possible since the positive first term
192 // can only increase an (in range) negative term for addition
193 // or corresponding negated positive term for subtraction
195 (1u128 << (num_bits - 1)) - 1, // max positive
196 Size::from_bits(num_bits),
199 // Positive overflow not possible for similar reason
201 Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
208 u128::max_value() >> (128 - num_bits),
209 Size::from_bits(num_bits),
213 Scalar::from_uint(0u128, Size::from_bits(num_bits))
219 self.write_scalar(val, dest)?;
227 | sym::unchecked_rem => {
228 let l = self.read_immediate(args[0])?;
229 let r = self.read_immediate(args[1])?;
230 let bin_op = match intrinsic_name {
231 sym::unchecked_shl => BinOp::Shl,
232 sym::unchecked_shr => BinOp::Shr,
233 sym::unchecked_add => BinOp::Add,
234 sym::unchecked_sub => BinOp::Sub,
235 sym::unchecked_mul => BinOp::Mul,
236 sym::unchecked_div => BinOp::Div,
237 sym::unchecked_rem => BinOp::Rem,
238 _ => bug!("Already checked for int ops"),
240 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
242 let layout = self.layout_of(substs.type_at(0))?;
243 let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
244 if let sym::unchecked_shl | sym::unchecked_shr = intrinsic_name {
245 throw_ub_format!("Overflowing shift by {} in `{}`", r_val, intrinsic_name);
247 throw_ub_format!("Overflow executing `{}`", intrinsic_name);
250 self.write_scalar(val, dest)?;
252 sym::rotate_left | sym::rotate_right => {
253 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
254 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
255 let layout = self.layout_of(substs.type_at(0))?;
256 let val = self.read_scalar(args[0])?.not_undef()?;
257 let val_bits = self.force_bits(val, layout.size)?;
258 let raw_shift = self.read_scalar(args[1])?.not_undef()?;
259 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
260 let width_bits = layout.size.bits() as u128;
261 let shift_bits = raw_shift_bits % width_bits;
262 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
263 let result_bits = if intrinsic_name == sym::rotate_left {
264 (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
266 (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
268 let truncated_bits = self.truncate(result_bits, layout);
269 let result = Scalar::from_uint(truncated_bits, layout.size);
270 self.write_scalar(result, dest)?;
273 sym::ptr_offset_from => {
274 let isize_layout = self.layout_of(self.tcx.types.isize)?;
275 let a = self.read_immediate(args[0])?.to_scalar()?;
276 let b = self.read_immediate(args[1])?.to_scalar()?;
278 // Special case: if both scalars are *equal integers*
279 // and not NULL, we pretend there is an allocation of size 0 right there,
280 // and their offset is 0. (There's never a valid object at NULL, making it an
281 // exception from the exception.)
282 // This is the dual to the special exception for offset-by-0
283 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
285 // Control flow is weird because we cannot early-return (to reach the
286 // `go_to_block` at the end).
287 let done = if a.is_bits() && b.is_bits() {
288 let a = a.to_machine_usize(self)?;
289 let b = b.to_machine_usize(self)?;
290 if a == b && a != 0 {
291 self.write_scalar(Scalar::from_int(0, isize_layout.size), dest)?;
301 // General case: we need two pointers.
302 let a = self.force_ptr(a)?;
303 let b = self.force_ptr(b)?;
304 if a.alloc_id != b.alloc_id {
306 "ptr_offset_from cannot compute offset of pointers into different \
310 let usize_layout = self.layout_of(self.tcx.types.usize)?;
311 let a_offset = ImmTy::from_uint(a.offset.bytes(), usize_layout);
312 let b_offset = ImmTy::from_uint(b.offset.bytes(), usize_layout);
313 let (val, _overflowed, _ty) =
314 self.overflowing_binary_op(BinOp::Sub, a_offset, b_offset)?;
315 let pointee_layout = self.layout_of(substs.type_at(0))?;
316 let val = ImmTy::from_scalar(val, isize_layout);
317 let size = ImmTy::from_int(pointee_layout.size.bytes(), isize_layout);
318 self.exact_div(val, size, dest)?;
323 self.copy_op_transmute(args[0], dest)?;
325 sym::simd_insert => {
326 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
329 let (len, e_ty) = input.layout.ty.simd_size_and_type(self.tcx.tcx);
332 "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
338 input.layout, dest.layout,
339 "Return type `{}` must match vector type `{}`",
340 dest.layout.ty, input.layout.ty
343 elem.layout.ty, e_ty,
344 "Scalar element type `{}` must match vector element type `{}`",
349 let place = self.place_field(dest, i)?;
350 let value = if i == index { elem } else { self.operand_field(input, i)? };
351 self.copy_op(value, place)?;
354 sym::simd_extract => {
355 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
356 let (len, e_ty) = args[0].layout.ty.simd_size_and_type(self.tcx.tcx);
359 "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
365 e_ty, dest.layout.ty,
366 "Return type `{}` must match vector element type `{}`",
369 self.copy_op(self.operand_field(args[0], index)?, dest)?;
371 _ => return Ok(false),
374 self.dump_place(*dest);
375 self.go_to_block(ret);
381 a: ImmTy<'tcx, M::PointerTag>,
382 b: ImmTy<'tcx, M::PointerTag>,
383 dest: PlaceTy<'tcx, M::PointerTag>,
384 ) -> InterpResult<'tcx> {
385 // Performs an exact division, resulting in undefined behavior where
386 // `x % y != 0` or `y == 0` or `x == T::min_value() && y == -1`.
387 // First, check x % y != 0 (or if that computation overflows).
388 let (res, overflow, _ty) = self.overflowing_binary_op(BinOp::Rem, a, b)?;
389 if overflow || res.to_bits(a.layout.size)? != 0 {
390 // Then, check if `b` is -1, which is the "min_value / -1" case.
391 let minus1 = Scalar::from_int(-1, dest.layout.size);
392 let b_scalar = b.to_scalar().unwrap();
393 if b_scalar == minus1 {
394 throw_ub_format!("exact_div: result of dividing MIN by -1 cannot be represented")
396 throw_ub_format!("exact_div: {} cannot be divided by {} without remainder", a, b,)
399 // `Rem` says this is all right, so we can let `Div` do its job.
400 self.binop_ignore_overflow(BinOp::Div, a, b, dest)