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