]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/meth.rs
Rollup merge of #39604 - est31:i128_tests, r=alexcrichton
[rust.git] / src / librustc_trans / meth.rs
1 // Copyright 2012 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 attributes;
12 use llvm::{ValueRef, get_params};
13 use rustc::traits;
14 use callee::{Callee, CalleeData};
15 use common::*;
16 use builder::Builder;
17 use consts;
18 use declare;
19 use glue;
20 use machine;
21 use monomorphize::Instance;
22 use type_::Type;
23 use type_of::*;
24 use value::Value;
25 use rustc::ty;
26
27 // drop_glue pointer, size, align.
28 const VTABLE_OFFSET: usize = 3;
29
30 /// Extracts a method from a trait object's vtable, at the specified index.
31 pub fn get_virtual_method<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
32                                     llvtable: ValueRef,
33                                     vtable_index: usize)
34                                     -> ValueRef {
35     // Load the data pointer from the object.
36     debug!("get_virtual_method(vtable_index={}, llvtable={:?})",
37            vtable_index, Value(llvtable));
38
39     bcx.load(bcx.gepi(llvtable, &[vtable_index + VTABLE_OFFSET]), None)
40 }
41
42 /// Generate a shim function that allows an object type like `SomeTrait` to
43 /// implement the type `SomeTrait`. Imagine a trait definition:
44 ///
45 ///    trait SomeTrait { fn get(&self) -> i32; ... }
46 ///
47 /// And a generic bit of code:
48 ///
49 ///    fn foo<T:SomeTrait>(t: &T) {
50 ///        let x = SomeTrait::get;
51 ///        x(t)
52 ///    }
53 ///
54 /// What is the value of `x` when `foo` is invoked with `T=SomeTrait`?
55 /// The answer is that it is a shim function generated by this routine:
56 ///
57 ///    fn shim(t: &SomeTrait) -> i32 {
58 ///        // ... call t.get() virtually ...
59 ///    }
60 ///
61 /// In fact, all virtual calls can be thought of as normal trait calls
62 /// that go through this shim function.
63 pub fn trans_object_shim<'a, 'tcx>(ccx: &'a CrateContext<'a, 'tcx>,
64                                    callee: Callee<'tcx>)
65                                    -> ValueRef {
66     debug!("trans_object_shim({:?})", callee);
67
68     let function_name = match callee.ty.sty {
69         ty::TyFnDef(def_id, substs, _) => {
70             let instance = Instance::new(def_id, substs);
71             instance.symbol_name(ccx.shared())
72         }
73         _ => bug!()
74     };
75
76     let llfn = declare::define_internal_fn(ccx, &function_name, callee.ty);
77     attributes::set_frame_pointer_elimination(ccx, llfn);
78
79     let bcx = Builder::new_block(ccx, llfn, "entry-block");
80
81     let mut llargs = get_params(llfn);
82     let fn_ret = callee.ty.fn_ret();
83     let fn_ty = callee.direct_fn_type(ccx, &[]);
84
85     let fn_ptr = match callee.data {
86         CalleeData::Virtual(idx) => {
87             let fn_ptr = get_virtual_method(&bcx,
88                 llargs.remove(fn_ty.ret.is_indirect() as usize + 1), idx);
89             let llty = fn_ty.llvm_type(bcx.ccx).ptr_to();
90             bcx.pointercast(fn_ptr, llty)
91         },
92         _ => bug!("trans_object_shim called with non-virtual callee"),
93     };
94     let llret = bcx.call(fn_ptr, &llargs, None);
95     fn_ty.apply_attrs_callsite(llret);
96
97     if fn_ret.0.is_never() {
98         bcx.unreachable();
99     } else {
100         if fn_ty.ret.is_indirect() || fn_ty.ret.is_ignore() {
101             bcx.ret_void();
102         } else {
103             bcx.ret(llret);
104         }
105     }
106
107     llfn
108 }
109
110 /// Creates a dynamic vtable for the given type and vtable origin.
111 /// This is used only for objects.
112 ///
113 /// The vtables are cached instead of created on every call.
114 ///
115 /// The `trait_ref` encodes the erased self type. Hence if we are
116 /// making an object `Foo<Trait>` from a value of type `Foo<T>`, then
117 /// `trait_ref` would map `T:Trait`.
118 pub fn get_vtable<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
119                             ty: ty::Ty<'tcx>,
120                             trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>)
121                             -> ValueRef
122 {
123     let tcx = ccx.tcx();
124
125     debug!("get_vtable(ty={:?}, trait_ref={:?})", ty, trait_ref);
126
127     // Check the cache.
128     if let Some(&val) = ccx.vtables().borrow().get(&(ty, trait_ref)) {
129         return val;
130     }
131
132     // Not in the cache. Build it.
133     let nullptr = C_null(Type::nil(ccx).ptr_to());
134
135     let size_ty = sizing_type_of(ccx, ty);
136     let size = machine::llsize_of_alloc(ccx, size_ty);
137     let align = align_of(ccx, ty);
138
139     let mut components: Vec<_> = [
140         // Generate a destructor for the vtable.
141         glue::get_drop_glue(ccx, ty),
142         C_uint(ccx, size),
143         C_uint(ccx, align)
144     ].iter().cloned().collect();
145
146     if let Some(trait_ref) = trait_ref {
147         let trait_ref = trait_ref.with_self_ty(tcx, ty);
148         let methods = traits::get_vtable_methods(tcx, trait_ref).map(|opt_mth| {
149             opt_mth.map_or(nullptr, |(def_id, substs)| {
150                 Callee::def(ccx, def_id, substs).reify(ccx)
151             })
152         });
153         components.extend(methods);
154     }
155
156     let vtable_const = C_struct(ccx, &components, false);
157     let align = machine::llalign_of_pref(ccx, val_ty(vtable_const));
158     let vtable = consts::addr_of(ccx, vtable_const, align, "vtable");
159
160     ccx.vtables().borrow_mut().insert((ty, trait_ref), vtable);
161     vtable
162 }