1 use arena::{TypedArena, DroplessArena};
5 use std::cell::RefCell;
6 use std::marker::PhantomData;
7 use smallvec::SmallVec;
9 /// This declares a list of types which can be allocated by `Arena`.
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.
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.
19 macro_rules! arena_types {
20 ($macro:path, $args:tt, $tcx:lifetime) => (
22 [] vtable_method: Option<(
23 rustc::hir::def_id::DefId,
24 rustc::ty::subst::SubstsRef<$tcx>
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,
33 rustc::infer::canonical::Canonical<'tcx,
34 rustc::infer::canonical::QueryResponse<'tcx,
35 rustc::traits::query::dropck_outlives::DropckOutlivesResult<'tcx>
38 [] normalize_projection_ty:
39 rustc::infer::canonical::Canonical<'tcx,
40 rustc::infer::canonical::QueryResponse<'tcx,
41 rustc::traits::query::normalize::NormalizationResult<'tcx>
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>>
51 rustc::infer::canonical::Canonical<'tcx,
52 rustc::infer::canonical::QueryResponse<'tcx, ()>
54 [] type_op_normalize_poly_fn_sig:
55 rustc::infer::canonical::Canonical<'tcx,
56 rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::PolyFnSig<'tcx>>
58 [] type_op_normalize_fn_sig:
59 rustc::infer::canonical::Canonical<'tcx,
60 rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::FnSig<'tcx>>
62 [] type_op_normalize_predicate:
63 rustc::infer::canonical::Canonical<'tcx,
64 rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::Predicate<'tcx>>
66 [] type_op_normalize_ty:
67 rustc::infer::canonical::Canonical<'tcx,
68 rustc::infer::canonical::QueryResponse<'tcx, rustc::ty::Ty<'tcx>>
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
79 [few] resolve_lifetimes: rustc::middle::resolve_lifetime::ResolveLifetimes,
80 [decode] generic_predicates: rustc::ty::GenericPredicates<'tcx>,
81 [few] lint_levels: rustc::lint::LintLevelMap,
86 macro_rules! arena_for_type {
90 ([few $(, $attrs:ident)*][$ty:ty]) => {
93 ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
94 arena_for_type!([$($attrs),*]$args)
98 macro_rules! declare_arena {
99 ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
101 pub struct Arena<$tcx> {
102 dropless: DroplessArena,
104 $($name: arena_for_type!($a[$ty]),)*
109 macro_rules! which_arena_for_type {
110 ([][$arena:expr]) => {
113 ([few$(, $attrs:ident)*][$arena:expr]) => {
116 ([$ignore:ident$(, $attrs:ident)*]$args:tt) => {
117 which_arena_for_type!([$($attrs),*]$args)
121 macro_rules! impl_arena_allocatable {
122 ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
124 impl ArenaAllocatable for $ty {}
125 unsafe impl<$tcx> ArenaField<$tcx> for $ty {
127 fn arena<'a>(_arena: &'a Arena<$tcx>) -> Option<&'a TypedArena<Self>> {
128 which_arena_for_type!($a[&_arena.$name])
135 arena_types!(declare_arena, [], 'tcx);
137 arena_types!(impl_arena_allocatable, [], 'tcx);
139 pub trait ArenaAllocatable {}
141 impl<T: Copy> ArenaAllocatable for T {}
143 unsafe trait ArenaField<'tcx>: Sized {
144 /// Returns a specific arena to allocate from.
145 /// If None is returned, the DropArena will be used.
146 fn arena<'a>(arena: &'a Arena<'tcx>) -> Option<&'a TypedArena<Self>>;
149 unsafe impl<'tcx, T> ArenaField<'tcx> for T {
151 default fn arena<'a>(_: &'a Arena<'tcx>) -> Option<&'a TypedArena<Self>> {
156 impl<'tcx> Arena<'tcx> {
158 pub fn alloc<T: ArenaAllocatable>(&self, value: T) -> &mut T {
159 if !mem::needs_drop::<T>() {
160 return self.dropless.alloc(value);
162 match <T as ArenaField<'tcx>>::arena(self) {
163 Some(arena) => arena.alloc(value),
164 None => unsafe { self.drop.alloc(value) },
169 pub fn alloc_slice<T: Copy>(&self, value: &[T]) -> &mut [T] {
170 if value.len() == 0 {
173 self.dropless.alloc_slice(value)
176 pub fn alloc_from_iter<
178 I: IntoIterator<Item = T>
183 if !mem::needs_drop::<T>() {
184 return self.dropless.alloc_from_iter(iter);
186 match <T as ArenaField<'tcx>>::arena(self) {
187 Some(arena) => arena.alloc_from_iter(iter),
188 None => unsafe { self.drop.alloc_from_iter(iter) },
193 /// Calls the destructor for an object when dropped.
195 drop_fn: unsafe fn(*mut u8),
199 unsafe fn drop_for_type<T>(to_drop: *mut u8) {
200 std::ptr::drop_in_place(to_drop as *mut T)
203 impl Drop for DropType {
206 (self.drop_fn)(self.obj)
211 /// An arena which can be used to allocate any type.
212 /// Allocating in this arena is unsafe since the type system
213 /// doesn't know which types it contains. In order to
214 /// allocate safely, you must store a PhantomData<T>
215 /// alongside this arena for each type T you allocate.
218 /// A list of destructors to run when the arena drops.
219 /// Ordered so `destructors` gets dropped before the arena
220 /// since its destructor can reference memory in the arena.
221 destructors: RefCell<Vec<DropType>>,
222 arena: DroplessArena,
227 unsafe fn alloc<T>(&self, object: T) -> &mut T {
228 let mem = self.arena.alloc_raw(
231 ) as *mut _ as *mut T;
232 // Write into uninitialized memory.
233 ptr::write(mem, object);
234 let result = &mut *mem;
235 // Record the destructor after doing the allocation as that may panic
236 // and would cause `object`'s destuctor to run twice if it was recorded before
237 self.destructors.borrow_mut().push(DropType {
238 drop_fn: drop_for_type::<T>,
239 obj: result as *mut T as *mut u8,
245 unsafe fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
246 let mut vec: SmallVec<[_; 8]> = iter.into_iter().collect();
252 let start_ptr = self.arena.alloc_raw(
253 len.checked_mul(mem::size_of::<T>()).unwrap(),
255 ) as *mut _ as *mut T;
257 let mut destructors = self.destructors.borrow_mut();
258 // Reserve space for the destructors so we can't panic while adding them
259 destructors.reserve(len);
261 // Move the content to the arena by copying it and then forgetting
262 // the content of the SmallVec
263 vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
264 mem::forget(vec.drain());
266 // Record the destructors after doing the allocation as that may panic
267 // and would cause `object`'s destuctor to run twice if it was recorded before
269 destructors.push(DropType {
270 drop_fn: drop_for_type::<T>,
271 obj: start_ptr.offset(i as isize) as *mut u8,
275 slice::from_raw_parts_mut(start_ptr, len)