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