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