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