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)]
23 use smallvec::SmallVec;
25 use std::alloc::Layout;
26 use std::cell::{Cell, RefCell};
28 use std::marker::{PhantomData, Send};
29 use std::mem::{self, MaybeUninit};
35 fn cold_path<F: FnOnce() -> R, R>(f: F) -> R {
39 /// An arena that can hold objects of only one type.
40 pub struct TypedArena<T> {
41 /// A pointer to the next object to be allocated.
44 /// A pointer to the end of the allocated area. When this pointer is
45 /// reached, a new chunk is allocated.
48 /// A vector of arena chunks.
49 chunks: RefCell<Vec<ArenaChunk<T>>>,
51 /// Marker indicating that dropping the arena causes its owned
52 /// instances of `T` to be dropped.
56 struct ArenaChunk<T = u8> {
57 /// The raw storage for the arena chunk.
58 storage: Box<[MaybeUninit<T>]>,
59 /// The number of valid entries in the chunk.
63 impl<T> ArenaChunk<T> {
65 unsafe fn new(capacity: usize) -> ArenaChunk<T> {
66 ArenaChunk { storage: Box::new_uninit_slice(capacity), entries: 0 }
69 /// Destroys this arena chunk.
71 unsafe fn destroy(&mut self, len: usize) {
72 // The branch on needs_drop() is an -O1 performance optimization.
73 // Without the branch, dropping TypedArena<u8> takes linear time.
74 if mem::needs_drop::<T>() {
75 ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(&mut self.storage[..len]));
79 // Returns a pointer to the first allocated object.
81 fn start(&mut self) -> *mut T {
82 MaybeUninit::slice_as_mut_ptr(&mut self.storage)
85 // Returns a pointer to the end of the allocated space.
87 fn end(&mut self) -> *mut T {
89 if mem::size_of::<T>() == 0 {
90 // A pointer as large as possible for zero-sized elements.
93 self.start().add(self.storage.len())
99 // The arenas start with PAGE-sized chunks, and then each new chunk is twice as
100 // big as its predecessor, up until we reach HUGE_PAGE-sized chunks, whereupon
101 // we stop growing. This scales well, from arenas that are barely used up to
102 // arenas that are used for 100s of MiBs. Note also that the chosen sizes match
103 // the usual sizes of pages and huge pages on Linux.
104 const PAGE: usize = 4096;
105 const HUGE_PAGE: usize = 2 * 1024 * 1024;
107 impl<T> Default for TypedArena<T> {
108 /// Creates a new `TypedArena`.
109 fn default() -> TypedArena<T> {
111 // We set both `ptr` and `end` to 0 so that the first call to
112 // alloc() will trigger a grow().
113 ptr: Cell::new(ptr::null_mut()),
114 end: Cell::new(ptr::null_mut()),
115 chunks: Default::default(),
122 fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T];
125 impl<I, T> IterExt<T> for I
127 I: IntoIterator<Item = T>,
129 // This default collects into a `SmallVec` and then allocates by copying
130 // from it. The specializations below for types like `Vec` are more
131 // efficient, copying directly without the intermediate collecting step.
132 // This default could be made more efficient, like
133 // `DroplessArena::alloc_from_iter`, but it's not hot enough to bother.
135 default fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T] {
136 let vec: SmallVec<[_; 8]> = self.into_iter().collect();
137 vec.alloc_from_iter(arena)
141 impl<T, const N: usize> IterExt<T> for std::array::IntoIter<T, N> {
143 fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T] {
144 let len = self.len();
148 // Move the content to the arena by copying and then forgetting it.
150 let start_ptr = arena.alloc_raw_slice(len);
151 self.as_slice().as_ptr().copy_to_nonoverlapping(start_ptr, len);
153 slice::from_raw_parts_mut(start_ptr, len)
158 impl<T> IterExt<T> for Vec<T> {
160 fn alloc_from_iter(mut self, arena: &TypedArena<T>) -> &mut [T] {
161 let len = self.len();
165 // Move the content to the arena by copying and then forgetting it.
167 let start_ptr = arena.alloc_raw_slice(len);
168 self.as_ptr().copy_to_nonoverlapping(start_ptr, len);
170 slice::from_raw_parts_mut(start_ptr, len)
175 impl<A: smallvec::Array> IterExt<A::Item> for SmallVec<A> {
177 fn alloc_from_iter(mut self, arena: &TypedArena<A::Item>) -> &mut [A::Item] {
178 let len = self.len();
182 // Move the content to the arena by copying and then forgetting it.
184 let start_ptr = arena.alloc_raw_slice(len);
185 self.as_ptr().copy_to_nonoverlapping(start_ptr, len);
187 slice::from_raw_parts_mut(start_ptr, len)
192 impl<T> TypedArena<T> {
193 /// Allocates an object in the `TypedArena`, returning a reference to it.
195 pub fn alloc(&self, object: T) -> &mut T {
196 if self.ptr == self.end {
201 if mem::size_of::<T>() == 0 {
202 self.ptr.set((self.ptr.get() as *mut u8).wrapping_offset(1) as *mut T);
203 let ptr = ptr::NonNull::<T>::dangling().as_ptr();
204 // Don't drop the object. This `write` is equivalent to `forget`.
205 ptr::write(ptr, object);
208 let ptr = self.ptr.get();
209 // Advance the pointer.
210 self.ptr.set(self.ptr.get().offset(1));
211 // Write into uninitialized memory.
212 ptr::write(ptr, object);
219 fn can_allocate(&self, additional: usize) -> bool {
220 // FIXME: this should *likely* use `offset_from`, but more
221 // investigation is needed (including running tests in miri).
222 let available_bytes = self.end.get().addr() - self.ptr.get().addr();
223 let additional_bytes = additional.checked_mul(mem::size_of::<T>()).unwrap();
224 available_bytes >= additional_bytes
227 /// Ensures there's enough space in the current chunk to fit `len` objects.
229 fn ensure_capacity(&self, additional: usize) {
230 if !self.can_allocate(additional) {
231 self.grow(additional);
232 debug_assert!(self.can_allocate(additional));
237 unsafe fn alloc_raw_slice(&self, len: usize) -> *mut T {
238 assert!(mem::size_of::<T>() != 0);
241 self.ensure_capacity(len);
243 let start_ptr = self.ptr.get();
244 self.ptr.set(start_ptr.add(len));
249 pub fn alloc_from_iter<I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
250 assert!(mem::size_of::<T>() != 0);
251 iter.alloc_from_iter(self)
257 fn grow(&self, additional: usize) {
259 // We need the element size to convert chunk sizes (ranging from
260 // PAGE to HUGE_PAGE bytes) to element counts.
261 let elem_size = cmp::max(1, mem::size_of::<T>());
262 let mut chunks = self.chunks.borrow_mut();
264 if let Some(last_chunk) = chunks.last_mut() {
265 // If a type is `!needs_drop`, we don't need to keep track of how many elements
266 // the chunk stores - the field will be ignored anyway.
267 if mem::needs_drop::<T>() {
268 // FIXME: this should *likely* use `offset_from`, but more
269 // investigation is needed (including running tests in miri).
270 let used_bytes = self.ptr.get().addr() - last_chunk.start().addr();
271 last_chunk.entries = used_bytes / mem::size_of::<T>();
274 // If the previous chunk's len is less than HUGE_PAGE
275 // bytes, then this chunk will be least double the previous
277 new_cap = last_chunk.storage.len().min(HUGE_PAGE / elem_size / 2);
280 new_cap = PAGE / elem_size;
282 // Also ensure that this chunk can fit `additional`.
283 new_cap = cmp::max(additional, new_cap);
285 let mut chunk = ArenaChunk::<T>::new(new_cap);
286 self.ptr.set(chunk.start());
287 self.end.set(chunk.end());
292 // Drops the contents of the last chunk. The last chunk is partially empty, unlike all other
294 fn clear_last_chunk(&self, last_chunk: &mut ArenaChunk<T>) {
295 // Determine how much was filled.
296 let start = last_chunk.start().addr();
297 // We obtain the value of the pointer to the first uninitialized element.
298 let end = self.ptr.get().addr();
299 // We then calculate the number of elements to be dropped in the last chunk,
300 // which is the filled area's length.
301 let diff = if mem::size_of::<T>() == 0 {
302 // `T` is ZST. It can't have a drop flag, so the value here doesn't matter. We get
303 // the number of zero-sized values in the last and only chunk, just out of caution.
304 // Recall that `end` was incremented for each allocated value.
307 // FIXME: this should *likely* use `offset_from`, but more
308 // investigation is needed (including running tests in miri).
309 (end - start) / mem::size_of::<T>()
311 // Pass that to the `destroy` method.
313 last_chunk.destroy(diff);
316 self.ptr.set(last_chunk.start());
320 unsafe impl<#[may_dangle] T> Drop for TypedArena<T> {
323 // Determine how much was filled.
324 let mut chunks_borrow = self.chunks.borrow_mut();
325 if let Some(mut last_chunk) = chunks_borrow.pop() {
326 // Drop the contents of the last chunk.
327 self.clear_last_chunk(&mut last_chunk);
328 // The last chunk will be dropped. Destroy all other chunks.
329 for chunk in chunks_borrow.iter_mut() {
330 chunk.destroy(chunk.entries);
333 // Box handles deallocation of `last_chunk` and `self.chunks`.
338 unsafe impl<T: Send> Send for TypedArena<T> {}
340 /// An arena that can hold objects of multiple different types that impl `Copy`
341 /// and/or satisfy `!mem::needs_drop`.
342 pub struct DroplessArena {
343 /// A pointer to the start of the free space.
344 start: Cell<*mut u8>,
346 /// A pointer to the end of free space.
348 /// The allocation proceeds downwards from the end of the chunk towards the
349 /// start. (This is slightly simpler and faster than allocating upwards,
350 /// see <https://fitzgeraldnick.com/2019/11/01/always-bump-downwards.html>.)
351 /// When this pointer crosses the start pointer, a new chunk is allocated.
354 /// A vector of arena chunks.
355 chunks: RefCell<Vec<ArenaChunk>>,
358 unsafe impl Send for DroplessArena {}
360 impl Default for DroplessArena {
362 fn default() -> DroplessArena {
364 start: Cell::new(ptr::null_mut()),
365 end: Cell::new(ptr::null_mut()),
366 chunks: Default::default(),
374 fn grow(&self, additional: usize) {
376 let mut chunks = self.chunks.borrow_mut();
378 if let Some(last_chunk) = chunks.last_mut() {
379 // There is no need to update `last_chunk.entries` because that
380 // field isn't used by `DroplessArena`.
382 // If the previous chunk's len is less than HUGE_PAGE
383 // bytes, then this chunk will be least double the previous
385 new_cap = last_chunk.storage.len().min(HUGE_PAGE / 2);
390 // Also ensure that this chunk can fit `additional`.
391 new_cap = cmp::max(additional, new_cap);
393 let mut chunk = ArenaChunk::new(new_cap);
394 self.start.set(chunk.start());
395 self.end.set(chunk.end());
400 /// Allocates a byte slice with specified layout from the current memory
401 /// chunk. Returns `None` if there is no free space left to satisfy the
404 fn alloc_raw_without_grow(&self, layout: Layout) -> Option<*mut u8> {
405 let start = self.start.get().addr();
406 let old_end = self.end.get();
407 let end = old_end.addr();
409 let align = layout.align();
410 let bytes = layout.size();
412 let new_end = end.checked_sub(bytes)? & !(align - 1);
413 if start <= new_end {
414 let new_end = old_end.with_addr(new_end);
415 self.end.set(new_end);
423 pub fn alloc_raw(&self, layout: Layout) -> *mut u8 {
424 assert!(layout.size() != 0);
426 if let Some(a) = self.alloc_raw_without_grow(layout) {
429 // No free space left. Allocate a new chunk to satisfy the request.
430 // On failure the grow will panic or abort.
431 self.grow(layout.size());
436 pub fn alloc<T>(&self, object: T) -> &mut T {
437 assert!(!mem::needs_drop::<T>());
439 let mem = self.alloc_raw(Layout::for_value::<T>(&object)) as *mut T;
442 // Write into uninitialized memory.
443 ptr::write(mem, object);
448 /// Allocates a slice of objects that are copied into the `DroplessArena`, returning a mutable
449 /// reference to it. Will panic if passed a zero-sized type.
453 /// - Zero-sized types
454 /// - Zero-length slices
456 pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
460 assert!(!mem::needs_drop::<T>());
461 assert!(mem::size_of::<T>() != 0);
462 assert!(!slice.is_empty());
464 let mem = self.alloc_raw(Layout::for_value::<[T]>(slice)) as *mut T;
467 mem.copy_from_nonoverlapping(slice.as_ptr(), slice.len());
468 slice::from_raw_parts_mut(mem, slice.len())
473 unsafe fn write_from_iter<T, I: Iterator<Item = T>>(
480 // Use a manual loop since LLVM manages to optimize it better for
483 let value = iter.next();
484 if i >= len || value.is_none() {
485 // We only return as many items as the iterator gave us, even
486 // though it was supposed to give us `len`
487 return slice::from_raw_parts_mut(mem, i);
489 ptr::write(mem.add(i), value.unwrap());
495 pub fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
496 let iter = iter.into_iter();
497 assert!(mem::size_of::<T>() != 0);
498 assert!(!mem::needs_drop::<T>());
500 let size_hint = iter.size_hint();
503 (min, Some(max)) if min == max => {
504 // We know the exact number of elements the iterator will produce here
511 let mem = self.alloc_raw(Layout::array::<T>(len).unwrap()) as *mut T;
512 unsafe { self.write_from_iter(iter, len, mem) }
515 cold_path(move || -> &mut [T] {
516 let mut vec: SmallVec<[_; 8]> = iter.collect();
520 // Move the content to the arena by copying it and then forgetting
521 // the content of the SmallVec
525 self.alloc_raw(Layout::for_value::<[T]>(vec.as_slice())) as *mut T;
526 vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
528 slice::from_raw_parts_mut(start_ptr, len)
536 /// Declare an `Arena` containing one dropless arena and many typed arenas (the
537 /// types of the typed arenas are specified by the arguments).
539 /// There are three cases of interest.
540 /// - Types that are `Copy`: these need not be specified in the arguments. They
541 /// will use the `DroplessArena`.
542 /// - Types that are `!Copy` and `!Drop`: these must be specified in the
543 /// arguments. An empty `TypedArena` will be created for each one, but the
544 /// `DroplessArena` will always be used and the `TypedArena` will stay empty.
545 /// This is odd but harmless, because an empty arena allocates no memory.
546 /// - Types that are `!Copy` and `Drop`: these must be specified in the
547 /// arguments. The `TypedArena` will be used for them.
549 #[rustc_macro_transparency = "semitransparent"]
550 pub macro declare_arena([$($a:tt $name:ident: $ty:ty,)*]) {
552 pub struct Arena<'tcx> {
553 pub dropless: $crate::DroplessArena,
554 $($name: $crate::TypedArena<$ty>,)*
557 pub trait ArenaAllocatable<'tcx, C = rustc_arena::IsNotCopy>: Sized {
558 fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self;
559 fn allocate_from_iter<'a>(
560 arena: &'a Arena<'tcx>,
561 iter: impl ::std::iter::IntoIterator<Item = Self>,
565 // Any type that impls `Copy` can be arena-allocated in the `DroplessArena`.
566 impl<'tcx, T: Copy> ArenaAllocatable<'tcx, rustc_arena::IsCopy> for T {
568 fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self {
569 arena.dropless.alloc(self)
572 fn allocate_from_iter<'a>(
573 arena: &'a Arena<'tcx>,
574 iter: impl ::std::iter::IntoIterator<Item = Self>,
575 ) -> &'a mut [Self] {
576 arena.dropless.alloc_from_iter(iter)
580 impl<'tcx> ArenaAllocatable<'tcx, rustc_arena::IsNotCopy> for $ty {
582 fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self {
583 if !::std::mem::needs_drop::<Self>() {
584 arena.dropless.alloc(self)
586 arena.$name.alloc(self)
591 fn allocate_from_iter<'a>(
592 arena: &'a Arena<'tcx>,
593 iter: impl ::std::iter::IntoIterator<Item = Self>,
594 ) -> &'a mut [Self] {
595 if !::std::mem::needs_drop::<Self>() {
596 arena.dropless.alloc_from_iter(iter)
598 arena.$name.alloc_from_iter(iter)
604 impl<'tcx> Arena<'tcx> {
606 pub fn alloc<T: ArenaAllocatable<'tcx, C>, C>(&self, value: T) -> &mut T {
607 value.allocate_on(self)
610 // Any type that impls `Copy` can have slices be arena-allocated in the `DroplessArena`.
612 pub fn alloc_slice<T: ::std::marker::Copy>(&self, value: &[T]) -> &mut [T] {
613 if value.is_empty() {
616 self.dropless.alloc_slice(value)
619 pub fn alloc_from_iter<'a, T: ArenaAllocatable<'tcx, C>, C>(
621 iter: impl ::std::iter::IntoIterator<Item = T>,
623 T::allocate_from_iter(self, iter)
628 // Marker types that let us give different behaviour for arenas allocating
629 // `Copy` types vs `!Copy` types.
631 pub struct IsNotCopy;