1
Fork 0
rust/src/librustc_mir/interpret/operator.rs

266 lines
9.6 KiB
Rust
Raw Normal View History

use rustc::mir;
use rustc::ty::{self, Ty};
use rustc_const_math::ConstFloat;
use syntax::ast::FloatTy;
use std::cmp::Ordering;
use rustc::ty::layout::LayoutOf;
use super::{EvalContext, Place, Machine, ValTy};
use rustc::mir::interpret::{EvalResult, PrimVal, Value};
2018-01-16 09:31:48 +01:00
impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
fn binop_with_overflow(
&mut self,
op: mir::BinOp,
left: ValTy<'tcx>,
right: ValTy<'tcx>,
) -> EvalResult<'tcx, (PrimVal, bool)> {
let left_val = self.value_to_primval(left)?;
let right_val = self.value_to_primval(right)?;
self.binary_op(op, left_val, left.ty, right_val, right.ty)
}
/// Applies the binary operation `op` to the two operands and writes a tuple of the result
/// and a boolean signifying the potential overflow to the destination.
pub fn intrinsic_with_overflow(
&mut self,
op: mir::BinOp,
left: ValTy<'tcx>,
right: ValTy<'tcx>,
2017-12-06 09:25:29 +01:00
dest: Place,
dest_ty: Ty<'tcx>,
) -> EvalResult<'tcx> {
let (val, overflowed) = self.binop_with_overflow(op, left, right)?;
let val = Value::ByValPair(val, PrimVal::from_bool(overflowed));
let valty = ValTy {
value: val,
ty: dest_ty,
};
self.write_value(valty, dest)
}
/// Applies the binary operation `op` to the arguments and writes the result to the
/// destination. Returns `true` if the operation overflowed.
pub fn intrinsic_overflowing(
&mut self,
op: mir::BinOp,
left: ValTy<'tcx>,
right: ValTy<'tcx>,
2017-12-06 09:25:29 +01:00
dest: Place,
dest_ty: Ty<'tcx>,
) -> EvalResult<'tcx, bool> {
let (val, overflowed) = self.binop_with_overflow(op, left, right)?;
self.write_primval(dest, val, dest_ty)?;
Ok(overflowed)
}
}
2018-01-16 09:31:48 +01:00
impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
/// Returns the result of the specified operation and whether it overflowed.
pub fn binary_op(
&self,
bin_op: mir::BinOp,
left: PrimVal,
left_ty: Ty<'tcx>,
right: PrimVal,
right_ty: Ty<'tcx>,
) -> EvalResult<'tcx, (PrimVal, bool)> {
use rustc::mir::BinOp::*;
let left_kind = self.ty_to_primval_kind(left_ty)?;
let right_kind = self.ty_to_primval_kind(right_ty)?;
trace!("Running binary op {:?}: {:?} ({:?}), {:?} ({:?})", bin_op, left, left_kind, right, right_kind);
2017-06-21 20:18:42 -07:00
// I: Handle operations that support pointers
if !left_kind.is_float() && !right_kind.is_float() {
2017-08-01 11:11:57 +02:00
if let Some(handled) = M::try_ptr_op(self, bin_op, left, left_ty, right, right_ty)? {
return Ok(handled);
}
2017-06-19 10:58:59 +02:00
}
2017-06-21 20:18:42 -07:00
// II: From now on, everything must be bytes, no pointers
2017-06-19 10:58:59 +02:00
let l = left.to_bytes()?;
let r = right.to_bytes()?;
// These ops can have an RHS with a different numeric type.
if right_kind.is_int() && (bin_op == Shl || bin_op == Shr) {
let op: fn(u128, u32) -> (u128, bool) = match bin_op {
Shl => u128::overflowing_shl,
Shr => u128::overflowing_shr,
_ => bug!("it has already been checked that this is a shift op"),
};
let l = if left_ty.is_signed() {
self.sign_extend(l, left_ty)?
} else {
l
};
let (result, oflo) = op(l, r as u32);
let truncated = self.truncate(result, left_ty)?;
return Ok((PrimVal::Bytes(truncated), oflo || truncated != result));
}
if left_kind != right_kind {
let msg = format!(
"unimplemented binary op {:?}: {:?} ({:?}), {:?} ({:?})",
bin_op,
left,
left_kind,
right,
right_kind
);
2017-08-02 16:59:01 +02:00
return err!(Unimplemented(msg));
}
let float_op = |op, l, r, ty| {
let l = ConstFloat {
bits: l,
ty,
};
let r = ConstFloat {
bits: r,
ty,
};
match op {
Eq => PrimVal::from_bool(l.try_cmp(r).unwrap() == Ordering::Equal),
Ne => PrimVal::from_bool(l.try_cmp(r).unwrap() != Ordering::Equal),
Lt => PrimVal::from_bool(l.try_cmp(r).unwrap() == Ordering::Less),
Le => PrimVal::from_bool(l.try_cmp(r).unwrap() != Ordering::Greater),
Gt => PrimVal::from_bool(l.try_cmp(r).unwrap() == Ordering::Greater),
Ge => PrimVal::from_bool(l.try_cmp(r).unwrap() != Ordering::Less),
Add => PrimVal::Bytes((l + r).unwrap().bits),
Sub => PrimVal::Bytes((l - r).unwrap().bits),
Mul => PrimVal::Bytes((l * r).unwrap().bits),
Div => PrimVal::Bytes((l / r).unwrap().bits),
Rem => PrimVal::Bytes((l % r).unwrap().bits),
_ => bug!("invalid float op: `{:?}`", op),
}
};
if left_ty.is_signed() {
let op: Option<fn(&i128, &i128) -> bool> = match bin_op {
Lt => Some(i128::lt),
Le => Some(i128::le),
Gt => Some(i128::gt),
Ge => Some(i128::ge),
_ => None,
};
if let Some(op) = op {
let l = self.sign_extend(l, left_ty)? as i128;
let r = self.sign_extend(r, right_ty)? as i128;
return Ok((PrimVal::from_bool(op(&l, &r)), false));
}
let op: Option<fn(i128, i128) -> (i128, bool)> = match bin_op {
Rem | Div if r == 0 => return Ok((PrimVal::Bytes(l), true)),
Div => Some(i128::overflowing_div),
Rem => Some(i128::overflowing_rem),
Add => Some(i128::overflowing_add),
Sub => Some(i128::overflowing_sub),
Mul => Some(i128::overflowing_mul),
_ => None,
};
if let Some(op) = op {
let l128 = self.sign_extend(l, left_ty)? as i128;
let r = self.sign_extend(r, right_ty)? as i128;
let size = self.layout_of(left_ty)?.size.bits();
match bin_op {
Rem | Div => {
// int_min / -1
if r == -1 && l == (1 << (size - 1)) {
return Ok((PrimVal::Bytes(l), true));
}
},
_ => {},
}
trace!("{}, {}, {}", l, l128, r);
let (result, mut oflo) = op(l128, r);
trace!("{}, {}", result, oflo);
if !oflo && size != 128 {
let max = 1 << (size - 1);
oflo = result >= max || result < -max;
}
let result = result as u128;
let truncated = self.truncate(result, left_ty)?;
return Ok((PrimVal::Bytes(truncated), oflo));
}
}
if let ty::TyFloat(fty) = left_ty.sty {
return Ok((float_op(bin_op, l, r, fty), false));
}
// only ints left
let val = match bin_op {
Eq => PrimVal::from_bool(l == r),
Ne => PrimVal::from_bool(l != r),
Lt => PrimVal::from_bool(l < r),
Le => PrimVal::from_bool(l <= r),
Gt => PrimVal::from_bool(l > r),
Ge => PrimVal::from_bool(l >= r),
BitOr => PrimVal::Bytes(l | r),
BitAnd => PrimVal::Bytes(l & r),
BitXor => PrimVal::Bytes(l ^ r),
Add | Sub | Mul | Rem | Div => {
let op: fn(u128, u128) -> (u128, bool) = match bin_op {
Add => u128::overflowing_add,
Sub => u128::overflowing_sub,
Mul => u128::overflowing_mul,
Rem | Div if r == 0 => return Ok((PrimVal::Bytes(l), true)),
Div => u128::overflowing_div,
Rem => u128::overflowing_rem,
_ => bug!(),
};
let (result, oflo) = op(l, r);
let truncated = self.truncate(result, left_ty)?;
return Ok((PrimVal::Bytes(truncated), oflo || truncated != result));
}
_ => {
let msg = format!(
"unimplemented binary op {:?}: {:?} ({:?}), {:?} ({:?})",
bin_op,
left,
left_ty,
right,
right_ty,
);
2017-08-02 16:59:01 +02:00
return err!(Unimplemented(msg));
}
};
Ok((val, false))
}
pub fn unary_op(
&self,
un_op: mir::UnOp,
val: PrimVal,
ty: Ty<'tcx>,
) -> EvalResult<'tcx, PrimVal> {
use rustc::mir::UnOp::*;
use rustc_apfloat::ieee::{Single, Double};
use rustc_apfloat::Float;
let bytes = val.to_bytes()?;
let size = self.layout_of(ty)?.size.bits();
2017-01-12 08:28:42 +01:00
let result_bytes = match (un_op, &ty.sty) {
2017-01-12 08:28:42 +01:00
(Not, ty::TyBool) => !val.to_bool()? as u128,
2017-01-12 08:28:42 +01:00
(Not, _) => !bytes,
(Neg, ty::TyFloat(FloatTy::F32)) => Single::to_bits(-Single::from_bits(bytes)),
(Neg, ty::TyFloat(FloatTy::F64)) => Double::to_bits(-Double::from_bits(bytes)),
(Neg, _) if bytes == (1 << (size - 1)) => return err!(OverflowingMath),
(Neg, _) => (-(bytes as i128)) as u128,
};
Ok(PrimVal::Bytes(self.truncate(result_bytes, ty)?))
}
}