Skip to content

Commit ea22adb

Browse files
committed
adjust constValue::Slice to work for arbitrary slice types
1 parent 0692db1 commit ea22adb

File tree

12 files changed

+75
-63
lines changed

12 files changed

+75
-63
lines changed

Diff for: compiler/rustc_codegen_cranelift/src/constant.rs

+4-8
Original file line numberDiff line numberDiff line change
@@ -184,15 +184,11 @@ pub(crate) fn codegen_const_value<'tcx>(
184184
.offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
185185
layout,
186186
),
187-
ConstValue::Slice { data, start, end } => {
187+
ConstValue::Slice { data, meta } => {
188188
let alloc_id = fx.tcx.reserve_and_set_memory_alloc(data);
189-
let ptr = pointer_for_allocation(fx, alloc_id)
190-
.offset_i64(fx, i64::try_from(start).unwrap())
191-
.get_addr(fx);
192-
let len = fx
193-
.bcx
194-
.ins()
195-
.iconst(fx.pointer_type, i64::try_from(end.checked_sub(start).unwrap()).unwrap());
189+
let ptr = pointer_for_allocation(fx, alloc_id).get_addr(fx);
190+
// FIXME: the `try_from` here can actually fail, e.g. for very long ZST slices.
191+
let len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(meta).unwrap());
196192
CValue::by_val_pair(ptr, len, layout)
197193
}
198194
}

Diff for: compiler/rustc_codegen_ssa/src/mir/operand.rs

+3-6
Original file line numberDiff line numberDiff line change
@@ -100,23 +100,20 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> {
100100
OperandValue::Immediate(llval)
101101
}
102102
ConstValue::ZeroSized => return OperandRef::zero_sized(layout),
103-
ConstValue::Slice { data, start, end } => {
103+
ConstValue::Slice { data, meta } => {
104104
let Abi::ScalarPair(a_scalar, _) = layout.abi else {
105105
bug!("from_const: invalid ScalarPair layout: {:#?}", layout);
106106
};
107107
let a = Scalar::from_pointer(
108-
Pointer::new(
109-
bx.tcx().reserve_and_set_memory_alloc(data),
110-
Size::from_bytes(start),
111-
),
108+
Pointer::new(bx.tcx().reserve_and_set_memory_alloc(data), Size::ZERO),
112109
&bx.tcx(),
113110
);
114111
let a_llval = bx.scalar_to_backend(
115112
a,
116113
a_scalar,
117114
bx.scalar_pair_element_backend_type(layout, 0, true),
118115
);
119-
let b_llval = bx.const_usize((end - start) as u64);
116+
let b_llval = bx.const_usize(meta);
120117
OperandValue::Pair(a_llval, b_llval)
121118
}
122119
ConstValue::Indirect { alloc_id, offset } => {

Diff for: compiler/rustc_const_eval/src/const_eval/eval_queries.rs

+16-9
Original file line numberDiff line numberDiff line change
@@ -151,19 +151,26 @@ pub(super) fn op_to_const<'tcx>(
151151
Immediate::Scalar(x) => ConstValue::Scalar(x),
152152
Immediate::ScalarPair(a, b) => {
153153
debug!("ScalarPair(a: {:?}, b: {:?})", a, b);
154-
// FIXME: assert that this has an appropriate type.
155-
// Currently we actually get here for non-[u8] slices during valtree construction!
156-
let msg = "`op_to_const` on an immediate scalar pair must only be used on slice references to actually allocated memory";
154+
// This codepath solely exists for `valtree_to_const_value` to not need to generate
155+
// a `ConstValue::Indirect` for wide references, so it is tightly restricted to just
156+
// that case.
157+
let pointee_ty = imm.layout.ty.builtin_deref(false).unwrap().ty; // `false` = no raw ptrs
158+
debug_assert!(
159+
matches!(
160+
ecx.tcx.struct_tail_without_normalization(pointee_ty).kind(),
161+
ty::Str | ty::Slice(..),
162+
),
163+
"`ConstValue::Slice` is for slice-tailed types only, but got {}",
164+
imm.layout.ty,
165+
);
166+
let msg = "`op_to_const` on an immediate scalar pair must only be used on slice references to the beginning of an actual allocation";
157167
// We know `offset` is relative to the allocation, so we can use `into_parts`.
158-
// We use `ConstValue::Slice` so that we don't have to generate an allocation for
159-
// `ConstValue::Indirect` here.
160168
let (alloc_id, offset) = a.to_pointer(ecx).expect(msg).into_parts();
161169
let alloc_id = alloc_id.expect(msg);
162170
let data = ecx.tcx.global_alloc(alloc_id).unwrap_memory();
163-
let start = offset.bytes_usize();
164-
let len = b.to_target_usize(ecx).expect(msg);
165-
let len: usize = len.try_into().unwrap();
166-
ConstValue::Slice { data, start, end: start + len }
171+
assert!(offset == abi::Size::ZERO, "{}", msg);
172+
let meta = b.to_target_usize(ecx).expect(msg);
173+
ConstValue::Slice { data, meta }
167174
}
168175
Immediate::Uninit => bug!("`Uninit` is not a valid value for {}", op.layout.ty),
169176
},

Diff for: compiler/rustc_const_eval/src/interpret/cast.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -351,7 +351,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
351351

352352
match (&src_pointee_ty.kind(), &dest_pointee_ty.kind()) {
353353
(&ty::Array(_, length), &ty::Slice(_)) => {
354-
let ptr = self.read_scalar(src)?;
354+
let ptr = self.read_pointer(src)?;
355355
// u64 cast is from usize to u64, which is always good
356356
let val = Immediate::new_slice(
357357
ptr,
@@ -367,6 +367,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
367367
return self.write_immediate(*val, dest);
368368
}
369369
let (old_data, old_vptr) = val.to_scalar_pair();
370+
let old_data = old_data.to_pointer(self)?;
370371
let old_vptr = old_vptr.to_pointer(self)?;
371372
let (ty, old_trait) = self.get_ptr_vtable(old_vptr)?;
372373
if old_trait != data_a.principal() {
@@ -378,7 +379,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
378379
(_, &ty::Dynamic(data, _, ty::Dyn)) => {
379380
// Initial cast from sized to dyn trait
380381
let vtable = self.get_vtable_ptr(src_pointee_ty, data.principal())?;
381-
let ptr = self.read_scalar(src)?;
382+
let ptr = self.read_pointer(src)?;
382383
let val = Immediate::new_dyn_trait(ptr, vtable, &*self.tcx);
383384
self.write_immediate(val, dest)
384385
}

Diff for: compiler/rustc_const_eval/src/interpret/intrinsics.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ pub(crate) fn eval_nullary_intrinsic<'tcx>(
6262
sym::type_name => {
6363
ensure_monomorphic_enough(tcx, tp_ty)?;
6464
let alloc = alloc_type_name(tcx, tp_ty);
65-
ConstValue::Slice { data: alloc, start: 0, end: alloc.inner().len() }
65+
ConstValue::Slice { data: alloc, meta: alloc.inner().size().bytes() }
6666
}
6767
sym::needs_drop => {
6868
ensure_monomorphic_enough(tcx, tp_ty)?;

Diff for: compiler/rustc_const_eval/src/interpret/operand.rs

+18-15
Original file line numberDiff line numberDiff line change
@@ -43,24 +43,30 @@ impl<Prov: Provenance> From<Scalar<Prov>> for Immediate<Prov> {
4343
}
4444

4545
impl<Prov: Provenance> Immediate<Prov> {
46-
pub fn from_pointer(p: Pointer<Prov>, cx: &impl HasDataLayout) -> Self {
47-
Immediate::Scalar(Scalar::from_pointer(p, cx))
46+
pub fn from_pointer(ptr: Pointer<Prov>, cx: &impl HasDataLayout) -> Self {
47+
Immediate::Scalar(Scalar::from_pointer(ptr, cx))
4848
}
4949

50-
pub fn from_maybe_pointer(p: Pointer<Option<Prov>>, cx: &impl HasDataLayout) -> Self {
51-
Immediate::Scalar(Scalar::from_maybe_pointer(p, cx))
50+
pub fn from_maybe_pointer(ptr: Pointer<Option<Prov>>, cx: &impl HasDataLayout) -> Self {
51+
Immediate::Scalar(Scalar::from_maybe_pointer(ptr, cx))
5252
}
5353

54-
pub fn new_slice(val: Scalar<Prov>, len: u64, cx: &impl HasDataLayout) -> Self {
55-
Immediate::ScalarPair(val, Scalar::from_target_usize(len, cx))
54+
pub fn new_slice(ptr: Pointer<Option<Prov>>, len: u64, cx: &impl HasDataLayout) -> Self {
55+
Immediate::ScalarPair(
56+
Scalar::from_maybe_pointer(ptr, cx),
57+
Scalar::from_target_usize(len, cx),
58+
)
5659
}
5760

5861
pub fn new_dyn_trait(
59-
val: Scalar<Prov>,
62+
val: Pointer<Option<Prov>>,
6063
vtable: Pointer<Option<Prov>>,
6164
cx: &impl HasDataLayout,
6265
) -> Self {
63-
Immediate::ScalarPair(val, Scalar::from_maybe_pointer(vtable, cx))
66+
Immediate::ScalarPair(
67+
Scalar::from_maybe_pointer(val, cx),
68+
Scalar::from_maybe_pointer(vtable, cx),
69+
)
6470
}
6571

6672
#[inline]
@@ -722,16 +728,13 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
722728
}
723729
mir::ConstValue::Scalar(x) => Operand::Immediate(adjust_scalar(x)?.into()),
724730
mir::ConstValue::ZeroSized => Operand::Immediate(Immediate::Uninit),
725-
mir::ConstValue::Slice { data, start, end } => {
731+
mir::ConstValue::Slice { data, meta } => {
726732
// We rely on mutability being set correctly in `data` to prevent writes
727733
// where none should happen.
728-
let ptr = Pointer::new(
729-
self.tcx.reserve_and_set_memory_alloc(data),
730-
Size::from_bytes(start), // offset: `start`
731-
);
734+
let ptr = Pointer::new(self.tcx.reserve_and_set_memory_alloc(data), Size::ZERO);
732735
Operand::Immediate(Immediate::new_slice(
733-
Scalar::from_pointer(self.global_base_pointer(ptr)?, &*self.tcx),
734-
u64::try_from(end.checked_sub(start).unwrap()).unwrap(), // len: `end - start`
736+
self.global_base_pointer(ptr)?.into(),
737+
meta,
735738
self,
736739
))
737740
}

Diff for: compiler/rustc_middle/src/mir/consts.rs

+18-9
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,20 @@ pub enum ConstValue<'tcx> {
4141
/// Only for ZSTs.
4242
ZeroSized,
4343

44-
/// Used for `&[u8]` and `&str`.
44+
/// Used for references to unsized types with slice tail.
4545
///
46-
/// This is worth an optimized representation since Rust has literals of these types.
47-
/// Not having to indirect those through an `AllocId` (or two, if we used `Indirect`) has shown
48-
/// measurable performance improvements on stress tests.
49-
Slice { data: ConstAllocation<'tcx>, start: usize, end: usize },
46+
/// This is worth an optimized representation since Rust has literals of type `&str` and
47+
/// `&[u8]`. Not having to indirect those through an `AllocId` (or two, if we used `Indirect`)
48+
/// has shown measurable performance improvements on stress tests. We then reuse this
49+
/// optimization for slice-tail types more generally during valtree-to-constval conversion.
50+
Slice {
51+
/// The allocation storing the slice contents.
52+
/// This always points to the beginning of the allocation.
53+
data: ConstAllocation<'tcx>,
54+
/// The metadata field of the reference.
55+
/// This is a "target usize", so we use `u64` as in the interpreter.
56+
meta: u64,
57+
},
5058

5159
/// A value not representable by the other variants; needs to be stored in-memory.
5260
///
@@ -65,7 +73,7 @@ pub enum ConstValue<'tcx> {
6573
}
6674

6775
#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
68-
static_assert_size!(ConstValue<'_>, 32);
76+
static_assert_size!(ConstValue<'_>, 24);
6977

7078
impl<'tcx> ConstValue<'tcx> {
7179
#[inline]
@@ -124,7 +132,7 @@ impl<'tcx> ConstValue<'tcx> {
124132
ConstValue::Scalar(_) | ConstValue::ZeroSized => {
125133
bug!("`try_get_slice_bytes` on non-slice constant")
126134
}
127-
&ConstValue::Slice { data, start, end } => (data, start, end),
135+
&ConstValue::Slice { data, meta } => (data, 0, meta),
128136
&ConstValue::Indirect { alloc_id, offset } => {
129137
// The reference itself is stored behind an indirection.
130138
// Load the reference, and then load the actual slice contents.
@@ -151,18 +159,19 @@ impl<'tcx> ConstValue<'tcx> {
151159
)
152160
.ok()?;
153161
let len = len.to_target_usize(&tcx).ok()?;
154-
let len: usize = len.try_into().ok()?;
155162
if len == 0 {
156163
return Some(&[]);
157164
}
158165
// Non-empty slice, must have memory. We know this is a relative pointer.
159166
let (inner_alloc_id, offset) = ptr.into_parts();
160167
let data = tcx.global_alloc(inner_alloc_id?).unwrap_memory();
161-
(data, offset.bytes_usize(), offset.bytes_usize() + len)
168+
(data, offset.bytes(), offset.bytes() + len)
162169
}
163170
};
164171

165172
// This is for diagnostics only, so we are okay to use `inspect_with_uninit_and_ptr_outside_interpreter`.
173+
let start = start.try_into().unwrap();
174+
let end = end.try_into().unwrap();
166175
Some(data.inner().inspect_with_uninit_and_ptr_outside_interpreter(start..end))
167176
}
168177
}

Diff for: compiler/rustc_middle/src/ty/structural_impls.rs

+1
Original file line numberDiff line numberDiff line change
@@ -457,6 +457,7 @@ TrivialLiftImpls! {
457457
(),
458458
bool,
459459
usize,
460+
u64,
460461
}
461462

462463
// For some things about which the type library does not know, or does not

Diff for: compiler/rustc_mir_build/src/build/expr/as_constant.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -131,14 +131,14 @@ fn lit_to_mir_constant<'tcx>(
131131
let s = s.as_str();
132132
let allocation = Allocation::from_bytes_byte_aligned_immutable(s.as_bytes());
133133
let allocation = tcx.mk_const_alloc(allocation);
134-
ConstValue::Slice { data: allocation, start: 0, end: s.len() }
134+
ConstValue::Slice { data: allocation, meta: allocation.inner().size().bytes() }
135135
}
136136
(ast::LitKind::ByteStr(data, _), ty::Ref(_, inner_ty, _))
137137
if matches!(inner_ty.kind(), ty::Slice(_)) =>
138138
{
139139
let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8]);
140140
let allocation = tcx.mk_const_alloc(allocation);
141-
ConstValue::Slice { data: allocation, start: 0, end: data.len() }
141+
ConstValue::Slice { data: allocation, meta: allocation.inner().size().bytes() }
142142
}
143143
(ast::LitKind::ByteStr(data, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
144144
let id = tcx.allocate_bytes(data);
@@ -148,7 +148,7 @@ fn lit_to_mir_constant<'tcx>(
148148
{
149149
let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8]);
150150
let allocation = tcx.mk_const_alloc(allocation);
151-
ConstValue::Slice { data: allocation, start: 0, end: data.len() }
151+
ConstValue::Slice { data: allocation, meta: allocation.inner().size().bytes() }
152152
}
153153
(ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
154154
ConstValue::Scalar(Scalar::from_uint(*n, Size::from_bytes(1)))

Diff for: compiler/rustc_monomorphize/src/collector.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1449,7 +1449,7 @@ fn collect_const_value<'tcx>(
14491449
collect_alloc(tcx, ptr.provenance, output)
14501450
}
14511451
mir::ConstValue::Indirect { alloc_id, .. } => collect_alloc(tcx, alloc_id, output),
1452-
mir::ConstValue::Slice { data, start: _, end: _ } => {
1452+
mir::ConstValue::Slice { data, meta: _ } => {
14531453
for &id in data.inner().provenance().ptrs().values() {
14541454
collect_alloc(tcx, id, output);
14551455
}

Diff for: compiler/rustc_smir/src/rustc_smir/alloc.rs

+6-8
Original file line numberDiff line numberDiff line change
@@ -47,14 +47,12 @@ pub fn new_allocation<'tcx>(
4747
tables.tcx.layout_of(rustc_middle::ty::ParamEnv::empty().and(ty)).unwrap().align;
4848
new_empty_allocation(align.abi)
4949
}
50-
ConstValue::Slice { data, start, end } => {
50+
ConstValue::Slice { data, meta } => {
5151
let alloc_id = tables.tcx.reserve_and_set_memory_alloc(data);
52-
let ptr = Pointer::new(alloc_id, rustc_target::abi::Size::from_bytes(start));
52+
let ptr = Pointer::new(alloc_id, rustc_target::abi::Size::ZERO);
5353
let scalar_ptr = rustc_middle::mir::interpret::Scalar::from_pointer(ptr, &tables.tcx);
54-
let scalar_len = rustc_middle::mir::interpret::Scalar::from_target_usize(
55-
(end - start) as u64,
56-
&tables.tcx,
57-
);
54+
let scalar_meta =
55+
rustc_middle::mir::interpret::Scalar::from_target_usize(meta, &tables.tcx);
5856
let layout =
5957
tables.tcx.layout_of(rustc_middle::ty::ParamEnv::reveal_all().and(ty)).unwrap();
6058
let mut allocation =
@@ -69,8 +67,8 @@ pub fn new_allocation<'tcx>(
6967
allocation
7068
.write_scalar(
7169
&tables.tcx,
72-
alloc_range(tables.tcx.data_layout.pointer_size, scalar_len.size()),
73-
scalar_len,
70+
alloc_range(tables.tcx.data_layout.pointer_size, scalar_meta.size()),
71+
scalar_meta,
7472
)
7573
.unwrap();
7674
allocation.stable(tables)

Diff for: src/tools/miri/src/shims/backtrace.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
8989
}
9090

9191
this.write_immediate(
92-
Immediate::new_slice(Scalar::from_maybe_pointer(alloc.ptr(), this), len, this),
92+
Immediate::new_slice(alloc.ptr(), len, this),
9393
dest,
9494
)?;
9595
}

0 commit comments

Comments
 (0)