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