]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/intrinsics.rs
Add a `const_eval` helper to `InterpCx`
[rust.git] / src / librustc_mir / interpret / intrinsics.rs
1 //! Intrinsics and other functions that the miri engine executes without
2 //! looking at their MIR. Intrinsics/functions supported here are shared by CTFE
3 //! and miri.
4
5 use rustc::hir::def_id::DefId;
6 use rustc::mir::{
7     self,
8     interpret::{ConstValue, InterpResult, Scalar},
9     BinOp,
10 };
11 use rustc::ty;
12 use rustc::ty::layout::{LayoutOf, Primitive, Size};
13 use rustc::ty::subst::SubstsRef;
14 use rustc::ty::TyCtxt;
15 use syntax_pos::symbol::{sym, Symbol};
16 use syntax_pos::Span;
17
18 use super::{ImmTy, InterpCx, Machine, OpTy, PlaceTy};
19
20 mod caller_location;
21 mod type_name;
22
23 fn numeric_intrinsic<'tcx, Tag>(
24     name: Symbol,
25     bits: u128,
26     kind: Primitive,
27 ) -> InterpResult<'tcx, Scalar<Tag>> {
28     let size = match kind {
29         Primitive::Int(integer, _) => integer.size(),
30         _ => bug!("invalid `{}` argument: {:?}", name, bits),
31     };
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),
40     };
41     Ok(Scalar::from_uint(bits_out, size))
42 }
43
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>(
47     tcx: TyCtxt<'tcx>,
48     param_env: ty::ParamEnv<'tcx>,
49     def_id: DefId,
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);
54     Ok(match name {
55         sym::type_name => {
56             let alloc = type_name::alloc_type_name(tcx, tp_ty);
57             tcx.mk_const(ty::Const {
58                 val: ty::ConstKind::Value(ConstValue::Slice {
59                     data: alloc,
60                     start: 0,
61                     end: alloc.len(),
62                 }),
63                 ty: tcx.mk_static_str(),
64             })
65         }
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)))?;
69             let n = match name {
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(),
73                 _ => bug!(),
74             };
75             ty::Const::from_usize(tcx, n)
76         }
77         sym::type_id => {
78             ty::Const::from_bits(tcx, tcx.type_id_hash(tp_ty).into(), param_env.and(tcx.types.u64))
79         }
80         other => bug!("`{}` is not a zero arg intrinsic", other),
81     })
82 }
83
84 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
85     /// Returns `true` if emulation happened.
86     pub fn emulate_intrinsic(
87         &mut self,
88         span: Span,
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());
95
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 {
99             Some(p) => p,
100             None => match intrinsic_name {
101                 sym::transmute => throw_ub!(Unreachable),
102                 _ => return Ok(false),
103             },
104         };
105
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)?;
113             }
114
115             sym::min_align_of
116             | sym::pref_align_of
117             | sym::needs_drop
118             | sym::size_of
119             | sym::type_id
120             | sym::type_name => {
121                 let gid = GlobalId { instance, promoted: None };
122                 let val = self.const_eval(gid)?;
123                 self.copy_op(val, dest)?;
124             }
125
126             sym::ctpop
127             | sym::cttz
128             | sym::cttz_nonzero
129             | sym::ctlz
130             | sym::ctlz_nonzero
131             | sym::bswap
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)),
140                 };
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),
145                 };
146                 if nonzero && bits == 0 {
147                     throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
148                 }
149                 let out_val = numeric_intrinsic(intrinsic_name, bits, kind)?;
150                 self.write_scalar(out_val, dest)?;
151             }
152             sym::wrapping_add
153             | sym::wrapping_sub
154             | sym::wrapping_mul
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"),
168                 };
169                 if ignore_overflow {
170                     self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
171                 } else {
172                     self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
173                 }
174             }
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
194                             Scalar::from_uint(
195                                 (1u128 << (num_bits - 1)) - 1, // max positive
196                                 Size::from_bits(num_bits),
197                             )
198                         } else {
199                             // Positive overflow not possible for similar reason
200                             // max negative
201                             Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
202                         }
203                     } else {
204                         // unsigned
205                         if is_add {
206                             // max unsigned
207                             Scalar::from_uint(
208                                 u128::max_value() >> (128 - num_bits),
209                                 Size::from_bits(num_bits),
210                             )
211                         } else {
212                             // underflow to 0
213                             Scalar::from_uint(0u128, Size::from_bits(num_bits))
214                         }
215                     }
216                 } else {
217                     val
218                 };
219                 self.write_scalar(val, dest)?;
220             }
221             sym::unchecked_shl | sym::unchecked_shr => {
222                 let l = self.read_immediate(args[0])?;
223                 let r = self.read_immediate(args[1])?;
224                 let bin_op = match intrinsic_name {
225                     sym::unchecked_shl => BinOp::Shl,
226                     sym::unchecked_shr => BinOp::Shr,
227                     _ => bug!("Already checked for int ops"),
228                 };
229                 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
230                 if overflowed {
231                     let layout = self.layout_of(substs.type_at(0))?;
232                     let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
233                     throw_ub_format!("Overflowing shift by {} in `{}`", r_val, intrinsic_name);
234                 }
235                 self.write_scalar(val, dest)?;
236             }
237             sym::rotate_left | sym::rotate_right => {
238                 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
239                 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
240                 let layout = self.layout_of(substs.type_at(0))?;
241                 let val = self.read_scalar(args[0])?.not_undef()?;
242                 let val_bits = self.force_bits(val, layout.size)?;
243                 let raw_shift = self.read_scalar(args[1])?.not_undef()?;
244                 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
245                 let width_bits = layout.size.bits() as u128;
246                 let shift_bits = raw_shift_bits % width_bits;
247                 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
248                 let result_bits = if intrinsic_name == sym::rotate_left {
249                     (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
250                 } else {
251                     (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
252                 };
253                 let truncated_bits = self.truncate(result_bits, layout);
254                 let result = Scalar::from_uint(truncated_bits, layout.size);
255                 self.write_scalar(result, dest)?;
256             }
257
258             sym::ptr_offset_from => {
259                 let isize_layout = self.layout_of(self.tcx.types.isize)?;
260                 let a = self.read_immediate(args[0])?.to_scalar()?;
261                 let b = self.read_immediate(args[1])?.to_scalar()?;
262
263                 // Special case: if both scalars are *equal integers*
264                 // and not NULL, we pretend there is an allocation of size 0 right there,
265                 // and their offset is 0. (There's never a valid object at NULL, making it an
266                 // exception from the exception.)
267                 // This is the dual to the special exception for offset-by-0
268                 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
269                 //
270                 // Control flow is weird because we cannot early-return (to reach the
271                 // `go_to_block` at the end).
272                 let done = 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)?;
277                         true
278                     } else {
279                         false
280                     }
281                 } else {
282                     false
283                 };
284
285                 if !done {
286                     // General case: we need two pointers.
287                     let a = self.force_ptr(a)?;
288                     let b = self.force_ptr(b)?;
289                     if a.alloc_id != b.alloc_id {
290                         throw_ub_format!(
291                             "ptr_offset_from cannot compute offset of pointers into different \
292                             allocations.",
293                         );
294                     }
295                     let usize_layout = self.layout_of(self.tcx.types.usize)?;
296                     let a_offset = ImmTy::from_uint(a.offset.bytes(), usize_layout);
297                     let b_offset = ImmTy::from_uint(b.offset.bytes(), usize_layout);
298                     let (val, _overflowed, _ty) =
299                         self.overflowing_binary_op(BinOp::Sub, a_offset, b_offset)?;
300                     let pointee_layout = self.layout_of(substs.type_at(0))?;
301                     let val = ImmTy::from_scalar(val, isize_layout);
302                     let size = ImmTy::from_int(pointee_layout.size.bytes(), isize_layout);
303                     self.exact_div(val, size, dest)?;
304                 }
305             }
306
307             sym::transmute => {
308                 self.copy_op_transmute(args[0], dest)?;
309             }
310             sym::simd_insert => {
311                 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
312                 let elem = args[2];
313                 let input = args[0];
314                 let (len, e_ty) = input.layout.ty.simd_size_and_type(self.tcx.tcx);
315                 assert!(
316                     index < len,
317                     "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
318                     index,
319                     e_ty,
320                     len
321                 );
322                 assert_eq!(
323                     input.layout, dest.layout,
324                     "Return type `{}` must match vector type `{}`",
325                     dest.layout.ty, input.layout.ty
326                 );
327                 assert_eq!(
328                     elem.layout.ty, e_ty,
329                     "Scalar element type `{}` must match vector element type `{}`",
330                     elem.layout.ty, e_ty
331                 );
332
333                 for i in 0..len {
334                     let place = self.place_field(dest, i)?;
335                     let value = if i == index { elem } else { self.operand_field(input, i)? };
336                     self.copy_op(value, place)?;
337                 }
338             }
339             sym::simd_extract => {
340                 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
341                 let (len, e_ty) = args[0].layout.ty.simd_size_and_type(self.tcx.tcx);
342                 assert!(
343                     index < len,
344                     "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
345                     index,
346                     e_ty,
347                     len
348                 );
349                 assert_eq!(
350                     e_ty, dest.layout.ty,
351                     "Return type `{}` must match vector element type `{}`",
352                     dest.layout.ty, e_ty
353                 );
354                 self.copy_op(self.operand_field(args[0], index)?, dest)?;
355             }
356             _ => return Ok(false),
357         }
358
359         self.dump_place(*dest);
360         self.go_to_block(ret);
361         Ok(true)
362     }
363
364     /// "Intercept" a function call to a panic-related function
365     /// because we have something special to do for it.
366     /// Returns `true` if an intercept happened.
367     pub fn hook_panic_fn(
368         &mut self,
369         instance: ty::Instance<'tcx>,
370         args: &[OpTy<'tcx, M::PointerTag>],
371         _ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
372     ) -> InterpResult<'tcx, bool> {
373         let def_id = instance.def_id();
374         if Some(def_id) == self.tcx.lang_items().panic_fn() {
375             // &'static str, &core::panic::Location { &'static str, u32, u32 }
376             assert!(args.len() == 2);
377
378             let msg_place = self.deref_operand(args[0])?;
379             let msg = Symbol::intern(self.read_str(msg_place)?);
380
381             let location = self.deref_operand(args[1])?;
382             let (file, line, col) = (
383                 self.mplace_field(location, 0)?,
384                 self.mplace_field(location, 1)?,
385                 self.mplace_field(location, 2)?,
386             );
387
388             let file_place = self.deref_operand(file.into())?;
389             let file = Symbol::intern(self.read_str(file_place)?);
390             let line = self.read_scalar(line.into())?.to_u32()?;
391             let col = self.read_scalar(col.into())?.to_u32()?;
392             throw_panic!(Panic { msg, file, line, col })
393         } else if Some(def_id) == self.tcx.lang_items().begin_panic_fn() {
394             assert!(args.len() == 2);
395             // &'static str, &(&'static str, u32, u32)
396             let msg = args[0];
397             let place = self.deref_operand(args[1])?;
398             let (file, line, col) = (
399                 self.mplace_field(place, 0)?,
400                 self.mplace_field(place, 1)?,
401                 self.mplace_field(place, 2)?,
402             );
403
404             let msg_place = self.deref_operand(msg.into())?;
405             let msg = Symbol::intern(self.read_str(msg_place)?);
406             let file_place = self.deref_operand(file.into())?;
407             let file = Symbol::intern(self.read_str(file_place)?);
408             let line = self.read_scalar(line.into())?.to_u32()?;
409             let col = self.read_scalar(col.into())?.to_u32()?;
410             throw_panic!(Panic { msg, file, line, col })
411         } else {
412             return Ok(false);
413         }
414     }
415
416     pub fn exact_div(
417         &mut self,
418         a: ImmTy<'tcx, M::PointerTag>,
419         b: ImmTy<'tcx, M::PointerTag>,
420         dest: PlaceTy<'tcx, M::PointerTag>,
421     ) -> InterpResult<'tcx> {
422         // Performs an exact division, resulting in undefined behavior where
423         // `x % y != 0` or `y == 0` or `x == T::min_value() && y == -1`.
424         // First, check x % y != 0.
425         if self.binary_op(BinOp::Rem, a, b)?.to_bits()? != 0 {
426             // Then, check if `b` is -1, which is the "min_value / -1" case.
427             let minus1 = Scalar::from_int(-1, dest.layout.size);
428             let b_scalar = b.to_scalar().unwrap();
429             if b_scalar == minus1 {
430                 throw_ub_format!("exact_div: result of dividing MIN by -1 cannot be represented")
431             } else {
432                 throw_ub_format!("exact_div: {} cannot be divided by {} without remainder", a, b,)
433             }
434         }
435         self.binop_ignore_overflow(BinOp::Div, a, b, dest)
436     }
437 }