]> git.lizzy.rs Git - rust.git/blob - src/librustc/arena.rs
Rollup merge of #68033 - ollie27:win_f32, r=dtolnay
[rust.git] / src / librustc / arena.rs
1 use arena::{DroplessArena, TypedArena};
2 use smallvec::SmallVec;
3 use std::cell::RefCell;
4 use std::marker::PhantomData;
5 use std::mem;
6 use std::ptr;
7 use std::slice;
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             [] layouts: rustc::ty::layout::LayoutDetails,
23             [] generics: rustc::ty::Generics,
24             [] trait_def: rustc::ty::TraitDef,
25             [] adt_def: rustc::ty::AdtDef,
26             [] steal_mir: rustc::ty::steal::Steal<rustc::mir::BodyAndCache<$tcx>>,
27             [] mir: rustc::mir::BodyAndCache<$tcx>,
28             [] steal_promoted: rustc::ty::steal::Steal<
29                 rustc_index::vec::IndexVec<
30                     rustc::mir::Promoted,
31                     rustc::mir::BodyAndCache<$tcx>
32                 >
33             >,
34             [] promoted: rustc_index::vec::IndexVec<
35                 rustc::mir::Promoted,
36                 rustc::mir::BodyAndCache<$tcx>
37             >,
38             [] tables: rustc::ty::TypeckTables<$tcx>,
39             [] const_allocs: rustc::mir::interpret::Allocation,
40             [] vtable_method: Option<(
41                 rustc_hir::def_id::DefId,
42                 rustc::ty::subst::SubstsRef<$tcx>
43             )>,
44             [few, decode] mir_keys: rustc_hir::def_id::DefIdSet,
45             [decode] specialization_graph: rustc::traits::specialization_graph::Graph,
46             [] region_scope_tree: rustc::middle::region::ScopeTree,
47             [] item_local_set: rustc_hir::ItemLocalSet,
48             [decode] mir_const_qualif: rustc_index::bit_set::BitSet<rustc::mir::Local>,
49             [] trait_impls_of: rustc::ty::trait_def::TraitImpls,
50             [] dropck_outlives:
51                 rustc::infer::canonical::Canonical<'tcx,
52                     rustc::infer::canonical::QueryResponse<'tcx,
53                         rustc::traits::query::dropck_outlives::DropckOutlivesResult<'tcx>
54                     >
55                 >,
56             [] normalize_projection_ty:
57                 rustc::infer::canonical::Canonical<'tcx,
58                     rustc::infer::canonical::QueryResponse<'tcx,
59                         rustc::traits::query::normalize::NormalizationResult<'tcx>
60                     >
61                 >,
62             [] implied_outlives_bounds:
63                 rustc::infer::canonical::Canonical<'tcx,
64                     rustc::infer::canonical::QueryResponse<'tcx,
65                         Vec<rustc::traits::query::outlives_bounds::OutlivesBound<'tcx>>
66                     >
67                 >,
68             [] type_op_subtype:
69                 rustc::infer::canonical::Canonical<'tcx,
70                     rustc::infer::canonical::QueryResponse<'tcx, ()>
71                 >,
72             [] type_op_normalize_poly_fn_sig:
73                 rustc::infer::canonical::Canonical<'tcx,
74                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::PolyFnSig<'tcx>>
75                 >,
76             [] type_op_normalize_fn_sig:
77                 rustc::infer::canonical::Canonical<'tcx,
78                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::FnSig<'tcx>>
79                 >,
80             [] type_op_normalize_predicate:
81                 rustc::infer::canonical::Canonical<'tcx,
82                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::Predicate<'tcx>>
83                 >,
84             [] type_op_normalize_ty:
85                 rustc::infer::canonical::Canonical<'tcx,
86                     rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::Ty<'tcx>>
87                 >,
88             [few] crate_inherent_impls: rustc::ty::CrateInherentImpls,
89             [few] upstream_monomorphizations:
90                 rustc_hir::def_id::DefIdMap<
91                     rustc_data_structures::fx::FxHashMap<
92                         rustc::ty::subst::SubstsRef<'tcx>,
93                         rustc_hir::def_id::CrateNum
94                     >
95                 >,
96             [few] diagnostic_items: rustc_data_structures::fx::FxHashMap<
97                 rustc_span::symbol::Symbol,
98                 rustc_hir::def_id::DefId,
99             >,
100             [few] resolve_lifetimes: rustc::middle::resolve_lifetime::ResolveLifetimes,
101             [few] lint_levels: rustc::lint::LintLevelMap,
102             [few] stability_index: rustc::middle::stability::Index<'tcx>,
103             [few] features: rustc_feature::Features,
104             [few] all_traits: Vec<rustc_hir::def_id::DefId>,
105             [few] privacy_access_levels: rustc::middle::privacy::AccessLevels,
106             [few] target_features_whitelist: rustc_data_structures::fx::FxHashMap<
107                 String,
108                 Option<rustc_span::symbol::Symbol>
109             >,
110             [few] wasm_import_module_map: rustc_data_structures::fx::FxHashMap<
111                 rustc_hir::def_id::DefId,
112                 String
113             >,
114             [few] get_lib_features: rustc::middle::lib_features::LibFeatures,
115             [few] defined_lib_features: rustc::middle::lang_items::LanguageItems,
116             [few] visible_parent_map: rustc_hir::def_id::DefIdMap<rustc_hir::def_id::DefId>,
117             [few] foreign_module: rustc::middle::cstore::ForeignModule,
118             [few] foreign_modules: Vec<rustc::middle::cstore::ForeignModule>,
119             [few] reachable_non_generics: rustc_hir::def_id::DefIdMap<
120                 rustc::middle::exported_symbols::SymbolExportLevel
121             >,
122             [few] crate_variances: rustc::ty::CrateVariancesMap<'tcx>,
123             [few] inferred_outlives_crate: rustc::ty::CratePredicatesMap<'tcx>,
124             [] upvars: rustc_data_structures::fx::FxIndexMap<rustc_hir::HirId, rustc_hir::Upvar>,
125
126             // HIR types
127             [few] hir_forest: rustc::hir::map::Forest<$tcx>,
128             [] arm: rustc_hir::Arm<$tcx>,
129             [] attribute: syntax::ast::Attribute,
130             [] block: rustc_hir::Block<$tcx>,
131             [] bare_fn_ty: rustc_hir::BareFnTy<$tcx>,
132             [few] global_asm: rustc_hir::GlobalAsm,
133             [] generic_arg: rustc_hir::GenericArg<$tcx>,
134             [] generic_args: rustc_hir::GenericArgs<$tcx>,
135             [] generic_bound: rustc_hir::GenericBound<$tcx>,
136             [] generic_param: rustc_hir::GenericParam<$tcx>,
137             [] expr: rustc_hir::Expr<$tcx>,
138             [] field: rustc_hir::Field<$tcx>,
139             [] field_pat: rustc_hir::FieldPat<$tcx>,
140             [] fn_decl: rustc_hir::FnDecl<$tcx>,
141             [] foreign_item: rustc_hir::ForeignItem<$tcx>,
142             [] impl_item_ref: rustc_hir::ImplItemRef<$tcx>,
143             [] inline_asm: rustc_hir::InlineAsm<$tcx>,
144             [] local: rustc_hir::Local<$tcx>,
145             [few] macro_def: rustc_hir::MacroDef<$tcx>,
146             [] param: rustc_hir::Param<$tcx>,
147             [] pat: rustc_hir::Pat<$tcx>,
148             [] path: rustc_hir::Path<$tcx>,
149             [] path_segment: rustc_hir::PathSegment<$tcx>,
150             [] poly_trait_ref: rustc_hir::PolyTraitRef<$tcx>,
151             [] qpath: rustc_hir::QPath<$tcx>,
152             [] stmt: rustc_hir::Stmt<$tcx>,
153             [] struct_field: rustc_hir::StructField<$tcx>,
154             [] trait_item_ref: rustc_hir::TraitItemRef,
155             [] ty: rustc_hir::Ty<$tcx>,
156             [] type_binding: rustc_hir::TypeBinding<$tcx>,
157             [] variant: rustc_hir::Variant<$tcx>,
158             [] where_predicate: rustc_hir::WherePredicate<$tcx>,
159         ], $tcx);
160     )
161 }
162
163 macro_rules! arena_for_type {
164     ([][$ty:ty]) => {
165         TypedArena<$ty>
166     };
167     ([few $(, $attrs:ident)*][$ty:ty]) => {
168         PhantomData<$ty>
169     };
170     ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
171         arena_for_type!([$($attrs),*]$args)
172     };
173 }
174
175 macro_rules! declare_arena {
176     ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
177         #[derive(Default)]
178         pub struct Arena<$tcx> {
179             dropless: DroplessArena,
180             drop: DropArena,
181             $($name: arena_for_type!($a[$ty]),)*
182         }
183     }
184 }
185
186 macro_rules! which_arena_for_type {
187     ([][$arena:expr]) => {
188         Some($arena)
189     };
190     ([few$(, $attrs:ident)*][$arena:expr]) => {
191         None
192     };
193     ([$ignore:ident$(, $attrs:ident)*]$args:tt) => {
194         which_arena_for_type!([$($attrs),*]$args)
195     };
196 }
197
198 macro_rules! impl_arena_allocatable {
199     ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
200         $(
201             impl ArenaAllocatable for $ty {}
202             unsafe impl<$tcx> ArenaField<$tcx> for $ty {
203                 #[inline]
204                 fn arena<'a>(_arena: &'a Arena<$tcx>) -> Option<&'a TypedArena<Self>> {
205                     which_arena_for_type!($a[&_arena.$name])
206                 }
207             }
208         )*
209     }
210 }
211
212 arena_types!(declare_arena, [], 'tcx);
213
214 arena_types!(impl_arena_allocatable, [], 'tcx);
215
216 pub trait ArenaAllocatable {}
217
218 impl<T: Copy> ArenaAllocatable for T {}
219
220 unsafe trait ArenaField<'tcx>: Sized {
221     /// Returns a specific arena to allocate from.
222     /// If `None` is returned, the `DropArena` will be used.
223     fn arena<'a>(arena: &'a Arena<'tcx>) -> Option<&'a TypedArena<Self>>;
224 }
225
226 unsafe impl<'tcx, T> ArenaField<'tcx> for T {
227     #[inline]
228     default fn arena<'a>(_: &'a Arena<'tcx>) -> Option<&'a TypedArena<Self>> {
229         panic!()
230     }
231 }
232
233 impl<'tcx> Arena<'tcx> {
234     #[inline]
235     pub fn alloc<T: ArenaAllocatable>(&self, value: T) -> &mut T {
236         if !mem::needs_drop::<T>() {
237             return self.dropless.alloc(value);
238         }
239         match <T as ArenaField<'tcx>>::arena(self) {
240             Some(arena) => arena.alloc(value),
241             None => unsafe { self.drop.alloc(value) },
242         }
243     }
244
245     #[inline]
246     pub fn alloc_slice<T: Copy>(&self, value: &[T]) -> &mut [T] {
247         if value.len() == 0 {
248             return &mut [];
249         }
250         self.dropless.alloc_slice(value)
251     }
252
253     pub fn alloc_from_iter<T: ArenaAllocatable, I: IntoIterator<Item = T>>(
254         &'a self,
255         iter: I,
256     ) -> &'a mut [T] {
257         if !mem::needs_drop::<T>() {
258             return self.dropless.alloc_from_iter(iter);
259         }
260         match <T as ArenaField<'tcx>>::arena(self) {
261             Some(arena) => arena.alloc_from_iter(iter),
262             None => unsafe { self.drop.alloc_from_iter(iter) },
263         }
264     }
265 }
266
267 /// Calls the destructor for an object when dropped.
268 struct DropType {
269     drop_fn: unsafe fn(*mut u8),
270     obj: *mut u8,
271 }
272
273 unsafe fn drop_for_type<T>(to_drop: *mut u8) {
274     std::ptr::drop_in_place(to_drop as *mut T)
275 }
276
277 impl Drop for DropType {
278     fn drop(&mut self) {
279         unsafe { (self.drop_fn)(self.obj) }
280     }
281 }
282
283 /// An arena which can be used to allocate any type.
284 /// Allocating in this arena is unsafe since the type system
285 /// doesn't know which types it contains. In order to
286 /// allocate safely, you must store a PhantomData<T>
287 /// alongside this arena for each type T you allocate.
288 #[derive(Default)]
289 struct DropArena {
290     /// A list of destructors to run when the arena drops.
291     /// Ordered so `destructors` gets dropped before the arena
292     /// since its destructor can reference memory in the arena.
293     destructors: RefCell<Vec<DropType>>,
294     arena: DroplessArena,
295 }
296
297 impl DropArena {
298     #[inline]
299     unsafe fn alloc<T>(&self, object: T) -> &mut T {
300         let mem =
301             self.arena.alloc_raw(mem::size_of::<T>(), mem::align_of::<T>()) as *mut _ as *mut T;
302         // Write into uninitialized memory.
303         ptr::write(mem, object);
304         let result = &mut *mem;
305         // Record the destructor after doing the allocation as that may panic
306         // and would cause `object`'s destuctor to run twice if it was recorded before
307         self.destructors
308             .borrow_mut()
309             .push(DropType { drop_fn: drop_for_type::<T>, obj: result as *mut T as *mut u8 });
310         result
311     }
312
313     #[inline]
314     unsafe fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
315         let mut vec: SmallVec<[_; 8]> = iter.into_iter().collect();
316         if vec.is_empty() {
317             return &mut [];
318         }
319         let len = vec.len();
320
321         let start_ptr = self
322             .arena
323             .alloc_raw(len.checked_mul(mem::size_of::<T>()).unwrap(), mem::align_of::<T>())
324             as *mut _ as *mut T;
325
326         let mut destructors = self.destructors.borrow_mut();
327         // Reserve space for the destructors so we can't panic while adding them
328         destructors.reserve(len);
329
330         // Move the content to the arena by copying it and then forgetting
331         // the content of the SmallVec
332         vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
333         mem::forget(vec.drain(..));
334
335         // Record the destructors after doing the allocation as that may panic
336         // and would cause `object`'s destuctor to run twice if it was recorded before
337         for i in 0..len {
338             destructors.push(DropType {
339                 drop_fn: drop_for_type::<T>,
340                 obj: start_ptr.offset(i as isize) as *mut u8,
341             });
342         }
343
344         slice::from_raw_parts_mut(start_ptr, len)
345     }
346 }