]> git.lizzy.rs Git - rust.git/blob - src/librustc/arena.rs
Rollup merge of #60315 - pietroalbini:fix-tools-version, r=Mark-Simulacrum
[rust.git] / src / librustc / arena.rs
1 use arena::{TypedArena, DroplessArena};
2 use std::mem;
3 use std::ptr;
4 use std::slice;
5 use std::cell::RefCell;
6 use std::marker::PhantomData;
7 use smallvec::SmallVec;
8
9 #[macro_export]
10 macro_rules! arena_types {
11     ($macro:path, $args:tt, $tcx:lifetime) => (
12         $macro!($args, [
13             [] vtable_method: Option<(
14                 rustc::hir::def_id::DefId,
15                 rustc::ty::subst::SubstsRef<$tcx>
16             )>,
17             [few] mir_keys: rustc::util::nodemap::DefIdSet,
18             [decode] specialization_graph: rustc::traits::specialization_graph::Graph,
19             [] region_scope_tree: rustc::middle::region::ScopeTree,
20             [] item_local_set: rustc::util::nodemap::ItemLocalSet,
21             [decode] mir_const_qualif: rustc_data_structures::bit_set::BitSet<rustc::mir::Local>,
22             [] trait_impls_of: rustc::ty::trait_def::TraitImpls,
23             [] dropck_outlives:
24                 rustc::infer::canonical::Canonical<'tcx,
25                     rustc::infer::canonical::QueryResponse<'tcx,
26                         rustc::traits::query::dropck_outlives::DropckOutlivesResult<'tcx>
27                     >
28                 >,
29             [] normalize_projection_ty:
30                 rustc::infer::canonical::Canonical<'tcx,
31                     rustc::infer::canonical::QueryResponse<'tcx,
32                         rustc::traits::query::normalize::NormalizationResult<'tcx>
33                     >
34                 >,
35             [] implied_outlives_bounds:
36                 rustc::infer::canonical::Canonical<'tcx,
37                     rustc::infer::canonical::QueryResponse<'tcx,
38                         Vec<rustc::traits::query::outlives_bounds::OutlivesBound<'tcx>>
39                     >
40                 >,
41             [] type_op_subtype:
42                 rustc::infer::canonical::Canonical<'tcx,
43                     rustc::infer::canonical::QueryResponse<'tcx, ()>
44                 >,
45             [] type_op_normalize_poly_fn_sig:
46                 rustc::infer::canonical::Canonical<'tcx,
47                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::PolyFnSig<'tcx>>
48                 >,
49             [] type_op_normalize_fn_sig:
50                 rustc::infer::canonical::Canonical<'tcx,
51                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::FnSig<'tcx>>
52                 >,
53             [] type_op_normalize_predicate:
54                 rustc::infer::canonical::Canonical<'tcx,
55                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::Predicate<'tcx>>
56                 >,
57             [] type_op_normalize_ty:
58                 rustc::infer::canonical::Canonical<'tcx,
59                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::Ty<'tcx>>
60                 >,
61         ], $tcx);
62     )
63 }
64
65 macro_rules! arena_for_type {
66     ([][$ty:ty]) => {
67         TypedArena<$ty>
68     };
69     ([few $(, $attrs:ident)*][$ty:ty]) => {
70         PhantomData<$ty>
71     };
72     ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
73         arena_for_type!([$($attrs),*]$args)
74     };
75 }
76
77 macro_rules! declare_arena {
78     ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
79         #[derive(Default)]
80         pub struct Arena<$tcx> {
81             dropless: DroplessArena,
82             drop: DropArena,
83             $($name: arena_for_type!($a[$ty]),)*
84         }
85     }
86 }
87
88 macro_rules! which_arena_for_type {
89     ([][$arena:expr]) => {
90         Some($arena)
91     };
92     ([few$(, $attrs:ident)*][$arena:expr]) => {
93         None
94     };
95     ([$ignore:ident$(, $attrs:ident)*]$args:tt) => {
96         which_arena_for_type!([$($attrs),*]$args)
97     };
98 }
99
100 macro_rules! impl_arena_allocatable {
101     ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
102         $(
103             impl ArenaAllocatable for $ty {}
104             unsafe impl<$tcx> ArenaField<$tcx> for $ty {
105                 #[inline]
106                 fn arena<'a>(_arena: &'a Arena<$tcx>) -> Option<&'a TypedArena<Self>> {
107                     which_arena_for_type!($a[&_arena.$name])
108                 }
109             }
110         )*
111     }
112 }
113
114 arena_types!(declare_arena, [], 'tcx);
115
116 arena_types!(impl_arena_allocatable, [], 'tcx);
117
118 pub trait ArenaAllocatable {}
119
120 impl<T: Copy> ArenaAllocatable for T {}
121
122 pub unsafe trait ArenaField<'tcx>: Sized {
123     /// Returns a specific arena to allocate from.
124     /// If None is returned, the DropArena will be used.
125     fn arena<'a>(arena: &'a Arena<'tcx>) -> Option<&'a TypedArena<Self>>;
126 }
127
128 unsafe impl<'tcx, T> ArenaField<'tcx> for T {
129     #[inline]
130     default fn arena<'a>(_: &'a Arena<'tcx>) -> Option<&'a TypedArena<Self>> {
131         panic!()
132     }
133 }
134
135 impl<'tcx> Arena<'tcx> {
136     #[inline]
137     pub fn alloc<T: ArenaAllocatable>(&self, value: T) -> &mut T {
138         if !mem::needs_drop::<T>() {
139             return self.dropless.alloc(value);
140         }
141         match <T as ArenaField<'tcx>>::arena(self) {
142             Some(arena) => arena.alloc(value),
143             None => unsafe { self.drop.alloc(value) },
144         }
145     }
146
147     pub fn alloc_from_iter<
148         T: ArenaAllocatable,
149         I: IntoIterator<Item = T>
150     >(
151         &'a self,
152         iter: I
153     ) -> &'a mut [T] {
154         if !mem::needs_drop::<T>() {
155             return self.dropless.alloc_from_iter(iter);
156         }
157         match <T as ArenaField<'tcx>>::arena(self) {
158             Some(arena) => arena.alloc_from_iter(iter),
159             None => unsafe { self.drop.alloc_from_iter(iter) },
160         }
161     }
162 }
163
164 /// Calls the destructor for an object when dropped.
165 struct DropType {
166     drop_fn: unsafe fn(*mut u8),
167     obj: *mut u8,
168 }
169
170 unsafe fn drop_for_type<T>(to_drop: *mut u8) {
171     std::ptr::drop_in_place(to_drop as *mut T)
172 }
173
174 impl Drop for DropType {
175     fn drop(&mut self) {
176         unsafe {
177             (self.drop_fn)(self.obj)
178         }
179     }
180 }
181
182 /// An arena which can be used to allocate any type.
183 /// Allocating in this arena is unsafe since the type system
184 /// doesn't know which types it contains. In order to
185 /// allocate safely, you must store a PhantomData<T>
186 /// alongside this arena for each type T you allocate.
187 #[derive(Default)]
188 struct DropArena {
189     /// A list of destructors to run when the arena drops.
190     /// Ordered so `destructors` gets dropped before the arena
191     /// since its destructor can reference memory in the arena.
192     destructors: RefCell<Vec<DropType>>,
193     arena: DroplessArena,
194 }
195
196 impl DropArena {
197     #[inline]
198     unsafe fn alloc<T>(&self, object: T) -> &mut T {
199         let mem = self.arena.alloc_raw(
200             mem::size_of::<T>(),
201             mem::align_of::<T>()
202         ) as *mut _ as *mut T;
203         // Write into uninitialized memory.
204         ptr::write(mem, object);
205         let result = &mut *mem;
206         // Record the destructor after doing the allocation as that may panic
207         // and would cause `object`'s destuctor to run twice if it was recorded before
208         self.destructors.borrow_mut().push(DropType {
209             drop_fn: drop_for_type::<T>,
210             obj: result as *mut T as *mut u8,
211         });
212         result
213     }
214
215     #[inline]
216     unsafe fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
217         let mut vec: SmallVec<[_; 8]> = iter.into_iter().collect();
218         if vec.is_empty() {
219             return &mut [];
220         }
221         let len = vec.len();
222
223         let start_ptr = self.arena.alloc_raw(
224             len.checked_mul(mem::size_of::<T>()).unwrap(),
225             mem::align_of::<T>()
226         ) as *mut _ as *mut T;
227
228         let mut destructors = self.destructors.borrow_mut();
229         // Reserve space for the destructors so we can't panic while adding them
230         destructors.reserve(len);
231
232         // Move the content to the arena by copying it and then forgetting
233         // the content of the SmallVec
234         vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
235         mem::forget(vec.drain());
236
237         // Record the destructors after doing the allocation as that may panic
238         // and would cause `object`'s destuctor to run twice if it was recorded before
239         for i in 0..len {
240             destructors.push(DropType {
241                 drop_fn: drop_for_type::<T>,
242                 obj: start_ptr.offset(i as isize) as *mut u8,
243             });
244         }
245
246         slice::from_raw_parts_mut(start_ptr, len)
247     }
248 }