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;
13 use llvm::{ValueRef, get_params};
14 use middle::def_id::DefId;
15 use middle::subst::{Subst, Substs};
16 use middle::subst::VecPerParamSpace;
28 use trans::debuginfo::DebugLoc;
30 use trans::expr::SaveIn;
34 use trans::monomorphize;
35 use trans::type_::Type;
36 use trans::type_of::*;
37 use middle::ty::{self, Ty, HasTypeFlags};
38 use middle::ty::MethodCall;
42 use syntax::codemap::DUMMY_SP;
45 use rustc_front::visit;
48 // drop_glue pointer, size, align.
49 const VTABLE_OFFSET: usize = 3;
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,
57 impl_items: &[P<hir::ImplItem>],
58 generics: &hir::Generics,
60 let _icx = push_ctxt("meth::trans_impl");
63 debug!("trans_impl(name={}, id={})", name, id);
65 let mut v = TransItemVisitor { ccx: ccx };
67 // Both here and below with generic methods, be sure to recurse and look for
68 // items that we need to translate.
69 if !generics.ty_params.is_empty() {
70 for impl_item in impl_items {
71 match impl_item.node {
72 hir::MethodImplItem(..) => {
73 visit::walk_impl_item(&mut v, impl_item);
80 for impl_item in impl_items {
81 match impl_item.node {
82 hir::MethodImplItem(ref sig, ref body) => {
83 if sig.generics.ty_params.is_empty() {
84 let trans_everywhere = attr::requests_inline(&impl_item.attrs);
85 for (ref ccx, is_origin) in ccx.maybe_iter(trans_everywhere) {
86 let llfn = get_item_val(ccx, impl_item.id);
87 let empty_substs = tcx.mk_substs(Substs::trans_empty());
88 trans_fn(ccx, &sig.decl, body, llfn,
89 empty_substs, impl_item.id, &[]);
93 if is_origin { OriginalTranslation } else { InlinedCopy });
96 visit::walk_impl_item(&mut v, impl_item);
103 pub fn trans_method_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
104 method_call: MethodCall,
105 self_expr: Option<&hir::Expr>,
106 arg_cleanup_scope: cleanup::ScopeId)
107 -> Callee<'blk, 'tcx> {
108 let _icx = push_ctxt("meth::trans_method_callee");
110 let method = bcx.tcx().tables.borrow().method_map[&method_call];
112 match bcx.tcx().impl_or_trait_item(method.def_id).container() {
113 ty::ImplContainer(_) => {
114 debug!("trans_method_callee: static, {:?}", method.def_id);
115 let datum = callee::trans_fn_ref(bcx.ccx(),
117 MethodCallKey(method_call),
118 bcx.fcx.param_substs);
126 ty::TraitContainer(trait_def_id) => {
127 let trait_substs = method.substs.clone().method_to_trait();
128 let trait_substs = bcx.tcx().mk_substs(trait_substs);
129 let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
131 let trait_ref = ty::Binder(bcx.monomorphize(&trait_ref));
132 let span = bcx.tcx().map.span(method_call.expr_id);
133 debug!("method_call={:?} trait_ref={:?} trait_ref id={:?} substs={:?}",
138 let origin = fulfill_obligation(bcx.ccx(),
141 debug!("origin = {:?}", origin);
142 trans_monomorphized_callee(bcx,
154 pub fn trans_static_method_callee<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
157 expr_id: ast::NodeId,
158 param_substs: &'tcx subst::Substs<'tcx>)
159 -> Datum<'tcx, Rvalue>
161 let _icx = push_ctxt("meth::trans_static_method_callee");
164 debug!("trans_static_method_callee(method_id={:?}, trait_id={}, \
167 tcx.item_path_str(trait_id),
170 let mname = tcx.item_name(method_id);
172 debug!("trans_static_method_callee: method_id={:?}, expr_id={}, \
173 name={}", method_id, expr_id, mname);
175 // Find the substitutions for the fn itself. This includes
176 // type parameters that belong to the trait but also some that
177 // belong to the method:
178 let rcvr_substs = node_id_substs(ccx, ExprId(expr_id), param_substs);
179 let subst::SeparateVecsPerParamSpace {
183 } = rcvr_substs.types.split();
185 // Lookup the precise impl being called. To do that, we need to
186 // create a trait reference identifying the self type and other
187 // input type parameters. To create that trait reference, we have
188 // to pick apart the type parameters to identify just those that
189 // pertain to the trait. This is easiest to explain by example:
192 // fn from<U:Foo>(n: U) -> Option<Self>;
195 // let f = <Vec<int> as Convert>::from::<String>(...)
197 // Here, in this call, which I've written with explicit UFCS
198 // notation, the set of type parameters will be:
200 // rcvr_type: [] <-- nothing declared on the trait itself
201 // rcvr_self: [Vec<int>] <-- the self type
202 // rcvr_method: [String] <-- method type parameter
204 // So we create a trait reference using the first two,
205 // basically corresponding to `<Vec<int> as Convert>`.
206 // The remaining type parameters (`rcvr_method`) will be used below.
208 Substs::erased(VecPerParamSpace::new(rcvr_type,
211 let trait_substs = tcx.mk_substs(trait_substs);
212 debug!("trait_substs={:?}", trait_substs);
213 let trait_ref = ty::Binder(ty::TraitRef::new(trait_id, trait_substs));
214 let vtbl = fulfill_obligation(ccx,
218 // Now that we know which impl is being used, we can dispatch to
219 // the actual function:
221 traits::VtableImpl(traits::VtableImplData {
222 impl_def_id: impl_did,
226 assert!(!impl_substs.types.needs_infer());
228 // Create the substitutions that are in scope. This combines
229 // the type parameters from the impl with those declared earlier.
230 // To see what I mean, consider a possible impl:
232 // impl<T> Convert for Vec<T> {
233 // fn from<U:Foo>(n: U) { ... }
236 // Recall that we matched `<Vec<int> as Convert>`. Trait
237 // resolution will have given us a substitution
238 // containing `impl_substs=[[T=int],[],[]]` (the type
239 // parameters defined on the impl). We combine
240 // that with the `rcvr_method` from before, which tells us
241 // the type parameters from the *method*, to yield
242 // `callee_substs=[[T=int],[],[U=String]]`.
243 let subst::SeparateVecsPerParamSpace {
247 } = impl_substs.types.split();
249 Substs::erased(VecPerParamSpace::new(impl_type,
253 let mth = tcx.get_impl_method(impl_did, callee_substs, mname);
254 trans_fn_ref_with_substs(ccx, mth.method.def_id, ExprId(expr_id),
258 traits::VtableObject(ref data) => {
259 let idx = traits::get_vtable_index_of_object_method(tcx, data, method_id);
260 trans_object_shim(ccx,
261 data.upcast_trait_ref.clone(),
266 tcx.sess.bug(&format!("static call to invalid vtable: {:?}",
272 fn trans_monomorphized_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
273 method_call: MethodCall,
274 self_expr: Option<&hir::Expr>,
278 vtable: traits::Vtable<'tcx, ()>,
279 arg_cleanup_scope: cleanup::ScopeId)
280 -> Callee<'blk, 'tcx> {
281 let _icx = push_ctxt("meth::trans_monomorphized_callee");
283 traits::VtableImpl(vtable_impl) => {
285 let impl_did = vtable_impl.impl_def_id;
286 let mname = match ccx.tcx().impl_or_trait_item(method_id) {
287 ty::MethodTraitItem(method) => method.name,
289 bcx.tcx().sess.bug("can't monomorphize a non-method trait \
293 // create a concatenated set of substitutions which includes
294 // those from the impl and those from the method:
296 combine_impl_and_methods_tps(
297 bcx, MethodCallKey(method_call), vtable_impl.substs);
299 let mth = bcx.tcx().get_impl_method(impl_did, callee_substs, mname);
300 // translate the function
301 let datum = trans_fn_ref_with_substs(bcx.ccx(),
303 MethodCallKey(method_call),
304 bcx.fcx.param_substs,
307 Callee { bcx: bcx, data: Fn(datum.val), ty: datum.ty }
309 traits::VtableClosure(vtable_closure) => {
310 // The substitutions should have no type parameters remaining
311 // after passing through fulfill_obligation
312 let trait_closure_kind = bcx.tcx().lang_items.fn_trait_kind(trait_id).unwrap();
313 let llfn = closure::trans_closure_method(bcx.ccx(),
314 vtable_closure.closure_def_id,
315 vtable_closure.substs,
320 ty: monomorphize_type(bcx, method_ty)
323 traits::VtableFnPointer(fn_ty) => {
324 let trait_closure_kind = bcx.tcx().lang_items.fn_trait_kind(trait_id).unwrap();
325 let llfn = trans_fn_pointer_shim(bcx.ccx(), trait_closure_kind, fn_ty);
329 ty: monomorphize_type(bcx, method_ty)
332 traits::VtableObject(ref data) => {
333 let idx = traits::get_vtable_index_of_object_method(bcx.tcx(), data, method_id);
334 if let Some(self_expr) = self_expr {
335 if let ty::TyBareFn(_, ref fty) = monomorphize_type(bcx, method_ty).sty {
336 let ty = bcx.tcx().mk_fn(None, opaque_method_ty(bcx.tcx(), fty));
337 return trans_trait_callee(bcx, ty, idx, self_expr, arg_cleanup_scope);
340 let datum = trans_object_shim(bcx.ccx(),
341 data.upcast_trait_ref.clone(),
344 Callee { bcx: bcx, data: Fn(datum.val), ty: datum.ty }
346 traits::VtableBuiltin(..) |
347 traits::VtableDefaultImpl(..) |
348 traits::VtableParam(..) => {
350 &format!("resolved vtable bad vtable {:?} in trans",
356 /// Creates a concatenated set of substitutions which includes those from the impl and those from
357 /// the method. This are some subtle complications here. Statically, we have a list of type
358 /// parameters like `[T0, T1, T2, M1, M2, M3]` where `Tn` are type parameters that appear on the
359 /// receiver. For example, if the receiver is a method parameter `A` with a bound like
360 /// `trait<B,C,D>` then `Tn` would be `[B,C,D]`.
362 /// The weird part is that the type `A` might now be bound to any other type, such as `foo<X>`.
363 /// In that case, the vector we want is: `[X, M1, M2, M3]`. Therefore, what we do now is to slice
364 /// off the method type parameters and append them to the type parameters from the type that the
365 /// receiver is mapped to.
366 fn combine_impl_and_methods_tps<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
367 node: ExprOrMethodCall,
368 rcvr_substs: subst::Substs<'tcx>)
369 -> subst::Substs<'tcx>
373 let node_substs = node_id_substs(ccx, node, bcx.fcx.param_substs);
375 debug!("rcvr_substs={:?}", rcvr_substs);
376 debug!("node_substs={:?}", node_substs);
378 // Break apart the type parameters from the node and type
379 // parameters from the receiver.
380 let node_method = node_substs.types.split().fns;
381 let subst::SeparateVecsPerParamSpace {
385 } = rcvr_substs.types.clone().split();
386 assert!(rcvr_method.is_empty());
388 regions: subst::ErasedRegions,
389 types: subst::VecPerParamSpace::new(rcvr_type, rcvr_self, node_method)
393 /// Create a method callee where the method is coming from a trait object (e.g., Box<Trait> type).
394 /// In this case, we must pull the fn pointer out of the vtable that is packaged up with the
395 /// object. Objects are represented as a pair, so we first evaluate the self expression and then
396 /// extract the self data and vtable out of the pair.
397 fn trans_trait_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
398 opaque_fn_ty: Ty<'tcx>,
400 self_expr: &hir::Expr,
401 arg_cleanup_scope: cleanup::ScopeId)
402 -> Callee<'blk, 'tcx> {
403 let _icx = push_ctxt("meth::trans_trait_callee");
406 // Translate self_datum and take ownership of the value by
407 // converting to an rvalue.
408 let self_datum = unpack_datum!(
409 bcx, expr::trans(bcx, self_expr));
411 let llval = if bcx.fcx.type_needs_drop(self_datum.ty) {
412 let self_datum = unpack_datum!(
413 bcx, self_datum.to_rvalue_datum(bcx, "trait_callee"));
415 // Convert to by-ref since `trans_trait_callee_from_llval` wants it
417 let self_datum = unpack_datum!(
418 bcx, self_datum.to_ref_datum(bcx));
420 // Arrange cleanup in case something should go wrong before the
421 // actual call occurs.
422 self_datum.add_clean(bcx.fcx, arg_cleanup_scope)
424 // We don't have to do anything about cleanups for &Trait and &mut Trait.
425 assert!(self_datum.kind.is_by_ref());
429 let llself = Load(bcx, expr::get_dataptr(bcx, llval));
430 let llvtable = Load(bcx, expr::get_meta(bcx, llval));
431 trans_trait_callee_from_llval(bcx, opaque_fn_ty, vtable_index, llself, llvtable)
434 /// Same as `trans_trait_callee()` above, except that it is given a by-ref pointer to the object
436 fn trans_trait_callee_from_llval<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
437 opaque_fn_ty: Ty<'tcx>,
441 -> Callee<'blk, 'tcx> {
442 let _icx = push_ctxt("meth::trans_trait_callee");
445 // Load the data pointer from the object.
446 debug!("trans_trait_callee_from_llval(callee_ty={}, vtable_index={}, llself={}, llvtable={})",
449 bcx.val_to_string(llself),
450 bcx.val_to_string(llvtable));
452 // Replace the self type (&Self or Box<Self>) with an opaque pointer.
453 let mptr = Load(bcx, GEPi(bcx, llvtable, &[vtable_index + VTABLE_OFFSET]));
454 let llcallee_ty = type_of_fn_from_ty(ccx, opaque_fn_ty);
458 data: TraitItem(MethodData {
459 llfn: PointerCast(bcx, mptr, llcallee_ty.ptr_to()),
460 llself: PointerCast(bcx, llself, Type::i8p(ccx)),
466 /// Generate a shim function that allows an object type like `SomeTrait` to
467 /// implement the type `SomeTrait`. Imagine a trait definition:
469 /// trait SomeTrait { fn get(&self) -> int; ... }
471 /// And a generic bit of code:
473 /// fn foo<T:SomeTrait>(t: &T) {
474 /// let x = SomeTrait::get;
478 /// What is the value of `x` when `foo` is invoked with `T=SomeTrait`?
479 /// The answer is that it is a shim function generated by this routine:
481 /// fn shim(t: &SomeTrait) -> int {
482 /// // ... call t.get() virtually ...
485 /// In fact, all virtual calls can be thought of as normal trait calls
486 /// that go through this shim function.
487 fn trans_object_shim<'a, 'tcx>(
488 ccx: &'a CrateContext<'a, 'tcx>,
489 upcast_trait_ref: ty::PolyTraitRef<'tcx>,
492 -> Datum<'tcx, Rvalue>
494 let _icx = push_ctxt("trans_object_shim");
497 debug!("trans_object_shim(upcast_trait_ref={:?}, method_id={:?})",
501 // Upcast to the trait in question and extract out the substitutions.
502 let upcast_trait_ref = tcx.erase_late_bound_regions(&upcast_trait_ref);
503 let object_substs = upcast_trait_ref.substs.clone().erase_regions();
504 debug!("trans_object_shim: object_substs={:?}", object_substs);
506 // Lookup the type of this method as declared in the trait and apply substitutions.
507 let method_ty = match tcx.impl_or_trait_item(method_id) {
508 ty::MethodTraitItem(method) => method,
510 tcx.sess.bug("can't create a method shim for a non-method item")
513 let fty = monomorphize::apply_param_substs(tcx, &object_substs, &method_ty.fty);
514 let fty = tcx.mk_bare_fn(fty);
515 let method_ty = opaque_method_ty(tcx, fty);
516 debug!("trans_object_shim: fty={:?} method_ty={:?}", fty, method_ty);
519 let shim_fn_ty = tcx.mk_fn(None, fty);
520 let method_bare_fn_ty = tcx.mk_fn(None, method_ty);
521 let function_name = link::mangle_internal_name_by_type_and_seq(ccx, shim_fn_ty, "object_shim");
522 let llfn = declare::define_internal_rust_fn(ccx, &function_name, shim_fn_ty);
524 let sig = ccx.tcx().erase_late_bound_regions(&fty.sig);
526 let empty_substs = tcx.mk_substs(Substs::trans_empty());
527 let (block_arena, fcx): (TypedArena<_>, FunctionContext);
528 block_arena = TypedArena::new();
529 fcx = new_fn_ctxt(ccx,
537 let mut bcx = init_function(&fcx, false, sig.output);
539 let llargs = get_params(fcx.llfn);
541 let self_idx = fcx.arg_offset();
542 let llself = llargs[self_idx];
543 let llvtable = llargs[self_idx + 1];
545 debug!("trans_object_shim: llself={}, llvtable={}",
546 bcx.val_to_string(llself), bcx.val_to_string(llvtable));
548 assert!(!fcx.needs_ret_allocas);
551 fcx.llretslotptr.get().map(
552 |_| expr::SaveIn(fcx.get_ret_slot(bcx, sig.output, "ret_slot")));
554 debug!("trans_object_shim: method_offset_in_vtable={}",
557 bcx = trans_call_inner(bcx,
559 |bcx, _| trans_trait_callee_from_llval(bcx,
563 ArgVals(&llargs[(self_idx + 2)..]),
566 finish_fn(&fcx, bcx, sig.output, DebugLoc::None);
568 immediate_rvalue(llfn, shim_fn_ty)
571 /// Creates a returns a dynamic vtable for the given type and vtable origin.
572 /// This is used only for objects.
574 /// The `trait_ref` encodes the erased self type. Hence if we are
575 /// making an object `Foo<Trait>` from a value of type `Foo<T>`, then
576 /// `trait_ref` would map `T:Trait`.
577 pub fn get_vtable<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
578 trait_ref: ty::PolyTraitRef<'tcx>,
579 param_substs: &'tcx subst::Substs<'tcx>)
583 let _icx = push_ctxt("meth::get_vtable");
585 debug!("get_vtable(trait_ref={:?})", trait_ref);
588 match ccx.vtables().borrow().get(&trait_ref) {
589 Some(&val) => { return val }
593 // Not in the cache. Build it.
594 let methods = traits::supertraits(tcx, trait_ref.clone()).flat_map(|trait_ref| {
595 let vtable = fulfill_obligation(ccx, DUMMY_SP, trait_ref.clone());
597 // Should default trait error here?
598 traits::VtableDefaultImpl(_) |
599 traits::VtableBuiltin(_) => {
600 Vec::new().into_iter()
603 traits::VtableImplData {
607 emit_vtable_methods(ccx, id, substs, param_substs).into_iter()
609 traits::VtableClosure(
610 traits::VtableClosureData {
614 let trait_closure_kind = tcx.lang_items.fn_trait_kind(trait_ref.def_id()).unwrap();
615 let llfn = closure::trans_closure_method(ccx,
619 vec![llfn].into_iter()
621 traits::VtableFnPointer(bare_fn_ty) => {
622 let trait_closure_kind = tcx.lang_items.fn_trait_kind(trait_ref.def_id()).unwrap();
623 vec![trans_fn_pointer_shim(ccx, trait_closure_kind, bare_fn_ty)].into_iter()
625 traits::VtableObject(ref data) => {
626 // this would imply that the Self type being erased is
627 // an object type; this cannot happen because we
628 // cannot cast an unsized type into a trait object
630 &format!("cannot get vtable for an object type: {:?}",
633 traits::VtableParam(..) => {
635 &format!("resolved vtable for {:?} to bad vtable {:?} in trans",
642 let size_ty = sizing_type_of(ccx, trait_ref.self_ty());
643 let size = machine::llsize_of_alloc(ccx, size_ty);
644 let align = align_of(ccx, trait_ref.self_ty());
646 let components: Vec<_> = vec![
647 // Generate a destructor for the vtable.
648 glue::get_drop_glue(ccx, trait_ref.self_ty()),
651 ].into_iter().chain(methods).collect();
653 let vtable_const = C_struct(ccx, &components, false);
654 let align = machine::llalign_of_pref(ccx, val_ty(vtable_const));
655 let vtable = consts::addr_of(ccx, vtable_const, align, "vtable");
657 ccx.vtables().borrow_mut().insert(trait_ref, vtable);
661 fn emit_vtable_methods<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
663 substs: subst::Substs<'tcx>,
664 param_substs: &'tcx subst::Substs<'tcx>)
669 debug!("emit_vtable_methods(impl_id={:?}, substs={:?}, param_substs={:?})",
674 let trt_id = match tcx.impl_trait_ref(impl_id) {
675 Some(t_id) => t_id.def_id,
676 None => ccx.sess().bug("make_impl_vtable: don't know how to \
677 make a vtable for a type impl!")
680 tcx.populate_implementations_for_trait_if_necessary(trt_id);
682 let nullptr = C_null(Type::nil(ccx).ptr_to());
683 let trait_item_def_ids = tcx.trait_item_def_ids(trt_id);
687 // Filter out non-method items.
688 .filter_map(|item_def_id| {
690 ty::MethodTraitItemId(def_id) => Some(def_id),
695 // Now produce pointers for each remaining method. If the
696 // method could never be called from this object, just supply
698 .map(|trait_method_def_id| {
699 debug!("emit_vtable_methods: trait_method_def_id={:?}",
700 trait_method_def_id);
702 let trait_method_type = match tcx.impl_or_trait_item(trait_method_def_id) {
703 ty::MethodTraitItem(m) => m,
704 _ => ccx.sess().bug("should be a method, not other assoc item"),
706 let name = trait_method_type.name;
708 // Some methods cannot be called on an object; skip those.
709 if !traits::is_vtable_safe_method(tcx, trt_id, &trait_method_type) {
710 debug!("emit_vtable_methods: not vtable safe");
714 debug!("emit_vtable_methods: trait_method_type={:?}",
717 // The substitutions we have are on the impl, so we grab
718 // the method type from the impl to substitute into.
719 let mth = tcx.get_impl_method(impl_id, substs.clone(), name);
721 debug!("emit_vtable_methods: mth={:?}", mth);
723 // If this is a default method, it's possible that it
724 // relies on where clauses that do not hold for this
725 // particular set of type parameters. Note that this
726 // method could then never be called, so we do not want to
727 // try and trans it, in that case. Issue #23435.
729 let predicates = mth.method.predicates.predicates.subst(tcx, &mth.substs);
730 if !normalize_and_test_predicates(ccx, predicates.into_vec()) {
731 debug!("emit_vtable_methods: predicates do not hold");
736 trans_fn_ref_with_substs(ccx,
745 /// Replace the self type (&Self or Box<Self>) with an opaque pointer.
746 fn opaque_method_ty<'tcx>(tcx: &ty::ctxt<'tcx>, method_ty: &ty::BareFnTy<'tcx>)
747 -> &'tcx ty::BareFnTy<'tcx> {
748 let mut inputs = method_ty.sig.0.inputs.clone();
749 inputs[0] = tcx.mk_mut_ptr(tcx.mk_mach_int(ast::TyI8));
751 tcx.mk_bare_fn(ty::BareFnTy {
752 unsafety: method_ty.unsafety,
754 sig: ty::Binder(ty::FnSig {
756 output: method_ty.sig.0.output,
757 variadic: method_ty.sig.0.variadic,