1 //! The arena, a fast but limited type of allocator.
3 //! Arenas are a type of allocator that destroy the objects within, all at
4 //! once, once the arena itself is destroyed. They do not support deallocation
5 //! of individual objects while the arena itself is still alive. The benefit
6 //! of an arena is very fast allocation; just a pointer bump.
8 //! This crate implements several kinds of arena.
11 html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/",
12 test(no_crate_inject, attr(deny(warnings)))
14 #![feature(dropck_eyepatch)]
15 #![feature(new_uninit)]
16 #![feature(maybe_uninit_slice)]
17 #![feature(min_specialization)]
18 #![feature(decl_macro)]
19 #![feature(rustc_attrs)]
20 #![cfg_attr(test, feature(test))]
21 #![feature(strict_provenance)]
22 #![deny(rustc::untranslatable_diagnostic)]
23 #![deny(rustc::diagnostic_outside_of_impl)]
25 use smallvec::SmallVec;
27 use std::alloc::Layout;
28 use std::cell::{Cell, RefCell};
30 use std::marker::{PhantomData, Send};
31 use std::mem::{self, MaybeUninit};
32 use std::ptr::{self, NonNull};
37 fn cold_path<F: FnOnce() -> R, R>(f: F) -> R {
41 /// An arena that can hold objects of only one type.
42 pub struct TypedArena<T> {
43 /// A pointer to the next object to be allocated.
46 /// A pointer to the end of the allocated area. When this pointer is
47 /// reached, a new chunk is allocated.
50 /// A vector of arena chunks.
51 chunks: RefCell<Vec<ArenaChunk<T>>>,
53 /// Marker indicating that dropping the arena causes its owned
54 /// instances of `T` to be dropped.
58 struct ArenaChunk<T = u8> {
59 /// The raw storage for the arena chunk.
60 storage: NonNull<[MaybeUninit<T>]>,
61 /// The number of valid entries in the chunk.
65 unsafe impl<#[may_dangle] T> Drop for ArenaChunk<T> {
67 unsafe { Box::from_raw(self.storage.as_mut()) };
71 impl<T> ArenaChunk<T> {
73 unsafe fn new(capacity: usize) -> ArenaChunk<T> {
75 storage: NonNull::new(Box::into_raw(Box::new_uninit_slice(capacity))).unwrap(),
80 /// Destroys this arena chunk.
82 unsafe fn destroy(&mut self, len: usize) {
83 // The branch on needs_drop() is an -O1 performance optimization.
84 // Without the branch, dropping TypedArena<u8> takes linear time.
85 if mem::needs_drop::<T>() {
86 let slice = &mut *(self.storage.as_mut());
87 ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(&mut slice[..len]));
91 // Returns a pointer to the first allocated object.
93 fn start(&mut self) -> *mut T {
94 self.storage.as_ptr() as *mut T
97 // Returns a pointer to the end of the allocated space.
99 fn end(&mut self) -> *mut T {
101 if mem::size_of::<T>() == 0 {
102 // A pointer as large as possible for zero-sized elements.
105 self.start().add((*self.storage.as_ptr()).len())
111 // The arenas start with PAGE-sized chunks, and then each new chunk is twice as
112 // big as its predecessor, up until we reach HUGE_PAGE-sized chunks, whereupon
113 // we stop growing. This scales well, from arenas that are barely used up to
114 // arenas that are used for 100s of MiBs. Note also that the chosen sizes match
115 // the usual sizes of pages and huge pages on Linux.
116 const PAGE: usize = 4096;
117 const HUGE_PAGE: usize = 2 * 1024 * 1024;
119 impl<T> Default for TypedArena<T> {
120 /// Creates a new `TypedArena`.
121 fn default() -> TypedArena<T> {
123 // We set both `ptr` and `end` to 0 so that the first call to
124 // alloc() will trigger a grow().
125 ptr: Cell::new(ptr::null_mut()),
126 end: Cell::new(ptr::null_mut()),
127 chunks: Default::default(),
134 fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T];
137 impl<I, T> IterExt<T> for I
139 I: IntoIterator<Item = T>,
141 // This default collects into a `SmallVec` and then allocates by copying
142 // from it. The specializations below for types like `Vec` are more
143 // efficient, copying directly without the intermediate collecting step.
144 // This default could be made more efficient, like
145 // `DroplessArena::alloc_from_iter`, but it's not hot enough to bother.
147 default fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T] {
148 let vec: SmallVec<[_; 8]> = self.into_iter().collect();
149 vec.alloc_from_iter(arena)
153 impl<T, const N: usize> IterExt<T> for std::array::IntoIter<T, N> {
155 fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T] {
156 let len = self.len();
160 // Move the content to the arena by copying and then forgetting it.
162 let start_ptr = arena.alloc_raw_slice(len);
163 self.as_slice().as_ptr().copy_to_nonoverlapping(start_ptr, len);
165 slice::from_raw_parts_mut(start_ptr, len)
170 impl<T> IterExt<T> for Vec<T> {
172 fn alloc_from_iter(mut self, arena: &TypedArena<T>) -> &mut [T] {
173 let len = self.len();
177 // Move the content to the arena by copying and then forgetting it.
179 let start_ptr = arena.alloc_raw_slice(len);
180 self.as_ptr().copy_to_nonoverlapping(start_ptr, len);
182 slice::from_raw_parts_mut(start_ptr, len)
187 impl<A: smallvec::Array> IterExt<A::Item> for SmallVec<A> {
189 fn alloc_from_iter(mut self, arena: &TypedArena<A::Item>) -> &mut [A::Item] {
190 let len = self.len();
194 // Move the content to the arena by copying and then forgetting it.
196 let start_ptr = arena.alloc_raw_slice(len);
197 self.as_ptr().copy_to_nonoverlapping(start_ptr, len);
199 slice::from_raw_parts_mut(start_ptr, len)
204 impl<T> TypedArena<T> {
205 /// Allocates an object in the `TypedArena`, returning a reference to it.
207 pub fn alloc(&self, object: T) -> &mut T {
208 if self.ptr == self.end {
213 if mem::size_of::<T>() == 0 {
214 self.ptr.set((self.ptr.get() as *mut u8).wrapping_offset(1) as *mut T);
215 let ptr = ptr::NonNull::<T>::dangling().as_ptr();
216 // Don't drop the object. This `write` is equivalent to `forget`.
217 ptr::write(ptr, object);
220 let ptr = self.ptr.get();
221 // Advance the pointer.
222 self.ptr.set(self.ptr.get().add(1));
223 // Write into uninitialized memory.
224 ptr::write(ptr, object);
231 fn can_allocate(&self, additional: usize) -> bool {
232 // FIXME: this should *likely* use `offset_from`, but more
233 // investigation is needed (including running tests in miri).
234 let available_bytes = self.end.get().addr() - self.ptr.get().addr();
235 let additional_bytes = additional.checked_mul(mem::size_of::<T>()).unwrap();
236 available_bytes >= additional_bytes
239 /// Ensures there's enough space in the current chunk to fit `len` objects.
241 fn ensure_capacity(&self, additional: usize) {
242 if !self.can_allocate(additional) {
243 self.grow(additional);
244 debug_assert!(self.can_allocate(additional));
249 unsafe fn alloc_raw_slice(&self, len: usize) -> *mut T {
250 assert!(mem::size_of::<T>() != 0);
253 self.ensure_capacity(len);
255 let start_ptr = self.ptr.get();
256 self.ptr.set(start_ptr.add(len));
261 pub fn alloc_from_iter<I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
262 assert!(mem::size_of::<T>() != 0);
263 iter.alloc_from_iter(self)
269 fn grow(&self, additional: usize) {
271 // We need the element size to convert chunk sizes (ranging from
272 // PAGE to HUGE_PAGE bytes) to element counts.
273 let elem_size = cmp::max(1, mem::size_of::<T>());
274 let mut chunks = self.chunks.borrow_mut();
276 if let Some(last_chunk) = chunks.last_mut() {
277 // If a type is `!needs_drop`, we don't need to keep track of how many elements
278 // the chunk stores - the field will be ignored anyway.
279 if mem::needs_drop::<T>() {
280 // FIXME: this should *likely* use `offset_from`, but more
281 // investigation is needed (including running tests in miri).
282 let used_bytes = self.ptr.get().addr() - last_chunk.start().addr();
283 last_chunk.entries = used_bytes / mem::size_of::<T>();
286 // If the previous chunk's len is less than HUGE_PAGE
287 // bytes, then this chunk will be least double the previous
289 new_cap = (*last_chunk.storage.as_ptr()).len().min(HUGE_PAGE / elem_size / 2);
292 new_cap = PAGE / elem_size;
294 // Also ensure that this chunk can fit `additional`.
295 new_cap = cmp::max(additional, new_cap);
297 let mut chunk = ArenaChunk::<T>::new(new_cap);
298 self.ptr.set(chunk.start());
299 self.end.set(chunk.end());
304 // Drops the contents of the last chunk. The last chunk is partially empty, unlike all other
306 fn clear_last_chunk(&self, last_chunk: &mut ArenaChunk<T>) {
307 // Determine how much was filled.
308 let start = last_chunk.start().addr();
309 // We obtain the value of the pointer to the first uninitialized element.
310 let end = self.ptr.get().addr();
311 // We then calculate the number of elements to be dropped in the last chunk,
312 // which is the filled area's length.
313 let diff = if mem::size_of::<T>() == 0 {
314 // `T` is ZST. It can't have a drop flag, so the value here doesn't matter. We get
315 // the number of zero-sized values in the last and only chunk, just out of caution.
316 // Recall that `end` was incremented for each allocated value.
319 // FIXME: this should *likely* use `offset_from`, but more
320 // investigation is needed (including running tests in miri).
321 (end - start) / mem::size_of::<T>()
323 // Pass that to the `destroy` method.
325 last_chunk.destroy(diff);
328 self.ptr.set(last_chunk.start());
332 unsafe impl<#[may_dangle] T> Drop for TypedArena<T> {
335 // Determine how much was filled.
336 let mut chunks_borrow = self.chunks.borrow_mut();
337 if let Some(mut last_chunk) = chunks_borrow.pop() {
338 // Drop the contents of the last chunk.
339 self.clear_last_chunk(&mut last_chunk);
340 // The last chunk will be dropped. Destroy all other chunks.
341 for chunk in chunks_borrow.iter_mut() {
342 chunk.destroy(chunk.entries);
345 // Box handles deallocation of `last_chunk` and `self.chunks`.
350 unsafe impl<T: Send> Send for TypedArena<T> {}
352 /// An arena that can hold objects of multiple different types that impl `Copy`
353 /// and/or satisfy `!mem::needs_drop`.
354 pub struct DroplessArena {
355 /// A pointer to the start of the free space.
356 start: Cell<*mut u8>,
358 /// A pointer to the end of free space.
360 /// The allocation proceeds downwards from the end of the chunk towards the
361 /// start. (This is slightly simpler and faster than allocating upwards,
362 /// see <https://fitzgeraldnick.com/2019/11/01/always-bump-downwards.html>.)
363 /// When this pointer crosses the start pointer, a new chunk is allocated.
366 /// A vector of arena chunks.
367 chunks: RefCell<Vec<ArenaChunk>>,
370 unsafe impl Send for DroplessArena {}
372 impl Default for DroplessArena {
374 fn default() -> DroplessArena {
376 start: Cell::new(ptr::null_mut()),
377 end: Cell::new(ptr::null_mut()),
378 chunks: Default::default(),
386 fn grow(&self, additional: usize) {
388 let mut chunks = self.chunks.borrow_mut();
390 if let Some(last_chunk) = chunks.last_mut() {
391 // There is no need to update `last_chunk.entries` because that
392 // field isn't used by `DroplessArena`.
394 // If the previous chunk's len is less than HUGE_PAGE
395 // bytes, then this chunk will be least double the previous
397 new_cap = (*last_chunk.storage.as_ptr()).len().min(HUGE_PAGE / 2);
402 // Also ensure that this chunk can fit `additional`.
403 new_cap = cmp::max(additional, new_cap);
405 let mut chunk = ArenaChunk::new(new_cap);
406 self.start.set(chunk.start());
407 self.end.set(chunk.end());
412 /// Allocates a byte slice with specified layout from the current memory
413 /// chunk. Returns `None` if there is no free space left to satisfy the
416 fn alloc_raw_without_grow(&self, layout: Layout) -> Option<*mut u8> {
417 let start = self.start.get().addr();
418 let old_end = self.end.get();
419 let end = old_end.addr();
421 let align = layout.align();
422 let bytes = layout.size();
424 let new_end = end.checked_sub(bytes)? & !(align - 1);
425 if start <= new_end {
426 let new_end = old_end.with_addr(new_end);
427 self.end.set(new_end);
435 pub fn alloc_raw(&self, layout: Layout) -> *mut u8 {
436 assert!(layout.size() != 0);
438 if let Some(a) = self.alloc_raw_without_grow(layout) {
441 // No free space left. Allocate a new chunk to satisfy the request.
442 // On failure the grow will panic or abort.
443 self.grow(layout.size());
448 pub fn alloc<T>(&self, object: T) -> &mut T {
449 assert!(!mem::needs_drop::<T>());
451 let mem = self.alloc_raw(Layout::for_value::<T>(&object)) as *mut T;
454 // Write into uninitialized memory.
455 ptr::write(mem, object);
460 /// Allocates a slice of objects that are copied into the `DroplessArena`, returning a mutable
461 /// reference to it. Will panic if passed a zero-sized type.
465 /// - Zero-sized types
466 /// - Zero-length slices
468 pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
472 assert!(!mem::needs_drop::<T>());
473 assert!(mem::size_of::<T>() != 0);
474 assert!(!slice.is_empty());
476 let mem = self.alloc_raw(Layout::for_value::<[T]>(slice)) as *mut T;
479 mem.copy_from_nonoverlapping(slice.as_ptr(), slice.len());
480 slice::from_raw_parts_mut(mem, slice.len())
485 unsafe fn write_from_iter<T, I: Iterator<Item = T>>(
492 // Use a manual loop since LLVM manages to optimize it better for
495 let value = iter.next();
496 if i >= len || value.is_none() {
497 // We only return as many items as the iterator gave us, even
498 // though it was supposed to give us `len`
499 return slice::from_raw_parts_mut(mem, i);
501 ptr::write(mem.add(i), value.unwrap());
507 pub fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
508 let iter = iter.into_iter();
509 assert!(mem::size_of::<T>() != 0);
510 assert!(!mem::needs_drop::<T>());
512 let size_hint = iter.size_hint();
515 (min, Some(max)) if min == max => {
516 // We know the exact number of elements the iterator will produce here
523 let mem = self.alloc_raw(Layout::array::<T>(len).unwrap()) as *mut T;
524 unsafe { self.write_from_iter(iter, len, mem) }
527 cold_path(move || -> &mut [T] {
528 let mut vec: SmallVec<[_; 8]> = iter.collect();
532 // Move the content to the arena by copying it and then forgetting
533 // the content of the SmallVec
537 self.alloc_raw(Layout::for_value::<[T]>(vec.as_slice())) as *mut T;
538 vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
540 slice::from_raw_parts_mut(start_ptr, len)
548 /// Declare an `Arena` containing one dropless arena and many typed arenas (the
549 /// types of the typed arenas are specified by the arguments).
551 /// There are three cases of interest.
552 /// - Types that are `Copy`: these need not be specified in the arguments. They
553 /// will use the `DroplessArena`.
554 /// - Types that are `!Copy` and `!Drop`: these must be specified in the
555 /// arguments. An empty `TypedArena` will be created for each one, but the
556 /// `DroplessArena` will always be used and the `TypedArena` will stay empty.
557 /// This is odd but harmless, because an empty arena allocates no memory.
558 /// - Types that are `!Copy` and `Drop`: these must be specified in the
559 /// arguments. The `TypedArena` will be used for them.
561 #[rustc_macro_transparency = "semitransparent"]
562 pub macro declare_arena([$($a:tt $name:ident: $ty:ty,)*]) {
564 pub struct Arena<'tcx> {
565 pub dropless: $crate::DroplessArena,
566 $($name: $crate::TypedArena<$ty>,)*
569 pub trait ArenaAllocatable<'tcx, C = rustc_arena::IsNotCopy>: Sized {
570 fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self;
571 fn allocate_from_iter<'a>(
572 arena: &'a Arena<'tcx>,
573 iter: impl ::std::iter::IntoIterator<Item = Self>,
577 // Any type that impls `Copy` can be arena-allocated in the `DroplessArena`.
578 impl<'tcx, T: Copy> ArenaAllocatable<'tcx, rustc_arena::IsCopy> for T {
580 fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self {
581 arena.dropless.alloc(self)
584 fn allocate_from_iter<'a>(
585 arena: &'a Arena<'tcx>,
586 iter: impl ::std::iter::IntoIterator<Item = Self>,
587 ) -> &'a mut [Self] {
588 arena.dropless.alloc_from_iter(iter)
592 impl<'tcx> ArenaAllocatable<'tcx, rustc_arena::IsNotCopy> for $ty {
594 fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self {
595 if !::std::mem::needs_drop::<Self>() {
596 arena.dropless.alloc(self)
598 arena.$name.alloc(self)
603 fn allocate_from_iter<'a>(
604 arena: &'a Arena<'tcx>,
605 iter: impl ::std::iter::IntoIterator<Item = Self>,
606 ) -> &'a mut [Self] {
607 if !::std::mem::needs_drop::<Self>() {
608 arena.dropless.alloc_from_iter(iter)
610 arena.$name.alloc_from_iter(iter)
616 impl<'tcx> Arena<'tcx> {
618 pub fn alloc<T: ArenaAllocatable<'tcx, C>, C>(&self, value: T) -> &mut T {
619 value.allocate_on(self)
622 // Any type that impls `Copy` can have slices be arena-allocated in the `DroplessArena`.
624 pub fn alloc_slice<T: ::std::marker::Copy>(&self, value: &[T]) -> &mut [T] {
625 if value.is_empty() {
628 self.dropless.alloc_slice(value)
631 pub fn alloc_from_iter<'a, T: ArenaAllocatable<'tcx, C>, C>(
633 iter: impl ::std::iter::IntoIterator<Item = T>,
635 T::allocate_from_iter(self, iter)
640 // Marker types that let us give different behaviour for arenas allocating
641 // `Copy` types vs `!Copy` types.
643 pub struct IsNotCopy;