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.
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.
11 use arena::TypedArena;
14 use llvm::{self, ValueRef, get_param};
15 use metadata::csearch;
16 use middle::subst::{Subst, Substs};
17 use middle::subst::VecPerParamSpace;
27 use trans::expr::{SaveIn, Ignore};
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;
37 use std::c_str::ToCStr;
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;
45 // drop_glue pointer, size, align.
46 static VTABLE_OFFSET: uint = 3;
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,
54 impl_items: &[ast::ImplItem],
55 generics: &ast::Generics,
57 let _icx = push_ctxt("meth::trans_impl");
60 debug!("trans_impl(name={}, id={})", name.repr(tcx), id);
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() {
68 ast::MethodImplItem(ref method) => {
69 visit::walk_method_helper(&mut v, &**method);
71 ast::TypeImplItem(_) => {}
76 for impl_item in impl_items.iter() {
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);
87 &Substs::trans_empty(),
93 if is_origin { OriginalTranslation } else { InlinedCopy });
96 let mut v = TransItemVisitor {
99 visit::walk_method_helper(&mut v, &**method);
101 ast::TypeImplItem(_) => {}
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");
113 let (origin, method_ty) =
117 .map(|method| (method.origin.clone(), method.ty))
121 ty::MethodStatic(did) |
122 ty::MethodStaticUnboxedClosure(did) => {
125 data: Fn(callee::trans_fn_ref(bcx.ccx(),
127 MethodCallKey(method_call),
128 bcx.fcx.param_substs).val),
132 ty::MethodTypeParam(ty::MethodParam {
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={}",
140 trait_ref.repr(bcx.tcx()));
141 let origin = fulfill_obligation(bcx.ccx(),
144 debug!("origin = {}", origin.repr(bcx.tcx()));
145 trans_monomorphized_callee(bcx,
152 ty::MethodTraitObject(ref mt) => {
153 let self_expr = match self_expr {
154 Some(self_expr) => self_expr,
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?)")
161 trans_trait_callee(bcx,
162 monomorphize_type(bcx, method_ty),
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>
177 let _icx = push_ctxt("meth::trans_static_method_callee");
180 debug!("trans_static_method_callee(method_id={}, trait_id={}, \
183 ty::item_path_str(tcx, trait_id),
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?!")
199 _ => panic!("callee is not a trait method")
202 csearch::get_item_path(tcx, method_id).last().unwrap().name()
204 debug!("trans_static_method_callee: method_id={}, expr_id={}, \
205 name={}", method_id, expr_id, token::get_name(mname));
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 {
215 } = rcvr_substs.types.split();
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:
224 // fn from<U:Foo>(n: U) -> Option<Self>;
227 // let f = <Vec<int> as Convert>::from::<String>(...)
229 // Here, in this call, which I've written with explicit UFCS
230 // notation, the set of type parameters will be:
232 // rcvr_type: [] <-- nothing declared on the trait itself
233 // rcvr_self: [Vec<int>] <-- the self type
234 // rcvr_method: [String] <-- method type parameter
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.
240 Substs::erased(VecPerParamSpace::new(rcvr_type,
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,
251 // Now that we know which impl is being used, we can dispatch to
252 // the actual function:
254 traits::VtableImpl(traits::VtableImplData {
255 impl_def_id: impl_did,
259 assert!(impl_substs.types.all(|t| !ty::type_needs_infer(*t)));
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:
265 // impl<T> Convert for Vec<T> {
266 // fn from<U:Foo>(n: U) { ... }
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 {
280 } = impl_substs.types.split();
282 Substs::erased(VecPerParamSpace::new(impl_type,
286 let mth_id = method_with_name(ccx, impl_did, mname);
287 trans_fn_ref_with_substs(ccx, mth_id, ExprId(expr_id),
292 tcx.sess.bug(format!("static call to invalid vtable: {}",
298 fn method_with_name(ccx: &CrateContext, impl_id: ast::DefId, name: ast::Name)
300 match ccx.impl_method_cache().borrow().get(&(impl_id, name)).cloned() {
305 let impl_items = ccx.tcx().impl_items.borrow();
307 impl_items.get(&impl_id)
308 .expect("could not find impl while translating");
309 let meth_did = impl_items.iter()
311 ty::impl_or_trait_item(ccx.tcx(), did.def_id()).name() == name
312 }).expect("could not find method while \
315 ccx.impl_method_cache().borrow_mut().insert((impl_id, name),
320 fn trans_monomorphized_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
321 method_call: MethodCall,
322 trait_id: ast::DefId,
324 vtable: traits::Vtable<'tcx, ()>)
325 -> Callee<'blk, 'tcx> {
326 let _icx = push_ctxt("meth::trans_monomorphized_callee");
328 traits::VtableImpl(vtable_impl) => {
330 let impl_did = vtable_impl.impl_def_id;
331 let mname = match ty::trait_item(ccx.tcx(), trait_id, n_method) {
332 ty::MethodTraitItem(method) => method.name,
333 ty::TypeTraitItem(_) => {
334 bcx.tcx().sess.bug("can't monomorphize an associated \
338 let mth_id = method_with_name(bcx.ccx(), impl_did, mname);
340 // create a concatenated set of substitutions which includes
341 // those from the impl and those from the method:
343 combine_impl_and_methods_tps(
344 bcx, MethodCallKey(method_call), vtable_impl.substs);
346 // translate the function
347 let llfn = trans_fn_ref_with_substs(bcx.ccx(),
349 MethodCallKey(method_call),
350 bcx.fcx.param_substs,
353 Callee { bcx: bcx, data: Fn(llfn) }
355 traits::VtableUnboxedClosure(closure_def_id, substs) => {
356 // The substitutions should have no type parameters remaining
357 // after passing through fulfill_obligation
358 let llfn = trans_fn_ref_with_substs(bcx.ccx(),
360 MethodCallKey(method_call),
361 bcx.fcx.param_substs,
369 traits::VtableFnPointer(fn_ty) => {
370 let llfn = trans_fn_pointer_shim(bcx.ccx(), fn_ty);
371 Callee { bcx: bcx, data: Fn(llfn) }
373 traits::VtableObject(ref data) => {
374 let llfn = trans_object_shim(bcx.ccx(), data.object_ty, trait_id, n_method);
375 Callee { bcx: bcx, data: Fn(llfn) }
377 traits::VtableBuiltin(..) |
378 traits::VtableParam(..) => {
380 format!("resolved vtable bad vtable {} in trans",
381 vtable.repr(bcx.tcx()))[]);
386 /// Creates a concatenated set of substitutions which includes those from the impl and those from
387 /// the method. This are some subtle complications here. Statically, we have a list of type
388 /// parameters like `[T0, T1, T2, M1, M2, M3]` where `Tn` are type parameters that appear on the
389 /// receiver. For example, if the receiver is a method parameter `A` with a bound like
390 /// `trait<B,C,D>` then `Tn` would be `[B,C,D]`.
392 /// The weird part is that the type `A` might now be bound to any other type, such as `foo<X>`.
393 /// In that case, the vector we want is: `[X, M1, M2, M3]`. Therefore, what we do now is to slice
394 /// off the method type parameters and append them to the type parameters from the type that the
395 /// receiver is mapped to.
396 fn combine_impl_and_methods_tps<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
397 node: ExprOrMethodCall,
398 rcvr_substs: subst::Substs<'tcx>)
399 -> subst::Substs<'tcx>
403 let node_substs = node_id_substs(ccx, node, bcx.fcx.param_substs);
405 debug!("rcvr_substs={}", rcvr_substs.repr(ccx.tcx()));
406 debug!("node_substs={}", node_substs.repr(ccx.tcx()));
408 // Break apart the type parameters from the node and type
409 // parameters from the receiver.
410 let node_method = node_substs.types.split().fns;
411 let subst::SeparateVecsPerParamSpace {
415 } = rcvr_substs.types.clone().split();
416 assert!(rcvr_method.is_empty());
418 regions: subst::ErasedRegions,
419 types: subst::VecPerParamSpace::new(rcvr_type, rcvr_self, node_method)
423 /// Create a method callee where the method is coming from a trait object (e.g., Box<Trait> type).
424 /// In this case, we must pull the fn pointer out of the vtable that is packaged up with the
425 /// object. Objects are represented as a pair, so we first evaluate the self expression and then
426 /// extract the self data and vtable out of the pair.
427 fn trans_trait_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
430 self_expr: &ast::Expr,
431 arg_cleanup_scope: cleanup::ScopeId)
432 -> Callee<'blk, 'tcx> {
433 let _icx = push_ctxt("meth::trans_trait_callee");
436 // Translate self_datum and take ownership of the value by
437 // converting to an rvalue.
438 let self_datum = unpack_datum!(
439 bcx, expr::trans(bcx, self_expr));
441 let llval = if type_needs_drop(bcx.tcx(), self_datum.ty) {
442 let self_datum = unpack_datum!(
443 bcx, self_datum.to_rvalue_datum(bcx, "trait_callee"));
445 // Convert to by-ref since `trans_trait_callee_from_llval` wants it
447 let self_datum = unpack_datum!(
448 bcx, self_datum.to_ref_datum(bcx));
450 // Arrange cleanup in case something should go wrong before the
451 // actual call occurs.
452 self_datum.add_clean(bcx.fcx, arg_cleanup_scope)
454 // We don't have to do anything about cleanups for &Trait and &mut Trait.
455 assert!(self_datum.kind.is_by_ref());
459 trans_trait_callee_from_llval(bcx, method_ty, n_method, llval)
462 /// Same as `trans_trait_callee()` above, except that it is given a by-ref pointer to the object
464 pub fn trans_trait_callee_from_llval<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
468 -> Callee<'blk, 'tcx> {
469 let _icx = push_ctxt("meth::trans_trait_callee");
472 // Load the data pointer from the object.
473 debug!("(translating trait callee) loading second index from pair");
474 let llboxptr = GEPi(bcx, llpair, &[0u, abi::FAT_PTR_ADDR]);
475 let llbox = Load(bcx, llboxptr);
476 let llself = PointerCast(bcx, llbox, Type::i8p(ccx));
478 // Load the function from the vtable and cast it to the expected type.
479 debug!("(translating trait callee) loading method");
480 // Replace the self type (&Self or Box<Self>) with an opaque pointer.
481 let llcallee_ty = match callee_ty.sty {
482 ty::ty_bare_fn(_, ref f) if f.abi == Rust || f.abi == RustCall => {
484 Some(Type::i8p(ccx)),
485 f.sig.0.inputs.slice_from(1),
490 ccx.sess().bug("meth::trans_trait_callee given non-bare-rust-fn");
493 let llvtable = Load(bcx,
496 &[0u, abi::FAT_PTR_EXTRA]),
497 Type::vtable(ccx).ptr_to().ptr_to()));
498 let mptr = Load(bcx, GEPi(bcx, llvtable, &[0u, n_method + VTABLE_OFFSET]));
499 let mptr = PointerCast(bcx, mptr, llcallee_ty.ptr_to());
503 data: TraitItem(MethodData {
510 /// Generate a shim function that allows an object type like `SomeTrait` to
511 /// implement the type `SomeTrait`. Imagine a trait definition:
513 /// trait SomeTrait { fn get(&self) -> int; ... }
515 /// And a generic bit of code:
517 /// fn foo<T:SomeTrait>(t: &T) {
518 /// let x = SomeTrait::get;
522 /// What is the value of `x` when `foo` is invoked with `T=SomeTrait`?
523 /// The answer is that it it is a shim function generate by this
526 /// fn shim(t: &SomeTrait) -> int {
527 /// // ... call t.get() virtually ...
530 /// In fact, all virtual calls can be thought of as normal trait calls
531 /// that go through this shim function.
532 pub fn trans_object_shim<'a, 'tcx>(
533 ccx: &'a CrateContext<'a, 'tcx>,
535 trait_id: ast::DefId,
536 method_offset_in_trait: uint)
539 let _icx = push_ctxt("trans_object_shim");
542 debug!("trans_object_shim(object_ty={}, trait_id={}, n_method={})",
545 method_offset_in_trait);
547 let object_trait_ref =
548 match object_ty.sty {
549 ty::ty_trait(ref data) => {
550 data.principal_trait_ref_with_self_ty(tcx, object_ty)
553 tcx.sess.bug(format!("trans_object_shim() called on non-object: {}",
554 object_ty.repr(tcx)).as_slice());
558 // Upcast to the trait in question and extract out the substitutions.
559 let upcast_trait_ref = traits::upcast(ccx.tcx(), object_trait_ref.clone(), trait_id).unwrap();
560 let object_substs = upcast_trait_ref.substs().clone().erase_regions();
561 debug!("trans_object_shim: object_substs={}", object_substs.repr(tcx));
563 // Lookup the type of this method as deeclared in the trait and apply substitutions.
564 let method_ty = match ty::trait_item(tcx, trait_id, method_offset_in_trait) {
565 ty::MethodTraitItem(method) => method,
566 ty::TypeTraitItem(_) => {
567 tcx.sess.bug("can't create a method shim for an associated type")
570 let fty = method_ty.fty.subst(tcx, &object_substs);
571 let fty = tcx.mk_bare_fn(fty);
572 debug!("trans_object_shim: fty={}", fty.repr(tcx));
575 let method_bare_fn_ty =
576 ty::mk_bare_fn(tcx, None, fty);
578 link::mangle_internal_name_by_type_and_seq(ccx, method_bare_fn_ty, "object_shim");
580 decl_internal_rust_fn(ccx, method_bare_fn_ty, function_name.as_slice());
583 let block_arena = TypedArena::new();
584 let empty_substs = Substs::trans_empty();
585 let fcx = new_fn_ctxt(ccx,
593 let mut bcx = init_function(&fcx, false, fty.sig.0.output);
595 // the first argument (`self`) will be a trait object
596 let llobject = get_param(fcx.llfn, fcx.arg_pos(0) as u32);
598 debug!("trans_object_shim: llobject={}",
599 bcx.val_to_string(llobject));
601 // the remaining arguments will be, well, whatever they are
603 fty.sig.0.inputs[1..].iter()
606 let llarg = get_param(fcx.llfn, fcx.arg_pos(i+1) as u32);
607 debug!("trans_object_shim: input #{} == {}",
608 i, bcx.val_to_string(llarg));
612 assert!(!fcx.needs_ret_allocas);
615 fcx.llretslotptr.get().map(
616 |_| expr::SaveIn(fcx.get_ret_slot(bcx, fty.sig.0.output, "ret_slot")));
618 let method_offset_in_vtable =
619 traits::get_vtable_index_of_object_method(bcx.tcx(),
620 object_trait_ref.clone(),
622 method_offset_in_trait);
623 debug!("trans_object_shim: method_offset_in_vtable={}",
624 method_offset_in_vtable);
626 bcx = trans_call_inner(bcx,
629 |bcx, _| trans_trait_callee_from_llval(bcx,
631 method_offset_in_vtable,
633 ArgVals(llargs.as_slice()),
636 finish_fn(&fcx, bcx, fty.sig.0.output);
641 /// Creates a returns a dynamic vtable for the given type and vtable origin.
642 /// This is used only for objects.
644 /// The `trait_ref` encodes the erased self type. Hence if we are
645 /// making an object `Foo<Trait>` from a value of type `Foo<T>`, then
646 /// `trait_ref` would map `T:Trait`, but `box_ty` would be
647 /// `Foo<T>`. This `box_ty` is primarily used to encode the destructor.
648 /// This will hopefully change now that DST is underway.
649 pub fn get_vtable<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
651 trait_ref: ty::PolyTraitRef<'tcx>)
654 debug!("get_vtable(box_ty={}, trait_ref={})",
655 box_ty.repr(bcx.tcx()),
656 trait_ref.repr(bcx.tcx()));
660 let _icx = push_ctxt("meth::get_vtable");
663 let cache_key = (box_ty, trait_ref.clone());
664 match ccx.vtables().borrow().get(&cache_key) {
665 Some(&val) => { return val }
669 // Not in the cache. Build it.
670 let methods = traits::supertraits(tcx, trait_ref.clone()).flat_map(|trait_ref| {
671 let vtable = fulfill_obligation(bcx.ccx(),
675 traits::VtableBuiltin(_) => {
676 Vec::new().into_iter()
679 traits::VtableImplData {
683 emit_vtable_methods(bcx, id, substs).into_iter()
685 traits::VtableUnboxedClosure(closure_def_id, substs) => {
686 let llfn = trans_fn_ref_with_substs(
690 bcx.fcx.param_substs,
693 (vec!(llfn)).into_iter()
695 traits::VtableFnPointer(bare_fn_ty) => {
696 let llfn = vec![trans_fn_pointer_shim(bcx.ccx(), bare_fn_ty)];
699 traits::VtableObject(ref data) => {
700 // this would imply that the Self type being erased is
701 // an object type; this cannot happen because we
702 // cannot cast an unsized type into a trait object
704 format!("cannot get vtable for an object type: {}",
705 data.repr(bcx.tcx())).as_slice());
707 traits::VtableParam => {
709 format!("resolved vtable for {} to bad vtable {} in trans",
710 trait_ref.repr(bcx.tcx()),
711 vtable.repr(bcx.tcx()))[]);
716 let size_ty = sizing_type_of(ccx, trait_ref.self_ty());
717 let size = machine::llsize_of_alloc(ccx, size_ty);
718 let ll_size = C_uint(ccx, size);
719 let align = align_of(ccx, trait_ref.self_ty());
720 let ll_align = C_uint(ccx, align);
722 // Generate a destructor for the vtable.
723 let drop_glue = glue::get_drop_glue(ccx, box_ty);
724 let vtable = make_vtable(ccx, drop_glue, ll_size, ll_align, methods);
726 ccx.vtables().borrow_mut().insert(cache_key, vtable);
730 /// Helper function to declare and initialize the vtable.
731 pub fn make_vtable<I: Iterator<Item=ValueRef>>(ccx: &CrateContext,
737 let _icx = push_ctxt("meth::make_vtable");
739 let head = vec![drop_glue, size, align];
740 let components: Vec<_> = head.into_iter().chain(ptrs).collect();
743 let tbl = C_struct(ccx, components[], false);
744 let sym = token::gensym("vtable");
745 let vt_gvar = format!("vtable{}", sym.uint()).with_c_str(|buf| {
746 llvm::LLVMAddGlobal(ccx.llmod(), val_ty(tbl).to_ref(), buf)
748 llvm::LLVMSetInitializer(vt_gvar, tbl);
749 llvm::LLVMSetGlobalConstant(vt_gvar, llvm::True);
750 llvm::SetLinkage(vt_gvar, llvm::InternalLinkage);
755 fn emit_vtable_methods<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
757 substs: subst::Substs<'tcx>)
762 let trt_id = match ty::impl_trait_ref(tcx, impl_id) {
763 Some(t_id) => t_id.def_id,
764 None => ccx.sess().bug("make_impl_vtable: don't know how to \
765 make a vtable for a type impl!")
768 ty::populate_implementations_for_trait_if_necessary(bcx.tcx(), trt_id);
770 let trait_item_def_ids = ty::trait_item_def_ids(tcx, trt_id);
771 trait_item_def_ids.iter().flat_map(|method_def_id| {
772 let method_def_id = method_def_id.def_id();
773 let name = ty::impl_or_trait_item(tcx, method_def_id).name();
774 // The substitutions we have are on the impl, so we grab
775 // the method type from the impl to substitute into.
776 let m_id = method_with_name(ccx, impl_id, name);
777 let ti = ty::impl_or_trait_item(tcx, m_id);
779 ty::MethodTraitItem(m) => {
780 debug!("(making impl vtable) emitting method {} at subst {}",
783 if m.generics.has_type_params(subst::FnSpace) ||
784 ty::type_has_self(ty::mk_bare_fn(tcx, None, tcx.mk_bare_fn(m.fty.clone())))
786 debug!("(making impl vtable) method has self or type \
788 token::get_name(name));
789 Some(C_null(Type::nil(ccx).ptr_to())).into_iter()
791 let fn_ref = trans_fn_ref_with_substs(
795 bcx.fcx.param_substs,
798 // currently, at least, by-value self is not object safe
799 assert!(m.explicit_self != ty::ByValueExplicitSelfCategory);
801 Some(fn_ref).into_iter()
804 ty::TypeTraitItem(_) => {
811 /// Generates the code to convert from a pointer (`Box<T>`, `&T`, etc) into an object
812 /// (`Box<Trait>`, `&Trait`, etc). This means creating a pair where the first word is the vtable
813 /// and the second word is the pointer.
814 pub fn trans_trait_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
815 datum: Datum<'tcx, Expr>,
817 trait_ref: ty::PolyTraitRef<'tcx>,
819 -> Block<'blk, 'tcx> {
821 let _icx = push_ctxt("meth::trans_trait_cast");
823 let lldest = match dest {
825 return datum.clean(bcx, "trait_trait_cast", id);
830 debug!("trans_trait_cast: trait_ref={}",
831 trait_ref.repr(bcx.tcx()));
833 let datum_ty = datum.ty;
834 let llbox_ty = type_of(bcx.ccx(), datum_ty);
836 // Store the pointer into the first half of pair.
837 let llboxdest = GEPi(bcx, lldest, &[0u, abi::FAT_PTR_ADDR]);
838 let llboxdest = PointerCast(bcx, llboxdest, llbox_ty.ptr_to());
839 bcx = datum.store_to(bcx, llboxdest);
841 // Store the vtable into the second half of pair.
842 let vtable = get_vtable(bcx, datum_ty, trait_ref);
843 let llvtabledest = GEPi(bcx, lldest, &[0u, abi::FAT_PTR_EXTRA]);
844 let llvtabledest = PointerCast(bcx, llvtabledest, val_ty(vtable).ptr_to());
845 Store(bcx, vtable, llvtabledest);