]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/traits.rs
bda585b8eda349f82ad817601495994f14af6b55
[rust.git] / src / librustc_mir / interpret / traits.rs
1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use rustc::ty::{self, Ty};
12 use rustc::ty::layout::{Size, Align, LayoutOf};
13 use rustc::mir::interpret::{Scalar, Pointer, EvalResult, PointerArithmetic};
14
15 use super::{EvalContext, Machine, MemoryKind};
16
17 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
18     /// Creates a dynamic vtable for the given type and vtable origin. This is used only for
19     /// objects.
20     ///
21     /// The `trait_ref` encodes the erased self type. Hence if we are
22     /// making an object `Foo<Trait>` from a value of type `Foo<T>`, then
23     /// `trait_ref` would map `T:Trait`.
24     pub fn get_vtable(
25         &mut self,
26         ty: Ty<'tcx>,
27         poly_trait_ref: ty::PolyExistentialTraitRef<'tcx>,
28     ) -> EvalResult<'tcx, Pointer<M::PointerTag>> {
29         trace!("get_vtable(trait_ref={:?})", poly_trait_ref);
30
31         let (ty, poly_trait_ref) = self.tcx.erase_regions(&(ty, poly_trait_ref));
32
33         if let Some(&vtable) = self.vtables.get(&(ty, poly_trait_ref)) {
34             return Ok(Pointer::from(vtable).with_default_tag());
35         }
36
37         let trait_ref = poly_trait_ref.with_self_ty(*self.tcx, ty);
38         let trait_ref = self.tcx.erase_regions(&trait_ref);
39
40         let methods = self.tcx.vtable_methods(trait_ref);
41
42         let layout = self.layout_of(ty)?;
43         assert!(!layout.is_unsized(), "can't create a vtable for an unsized type");
44         let size = layout.size.bytes();
45         let align = layout.align.abi.bytes();
46
47         let ptr_size = self.pointer_size();
48         let ptr_align = self.tcx.data_layout.pointer_align.abi;
49         // /////////////////////////////////////////////////////////////////////////////////////////
50         // If you touch this code, be sure to also make the corresponding changes to
51         // `get_vtable` in rust_codegen_llvm/meth.rs
52         // /////////////////////////////////////////////////////////////////////////////////////////
53         let vtable = self.memory.allocate(
54             ptr_size * (3 + methods.len() as u64),
55             ptr_align,
56             MemoryKind::Vtable,
57         )?.with_default_tag();
58         let tcx = &*self.tcx;
59
60         let drop = ::monomorphize::resolve_drop_in_place(*tcx, ty);
61         let drop = self.memory.create_fn_alloc(drop).with_default_tag();
62         // no need to do any alignment checks on the memory accesses below, because we know the
63         // allocation is correctly aligned as we created it above. Also we're only offsetting by
64         // multiples of `ptr_align`, which means that it will stay aligned to `ptr_align`.
65         self.memory
66             .get_mut(vtable.alloc_id)?
67             .write_ptr_sized(tcx, vtable, Scalar::Ptr(drop).into())?;
68
69         let size_ptr = vtable.offset(ptr_size, self)?;
70         self.memory
71             .get_mut(size_ptr.alloc_id)?
72             .write_ptr_sized(tcx, size_ptr, Scalar::from_uint(size, ptr_size).into())?;
73         let align_ptr = vtable.offset(ptr_size * 2, self)?;
74         self.memory
75             .get_mut(align_ptr.alloc_id)?
76             .write_ptr_sized(tcx, align_ptr, Scalar::from_uint(align, ptr_size).into())?;
77
78         for (i, method) in methods.iter().enumerate() {
79             if let Some((def_id, substs)) = *method {
80                 let instance = self.resolve(def_id, substs)?;
81                 let fn_ptr = self.memory.create_fn_alloc(instance).with_default_tag();
82                 let method_ptr = vtable.offset(ptr_size * (3 + i as u64), self)?;
83                 self.memory
84                     .get_mut(method_ptr.alloc_id)?
85                     .write_ptr_sized(tcx, method_ptr, Scalar::Ptr(fn_ptr).into())?;
86             }
87         }
88
89         self.memory.mark_immutable(vtable.alloc_id)?;
90         assert!(self.vtables.insert((ty, poly_trait_ref), vtable.alloc_id).is_none());
91
92         Ok(vtable)
93     }
94
95     /// Return the drop fn instance as well as the actual dynamic type
96     pub fn read_drop_type_from_vtable(
97         &self,
98         vtable: Pointer<M::PointerTag>,
99     ) -> EvalResult<'tcx, (ty::Instance<'tcx>, ty::Ty<'tcx>)> {
100         // we don't care about the pointee type, we just want a pointer
101         self.memory.check_align(vtable.into(), self.tcx.data_layout.pointer_align.abi)?;
102         let drop_fn = self.memory
103             .get(vtable.alloc_id)?
104             .read_ptr_sized(self, vtable)?
105             .to_ptr()?;
106         let drop_instance = self.memory.get_fn(drop_fn)?;
107         trace!("Found drop fn: {:?}", drop_instance);
108         let fn_sig = drop_instance.ty(*self.tcx).fn_sig(*self.tcx);
109         let fn_sig = self.tcx.normalize_erasing_late_bound_regions(self.param_env, &fn_sig);
110         // the drop function takes *mut T where T is the type being dropped, so get that
111         let ty = fn_sig.inputs()[0].builtin_deref(true).unwrap().ty;
112         Ok((drop_instance, ty))
113     }
114
115     pub fn read_size_and_align_from_vtable(
116         &self,
117         vtable: Pointer<M::PointerTag>,
118     ) -> EvalResult<'tcx, (Size, Align)> {
119         let pointer_size = self.pointer_size();
120         self.memory.check_align(vtable.into(), self.tcx.data_layout.pointer_align.abi)?;
121         let alloc = self.memory.get(vtable.alloc_id)?;
122         let size = alloc.read_ptr_sized(self, vtable.offset(pointer_size, self)?)?
123             .to_bits(pointer_size)? as u64;
124         let align = alloc.read_ptr_sized(
125             self,
126             vtable.offset(pointer_size * 2, self)?,
127         )?.to_bits(pointer_size)? as u64;
128         Ok((Size::from_bytes(size), Align::from_bytes(align).unwrap()))
129     }
130 }