]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/intrinsics.rs
Rollup merge of #69141 - mark-i-m:proper-linkcheck-2, r=Dylan-DPC
[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, &'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
222             | sym::unchecked_shr
223             | sym::unchecked_add
224             | sym::unchecked_sub
225             | sym::unchecked_mul
226             | sym::unchecked_div
227             | sym::unchecked_rem => {
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                     sym::unchecked_add => BinOp::Add,
234                     sym::unchecked_sub => BinOp::Sub,
235                     sym::unchecked_mul => BinOp::Mul,
236                     sym::unchecked_div => BinOp::Div,
237                     sym::unchecked_rem => BinOp::Rem,
238                     _ => bug!("Already checked for int ops"),
239                 };
240                 let (val, overflowed, _ty) = self.overflowing_binary_op(bin_op, l, r)?;
241                 if overflowed {
242                     let layout = self.layout_of(substs.type_at(0))?;
243                     let r_val = self.force_bits(r.to_scalar()?, layout.size)?;
244                     if let sym::unchecked_shl | sym::unchecked_shr = intrinsic_name {
245                         throw_ub_format!("Overflowing shift by {} in `{}`", r_val, intrinsic_name);
246                     } else {
247                         throw_ub_format!("Overflow executing `{}`", intrinsic_name);
248                     }
249                 }
250                 self.write_scalar(val, dest)?;
251             }
252             sym::rotate_left | sym::rotate_right => {
253                 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
254                 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
255                 let layout = self.layout_of(substs.type_at(0))?;
256                 let val = self.read_scalar(args[0])?.not_undef()?;
257                 let val_bits = self.force_bits(val, layout.size)?;
258                 let raw_shift = self.read_scalar(args[1])?.not_undef()?;
259                 let raw_shift_bits = self.force_bits(raw_shift, layout.size)?;
260                 let width_bits = layout.size.bits() as u128;
261                 let shift_bits = raw_shift_bits % width_bits;
262                 let inv_shift_bits = (width_bits - shift_bits) % width_bits;
263                 let result_bits = if intrinsic_name == sym::rotate_left {
264                     (val_bits << shift_bits) | (val_bits >> inv_shift_bits)
265                 } else {
266                     (val_bits >> shift_bits) | (val_bits << inv_shift_bits)
267                 };
268                 let truncated_bits = self.truncate(result_bits, layout);
269                 let result = Scalar::from_uint(truncated_bits, layout.size);
270                 self.write_scalar(result, dest)?;
271             }
272
273             sym::ptr_offset_from => {
274                 let isize_layout = self.layout_of(self.tcx.types.isize)?;
275                 let a = self.read_immediate(args[0])?.to_scalar()?;
276                 let b = self.read_immediate(args[1])?.to_scalar()?;
277
278                 // Special case: if both scalars are *equal integers*
279                 // and not NULL, we pretend there is an allocation of size 0 right there,
280                 // and their offset is 0. (There's never a valid object at NULL, making it an
281                 // exception from the exception.)
282                 // This is the dual to the special exception for offset-by-0
283                 // in the inbounds pointer offset operation (see the Miri code, `src/operator.rs`).
284                 //
285                 // Control flow is weird because we cannot early-return (to reach the
286                 // `go_to_block` at the end).
287                 let done = if a.is_bits() && b.is_bits() {
288                     let a = a.to_machine_usize(self)?;
289                     let b = b.to_machine_usize(self)?;
290                     if a == b && a != 0 {
291                         self.write_scalar(Scalar::from_int(0, isize_layout.size), dest)?;
292                         true
293                     } else {
294                         false
295                     }
296                 } else {
297                     false
298                 };
299
300                 if !done {
301                     // General case: we need two pointers.
302                     let a = self.force_ptr(a)?;
303                     let b = self.force_ptr(b)?;
304                     if a.alloc_id != b.alloc_id {
305                         throw_ub_format!(
306                             "ptr_offset_from cannot compute offset of pointers into different \
307                             allocations.",
308                         );
309                     }
310                     let usize_layout = self.layout_of(self.tcx.types.usize)?;
311                     let a_offset = ImmTy::from_uint(a.offset.bytes(), usize_layout);
312                     let b_offset = ImmTy::from_uint(b.offset.bytes(), usize_layout);
313                     let (val, _overflowed, _ty) =
314                         self.overflowing_binary_op(BinOp::Sub, a_offset, b_offset)?;
315                     let pointee_layout = self.layout_of(substs.type_at(0))?;
316                     let val = ImmTy::from_scalar(val, isize_layout);
317                     let size = ImmTy::from_int(pointee_layout.size.bytes(), isize_layout);
318                     self.exact_div(val, size, dest)?;
319                 }
320             }
321
322             sym::transmute => {
323                 self.copy_op_transmute(args[0], dest)?;
324             }
325             sym::simd_insert => {
326                 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
327                 let elem = args[2];
328                 let input = args[0];
329                 let (len, e_ty) = input.layout.ty.simd_size_and_type(self.tcx.tcx);
330                 assert!(
331                     index < len,
332                     "Index `{}` must be in bounds of vector type `{}`: `[0, {})`",
333                     index,
334                     e_ty,
335                     len
336                 );
337                 assert_eq!(
338                     input.layout, dest.layout,
339                     "Return type `{}` must match vector type `{}`",
340                     dest.layout.ty, input.layout.ty
341                 );
342                 assert_eq!(
343                     elem.layout.ty, e_ty,
344                     "Scalar element type `{}` must match vector element type `{}`",
345                     elem.layout.ty, e_ty
346                 );
347
348                 for i in 0..len {
349                     let place = self.place_field(dest, i)?;
350                     let value = if i == index { elem } else { self.operand_field(input, i)? };
351                     self.copy_op(value, place)?;
352                 }
353             }
354             sym::simd_extract => {
355                 let index = u64::from(self.read_scalar(args[1])?.to_u32()?);
356                 let (len, e_ty) = args[0].layout.ty.simd_size_and_type(self.tcx.tcx);
357                 assert!(
358                     index < len,
359                     "index `{}` is out-of-bounds of vector type `{}` with length `{}`",
360                     index,
361                     e_ty,
362                     len
363                 );
364                 assert_eq!(
365                     e_ty, dest.layout.ty,
366                     "Return type `{}` must match vector element type `{}`",
367                     dest.layout.ty, e_ty
368                 );
369                 self.copy_op(self.operand_field(args[0], index)?, dest)?;
370             }
371             _ => return Ok(false),
372         }
373
374         self.dump_place(*dest);
375         self.go_to_block(ret);
376         Ok(true)
377     }
378
379     pub fn exact_div(
380         &mut self,
381         a: ImmTy<'tcx, M::PointerTag>,
382         b: ImmTy<'tcx, M::PointerTag>,
383         dest: PlaceTy<'tcx, M::PointerTag>,
384     ) -> InterpResult<'tcx> {
385         // Performs an exact division, resulting in undefined behavior where
386         // `x % y != 0` or `y == 0` or `x == T::min_value() && y == -1`.
387         // First, check x % y != 0 (or if that computation overflows).
388         let (res, overflow, _ty) = self.overflowing_binary_op(BinOp::Rem, a, b)?;
389         if overflow || res.to_bits(a.layout.size)? != 0 {
390             // Then, check if `b` is -1, which is the "min_value / -1" case.
391             let minus1 = Scalar::from_int(-1, dest.layout.size);
392             let b_scalar = b.to_scalar().unwrap();
393             if b_scalar == minus1 {
394                 throw_ub_format!("exact_div: result of dividing MIN by -1 cannot be represented")
395             } else {
396                 throw_ub_format!("exact_div: {} cannot be divided by {} without remainder", a, b,)
397             }
398         }
399         // `Rem` says this is all right, so we can let `Div` do its job.
400         self.binop_ignore_overflow(BinOp::Div, a, b, dest)
401     }
402 }