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