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 syntax::symbol::Symbol;
8 use rustc::ty::layout::{LayoutOf, Primitive, Size};
9 use rustc::ty::subst::SubstsRef;
10 use rustc::hir::def_id::DefId;
11 use rustc::ty::TyCtxt;
12 use rustc::mir::BinOp;
13 use rustc::mir::interpret::{InterpResult, Scalar, GlobalId, ConstValue};
16 Machine, PlaceTy, OpTy, InterpCx, ImmTy,
22 fn numeric_intrinsic<'tcx, Tag>(
26 ) -> InterpResult<'tcx, Scalar<Tag>> {
27 let size = match kind {
28 Primitive::Int(integer, _) => integer.size(),
29 _ => bug!("invalid `{}` argument: {:?}", name, bits),
31 let extra = 128 - size.bits() as u128;
32 let bits_out = match name {
33 "ctpop" => bits.count_ones() as u128,
34 "ctlz" => bits.leading_zeros() as u128 - extra,
35 "cttz" => (bits << extra).trailing_zeros() as u128 - extra,
36 "bswap" => (bits << extra).swap_bytes(),
37 "bitreverse" => (bits << extra).reverse_bits(),
38 _ => bug!("not a numeric intrinsic: {}", name),
40 Ok(Scalar::from_uint(bits_out, size))
43 /// The logic for all nullary intrinsics is implemented here. These intrinsics don't get evaluated
44 /// inside an `InterpCx` and instead have their value computed directly from rustc internal info.
45 crate fn eval_nullary_intrinsic<'tcx>(
47 param_env: ty::ParamEnv<'tcx>,
49 substs: SubstsRef<'tcx>,
50 ) -> InterpResult<'tcx, &'tcx ty::Const<'tcx>> {
51 let tp_ty = substs.type_at(0);
52 let name = &*tcx.item_name(def_id).as_str();
55 let alloc = type_name::alloc_type_name(tcx, tp_ty);
56 tcx.mk_const(ty::Const {
57 val: ConstValue::Slice {
62 ty: tcx.mk_static_str(),
65 "needs_drop" => ty::Const::from_bool(tcx, tp_ty.needs_drop(tcx, param_env)),
69 let layout = tcx.layout_of(param_env.and(tp_ty)).map_err(|e| err_inval!(Layout(e)))?;
71 "pref_align_of" => layout.align.pref.bytes(),
72 "min_align_of" => layout.align.abi.bytes(),
73 "size_of" => layout.size.bytes(),
76 ty::Const::from_usize(tcx, n)
78 "type_id" => ty::Const::from_bits(
80 tcx.type_id_hash(tp_ty).into(),
81 param_env.and(tcx.types.u64),
83 other => bug!("`{}` is not a zero arg intrinsic", other),
87 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
88 /// Returns `true` if emulation happened.
89 pub fn emulate_intrinsic(
92 instance: ty::Instance<'tcx>,
93 args: &[OpTy<'tcx, M::PointerTag>],
94 dest: Option<PlaceTy<'tcx, M::PointerTag>>,
95 ) -> InterpResult<'tcx, bool> {
96 let substs = instance.substs;
98 // The intrinsic itself cannot diverge, so if we got here without a return
99 // place... (can happen e.g., for transmute returning `!`)
100 let dest = match dest {
102 None => throw_ub!(Unreachable)
104 let intrinsic_name = &self.tcx.item_name(instance.def_id()).as_str();
106 match intrinsic_name {
107 "caller_location" => {
108 let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
109 let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
110 let location = self.alloc_caller_location(
111 Symbol::intern(&caller.file.name.to_string()),
113 caller.col_display as u32 + 1,
115 self.write_scalar(location.ptr, dest)?;
128 let val = self.tcx.const_eval(self.param_env.and(gid))?;
129 let val = self.eval_const_to_op(val, None)?;
130 self.copy_op(val, dest)?;
140 let ty = substs.type_at(0);
141 let layout_of = self.layout_of(ty)?;
142 let val = self.read_scalar(args[0])?.not_undef()?;
143 let bits = self.force_bits(val, layout_of.size)?;
144 let kind = match layout_of.abi {
145 ty::layout::Abi::Scalar(ref scalar) => scalar.value,
146 _ => throw_unsup!(TypeNotPrimitive(ty)),
148 let out_val = if intrinsic_name.ends_with("_nonzero") {
150 throw_ub_format!("`{}` called on 0", intrinsic_name);
152 numeric_intrinsic(intrinsic_name.trim_end_matches("_nonzero"), bits, kind)?
154 numeric_intrinsic(intrinsic_name, bits, kind)?
156 self.write_scalar(out_val, dest)?;
161 | "add_with_overflow"
162 | "sub_with_overflow"
163 | "mul_with_overflow" => {
164 let lhs = self.read_immediate(args[0])?;
165 let rhs = self.read_immediate(args[1])?;
166 let (bin_op, ignore_overflow) = match intrinsic_name {
167 "wrapping_add" => (BinOp::Add, true),
168 "wrapping_sub" => (BinOp::Sub, true),
169 "wrapping_mul" => (BinOp::Mul, true),
170 "add_with_overflow" => (BinOp::Add, false),
171 "sub_with_overflow" => (BinOp::Sub, false),
172 "mul_with_overflow" => (BinOp::Mul, false),
173 _ => bug!("Already checked for int ops")
176 self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
178 self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
181 "saturating_add" | "saturating_sub" => {
182 let l = self.read_immediate(args[0])?;
183 let r = self.read_immediate(args[1])?;
184 let is_add = intrinsic_name == "saturating_add";
185 let (val, overflowed, _ty) = self.overflowing_binary_op(if is_add {
190 let val = if overflowed {
191 let num_bits = l.layout.size.bits();
192 if l.layout.abi.is_signed() {
193 // For signed ints the saturated value depends on the sign of the first
194 // term since the sign of the second term can be inferred from this and
195 // the fact that the operation has overflowed (if either is 0 no
196 // overflow can occur)
197 let first_term: u128 = self.force_bits(l.to_scalar()?, l.layout.size)?;
198 let first_term_positive = first_term & (1 << (num_bits-1)) == 0;
199 if first_term_positive {
200 // Negative overflow not possible since the positive first term
201 // can only increase an (in range) negative term for addition
202 // or corresponding negated positive term for subtraction
203 Scalar::from_uint((1u128 << (num_bits - 1)) - 1, // max positive
204 Size::from_bits(num_bits))
206 // Positive overflow not possible for similar reason
208 Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
213 Scalar::from_uint(u128::max_value() >> (128 - num_bits),
214 Size::from_bits(num_bits))
215 } else { // underflow to 0
216 Scalar::from_uint(0u128, Size::from_bits(num_bits))
222 self.write_scalar(val, dest)?;
224 "unchecked_shl" | "unchecked_shr" => {
225 let l = self.read_immediate(args[0])?;
226 let r = self.read_immediate(args[1])?;
227 let bin_op = match intrinsic_name {
228 "unchecked_shl" => BinOp::Shl,
229 "unchecked_shr" => BinOp::Shr,
230 _ => bug!("Already checked for int ops")
232 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
234 let layout = self.layout_of(substs.type_at(0))?;
235 let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
236 throw_ub_format!("Overflowing shift by {} in `{}`", r_val, intrinsic_name);
238 self.write_scalar(val, dest)?;
240 "rotate_left" | "rotate_right" => {
241 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
242 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
243 let layout = self.layout_of(substs.type_at(0))?;
244 let val = self.read_scalar(args[0])?.not_undef()?;
245 let val_bits = self.force_bits(val, layout.size)?;
246 let raw_shift = self.read_scalar(args[1])?.not_undef()?;
247 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
248 let width_bits = layout.size.bits() as u128;
249 let shift_bits = raw_shift_bits % width_bits;
250 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
251 let result_bits = if intrinsic_name == "rotate_left" {
252 (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
254 (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
256 let truncated_bits = self.truncate(result_bits, layout);
257 let result = Scalar::from_uint(truncated_bits, layout.size);
258 self.write_scalar(result, dest)?;
261 "ptr_offset_from" => {
262 let isize_layout = self.layout_of(self.tcx.types.isize)?;
263 let a = self.read_immediate(args[0])?.to_scalar()?;
264 let b = self.read_immediate(args[1])?.to_scalar()?;
266 // Special case: if both scalars are *equal integers*
267 // and not NULL, we pretend there is an allocation of size 0 right there,
268 // and their offset is 0. (There's never a valid object at NULL, making it an
269 // exception from the exception.)
270 // This is the dual to the special exception for offset-by-0
271 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
272 if a.is_bits() && b.is_bits() {
273 let a = a.to_machine_usize(self)?;
274 let b = b.to_machine_usize(self)?;
275 if a == b && a != 0 {
276 self.write_scalar(Scalar::from_int(0, isize_layout.size), dest)?;
281 // General case: we need two pointers.
282 let a = self.force_ptr(a)?;
283 let b = self.force_ptr(b)?;
284 if a.alloc_id != b.alloc_id {
286 "ptr_offset_from cannot compute offset of pointers into different \
290 let usize_layout = self.layout_of(self.tcx.types.usize)?;
291 let a_offset = ImmTy::from_uint(a.offset.bytes(), usize_layout);
292 let b_offset = ImmTy::from_uint(b.offset.bytes(), usize_layout);
293 let (val, _overflowed, _ty) = self.overflowing_binary_op(
294 BinOp::Sub, a_offset, b_offset,
296 let pointee_layout = self.layout_of(substs.type_at(0))?;
297 let val = ImmTy::from_scalar(val, isize_layout);
298 let size = ImmTy::from_int(pointee_layout.size.bytes(), isize_layout);
299 self.exact_div(val, size, dest)?;
303 self.copy_op_transmute(args[0], dest)?;
306 let index = self.read_scalar(args[1])?.to_u32()? as u64;
307 let scalar = args[2];
309 let (len, e_ty) = self.read_vector_ty(input);
312 "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
316 input.layout, dest.layout,
317 "Return type `{}` must match vector type `{}`",
318 dest.layout.ty, input.layout.ty
321 scalar.layout.ty, e_ty,
322 "Scalar type `{}` must match vector element type `{}`",
323 scalar.layout.ty, e_ty
327 let place = self.place_field(dest, i)?;
328 let value = if i == index {
331 self.operand_field(input, i)?
333 self.copy_op(value, place)?;
337 let index = self.read_scalar(args[1])?.to_u32()? as _;
338 let (len, e_ty) = self.read_vector_ty(args[0]);
341 "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
345 e_ty, dest.layout.ty,
346 "Return type `{}` must match vector element type `{}`",
349 self.copy_op(self.operand_field(args[0], index)?, dest)?;
351 _ => return Ok(false),
357 /// "Intercept" a function call to a panic-related function
358 /// because we have something special to do for it.
359 /// Returns `true` if an intercept happened.
360 pub fn hook_panic_fn(
362 instance: ty::Instance<'tcx>,
363 args: &[OpTy<'tcx, M::PointerTag>],
364 _dest: Option<PlaceTy<'tcx, M::PointerTag>>,
365 ) -> InterpResult<'tcx, bool> {
366 let def_id = instance.def_id();
367 if Some(def_id) == self.tcx.lang_items().panic_fn() {
368 // &'static str, &core::panic::Location { &'static str, u32, u32 }
369 assert!(args.len() == 2);
371 let msg_place = self.deref_operand(args[0])?;
372 let msg = Symbol::intern(self.read_str(msg_place)?);
374 let location = self.deref_operand(args[1])?;
375 let (file, line, col) = (
376 self.mplace_field(location, 0)?,
377 self.mplace_field(location, 1)?,
378 self.mplace_field(location, 2)?,
381 let file_place = self.deref_operand(file.into())?;
382 let file = Symbol::intern(self.read_str(file_place)?);
383 let line = self.read_scalar(line.into())?.to_u32()?;
384 let col = self.read_scalar(col.into())?.to_u32()?;
385 throw_panic!(Panic { msg, file, line, col })
386 } else if Some(def_id) == self.tcx.lang_items().begin_panic_fn() {
387 assert!(args.len() == 2);
388 // &'static str, &(&'static str, u32, u32)
390 let place = self.deref_operand(args[1])?;
391 let (file, line, col) = (
392 self.mplace_field(place, 0)?,
393 self.mplace_field(place, 1)?,
394 self.mplace_field(place, 2)?,
397 let msg_place = self.deref_operand(msg.into())?;
398 let msg = Symbol::intern(self.read_str(msg_place)?);
399 let file_place = self.deref_operand(file.into())?;
400 let file = Symbol::intern(self.read_str(file_place)?);
401 let line = self.read_scalar(line.into())?.to_u32()?;
402 let col = self.read_scalar(col.into())?.to_u32()?;
403 throw_panic!(Panic { msg, file, line, col })
411 a: ImmTy<'tcx, M::PointerTag>,
412 b: ImmTy<'tcx, M::PointerTag>,
413 dest: PlaceTy<'tcx, M::PointerTag>,
414 ) -> InterpResult<'tcx> {
415 // Performs an exact division, resulting in undefined behavior where
416 // `x % y != 0` or `y == 0` or `x == T::min_value() && y == -1`.
417 // First, check x % y != 0.
418 if self.binary_op(BinOp::Rem, a, b)?.to_bits()? != 0 {
419 // Then, check if `b` is -1, which is the "min_value / -1" case.
420 let minus1 = Scalar::from_int(-1, dest.layout.size);
421 let b = b.to_scalar().unwrap();
423 throw_ub_format!("exact_div: result of dividing MIN by -1 cannot be represented")
426 "exact_div: {} cannot be divided by {} without remainder",
427 a.to_scalar().unwrap(),
432 self.binop_ignore_overflow(BinOp::Div, a, b, dest)