]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/operator.rs
Merge commit 'e214ea82ad0a751563acf67e1cd9279cf302db3a' into clippyup
[rust.git] / src / librustc_mir / interpret / operator.rs
1 use std::convert::TryFrom;
2
3 use rustc_apfloat::Float;
4 use rustc_ast::ast::FloatTy;
5 use rustc_middle::mir;
6 use rustc_middle::mir::interpret::{InterpResult, Scalar};
7 use rustc_middle::ty::{self, layout::TyAndLayout, Ty};
8 use rustc_target::abi::LayoutOf;
9
10 use super::{ImmTy, Immediate, InterpCx, Machine, PlaceTy};
11
12 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
13     /// Applies the binary operation `op` to the two operands and writes a tuple of the result
14     /// and a boolean signifying the potential overflow to the destination.
15     pub fn binop_with_overflow(
16         &mut self,
17         op: mir::BinOp,
18         left: ImmTy<'tcx, M::PointerTag>,
19         right: ImmTy<'tcx, M::PointerTag>,
20         dest: PlaceTy<'tcx, M::PointerTag>,
21     ) -> InterpResult<'tcx> {
22         let (val, overflowed, ty) = self.overflowing_binary_op(op, left, right)?;
23         debug_assert_eq!(
24             self.tcx.intern_tup(&[ty, self.tcx.types.bool]),
25             dest.layout.ty,
26             "type mismatch for result of {:?}",
27             op,
28         );
29         let val = Immediate::ScalarPair(val.into(), Scalar::from_bool(overflowed).into());
30         self.write_immediate(val, dest)
31     }
32
33     /// Applies the binary operation `op` to the arguments and writes the result to the
34     /// destination.
35     pub fn binop_ignore_overflow(
36         &mut self,
37         op: mir::BinOp,
38         left: ImmTy<'tcx, M::PointerTag>,
39         right: ImmTy<'tcx, M::PointerTag>,
40         dest: PlaceTy<'tcx, M::PointerTag>,
41     ) -> InterpResult<'tcx> {
42         let (val, _overflowed, ty) = self.overflowing_binary_op(op, left, right)?;
43         assert_eq!(ty, dest.layout.ty, "type mismatch for result of {:?}", op);
44         self.write_scalar(val, dest)
45     }
46 }
47
48 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
49     fn binary_char_op(
50         &self,
51         bin_op: mir::BinOp,
52         l: char,
53         r: char,
54     ) -> (Scalar<M::PointerTag>, bool, Ty<'tcx>) {
55         use rustc_middle::mir::BinOp::*;
56
57         let res = match bin_op {
58             Eq => l == r,
59             Ne => l != r,
60             Lt => l < r,
61             Le => l <= r,
62             Gt => l > r,
63             Ge => l >= r,
64             _ => bug!("Invalid operation on char: {:?}", bin_op),
65         };
66         (Scalar::from_bool(res), false, self.tcx.types.bool)
67     }
68
69     fn binary_bool_op(
70         &self,
71         bin_op: mir::BinOp,
72         l: bool,
73         r: bool,
74     ) -> (Scalar<M::PointerTag>, bool, Ty<'tcx>) {
75         use rustc_middle::mir::BinOp::*;
76
77         let res = match bin_op {
78             Eq => l == r,
79             Ne => l != r,
80             Lt => l < r,
81             Le => l <= r,
82             Gt => l > r,
83             Ge => l >= r,
84             BitAnd => l & r,
85             BitOr => l | r,
86             BitXor => l ^ r,
87             _ => bug!("Invalid operation on bool: {:?}", bin_op),
88         };
89         (Scalar::from_bool(res), false, self.tcx.types.bool)
90     }
91
92     fn binary_float_op<F: Float + Into<Scalar<M::PointerTag>>>(
93         &self,
94         bin_op: mir::BinOp,
95         ty: Ty<'tcx>,
96         l: F,
97         r: F,
98     ) -> (Scalar<M::PointerTag>, bool, Ty<'tcx>) {
99         use rustc_middle::mir::BinOp::*;
100
101         let (val, ty) = match bin_op {
102             Eq => (Scalar::from_bool(l == r), self.tcx.types.bool),
103             Ne => (Scalar::from_bool(l != r), self.tcx.types.bool),
104             Lt => (Scalar::from_bool(l < r), self.tcx.types.bool),
105             Le => (Scalar::from_bool(l <= r), self.tcx.types.bool),
106             Gt => (Scalar::from_bool(l > r), self.tcx.types.bool),
107             Ge => (Scalar::from_bool(l >= r), self.tcx.types.bool),
108             Add => ((l + r).value.into(), ty),
109             Sub => ((l - r).value.into(), ty),
110             Mul => ((l * r).value.into(), ty),
111             Div => ((l / r).value.into(), ty),
112             Rem => ((l % r).value.into(), ty),
113             _ => bug!("invalid float op: `{:?}`", bin_op),
114         };
115         (val, false, ty)
116     }
117
118     fn binary_int_op(
119         &self,
120         bin_op: mir::BinOp,
121         // passing in raw bits
122         l: u128,
123         left_layout: TyAndLayout<'tcx>,
124         r: u128,
125         right_layout: TyAndLayout<'tcx>,
126     ) -> InterpResult<'tcx, (Scalar<M::PointerTag>, bool, Ty<'tcx>)> {
127         use rustc_middle::mir::BinOp::*;
128
129         // Shift ops can have an RHS with a different numeric type.
130         if bin_op == Shl || bin_op == Shr {
131             let signed = left_layout.abi.is_signed();
132             let size = u128::from(left_layout.size.bits());
133             let overflow = r >= size;
134             let r = r % size; // mask to type size
135             let r = u32::try_from(r).unwrap(); // we masked so this will always fit
136             let result = if signed {
137                 let l = self.sign_extend(l, left_layout) as i128;
138                 let result = match bin_op {
139                     Shl => l.checked_shl(r).unwrap(),
140                     Shr => l.checked_shr(r).unwrap(),
141                     _ => bug!("it has already been checked that this is a shift op"),
142                 };
143                 result as u128
144             } else {
145                 match bin_op {
146                     Shl => l.checked_shl(r).unwrap(),
147                     Shr => l.checked_shr(r).unwrap(),
148                     _ => bug!("it has already been checked that this is a shift op"),
149                 }
150             };
151             let truncated = self.truncate(result, left_layout);
152             return Ok((Scalar::from_uint(truncated, left_layout.size), overflow, left_layout.ty));
153         }
154
155         // For the remaining ops, the types must be the same on both sides
156         if left_layout.ty != right_layout.ty {
157             bug!(
158                 "invalid asymmetric binary op {:?}: {:?} ({:?}), {:?} ({:?})",
159                 bin_op,
160                 l,
161                 left_layout.ty,
162                 r,
163                 right_layout.ty,
164             )
165         }
166
167         let size = left_layout.size;
168
169         // Operations that need special treatment for signed integers
170         if left_layout.abi.is_signed() {
171             let op: Option<fn(&i128, &i128) -> bool> = match bin_op {
172                 Lt => Some(i128::lt),
173                 Le => Some(i128::le),
174                 Gt => Some(i128::gt),
175                 Ge => Some(i128::ge),
176                 _ => None,
177             };
178             if let Some(op) = op {
179                 let l = self.sign_extend(l, left_layout) as i128;
180                 let r = self.sign_extend(r, right_layout) as i128;
181                 return Ok((Scalar::from_bool(op(&l, &r)), false, self.tcx.types.bool));
182             }
183             let op: Option<fn(i128, i128) -> (i128, bool)> = match bin_op {
184                 Div if r == 0 => throw_ub!(DivisionByZero),
185                 Rem if r == 0 => throw_ub!(RemainderByZero),
186                 Div => Some(i128::overflowing_div),
187                 Rem => Some(i128::overflowing_rem),
188                 Add => Some(i128::overflowing_add),
189                 Sub => Some(i128::overflowing_sub),
190                 Mul => Some(i128::overflowing_mul),
191                 _ => None,
192             };
193             if let Some(op) = op {
194                 let r = self.sign_extend(r, right_layout) as i128;
195                 // We need a special check for overflowing remainder:
196                 // "int_min % -1" overflows and returns 0, but after casting things to a larger int
197                 // type it does *not* overflow nor give an unrepresentable result!
198                 if bin_op == Rem {
199                     if r == -1 && l == (1 << (size.bits() - 1)) {
200                         return Ok((Scalar::from_int(0, size), true, left_layout.ty));
201                     }
202                 }
203                 let l = self.sign_extend(l, left_layout) as i128;
204
205                 let (result, oflo) = op(l, r);
206                 // This may be out-of-bounds for the result type, so we have to truncate ourselves.
207                 // If that truncation loses any information, we have an overflow.
208                 let result = result as u128;
209                 let truncated = self.truncate(result, left_layout);
210                 return Ok((
211                     Scalar::from_uint(truncated, size),
212                     oflo || self.sign_extend(truncated, left_layout) != result,
213                     left_layout.ty,
214                 ));
215             }
216         }
217
218         let (val, ty) = match bin_op {
219             Eq => (Scalar::from_bool(l == r), self.tcx.types.bool),
220             Ne => (Scalar::from_bool(l != r), self.tcx.types.bool),
221
222             Lt => (Scalar::from_bool(l < r), self.tcx.types.bool),
223             Le => (Scalar::from_bool(l <= r), self.tcx.types.bool),
224             Gt => (Scalar::from_bool(l > r), self.tcx.types.bool),
225             Ge => (Scalar::from_bool(l >= r), self.tcx.types.bool),
226
227             BitOr => (Scalar::from_uint(l | r, size), left_layout.ty),
228             BitAnd => (Scalar::from_uint(l & r, size), left_layout.ty),
229             BitXor => (Scalar::from_uint(l ^ r, size), left_layout.ty),
230
231             Add | Sub | Mul | Rem | Div => {
232                 assert!(!left_layout.abi.is_signed());
233                 let op: fn(u128, u128) -> (u128, bool) = match bin_op {
234                     Add => u128::overflowing_add,
235                     Sub => u128::overflowing_sub,
236                     Mul => u128::overflowing_mul,
237                     Div if r == 0 => throw_ub!(DivisionByZero),
238                     Rem if r == 0 => throw_ub!(RemainderByZero),
239                     Div => u128::overflowing_div,
240                     Rem => u128::overflowing_rem,
241                     _ => bug!(),
242                 };
243                 let (result, oflo) = op(l, r);
244                 // Truncate to target type.
245                 // If that truncation loses any information, we have an overflow.
246                 let truncated = self.truncate(result, left_layout);
247                 return Ok((
248                     Scalar::from_uint(truncated, size),
249                     oflo || truncated != result,
250                     left_layout.ty,
251                 ));
252             }
253
254             _ => bug!(
255                 "invalid binary op {:?}: {:?}, {:?} (both {:?})",
256                 bin_op,
257                 l,
258                 r,
259                 right_layout.ty,
260             ),
261         };
262
263         Ok((val, false, ty))
264     }
265
266     /// Returns the result of the specified operation, whether it overflowed, and
267     /// the result type.
268     pub fn overflowing_binary_op(
269         &self,
270         bin_op: mir::BinOp,
271         left: ImmTy<'tcx, M::PointerTag>,
272         right: ImmTy<'tcx, M::PointerTag>,
273     ) -> InterpResult<'tcx, (Scalar<M::PointerTag>, bool, Ty<'tcx>)> {
274         trace!(
275             "Running binary op {:?}: {:?} ({:?}), {:?} ({:?})",
276             bin_op,
277             *left,
278             left.layout.ty,
279             *right,
280             right.layout.ty
281         );
282
283         match left.layout.ty.kind {
284             ty::Char => {
285                 assert_eq!(left.layout.ty, right.layout.ty);
286                 let left = left.to_scalar()?;
287                 let right = right.to_scalar()?;
288                 Ok(self.binary_char_op(bin_op, left.to_char()?, right.to_char()?))
289             }
290             ty::Bool => {
291                 assert_eq!(left.layout.ty, right.layout.ty);
292                 let left = left.to_scalar()?;
293                 let right = right.to_scalar()?;
294                 Ok(self.binary_bool_op(bin_op, left.to_bool()?, right.to_bool()?))
295             }
296             ty::Float(fty) => {
297                 assert_eq!(left.layout.ty, right.layout.ty);
298                 let ty = left.layout.ty;
299                 let left = left.to_scalar()?;
300                 let right = right.to_scalar()?;
301                 Ok(match fty {
302                     FloatTy::F32 => {
303                         self.binary_float_op(bin_op, ty, left.to_f32()?, right.to_f32()?)
304                     }
305                     FloatTy::F64 => {
306                         self.binary_float_op(bin_op, ty, left.to_f64()?, right.to_f64()?)
307                     }
308                 })
309             }
310             _ if left.layout.ty.is_integral() => {
311                 // the RHS type can be different, e.g. for shifts -- but it has to be integral, too
312                 assert!(
313                     right.layout.ty.is_integral(),
314                     "Unexpected types for BinOp: {:?} {:?} {:?}",
315                     left.layout.ty,
316                     bin_op,
317                     right.layout.ty
318                 );
319
320                 let l = self.force_bits(left.to_scalar()?, left.layout.size)?;
321                 let r = self.force_bits(right.to_scalar()?, right.layout.size)?;
322                 self.binary_int_op(bin_op, l, left.layout, r, right.layout)
323             }
324             _ if left.layout.ty.is_any_ptr() => {
325                 // The RHS type must be the same *or an integer type* (for `Offset`).
326                 assert!(
327                     right.layout.ty == left.layout.ty || right.layout.ty.is_integral(),
328                     "Unexpected types for BinOp: {:?} {:?} {:?}",
329                     left.layout.ty,
330                     bin_op,
331                     right.layout.ty
332                 );
333
334                 M::binary_ptr_op(self, bin_op, left, right)
335             }
336             _ => bug!("Invalid MIR: bad LHS type for binop: {:?}", left.layout.ty),
337         }
338     }
339
340     /// Typed version of `overflowing_binary_op`, returning an `ImmTy`. Also ignores overflows.
341     #[inline]
342     pub fn binary_op(
343         &self,
344         bin_op: mir::BinOp,
345         left: ImmTy<'tcx, M::PointerTag>,
346         right: ImmTy<'tcx, M::PointerTag>,
347     ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
348         let (val, _overflow, ty) = self.overflowing_binary_op(bin_op, left, right)?;
349         Ok(ImmTy::from_scalar(val, self.layout_of(ty)?))
350     }
351
352     /// Returns the result of the specified operation, whether it overflowed, and
353     /// the result type.
354     pub fn overflowing_unary_op(
355         &self,
356         un_op: mir::UnOp,
357         val: ImmTy<'tcx, M::PointerTag>,
358     ) -> InterpResult<'tcx, (Scalar<M::PointerTag>, bool, Ty<'tcx>)> {
359         use rustc_middle::mir::UnOp::*;
360
361         let layout = val.layout;
362         let val = val.to_scalar()?;
363         trace!("Running unary op {:?}: {:?} ({:?})", un_op, val, layout.ty);
364
365         match layout.ty.kind {
366             ty::Bool => {
367                 let val = val.to_bool()?;
368                 let res = match un_op {
369                     Not => !val,
370                     _ => bug!("Invalid bool op {:?}", un_op),
371                 };
372                 Ok((Scalar::from_bool(res), false, self.tcx.types.bool))
373             }
374             ty::Float(fty) => {
375                 let res = match (un_op, fty) {
376                     (Neg, FloatTy::F32) => Scalar::from_f32(-val.to_f32()?),
377                     (Neg, FloatTy::F64) => Scalar::from_f64(-val.to_f64()?),
378                     _ => bug!("Invalid float op {:?}", un_op),
379                 };
380                 Ok((res, false, layout.ty))
381             }
382             _ => {
383                 assert!(layout.ty.is_integral());
384                 let val = self.force_bits(val, layout.size)?;
385                 let (res, overflow) = match un_op {
386                     Not => (self.truncate(!val, layout), false), // bitwise negation, then truncate
387                     Neg => {
388                         // arithmetic negation
389                         assert!(layout.abi.is_signed());
390                         let val = self.sign_extend(val, layout) as i128;
391                         let (res, overflow) = val.overflowing_neg();
392                         let res = res as u128;
393                         // Truncate to target type.
394                         // If that truncation loses any information, we have an overflow.
395                         let truncated = self.truncate(res, layout);
396                         (truncated, overflow || self.sign_extend(truncated, layout) != res)
397                     }
398                 };
399                 Ok((Scalar::from_uint(res, layout.size), overflow, layout.ty))
400             }
401         }
402     }
403
404     pub fn unary_op(
405         &self,
406         un_op: mir::UnOp,
407         val: ImmTy<'tcx, M::PointerTag>,
408     ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
409         let (val, _overflow, ty) = self.overflowing_unary_op(un_op, val)?;
410         Ok(ImmTy::from_scalar(val, self.layout_of(ty)?))
411     }
412 }