]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/intrinsics.rs
Auto merge of #68952 - faern:stabilize-assoc-int-consts, r=dtolnay
[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::mir::{
6     self,
7     interpret::{ConstValue, GlobalId, InterpResult, Scalar},
8     BinOp,
9 };
10 use rustc::ty;
11 use rustc::ty::layout::{LayoutOf, Primitive, Size};
12 use rustc::ty::subst::SubstsRef;
13 use rustc::ty::TyCtxt;
14 use rustc_hir::def_id::DefId;
15 use rustc_span::symbol::{sym, Symbol};
16 use rustc_span::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, ConstValue<'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             ConstValue::Slice { data: alloc, start: 0, end: alloc.len() }
58         }
59         sym::needs_drop => ConstValue::from_bool(tp_ty.needs_drop(tcx, param_env)),
60         sym::size_of | sym::min_align_of | sym::pref_align_of => {
61             let layout = tcx.layout_of(param_env.and(tp_ty)).map_err(|e| err_inval!(Layout(e)))?;
62             let n = match name {
63                 sym::pref_align_of => layout.align.pref.bytes(),
64                 sym::min_align_of => layout.align.abi.bytes(),
65                 sym::size_of => layout.size.bytes(),
66                 _ => bug!(),
67             };
68             ConstValue::from_machine_usize(n, &tcx)
69         }
70         sym::type_id => ConstValue::from_u64(tcx.type_id_hash(tp_ty)),
71         other => bug!("`{}` is not a zero arg intrinsic", other),
72     })
73 }
74
75 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
76     /// Returns `true` if emulation happened.
77     pub fn emulate_intrinsic(
78         &mut self,
79         span: Span,
80         instance: ty::Instance<'tcx>,
81         args: &[OpTy<'tcx, M::PointerTag>],
82         ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
83     ) -> InterpResult<'tcx, bool> {
84         let substs = instance.substs;
85         let intrinsic_name = self.tcx.item_name(instance.def_id());
86
87         // We currently do not handle any intrinsics that are *allowed* to diverge,
88         // but `transmute` could lack a return place in case of UB.
89         let (dest, ret) = match ret {
90             Some(p) => p,
91             None => match intrinsic_name {
92                 sym::transmute => throw_ub!(Unreachable),
93                 _ => return Ok(false),
94             },
95         };
96
97         // Keep the patterns in this match ordered the same as the list in
98         // `src/librustc/ty/constness.rs`
99         match intrinsic_name {
100             sym::caller_location => {
101                 let span = self.find_closest_untracked_caller_location().unwrap_or(span);
102                 let location = self.alloc_caller_location_for_span(span);
103                 self.write_scalar(location.ptr, dest)?;
104             }
105
106             sym::min_align_of
107             | sym::pref_align_of
108             | sym::needs_drop
109             | sym::size_of
110             | sym::type_id
111             | sym::type_name => {
112                 let gid = GlobalId { instance, promoted: None };
113                 let ty = match intrinsic_name {
114                     sym::min_align_of | sym::pref_align_of | sym::size_of => self.tcx.types.usize,
115                     sym::needs_drop => self.tcx.types.bool,
116                     sym::type_id => self.tcx.types.u64,
117                     sym::type_name => self.tcx.mk_static_str(),
118                     _ => span_bug!(span, "Already checked for nullary intrinsics"),
119                 };
120                 let val = self.const_eval(gid, ty)?;
121                 self.copy_op(val, dest)?;
122             }
123
124             sym::ctpop
125             | sym::cttz
126             | sym::cttz_nonzero
127             | sym::ctlz
128             | sym::ctlz_nonzero
129             | sym::bswap
130             | sym::bitreverse => {
131                 let ty = substs.type_at(0);
132                 let layout_of = self.layout_of(ty)?;
133                 let val = self.read_scalar(args[0])?.not_undef()?;
134                 let bits = self.force_bits(val, layout_of.size)?;
135                 let kind = match layout_of.abi {
136                     ty::layout::Abi::Scalar(ref scalar) => scalar.value,
137                     _ => throw_unsup!(TypeNotPrimitive(ty)),
138                 };
139                 let (nonzero, intrinsic_name) = match intrinsic_name {
140                     sym::cttz_nonzero => (true, sym::cttz),
141                     sym::ctlz_nonzero => (true, sym::ctlz),
142                     other => (false, other),
143                 };
144                 if nonzero && bits == 0 {
145                     throw_ub_format!("`{}_nonzero` called on 0", intrinsic_name);
146                 }
147                 let out_val = numeric_intrinsic(intrinsic_name, bits, kind)?;
148                 self.write_scalar(out_val, dest)?;
149             }
150             sym::wrapping_add
151             | sym::wrapping_sub
152             | sym::wrapping_mul
153             | sym::add_with_overflow
154             | sym::sub_with_overflow
155             | sym::mul_with_overflow => {
156                 let lhs = self.read_immediate(args[0])?;
157                 let rhs = self.read_immediate(args[1])?;
158                 let (bin_op, ignore_overflow) = match intrinsic_name {
159                     sym::wrapping_add => (BinOp::Add, true),
160                     sym::wrapping_sub => (BinOp::Sub, true),
161                     sym::wrapping_mul => (BinOp::Mul, true),
162                     sym::add_with_overflow => (BinOp::Add, false),
163                     sym::sub_with_overflow => (BinOp::Sub, false),
164                     sym::mul_with_overflow => (BinOp::Mul, false),
165                     _ => bug!("Already checked for int ops"),
166                 };
167                 if ignore_overflow {
168                     self.binop_ignore_overflow(bin_op, lhs, rhs, dest)?;
169                 } else {
170                     self.binop_with_overflow(bin_op, lhs, rhs, dest)?;
171                 }
172             }
173             sym::saturating_add | sym::saturating_sub => {
174                 let l = self.read_immediate(args[0])?;
175                 let r = self.read_immediate(args[1])?;
176                 let is_add = intrinsic_name == sym::saturating_add;
177                 let (val, overflowed, _ty) =
178                     self.overflowing_binary_op(if is_add { BinOp::Add } else { BinOp::Sub }, l, r)?;
179                 let val = if overflowed {
180                     let num_bits = l.layout.size.bits();
181                     if l.layout.abi.is_signed() {
182                         // For signed ints the saturated value depends on the sign of the first
183                         // term since the sign of the second term can be inferred from this and
184                         // the fact that the operation has overflowed (if either is 0 no
185                         // overflow can occur)
186                         let first_term: u128 = self.force_bits(l.to_scalar()?, l.layout.size)?;
187                         let first_term_positive = first_term & (1 << (num_bits - 1)) == 0;
188                         if first_term_positive {
189                             // Negative overflow not possible since the positive first term
190                             // can only increase an (in range) negative term for addition
191                             // or corresponding negated positive term for subtraction
192                             Scalar::from_uint(
193                                 (1u128 << (num_bits - 1)) - 1, // max positive
194                                 Size::from_bits(num_bits),
195                             )
196                         } else {
197                             // Positive overflow not possible for similar reason
198                             // max negative
199                             Scalar::from_uint(1u128 << (num_bits - 1), Size::from_bits(num_bits))
200                         }
201                     } else {
202                         // unsigned
203                         if is_add {
204                             // max unsigned
205                             Scalar::from_uint(
206                                 u128::max_value() >> (128 - num_bits),
207                                 Size::from_bits(num_bits),
208                             )
209                         } else {
210                             // underflow to 0
211                             Scalar::from_uint(0u128, Size::from_bits(num_bits))
212                         }
213                     }
214                 } else {
215                     val
216                 };
217                 self.write_scalar(val, dest)?;
218             }
219             sym::unchecked_shl
220             | sym::unchecked_shr
221             | sym::unchecked_add
222             | sym::unchecked_sub
223             | sym::unchecked_mul
224             | sym::unchecked_div
225             | sym::unchecked_rem => {
226                 let l = self.read_immediate(args[0])?;
227                 let r = self.read_immediate(args[1])?;
228                 let bin_op = match intrinsic_name {
229                     sym::unchecked_shl => BinOp::Shl,
230                     sym::unchecked_shr => BinOp::Shr,
231                     sym::unchecked_add => BinOp::Add,
232                     sym::unchecked_sub => BinOp::Sub,
233                     sym::unchecked_mul => BinOp::Mul,
234                     sym::unchecked_div => BinOp::Div,
235                     sym::unchecked_rem => BinOp::Rem,
236                     _ => bug!("Already checked for int ops"),
237                 };
238                 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
239                 if overflowed {
240                     let layout = self.layout_of(substs.type_at(0))?;
241                     let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
242                     if let sym::unchecked_shl | sym::unchecked_shr = intrinsic_name {
243                         throw_ub_format!("Overflowing shift by {} in `{}`", r_val, intrinsic_name);
244                     } else {
245                         throw_ub_format!("Overflow executing `{}`", intrinsic_name);
246                     }
247                 }
248                 self.write_scalar(val, dest)?;
249             }
250             sym::rotate_left | sym::rotate_right => {
251                 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
252                 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
253                 let layout = self.layout_of(substs.type_at(0))?;
254                 let val = self.read_scalar(args[0])?.not_undef()?;
255                 let val_bits = self.force_bits(val, layout.size)?;
256                 let raw_shift = self.read_scalar(args[1])?.not_undef()?;
257                 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
258                 let width_bits = layout.size.bits() as u128;
259                 let shift_bits = raw_shift_bits % width_bits;
260                 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
261                 let result_bits = if intrinsic_name == sym::rotate_left {
262                     (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
263                 } else {
264                     (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
265                 };
266                 let truncated_bits = self.truncate(result_bits, layout);
267                 let result = Scalar::from_uint(truncated_bits, layout.size);
268                 self.write_scalar(result, dest)?;
269             }
270
271             sym::ptr_offset_from => {
272                 let isize_layout = self.layout_of(self.tcx.types.isize)?;
273                 let a = self.read_immediate(args[0])?.to_scalar()?;
274                 let b = self.read_immediate(args[1])?.to_scalar()?;
275
276                 // Special case: if both scalars are *equal integers*
277                 // and not NULL, we pretend there is an allocation of size 0 right there,
278                 // and their offset is 0. (There's never a valid object at NULL, making it an
279                 // exception from the exception.)
280                 // This is the dual to the special exception for offset-by-0
281                 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
282                 //
283                 // Control flow is weird because we cannot early-return (to reach the
284                 // `go_to_block` at the end).
285                 let done = if a.is_bits() && b.is_bits() {
286                     let a = a.to_machine_usize(self)?;
287                     let b = b.to_machine_usize(self)?;
288                     if a == b && a != 0 {
289                         self.write_scalar(Scalar::from_int(0, isize_layout.size), dest)?;
290                         true
291                     } else {
292                         false
293                     }
294                 } else {
295                     false
296                 };
297
298                 if !done {
299                     // General case: we need two pointers.
300                     let a = self.force_ptr(a)?;
301                     let b = self.force_ptr(b)?;
302                     if a.alloc_id != b.alloc_id {
303                         throw_ub_format!(
304                             "ptr_offset_from cannot compute offset of pointers into different \
305                             allocations.",
306                         );
307                     }
308                     let usize_layout = self.layout_of(self.tcx.types.usize)?;
309                     let a_offset = ImmTy::from_uint(a.offset.bytes(), usize_layout);
310                     let b_offset = ImmTy::from_uint(b.offset.bytes(), usize_layout);
311                     let (val, _overflowed, _ty) =
312                         self.overflowing_binary_op(BinOp::Sub, a_offset, b_offset)?;
313                     let pointee_layout = self.layout_of(substs.type_at(0))?;
314                     let val = ImmTy::from_scalar(val, isize_layout);
315                     let size = ImmTy::from_int(pointee_layout.size.bytes(), isize_layout);
316                     self.exact_div(val, size, dest)?;
317                 }
318             }
319
320             sym::transmute => {
321                 self.copy_op_transmute(args[0], dest)?;
322             }
323             sym::simd_insert => {
324                 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
325                 let elem = args[2];
326                 let input = args[0];
327                 let (len, e_ty) = input.layout.ty.simd_size_and_type(self.tcx.tcx);
328                 assert!(
329                     index < len,
330                     "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
331                     index,
332                     e_ty,
333                     len
334                 );
335                 assert_eq!(
336                     input.layout, dest.layout,
337                     "Return type `{}` must match vector type `{}`",
338                     dest.layout.ty, input.layout.ty
339                 );
340                 assert_eq!(
341                     elem.layout.ty, e_ty,
342                     "Scalar element type `{}` must match vector element type `{}`",
343                     elem.layout.ty, e_ty
344                 );
345
346                 for i in 0..len {
347                     let place = self.place_field(dest, i)?;
348                     let value = if i == index { elem } else { self.operand_field(input, i)? };
349                     self.copy_op(value, place)?;
350                 }
351             }
352             sym::simd_extract => {
353                 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
354                 let (len, e_ty) = args[0].layout.ty.simd_size_and_type(self.tcx.tcx);
355                 assert!(
356                     index < len,
357                     "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
358                     index,
359                     e_ty,
360                     len
361                 );
362                 assert_eq!(
363                     e_ty, dest.layout.ty,
364                     "Return type `{}` must match vector element type `{}`",
365                     dest.layout.ty, e_ty
366                 );
367                 self.copy_op(self.operand_field(args[0], index)?, dest)?;
368             }
369             _ => return Ok(false),
370         }
371
372         self.dump_place(*dest);
373         self.go_to_block(ret);
374         Ok(true)
375     }
376
377     pub fn exact_div(
378         &mut self,
379         a: ImmTy<'tcx, M::PointerTag>,
380         b: ImmTy<'tcx, M::PointerTag>,
381         dest: PlaceTy<'tcx, M::PointerTag>,
382     ) -> InterpResult<'tcx> {
383         // Performs an exact division, resulting in undefined behavior where
384         // `x % y != 0` or `y == 0` or `x == T::min_value() && y == -1`.
385         // First, check x % y != 0 (or if that computation overflows).
386         let (res, overflow, _ty) = self.overflowing_binary_op(BinOp::Rem, a, b)?;
387         if overflow || res.assert_bits(a.layout.size) != 0 {
388             // Then, check if `b` is -1, which is the "min_value / -1" case.
389             let minus1 = Scalar::from_int(-1, dest.layout.size);
390             let b_scalar = b.to_scalar().unwrap();
391             if b_scalar == minus1 {
392                 throw_ub_format!("exact_div: result of dividing MIN by -1 cannot be represented")
393             } else {
394                 throw_ub_format!("exact_div: {} cannot be divided by {} without remainder", a, b,)
395             }
396         }
397         // `Rem` says this is all right, so we can let `Div` do its job.
398         self.binop_ignore_overflow(BinOp::Div, a, b, dest)
399     }
400 }