]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_arena/src/lib.rs
Rollup merge of #93293 - nvzqz:nonzero-min-max, r=joshtriplett
[rust.git] / compiler / rustc_arena / src / lib.rs
1 //! The arena, a fast but limited type of allocator.
2 //!
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.
7 //!
8 //! This crate implements several kinds of arena.
9
10 #![doc(
11     html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/",
12     test(no_crate_inject, attr(deny(warnings)))
13 )]
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
22 use smallvec::SmallVec;
23
24 use std::alloc::Layout;
25 use std::cell::{Cell, RefCell};
26 use std::cmp;
27 use std::marker::{PhantomData, Send};
28 use std::mem::{self, MaybeUninit};
29 use std::ptr;
30 use std::slice;
31
32 #[inline(never)]
33 #[cold]
34 fn cold_path<F: FnOnce() -> R, R>(f: F) -> R {
35     f()
36 }
37
38 /// An arena that can hold objects of only one type.
39 pub struct TypedArena<T> {
40     /// A pointer to the next object to be allocated.
41     ptr: Cell<*mut T>,
42
43     /// A pointer to the end of the allocated area. When this pointer is
44     /// reached, a new chunk is allocated.
45     end: Cell<*mut T>,
46
47     /// A vector of arena chunks.
48     chunks: RefCell<Vec<ArenaChunk<T>>>,
49
50     /// Marker indicating that dropping the arena causes its owned
51     /// instances of `T` to be dropped.
52     _own: PhantomData<T>,
53 }
54
55 struct ArenaChunk<T = u8> {
56     /// The raw storage for the arena chunk.
57     storage: Box<[MaybeUninit<T>]>,
58     /// The number of valid entries in the chunk.
59     entries: usize,
60 }
61
62 impl<T> ArenaChunk<T> {
63     #[inline]
64     unsafe fn new(capacity: usize) -> ArenaChunk<T> {
65         ArenaChunk { storage: Box::new_uninit_slice(capacity), entries: 0 }
66     }
67
68     /// Destroys this arena chunk.
69     #[inline]
70     unsafe fn destroy(&mut self, len: usize) {
71         // The branch on needs_drop() is an -O1 performance optimization.
72         // Without the branch, dropping TypedArena<u8> takes linear time.
73         if mem::needs_drop::<T>() {
74             ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(&mut self.storage[..len]));
75         }
76     }
77
78     // Returns a pointer to the first allocated object.
79     #[inline]
80     fn start(&mut self) -> *mut T {
81         MaybeUninit::slice_as_mut_ptr(&mut self.storage)
82     }
83
84     // Returns a pointer to the end of the allocated space.
85     #[inline]
86     fn end(&mut self) -> *mut T {
87         unsafe {
88             if mem::size_of::<T>() == 0 {
89                 // A pointer as large as possible for zero-sized elements.
90                 !0 as *mut T
91             } else {
92                 self.start().add(self.storage.len())
93             }
94         }
95     }
96 }
97
98 // The arenas start with PAGE-sized chunks, and then each new chunk is twice as
99 // big as its predecessor, up until we reach HUGE_PAGE-sized chunks, whereupon
100 // we stop growing. This scales well, from arenas that are barely used up to
101 // arenas that are used for 100s of MiBs. Note also that the chosen sizes match
102 // the usual sizes of pages and huge pages on Linux.
103 const PAGE: usize = 4096;
104 const HUGE_PAGE: usize = 2 * 1024 * 1024;
105
106 impl<T> Default for TypedArena<T> {
107     /// Creates a new `TypedArena`.
108     fn default() -> TypedArena<T> {
109         TypedArena {
110             // We set both `ptr` and `end` to 0 so that the first call to
111             // alloc() will trigger a grow().
112             ptr: Cell::new(ptr::null_mut()),
113             end: Cell::new(ptr::null_mut()),
114             chunks: Default::default(),
115             _own: PhantomData,
116         }
117     }
118 }
119
120 trait IterExt<T> {
121     fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T];
122 }
123
124 impl<I, T> IterExt<T> for I
125 where
126     I: IntoIterator<Item = T>,
127 {
128     // This default collects into a `SmallVec` and then allocates by copying
129     // from it. The specializations below for types like `Vec` are more
130     // efficient, copying directly without the intermediate collecting step.
131     // This default could be made more efficient, like
132     // `DroplessArena::alloc_from_iter`, but it's not hot enough to bother.
133     #[inline]
134     default fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T] {
135         let vec: SmallVec<[_; 8]> = self.into_iter().collect();
136         vec.alloc_from_iter(arena)
137     }
138 }
139
140 impl<T, const N: usize> IterExt<T> for std::array::IntoIter<T, N> {
141     #[inline]
142     fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T] {
143         let len = self.len();
144         if len == 0 {
145             return &mut [];
146         }
147         // Move the content to the arena by copying and then forgetting it.
148         unsafe {
149             let start_ptr = arena.alloc_raw_slice(len);
150             self.as_slice().as_ptr().copy_to_nonoverlapping(start_ptr, len);
151             mem::forget(self);
152             slice::from_raw_parts_mut(start_ptr, len)
153         }
154     }
155 }
156
157 impl<T> IterExt<T> for Vec<T> {
158     #[inline]
159     fn alloc_from_iter(mut self, arena: &TypedArena<T>) -> &mut [T] {
160         let len = self.len();
161         if len == 0 {
162             return &mut [];
163         }
164         // Move the content to the arena by copying and then forgetting it.
165         unsafe {
166             let start_ptr = arena.alloc_raw_slice(len);
167             self.as_ptr().copy_to_nonoverlapping(start_ptr, len);
168             self.set_len(0);
169             slice::from_raw_parts_mut(start_ptr, len)
170         }
171     }
172 }
173
174 impl<A: smallvec::Array> IterExt<A::Item> for SmallVec<A> {
175     #[inline]
176     fn alloc_from_iter(mut self, arena: &TypedArena<A::Item>) -> &mut [A::Item] {
177         let len = self.len();
178         if len == 0 {
179             return &mut [];
180         }
181         // Move the content to the arena by copying and then forgetting it.
182         unsafe {
183             let start_ptr = arena.alloc_raw_slice(len);
184             self.as_ptr().copy_to_nonoverlapping(start_ptr, len);
185             self.set_len(0);
186             slice::from_raw_parts_mut(start_ptr, len)
187         }
188     }
189 }
190
191 impl<T> TypedArena<T> {
192     /// Allocates an object in the `TypedArena`, returning a reference to it.
193     #[inline]
194     pub fn alloc(&self, object: T) -> &mut T {
195         if self.ptr == self.end {
196             self.grow(1)
197         }
198
199         unsafe {
200             if mem::size_of::<T>() == 0 {
201                 self.ptr.set((self.ptr.get() as *mut u8).wrapping_offset(1) as *mut T);
202                 let ptr = mem::align_of::<T>() as *mut T;
203                 // Don't drop the object. This `write` is equivalent to `forget`.
204                 ptr::write(ptr, object);
205                 &mut *ptr
206             } else {
207                 let ptr = self.ptr.get();
208                 // Advance the pointer.
209                 self.ptr.set(self.ptr.get().offset(1));
210                 // Write into uninitialized memory.
211                 ptr::write(ptr, object);
212                 &mut *ptr
213             }
214         }
215     }
216
217     #[inline]
218     fn can_allocate(&self, additional: usize) -> bool {
219         let available_bytes = self.end.get() as usize - self.ptr.get() as usize;
220         let additional_bytes = additional.checked_mul(mem::size_of::<T>()).unwrap();
221         available_bytes >= additional_bytes
222     }
223
224     /// Ensures there's enough space in the current chunk to fit `len` objects.
225     #[inline]
226     fn ensure_capacity(&self, additional: usize) {
227         if !self.can_allocate(additional) {
228             self.grow(additional);
229             debug_assert!(self.can_allocate(additional));
230         }
231     }
232
233     #[inline]
234     unsafe fn alloc_raw_slice(&self, len: usize) -> *mut T {
235         assert!(mem::size_of::<T>() != 0);
236         assert!(len != 0);
237
238         self.ensure_capacity(len);
239
240         let start_ptr = self.ptr.get();
241         self.ptr.set(start_ptr.add(len));
242         start_ptr
243     }
244
245     #[inline]
246     pub fn alloc_from_iter<I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
247         assert!(mem::size_of::<T>() != 0);
248         iter.alloc_from_iter(self)
249     }
250
251     /// Grows the arena.
252     #[inline(never)]
253     #[cold]
254     fn grow(&self, additional: usize) {
255         unsafe {
256             // We need the element size to convert chunk sizes (ranging from
257             // PAGE to HUGE_PAGE bytes) to element counts.
258             let elem_size = cmp::max(1, mem::size_of::<T>());
259             let mut chunks = self.chunks.borrow_mut();
260             let mut new_cap;
261             if let Some(last_chunk) = chunks.last_mut() {
262                 // If a type is `!needs_drop`, we don't need to keep track of how many elements
263                 // the chunk stores - the field will be ignored anyway.
264                 if mem::needs_drop::<T>() {
265                     let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
266                     last_chunk.entries = used_bytes / mem::size_of::<T>();
267                 }
268
269                 // If the previous chunk's len is less than HUGE_PAGE
270                 // bytes, then this chunk will be least double the previous
271                 // chunk's size.
272                 new_cap = last_chunk.storage.len().min(HUGE_PAGE / elem_size / 2);
273                 new_cap *= 2;
274             } else {
275                 new_cap = PAGE / elem_size;
276             }
277             // Also ensure that this chunk can fit `additional`.
278             new_cap = cmp::max(additional, new_cap);
279
280             let mut chunk = ArenaChunk::<T>::new(new_cap);
281             self.ptr.set(chunk.start());
282             self.end.set(chunk.end());
283             chunks.push(chunk);
284         }
285     }
286
287     // Drops the contents of the last chunk. The last chunk is partially empty, unlike all other
288     // chunks.
289     fn clear_last_chunk(&self, last_chunk: &mut ArenaChunk<T>) {
290         // Determine how much was filled.
291         let start = last_chunk.start() as usize;
292         // We obtain the value of the pointer to the first uninitialized element.
293         let end = self.ptr.get() as usize;
294         // We then calculate the number of elements to be dropped in the last chunk,
295         // which is the filled area's length.
296         let diff = if mem::size_of::<T>() == 0 {
297             // `T` is ZST. It can't have a drop flag, so the value here doesn't matter. We get
298             // the number of zero-sized values in the last and only chunk, just out of caution.
299             // Recall that `end` was incremented for each allocated value.
300             end - start
301         } else {
302             (end - start) / mem::size_of::<T>()
303         };
304         // Pass that to the `destroy` method.
305         unsafe {
306             last_chunk.destroy(diff);
307         }
308         // Reset the chunk.
309         self.ptr.set(last_chunk.start());
310     }
311 }
312
313 unsafe impl<#[may_dangle] T> Drop for TypedArena<T> {
314     fn drop(&mut self) {
315         unsafe {
316             // Determine how much was filled.
317             let mut chunks_borrow = self.chunks.borrow_mut();
318             if let Some(mut last_chunk) = chunks_borrow.pop() {
319                 // Drop the contents of the last chunk.
320                 self.clear_last_chunk(&mut last_chunk);
321                 // The last chunk will be dropped. Destroy all other chunks.
322                 for chunk in chunks_borrow.iter_mut() {
323                     chunk.destroy(chunk.entries);
324                 }
325             }
326             // Box handles deallocation of `last_chunk` and `self.chunks`.
327         }
328     }
329 }
330
331 unsafe impl<T: Send> Send for TypedArena<T> {}
332
333 /// An arena that can hold objects of multiple different types that impl `Copy`
334 /// and/or satisfy `!mem::needs_drop`.
335 pub struct DroplessArena {
336     /// A pointer to the start of the free space.
337     start: Cell<*mut u8>,
338
339     /// A pointer to the end of free space.
340     ///
341     /// The allocation proceeds downwards from the end of the chunk towards the
342     /// start. (This is slightly simpler and faster than allocating upwards,
343     /// see <https://fitzgeraldnick.com/2019/11/01/always-bump-downwards.html>.)
344     /// When this pointer crosses the start pointer, a new chunk is allocated.
345     end: Cell<*mut u8>,
346
347     /// A vector of arena chunks.
348     chunks: RefCell<Vec<ArenaChunk>>,
349 }
350
351 unsafe impl Send for DroplessArena {}
352
353 impl Default for DroplessArena {
354     #[inline]
355     fn default() -> DroplessArena {
356         DroplessArena {
357             start: Cell::new(ptr::null_mut()),
358             end: Cell::new(ptr::null_mut()),
359             chunks: Default::default(),
360         }
361     }
362 }
363
364 impl DroplessArena {
365     #[inline(never)]
366     #[cold]
367     fn grow(&self, additional: usize) {
368         unsafe {
369             let mut chunks = self.chunks.borrow_mut();
370             let mut new_cap;
371             if let Some(last_chunk) = chunks.last_mut() {
372                 // There is no need to update `last_chunk.entries` because that
373                 // field isn't used by `DroplessArena`.
374
375                 // If the previous chunk's len is less than HUGE_PAGE
376                 // bytes, then this chunk will be least double the previous
377                 // chunk's size.
378                 new_cap = last_chunk.storage.len().min(HUGE_PAGE / 2);
379                 new_cap *= 2;
380             } else {
381                 new_cap = PAGE;
382             }
383             // Also ensure that this chunk can fit `additional`.
384             new_cap = cmp::max(additional, new_cap);
385
386             let mut chunk = ArenaChunk::new(new_cap);
387             self.start.set(chunk.start());
388             self.end.set(chunk.end());
389             chunks.push(chunk);
390         }
391     }
392
393     /// Allocates a byte slice with specified layout from the current memory
394     /// chunk. Returns `None` if there is no free space left to satisfy the
395     /// request.
396     #[inline]
397     fn alloc_raw_without_grow(&self, layout: Layout) -> Option<*mut u8> {
398         let start = self.start.get() as usize;
399         let end = self.end.get() as usize;
400
401         let align = layout.align();
402         let bytes = layout.size();
403
404         let new_end = end.checked_sub(bytes)? & !(align - 1);
405         if start <= new_end {
406             let new_end = new_end as *mut u8;
407             self.end.set(new_end);
408             Some(new_end)
409         } else {
410             None
411         }
412     }
413
414     #[inline]
415     pub fn alloc_raw(&self, layout: Layout) -> *mut u8 {
416         assert!(layout.size() != 0);
417         loop {
418             if let Some(a) = self.alloc_raw_without_grow(layout) {
419                 break a;
420             }
421             // No free space left. Allocate a new chunk to satisfy the request.
422             // On failure the grow will panic or abort.
423             self.grow(layout.size());
424         }
425     }
426
427     #[inline]
428     pub fn alloc<T>(&self, object: T) -> &mut T {
429         assert!(!mem::needs_drop::<T>());
430
431         let mem = self.alloc_raw(Layout::for_value::<T>(&object)) as *mut T;
432
433         unsafe {
434             // Write into uninitialized memory.
435             ptr::write(mem, object);
436             &mut *mem
437         }
438     }
439
440     /// Allocates a slice of objects that are copied into the `DroplessArena`, returning a mutable
441     /// reference to it. Will panic if passed a zero-sized type.
442     ///
443     /// Panics:
444     ///
445     ///  - Zero-sized types
446     ///  - Zero-length slices
447     #[inline]
448     pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
449     where
450         T: Copy,
451     {
452         assert!(!mem::needs_drop::<T>());
453         assert!(mem::size_of::<T>() != 0);
454         assert!(!slice.is_empty());
455
456         let mem = self.alloc_raw(Layout::for_value::<[T]>(slice)) as *mut T;
457
458         unsafe {
459             mem.copy_from_nonoverlapping(slice.as_ptr(), slice.len());
460             slice::from_raw_parts_mut(mem, slice.len())
461         }
462     }
463
464     #[inline]
465     unsafe fn write_from_iter<T, I: Iterator<Item = T>>(
466         &self,
467         mut iter: I,
468         len: usize,
469         mem: *mut T,
470     ) -> &mut [T] {
471         let mut i = 0;
472         // Use a manual loop since LLVM manages to optimize it better for
473         // slice iterators
474         loop {
475             let value = iter.next();
476             if i >= len || value.is_none() {
477                 // We only return as many items as the iterator gave us, even
478                 // though it was supposed to give us `len`
479                 return slice::from_raw_parts_mut(mem, i);
480             }
481             ptr::write(mem.add(i), value.unwrap());
482             i += 1;
483         }
484     }
485
486     #[inline]
487     pub fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
488         let iter = iter.into_iter();
489         assert!(mem::size_of::<T>() != 0);
490         assert!(!mem::needs_drop::<T>());
491
492         let size_hint = iter.size_hint();
493
494         match size_hint {
495             (min, Some(max)) if min == max => {
496                 // We know the exact number of elements the iterator will produce here
497                 let len = min;
498
499                 if len == 0 {
500                     return &mut [];
501                 }
502
503                 let mem = self.alloc_raw(Layout::array::<T>(len).unwrap()) as *mut T;
504                 unsafe { self.write_from_iter(iter, len, mem) }
505             }
506             (_, _) => {
507                 cold_path(move || -> &mut [T] {
508                     let mut vec: SmallVec<[_; 8]> = iter.collect();
509                     if vec.is_empty() {
510                         return &mut [];
511                     }
512                     // Move the content to the arena by copying it and then forgetting
513                     // the content of the SmallVec
514                     unsafe {
515                         let len = vec.len();
516                         let start_ptr =
517                             self.alloc_raw(Layout::for_value::<[T]>(vec.as_slice())) as *mut T;
518                         vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
519                         vec.set_len(0);
520                         slice::from_raw_parts_mut(start_ptr, len)
521                     }
522                 })
523             }
524         }
525     }
526 }
527
528 /// Declare an `Arena` containing one dropless arena and many typed arenas (the
529 /// types of the typed arenas are specified by the arguments).
530 ///
531 /// There are three cases of interest.
532 /// - Types that are `Copy`: these need not be specified in the arguments. They
533 ///   will use the `DroplessArena`.
534 /// - Types that are `!Copy` and `!Drop`: these must be specified in the
535 ///   arguments. An empty `TypedArena` will be created for each one, but the
536 ///   `DroplessArena` will always be used and the `TypedArena` will stay empty.
537 ///   This is odd but harmless, because an empty arena allocates no memory.
538 /// - Types that are `!Copy` and `Drop`: these must be specified in the
539 ///   arguments. The `TypedArena` will be used for them.
540 ///
541 #[rustc_macro_transparency = "semitransparent"]
542 pub macro declare_arena([$($a:tt $name:ident: $ty:ty,)*]) {
543     #[derive(Default)]
544     pub struct Arena<'tcx> {
545         pub dropless: $crate::DroplessArena,
546         $($name: $crate::TypedArena<$ty>,)*
547     }
548
549     pub trait ArenaAllocatable<'tcx, C = rustc_arena::IsNotCopy>: Sized {
550         fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self;
551         fn allocate_from_iter<'a>(
552             arena: &'a Arena<'tcx>,
553             iter: impl ::std::iter::IntoIterator<Item = Self>,
554         ) -> &'a mut [Self];
555     }
556
557     // Any type that impls `Copy` can be arena-allocated in the `DroplessArena`.
558     impl<'tcx, T: Copy> ArenaAllocatable<'tcx, rustc_arena::IsCopy> for T {
559         #[inline]
560         fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self {
561             arena.dropless.alloc(self)
562         }
563         #[inline]
564         fn allocate_from_iter<'a>(
565             arena: &'a Arena<'tcx>,
566             iter: impl ::std::iter::IntoIterator<Item = Self>,
567         ) -> &'a mut [Self] {
568             arena.dropless.alloc_from_iter(iter)
569         }
570     }
571     $(
572         impl<'tcx> ArenaAllocatable<'tcx, rustc_arena::IsNotCopy> for $ty {
573             #[inline]
574             fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self {
575                 if !::std::mem::needs_drop::<Self>() {
576                     arena.dropless.alloc(self)
577                 } else {
578                     arena.$name.alloc(self)
579                 }
580             }
581
582             #[inline]
583             fn allocate_from_iter<'a>(
584                 arena: &'a Arena<'tcx>,
585                 iter: impl ::std::iter::IntoIterator<Item = Self>,
586             ) -> &'a mut [Self] {
587                 if !::std::mem::needs_drop::<Self>() {
588                     arena.dropless.alloc_from_iter(iter)
589                 } else {
590                     arena.$name.alloc_from_iter(iter)
591                 }
592             }
593         }
594     )*
595
596     impl<'tcx> Arena<'tcx> {
597         #[inline]
598         pub fn alloc<T: ArenaAllocatable<'tcx, C>, C>(&self, value: T) -> &mut T {
599             value.allocate_on(self)
600         }
601
602         // Any type that impls `Copy` can have slices be arena-allocated in the `DroplessArena`.
603         #[inline]
604         pub fn alloc_slice<T: ::std::marker::Copy>(&self, value: &[T]) -> &mut [T] {
605             if value.is_empty() {
606                 return &mut [];
607             }
608             self.dropless.alloc_slice(value)
609         }
610
611         pub fn alloc_from_iter<'a, T: ArenaAllocatable<'tcx, C>, C>(
612             &'a self,
613             iter: impl ::std::iter::IntoIterator<Item = T>,
614         ) -> &'a mut [T] {
615             T::allocate_from_iter(self, iter)
616         }
617     }
618 }
619
620 // Marker types that let us give different behaviour for arenas allocating
621 // `Copy` types vs `!Copy` types.
622 pub struct IsCopy;
623 pub struct IsNotCopy;
624
625 #[cfg(test)]
626 mod tests;