Skip to content

Commit 179f5de

Browse files
committed
extend allocbytes with associated type
1 parent aa57e46 commit 179f5de

File tree

16 files changed

+78
-34
lines changed

16 files changed

+78
-34
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_alloc_params(
202+
&self,
203+
) -> <Self::Bytes as rustc_middle::mir::interpret::AllocBytes>::AllocParams {
204+
}
200205
}

compiler/rustc_const_eval/src/const_eval/machine.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -735,6 +735,9 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
735735
Cow::Owned(compute_range())
736736
}
737737
}
738+
739+
fn get_default_alloc_params(&self) -> <Self::Bytes as mir::interpret::AllocBytes>::AllocParams {
740+
}
738741
}
739742

740743
// 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_alloc_params(&self) -> <Self::Bytes as AllocBytes>::AllocParams;
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 params = self.machine.get_default_alloc_params();
236237
let alloc = if M::PANIC_ON_ALLOC_FAIL {
237-
Allocation::new(size, align, init)
238+
Allocation::new(size, align, init, params)
238239
} else {
239-
Allocation::try_new(size, align, init)?
240+
Allocation::try_new(size, align, init, params)?
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 params = self.machine.get_default_alloc_params();
253+
let alloc = Allocation::from_bytes(bytes, align, mutability, params);
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: 40 additions & 17 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 AllocParams;
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+
_params: Self::AllocParams,
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, _params: Self::AllocParams) -> Option<Self>;
3644

3745
/// Gives direct access to the raw underlying storage.
3846
///
@@ -51,11 +59,13 @@ pub trait AllocBytes: Clone + fmt::Debug + Deref<Target = [u8]> + DerefMut<Targe
5159

5260
/// Default `bytes` for `Allocation` is a `Box<u8>`.
5361
impl AllocBytes for Box<[u8]> {
54-
fn from_bytes<'a>(slice: impl Into<Cow<'a, [u8]>>, _align: Align) -> Self {
62+
type AllocParams = ();
63+
64+
fn from_bytes<'a>(slice: impl Into<Cow<'a, [u8]>>, _align: Align, _params: ()) -> Self {
5565
Box::<[u8]>::from(slice.into())
5666
}
5767

58-
fn zeroed(size: Size, _align: Align) -> Option<Self> {
68+
fn zeroed(size: Size, _align: Align, _params: ()) -> Option<Self> {
5969
let bytes = Box::<[u8]>::try_new_zeroed_slice(size.bytes().try_into().ok()?).ok()?;
6070
// SAFETY: the box was zero-allocated, which is a valid initial value for Box<[u8]>
6171
let bytes = unsafe { bytes.assume_init() };
@@ -172,9 +182,8 @@ fn all_zero(buf: &[u8]) -> bool {
172182
}
173183

174184
/// Custom encoder for [`Allocation`] to more efficiently represent the case where all bytes are 0.
175-
impl<Prov: Provenance, Extra, Bytes, E: Encoder> Encodable<E> for Allocation<Prov, Extra, Bytes>
185+
impl<Prov: Provenance, Extra, E: Encoder> Encodable<E> for Allocation<Prov, Extra, Box<[u8]>>
176186
where
177-
Bytes: AllocBytes,
178187
ProvenanceMap<Prov>: Encodable<E>,
179188
Extra: Encodable<E>,
180189
{
@@ -192,9 +201,8 @@ where
192201
}
193202
}
194203

195-
impl<Prov: Provenance, Extra, Bytes, D: Decoder> Decodable<D> for Allocation<Prov, Extra, Bytes>
204+
impl<Prov: Provenance, Extra, D: Decoder> Decodable<D> for Allocation<Prov, Extra, Box<[u8]>>
196205
where
197-
Bytes: AllocBytes,
198206
ProvenanceMap<Prov>: Decodable<D>,
199207
Extra: Decodable<D>,
200208
{
@@ -203,7 +211,7 @@ where
203211

204212
let len = decoder.read_usize();
205213
let bytes = if all_zero { vec![0u8; len] } else { decoder.read_raw_bytes(len).to_vec() };
206-
let bytes = Bytes::from_bytes(bytes, align);
214+
let bytes = <Box<[u8]> as AllocBytes>::from_bytes(bytes, align, ());
207215

208216
let provenance = Decodable::decode(decoder);
209217
let init_mask = Decodable::decode(decoder);
@@ -395,8 +403,9 @@ impl<Prov: Provenance, Bytes: AllocBytes> Allocation<Prov, (), Bytes> {
395403
slice: impl Into<Cow<'a, [u8]>>,
396404
align: Align,
397405
mutability: Mutability,
406+
params: <Bytes as AllocBytes>::AllocParams,
398407
) -> Self {
399-
let bytes = Bytes::from_bytes(slice, align);
408+
let bytes = Bytes::from_bytes(slice, align, params);
400409
let size = Size::from_bytes(bytes.len());
401410
Self {
402411
bytes,
@@ -408,14 +417,18 @@ impl<Prov: Provenance, Bytes: AllocBytes> Allocation<Prov, (), Bytes> {
408417
}
409418
}
410419

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)
420+
pub fn from_bytes_byte_aligned_immutable<'a>(
421+
slice: impl Into<Cow<'a, [u8]>>,
422+
params: <Bytes as AllocBytes>::AllocParams,
423+
) -> Self {
424+
Allocation::from_bytes(slice, Align::ONE, Mutability::Not, params)
413425
}
414426

415427
fn new_inner<R>(
416428
size: Size,
417429
align: Align,
418430
init: AllocInit,
431+
params: <Bytes as AllocBytes>::AllocParams,
419432
fail: impl FnOnce() -> R,
420433
) -> Result<Self, R> {
421434
// We raise an error if we cannot create the allocation on the host.
@@ -424,7 +437,7 @@ impl<Prov: Provenance, Bytes: AllocBytes> Allocation<Prov, (), Bytes> {
424437
// deterministic. However, we can be non-deterministic here because all uses of const
425438
// evaluation (including ConstProp!) will make compilation fail (via hard error
426439
// or ICE) upon encountering a `MemoryExhausted` error.
427-
let bytes = Bytes::zeroed(size, align).ok_or_else(fail)?;
440+
let bytes = Bytes::zeroed(size, align, params).ok_or_else(fail)?;
428441

429442
Ok(Allocation {
430443
bytes,
@@ -444,8 +457,13 @@ impl<Prov: Provenance, Bytes: AllocBytes> Allocation<Prov, (), Bytes> {
444457

445458
/// Try to create an Allocation of `size` bytes, failing if there is not enough memory
446459
/// 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, || {
460+
pub fn try_new<'tcx>(
461+
size: Size,
462+
align: Align,
463+
init: AllocInit,
464+
params: <Bytes as AllocBytes>::AllocParams,
465+
) -> InterpResult<'tcx, Self> {
466+
Self::new_inner(size, align, init, params, || {
449467
ty::tls::with(|tcx| tcx.dcx().delayed_bug("exhausted memory during interpretation"));
450468
InterpErrorKind::ResourceExhaustion(ResourceExhaustionInfo::MemoryExhausted)
451469
})
@@ -457,8 +475,13 @@ impl<Prov: Provenance, Bytes: AllocBytes> Allocation<Prov, (), Bytes> {
457475
///
458476
/// Example use case: To obtain an Allocation filled with specific data,
459477
/// 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, || {
478+
pub fn new(
479+
size: Size,
480+
align: Align,
481+
init: AllocInit,
482+
params: <Bytes as AllocBytes>::AllocParams,
483+
) -> Self {
484+
match Self::new_inner(size, align, init, params, || {
462485
panic!(
463486
"interpreter ran out of memory: cannot create allocation of {} bytes",
464487
size.bytes()

compiler/rustc_middle/src/ty/context.rs

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

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: 6 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 AllocParams = ();
91+
92+
fn from_bytes<'a>(slice: impl Into<Cow<'a, [u8]>>, align: Align, _params: ()) -> 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, _params: ()) -> Option<Self> {
106109
let size = size.bytes();
107110
let align = align.bytes();
108111
// SAFETY: `alloc_fn` will only be used with `size != 0`.

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_alloc_params(&self) -> () {}
18071810
}
18081811

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

0 commit comments

Comments
 (0)