Skip to content

Commit 3c71aef

Browse files
committed
extend allocbytes with associated type
1 parent 3de4f1c commit 3c71aef

File tree

16 files changed

+88
-30
lines changed

16 files changed

+88
-30
lines changed

compiler/rustc_const_eval/src/const_eval/dummy_machine.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,4 +197,9 @@ impl<'tcx> interpret::Machine<'tcx> for DummyMachine {
197197
) -> &'a mut Vec<interpret::Frame<'tcx, Self::Provenance, Self::FrameExtra>> {
198198
unimplemented!()
199199
}
200+
201+
fn get_default_byte_mdata(
202+
&self,
203+
) -> <Self::Bytes as rustc_middle::mir::interpret::AllocBytes>::ByteMetadata {
204+
}
200205
}

compiler/rustc_const_eval/src/const_eval/machine.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -735,6 +735,8 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
735735
Cow::Owned(compute_range())
736736
}
737737
}
738+
739+
fn get_default_byte_mdata(&self) -> <Self::Bytes as mir::interpret::AllocBytes>::ByteMetadata {}
738740
}
739741

740742
// Please do not add any code below the above `Machine` trait impl. I (oli-obk) plan more cleanups

compiler/rustc_const_eval/src/interpret/intrinsics.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ use crate::fluent_generated as fluent;
2626
/// Directly returns an `Allocation` containing an absolute path representation of the given type.
2727
pub(crate) fn alloc_type_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ConstAllocation<'tcx> {
2828
let path = crate::util::type_name(tcx, ty);
29-
let alloc = Allocation::from_bytes_byte_aligned_immutable(path.into_bytes());
29+
let alloc = Allocation::from_bytes_byte_aligned_immutable(path.into_bytes(), ());
3030
tcx.mk_const_alloc(alloc)
3131
}
3232

compiler/rustc_const_eval/src/interpret/machine.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -628,6 +628,8 @@ pub trait Machine<'tcx>: Sized {
628628
// Default to no caching.
629629
Cow::Owned(compute_range())
630630
}
631+
632+
fn get_default_byte_mdata(&self) -> <Self::Bytes as AllocBytes>::ByteMetadata;
631633
}
632634

633635
/// A lot of the flexibility above is just needed for `Miri`, but all "compile-time" machines

compiler/rustc_const_eval/src/interpret/memory.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -233,10 +233,11 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
233233
kind: MemoryKind<M::MemoryKind>,
234234
init: AllocInit,
235235
) -> InterpResult<'tcx, Pointer<M::Provenance>> {
236+
let dsc = self.machine.get_default_byte_mdata();
236237
let alloc = if M::PANIC_ON_ALLOC_FAIL {
237-
Allocation::new(size, align, init)
238+
Allocation::new(size, align, init, dsc)
238239
} else {
239-
Allocation::try_new(size, align, init)?
240+
Allocation::try_new(size, align, init, dsc)?
240241
};
241242
self.insert_allocation(alloc, kind)
242243
}
@@ -248,7 +249,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
248249
kind: MemoryKind<M::MemoryKind>,
249250
mutability: Mutability,
250251
) -> InterpResult<'tcx, Pointer<M::Provenance>> {
251-
let alloc = Allocation::from_bytes(bytes, align, mutability);
252+
let dsc = self.machine.get_default_byte_mdata();
253+
let alloc = Allocation::from_bytes(bytes, align, mutability, dsc);
252254
self.insert_allocation(alloc, kind)
253255
}
254256

compiler/rustc_const_eval/src/interpret/util.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ pub(crate) fn create_static_alloc<'tcx>(
3838
static_def_id: LocalDefId,
3939
layout: TyAndLayout<'tcx>,
4040
) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
41-
let alloc = Allocation::try_new(layout.size, layout.align.abi, AllocInit::Uninit)?;
41+
let alloc = Allocation::try_new(layout.size, layout.align.abi, AllocInit::Uninit, ())?;
4242
let alloc_id = ecx.tcx.reserve_and_set_static_alloc(static_def_id.into());
4343
assert_eq!(ecx.machine.static_root_ids, None);
4444
ecx.machine.static_root_ids = Some((alloc_id, static_def_id));

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

Lines changed: 48 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,20 @@ use crate::ty;
2727

2828
/// Functionality required for the bytes of an `Allocation`.
2929
pub trait AllocBytes: Clone + fmt::Debug + Deref<Target = [u8]> + DerefMut<Target = [u8]> {
30+
/// Used for giving extra metadata on creation. Miri uses this to allow
31+
/// machine memory to be allocated separately from other allocations.
32+
type ByteMetadata: Clone + fmt::Debug;
33+
3034
/// Create an `AllocBytes` from a slice of `u8`.
31-
fn from_bytes<'a>(slice: impl Into<Cow<'a, [u8]>>, _align: Align) -> Self;
35+
fn from_bytes<'a>(
36+
slice: impl Into<Cow<'a, [u8]>>,
37+
_align: Align,
38+
_dsc: Self::ByteMetadata,
39+
) -> Self;
3240

3341
/// Create a zeroed `AllocBytes` of the specified size and alignment.
3442
/// Returns `None` if we ran out of memory on the host.
35-
fn zeroed(size: Size, _align: Align) -> Option<Self>;
43+
fn zeroed(size: Size, _align: Align, _dsc: Self::ByteMetadata) -> Option<Self>;
3644

3745
/// Gives direct access to the raw underlying storage.
3846
///
@@ -47,15 +55,20 @@ pub trait AllocBytes: Clone + fmt::Debug + Deref<Target = [u8]> + DerefMut<Targe
4755
/// - other pointers returned by this method, and
4856
/// - references returned from `deref()`, as long as there was no write.
4957
fn as_ptr(&self) -> *const u8;
58+
59+
/// Gets the allocation metadata.
60+
fn get_mdata(&self) -> Self::ByteMetadata;
5061
}
5162

5263
/// Default `bytes` for `Allocation` is a `Box<u8>`.
5364
impl AllocBytes for Box<[u8]> {
54-
fn from_bytes<'a>(slice: impl Into<Cow<'a, [u8]>>, _align: Align) -> Self {
65+
type ByteMetadata = ();
66+
67+
fn from_bytes<'a>(slice: impl Into<Cow<'a, [u8]>>, _align: Align, _dsc: ()) -> Self {
5568
Box::<[u8]>::from(slice.into())
5669
}
5770

58-
fn zeroed(size: Size, _align: Align) -> Option<Self> {
71+
fn zeroed(size: Size, _align: Align, _dsc: ()) -> Option<Self> {
5972
let bytes = Box::<[u8]>::try_new_zeroed_slice(size.bytes().try_into().ok()?).ok()?;
6073
// SAFETY: the box was zero-allocated, which is a valid initial value for Box<[u8]>
6174
let bytes = unsafe { bytes.assume_init() };
@@ -69,6 +82,8 @@ impl AllocBytes for Box<[u8]> {
6982
fn as_ptr(&self) -> *const u8 {
7083
Box::as_ptr(self).cast()
7184
}
85+
86+
fn get_mdata(&self) -> () {}
7287
}
7388

7489
/// This type represents an Allocation in the Miri/CTFE core engine.
@@ -175,6 +190,7 @@ fn all_zero(buf: &[u8]) -> bool {
175190
impl<Prov: Provenance, Extra, Bytes, E: Encoder> Encodable<E> for Allocation<Prov, Extra, Bytes>
176191
where
177192
Bytes: AllocBytes,
193+
Bytes::ByteMetadata: Encodable<E>,
178194
ProvenanceMap<Prov>: Encodable<E>,
179195
Extra: Encodable<E>,
180196
{
@@ -186,6 +202,7 @@ where
186202
if !all_zero {
187203
encoder.emit_raw_bytes(&self.bytes);
188204
}
205+
self.bytes.get_mdata().encode(encoder);
189206
self.provenance.encode(encoder);
190207
self.init_mask.encode(encoder);
191208
self.extra.encode(encoder);
@@ -195,6 +212,7 @@ where
195212
impl<Prov: Provenance, Extra, Bytes, D: Decoder> Decodable<D> for Allocation<Prov, Extra, Bytes>
196213
where
197214
Bytes: AllocBytes,
215+
Bytes::ByteMetadata: Decodable<D>,
198216
ProvenanceMap<Prov>: Decodable<D>,
199217
Extra: Decodable<D>,
200218
{
@@ -203,7 +221,9 @@ where
203221

204222
let len = decoder.read_usize();
205223
let bytes = if all_zero { vec![0u8; len] } else { decoder.read_raw_bytes(len).to_vec() };
206-
let bytes = Bytes::from_bytes(bytes, align);
224+
225+
let mdata = Decodable::decode(decoder);
226+
let bytes = Bytes::from_bytes(bytes, align, mdata);
207227

208228
let provenance = Decodable::decode(decoder);
209229
let init_mask = Decodable::decode(decoder);
@@ -395,8 +415,9 @@ impl<Prov: Provenance, Bytes: AllocBytes> Allocation<Prov, (), Bytes> {
395415
slice: impl Into<Cow<'a, [u8]>>,
396416
align: Align,
397417
mutability: Mutability,
418+
dsc: <Bytes as AllocBytes>::ByteMetadata,
398419
) -> Self {
399-
let bytes = Bytes::from_bytes(slice, align);
420+
let bytes = Bytes::from_bytes(slice, align, dsc);
400421
let size = Size::from_bytes(bytes.len());
401422
Self {
402423
bytes,
@@ -408,14 +429,18 @@ impl<Prov: Provenance, Bytes: AllocBytes> Allocation<Prov, (), Bytes> {
408429
}
409430
}
410431

411-
pub fn from_bytes_byte_aligned_immutable<'a>(slice: impl Into<Cow<'a, [u8]>>) -> Self {
412-
Allocation::from_bytes(slice, Align::ONE, Mutability::Not)
432+
pub fn from_bytes_byte_aligned_immutable<'a>(
433+
slice: impl Into<Cow<'a, [u8]>>,
434+
dsc: <Bytes as AllocBytes>::ByteMetadata,
435+
) -> Self {
436+
Allocation::from_bytes(slice, Align::ONE, Mutability::Not, dsc)
413437
}
414438

415439
fn new_inner<R>(
416440
size: Size,
417441
align: Align,
418442
init: AllocInit,
443+
dsc: <Bytes as AllocBytes>::ByteMetadata,
419444
fail: impl FnOnce() -> R,
420445
) -> Result<Self, R> {
421446
// We raise an error if we cannot create the allocation on the host.
@@ -424,7 +449,7 @@ impl<Prov: Provenance, Bytes: AllocBytes> Allocation<Prov, (), Bytes> {
424449
// deterministic. However, we can be non-deterministic here because all uses of const
425450
// evaluation (including ConstProp!) will make compilation fail (via hard error
426451
// or ICE) upon encountering a `MemoryExhausted` error.
427-
let bytes = Bytes::zeroed(size, align).ok_or_else(fail)?;
452+
let bytes = Bytes::zeroed(size, align, dsc).ok_or_else(fail)?;
428453

429454
Ok(Allocation {
430455
bytes,
@@ -444,8 +469,13 @@ impl<Prov: Provenance, Bytes: AllocBytes> Allocation<Prov, (), Bytes> {
444469

445470
/// Try to create an Allocation of `size` bytes, failing if there is not enough memory
446471
/// available to the compiler to do so.
447-
pub fn try_new<'tcx>(size: Size, align: Align, init: AllocInit) -> InterpResult<'tcx, Self> {
448-
Self::new_inner(size, align, init, || {
472+
pub fn try_new<'tcx>(
473+
size: Size,
474+
align: Align,
475+
init: AllocInit,
476+
dsc: <Bytes as AllocBytes>::ByteMetadata,
477+
) -> InterpResult<'tcx, Self> {
478+
Self::new_inner(size, align, init, dsc, || {
449479
ty::tls::with(|tcx| tcx.dcx().delayed_bug("exhausted memory during interpretation"));
450480
InterpErrorKind::ResourceExhaustion(ResourceExhaustionInfo::MemoryExhausted)
451481
})
@@ -457,8 +487,13 @@ impl<Prov: Provenance, Bytes: AllocBytes> Allocation<Prov, (), Bytes> {
457487
///
458488
/// Example use case: To obtain an Allocation filled with specific data,
459489
/// first call this function and then call write_scalar to fill in the right data.
460-
pub fn new(size: Size, align: Align, init: AllocInit) -> Self {
461-
match Self::new_inner(size, align, init, || {
490+
pub fn new(
491+
size: Size,
492+
align: Align,
493+
init: AllocInit,
494+
dsc: <Bytes as AllocBytes>::ByteMetadata,
495+
) -> Self {
496+
match Self::new_inner(size, align, init, dsc, || {
462497
panic!(
463498
"interpreter ran out of memory: cannot create allocation of {} bytes",
464499
size.bytes()

compiler/rustc_middle/src/ty/context.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1579,7 +1579,7 @@ impl<'tcx> TyCtxt<'tcx> {
15791579
/// Returns the same `AllocId` if called again with the same bytes.
15801580
pub fn allocate_bytes_dedup(self, bytes: &[u8], salt: usize) -> interpret::AllocId {
15811581
// Create an allocation that just contains these bytes.
1582-
let alloc = interpret::Allocation::from_bytes_byte_aligned_immutable(bytes);
1582+
let alloc = interpret::Allocation::from_bytes_byte_aligned_immutable(bytes, ());
15831583
let alloc = self.mk_const_alloc(alloc);
15841584
self.reserve_and_set_memory_dedup(alloc, salt)
15851585
}

compiler/rustc_middle/src/ty/vtable.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ pub(super) fn vtable_allocation_provider<'tcx>(
110110
let ptr_align = tcx.data_layout.pointer_align.abi;
111111

112112
let vtable_size = ptr_size * u64::try_from(vtable_entries.len()).unwrap();
113-
let mut vtable = Allocation::new(vtable_size, ptr_align, AllocInit::Uninit);
113+
let mut vtable = Allocation::new(vtable_size, ptr_align, AllocInit::Uninit, ());
114114

115115
// No need to do any alignment checks on the memory accesses below, because we know the
116116
// allocation is correctly aligned as we created it above. Also we're only offsetting by

compiler/rustc_mir_build/src/builder/expr/as_constant.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -121,14 +121,14 @@ fn lit_to_mir_constant<'tcx>(tcx: TyCtxt<'tcx>, lit_input: LitToConstInput<'tcx>
121121
let value = match (lit, lit_ty.kind()) {
122122
(ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
123123
let s = s.as_str();
124-
let allocation = Allocation::from_bytes_byte_aligned_immutable(s.as_bytes());
124+
let allocation = Allocation::from_bytes_byte_aligned_immutable(s.as_bytes(), ());
125125
let allocation = tcx.mk_const_alloc(allocation);
126126
ConstValue::Slice { data: allocation, meta: allocation.inner().size().bytes() }
127127
}
128128
(ast::LitKind::ByteStr(data, _), ty::Ref(_, inner_ty, _))
129129
if matches!(inner_ty.kind(), ty::Slice(_)) =>
130130
{
131-
let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8]);
131+
let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8], ());
132132
let allocation = tcx.mk_const_alloc(allocation);
133133
ConstValue::Slice { data: allocation, meta: allocation.inner().size().bytes() }
134134
}
@@ -138,7 +138,7 @@ fn lit_to_mir_constant<'tcx>(tcx: TyCtxt<'tcx>, lit_input: LitToConstInput<'tcx>
138138
}
139139
(ast::LitKind::CStr(data, _), ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::CStr)) =>
140140
{
141-
let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8]);
141+
let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8], ());
142142
let allocation = tcx.mk_const_alloc(allocation);
143143
ConstValue::Slice { data: allocation, meta: allocation.inner().size().bytes() }
144144
}

compiler/rustc_mir_transform/src/large_enums.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,7 @@ impl EnumSizeOpt {
241241
data,
242242
tcx.data_layout.ptr_sized_integer().align(&tcx.data_layout).abi,
243243
Mutability::Not,
244+
(),
244245
);
245246
let alloc = tcx.reserve_and_set_memory_alloc(tcx.mk_const_alloc(alloc));
246247
Some((*adt_def, num_discrs, *alloc_cache.entry(ty).or_insert(alloc)))

compiler/rustc_smir/src/rustc_smir/alloc.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ pub(crate) fn try_new_allocation<'tcx>(
4848
size,
4949
layout.align.abi,
5050
AllocInit::Uninit,
51+
(),
5152
);
5253
allocation
5354
.write_scalar(&tables.tcx, alloc_range(Size::ZERO, size), scalar)
@@ -65,6 +66,7 @@ pub(crate) fn try_new_allocation<'tcx>(
6566
layout.size,
6667
layout.align.abi,
6768
AllocInit::Uninit,
69+
(),
6870
);
6971
allocation
7072
.write_scalar(

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
139139
AllocKind::LiveData => {
140140
if memory_kind == MiriMemoryKind::Global.into() {
141141
// For new global allocations, we always pre-allocate the memory to be able use the machine address directly.
142-
let prepared_bytes = MiriAllocBytes::zeroed(info.size, info.align)
142+
let prepared_bytes = MiriAllocBytes::zeroed(info.size, info.align, ())
143143
.unwrap_or_else(|| {
144144
panic!("Miri ran out of memory: cannot create allocation of {size:?} bytes", size = info.size)
145145
});
@@ -159,7 +159,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
159159
AllocKind::Function | AllocKind::VTable => {
160160
// Allocate some dummy memory to get a unique address for this function/vtable.
161161
let alloc_bytes =
162-
MiriAllocBytes::from_bytes(&[0u8; 1], Align::from_bytes(1).unwrap());
162+
MiriAllocBytes::from_bytes(&[0u8; 1], Align::from_bytes(1).unwrap(), ());
163163
let ptr = alloc_bytes.as_ptr();
164164
// Leak the underlying memory to ensure it remains unique.
165165
std::mem::forget(alloc_bytes);
@@ -429,7 +429,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
429429
prepared_alloc_bytes.copy_from_slice(bytes);
430430
interp_ok(prepared_alloc_bytes)
431431
} else {
432-
interp_ok(MiriAllocBytes::from_bytes(std::borrow::Cow::Borrowed(bytes), align))
432+
interp_ok(MiriAllocBytes::from_bytes(std::borrow::Cow::Borrowed(bytes), align, ()))
433433
}
434434
}
435435

src/tools/miri/src/alloc_bytes.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ impl Clone for MiriAllocBytes {
2424
fn clone(&self) -> Self {
2525
let bytes: Cow<'_, [u8]> = Cow::Borrowed(self);
2626
let align = Align::from_bytes(self.layout.align().to_u64()).unwrap();
27-
MiriAllocBytes::from_bytes(bytes, align)
27+
MiriAllocBytes::from_bytes(bytes, align, ())
2828
}
2929
}
3030

@@ -86,7 +86,10 @@ impl MiriAllocBytes {
8686
}
8787

8888
impl AllocBytes for MiriAllocBytes {
89-
fn from_bytes<'a>(slice: impl Into<Cow<'a, [u8]>>, align: Align) -> Self {
89+
/// Placeholder!
90+
type ByteMetadata = ();
91+
92+
fn from_bytes<'a>(slice: impl Into<Cow<'a, [u8]>>, align: Align, _dsc: ()) -> Self {
9093
let slice = slice.into();
9194
let size = slice.len();
9295
let align = align.bytes();
@@ -102,7 +105,7 @@ impl AllocBytes for MiriAllocBytes {
102105
alloc_bytes
103106
}
104107

105-
fn zeroed(size: Size, align: Align) -> Option<Self> {
108+
fn zeroed(size: Size, align: Align, _dsc: ()) -> Option<Self> {
106109
let size = size.bytes();
107110
let align = align.bytes();
108111
// SAFETY: `alloc_fn` will only be used with `size != 0`.
@@ -117,4 +120,7 @@ impl AllocBytes for MiriAllocBytes {
117120
fn as_ptr(&self) -> *const u8 {
118121
self.ptr
119122
}
123+
124+
/// Placeholder!
125+
fn get_mdata(&self) -> Self::ByteMetadata {}
120126
}

src/tools/miri/src/concurrency/thread.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -899,7 +899,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
899899
let mut alloc = alloc.inner().adjust_from_tcx(
900900
&this.tcx,
901901
|bytes, align| {
902-
interp_ok(MiriAllocBytes::from_bytes(std::borrow::Cow::Borrowed(bytes), align))
902+
interp_ok(MiriAllocBytes::from_bytes(std::borrow::Cow::Borrowed(bytes), align, ()))
903903
},
904904
|ptr| this.global_root_pointer(ptr),
905905
)?;

src/tools/miri/src/machine.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1804,6 +1804,9 @@ impl<'tcx> Machine<'tcx> for MiriMachine<'tcx> {
18041804
) -> Cow<'e, RangeSet> {
18051805
Cow::Borrowed(ecx.machine.union_data_ranges.entry(ty).or_insert_with(compute_range))
18061806
}
1807+
1808+
/// Placeholder!
1809+
fn get_default_byte_mdata(&self) -> () {}
18071810
}
18081811

18091812
/// Trait for callbacks handling asynchronous machine operations.

0 commit comments

Comments
 (0)