1 use std::convert::TryFrom;
4 use crate::mir::interpret::{alloc_range, AllocId, Allocation, Pointer, Scalar};
5 use crate::ty::{self, Instance, PolyTraitRef, Ty, TyCtxt};
6 use rustc_ast::Mutability;
8 #[derive(Clone, Copy, PartialEq, HashStable)]
9 pub enum VtblEntry<'tcx> {
10 /// destructor of this type (used in vtable header)
12 /// layout size of this type (used in vtable header)
14 /// layout align of this type (used in vtable header)
16 /// non-dispatchable associated function that is excluded from trait object
18 /// dispatchable associated function
19 Method(Instance<'tcx>),
20 /// pointer to a separate supertrait vtable, can be used by trait upcasting coercion
21 TraitVPtr(PolyTraitRef<'tcx>),
24 impl<'tcx> fmt::Debug for VtblEntry<'tcx> {
25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26 // We want to call `Display` on `Instance` and `PolyTraitRef`,
27 // so we implement this manually.
29 VtblEntry::MetadataDropInPlace => write!(f, "MetadataDropInPlace"),
30 VtblEntry::MetadataSize => write!(f, "MetadataSize"),
31 VtblEntry::MetadataAlign => write!(f, "MetadataAlign"),
32 VtblEntry::Vacant => write!(f, "Vacant"),
33 VtblEntry::Method(instance) => write!(f, "Method({})", instance),
34 VtblEntry::TraitVPtr(trait_ref) => write!(f, "TraitVPtr({})", trait_ref),
39 // Needs to be associated with the `'tcx` lifetime
40 impl<'tcx> TyCtxt<'tcx> {
41 pub const COMMON_VTABLE_ENTRIES: &'tcx [VtblEntry<'tcx>] =
42 &[VtblEntry::MetadataDropInPlace, VtblEntry::MetadataSize, VtblEntry::MetadataAlign];
45 pub const COMMON_VTABLE_ENTRIES_DROPINPLACE: usize = 0;
46 pub const COMMON_VTABLE_ENTRIES_SIZE: usize = 1;
47 pub const COMMON_VTABLE_ENTRIES_ALIGN: usize = 2;
49 /// Retrieves an allocation that represents the contents of a vtable.
50 /// Since this is a query, allocations are cached and not duplicated.
51 pub(super) fn vtable_allocation_provider<'tcx>(
53 key: (Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>),
55 let (ty, poly_trait_ref) = key;
57 let vtable_entries = if let Some(poly_trait_ref) = poly_trait_ref {
58 let trait_ref = poly_trait_ref.with_self_ty(tcx, ty);
59 let trait_ref = tcx.erase_regions(trait_ref);
61 tcx.vtable_entries(trait_ref)
63 TyCtxt::COMMON_VTABLE_ENTRIES
67 .layout_of(ty::ParamEnv::reveal_all().and(ty))
68 .expect("failed to build vtable representation");
69 assert!(layout.is_sized(), "can't create a vtable for an unsized type");
70 let size = layout.size.bytes();
71 let align = layout.align.abi.bytes();
73 let ptr_size = tcx.data_layout.pointer_size;
74 let ptr_align = tcx.data_layout.pointer_align.abi;
76 let vtable_size = ptr_size * u64::try_from(vtable_entries.len()).unwrap();
77 let mut vtable = Allocation::uninit(vtable_size, ptr_align, /* panic_on_fail */ true).unwrap();
79 // No need to do any alignment checks on the memory accesses below, because we know the
80 // allocation is correctly aligned as we created it above. Also we're only offsetting by
81 // multiples of `ptr_align`, which means that it will stay aligned to `ptr_align`.
83 for (idx, entry) in vtable_entries.iter().enumerate() {
84 let idx: u64 = u64::try_from(idx).unwrap();
85 let scalar = match entry {
86 VtblEntry::MetadataDropInPlace => {
87 let instance = ty::Instance::resolve_drop_in_place(tcx, ty);
88 let fn_alloc_id = tcx.create_fn_alloc(instance);
89 let fn_ptr = Pointer::from(fn_alloc_id);
90 Scalar::from_pointer(fn_ptr, &tcx)
92 VtblEntry::MetadataSize => Scalar::from_uint(size, ptr_size).into(),
93 VtblEntry::MetadataAlign => Scalar::from_uint(align, ptr_size).into(),
94 VtblEntry::Vacant => continue,
95 VtblEntry::Method(instance) => {
96 // Prepare the fn ptr we write into the vtable.
97 let instance = instance.polymorphize(tcx);
98 let fn_alloc_id = tcx.create_fn_alloc(instance);
99 let fn_ptr = Pointer::from(fn_alloc_id);
100 Scalar::from_pointer(fn_ptr, &tcx)
102 VtblEntry::TraitVPtr(trait_ref) => {
103 let super_trait_ref = trait_ref
104 .map_bound(|trait_ref| ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
105 let supertrait_alloc_id = tcx.vtable_allocation((ty, Some(super_trait_ref)));
106 let vptr = Pointer::from(supertrait_alloc_id);
107 Scalar::from_pointer(vptr, &tcx)
111 .write_scalar(&tcx, alloc_range(ptr_size * idx, ptr_size), scalar)
112 .expect("failed to build vtable representation");
115 vtable.mutability = Mutability::Not;
116 tcx.create_memory_alloc(tcx.intern_const_alloc(vtable))