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_pos::symbol::{sym, 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;
14 interpret::{InterpResult, Scalar, GlobalId, ConstValue}
18 Machine, PlaceTy, OpTy, InterpCx, ImmTy,
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 - size.bits() as u128;
34 let bits_out = match name {
35 sym::ctpop => bits.count_ones() as u128,
36 sym::ctlz => bits.leading_zeros() as u128 - extra,
37 sym::cttz => (bits << extra).trailing_zeros() as u128 - 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, &'tcx ty::Const<'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 tcx.mk_const(ty::Const {
59 val: ty::ConstKind::Value(ConstValue::Slice {
64 ty: tcx.mk_static_str(),
67 sym::needs_drop => ty::Const::from_bool(tcx, tp_ty.needs_drop(tcx, param_env)),
70 sym::pref_align_of => {
71 let layout = tcx.layout_of(param_env.and(tp_ty)).map_err(|e| err_inval!(Layout(e)))?;
73 sym::pref_align_of => layout.align.pref.bytes(),
74 sym::min_align_of => layout.align.abi.bytes(),
75 sym::size_of => layout.size.bytes(),
78 ty::Const::from_usize(tcx, n)
80 sym::type_id => ty::Const::from_bits(
82 tcx.type_id_hash(tp_ty).into(),
83 param_env.and(tcx.types.u64),
85 other => bug!("`{}` is not a zero arg intrinsic", other),
89 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
90 /// Returns `true` if emulation happened.
91 pub fn emulate_intrinsic(
94 instance: ty::Instance<'tcx>,
95 args: &[OpTy<'tcx, M::PointerTag>],
96 ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
97 ) -> InterpResult<'tcx, bool> {
98 let substs = instance.substs;
99 let intrinsic_name = self.tcx.item_name(instance.def_id());
101 // We currently do not handle any intrinsics that are *allowed* to diverge,
102 // but `transmute` could lack a return place in case of UB.
103 let (dest, ret) = match ret {
105 None => match intrinsic_name {
106 sym::transmute => throw_ub!(Unreachable),
107 _ => return Ok(false),
111 // Keep the patterns in this match ordered the same as the list in
112 // `src/librustc/ty/constness.rs`
113 match intrinsic_name {
114 sym::caller_location => {
115 let span = self.find_closest_untracked_caller_location().unwrap_or(span);
116 let location = self.alloc_caller_location_for_span(span);
117 self.write_scalar(location.ptr, dest)?;
130 let val = self.tcx.const_eval(self.param_env.and(gid))?;
131 let val = self.eval_const_to_op(val, None)?;
132 self.copy_op(val, dest)?;
141 | sym::bitreverse => {
142 let ty = substs.type_at(0);
143 let layout_of = self.layout_of(ty)?;
144 let val = self.read_scalar(args[0])?.not_undef()?;
145 let bits = self.force_bits(val, layout_of.size)?;
146 let kind = match layout_of.abi {
147 ty::layout::Abi::Scalar(ref scalar) => scalar.value,
148 _ => throw_unsup!(TypeNotPrimitive(ty)),
150 let (nonzero, intrinsic_name) = match intrinsic_name {
151 sym::cttz_nonzero => (true, sym::cttz),
152 sym::ctlz_nonzero => (true, sym::ctlz),
153 other => (false, other),
155 if nonzero && bits == 0 {
156 throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
158 let out_val = numeric_intrinsic(intrinsic_name, bits, kind)?;
159 self.write_scalar(out_val, dest)?;
164 | sym::add_with_overflow
165 | sym::sub_with_overflow
166 | sym::mul_with_overflow => {
167 let lhs = self.read_immediate(args[0])?;
168 let rhs = self.read_immediate(args[1])?;
169 let (bin_op, ignore_overflow) = match intrinsic_name {
170 sym::wrapping_add => (BinOp::Add, true),
171 sym::wrapping_sub => (BinOp::Sub, true),
172 sym::wrapping_mul => (BinOp::Mul, true),
173 sym::add_with_overflow => (BinOp::Add, false),
174 sym::sub_with_overflow => (BinOp::Sub, false),
175 sym::mul_with_overflow => (BinOp::Mul, false),
176 _ => bug!("Already checked for int ops")
179 self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
181 self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
184 sym::saturating_add | sym::saturating_sub => {
185 let l = self.read_immediate(args[0])?;
186 let r = self.read_immediate(args[1])?;
187 let is_add = intrinsic_name == sym::saturating_add;
188 let (val, overflowed, _ty) = self.overflowing_binary_op(if is_add {
193 let val = if overflowed {
194 let num_bits = l.layout.size.bits();
195 if l.layout.abi.is_signed() {
196 // For signed ints the saturated value depends on the sign of the first
197 // term since the sign of the second term can be inferred from this and
198 // the fact that the operation has overflowed (if either is 0 no
199 // overflow can occur)
200 let first_term: u128 = self.force_bits(l.to_scalar()?, l.layout.size)?;
201 let first_term_positive = first_term & (1 << (num_bits-1)) == 0;
202 if first_term_positive {
203 // Negative overflow not possible since the positive first term
204 // can only increase an (in range) negative term for addition
205 // or corresponding negated positive term for subtraction
206 Scalar::from_uint((1u128 << (num_bits - 1)) - 1, // max positive
207 Size::from_bits(num_bits))
209 // Positive overflow not possible for similar reason
211 Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
216 Scalar::from_uint(u128::max_value() >> (128 - num_bits),
217 Size::from_bits(num_bits))
218 } else { // underflow to 0
219 Scalar::from_uint(0u128, Size::from_bits(num_bits))
225 self.write_scalar(val, dest)?;
227 sym::unchecked_shl | sym::unchecked_shr => {
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 _ => bug!("Already checked for int ops")
235 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
237 let layout = self.layout_of(substs.type_at(0))?;
238 let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
239 throw_ub_format!("Overflowing shift by {} in `{}`", r_val, intrinsic_name);
241 self.write_scalar(val, dest)?;
243 sym::rotate_left | sym::rotate_right => {
244 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
245 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
246 let layout = self.layout_of(substs.type_at(0))?;
247 let val = self.read_scalar(args[0])?.not_undef()?;
248 let val_bits = self.force_bits(val, layout.size)?;
249 let raw_shift = self.read_scalar(args[1])?.not_undef()?;
250 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
251 let width_bits = layout.size.bits() as u128;
252 let shift_bits = raw_shift_bits % width_bits;
253 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
254 let result_bits = if intrinsic_name == sym::rotate_left {
255 (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
257 (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
259 let truncated_bits = self.truncate(result_bits, layout);
260 let result = Scalar::from_uint(truncated_bits, layout.size);
261 self.write_scalar(result, dest)?;
264 sym::ptr_offset_from => {
265 let isize_layout = self.layout_of(self.tcx.types.isize)?;
266 let a = self.read_immediate(args[0])?.to_scalar()?;
267 let b = self.read_immediate(args[1])?.to_scalar()?;
269 // Special case: if both scalars are *equal integers*
270 // and not NULL, we pretend there is an allocation of size 0 right there,
271 // and their offset is 0. (There's never a valid object at NULL, making it an
272 // exception from the exception.)
273 // This is the dual to the special exception for offset-by-0
274 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
276 // Control flow is weird because we cannot early-return (to reach the
277 // `go_to_block` at the end).
278 let done = if a.is_bits() && b.is_bits() {
279 let a = a.to_machine_usize(self)?;
280 let b = b.to_machine_usize(self)?;
281 if a == b && a != 0 {
282 self.write_scalar(Scalar::from_int(0, isize_layout.size), dest)?;
288 // General case: we need two pointers.
289 let a = self.force_ptr(a)?;
290 let b = self.force_ptr(b)?;
291 if a.alloc_id != b.alloc_id {
293 "ptr_offset_from cannot compute offset of pointers into different \
297 let usize_layout = self.layout_of(self.tcx.types.usize)?;
298 let a_offset = ImmTy::from_uint(a.offset.bytes(), usize_layout);
299 let b_offset = ImmTy::from_uint(b.offset.bytes(), usize_layout);
300 let (val, _overflowed, _ty) = self.overflowing_binary_op(
301 BinOp::Sub, a_offset, b_offset,
303 let pointee_layout = self.layout_of(substs.type_at(0))?;
304 let val = ImmTy::from_scalar(val, isize_layout);
305 let size = ImmTy::from_int(pointee_layout.size.bytes(), isize_layout);
306 self.exact_div(val, size, dest)?;
311 self.copy_op_transmute(args[0], dest)?;
313 sym::simd_insert => {
314 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
317 let (len, e_ty) = input.layout.ty.simd_size_and_type(self.tcx.tcx);
320 "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
324 input.layout, dest.layout,
325 "Return type `{}` must match vector type `{}`",
326 dest.layout.ty, input.layout.ty
329 elem.layout.ty, e_ty,
330 "Scalar element type `{}` must match vector element type `{}`",
335 let place = self.place_field(dest, i)?;
336 let value = if i == index {
339 self.operand_field(input, i)?
341 self.copy_op(value, place)?;
344 sym::simd_extract => {
345 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
346 let (len, e_ty) = args[0].layout.ty.simd_size_and_type(self.tcx.tcx);
349 "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
353 e_ty, dest.layout.ty,
354 "Return type `{}` must match vector element type `{}`",
357 self.copy_op(self.operand_field(args[0], index)?, dest)?;
359 _ => return Ok(false),
362 self.dump_place(*dest);
363 self.go_to_block(ret);
367 /// "Intercept" a function call to a panic-related function
368 /// because we have something special to do for it.
369 /// Returns `true` if an intercept happened.
370 pub fn hook_panic_fn(
372 instance: ty::Instance<'tcx>,
373 args: &[OpTy<'tcx, M::PointerTag>],
374 _ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
375 ) -> InterpResult<'tcx, bool> {
376 let def_id = instance.def_id();
377 if Some(def_id) == self.tcx.lang_items().panic_fn() {
378 // &'static str, &core::panic::Location { &'static str, u32, u32 }
379 assert!(args.len() == 2);
381 let msg_place = self.deref_operand(args[0])?;
382 let msg = Symbol::intern(self.read_str(msg_place)?);
384 let location = self.deref_operand(args[1])?;
385 let (file, line, col) = (
386 self.mplace_field(location, 0)?,
387 self.mplace_field(location, 1)?,
388 self.mplace_field(location, 2)?,
391 let file_place = self.deref_operand(file.into())?;
392 let file = Symbol::intern(self.read_str(file_place)?);
393 let line = self.read_scalar(line.into())?.to_u32()?;
394 let col = self.read_scalar(col.into())?.to_u32()?;
395 throw_panic!(Panic { msg, file, line, col })
396 } else if Some(def_id) == self.tcx.lang_items().begin_panic_fn() {
397 assert!(args.len() == 2);
398 // &'static str, &(&'static str, u32, u32)
400 let place = self.deref_operand(args[1])?;
401 let (file, line, col) = (
402 self.mplace_field(place, 0)?,
403 self.mplace_field(place, 1)?,
404 self.mplace_field(place, 2)?,
407 let msg_place = self.deref_operand(msg.into())?;
408 let msg = Symbol::intern(self.read_str(msg_place)?);
409 let file_place = self.deref_operand(file.into())?;
410 let file = Symbol::intern(self.read_str(file_place)?);
411 let line = self.read_scalar(line.into())?.to_u32()?;
412 let col = self.read_scalar(col.into())?.to_u32()?;
413 throw_panic!(Panic { msg, file, line, col })
421 a: ImmTy<'tcx, M::PointerTag>,
422 b: ImmTy<'tcx, M::PointerTag>,
423 dest: PlaceTy<'tcx, M::PointerTag>,
424 ) -> InterpResult<'tcx> {
425 // Performs an exact division, resulting in undefined behavior where
426 // `x % y != 0` or `y == 0` or `x == T::min_value() && y == -1`.
427 // First, check x % y != 0.
428 if self.binary_op(BinOp::Rem, a, b)?.to_bits()? != 0 {
429 // Then, check if `b` is -1, which is the "min_value / -1" case.
430 let minus1 = Scalar::from_int(-1, dest.layout.size);
431 let b_scalar = b.to_scalar().unwrap();
432 if b_scalar == minus1 {
433 throw_ub_format!("exact_div: result of dividing MIN by -1 cannot be represented")
436 "exact_div: {} cannot be divided by {} without remainder",
442 self.binop_ignore_overflow(BinOp::Div, a, b, dest)