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.
15 use metadata::csearch;
16 use middle::subst::{Subst,Substs};
17 use middle::subst::VecPerParamSpace;
20 use middle::trans::base::*;
21 use middle::trans::build::*;
22 use middle::trans::callee::*;
23 use middle::trans::callee;
24 use middle::trans::cleanup;
25 use middle::trans::common::*;
26 use middle::trans::datum::*;
27 use middle::trans::expr::{SaveIn, Ignore};
28 use middle::trans::expr;
29 use middle::trans::glue;
30 use middle::trans::machine;
31 use middle::trans::type_::Type;
32 use middle::trans::type_of::*;
35 use middle::typeck::MethodCall;
36 use util::ppaux::Repr;
38 use std::c_str::ToCStr;
40 use syntax::abi::{Rust, RustCall};
41 use syntax::parse::token;
42 use syntax::{ast, ast_map, attr, visit};
43 use syntax::ast_util::PostExpansionMethod;
44 use syntax::codemap::DUMMY_SP;
46 // drop_glue pointer, size, align.
47 static VTABLE_OFFSET: uint = 3;
50 The main "translation" pass for methods. Generates code
51 for non-monomorphized methods only. Other methods will
52 be generated once they are invoked with specific type parameters,
53 see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`.
55 pub fn trans_impl(ccx: &CrateContext,
57 impl_items: &[ast::ImplItem],
58 generics: &ast::Generics,
60 let _icx = push_ctxt("meth::trans_impl");
63 debug!("trans_impl(name={}, id={})", name.repr(tcx), id);
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 let mut v = TransItemVisitor{ ccx: ccx };
69 for impl_item in impl_items.iter() {
71 ast::MethodImplItem(ref method) => {
72 visit::walk_method_helper(&mut v, &**method);
74 ast::TypeImplItem(_) => {}
79 for impl_item in impl_items.iter() {
81 ast::MethodImplItem(ref method) => {
82 if method.pe_generics().ty_params.len() == 0u {
83 let trans_everywhere = attr::requests_inline(method.attrs.as_slice());
84 for (ref ccx, is_origin) in ccx.maybe_iter(trans_everywhere) {
85 let llfn = get_item_val(ccx, method.id);
90 ¶m_substs::empty(),
96 if is_origin { OriginalTranslation } else { InlinedCopy });
99 let mut v = TransItemVisitor {
102 visit::walk_method_helper(&mut v, &**method);
104 ast::TypeImplItem(_) => {}
109 pub fn trans_method_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
110 method_call: MethodCall,
111 self_expr: Option<&ast::Expr>,
112 arg_cleanup_scope: cleanup::ScopeId)
113 -> Callee<'blk, 'tcx> {
114 let _icx = push_ctxt("meth::trans_method_callee");
116 let (origin, method_ty) =
120 .map(|method| (method.origin.clone(), method.ty))
124 typeck::MethodStatic(did) |
125 typeck::MethodStaticUnboxedClosure(did) => {
128 data: Fn(callee::trans_fn_ref(bcx,
130 MethodCall(method_call))),
134 typeck::MethodTypeParam(typeck::MethodParam {
139 Rc::new(trait_ref.subst(bcx.tcx(),
140 &bcx.fcx.param_substs.substs));
141 let span = bcx.tcx().map.span(method_call.expr_id);
142 let origin = fulfill_obligation(bcx.ccx(),
144 (*trait_ref).clone());
145 debug!("origin = {}", origin.repr(bcx.tcx()));
146 trans_monomorphized_callee(bcx, method_call, trait_ref.def_id,
150 typeck::MethodTraitObject(ref mt) => {
151 let self_expr = match self_expr {
152 Some(self_expr) => self_expr,
154 bcx.sess().span_bug(bcx.tcx().map.span(method_call.expr_id),
155 "self expr wasn't provided for trait object \
156 callee (trying to call overloaded op?)")
159 trans_trait_callee(bcx,
160 monomorphize_type(bcx, method_ty),
168 pub fn trans_static_method_callee(bcx: Block,
169 method_id: ast::DefId,
170 trait_id: ast::DefId,
171 expr_id: ast::NodeId)
174 let _icx = push_ctxt("meth::trans_static_method_callee");
177 debug!("trans_static_method_callee(method_id={}, trait_id={}, \
180 ty::item_path_str(bcx.tcx(), trait_id),
183 let mname = if method_id.krate == ast::LOCAL_CRATE {
184 match bcx.tcx().map.get(method_id.node) {
185 ast_map::NodeTraitItem(method) => {
186 let ident = match *method {
187 ast::RequiredMethod(ref m) => m.ident,
188 ast::ProvidedMethod(ref m) => m.pe_ident(),
189 ast::TypeTraitItem(_) => {
190 bcx.tcx().sess.bug("trans_static_method_callee() on \
191 an associated type?!")
196 _ => panic!("callee is not a trait method")
199 csearch::get_item_path(bcx.tcx(), method_id).last().unwrap().name()
201 debug!("trans_static_method_callee: method_id={}, expr_id={}, \
202 name={}", method_id, expr_id, token::get_name(mname));
204 // Find the substitutions for the fn itself. This includes
205 // type parameters that belong to the trait but also some that
206 // belong to the method:
207 let rcvr_substs = node_id_substs(bcx, ExprId(expr_id));
208 let subst::SeparateVecsPerParamSpace {
213 } = rcvr_substs.types.split();
215 // Lookup the precise impl being called. To do that, we need to
216 // create a trait reference identifying the self type and other
217 // input type parameters. To create that trait reference, we have
218 // to pick apart the type parameters to identify just those that
219 // pertain to the trait. This is easiest to explain by example:
222 // fn from<U:Foo>(n: U) -> Option<Self>;
225 // let f = <Vec<int> as Convert>::from::<String>(...)
227 // Here, in this call, which I've written with explicit UFCS
228 // notation, the set of type parameters will be:
230 // rcvr_type: [] <-- nothing declared on the trait itself
231 // rcvr_self: [Vec<int>] <-- the self type
232 // rcvr_method: [String] <-- method type parameter
234 // So we create a trait reference using the first two,
235 // basically corresponding to `<Vec<int> as Convert>`.
236 // The remaining type parameters (`rcvr_method`) will be used below.
238 Substs::erased(VecPerParamSpace::new(rcvr_type,
242 debug!("trait_substs={}", trait_substs.repr(bcx.tcx()));
243 let trait_ref = Rc::new(ty::TraitRef { def_id: trait_id,
244 substs: trait_substs });
245 let vtbl = fulfill_obligation(bcx.ccx(),
249 // Now that we know which impl is being used, we can dispatch to
250 // the actual function:
252 traits::VtableImpl(traits::VtableImplData {
253 impl_def_id: impl_did,
257 assert!(impl_substs.types.all(|t| !ty::type_needs_infer(*t)));
259 // Create the substitutions that are in scope. This combines
260 // the type parameters from the impl with those declared earlier.
261 // To see what I mean, consider a possible impl:
263 // impl<T> Convert for Vec<T> {
264 // fn from<U:Foo>(n: U) { ... }
267 // Recall that we matched `<Vec<int> as Convert>`. Trait
268 // resolution will have given us a substitution
269 // containing `impl_substs=[[T=int],[],[]]` (the type
270 // parameters defined on the impl). We combine
271 // that with the `rcvr_method` from before, which tells us
272 // the type parameters from the *method*, to yield
273 // `callee_substs=[[T=int],[],[U=String]]`.
274 let subst::SeparateVecsPerParamSpace {
279 } = impl_substs.types.split();
281 Substs::erased(VecPerParamSpace::new(impl_type,
286 let mth_id = method_with_name(ccx, impl_did, mname);
287 let llfn = trans_fn_ref_with_substs(bcx, mth_id, ExprId(expr_id),
290 let callee_ty = node_id_type(bcx, expr_id);
291 let llty = type_of_fn_from_ty(ccx, callee_ty).ptr_to();
292 PointerCast(bcx, llfn, llty)
296 format!("static call to invalid vtable: {}",
297 vtbl.repr(bcx.tcx())).as_slice());
302 fn method_with_name(ccx: &CrateContext, impl_id: ast::DefId, name: ast::Name)
304 match ccx.impl_method_cache().borrow().find_copy(&(impl_id, name)) {
309 let impl_items = ccx.tcx().impl_items.borrow();
311 impl_items.get(&impl_id)
312 .expect("could not find impl while translating");
313 let meth_did = impl_items.iter()
315 ty::impl_or_trait_item(ccx.tcx(), did.def_id()).name() == name
316 }).expect("could not find method while \
319 ccx.impl_method_cache().borrow_mut().insert((impl_id, name),
324 fn trans_monomorphized_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
325 method_call: MethodCall,
326 trait_id: ast::DefId,
328 vtable: traits::Vtable<()>)
329 -> Callee<'blk, 'tcx> {
330 let _icx = push_ctxt("meth::trans_monomorphized_callee");
332 traits::VtableImpl(vtable_impl) => {
334 let impl_did = vtable_impl.impl_def_id;
335 let mname = match ty::trait_item(ccx.tcx(), trait_id, n_method) {
336 ty::MethodTraitItem(method) => method.name,
337 ty::TypeTraitItem(_) => {
338 bcx.tcx().sess.bug("can't monomorphize an associated \
342 let mth_id = method_with_name(bcx.ccx(), impl_did, mname);
344 // create a concatenated set of substitutions which includes
345 // those from the impl and those from the method:
347 combine_impl_and_methods_tps(
348 bcx, MethodCall(method_call), vtable_impl.substs);
350 // translate the function
351 let llfn = trans_fn_ref_with_substs(bcx,
353 MethodCall(method_call),
356 Callee { bcx: bcx, data: Fn(llfn) }
358 traits::VtableUnboxedClosure(closure_def_id, substs) => {
359 // The substitutions should have no type parameters remaining
360 // after passing through fulfill_obligation
361 let llfn = trans_fn_ref_with_substs(bcx,
363 MethodCall(method_call),
373 "vtable_param left in monomorphized function's vtable substs");
378 fn combine_impl_and_methods_tps(bcx: Block,
379 node: ExprOrMethodCall,
380 rcvr_substs: subst::Substs)
384 * Creates a concatenated set of substitutions which includes
385 * those from the impl and those from the method. This are
386 * some subtle complications here. Statically, we have a list
387 * of type parameters like `[T0, T1, T2, M1, M2, M3]` where
388 * `Tn` are type parameters that appear on the receiver. For
389 * example, if the receiver is a method parameter `A` with a
390 * bound like `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
393 * any other type, such as `foo<X>`. In that case, the vector
394 * we want is: `[X, M1, M2, M3]`. Therefore, what we do now is
395 * to slice off the method type parameters and append them to
396 * the type parameters from the type that the receiver is
402 let node_substs = node_id_substs(bcx, node);
404 debug!("rcvr_substs={}", rcvr_substs.repr(ccx.tcx()));
405 debug!("node_substs={}", node_substs.repr(ccx.tcx()));
407 // Break apart the type parameters from the node and type
408 // parameters from the receiver.
409 let node_method = node_substs.types.split().fns;
410 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, rcvr_assoc, node_method)
423 fn trans_trait_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
426 self_expr: &ast::Expr,
427 arg_cleanup_scope: cleanup::ScopeId)
428 -> Callee<'blk, 'tcx> {
430 * Create a method callee where the method is coming from a trait
431 * object (e.g., Box<Trait> type). In this case, we must pull the fn
432 * pointer out of the vtable that is packaged up with the object.
433 * Objects are represented as a pair, so we first evaluate the self
434 * expression and then extract the self data and vtable out of the
438 let _icx = push_ctxt("meth::trans_trait_callee");
441 // Translate self_datum and take ownership of the value by
442 // converting to an rvalue.
443 let self_datum = unpack_datum!(
444 bcx, expr::trans(bcx, self_expr));
446 let llval = if ty::type_needs_drop(bcx.tcx(), self_datum.ty) {
447 let self_datum = unpack_datum!(
448 bcx, self_datum.to_rvalue_datum(bcx, "trait_callee"));
450 // Convert to by-ref since `trans_trait_callee_from_llval` wants it
452 let self_datum = unpack_datum!(
453 bcx, self_datum.to_ref_datum(bcx));
455 // Arrange cleanup in case something should go wrong before the
456 // actual call occurs.
457 self_datum.add_clean(bcx.fcx, arg_cleanup_scope)
459 // We don't have to do anything about cleanups for &Trait and &mut Trait.
460 assert!(self_datum.kind.is_by_ref());
464 trans_trait_callee_from_llval(bcx, method_ty, n_method, llval)
467 pub fn trans_trait_callee_from_llval<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
471 -> Callee<'blk, 'tcx> {
473 * Same as `trans_trait_callee()` above, except that it is given
474 * a by-ref pointer to the object pair.
477 let _icx = push_ctxt("meth::trans_trait_callee");
480 // Load the data pointer from the object.
481 debug!("(translating trait callee) loading second index from pair");
482 let llboxptr = GEPi(bcx, llpair, [0u, abi::trt_field_box]);
483 let llbox = Load(bcx, llboxptr);
484 let llself = PointerCast(bcx, llbox, Type::i8p(ccx));
486 // Load the function from the vtable and cast it to the expected type.
487 debug!("(translating trait callee) loading method");
488 // Replace the self type (&Self or Box<Self>) with an opaque pointer.
489 let llcallee_ty = match ty::get(callee_ty).sty {
490 ty::ty_bare_fn(ref f) if f.abi == Rust || f.abi == RustCall => {
492 Some(Type::i8p(ccx)),
493 f.sig.inputs.slice_from(1),
498 ccx.sess().bug("meth::trans_trait_callee given non-bare-rust-fn");
501 let llvtable = Load(bcx,
504 [0u, abi::trt_field_vtable]),
505 Type::vtable(ccx).ptr_to().ptr_to()));
506 let mptr = Load(bcx, GEPi(bcx, llvtable, [0u, n_method + VTABLE_OFFSET]));
507 let mptr = PointerCast(bcx, mptr, llcallee_ty.ptr_to());
511 data: TraitItem(MethodData {
518 /// Creates a returns a dynamic vtable for the given type and vtable origin.
519 /// This is used only for objects.
521 /// The `trait_ref` encodes the erased self type. Hence if we are
522 /// making an object `Foo<Trait>` from a value of type `Foo<T>`, then
523 /// `trait_ref` would map `T:Trait`, but `box_ty` would be
524 /// `Foo<T>`. This `box_ty` is primarily used to encode the destructor.
525 /// This will hopefully change now that DST is underway.
526 pub fn get_vtable(bcx: Block,
528 trait_ref: Rc<ty::TraitRef>)
531 debug!("get_vtable(box_ty={}, trait_ref={})",
532 box_ty.repr(bcx.tcx()),
533 trait_ref.repr(bcx.tcx()));
537 let _icx = push_ctxt("meth::get_vtable");
540 let cache_key = (box_ty, trait_ref.clone());
541 match ccx.vtables().borrow().get(&cache_key) {
542 Some(&val) => { return val }
546 // Not in the cache. Build it.
547 let methods = traits::supertraits(tcx, trait_ref.clone()).flat_map(|trait_ref| {
548 let vtable = fulfill_obligation(bcx.ccx(),
552 traits::VtableBuiltin(_) => {
553 Vec::new().into_iter()
556 traits::VtableImplData {
560 emit_vtable_methods(bcx, id, substs).into_iter()
562 traits::VtableUnboxedClosure(closure_def_id, substs) => {
563 // Look up closure type
564 let self_ty = ty::node_id_to_type(bcx.tcx(), closure_def_id.node);
565 // Apply substitutions from closure param environment.
566 // The substitutions should have no type parameters
567 // remaining after passing through fulfill_obligation
568 let self_ty = self_ty.subst(bcx.tcx(), &substs);
570 let mut llfn = trans_fn_ref_with_substs(
577 let unboxed_closures = bcx.tcx()
581 unboxed_closures.get(&closure_def_id)
582 .expect("get_vtable(): didn't find \
584 if closure_info.kind == ty::FnOnceUnboxedClosureKind {
585 // Untuple the arguments and create an unboxing shim.
586 let (new_inputs, new_output) = match ty::get(self_ty).sty {
587 ty::ty_unboxed_closure(_, _, ref substs) => {
588 let mut new_inputs = vec![self_ty.clone()];
589 match ty::get(closure_info.closure_type
592 ty::ty_tup(ref elements) => {
593 for element in elements.iter() {
594 new_inputs.push(element.subst(bcx.tcx(), substs));
599 bcx.tcx().sess.bug("get_vtable(): closure \
600 type wasn't a tuple")
604 closure_info.closure_type.sig.output.subst(bcx.tcx(), substs))
606 _ => bcx.tcx().sess.bug("get_vtable(): def wasn't an unboxed closure")
609 let closure_type = ty::BareFnTy {
610 fn_style: closure_info.closure_type.fn_style,
613 binder_id: closure_info.closure_type
621 debug!("get_vtable(): closure type is {}",
622 closure_type.repr(bcx.tcx()));
623 llfn = trans_unboxing_shim(bcx,
631 (vec!(llfn)).into_iter()
633 traits::VtableParam(..) => {
635 format!("resolved vtable for {} to bad vtable {} in trans",
636 trait_ref.repr(bcx.tcx()),
637 vtable.repr(bcx.tcx())).as_slice());
642 let size_ty = sizing_type_of(ccx, trait_ref.self_ty());
643 let size = machine::llsize_of_alloc(ccx, size_ty);
644 let ll_size = C_uint(ccx, size);
645 let align = align_of(ccx, trait_ref.self_ty());
646 let ll_align = C_uint(ccx, align);
648 // Generate a destructor for the vtable.
649 let drop_glue = glue::get_drop_glue(ccx, box_ty);
650 let vtable = make_vtable(ccx, drop_glue, ll_size, ll_align, methods);
652 ccx.vtables().borrow_mut().insert(cache_key, vtable);
656 /// Helper function to declare and initialize the vtable.
657 pub fn make_vtable<I: Iterator<ValueRef>>(ccx: &CrateContext,
663 let _icx = push_ctxt("meth::make_vtable");
665 let head = vec![drop_glue, size, align];
666 let components: Vec<_> = head.into_iter().chain(ptrs).collect();
669 let tbl = C_struct(ccx, components.as_slice(), false);
670 let sym = token::gensym("vtable");
671 let vt_gvar = format!("vtable{}", sym.uint()).with_c_str(|buf| {
672 llvm::LLVMAddGlobal(ccx.llmod(), val_ty(tbl).to_ref(), buf)
674 llvm::LLVMSetInitializer(vt_gvar, tbl);
675 llvm::LLVMSetGlobalConstant(vt_gvar, llvm::True);
676 llvm::SetLinkage(vt_gvar, llvm::InternalLinkage);
681 fn emit_vtable_methods(bcx: Block,
683 substs: subst::Substs)
688 let trt_id = match ty::impl_trait_ref(tcx, impl_id) {
689 Some(t_id) => t_id.def_id,
690 None => ccx.sess().bug("make_impl_vtable: don't know how to \
691 make a vtable for a type impl!")
694 ty::populate_implementations_for_trait_if_necessary(bcx.tcx(), trt_id);
696 let trait_item_def_ids = ty::trait_item_def_ids(tcx, trt_id);
697 trait_item_def_ids.iter().flat_map(|method_def_id| {
698 let method_def_id = method_def_id.def_id();
699 let name = ty::impl_or_trait_item(tcx, method_def_id).name();
700 // The substitutions we have are on the impl, so we grab
701 // the method type from the impl to substitute into.
702 let m_id = method_with_name(ccx, impl_id, name);
703 let ti = ty::impl_or_trait_item(tcx, m_id);
705 ty::MethodTraitItem(m) => {
706 debug!("(making impl vtable) emitting method {} at subst {}",
709 if m.generics.has_type_params(subst::FnSpace) ||
710 ty::type_has_self(ty::mk_bare_fn(tcx, m.fty.clone())) {
711 debug!("(making impl vtable) method has self or type \
713 token::get_name(name));
714 Some(C_null(Type::nil(ccx).ptr_to())).into_iter()
716 let mut fn_ref = trans_fn_ref_with_substs(
721 if m.explicit_self == ty::ByValueExplicitSelfCategory {
722 fn_ref = trans_unboxing_shim(bcx,
728 Some(fn_ref).into_iter()
731 ty::TypeTraitItem(_) => {
738 pub fn trans_trait_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
741 trait_ref: Rc<ty::TraitRef>,
743 -> Block<'blk, 'tcx> {
745 * Generates the code to convert from a pointer (`Box<T>`, `&T`, etc)
746 * into an object (`Box<Trait>`, `&Trait`, etc). This means creating a
747 * pair where the first word is the vtable and the second word is
752 let _icx = push_ctxt("meth::trans_trait_cast");
754 let lldest = match dest {
756 return datum.clean(bcx, "trait_trait_cast", id);
761 debug!("trans_trait_cast: trait_ref={}",
762 trait_ref.repr(bcx.tcx()));
764 let datum_ty = datum.ty;
765 let llbox_ty = type_of(bcx.ccx(), datum_ty);
767 // Store the pointer into the first half of pair.
768 let llboxdest = GEPi(bcx, lldest, [0u, abi::trt_field_box]);
769 let llboxdest = PointerCast(bcx, llboxdest, llbox_ty.ptr_to());
770 bcx = datum.store_to(bcx, llboxdest);
772 // Store the vtable into the second half of pair.
773 let vtable = get_vtable(bcx, datum_ty, trait_ref);
774 let llvtabledest = GEPi(bcx, lldest, [0u, abi::trt_field_vtable]);
775 let llvtabledest = PointerCast(bcx, llvtabledest, val_ty(vtable).ptr_to());
776 Store(bcx, vtable, llvtabledest);