]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/intrinsics.rs
Return Ok(false) instead of throwing when handling a diverging intrinsic
[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         // We currently do not handle any diverging intrinsics.
99         let dest = match dest {
100             Some(dest) => dest,
101             None => return Ok(false)
102         };
103         let intrinsic_name = &*self.tcx.item_name(instance.def_id()).as_str();
104
105         match intrinsic_name {
106             "caller_location" => {
107                 let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
108                 let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
109                 let location = self.alloc_caller_location(
110                     Symbol::intern(&caller.file.name.to_string()),
111                     caller.line as u32,
112                     caller.col_display as u32 + 1,
113                 )?;
114                 self.write_scalar(location.ptr, dest)?;
115             }
116
117             "min_align_of" |
118             "pref_align_of" |
119             "needs_drop" |
120             "size_of" |
121             "type_id" |
122             "type_name" => {
123                 let gid = GlobalId {
124                     instance,
125                     promoted: None,
126                 };
127                 let val = self.tcx.const_eval(self.param_env.and(gid))?;
128                 let val = self.eval_const_to_op(val, None)?;
129                 self.copy_op(val, dest)?;
130             }
131
132             | "ctpop"
133             | "cttz"
134             | "cttz_nonzero"
135             | "ctlz"
136             | "ctlz_nonzero"
137             | "bswap"
138             | "bitreverse" => {
139                 let ty = substs.type_at(0);
140                 let layout_of = self.layout_of(ty)?;
141                 let val = self.read_scalar(args[0])?.not_undef()?;
142                 let bits = self.force_bits(val, layout_of.size)?;
143                 let kind = match layout_of.abi {
144                     ty::layout::Abi::Scalar(ref scalar) => scalar.value,
145                     _ => throw_unsup!(TypeNotPrimitive(ty)),
146                 };
147                 let out_val = if intrinsic_name.ends_with("_nonzero") {
148                     if bits == 0 {
149                         throw_ub_format!("`{}` called on 0", intrinsic_name);
150                     }
151                     numeric_intrinsic(intrinsic_name.trim_end_matches("_nonzero"), bits, kind)?
152                 } else {
153                     numeric_intrinsic(intrinsic_name, bits, kind)?
154                 };
155                 self.write_scalar(out_val, dest)?;
156             }
157             | "wrapping_add"
158             | "wrapping_sub"
159             | "wrapping_mul"
160             | "add_with_overflow"
161             | "sub_with_overflow"
162             | "mul_with_overflow" => {
163                 let lhs = self.read_immediate(args[0])?;
164                 let rhs = self.read_immediate(args[1])?;
165                 let (bin_op, ignore_overflow) = match intrinsic_name {
166                     "wrapping_add" => (BinOp::Add, true),
167                     "wrapping_sub" => (BinOp::Sub, true),
168                     "wrapping_mul" => (BinOp::Mul, true),
169                     "add_with_overflow" => (BinOp::Add, false),
170                     "sub_with_overflow" => (BinOp::Sub, false),
171                     "mul_with_overflow" => (BinOp::Mul, false),
172                     _ => bug!("Already checked for int ops")
173                 };
174                 if ignore_overflow {
175                     self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
176                 } else {
177                     self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
178                 }
179             }
180             "saturating_add" | "saturating_sub" => {
181                 let l = self.read_immediate(args[0])?;
182                 let r = self.read_immediate(args[1])?;
183                 let is_add = intrinsic_name == "saturating_add";
184                 let (val, overflowed, _ty) = self.overflowing_binary_op(if is_add {
185                     BinOp::Add
186                 } else {
187                     BinOp::Sub
188                 }, l, r)?;
189                 let val = if overflowed {
190                     let num_bits = l.layout.size.bits();
191                     if l.layout.abi.is_signed() {
192                         // For signed ints the saturated value depends on the sign of the first
193                         // term since the sign of the second term can be inferred from this and
194                         // the fact that the operation has overflowed (if either is 0 no
195                         // overflow can occur)
196                         let first_term: u128 = self.force_bits(l.to_scalar()?, l.layout.size)?;
197                         let first_term_positive = first_term & (1 << (num_bits-1)) == 0;
198                         if first_term_positive {
199                             // Negative overflow not possible since the positive first term
200                             // can only increase an (in range) negative term for addition
201                             // or corresponding negated positive term for subtraction
202                             Scalar::from_uint((1u128 << (num_bits - 1)) - 1,  // max positive
203                                 Size::from_bits(num_bits))
204                         } else {
205                             // Positive overflow not possible for similar reason
206                             // max negative
207                             Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
208                         }
209                     } else {  // unsigned
210                         if is_add {
211                             // max unsigned
212                             Scalar::from_uint(u128::max_value() >> (128 - num_bits),
213                                 Size::from_bits(num_bits))
214                         } else {  // underflow to 0
215                             Scalar::from_uint(0u128, Size::from_bits(num_bits))
216                         }
217                     }
218                 } else {
219                     val
220                 };
221                 self.write_scalar(val, dest)?;
222             }
223             "unchecked_shl" | "unchecked_shr" => {
224                 let l = self.read_immediate(args[0])?;
225                 let r = self.read_immediate(args[1])?;
226                 let bin_op = match intrinsic_name {
227                     "unchecked_shl" => BinOp::Shl,
228                     "unchecked_shr" => BinOp::Shr,
229                     _ => bug!("Already checked for int ops")
230                 };
231                 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
232                 if overflowed {
233                     let layout = self.layout_of(substs.type_at(0))?;
234                     let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
235                     throw_ub_format!("Overflowing shift by {} in `{}`", r_val, intrinsic_name);
236                 }
237                 self.write_scalar(val, dest)?;
238             }
239             "rotate_left" | "rotate_right" => {
240                 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
241                 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
242                 let layout = self.layout_of(substs.type_at(0))?;
243                 let val = self.read_scalar(args[0])?.not_undef()?;
244                 let val_bits = self.force_bits(val, layout.size)?;
245                 let raw_shift = self.read_scalar(args[1])?.not_undef()?;
246                 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
247                 let width_bits = layout.size.bits() as u128;
248                 let shift_bits = raw_shift_bits % width_bits;
249                 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
250                 let result_bits = if intrinsic_name == "rotate_left" {
251                     (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
252                 } else {
253                     (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
254                 };
255                 let truncated_bits = self.truncate(result_bits, layout);
256                 let result = Scalar::from_uint(truncated_bits, layout.size);
257                 self.write_scalar(result, dest)?;
258             }
259
260             "ptr_offset_from" => {
261                 let isize_layout = self.layout_of(self.tcx.types.isize)?;
262                 let a = self.read_immediate(args[0])?.to_scalar()?;
263                 let b = self.read_immediate(args[1])?.to_scalar()?;
264
265                 // Special case: if both scalars are *equal integers*
266                 // and not NULL, we pretend there is an allocation of size 0 right there,
267                 // and their offset is 0. (There's never a valid object at NULL, making it an
268                 // exception from the exception.)
269                 // This is the dual to the special exception for offset-by-0
270                 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
271                 if a.is_bits() && b.is_bits() {
272                     let a = a.to_machine_usize(self)?;
273                     let b = b.to_machine_usize(self)?;
274                     if a == b && a != 0 {
275                         self.write_scalar(Scalar::from_int(0, isize_layout.size), dest)?;
276                         return Ok(true);
277                     }
278                 }
279
280                 // General case: we need two pointers.
281                 let a = self.force_ptr(a)?;
282                 let b = self.force_ptr(b)?;
283                 if a.alloc_id != b.alloc_id {
284                     throw_ub_format!(
285                         "ptr_offset_from cannot compute offset of pointers into different \
286                         allocations.",
287                     );
288                 }
289                 let usize_layout = self.layout_of(self.tcx.types.usize)?;
290                 let a_offset = ImmTy::from_uint(a.offset.bytes(), usize_layout);
291                 let b_offset = ImmTy::from_uint(b.offset.bytes(), usize_layout);
292                 let (val, _overflowed, _ty) = self.overflowing_binary_op(
293                     BinOp::Sub, a_offset, b_offset,
294                 )?;
295                 let pointee_layout = self.layout_of(substs.type_at(0))?;
296                 let val = ImmTy::from_scalar(val, isize_layout);
297                 let size = ImmTy::from_int(pointee_layout.size.bytes(), isize_layout);
298                 self.exact_div(val, size, dest)?;
299             }
300
301             "transmute" => {
302                 self.copy_op_transmute(args[0], dest)?;
303             }
304             "simd_insert" => {
305                 let index = self.read_scalar(args[1])?.to_u32()? as u64;
306                 let scalar = args[2];
307                 let input = args[0];
308                 let (len, e_ty) = self.read_vector_ty(input);
309                 assert!(
310                     index < len,
311                     "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
312                     index, e_ty, len
313                 );
314                 assert_eq!(
315                     input.layout, dest.layout,
316                     "Return type `{}` must match vector type `{}`",
317                     dest.layout.ty, input.layout.ty
318                 );
319                 assert_eq!(
320                     scalar.layout.ty, e_ty,
321                     "Scalar type `{}` must match vector element type `{}`",
322                     scalar.layout.ty, e_ty
323                 );
324
325                 for i in 0..len {
326                     let place = self.place_field(dest, i)?;
327                     let value = if i == index {
328                         scalar
329                     } else {
330                         self.operand_field(input, i)?
331                     };
332                     self.copy_op(value, place)?;
333                 }
334             }
335             "simd_extract" => {
336                 let index = self.read_scalar(args[1])?.to_u32()? as _;
337                 let (len, e_ty) = self.read_vector_ty(args[0]);
338                 assert!(
339                     index < len,
340                     "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
341                     index, e_ty, len
342                 );
343                 assert_eq!(
344                     e_ty, dest.layout.ty,
345                     "Return type `{}` must match vector element type `{}`",
346                     dest.layout.ty, e_ty
347                 );
348                 self.copy_op(self.operand_field(args[0], index)?, dest)?;
349             }
350             _ => return Ok(false),
351         }
352
353         Ok(true)
354     }
355
356     /// "Intercept" a function call to a panic-related function
357     /// because we have something special to do for it.
358     /// Returns `true` if an intercept happened.
359     pub fn hook_panic_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 }