Skip to content

Commit b31f860

Browse files
committed
interpret: simplify pointer arithmetic logic
1 parent 5802bda commit b31f860

27 files changed

+73
-187
lines changed

compiler/rustc_abi/src/lib.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -517,7 +517,7 @@ impl Size {
517517
/// Truncates `value` to `self` bits and then sign-extends it to 128 bits
518518
/// (i.e., if it is negative, fill with 1's on the left).
519519
#[inline]
520-
pub fn sign_extend(self, value: u128) -> u128 {
520+
pub fn sign_extend(self, value: u128) -> i128 {
521521
let size = self.bits();
522522
if size == 0 {
523523
// Truncated until nothing is left.
@@ -527,7 +527,7 @@ impl Size {
527527
let shift = 128 - size;
528528
// Shift the unsigned value to the left, then shift back to the right as signed
529529
// (essentially fills with sign bit on the left).
530-
(((value << shift) as i128) >> shift) as u128
530+
((value << shift) as i128) >> shift
531531
}
532532

533533
/// Truncates `value` to `self` bits.
@@ -545,7 +545,7 @@ impl Size {
545545

546546
#[inline]
547547
pub fn signed_int_min(&self) -> i128 {
548-
self.sign_extend(1_u128 << (self.bits() - 1)) as i128
548+
self.sign_extend(1_u128 << (self.bits() - 1))
549549
}
550550

551551
#[inline]

compiler/rustc_const_eval/src/interpret/eval_context.rs

-11
Original file line numberDiff line numberDiff line change
@@ -561,17 +561,6 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
561561
self.frame().body
562562
}
563563

564-
#[inline(always)]
565-
pub fn sign_extend(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
566-
assert!(ty.abi.is_signed());
567-
ty.size.sign_extend(value)
568-
}
569-
570-
#[inline(always)]
571-
pub fn truncate(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
572-
ty.size.truncate(value)
573-
}
574-
575564
#[inline]
576565
pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
577566
ty.is_freeze(*self.tcx, self.param_env)

compiler/rustc_const_eval/src/interpret/intrinsics.rs

+3-6
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
211211
} else {
212212
(val_bits >> shift_bits) | (val_bits << inv_shift_bits)
213213
};
214-
let truncated_bits = self.truncate(result_bits, layout_val);
214+
let truncated_bits = layout_val.size.truncate(result_bits);
215215
let result = Scalar::from_uint(truncated_bits, layout_val.size);
216216
self.write_scalar(result, dest)?;
217217
}
@@ -585,13 +585,10 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
585585
ptr: Pointer<Option<M::Provenance>>,
586586
offset_bytes: i64,
587587
) -> InterpResult<'tcx, Pointer<Option<M::Provenance>>> {
588-
// We first compute the pointer with overflow checks, to get a specific error for when it
589-
// overflows (though technically this is redundant with the following inbounds check).
590-
let result = ptr.signed_offset(offset_bytes, self)?;
591588
// The offset must be in bounds starting from `ptr`.
592589
self.check_ptr_access_signed(ptr, offset_bytes, CheckInAllocMsg::PointerArithmeticTest)?;
593-
// Done.
594-
Ok(result)
590+
// This also implies that there is no overflow, so we are done.
591+
Ok(ptr.wrapping_signed_offset(offset_bytes, self))
595592
}
596593

597594
/// Copy `count*size_of::<T>()` many bytes from `*src` to `*dst`.

compiler/rustc_const_eval/src/interpret/memory.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -477,7 +477,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
477477
throw_ub!(PointerOutOfBounds {
478478
alloc_id,
479479
alloc_size,
480-
ptr_offset: self.target_usize_to_isize(offset),
480+
ptr_offset: self.sign_extend_to_target_isize(offset),
481481
inbounds_size: size,
482482
msg,
483483
})

compiler/rustc_const_eval/src/interpret/place.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -291,10 +291,8 @@ impl<'tcx, Prov: Provenance> Projectable<'tcx, Prov> for PlaceTy<'tcx, Prov> {
291291
// projections are type-checked and bounds-checked.
292292
assert!(offset + layout.size <= self.layout.size);
293293

294-
let new_offset = Size::from_bytes(
295-
ecx.data_layout()
296-
.offset(old_offset.unwrap_or(Size::ZERO).bytes(), offset.bytes())?,
297-
);
294+
// Size `+`, ensures no overflow.
295+
let new_offset = old_offset.unwrap_or(Size::ZERO) + offset;
298296

299297
PlaceTy {
300298
place: Place::Local { local, offset: Some(new_offset), locals_addr },

compiler/rustc_const_eval/src/interpret/step.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
364364
// of the first element.
365365
let elem_size = first.layout.size;
366366
let first_ptr = first.ptr();
367-
let rest_ptr = first_ptr.offset(elem_size, self)?;
367+
let rest_ptr = first_ptr.wrapping_offset(elem_size, self);
368368
// No alignment requirement since `copy_op` above already checked it.
369369
self.mem_copy_repeatedly(
370370
first_ptr,

compiler/rustc_lint/src/types.rs

+1-5
Original file line numberDiff line numberDiff line change
@@ -315,11 +315,7 @@ fn report_bin_hex_error(
315315
) {
316316
let (t, actually) = match ty {
317317
attr::IntType::SignedInt(t) => {
318-
let actually = if negative {
319-
-(size.sign_extend(val) as i128)
320-
} else {
321-
size.sign_extend(val) as i128
322-
};
318+
let actually = if negative { -(size.sign_extend(val)) } else { size.sign_extend(val) };
323319
(t.name_str(), actually.to_string())
324320
}
325321
attr::IntType::UnsignedInt(t) => {

compiler/rustc_middle/src/mir/interpret/pointer.rs

+11-87
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use super::{AllocId, InterpResult};
1+
use super::AllocId;
22

33
use rustc_data_structures::static_assert_size;
44
use rustc_macros::{HashStable, TyDecodable, TyEncodable};
@@ -39,62 +39,13 @@ pub trait PointerArithmetic: HasDataLayout {
3939
}
4040

4141
#[inline]
42-
fn target_usize_to_isize(&self, val: u64) -> i64 {
43-
let val = val as i64;
44-
// Now wrap-around into the machine_isize range.
45-
if val > self.target_isize_max() {
46-
// This can only happen if the ptr size is < 64, so we know max_usize_plus_1 fits into
47-
// i64.
48-
debug_assert!(self.pointer_size().bits() < 64);
49-
let max_usize_plus_1 = 1u128 << self.pointer_size().bits();
50-
val - i64::try_from(max_usize_plus_1).unwrap()
51-
} else {
52-
val
53-
}
54-
}
55-
56-
/// Helper function: truncate given value-"overflowed flag" pair to pointer size and
57-
/// update "overflowed flag" if there was an overflow.
58-
/// This should be called by all the other methods before returning!
59-
#[inline]
60-
fn truncate_to_ptr(&self, (val, over): (u64, bool)) -> (u64, bool) {
61-
let val = u128::from(val);
62-
let max_ptr_plus_1 = 1u128 << self.pointer_size().bits();
63-
(u64::try_from(val % max_ptr_plus_1).unwrap(), over || val >= max_ptr_plus_1)
64-
}
65-
66-
#[inline]
67-
fn overflowing_offset(&self, val: u64, i: u64) -> (u64, bool) {
68-
// We do not need to check if i fits in a machine usize. If it doesn't,
69-
// either the wrapping_add will wrap or res will not fit in a pointer.
70-
let res = val.overflowing_add(i);
71-
self.truncate_to_ptr(res)
72-
}
73-
74-
#[inline]
75-
fn overflowing_signed_offset(&self, val: u64, i: i64) -> (u64, bool) {
76-
// We need to make sure that i fits in a machine isize.
77-
let n = i.unsigned_abs();
78-
if i >= 0 {
79-
let (val, over) = self.overflowing_offset(val, n);
80-
(val, over || i > self.target_isize_max())
81-
} else {
82-
let res = val.overflowing_sub(n);
83-
let (val, over) = self.truncate_to_ptr(res);
84-
(val, over || i < self.target_isize_min())
85-
}
86-
}
87-
88-
#[inline]
89-
fn offset<'tcx>(&self, val: u64, i: u64) -> InterpResult<'tcx, u64> {
90-
let (res, over) = self.overflowing_offset(val, i);
91-
if over { throw_ub!(PointerArithOverflow) } else { Ok(res) }
42+
fn truncate_to_target_usize(&self, val: u64) -> u64 {
43+
self.pointer_size().truncate(val.into()).try_into().unwrap()
9244
}
9345

9446
#[inline]
95-
fn signed_offset<'tcx>(&self, val: u64, i: i64) -> InterpResult<'tcx, u64> {
96-
let (res, over) = self.overflowing_signed_offset(val, i);
97-
if over { throw_ub!(PointerArithOverflow) } else { Ok(res) }
47+
fn sign_extend_to_target_isize(&self, val: u64) -> i64 {
48+
self.pointer_size().sign_extend(val.into()).try_into().unwrap()
9849
}
9950
}
10051

@@ -330,7 +281,7 @@ impl<Prov> Pointer<Option<Prov>> {
330281
}
331282
}
332283

333-
impl<'tcx, Prov> Pointer<Prov> {
284+
impl<Prov> Pointer<Prov> {
334285
#[inline(always)]
335286
pub fn new(provenance: Prov, offset: Size) -> Self {
336287
Pointer { provenance, offset }
@@ -348,43 +299,16 @@ impl<'tcx, Prov> Pointer<Prov> {
348299
Pointer { provenance: f(self.provenance), ..self }
349300
}
350301

351-
#[inline]
352-
pub fn offset(self, i: Size, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> {
353-
Ok(Pointer {
354-
offset: Size::from_bytes(cx.data_layout().offset(self.offset.bytes(), i.bytes())?),
355-
..self
356-
})
357-
}
358-
359-
#[inline]
360-
pub fn overflowing_offset(self, i: Size, cx: &impl HasDataLayout) -> (Self, bool) {
361-
let (res, over) = cx.data_layout().overflowing_offset(self.offset.bytes(), i.bytes());
362-
let ptr = Pointer { offset: Size::from_bytes(res), ..self };
363-
(ptr, over)
364-
}
365-
366302
#[inline(always)]
367303
pub fn wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self {
368-
self.overflowing_offset(i, cx).0
369-
}
370-
371-
#[inline]
372-
pub fn signed_offset(self, i: i64, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> {
373-
Ok(Pointer {
374-
offset: Size::from_bytes(cx.data_layout().signed_offset(self.offset.bytes(), i)?),
375-
..self
376-
})
377-
}
378-
379-
#[inline]
380-
pub fn overflowing_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> (Self, bool) {
381-
let (res, over) = cx.data_layout().overflowing_signed_offset(self.offset.bytes(), i);
382-
let ptr = Pointer { offset: Size::from_bytes(res), ..self };
383-
(ptr, over)
304+
let res =
305+
cx.data_layout().truncate_to_target_usize(self.offset.bytes().wrapping_add(i.bytes()));
306+
Pointer { offset: Size::from_bytes(res), ..self }
384307
}
385308

386309
#[inline(always)]
387310
pub fn wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self {
388-
self.overflowing_signed_offset(i, cx).0
311+
// It's wrapping anyway, so we can just cast to `u64`.
312+
self.wrapping_offset(Size::from_bytes(i as u64), cx)
389313
}
390314
}

compiler/rustc_middle/src/mir/interpret/value.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -397,7 +397,7 @@ impl<'tcx, Prov: Provenance> Scalar<Prov> {
397397
#[inline]
398398
pub fn to_int(self, size: Size) -> InterpResult<'tcx, i128> {
399399
let b = self.to_bits(size)?;
400-
Ok(size.sign_extend(b) as i128)
400+
Ok(size.sign_extend(b))
401401
}
402402

403403
/// Converts the scalar to produce an `i8`. Fails if the scalar is a pointer.

compiler/rustc_middle/src/ty/consts/int.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ impl ScalarInt {
233233
let data = i.into();
234234
// `into` performed sign extension, we have to truncate
235235
let r = Self::raw(size.truncate(data as u128), size);
236-
(r, size.sign_extend(r.data) as i128 != data)
236+
(r, size.sign_extend(r.data) != data)
237237
}
238238

239239
#[inline]
@@ -334,7 +334,7 @@ impl ScalarInt {
334334
#[inline]
335335
pub fn to_int(self, size: Size) -> i128 {
336336
let b = self.to_bits(size);
337-
size.sign_extend(b) as i128
337+
size.sign_extend(b)
338338
}
339339

340340
/// Converts the `ScalarInt` to i8.

compiler/rustc_middle/src/ty/util.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ impl<'tcx> Discr<'tcx> {
7878
let (val, oflo) = if signed {
7979
let min = size.signed_int_min();
8080
let max = size.signed_int_max();
81-
let val = size.sign_extend(self.val) as i128;
81+
let val = size.sign_extend(self.val);
8282
assert!(n < (i128::MAX as u128));
8383
let n = n as i128;
8484
let oflo = val > max - n;

src/tools/miri/src/alloc_addresses/mod.rs

+10-14
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use rand::Rng;
1111

1212
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
1313
use rustc_span::Span;
14-
use rustc_target::abi::{Align, HasDataLayout, Size};
14+
use rustc_target::abi::{Align, Size};
1515

1616
use crate::{concurrency::VClock, *};
1717

@@ -307,15 +307,15 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
307307

308308
let (prov, offset) = ptr.into_parts(); // offset is relative (AllocId provenance)
309309
let alloc_id = prov.alloc_id();
310-
let base_addr = ecx.addr_from_alloc_id(alloc_id, kind)?;
311310

312-
// Add offset with the right kind of pointer-overflowing arithmetic.
313-
let dl = ecx.data_layout();
314-
let absolute_addr = dl.overflowing_offset(base_addr, offset.bytes()).0;
315-
Ok(interpret::Pointer::new(
311+
// Get a pointer to the beginning of this allocation.
312+
let base_addr = ecx.addr_from_alloc_id(alloc_id, kind)?;
313+
let base_ptr = interpret::Pointer::new(
316314
Provenance::Concrete { alloc_id, tag },
317-
Size::from_bytes(absolute_addr),
318-
))
315+
Size::from_bytes(base_addr),
316+
);
317+
// Add offset with the right kind of pointer-overflowing arithmetic.
318+
Ok(base_ptr.wrapping_offset(offset, ecx))
319319
}
320320

321321
/// When a pointer is used for a memory access, this computes where in which allocation the
@@ -341,12 +341,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
341341
let base_addr = *ecx.machine.alloc_addresses.borrow().base_addr.get(&alloc_id).unwrap();
342342

343343
// Wrapping "addr - base_addr"
344-
#[allow(clippy::cast_possible_wrap)] // we want to wrap here
345-
let neg_base_addr = (base_addr as i64).wrapping_neg();
346-
Some((
347-
alloc_id,
348-
Size::from_bytes(ecx.overflowing_signed_offset(addr.bytes(), neg_base_addr).0),
349-
))
344+
let rel_offset = ecx.truncate_to_target_usize(addr.bytes().wrapping_sub(base_addr));
345+
Some((alloc_id, Size::from_bytes(rel_offset)))
350346
}
351347
}
352348

src/tools/miri/src/helpers.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -606,7 +606,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
606606
}
607607
// The part between the end_ptr and the end of the place is also frozen.
608608
// So pretend there is a 0-sized `UnsafeCell` at the end.
609-
unsafe_cell_action(&place.ptr().offset(size, this)?, Size::ZERO)?;
609+
unsafe_cell_action(&place.ptr().wrapping_offset(size, this), Size::ZERO)?;
610610
// Done!
611611
return Ok(());
612612

@@ -975,7 +975,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
975975
loop {
976976
// FIXME: We are re-getting the allocation each time around the loop.
977977
// Would be nice if we could somehow "extend" an existing AllocRange.
978-
let alloc = this.get_ptr_alloc(ptr.offset(len, this)?, size1)?.unwrap(); // not a ZST, so we will get a result
978+
let alloc = this.get_ptr_alloc(ptr.wrapping_offset(len, this), size1)?.unwrap(); // not a ZST, so we will get a result
979979
let byte = alloc.read_integer(alloc_range(Size::ZERO, size1))?.to_u8()?;
980980
if byte == 0 {
981981
break;
@@ -1039,7 +1039,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
10391039
break;
10401040
} else {
10411041
wchars.push(wchar_int.try_into().unwrap());
1042-
ptr = ptr.offset(size, this)?;
1042+
ptr = ptr.wrapping_offset(size, this);
10431043
}
10441044
}
10451045

src/tools/miri/src/shims/foreign_items.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -622,7 +622,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
622622
{
623623
let idx = u64::try_from(idx).unwrap();
624624
#[allow(clippy::arithmetic_side_effects)] // idx < num, so this never wraps
625-
let new_ptr = ptr.offset(Size::from_bytes(num - idx - 1), this)?;
625+
let new_ptr = ptr.wrapping_offset(Size::from_bytes(num - idx - 1), this);
626626
this.write_pointer(new_ptr, dest)?;
627627
} else {
628628
this.write_null(dest)?;
@@ -646,7 +646,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
646646
.iter()
647647
.position(|&c| c == val);
648648
if let Some(idx) = idx {
649-
let new_ptr = ptr.offset(Size::from_bytes(idx as u64), this)?;
649+
let new_ptr = ptr.wrapping_offset(Size::from_bytes(idx as u64), this);
650650
this.write_pointer(new_ptr, dest)?;
651651
} else {
652652
this.write_null(dest)?;

src/tools/miri/src/shims/unix/env.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ impl<'tcx> UnixEnvVars<'tcx> {
8282
};
8383
// The offset is used to strip the "{name}=" part of the string.
8484
let var_ptr = var_ptr
85-
.offset(Size::from_bytes(u64::try_from(name.len()).unwrap().strict_add(1)), ecx)?;
85+
.wrapping_offset(Size::from_bytes(u64::try_from(name.len()).unwrap().strict_add(1)), ecx);
8686
Ok(Some(var_ptr))
8787
}
8888

src/tools/miri/src/shims/unix/fs.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -928,7 +928,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
928928
&this.ptr_to_mplace(entry, dirent64_layout),
929929
)?;
930930

931-
let name_ptr = entry.offset(Size::from_bytes(d_name_offset), this)?;
931+
let name_ptr = entry.wrapping_offset(Size::from_bytes(d_name_offset), this);
932932
this.write_bytes_ptr(name_ptr, name_bytes.iter().copied())?;
933933

934934
Some(entry)

src/tools/miri/src/shims/unix/linux/mem.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
5353
// We just allocated this, the access is definitely in-bounds and fits into our address space.
5454
// mmap guarantees new mappings are zero-init.
5555
this.write_bytes_ptr(
56-
ptr.offset(Size::from_bytes(old_size), this).unwrap().into(),
56+
ptr.wrapping_offset(Size::from_bytes(old_size), this).into(),
5757
std::iter::repeat(0u8).take(usize::try_from(increase).unwrap()),
5858
)
5959
.unwrap();

0 commit comments

Comments
 (0)