]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/meth.rs
doc: remove incomplete sentence
[rust.git] / src / librustc_trans / 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 arena::TypedArena;
12 use back::abi;
13 use back::link;
14 use llvm::{mod, ValueRef, get_param};
15 use metadata::csearch;
16 use middle::subst::{Subst, Substs};
17 use middle::subst::VecPerParamSpace;
18 use middle::subst;
19 use middle::traits;
20 use trans::base::*;
21 use trans::build::*;
22 use trans::callee::*;
23 use trans::callee;
24 use trans::cleanup;
25 use trans::common::*;
26 use trans::datum::*;
27 use trans::expr::{SaveIn, Ignore};
28 use trans::expr;
29 use trans::glue;
30 use trans::machine;
31 use trans::type_::Type;
32 use trans::type_of::*;
33 use middle::ty::{mod, Ty};
34 use middle::ty::MethodCall;
35 use util::ppaux::Repr;
36
37 use std::c_str::ToCStr;
38 use std::rc::Rc;
39 use syntax::abi::{Rust, RustCall};
40 use syntax::parse::token;
41 use syntax::{ast, ast_map, attr, visit};
42 use syntax::ast_util::PostExpansionMethod;
43 use syntax::codemap::DUMMY_SP;
44
45 // drop_glue pointer, size, align.
46 static VTABLE_OFFSET: uint = 3;
47
48 /// The main "translation" pass for methods.  Generates code
49 /// for non-monomorphized methods only.  Other methods will
50 /// be generated once they are invoked with specific type parameters,
51 /// see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`.
52 pub fn trans_impl(ccx: &CrateContext,
53                   name: ast::Ident,
54                   impl_items: &[ast::ImplItem],
55                   generics: &ast::Generics,
56                   id: ast::NodeId) {
57     let _icx = push_ctxt("meth::trans_impl");
58     let tcx = ccx.tcx();
59
60     debug!("trans_impl(name={}, id={})", name.repr(tcx), id);
61
62     // Both here and below with generic methods, be sure to recurse and look for
63     // items that we need to translate.
64     if !generics.ty_params.is_empty() {
65         let mut v = TransItemVisitor{ ccx: ccx };
66         for impl_item in impl_items.iter() {
67             match *impl_item {
68                 ast::MethodImplItem(ref method) => {
69                     visit::walk_method_helper(&mut v, &**method);
70                 }
71                 ast::TypeImplItem(_) => {}
72             }
73         }
74         return;
75     }
76     for impl_item in impl_items.iter() {
77         match *impl_item {
78             ast::MethodImplItem(ref method) => {
79                 if method.pe_generics().ty_params.len() == 0u {
80                     let trans_everywhere = attr::requests_inline(method.attrs[]);
81                     for (ref ccx, is_origin) in ccx.maybe_iter(trans_everywhere) {
82                         let llfn = get_item_val(ccx, method.id);
83                         trans_fn(ccx,
84                                  method.pe_fn_decl(),
85                                  method.pe_body(),
86                                  llfn,
87                                  &Substs::trans_empty(),
88                                  method.id,
89                                  &[]);
90                         update_linkage(ccx,
91                                        llfn,
92                                        Some(method.id),
93                                        if is_origin { OriginalTranslation } else { InlinedCopy });
94                     }
95                 }
96                 let mut v = TransItemVisitor {
97                     ccx: ccx,
98                 };
99                 visit::walk_method_helper(&mut v, &**method);
100             }
101             ast::TypeImplItem(_) => {}
102         }
103     }
104 }
105
106 pub fn trans_method_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
107                                        method_call: MethodCall,
108                                        self_expr: Option<&ast::Expr>,
109                                        arg_cleanup_scope: cleanup::ScopeId)
110                                        -> Callee<'blk, 'tcx> {
111     let _icx = push_ctxt("meth::trans_method_callee");
112
113     let (origin, method_ty) =
114         bcx.tcx().method_map
115                  .borrow()
116                  .get(&method_call)
117                  .map(|method| (method.origin.clone(), method.ty))
118                  .unwrap();
119
120     match origin {
121         ty::MethodStatic(did) |
122         ty::MethodStaticUnboxedClosure(did) => {
123             Callee {
124                 bcx: bcx,
125                 data: Fn(callee::trans_fn_ref(bcx,
126                                               did,
127                                               MethodCallKey(method_call))),
128             }
129         }
130
131         ty::MethodTypeParam(ty::MethodParam {
132             ref trait_ref,
133             method_num
134         }) => {
135             let trait_ref = ty::Binder(bcx.monomorphize(trait_ref));
136             let span = bcx.tcx().map.span(method_call.expr_id);
137             debug!("method_call={} trait_ref={}",
138                    method_call,
139                    trait_ref.repr(bcx.tcx()));
140             let origin = fulfill_obligation(bcx.ccx(),
141                                             span,
142                                             trait_ref.clone());
143             debug!("origin = {}", origin.repr(bcx.tcx()));
144             trans_monomorphized_callee(bcx,
145                                        method_call,
146                                        trait_ref.def_id(),
147                                        method_num,
148                                        origin)
149         }
150
151         ty::MethodTraitObject(ref mt) => {
152             let self_expr = match self_expr {
153                 Some(self_expr) => self_expr,
154                 None => {
155                     bcx.sess().span_bug(bcx.tcx().map.span(method_call.expr_id),
156                                         "self expr wasn't provided for trait object \
157                                          callee (trying to call overloaded op?)")
158                 }
159             };
160             trans_trait_callee(bcx,
161                                monomorphize_type(bcx, method_ty),
162                                mt.real_index,
163                                self_expr,
164                                arg_cleanup_scope)
165         }
166     }
167 }
168
169 pub fn trans_static_method_callee(bcx: Block,
170                                   method_id: ast::DefId,
171                                   trait_id: ast::DefId,
172                                   expr_id: ast::NodeId)
173                                   -> ValueRef
174 {
175     let _icx = push_ctxt("meth::trans_static_method_callee");
176     let ccx = bcx.ccx();
177
178     debug!("trans_static_method_callee(method_id={}, trait_id={}, \
179             expr_id={})",
180            method_id,
181            ty::item_path_str(bcx.tcx(), trait_id),
182            expr_id);
183
184     let mname = if method_id.krate == ast::LOCAL_CRATE {
185         match bcx.tcx().map.get(method_id.node) {
186             ast_map::NodeTraitItem(method) => {
187                 let ident = match *method {
188                     ast::RequiredMethod(ref m) => m.ident,
189                     ast::ProvidedMethod(ref m) => m.pe_ident(),
190                     ast::TypeTraitItem(_) => {
191                         bcx.tcx().sess.bug("trans_static_method_callee() on \
192                                             an associated type?!")
193                     }
194                 };
195                 ident.name
196             }
197             _ => panic!("callee is not a trait method")
198         }
199     } else {
200         csearch::get_item_path(bcx.tcx(), method_id).last().unwrap().name()
201     };
202     debug!("trans_static_method_callee: method_id={}, expr_id={}, \
203             name={}", method_id, expr_id, token::get_name(mname));
204
205     // Find the substitutions for the fn itself. This includes
206     // type parameters that belong to the trait but also some that
207     // belong to the method:
208     let rcvr_substs = node_id_substs(bcx, ExprId(expr_id));
209     let subst::SeparateVecsPerParamSpace {
210         types: rcvr_type,
211         selfs: rcvr_self,
212         fns: rcvr_method
213     } = rcvr_substs.types.split();
214
215     // Lookup the precise impl being called. To do that, we need to
216     // create a trait reference identifying the self type and other
217     // input type parameters. To create that trait reference, we have
218     // to pick apart the type parameters to identify just those that
219     // pertain to the trait. This is easiest to explain by example:
220     //
221     //     trait Convert {
222     //         fn from<U:Foo>(n: U) -> Option<Self>;
223     //     }
224     //     ...
225     //     let f = <Vec<int> as Convert>::from::<String>(...)
226     //
227     // Here, in this call, which I've written with explicit UFCS
228     // notation, the set of type parameters will be:
229     //
230     //     rcvr_type: [] <-- nothing declared on the trait itself
231     //     rcvr_self: [Vec<int>] <-- the self type
232     //     rcvr_method: [String] <-- method type parameter
233     //
234     // So we create a trait reference using the first two,
235     // basically corresponding to `<Vec<int> as Convert>`.
236     // The remaining type parameters (`rcvr_method`) will be used below.
237     let trait_substs =
238         Substs::erased(VecPerParamSpace::new(rcvr_type,
239                                              rcvr_self,
240                                              Vec::new()));
241     let trait_substs = bcx.tcx().mk_substs(trait_substs);
242     debug!("trait_substs={}", trait_substs.repr(bcx.tcx()));
243     let trait_ref = ty::Binder(Rc::new(ty::TraitRef { def_id: trait_id,
244                                                       substs: trait_substs }));
245     let vtbl = fulfill_obligation(bcx.ccx(),
246                                   DUMMY_SP,
247                                   trait_ref);
248
249     // Now that we know which impl is being used, we can dispatch to
250     // the actual function:
251     match vtbl {
252         traits::VtableImpl(traits::VtableImplData {
253             impl_def_id: impl_did,
254             substs: impl_substs,
255             nested: _ }) =>
256         {
257             assert!(impl_substs.types.all(|t| !ty::type_needs_infer(*t)));
258
259             // Create the substitutions that are in scope. This combines
260             // the type parameters from the impl with those declared earlier.
261             // To see what I mean, consider a possible impl:
262             //
263             //    impl<T> Convert for Vec<T> {
264             //        fn from<U:Foo>(n: U) { ... }
265             //    }
266             //
267             // Recall that we matched `<Vec<int> as Convert>`. Trait
268             // resolution will have given us a substitution
269             // containing `impl_substs=[[T=int],[],[]]` (the type
270             // parameters defined on the impl). We combine
271             // that with the `rcvr_method` from before, which tells us
272             // the type parameters from the *method*, to yield
273             // `callee_substs=[[T=int],[],[U=String]]`.
274             let subst::SeparateVecsPerParamSpace {
275                 types: impl_type,
276                 selfs: impl_self,
277                 fns: _
278             } = impl_substs.types.split();
279             let callee_substs =
280                 Substs::erased(VecPerParamSpace::new(impl_type,
281                                                      impl_self,
282                                                      rcvr_method));
283
284             let mth_id = method_with_name(ccx, impl_did, mname);
285             let llfn = trans_fn_ref_with_substs(bcx, mth_id, ExprId(expr_id),
286                                                 callee_substs);
287
288             let callee_ty = node_id_type(bcx, expr_id);
289             let llty = type_of_fn_from_ty(ccx, callee_ty).ptr_to();
290             PointerCast(bcx, llfn, llty)
291         }
292         _ => {
293             bcx.tcx().sess.bug(
294                 format!("static call to invalid vtable: {}",
295                         vtbl.repr(bcx.tcx()))[]);
296         }
297     }
298 }
299
300 fn method_with_name(ccx: &CrateContext, impl_id: ast::DefId, name: ast::Name)
301                     -> ast::DefId {
302     match ccx.impl_method_cache().borrow().get(&(impl_id, name)).cloned() {
303         Some(m) => return m,
304         None => {}
305     }
306
307     let impl_items = ccx.tcx().impl_items.borrow();
308     let impl_items =
309         impl_items.get(&impl_id)
310                   .expect("could not find impl while translating");
311     let meth_did = impl_items.iter()
312                              .find(|&did| {
313                                 ty::impl_or_trait_item(ccx.tcx(), did.def_id()).name() == name
314                              }).expect("could not find method while \
315                                         translating");
316
317     ccx.impl_method_cache().borrow_mut().insert((impl_id, name),
318                                               meth_did.def_id());
319     meth_did.def_id()
320 }
321
322 fn trans_monomorphized_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
323                                           method_call: MethodCall,
324                                           trait_id: ast::DefId,
325                                           n_method: uint,
326                                           vtable: traits::Vtable<'tcx, ()>)
327                                           -> Callee<'blk, 'tcx> {
328     let _icx = push_ctxt("meth::trans_monomorphized_callee");
329     match vtable {
330         traits::VtableImpl(vtable_impl) => {
331             let ccx = bcx.ccx();
332             let impl_did = vtable_impl.impl_def_id;
333             let mname = match ty::trait_item(ccx.tcx(), trait_id, n_method) {
334                 ty::MethodTraitItem(method) => method.name,
335                 ty::TypeTraitItem(_) => {
336                     bcx.tcx().sess.bug("can't monomorphize an associated \
337                                         type")
338                 }
339             };
340             let mth_id = method_with_name(bcx.ccx(), impl_did, mname);
341
342             // create a concatenated set of substitutions which includes
343             // those from the impl and those from the method:
344             let callee_substs =
345                 combine_impl_and_methods_tps(
346                     bcx, MethodCallKey(method_call), vtable_impl.substs);
347
348             // translate the function
349             let llfn = trans_fn_ref_with_substs(bcx,
350                                                 mth_id,
351                                                 MethodCallKey(method_call),
352                                                 callee_substs);
353
354             Callee { bcx: bcx, data: Fn(llfn) }
355         }
356         traits::VtableUnboxedClosure(closure_def_id, substs) => {
357             // The substitutions should have no type parameters remaining
358             // after passing through fulfill_obligation
359             let llfn = trans_fn_ref_with_substs(bcx,
360                                                 closure_def_id,
361                                                 MethodCallKey(method_call),
362                                                 substs);
363
364             Callee {
365                 bcx: bcx,
366                 data: Fn(llfn),
367             }
368         }
369         traits::VtableFnPointer(fn_ty) => {
370             let llfn = trans_fn_pointer_shim(bcx.ccx(), fn_ty);
371             Callee { bcx: bcx, data: Fn(llfn) }
372         }
373         traits::VtableObject(ref data) => {
374             let llfn = trans_object_shim(bcx.ccx(), data.object_ty, trait_id, n_method);
375             Callee { bcx: bcx, data: Fn(llfn) }
376         }
377         traits::VtableBuiltin(..) |
378         traits::VtableParam(..) => {
379             bcx.sess().bug(
380                 format!("resolved vtable bad vtable {} in trans",
381                         vtable.repr(bcx.tcx()))[]);
382         }
383     }
384 }
385
386  /// Creates a concatenated set of substitutions which includes those from the impl and those from
387  /// the method.  This are some subtle complications here.  Statically, we have a list of type
388  /// parameters like `[T0, T1, T2, M1, M2, M3]` where `Tn` are type parameters that appear on the
389  /// receiver.  For example, if the receiver is a method parameter `A` with a bound like
390  /// `trait<B,C,D>` then `Tn` would be `[B,C,D]`.
391  ///
392  /// The weird part is that the type `A` might now be bound to any other type, such as `foo<X>`.
393  /// In that case, the vector we want is: `[X, M1, M2, M3]`.  Therefore, what we do now is to slice
394  /// off the method type parameters and append them to the type parameters from the type that the
395  /// receiver is mapped to.
396 fn combine_impl_and_methods_tps<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
397                                             node: ExprOrMethodCall,
398                                             rcvr_substs: subst::Substs<'tcx>)
399                                             -> subst::Substs<'tcx>
400 {
401     let ccx = bcx.ccx();
402
403     let node_substs = node_id_substs(bcx, node);
404
405     debug!("rcvr_substs={}", rcvr_substs.repr(ccx.tcx()));
406     debug!("node_substs={}", node_substs.repr(ccx.tcx()));
407
408     // Break apart the type parameters from the node and type
409     // parameters from the receiver.
410     let node_method = node_substs.types.split().fns;
411     let subst::SeparateVecsPerParamSpace {
412         types: rcvr_type,
413         selfs: rcvr_self,
414         fns: rcvr_method
415     } = rcvr_substs.types.clone().split();
416     assert!(rcvr_method.is_empty());
417     subst::Substs {
418         regions: subst::ErasedRegions,
419         types: subst::VecPerParamSpace::new(rcvr_type, rcvr_self, node_method)
420     }
421 }
422
423 /// Create a method callee where the method is coming from a trait object (e.g., Box<Trait> type).
424 /// In this case, we must pull the fn pointer out of the vtable that is packaged up with the
425 /// object. Objects are represented as a pair, so we first evaluate the self expression and then
426 /// extract the self data and vtable out of the pair.
427 fn trans_trait_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
428                                   method_ty: Ty<'tcx>,
429                                   n_method: uint,
430                                   self_expr: &ast::Expr,
431                                   arg_cleanup_scope: cleanup::ScopeId)
432                                   -> Callee<'blk, 'tcx> {
433     let _icx = push_ctxt("meth::trans_trait_callee");
434     let mut bcx = bcx;
435
436     // Translate self_datum and take ownership of the value by
437     // converting to an rvalue.
438     let self_datum = unpack_datum!(
439         bcx, expr::trans(bcx, self_expr));
440
441     let llval = if type_needs_drop(bcx.tcx(), self_datum.ty) {
442         let self_datum = unpack_datum!(
443             bcx, self_datum.to_rvalue_datum(bcx, "trait_callee"));
444
445         // Convert to by-ref since `trans_trait_callee_from_llval` wants it
446         // that way.
447         let self_datum = unpack_datum!(
448             bcx, self_datum.to_ref_datum(bcx));
449
450         // Arrange cleanup in case something should go wrong before the
451         // actual call occurs.
452         self_datum.add_clean(bcx.fcx, arg_cleanup_scope)
453     } else {
454         // We don't have to do anything about cleanups for &Trait and &mut Trait.
455         assert!(self_datum.kind.is_by_ref());
456         self_datum.val
457     };
458
459     trans_trait_callee_from_llval(bcx, method_ty, n_method, llval)
460 }
461
462 /// Same as `trans_trait_callee()` above, except that it is given a by-ref pointer to the object
463 /// pair.
464 pub fn trans_trait_callee_from_llval<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
465                                                  callee_ty: Ty<'tcx>,
466                                                  n_method: uint,
467                                                  llpair: ValueRef)
468                                                  -> Callee<'blk, 'tcx> {
469     let _icx = push_ctxt("meth::trans_trait_callee");
470     let ccx = bcx.ccx();
471
472     // Load the data pointer from the object.
473     debug!("(translating trait callee) loading second index from pair");
474     let llboxptr = GEPi(bcx, llpair, &[0u, abi::FAT_PTR_ADDR]);
475     let llbox = Load(bcx, llboxptr);
476     let llself = PointerCast(bcx, llbox, Type::i8p(ccx));
477
478     // Load the function from the vtable and cast it to the expected type.
479     debug!("(translating trait callee) loading method");
480     // Replace the self type (&Self or Box<Self>) with an opaque pointer.
481     let llcallee_ty = match callee_ty.sty {
482         ty::ty_bare_fn(_, ref f) if f.abi == Rust || f.abi == RustCall => {
483             type_of_rust_fn(ccx,
484                             Some(Type::i8p(ccx)),
485                             f.sig.0.inputs.slice_from(1),
486                             f.sig.0.output,
487                             f.abi)
488         }
489         _ => {
490             ccx.sess().bug("meth::trans_trait_callee given non-bare-rust-fn");
491         }
492     };
493     let llvtable = Load(bcx,
494                         PointerCast(bcx,
495                                     GEPi(bcx, llpair,
496                                          &[0u, abi::FAT_PTR_EXTRA]),
497                                     Type::vtable(ccx).ptr_to().ptr_to()));
498     let mptr = Load(bcx, GEPi(bcx, llvtable, &[0u, n_method + VTABLE_OFFSET]));
499     let mptr = PointerCast(bcx, mptr, llcallee_ty.ptr_to());
500
501     return Callee {
502         bcx: bcx,
503         data: TraitItem(MethodData {
504             llfn: mptr,
505             llself: llself,
506         })
507     };
508 }
509
510 /// Generate a shim function that allows an object type like `SomeTrait` to
511 /// implement the type `SomeTrait`. Imagine a trait definition:
512 ///
513 ///    trait SomeTrait { fn get(&self) -> int; ... }
514 ///
515 /// And a generic bit of code:
516 ///
517 ///    fn foo<T:SomeTrait>(t: &T) {
518 ///        let x = SomeTrait::get;
519 ///        x(t)
520 ///    }
521 ///
522 /// What is the value of `x` when `foo` is invoked with `T=SomeTrait`?
523 /// The answer is that it it is a shim function generate by this
524 /// routine:
525 ///
526 ///    fn shim(t: &SomeTrait) -> int {
527 ///        // ... call t.get() virtually ...
528 ///    }
529 ///
530 /// In fact, all virtual calls can be thought of as normal trait calls
531 /// that go through this shim function.
532 pub fn trans_object_shim<'a, 'tcx>(
533     ccx: &'a CrateContext<'a, 'tcx>,
534     object_ty: Ty<'tcx>,
535     trait_id: ast::DefId,
536     method_offset_in_trait: uint)
537     -> ValueRef
538 {
539     let _icx = push_ctxt("trans_object_shim");
540     let tcx = ccx.tcx();
541
542     debug!("trans_object_shim(object_ty={}, trait_id={}, n_method={})",
543            object_ty.repr(tcx),
544            trait_id.repr(tcx),
545            method_offset_in_trait);
546
547     let object_trait_ref =
548         match object_ty.sty {
549             ty::ty_trait(ref data) => {
550                 data.principal_trait_ref_with_self_ty(tcx, object_ty)
551             }
552             _ => {
553                 tcx.sess.bug(format!("trans_object_shim() called on non-object: {}",
554                                      object_ty.repr(tcx)).as_slice());
555             }
556         };
557
558     // Upcast to the trait in question and extract out the substitutions.
559     let upcast_trait_ref = traits::upcast(ccx.tcx(), object_trait_ref.clone(), trait_id).unwrap();
560     let object_substs = upcast_trait_ref.substs().clone().erase_regions();
561     debug!("trans_object_shim: object_substs={}", object_substs.repr(tcx));
562
563     // Lookup the type of this method as deeclared in the trait and apply substitutions.
564     let method_ty = match ty::trait_item(tcx, trait_id, method_offset_in_trait) {
565         ty::MethodTraitItem(method) => method,
566         ty::TypeTraitItem(_) => {
567             tcx.sess.bug("can't create a method shim for an associated type")
568         }
569     };
570     let fty = method_ty.fty.subst(tcx, &object_substs);
571     let fty = tcx.mk_bare_fn(fty);
572     debug!("trans_object_shim: fty={}", fty.repr(tcx));
573
574     //
575     let method_bare_fn_ty =
576         ty::mk_bare_fn(tcx, None, fty);
577     let function_name =
578         link::mangle_internal_name_by_type_and_seq(ccx, method_bare_fn_ty, "object_shim");
579     let llfn =
580         decl_internal_rust_fn(ccx, method_bare_fn_ty, function_name.as_slice());
581
582     //
583     let block_arena = TypedArena::new();
584     let empty_substs = Substs::trans_empty();
585     let fcx = new_fn_ctxt(ccx,
586                           llfn,
587                           ast::DUMMY_NODE_ID,
588                           false,
589                           fty.sig.0.output,
590                           &empty_substs,
591                           None,
592                           &block_arena);
593     let mut bcx = init_function(&fcx, false, fty.sig.0.output);
594
595     // the first argument (`self`) will be a trait object
596     let llobject = get_param(fcx.llfn, fcx.arg_pos(0) as u32);
597
598     debug!("trans_object_shim: llobject={}",
599            bcx.val_to_string(llobject));
600
601     // the remaining arguments will be, well, whatever they are
602     let llargs: Vec<_> =
603         fty.sig.0.inputs[1..].iter()
604         .enumerate()
605         .map(|(i, _)| {
606             let llarg = get_param(fcx.llfn, fcx.arg_pos(i+1) as u32);
607             debug!("trans_object_shim: input #{} == {}",
608                    i, bcx.val_to_string(llarg));
609             llarg
610         })
611         .collect();
612     assert!(!fcx.needs_ret_allocas);
613
614     let dest =
615         fcx.llretslotptr.get().map(
616             |_| expr::SaveIn(fcx.get_ret_slot(bcx, fty.sig.0.output, "ret_slot")));
617
618     let method_offset_in_vtable =
619         traits::get_vtable_index_of_object_method(bcx.tcx(),
620                                                   object_trait_ref.clone(),
621                                                   trait_id,
622                                                   method_offset_in_trait);
623     debug!("trans_object_shim: method_offset_in_vtable={}",
624            method_offset_in_vtable);
625
626     bcx = trans_call_inner(bcx,
627                            None,
628                            method_bare_fn_ty,
629                            |bcx, _| trans_trait_callee_from_llval(bcx,
630                                                                   method_bare_fn_ty,
631                                                                   method_offset_in_vtable,
632                                                                   llobject),
633                            ArgVals(llargs.as_slice()),
634                            dest).bcx;
635
636     finish_fn(&fcx, bcx, fty.sig.0.output);
637
638     llfn
639 }
640
641 /// Creates a returns a dynamic vtable for the given type and vtable origin.
642 /// This is used only for objects.
643 ///
644 /// The `trait_ref` encodes the erased self type. Hence if we are
645 /// making an object `Foo<Trait>` from a value of type `Foo<T>`, then
646 /// `trait_ref` would map `T:Trait`, but `box_ty` would be
647 /// `Foo<T>`. This `box_ty` is primarily used to encode the destructor.
648 /// This will hopefully change now that DST is underway.
649 pub fn get_vtable<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
650                               box_ty: Ty<'tcx>,
651                               trait_ref: ty::PolyTraitRef<'tcx>)
652                               -> ValueRef
653 {
654     debug!("get_vtable(box_ty={}, trait_ref={})",
655            box_ty.repr(bcx.tcx()),
656            trait_ref.repr(bcx.tcx()));
657
658     let tcx = bcx.tcx();
659     let ccx = bcx.ccx();
660     let _icx = push_ctxt("meth::get_vtable");
661
662     // Check the cache.
663     let cache_key = (box_ty, trait_ref.clone());
664     match ccx.vtables().borrow().get(&cache_key) {
665         Some(&val) => { return val }
666         None => { }
667     }
668
669     // Not in the cache. Build it.
670     let methods = traits::supertraits(tcx, trait_ref.clone()).flat_map(|trait_ref| {
671         let vtable = fulfill_obligation(bcx.ccx(),
672                                         DUMMY_SP,
673                                         trait_ref.clone());
674         match vtable {
675             traits::VtableBuiltin(_) => {
676                 Vec::new().into_iter()
677             }
678             traits::VtableImpl(
679                 traits::VtableImplData {
680                     impl_def_id: id,
681                     substs,
682                     nested: _ }) => {
683                 emit_vtable_methods(bcx, id, substs).into_iter()
684             }
685             traits::VtableUnboxedClosure(closure_def_id, substs) => {
686                 let llfn = trans_fn_ref_with_substs(
687                     bcx,
688                     closure_def_id,
689                     ExprId(0),
690                     substs.clone());
691
692                 (vec!(llfn)).into_iter()
693             }
694             traits::VtableFnPointer(bare_fn_ty) => {
695                 let llfn = vec![trans_fn_pointer_shim(bcx.ccx(), bare_fn_ty)];
696                 llfn.into_iter()
697             }
698             traits::VtableObject(ref data) => {
699                 // this would imply that the Self type being erased is
700                 // an object type; this cannot happen because we
701                 // cannot cast an unsized type into a trait object
702                 bcx.sess().bug(
703                     format!("cannot get vtable for an object type: {}",
704                             data.repr(bcx.tcx())).as_slice());
705             }
706             traits::VtableParam => {
707                 bcx.sess().bug(
708                     format!("resolved vtable for {} to bad vtable {} in trans",
709                             trait_ref.repr(bcx.tcx()),
710                             vtable.repr(bcx.tcx()))[]);
711             }
712         }
713     });
714
715     let size_ty = sizing_type_of(ccx, trait_ref.self_ty());
716     let size = machine::llsize_of_alloc(ccx, size_ty);
717     let ll_size = C_uint(ccx, size);
718     let align = align_of(ccx, trait_ref.self_ty());
719     let ll_align = C_uint(ccx, align);
720
721     // Generate a destructor for the vtable.
722     let drop_glue = glue::get_drop_glue(ccx, box_ty);
723     let vtable = make_vtable(ccx, drop_glue, ll_size, ll_align, methods);
724
725     ccx.vtables().borrow_mut().insert(cache_key, vtable);
726     vtable
727 }
728
729 /// Helper function to declare and initialize the vtable.
730 pub fn make_vtable<I: Iterator<Item=ValueRef>>(ccx: &CrateContext,
731                                           drop_glue: ValueRef,
732                                           size: ValueRef,
733                                           align: ValueRef,
734                                           ptrs: I)
735                                           -> ValueRef {
736     let _icx = push_ctxt("meth::make_vtable");
737
738     let head = vec![drop_glue, size, align];
739     let components: Vec<_> = head.into_iter().chain(ptrs).collect();
740
741     unsafe {
742         let tbl = C_struct(ccx, components[], false);
743         let sym = token::gensym("vtable");
744         let vt_gvar = format!("vtable{}", sym.uint()).with_c_str(|buf| {
745             llvm::LLVMAddGlobal(ccx.llmod(), val_ty(tbl).to_ref(), buf)
746         });
747         llvm::LLVMSetInitializer(vt_gvar, tbl);
748         llvm::LLVMSetGlobalConstant(vt_gvar, llvm::True);
749         llvm::SetLinkage(vt_gvar, llvm::InternalLinkage);
750         vt_gvar
751     }
752 }
753
754 fn emit_vtable_methods<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
755                                    impl_id: ast::DefId,
756                                    substs: subst::Substs<'tcx>)
757                                    -> Vec<ValueRef> {
758     let ccx = bcx.ccx();
759     let tcx = ccx.tcx();
760
761     let trt_id = match ty::impl_trait_ref(tcx, impl_id) {
762         Some(t_id) => t_id.def_id,
763         None       => ccx.sess().bug("make_impl_vtable: don't know how to \
764                                       make a vtable for a type impl!")
765     };
766
767     ty::populate_implementations_for_trait_if_necessary(bcx.tcx(), trt_id);
768
769     let trait_item_def_ids = ty::trait_item_def_ids(tcx, trt_id);
770     trait_item_def_ids.iter().flat_map(|method_def_id| {
771         let method_def_id = method_def_id.def_id();
772         let name = ty::impl_or_trait_item(tcx, method_def_id).name();
773         // The substitutions we have are on the impl, so we grab
774         // the method type from the impl to substitute into.
775         let m_id = method_with_name(ccx, impl_id, name);
776         let ti = ty::impl_or_trait_item(tcx, m_id);
777         match ti {
778             ty::MethodTraitItem(m) => {
779                 debug!("(making impl vtable) emitting method {} at subst {}",
780                        m.repr(tcx),
781                        substs.repr(tcx));
782                 if m.generics.has_type_params(subst::FnSpace) ||
783                     ty::type_has_self(ty::mk_bare_fn(tcx, None, tcx.mk_bare_fn(m.fty.clone())))
784                 {
785                     debug!("(making impl vtable) method has self or type \
786                             params: {}",
787                            token::get_name(name));
788                     Some(C_null(Type::nil(ccx).ptr_to())).into_iter()
789                 } else {
790                     let fn_ref = trans_fn_ref_with_substs(
791                         bcx,
792                         m_id,
793                         ExprId(0),
794                         substs.clone());
795
796                     // currently, at least, by-value self is not object safe
797                     assert!(m.explicit_self != ty::ByValueExplicitSelfCategory);
798
799                     Some(fn_ref).into_iter()
800                 }
801             }
802             ty::TypeTraitItem(_) => {
803                 None.into_iter()
804             }
805         }
806     }).collect()
807 }
808
809 /// Generates the code to convert from a pointer (`Box<T>`, `&T`, etc) into an object
810 /// (`Box<Trait>`, `&Trait`, etc). This means creating a pair where the first word is the vtable
811 /// and the second word is the pointer.
812 pub fn trans_trait_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
813                                     datum: Datum<'tcx, Expr>,
814                                     id: ast::NodeId,
815                                     trait_ref: ty::PolyTraitRef<'tcx>,
816                                     dest: expr::Dest)
817                                     -> Block<'blk, 'tcx> {
818     let mut bcx = bcx;
819     let _icx = push_ctxt("meth::trans_trait_cast");
820
821     let lldest = match dest {
822         Ignore => {
823             return datum.clean(bcx, "trait_trait_cast", id);
824         }
825         SaveIn(dest) => dest
826     };
827
828     debug!("trans_trait_cast: trait_ref={}",
829            trait_ref.repr(bcx.tcx()));
830
831     let datum_ty = datum.ty;
832     let llbox_ty = type_of(bcx.ccx(), datum_ty);
833
834     // Store the pointer into the first half of pair.
835     let llboxdest = GEPi(bcx, lldest, &[0u, abi::FAT_PTR_ADDR]);
836     let llboxdest = PointerCast(bcx, llboxdest, llbox_ty.ptr_to());
837     bcx = datum.store_to(bcx, llboxdest);
838
839     // Store the vtable into the second half of pair.
840     let vtable = get_vtable(bcx, datum_ty, trait_ref);
841     let llvtabledest = GEPi(bcx, lldest, &[0u, abi::FAT_PTR_EXTRA]);
842     let llvtabledest = PointerCast(bcx, llvtabledest, val_ty(vtable).ptr_to());
843     Store(bcx, vtable, llvtabledest);
844
845     bcx
846 }