]> git.lizzy.rs Git - rust.git/blob - src/librustc/arena.rs
Rollup merge of #61077 - nnethercote:tweak-prefill, r=petrochenkov
[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 /// This declares a list of types which can be allocated by `Arena`.
10 ///
11 /// The `few` modifier will cause allocation to use the shared arena and recording the destructor.
12 /// This is faster and more memory efficient if there's only a few allocations of the type.
13 /// Leaving `few` out will cause the type to get its own dedicated `TypedArena` which is
14 /// faster and more memory efficient if there is lots of allocations.
15 ///
16 /// Specifying the `decode` modifier will add decode impls for &T and &[T] where T is the type
17 /// listed. These impls will appear in the implement_ty_decoder! macro.
18 #[macro_export]
19 macro_rules! arena_types {
20     ($macro:path, $args:tt, $tcx:lifetime) => (
21         $macro!($args, [
22             [] vtable_method: Option<(
23                 rustc::hir::def_id::DefId,
24                 rustc::ty::subst::SubstsRef<$tcx>
25             )>,
26             [few, decode] mir_keys: rustc::util::nodemap::DefIdSet,
27             [decode] specialization_graph: rustc::traits::specialization_graph::Graph,
28             [] region_scope_tree: rustc::middle::region::ScopeTree,
29             [] item_local_set: rustc::util::nodemap::ItemLocalSet,
30             [decode] mir_const_qualif: rustc_data_structures::bit_set::BitSet<rustc::mir::Local>,
31             [] trait_impls_of: rustc::ty::trait_def::TraitImpls,
32             [] dropck_outlives:
33                 rustc::infer::canonical::Canonical<'tcx,
34                     rustc::infer::canonical::QueryResponse<'tcx,
35                         rustc::traits::query::dropck_outlives::DropckOutlivesResult<'tcx>
36                     >
37                 >,
38             [] normalize_projection_ty:
39                 rustc::infer::canonical::Canonical<'tcx,
40                     rustc::infer::canonical::QueryResponse<'tcx,
41                         rustc::traits::query::normalize::NormalizationResult<'tcx>
42                     >
43                 >,
44             [] implied_outlives_bounds:
45                 rustc::infer::canonical::Canonical<'tcx,
46                     rustc::infer::canonical::QueryResponse<'tcx,
47                         Vec<rustc::traits::query::outlives_bounds::OutlivesBound<'tcx>>
48                     >
49                 >,
50             [] type_op_subtype:
51                 rustc::infer::canonical::Canonical<'tcx,
52                     rustc::infer::canonical::QueryResponse<'tcx, ()>
53                 >,
54             [] type_op_normalize_poly_fn_sig:
55                 rustc::infer::canonical::Canonical<'tcx,
56                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::PolyFnSig<'tcx>>
57                 >,
58             [] type_op_normalize_fn_sig:
59                 rustc::infer::canonical::Canonical<'tcx,
60                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::FnSig<'tcx>>
61                 >,
62             [] type_op_normalize_predicate:
63                 rustc::infer::canonical::Canonical<'tcx,
64                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::Predicate<'tcx>>
65                 >,
66             [] type_op_normalize_ty:
67                 rustc::infer::canonical::Canonical<'tcx,
68                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::Ty<'tcx>>
69                 >,
70             [few] crate_inherent_impls: rustc::ty::CrateInherentImpls,
71             [decode] borrowck: rustc::middle::borrowck::BorrowCheckResult,
72             [few] upstream_monomorphizations:
73                 rustc::util::nodemap::DefIdMap<
74                     rustc_data_structures::fx::FxHashMap<
75                         rustc::ty::subst::SubstsRef<'tcx>,
76                         rustc::hir::def_id::CrateNum
77                     >
78                 >,
79             [few] resolve_lifetimes: rustc::middle::resolve_lifetime::ResolveLifetimes,
80             [decode] generic_predicates: rustc::ty::GenericPredicates<'tcx>,
81             [few] lint_levels: rustc::lint::LintLevelMap,
82             [few] stability_index: rustc::middle::stability::Index<'tcx>,
83             [few] features: syntax::feature_gate::Features,
84             [few] all_traits: Vec<rustc::hir::def_id::DefId>,
85             [few] privacy_access_levels: rustc::middle::privacy::AccessLevels,
86             [few] target_features_whitelist: rustc_data_structures::fx::FxHashMap<
87                 String,
88                 Option<syntax::symbol::Symbol>
89             >,
90             [few] wasm_import_module_map: rustc_data_structures::fx::FxHashMap<
91                 rustc::hir::def_id::DefId,
92                 String
93             >,
94             [few] get_lib_features: rustc::middle::lib_features::LibFeatures,
95             [few] defined_lib_features: rustc::middle::lang_items::LanguageItems,
96             [few] visible_parent_map: rustc::util::nodemap::DefIdMap<rustc::hir::def_id::DefId>,
97             [few] foreign_module: rustc::middle::cstore::ForeignModule,
98             [few] foreign_modules: Vec<rustc::middle::cstore::ForeignModule>,
99             [few] reachable_non_generics: rustc::util::nodemap::DefIdMap<
100                 rustc::middle::exported_symbols::SymbolExportLevel
101             >,
102             [few] crate_variances: rustc::ty::CrateVariancesMap<'tcx>,
103             [few] inferred_outlives_crate: rustc::ty::CratePredicatesMap<'tcx>,
104         ], $tcx);
105     )
106 }
107
108 macro_rules! arena_for_type {
109     ([][$ty:ty]) => {
110         TypedArena<$ty>
111     };
112     ([few $(, $attrs:ident)*][$ty:ty]) => {
113         PhantomData<$ty>
114     };
115     ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
116         arena_for_type!([$($attrs),*]$args)
117     };
118 }
119
120 macro_rules! declare_arena {
121     ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
122         #[derive(Default)]
123         pub struct Arena<$tcx> {
124             dropless: DroplessArena,
125             drop: DropArena,
126             $($name: arena_for_type!($a[$ty]),)*
127         }
128     }
129 }
130
131 macro_rules! which_arena_for_type {
132     ([][$arena:expr]) => {
133         Some($arena)
134     };
135     ([few$(, $attrs:ident)*][$arena:expr]) => {
136         None
137     };
138     ([$ignore:ident$(, $attrs:ident)*]$args:tt) => {
139         which_arena_for_type!([$($attrs),*]$args)
140     };
141 }
142
143 macro_rules! impl_arena_allocatable {
144     ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
145         $(
146             impl ArenaAllocatable for $ty {}
147             unsafe impl<$tcx> ArenaField<$tcx> for $ty {
148                 #[inline]
149                 fn arena<'a>(_arena: &'a Arena<$tcx>) -> Option<&'a TypedArena<Self>> {
150                     which_arena_for_type!($a[&_arena.$name])
151                 }
152             }
153         )*
154     }
155 }
156
157 arena_types!(declare_arena, [], 'tcx);
158
159 arena_types!(impl_arena_allocatable, [], 'tcx);
160
161 pub trait ArenaAllocatable {}
162
163 impl<T: Copy> ArenaAllocatable for T {}
164
165 unsafe trait ArenaField<'tcx>: Sized {
166     /// Returns a specific arena to allocate from.
167     /// If None is returned, the DropArena will be used.
168     fn arena<'a>(arena: &'a Arena<'tcx>) -> Option<&'a TypedArena<Self>>;
169 }
170
171 unsafe impl<'tcx, T> ArenaField<'tcx> for T {
172     #[inline]
173     default fn arena<'a>(_: &'a Arena<'tcx>) -> Option<&'a TypedArena<Self>> {
174         panic!()
175     }
176 }
177
178 impl<'tcx> Arena<'tcx> {
179     #[inline]
180     pub fn alloc<T: ArenaAllocatable>(&self, value: T) -> &mut T {
181         if !mem::needs_drop::<T>() {
182             return self.dropless.alloc(value);
183         }
184         match <T as ArenaField<'tcx>>::arena(self) {
185             Some(arena) => arena.alloc(value),
186             None => unsafe { self.drop.alloc(value) },
187         }
188     }
189
190     #[inline]
191     pub fn alloc_slice<T: Copy>(&self, value: &[T]) -> &mut [T] {
192         if value.len() == 0 {
193             return &mut []
194         }
195         self.dropless.alloc_slice(value)
196     }
197
198     pub fn alloc_from_iter<
199         T: ArenaAllocatable,
200         I: IntoIterator<Item = T>
201     >(
202         &'a self,
203         iter: I
204     ) -> &'a mut [T] {
205         if !mem::needs_drop::<T>() {
206             return self.dropless.alloc_from_iter(iter);
207         }
208         match <T as ArenaField<'tcx>>::arena(self) {
209             Some(arena) => arena.alloc_from_iter(iter),
210             None => unsafe { self.drop.alloc_from_iter(iter) },
211         }
212     }
213 }
214
215 /// Calls the destructor for an object when dropped.
216 struct DropType {
217     drop_fn: unsafe fn(*mut u8),
218     obj: *mut u8,
219 }
220
221 unsafe fn drop_for_type<T>(to_drop: *mut u8) {
222     std::ptr::drop_in_place(to_drop as *mut T)
223 }
224
225 impl Drop for DropType {
226     fn drop(&mut self) {
227         unsafe {
228             (self.drop_fn)(self.obj)
229         }
230     }
231 }
232
233 /// An arena which can be used to allocate any type.
234 /// Allocating in this arena is unsafe since the type system
235 /// doesn't know which types it contains. In order to
236 /// allocate safely, you must store a PhantomData<T>
237 /// alongside this arena for each type T you allocate.
238 #[derive(Default)]
239 struct DropArena {
240     /// A list of destructors to run when the arena drops.
241     /// Ordered so `destructors` gets dropped before the arena
242     /// since its destructor can reference memory in the arena.
243     destructors: RefCell<Vec<DropType>>,
244     arena: DroplessArena,
245 }
246
247 impl DropArena {
248     #[inline]
249     unsafe fn alloc<T>(&self, object: T) -> &mut T {
250         let mem = self.arena.alloc_raw(
251             mem::size_of::<T>(),
252             mem::align_of::<T>()
253         ) as *mut _ as *mut T;
254         // Write into uninitialized memory.
255         ptr::write(mem, object);
256         let result = &mut *mem;
257         // Record the destructor after doing the allocation as that may panic
258         // and would cause `object`'s destuctor to run twice if it was recorded before
259         self.destructors.borrow_mut().push(DropType {
260             drop_fn: drop_for_type::<T>,
261             obj: result as *mut T as *mut u8,
262         });
263         result
264     }
265
266     #[inline]
267     unsafe fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
268         let mut vec: SmallVec<[_; 8]> = iter.into_iter().collect();
269         if vec.is_empty() {
270             return &mut [];
271         }
272         let len = vec.len();
273
274         let start_ptr = self.arena.alloc_raw(
275             len.checked_mul(mem::size_of::<T>()).unwrap(),
276             mem::align_of::<T>()
277         ) as *mut _ as *mut T;
278
279         let mut destructors = self.destructors.borrow_mut();
280         // Reserve space for the destructors so we can't panic while adding them
281         destructors.reserve(len);
282
283         // Move the content to the arena by copying it and then forgetting
284         // the content of the SmallVec
285         vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
286         mem::forget(vec.drain());
287
288         // Record the destructors after doing the allocation as that may panic
289         // and would cause `object`'s destuctor to run twice if it was recorded before
290         for i in 0..len {
291             destructors.push(DropType {
292                 drop_fn: drop_for_type::<T>,
293                 obj: start_ptr.offset(i as isize) as *mut u8,
294             });
295         }
296
297         slice::from_raw_parts_mut(start_ptr, len)
298     }
299 }