3 use rustc_middle::{mir, ty::Ty};
4 use rustc_target::abi::Size;
8 pub trait EvalContextExt<'tcx> {
12 left: &ImmTy<'tcx, Tag>,
13 right: &ImmTy<'tcx, Tag>,
14 ) -> InterpResult<'tcx, (Scalar<Tag>, bool, Ty<'tcx>)>;
17 impl<'mir, 'tcx> EvalContextExt<'tcx> for super::MiriEvalContext<'mir, 'tcx> {
21 left: &ImmTy<'tcx, Tag>,
22 right: &ImmTy<'tcx, Tag>,
23 ) -> InterpResult<'tcx, (Scalar<Tag>, bool, Ty<'tcx>)> {
24 use rustc_middle::mir::BinOp::*;
26 trace!("ptr_op: {:?} {:?} {:?}", *left, bin_op, *right);
29 Eq | Ne | Lt | Le | Gt | Ge => {
30 assert_eq!(left.layout.abi, right.layout.abi); // types an differ, e.g. fn ptrs with different `for`
31 let size = self.pointer_size();
32 // Just compare the bits. ScalarPairs are compared lexicographically.
33 // We thus always compare pairs and simply fill scalars up with 0.
34 let left = match **left {
35 Immediate::Scalar(l) => (l.check_init()?.to_bits(size)?, 0),
36 Immediate::ScalarPair(l1, l2) =>
37 (l1.check_init()?.to_bits(size)?, l2.check_init()?.to_bits(size)?),
38 Immediate::Uninit => throw_ub!(InvalidUninitBytes(None)),
40 let right = match **right {
41 Immediate::Scalar(r) => (r.check_init()?.to_bits(size)?, 0),
42 Immediate::ScalarPair(r1, r2) =>
43 (r1.check_init()?.to_bits(size)?, r2.check_init()?.to_bits(size)?),
44 Immediate::Uninit => throw_ub!(InvalidUninitBytes(None)),
46 let res = match bin_op {
55 (Scalar::from_bool(res), false, self.tcx.types.bool)
59 assert!(left.layout.ty.is_unsafe_ptr());
60 let ptr = self.scalar_to_ptr(left.to_scalar()?)?;
61 let offset = right.to_scalar()?.to_machine_isize(self)?;
64 left.layout.ty.builtin_deref(true).expect("Offset called on non-ptr type").ty;
65 let ptr = self.ptr_offset_inbounds(ptr, pointee_ty, offset)?;
66 (Scalar::from_maybe_pointer(ptr, self), false, left.layout.ty)
69 // Some more operations are possible with atomics.
70 // The return value always has the provenance of the *left* operand.
71 Add | Sub | BitOr | BitAnd | BitXor => {
72 assert!(left.layout.ty.is_unsafe_ptr());
73 assert!(right.layout.ty.is_unsafe_ptr());
74 let ptr = self.scalar_to_ptr(left.to_scalar()?)?;
75 // We do the actual operation with usize-typed scalars.
76 let left = ImmTy::from_uint(ptr.addr().bytes(), self.machine.layouts.usize);
77 let right = ImmTy::from_uint(
78 right.to_scalar()?.to_machine_usize(self)?,
79 self.machine.layouts.usize,
81 let (result, overflowing, _ty) =
82 self.overflowing_binary_op(bin_op, &left, &right)?;
83 // Construct a new pointer with the provenance of `ptr` (the LHS).
85 Pointer::new(ptr.provenance, Size::from_bytes(result.to_machine_usize(self)?));
86 (Scalar::from_maybe_pointer(result_ptr, self), overflowing, left.layout.ty)
89 _ => span_bug!(self.cur_span(), "Invalid operator on pointers: {:?}", bin_op),