3 use rustc_middle::ty::{self, Ty};
4 use rustc_target::abi::call::FnAbi;
6 #[derive(Copy, Clone, Debug)]
7 pub struct VirtualIndex(u64);
9 impl<'a, 'tcx> VirtualIndex {
10 pub fn from_index(index: usize) -> Self {
11 VirtualIndex(index as u64)
14 pub fn get_fn<Bx: BuilderMethods<'a, 'tcx>>(
18 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
20 // Load the data pointer from the object.
21 debug!("get_fn({:?}, {:?})", llvtable, self);
23 let llty = bx.fn_ptr_backend_type(fn_abi);
24 let llvtable = bx.pointercast(llvtable, bx.type_ptr_to(llty));
25 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
26 let gep = bx.inbounds_gep(llty, llvtable, &[bx.const_usize(self.0)]);
27 let ptr = bx.load(llty, gep, ptr_align);
28 bx.nonnull_metadata(ptr);
29 // Vtable loads are invariant.
30 bx.set_invariant_load(ptr);
34 pub fn get_usize<Bx: BuilderMethods<'a, 'tcx>>(
39 // Load the data pointer from the object.
40 debug!("get_int({:?}, {:?})", llvtable, self);
42 let llty = bx.type_isize();
43 let llvtable = bx.pointercast(llvtable, bx.type_ptr_to(llty));
44 let usize_align = bx.tcx().data_layout.pointer_align.abi;
45 let gep = bx.inbounds_gep(llty, llvtable, &[bx.const_usize(self.0)]);
46 let ptr = bx.load(llty, gep, usize_align);
47 // Vtable loads are invariant.
48 bx.set_invariant_load(ptr);
53 /// Creates a dynamic vtable for the given type and vtable origin.
54 /// This is used only for objects.
56 /// The vtables are cached instead of created on every call.
58 /// The `trait_ref` encodes the erased self type. Hence if we are
59 /// making an object `Foo<dyn Trait>` from a value of type `Foo<T>`, then
60 /// `trait_ref` would map `T: Trait`.
61 pub fn get_vtable<'tcx, Cx: CodegenMethods<'tcx>>(
64 trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
68 debug!("get_vtable(ty={:?}, trait_ref={:?})", ty, trait_ref);
71 if let Some(&val) = cx.vtables().borrow().get(&(ty, trait_ref)) {
75 let vtable_alloc_id = tcx.vtable_allocation(ty, trait_ref);
76 let vtable_allocation = tcx.global_alloc(vtable_alloc_id).unwrap_memory();
77 let vtable_const = cx.const_data_from_alloc(vtable_allocation);
78 let align = cx.data_layout().pointer_align.abi;
79 let vtable = cx.static_addr_of(vtable_const, align, Some("vtable"));
81 cx.create_vtable_metadata(ty, vtable);
82 cx.vtables().borrow_mut().insert((ty, trait_ref), vtable);