]> git.lizzy.rs Git - rust.git/blob - src/libarena/lib.rs
Rollup merge of #65965 - GuillaumeGomez:clean-up-librustc_typeck-error-codes, r=Mark...
[rust.git] / src / libarena / 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 `TypedArena`, a simple arena that can only hold
9 //! objects of a single type.
10
11 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
12        test(no_crate_inject, attr(deny(warnings))))]
13
14 #![feature(core_intrinsics)]
15 #![feature(dropck_eyepatch)]
16 #![feature(raw_vec_internals)]
17 #![cfg_attr(test, feature(test))]
18
19 #![allow(deprecated)]
20
21 extern crate alloc;
22
23 use rustc_data_structures::cold_path;
24 use rustc_data_structures::sync::MTLock;
25 use smallvec::SmallVec;
26
27 use std::cell::{Cell, RefCell};
28 use std::cmp;
29 use std::intrinsics;
30 use std::marker::{PhantomData, Send};
31 use std::mem;
32 use std::ptr;
33 use std::slice;
34
35 use alloc::raw_vec::RawVec;
36
37 /// An arena that can hold objects of only one type.
38 pub struct TypedArena<T> {
39     /// A pointer to the next object to be allocated.
40     ptr: Cell<*mut T>,
41
42     /// A pointer to the end of the allocated area. When this pointer is
43     /// reached, a new chunk is allocated.
44     end: Cell<*mut T>,
45
46     /// A vector of arena chunks.
47     chunks: RefCell<Vec<TypedArenaChunk<T>>>,
48
49     /// Marker indicating that dropping the arena causes its owned
50     /// instances of `T` to be dropped.
51     _own: PhantomData<T>,
52 }
53
54 struct TypedArenaChunk<T> {
55     /// The raw storage for the arena chunk.
56     storage: RawVec<T>,
57     /// The number of valid entries in the chunk.
58     entries: usize,
59 }
60
61 impl<T> TypedArenaChunk<T> {
62     #[inline]
63     unsafe fn new(capacity: usize) -> TypedArenaChunk<T> {
64         TypedArenaChunk {
65             storage: RawVec::with_capacity(capacity),
66             entries: 0,
67         }
68     }
69
70     /// Destroys this arena chunk.
71     #[inline]
72     unsafe fn destroy(&mut self, len: usize) {
73         // The branch on needs_drop() is an -O1 performance optimization.
74         // Without the branch, dropping TypedArena<u8> takes linear time.
75         if mem::needs_drop::<T>() {
76             let mut start = self.start();
77             // Destroy all allocated objects.
78             for _ in 0..len {
79                 ptr::drop_in_place(start);
80                 start = start.offset(1);
81             }
82         }
83     }
84
85     // Returns a pointer to the first allocated object.
86     #[inline]
87     fn start(&self) -> *mut T {
88         self.storage.ptr()
89     }
90
91     // Returns a pointer to the end of the allocated space.
92     #[inline]
93     fn end(&self) -> *mut T {
94         unsafe {
95             if mem::size_of::<T>() == 0 {
96                 // A pointer as large as possible for zero-sized elements.
97                 !0 as *mut T
98             } else {
99                 self.start().add(self.storage.capacity())
100             }
101         }
102     }
103 }
104
105 const PAGE: usize = 4096;
106
107 impl<T> Default for TypedArena<T> {
108     /// Creates a new `TypedArena`.
109     fn default() -> TypedArena<T> {
110         TypedArena {
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: RefCell::new(vec![]),
116             _own: PhantomData,
117         }
118     }
119 }
120
121 impl<T> TypedArena<T> {
122     pub fn in_arena(&self, ptr: *const T) -> bool {
123         let ptr = ptr as *const T as *mut T;
124
125         self.chunks.borrow().iter().any(|chunk| chunk.start() <= ptr && ptr < chunk.end())
126     }
127     /// Allocates an object in the `TypedArena`, returning a reference to it.
128     #[inline]
129     pub fn alloc(&self, object: T) -> &mut T {
130         if self.ptr == self.end {
131             self.grow(1)
132         }
133
134         unsafe {
135             if mem::size_of::<T>() == 0 {
136                 self.ptr
137                     .set(intrinsics::arith_offset(self.ptr.get() as *mut u8, 1)
138                         as *mut T);
139                 let ptr = mem::align_of::<T>() as *mut T;
140                 // Don't drop the object. This `write` is equivalent to `forget`.
141                 ptr::write(ptr, object);
142                 &mut *ptr
143             } else {
144                 let ptr = self.ptr.get();
145                 // Advance the pointer.
146                 self.ptr.set(self.ptr.get().offset(1));
147                 // Write into uninitialized memory.
148                 ptr::write(ptr, object);
149                 &mut *ptr
150             }
151         }
152     }
153
154     #[inline]
155     fn can_allocate(&self, len: usize) -> bool {
156         let available_capacity_bytes = self.end.get() as usize - self.ptr.get() as usize;
157         let at_least_bytes = len.checked_mul(mem::size_of::<T>()).unwrap();
158         available_capacity_bytes >= at_least_bytes
159     }
160
161     /// Ensures there's enough space in the current chunk to fit `len` objects.
162     #[inline]
163     fn ensure_capacity(&self, len: usize) {
164         if !self.can_allocate(len) {
165             self.grow(len);
166             debug_assert!(self.can_allocate(len));
167         }
168     }
169
170     #[inline]
171     unsafe fn alloc_raw_slice(&self, len: usize) -> *mut T {
172         assert!(mem::size_of::<T>() != 0);
173         assert!(len != 0);
174
175         self.ensure_capacity(len);
176
177         let start_ptr = self.ptr.get();
178         self.ptr.set(start_ptr.add(len));
179         start_ptr
180     }
181
182     /// Allocates a slice of objects that are copied into the `TypedArena`, returning a mutable
183     /// reference to it. Will panic if passed a zero-sized types.
184     ///
185     /// Panics:
186     ///
187     ///  - Zero-sized types
188     ///  - Zero-length slices
189     #[inline]
190     pub fn alloc_slice(&self, slice: &[T]) -> &mut [T]
191     where
192         T: Copy,
193     {
194         unsafe {
195             let len = slice.len();
196             let start_ptr = self.alloc_raw_slice(len);
197             slice.as_ptr().copy_to_nonoverlapping(start_ptr, len);
198             slice::from_raw_parts_mut(start_ptr, len)
199         }
200     }
201
202     #[inline]
203     pub fn alloc_from_iter<I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
204         assert!(mem::size_of::<T>() != 0);
205         let mut iter = iter.into_iter();
206         let size_hint = iter.size_hint();
207
208         match size_hint {
209             (min, Some(max)) if min == max => {
210                 // We know the exact number of elements the iterator will produce here
211                 let len = min;
212
213                 if len == 0 {
214                     return &mut [];
215                 }
216
217                 self.ensure_capacity(len);
218
219                 let slice = self.ptr.get();
220
221                 unsafe {
222                     let mut ptr = self.ptr.get();
223                     for _ in 0..len {
224                         // Write into uninitialized memory.
225                         ptr::write(ptr, iter.next().unwrap());
226                         // Advance the pointer.
227                         ptr = ptr.offset(1);
228                         // Update the pointer per iteration so if `iter.next()` panics
229                         // we destroy the correct amount
230                         self.ptr.set(ptr);
231                     }
232                     slice::from_raw_parts_mut(slice, len)
233                 }
234             }
235             _ => {
236                 cold_path(move || -> &mut [T] {
237                     let mut vec: SmallVec<[_; 8]> = iter.collect();
238                     if vec.is_empty() {
239                         return &mut [];
240                     }
241                     // Move the content to the arena by copying it and then forgetting
242                     // the content of the SmallVec
243                     unsafe {
244                         let len = vec.len();
245                         let start_ptr = self.alloc_raw_slice(len);
246                         vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
247                         vec.set_len(0);
248                         slice::from_raw_parts_mut(start_ptr, len)
249                     }
250                 })
251             }
252         }
253     }
254
255     /// Grows the arena.
256     #[inline(never)]
257     #[cold]
258     fn grow(&self, n: usize) {
259         unsafe {
260             let mut chunks = self.chunks.borrow_mut();
261             let (chunk, mut new_capacity);
262             if let Some(last_chunk) = chunks.last_mut() {
263                 let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
264                 let currently_used_cap = used_bytes / mem::size_of::<T>();
265                 last_chunk.entries = currently_used_cap;
266                 if last_chunk.storage.reserve_in_place(currently_used_cap, n) {
267                     self.end.set(last_chunk.end());
268                     return;
269                 } else {
270                     new_capacity = last_chunk.storage.capacity();
271                     loop {
272                         new_capacity = new_capacity.checked_mul(2).unwrap();
273                         if new_capacity >= currently_used_cap + n {
274                             break;
275                         }
276                     }
277                 }
278             } else {
279                 let elem_size = cmp::max(1, mem::size_of::<T>());
280                 new_capacity = cmp::max(n, PAGE / elem_size);
281             }
282             chunk = TypedArenaChunk::<T>::new(new_capacity);
283             self.ptr.set(chunk.start());
284             self.end.set(chunk.end());
285             chunks.push(chunk);
286         }
287     }
288
289     /// Clears the arena. Deallocates all but the longest chunk which may be reused.
290     pub fn clear(&mut self) {
291         unsafe {
292             // Clear the last chunk, which is partially filled.
293             let mut chunks_borrow = self.chunks.borrow_mut();
294             if let Some(mut last_chunk) = chunks_borrow.last_mut() {
295                 self.clear_last_chunk(&mut last_chunk);
296                 let len = chunks_borrow.len();
297                 // If `T` is ZST, code below has no effect.
298                 for mut chunk in chunks_borrow.drain(..len-1) {
299                     chunk.destroy(chunk.entries);
300                 }
301             }
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 TypedArenaChunk<T>) {
308         // Determine how much was filled.
309         let start = last_chunk.start() as usize;
310         // We obtain the value of the pointer to the first uninitialized element.
311         let end = self.ptr.get() as usize;
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             (end - start) / mem::size_of::<T>()
321         };
322         // Pass that to the `destroy` method.
323         unsafe {
324             last_chunk.destroy(diff);
325         }
326         // Reset the chunk.
327         self.ptr.set(last_chunk.start());
328     }
329 }
330
331 unsafe impl<#[may_dangle] T> Drop for TypedArena<T> {
332     fn drop(&mut self) {
333         unsafe {
334             // Determine how much was filled.
335             let mut chunks_borrow = self.chunks.borrow_mut();
336             if let Some(mut last_chunk) = chunks_borrow.pop() {
337                 // Drop the contents of the last chunk.
338                 self.clear_last_chunk(&mut last_chunk);
339                 // The last chunk will be dropped. Destroy all other chunks.
340                 for chunk in chunks_borrow.iter_mut() {
341                     chunk.destroy(chunk.entries);
342                 }
343             }
344             // RawVec handles deallocation of `last_chunk` and `self.chunks`.
345         }
346     }
347 }
348
349 unsafe impl<T: Send> Send for TypedArena<T> {}
350
351 pub struct DroplessArena {
352     /// A pointer to the next object to be allocated.
353     ptr: Cell<*mut u8>,
354
355     /// A pointer to the end of the allocated area. When this pointer is
356     /// reached, a new chunk is allocated.
357     end: Cell<*mut u8>,
358
359     /// A vector of arena chunks.
360     chunks: RefCell<Vec<TypedArenaChunk<u8>>>,
361 }
362
363 unsafe impl Send for DroplessArena {}
364
365 impl Default for DroplessArena {
366     #[inline]
367     fn default() -> DroplessArena {
368         DroplessArena {
369             ptr: Cell::new(ptr::null_mut()),
370             end: Cell::new(ptr::null_mut()),
371             chunks: Default::default(),
372         }
373     }
374 }
375
376 impl DroplessArena {
377     pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool {
378         let ptr = ptr as *const u8 as *mut u8;
379
380         self.chunks.borrow().iter().any(|chunk| chunk.start() <= ptr && ptr < chunk.end())
381     }
382
383     #[inline]
384     fn align(&self, align: usize) {
385         let final_address = ((self.ptr.get() as usize) + align - 1) & !(align - 1);
386         self.ptr.set(final_address as *mut u8);
387         assert!(self.ptr <= self.end);
388     }
389
390     #[inline(never)]
391     #[cold]
392     fn grow(&self, needed_bytes: usize) {
393         unsafe {
394             let mut chunks = self.chunks.borrow_mut();
395             let (chunk, mut new_capacity);
396             if let Some(last_chunk) = chunks.last_mut() {
397                 let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
398                 if last_chunk
399                     .storage
400                     .reserve_in_place(used_bytes, needed_bytes)
401                 {
402                     self.end.set(last_chunk.end());
403                     return;
404                 } else {
405                     new_capacity = last_chunk.storage.capacity();
406                     loop {
407                         new_capacity = new_capacity.checked_mul(2).unwrap();
408                         if new_capacity >= used_bytes + needed_bytes {
409                             break;
410                         }
411                     }
412                 }
413             } else {
414                 new_capacity = cmp::max(needed_bytes, PAGE);
415             }
416             chunk = TypedArenaChunk::<u8>::new(new_capacity);
417             self.ptr.set(chunk.start());
418             self.end.set(chunk.end());
419             chunks.push(chunk);
420         }
421     }
422
423     #[inline]
424     pub fn alloc_raw(&self, bytes: usize, align: usize) -> &mut [u8] {
425         unsafe {
426             assert!(bytes != 0);
427
428             self.align(align);
429
430             let future_end = intrinsics::arith_offset(self.ptr.get(), bytes as isize);
431             if (future_end as *mut u8) >= self.end.get() {
432                 self.grow(bytes);
433             }
434
435             let ptr = self.ptr.get();
436             // Set the pointer past ourselves
437             self.ptr.set(
438                 intrinsics::arith_offset(self.ptr.get(), bytes as isize) as *mut u8,
439             );
440             slice::from_raw_parts_mut(ptr, bytes)
441         }
442     }
443
444     #[inline]
445     pub fn alloc<T>(&self, object: T) -> &mut T {
446         assert!(!mem::needs_drop::<T>());
447
448         let mem = self.alloc_raw(
449             mem::size_of::<T>(),
450             mem::align_of::<T>()) as *mut _ as *mut T;
451
452         unsafe {
453             // Write into uninitialized memory.
454             ptr::write(mem, object);
455             &mut *mem
456         }
457     }
458
459     /// Allocates a slice of objects that are copied into the `DroplessArena`, returning a mutable
460     /// reference to it. Will panic if passed a zero-sized type.
461     ///
462     /// Panics:
463     ///
464     ///  - Zero-sized types
465     ///  - Zero-length slices
466     #[inline]
467     pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
468     where
469         T: Copy,
470     {
471         assert!(!mem::needs_drop::<T>());
472         assert!(mem::size_of::<T>() != 0);
473         assert!(!slice.is_empty());
474
475         let mem = self.alloc_raw(
476             slice.len() * mem::size_of::<T>(),
477             mem::align_of::<T>()) as *mut _ as *mut T;
478
479         unsafe {
480             let arena_slice = slice::from_raw_parts_mut(mem, slice.len());
481             arena_slice.copy_from_slice(slice);
482             arena_slice
483         }
484     }
485
486     #[inline]
487     unsafe fn write_from_iter<T, I: Iterator<Item = T>>(
488         &self,
489         mut iter: I,
490         len: usize,
491         mem: *mut T,
492     ) -> &mut [T] {
493         let mut i = 0;
494         // Use a manual loop since LLVM manages to optimize it better for
495         // slice iterators
496         loop {
497             let value = iter.next();
498             if i >= len || value.is_none() {
499                 // We only return as many items as the iterator gave us, even
500                 // though it was supposed to give us `len`
501                 return slice::from_raw_parts_mut(mem, i);
502             }
503             ptr::write(mem.add(i), value.unwrap());
504             i += 1;
505         }
506     }
507
508     #[inline]
509     pub fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
510         let iter = iter.into_iter();
511         assert!(mem::size_of::<T>() != 0);
512         assert!(!mem::needs_drop::<T>());
513
514         let size_hint = iter.size_hint();
515
516         match size_hint {
517             (min, Some(max)) if min == max => {
518                 // We know the exact number of elements the iterator will produce here
519                 let len = min;
520
521                 if len == 0 {
522                     return &mut []
523                 }
524                 let size = len.checked_mul(mem::size_of::<T>()).unwrap();
525                 let mem = self.alloc_raw(size, mem::align_of::<T>()) as *mut _ as *mut T;
526                 unsafe {
527                     self.write_from_iter(iter, len, mem)
528                 }
529             }
530             (_, _) => {
531                 cold_path(move || -> &mut [T] {
532                     let mut vec: SmallVec<[_; 8]> = iter.collect();
533                     if vec.is_empty() {
534                         return &mut [];
535                     }
536                     // Move the content to the arena by copying it and then forgetting
537                     // the content of the SmallVec
538                     unsafe {
539                         let len = vec.len();
540                         let start_ptr = self.alloc_raw(
541                             len * mem::size_of::<T>(),
542                             mem::align_of::<T>()
543                         ) as *mut _ as *mut T;
544                         vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
545                         vec.set_len(0);
546                         slice::from_raw_parts_mut(start_ptr, len)
547                     }
548                 })
549             }
550         }
551     }
552 }
553
554 #[derive(Default)]
555 // FIXME(@Zoxc): this type is entirely unused in rustc
556 pub struct SyncTypedArena<T> {
557     lock: MTLock<TypedArena<T>>,
558 }
559
560 impl<T> SyncTypedArena<T> {
561     #[inline(always)]
562     pub fn alloc(&self, object: T) -> &mut T {
563         // Extend the lifetime of the result since it's limited to the lock guard
564         unsafe { &mut *(self.lock.lock().alloc(object) as *mut T) }
565     }
566
567     #[inline(always)]
568     pub fn alloc_slice(&self, slice: &[T]) -> &mut [T]
569     where
570         T: Copy,
571     {
572         // Extend the lifetime of the result since it's limited to the lock guard
573         unsafe { &mut *(self.lock.lock().alloc_slice(slice) as *mut [T]) }
574     }
575
576     #[inline(always)]
577     pub fn clear(&mut self) {
578         self.lock.get_mut().clear();
579     }
580 }
581
582 #[derive(Default)]
583 pub struct SyncDroplessArena {
584     lock: MTLock<DroplessArena>,
585 }
586
587 impl SyncDroplessArena {
588     #[inline(always)]
589     pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool {
590         self.lock.lock().in_arena(ptr)
591     }
592
593     #[inline(always)]
594     pub fn alloc_raw(&self, bytes: usize, align: usize) -> &mut [u8] {
595         // Extend the lifetime of the result since it's limited to the lock guard
596         unsafe { &mut *(self.lock.lock().alloc_raw(bytes, align) as *mut [u8]) }
597     }
598
599     #[inline(always)]
600     pub fn alloc<T>(&self, object: T) -> &mut T {
601         // Extend the lifetime of the result since it's limited to the lock guard
602         unsafe { &mut *(self.lock.lock().alloc(object) as *mut T) }
603     }
604
605     #[inline(always)]
606     pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
607     where
608         T: Copy,
609     {
610         // Extend the lifetime of the result since it's limited to the lock guard
611         unsafe { &mut *(self.lock.lock().alloc_slice(slice) as *mut [T]) }
612     }
613 }
614
615 #[cfg(test)]
616 mod tests;