]> git.proxmox.com Git - rustc.git/blob - src/librustc_mir/interpret/operator.rs
470cc9346ee21407593440891d21eecdbef0a108
[rustc.git] / src / librustc_mir / interpret / operator.rs
1 use rustc::mir;
2 use rustc::ty::{self, Ty, layout::{TyLayout, LayoutOf}};
3 use syntax::ast::FloatTy;
4 use rustc_apfloat::Float;
5 use rustc::mir::interpret::{InterpResult, Scalar};
6
7 use super::{InterpCx, PlaceTy, Immediate, Machine, ImmTy};
8
9
10 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
11 /// Applies the binary operation `op` to the two operands and writes a tuple of the result
12 /// and a boolean signifying the potential overflow to the destination.
13 pub fn binop_with_overflow(
14 &mut self,
15 op: mir::BinOp,
16 left: ImmTy<'tcx, M::PointerTag>,
17 right: ImmTy<'tcx, M::PointerTag>,
18 dest: PlaceTy<'tcx, M::PointerTag>,
19 ) -> InterpResult<'tcx> {
20 let (val, overflowed, ty) = self.overflowing_binary_op(op, left, right)?;
21 debug_assert_eq!(
22 self.tcx.intern_tup(&[ty, self.tcx.types.bool]),
23 dest.layout.ty,
24 "type mismatch for result of {:?}", op,
25 );
26 let val = Immediate::ScalarPair(val.into(), Scalar::from_bool(overflowed).into());
27 self.write_immediate(val, dest)
28 }
29
30 /// Applies the binary operation `op` to the arguments and writes the result to the
31 /// destination.
32 pub fn binop_ignore_overflow(
33 &mut self,
34 op: mir::BinOp,
35 left: ImmTy<'tcx, M::PointerTag>,
36 right: ImmTy<'tcx, M::PointerTag>,
37 dest: PlaceTy<'tcx, M::PointerTag>,
38 ) -> InterpResult<'tcx> {
39 let (val, _overflowed, ty) = self.overflowing_binary_op(op, left, right)?;
40 assert_eq!(ty, dest.layout.ty, "type mismatch for result of {:?}", op);
41 self.write_scalar(val, dest)
42 }
43 }
44
45 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
46 fn binary_char_op(
47 &self,
48 bin_op: mir::BinOp,
49 l: char,
50 r: char,
51 ) -> (Scalar<M::PointerTag>, bool, Ty<'tcx>) {
52 use rustc::mir::BinOp::*;
53
54 let res = match bin_op {
55 Eq => l == r,
56 Ne => l != r,
57 Lt => l < r,
58 Le => l <= r,
59 Gt => l > r,
60 Ge => l >= r,
61 _ => bug!("Invalid operation on char: {:?}", bin_op),
62 };
63 return (Scalar::from_bool(res), false, self.tcx.types.bool);
64 }
65
66 fn binary_bool_op(
67 &self,
68 bin_op: mir::BinOp,
69 l: bool,
70 r: bool,
71 ) -> (Scalar<M::PointerTag>, bool, Ty<'tcx>) {
72 use rustc::mir::BinOp::*;
73
74 let res = match bin_op {
75 Eq => l == r,
76 Ne => l != r,
77 Lt => l < r,
78 Le => l <= r,
79 Gt => l > r,
80 Ge => l >= r,
81 BitAnd => l & r,
82 BitOr => l | r,
83 BitXor => l ^ r,
84 _ => bug!("Invalid operation on bool: {:?}", bin_op),
85 };
86 return (Scalar::from_bool(res), false, self.tcx.types.bool);
87 }
88
89 fn binary_float_op<F: Float + Into<Scalar<M::PointerTag>>>(
90 &self,
91 bin_op: mir::BinOp,
92 ty: Ty<'tcx>,
93 l: F,
94 r: F,
95 ) -> (Scalar<M::PointerTag>, bool, Ty<'tcx>) {
96 use rustc::mir::BinOp::*;
97
98 let (val, ty) = match bin_op {
99 Eq => (Scalar::from_bool(l == r), self.tcx.types.bool),
100 Ne => (Scalar::from_bool(l != r), self.tcx.types.bool),
101 Lt => (Scalar::from_bool(l < r), self.tcx.types.bool),
102 Le => (Scalar::from_bool(l <= r), self.tcx.types.bool),
103 Gt => (Scalar::from_bool(l > r), self.tcx.types.bool),
104 Ge => (Scalar::from_bool(l >= r), self.tcx.types.bool),
105 Add => ((l + r).value.into(), ty),
106 Sub => ((l - r).value.into(), ty),
107 Mul => ((l * r).value.into(), ty),
108 Div => ((l / r).value.into(), ty),
109 Rem => ((l % r).value.into(), ty),
110 _ => bug!("invalid float op: `{:?}`", bin_op),
111 };
112 return (val, false, ty);
113 }
114
115 fn binary_int_op(
116 &self,
117 bin_op: mir::BinOp,
118 // passing in raw bits
119 l: u128,
120 left_layout: TyLayout<'tcx>,
121 r: u128,
122 right_layout: TyLayout<'tcx>,
123 ) -> InterpResult<'tcx, (Scalar<M::PointerTag>, bool, Ty<'tcx>)> {
124 use rustc::mir::BinOp::*;
125
126 // Shift ops can have an RHS with a different numeric type.
127 if bin_op == Shl || bin_op == Shr {
128 let signed = left_layout.abi.is_signed();
129 let mut oflo = (r as u32 as u128) != r;
130 let mut r = r as u32;
131 let size = left_layout.size;
132 oflo |= r >= size.bits() as u32;
133 if oflo {
134 r %= size.bits() as u32;
135 }
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 << r,
140 Shr => l >> r,
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 << r,
147 Shr => l >> r,
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, size), oflo, 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, left_layout.ty,
161 r, right_layout.ty,
162 )
163 }
164
165 // Operations that need special treatment for signed integers
166 if left_layout.abi.is_signed() {
167 let op: Option<fn(&i128, &i128) -> bool> = match bin_op {
168 Lt => Some(i128::lt),
169 Le => Some(i128::le),
170 Gt => Some(i128::gt),
171 Ge => Some(i128::ge),
172 _ => None,
173 };
174 if let Some(op) = op {
175 let l = self.sign_extend(l, left_layout) as i128;
176 let r = self.sign_extend(r, right_layout) as i128;
177 return Ok((Scalar::from_bool(op(&l, &r)), false, self.tcx.types.bool));
178 }
179 let op: Option<fn(i128, i128) -> (i128, bool)> = match bin_op {
180 Div if r == 0 => throw_panic!(DivisionByZero),
181 Rem if r == 0 => throw_panic!(RemainderByZero),
182 Div => Some(i128::overflowing_div),
183 Rem => Some(i128::overflowing_rem),
184 Add => Some(i128::overflowing_add),
185 Sub => Some(i128::overflowing_sub),
186 Mul => Some(i128::overflowing_mul),
187 _ => None,
188 };
189 if let Some(op) = op {
190 let l128 = self.sign_extend(l, left_layout) as i128;
191 let r = self.sign_extend(r, right_layout) as i128;
192 let size = left_layout.size;
193 match bin_op {
194 Rem | Div => {
195 // int_min / -1
196 if r == -1 && l == (1 << (size.bits() - 1)) {
197 return Ok((Scalar::from_uint(l, size), true, left_layout.ty));
198 }
199 },
200 _ => {},
201 }
202 trace!("{}, {}, {}", l, l128, r);
203 let (result, mut oflo) = op(l128, r);
204 trace!("{}, {}", result, oflo);
205 if !oflo && size.bits() != 128 {
206 let max = 1 << (size.bits() - 1);
207 oflo = result >= max || result < -max;
208 }
209 // this may be out-of-bounds for the result type, so we have to truncate ourselves
210 let result = result as u128;
211 let truncated = self.truncate(result, left_layout);
212 return Ok((Scalar::from_uint(truncated, size), oflo, left_layout.ty));
213 }
214 }
215
216 let size = left_layout.size;
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 debug_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_panic!(DivisionByZero),
238 Rem if r == 0 => throw_panic!(RemainderByZero),
239 Div => u128::overflowing_div,
240 Rem => u128::overflowing_rem,
241 _ => bug!(),
242 };
243 let (result, oflo) = op(l, r);
244 let truncated = self.truncate(result, left_layout);
245 return Ok((
246 Scalar::from_uint(truncated, size),
247 oflo || truncated != result,
248 left_layout.ty,
249 ));
250 }
251
252 _ => {
253 bug!(
254 "invalid binary op {:?}: {:?}, {:?} (both {:?})",
255 bin_op,
256 l,
257 r,
258 right_layout.ty,
259 )
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!("Running binary op {:?}: {:?} ({:?}), {:?} ({:?})",
275 bin_op, *left, left.layout.ty, *right, right.layout.ty);
276
277 match left.layout.ty.sty {
278 ty::Char => {
279 assert_eq!(left.layout.ty, right.layout.ty);
280 let left = left.to_scalar()?;
281 let right = right.to_scalar()?;
282 Ok(self.binary_char_op(bin_op, left.to_char()?, right.to_char()?))
283 }
284 ty::Bool => {
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_bool_op(bin_op, left.to_bool()?, right.to_bool()?))
289 }
290 ty::Float(fty) => {
291 assert_eq!(left.layout.ty, right.layout.ty);
292 let ty = left.layout.ty;
293 let left = left.to_scalar()?;
294 let right = right.to_scalar()?;
295 Ok(match fty {
296 FloatTy::F32 =>
297 self.binary_float_op(bin_op, ty, left.to_f32()?, right.to_f32()?),
298 FloatTy::F64 =>
299 self.binary_float_op(bin_op, ty, left.to_f64()?, right.to_f64()?),
300 })
301 }
302 _ if left.layout.ty.is_integral() => {
303 // the RHS type can be different, e.g. for shifts -- but it has to be integral, too
304 assert!(
305 right.layout.ty.is_integral(),
306 "Unexpected types for BinOp: {:?} {:?} {:?}",
307 left.layout.ty, bin_op, right.layout.ty
308 );
309
310 let l = self.force_bits(left.to_scalar()?, left.layout.size)?;
311 let r = self.force_bits(right.to_scalar()?, right.layout.size)?;
312 self.binary_int_op(bin_op, l, left.layout, r, right.layout)
313 }
314 _ if left.layout.ty.is_any_ptr() => {
315 // The RHS type must be the same *or an integer type* (for `Offset`).
316 assert!(
317 right.layout.ty == left.layout.ty || right.layout.ty.is_integral(),
318 "Unexpected types for BinOp: {:?} {:?} {:?}",
319 left.layout.ty, bin_op, right.layout.ty
320 );
321
322 M::binary_ptr_op(self, bin_op, left, right)
323 }
324 _ => bug!("Invalid MIR: bad LHS type for binop: {:?}", left.layout.ty),
325 }
326 }
327
328 /// Typed version of `checked_binary_op`, returning an `ImmTy`. Also ignores overflows.
329 #[inline]
330 pub fn binary_op(
331 &self,
332 bin_op: mir::BinOp,
333 left: ImmTy<'tcx, M::PointerTag>,
334 right: ImmTy<'tcx, M::PointerTag>,
335 ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
336 let (val, _overflow, ty) = self.overflowing_binary_op(bin_op, left, right)?;
337 Ok(ImmTy::from_scalar(val, self.layout_of(ty)?))
338 }
339
340 pub fn unary_op(
341 &self,
342 un_op: mir::UnOp,
343 val: ImmTy<'tcx, M::PointerTag>,
344 ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> {
345 use rustc::mir::UnOp::*;
346
347 let layout = val.layout;
348 let val = val.to_scalar()?;
349 trace!("Running unary op {:?}: {:?} ({:?})", un_op, val, layout.ty);
350
351 match layout.ty.sty {
352 ty::Bool => {
353 let val = val.to_bool()?;
354 let res = match un_op {
355 Not => !val,
356 _ => bug!("Invalid bool op {:?}", un_op)
357 };
358 Ok(ImmTy::from_scalar(Scalar::from_bool(res), self.layout_of(self.tcx.types.bool)?))
359 }
360 ty::Float(fty) => {
361 let res = match (un_op, fty) {
362 (Neg, FloatTy::F32) => Scalar::from_f32(-val.to_f32()?),
363 (Neg, FloatTy::F64) => Scalar::from_f64(-val.to_f64()?),
364 _ => bug!("Invalid float op {:?}", un_op)
365 };
366 Ok(ImmTy::from_scalar(res, layout))
367 }
368 _ => {
369 assert!(layout.ty.is_integral());
370 let val = self.force_bits(val, layout.size)?;
371 let res = match un_op {
372 Not => !val,
373 Neg => {
374 assert!(layout.abi.is_signed());
375 (-(val as i128)) as u128
376 }
377 };
378 // res needs tuncating
379 Ok(ImmTy::from_uint(self.truncate(res, layout), layout))
380 }
381 }
382 }
383 }