]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/intrinsics.rs
Add hooks for Miri panic unwinding
[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 syntax::symbol::Symbol;
6 use syntax_pos::Span;
7 use rustc::ty;
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};
14
15 use super::{
16     Machine, PlaceTy, OpTy, InterpCx, ImmTy,
17 };
18
19 mod caller_location;
20 mod type_name;
21
22 fn numeric_intrinsic<'tcx, Tag>(
23     name: &str,
24     bits: u128,
25     kind: Primitive,
26 ) -> InterpResult<'tcx, Scalar<Tag>> {
27     let size = match kind {
28         Primitive::Int(integer, _) => integer.size(),
29         _ => bug!("invalid `{}` argument: {:?}", name, bits),
30     };
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),
39     };
40     Ok(Scalar::from_uint(bits_out, size))
41 }
42
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>(
46     tcx: TyCtxt<'tcx>,
47     param_env: ty::ParamEnv<'tcx>,
48     def_id: DefId,
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();
53     Ok(match name {
54         "type_name" => {
55             let alloc = type_name::alloc_type_name(tcx, tp_ty);
56             tcx.mk_const(ty::Const {
57                 val: ConstValue::Slice {
58                     data: alloc,
59                     start: 0,
60                     end: alloc.len(),
61                 },
62                 ty: tcx.mk_static_str(),
63             })
64         },
65         "needs_drop" => ty::Const::from_bool(tcx, tp_ty.needs_drop(tcx, param_env)),
66         "size_of" |
67         "min_align_of" |
68         "pref_align_of" => {
69             let layout = tcx.layout_of(param_env.and(tp_ty)).map_err(|e| err_inval!(Layout(e)))?;
70             let n = match name {
71                 "pref_align_of" => layout.align.pref.bytes(),
72                 "min_align_of" => layout.align.abi.bytes(),
73                 "size_of" => layout.size.bytes(),
74                 _ => bug!(),
75             };
76             ty::Const::from_usize(tcx, n)
77         },
78         "type_id" => ty::Const::from_bits(
79             tcx,
80             tcx.type_id_hash(tp_ty).into(),
81             param_env.and(tcx.types.u64),
82         ),
83         other => bug!("`{}` is not a zero arg intrinsic", other),
84     })
85 }
86
87 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
88     /// Returns `true` if emulation happened.
89     pub fn emulate_intrinsic(
90         &mut self,
91         span: Span,
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;
97
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 {
101             Some(dest) => dest,
102             None => throw_ub!(Unreachable)
103         };
104         let intrinsic_name = &self.tcx.item_name(instance.def_id()).as_str();
105
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()),
112                     caller.line as u32,
113                     caller.col_display as u32 + 1,
114                 )?;
115                 self.write_scalar(location.ptr, dest)?;
116             }
117
118             "min_align_of" |
119             "pref_align_of" |
120             "needs_drop" |
121             "size_of" |
122             "type_id" |
123             "type_name" => {
124                 let gid = GlobalId {
125                     instance,
126                     promoted: None,
127                 };
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)?;
131             }
132
133             | "ctpop"
134             | "cttz"
135             | "cttz_nonzero"
136             | "ctlz"
137             | "ctlz_nonzero"
138             | "bswap"
139             | "bitreverse" => {
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)),
147                 };
148                 let out_val = if intrinsic_name.ends_with("_nonzero") {
149                     if bits == 0 {
150                         throw_ub_format!("`{}` called on 0", intrinsic_name);
151                     }
152                     numeric_intrinsic(intrinsic_name.trim_end_matches("_nonzero"), bits, kind)?
153                 } else {
154                     numeric_intrinsic(intrinsic_name, bits, kind)?
155                 };
156                 self.write_scalar(out_val, dest)?;
157             }
158             | "wrapping_add"
159             | "wrapping_sub"
160             | "wrapping_mul"
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")
174                 };
175                 if ignore_overflow {
176                     self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
177                 } else {
178                     self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
179                 }
180             }
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 {
186                     BinOp::Add
187                 } else {
188                     BinOp::Sub
189                 }, l, r)?;
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))
205                         } else {
206                             // Positive overflow not possible for similar reason
207                             // max negative
208                             Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
209                         }
210                     } else {  // unsigned
211                         if is_add {
212                             // max unsigned
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))
217                         }
218                     }
219                 } else {
220                     val
221                 };
222                 self.write_scalar(val, dest)?;
223             }
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")
231                 };
232                 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
233                 if overflowed {
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);
237                 }
238                 self.write_scalar(val, dest)?;
239             }
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)
253                 } else {
254                     (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
255                 };
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)?;
259             }
260
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()?;
265
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)?;
277                         return Ok(true);
278                     }
279                 }
280
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 {
285                     throw_ub_format!(
286                         "ptr_offset_from cannot compute offset of pointers into different \
287                         allocations.",
288                     );
289                 }
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,
295                 )?;
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)?;
300             }
301
302             "transmute" => {
303                 self.copy_op_transmute(args[0], dest)?;
304             }
305             "simd_insert" => {
306                 let index = self.read_scalar(args[1])?.to_u32()? as u64;
307                 let scalar = args[2];
308                 let input = args[0];
309                 let (len, e_ty) = self.read_vector_ty(input);
310                 assert!(
311                     index < len,
312                     "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
313                     index, e_ty, len
314                 );
315                 assert_eq!(
316                     input.layout, dest.layout,
317                     "Return type `{}` must match vector type `{}`",
318                     dest.layout.ty, input.layout.ty
319                 );
320                 assert_eq!(
321                     scalar.layout.ty, e_ty,
322                     "Scalar type `{}` must match vector element type `{}`",
323                     scalar.layout.ty, e_ty
324                 );
325
326                 for i in 0..len {
327                     let place = self.place_field(dest, i)?;
328                     let value = if i == index {
329                         scalar
330                     } else {
331                         self.operand_field(input, i)?
332                     };
333                     self.copy_op(value, place)?;
334                 }
335             }
336             "simd_extract" => {
337                 let index = self.read_scalar(args[1])?.to_u32()? as _;
338                 let (len, e_ty) = self.read_vector_ty(args[0]);
339                 assert!(
340                     index < len,
341                     "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
342                     index, e_ty, len
343                 );
344                 assert_eq!(
345                     e_ty, dest.layout.ty,
346                     "Return type `{}` must match vector element type `{}`",
347                     dest.layout.ty, e_ty
348                 );
349                 self.copy_op(self.operand_field(args[0], index)?, dest)?;
350             }
351             _ => return Ok(false),
352         }
353
354         Ok(true)
355     }
356
357     /// "Intercept" a function call because we have something special to do for it.
358     /// Returns `true` if an intercept happened.
359     pub fn hook_fn(
360         &mut self,
361         instance: ty::Instance<'tcx>,
362         args: &[OpTy<'tcx, M::PointerTag>],
363         _dest: Option<PlaceTy<'tcx, M::PointerTag>>,
364     ) -> InterpResult<'tcx, bool> {
365         let def_id = instance.def_id();
366         if Some(def_id) == self.tcx.lang_items().panic_fn() {
367             // &'static str, &core::panic::Location { &'static str, u32, u32 }
368             assert!(args.len() == 2);
369
370             let msg_place = self.deref_operand(args[0])?;
371             let msg = Symbol::intern(self.read_str(msg_place)?);
372
373             let location = self.deref_operand(args[1])?;
374             let (file, line, col) = (
375                 self.mplace_field(location, 0)?,
376                 self.mplace_field(location, 1)?,
377                 self.mplace_field(location, 2)?,
378             );
379
380             let file_place = self.deref_operand(file.into())?;
381             let file = Symbol::intern(self.read_str(file_place)?);
382             let line = self.read_scalar(line.into())?.to_u32()?;
383             let col = self.read_scalar(col.into())?.to_u32()?;
384             throw_panic!(Panic { msg, file, line, col })
385         } else if Some(def_id) == self.tcx.lang_items().begin_panic_fn() {
386             assert!(args.len() == 2);
387             // &'static str, &(&'static str, u32, u32)
388             let msg = args[0];
389             let place = self.deref_operand(args[1])?;
390             let (file, line, col) = (
391                 self.mplace_field(place, 0)?,
392                 self.mplace_field(place, 1)?,
393                 self.mplace_field(place, 2)?,
394             );
395
396             let msg_place = self.deref_operand(msg.into())?;
397             let msg = Symbol::intern(self.read_str(msg_place)?);
398             let file_place = self.deref_operand(file.into())?;
399             let file = Symbol::intern(self.read_str(file_place)?);
400             let line = self.read_scalar(line.into())?.to_u32()?;
401             let col = self.read_scalar(col.into())?.to_u32()?;
402             throw_panic!(Panic { msg, file, line, col })
403         } else {
404             return Ok(false);
405         }
406     }
407
408     pub fn exact_div(
409         &mut self,
410         a: ImmTy<'tcx, M::PointerTag>,
411         b: ImmTy<'tcx, M::PointerTag>,
412         dest: PlaceTy<'tcx, M::PointerTag>,
413     ) -> InterpResult<'tcx> {
414         // Performs an exact division, resulting in undefined behavior where
415         // `x % y != 0` or `y == 0` or `x == T::min_value() && y == -1`.
416         // First, check x % y != 0.
417         if self.binary_op(BinOp::Rem, a, b)?.to_bits()? != 0 {
418             // Then, check if `b` is -1, which is the "min_value / -1" case.
419             let minus1 = Scalar::from_int(-1, dest.layout.size);
420             let b = b.to_scalar().unwrap();
421             if b == minus1 {
422                 throw_ub_format!("exact_div: result of dividing MIN by -1 cannot be represented")
423             } else {
424                 throw_ub_format!(
425                     "exact_div: {} cannot be divided by {} without remainder",
426                     a.to_scalar().unwrap(),
427                     b,
428                 )
429             }
430         }
431         self.binop_ignore_overflow(BinOp::Div, a, b, dest)
432     }
433 }