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;
16 use middle::subst::{Subst, Substs};
17 use middle::subst::VecPerParamSpace;
29 use trans::debuginfo::DebugLoc;
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;
46 // drop_glue pointer, size, align.
47 const VTABLE_OFFSET: usize = 3;
49 /// The main "translation" pass for methods. Generates code
50 /// for non-monomorphized methods only. Other methods will
51 /// be generated once they are invoked with specific type parameters,
52 /// see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`.
53 pub fn trans_impl(ccx: &CrateContext,
55 impl_items: &[hir::ImplItem],
56 generics: &hir::Generics,
58 let _icx = push_ctxt("meth::trans_impl");
61 debug!("trans_impl(name={}, id={})", name, id);
63 // Both here and below with generic methods, be sure to recurse and look for
64 // items that we need to translate.
65 if !generics.ty_params.is_empty() {
69 for impl_item in impl_items {
70 match impl_item.node {
71 hir::ImplItemKind::Method(ref sig, ref body) => {
72 if sig.generics.ty_params.is_empty() {
73 let trans_everywhere = attr::requests_inline(&impl_item.attrs);
74 for (ref ccx, is_origin) in ccx.maybe_iter(trans_everywhere) {
75 let llfn = get_item_val(ccx, impl_item.id);
76 let empty_substs = tcx.mk_substs(Substs::trans_empty());
77 trans_fn(ccx, &sig.decl, body, llfn,
78 empty_substs, impl_item.id, &[]);
82 if is_origin { OriginalTranslation } else { InlinedCopy });
91 pub fn trans_method_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
92 method_call: MethodCall,
93 self_expr: Option<&hir::Expr>,
94 arg_cleanup_scope: cleanup::ScopeId)
95 -> Callee<'blk, 'tcx> {
96 let _icx = push_ctxt("meth::trans_method_callee");
98 let method = bcx.tcx().tables.borrow().method_map[&method_call];
100 match bcx.tcx().impl_or_trait_item(method.def_id).container() {
101 ty::ImplContainer(_) => {
102 debug!("trans_method_callee: static, {:?}", method.def_id);
103 let datum = callee::trans_fn_ref(bcx.ccx(),
105 MethodCallKey(method_call),
106 bcx.fcx.param_substs);
114 ty::TraitContainer(trait_def_id) => {
115 let trait_substs = method.substs.clone().method_to_trait();
116 let trait_substs = bcx.tcx().mk_substs(trait_substs);
117 let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
119 let trait_ref = ty::Binder(bcx.monomorphize(&trait_ref));
120 let span = bcx.tcx().map.span(method_call.expr_id);
121 debug!("method_call={:?} trait_ref={:?} trait_ref id={:?} substs={:?}",
126 let origin = fulfill_obligation(bcx.ccx(),
129 debug!("origin = {:?}", origin);
130 trans_monomorphized_callee(bcx,
142 pub fn trans_static_method_callee<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
145 expr_id: ast::NodeId,
146 param_substs: &'tcx subst::Substs<'tcx>)
147 -> Datum<'tcx, Rvalue>
149 let _icx = push_ctxt("meth::trans_static_method_callee");
152 debug!("trans_static_method_callee(method_id={:?}, trait_id={}, \
155 tcx.item_path_str(trait_id),
158 let mname = tcx.item_name(method_id);
160 debug!("trans_static_method_callee: method_id={:?}, expr_id={}, \
161 name={}", method_id, expr_id, mname);
163 // Find the substitutions for the fn itself. This includes
164 // type parameters that belong to the trait but also some that
165 // belong to the method:
166 let rcvr_substs = node_id_substs(ccx, ExprId(expr_id), param_substs);
167 let subst::SeparateVecsPerParamSpace {
171 } = rcvr_substs.types.split();
173 // Lookup the precise impl being called. To do that, we need to
174 // create a trait reference identifying the self type and other
175 // input type parameters. To create that trait reference, we have
176 // to pick apart the type parameters to identify just those that
177 // pertain to the trait. This is easiest to explain by example:
180 // fn from<U:Foo>(n: U) -> Option<Self>;
183 // let f = <Vec<i32> as Convert>::from::<String>(...)
185 // Here, in this call, which I've written with explicit UFCS
186 // notation, the set of type parameters will be:
188 // rcvr_type: [] <-- nothing declared on the trait itself
189 // rcvr_self: [Vec<i32>] <-- the self type
190 // rcvr_method: [String] <-- method type parameter
192 // So we create a trait reference using the first two,
193 // basically corresponding to `<Vec<i32> as Convert>`.
194 // The remaining type parameters (`rcvr_method`) will be used below.
196 Substs::erased(VecPerParamSpace::new(rcvr_type,
199 let trait_substs = tcx.mk_substs(trait_substs);
200 debug!("trait_substs={:?}", trait_substs);
201 let trait_ref = ty::Binder(ty::TraitRef::new(trait_id, trait_substs));
202 let vtbl = fulfill_obligation(ccx,
206 // Now that we know which impl is being used, we can dispatch to
207 // the actual function:
209 traits::VtableImpl(traits::VtableImplData {
210 impl_def_id: impl_did,
214 assert!(!impl_substs.types.needs_infer());
216 // Create the substitutions that are in scope. This combines
217 // the type parameters from the impl with those declared earlier.
218 // To see what I mean, consider a possible impl:
220 // impl<T> Convert for Vec<T> {
221 // fn from<U:Foo>(n: U) { ... }
224 // Recall that we matched `<Vec<i32> as Convert>`. Trait
225 // resolution will have given us a substitution
226 // containing `impl_substs=[[T=i32],[],[]]` (the type
227 // parameters defined on the impl). We combine
228 // that with the `rcvr_method` from before, which tells us
229 // the type parameters from the *method*, to yield
230 // `callee_substs=[[T=i32],[],[U=String]]`.
231 let subst::SeparateVecsPerParamSpace {
235 } = impl_substs.types.split();
237 Substs::erased(VecPerParamSpace::new(impl_type,
241 let mth = tcx.get_impl_method(impl_did, callee_substs, mname);
242 trans_fn_ref_with_substs(ccx, mth.method.def_id, ExprId(expr_id),
246 traits::VtableObject(ref data) => {
247 let idx = traits::get_vtable_index_of_object_method(tcx, data, method_id);
248 trans_object_shim(ccx,
249 data.upcast_trait_ref.clone(),
254 tcx.sess.bug(&format!("static call to invalid vtable: {:?}",
260 fn trans_monomorphized_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
261 method_call: MethodCall,
262 self_expr: Option<&hir::Expr>,
266 vtable: traits::Vtable<'tcx, ()>,
267 arg_cleanup_scope: cleanup::ScopeId)
268 -> Callee<'blk, 'tcx> {
269 let _icx = push_ctxt("meth::trans_monomorphized_callee");
271 traits::VtableImpl(vtable_impl) => {
273 let impl_did = vtable_impl.impl_def_id;
274 let mname = match ccx.tcx().impl_or_trait_item(method_id) {
275 ty::MethodTraitItem(method) => method.name,
277 bcx.tcx().sess.bug("can't monomorphize a non-method trait \
281 // create a concatenated set of substitutions which includes
282 // those from the impl and those from the method:
284 combine_impl_and_methods_tps(
285 bcx, MethodCallKey(method_call), vtable_impl.substs);
287 let mth = bcx.tcx().get_impl_method(impl_did, callee_substs, mname);
288 // translate the function
289 let datum = trans_fn_ref_with_substs(bcx.ccx(),
291 MethodCallKey(method_call),
292 bcx.fcx.param_substs,
295 Callee { bcx: bcx, data: Fn(datum.val), ty: datum.ty }
297 traits::VtableClosure(vtable_closure) => {
298 // The substitutions should have no type parameters remaining
299 // after passing through fulfill_obligation
300 let trait_closure_kind = bcx.tcx().lang_items.fn_trait_kind(trait_id).unwrap();
301 let llfn = closure::trans_closure_method(bcx.ccx(),
302 vtable_closure.closure_def_id,
303 vtable_closure.substs,
308 ty: monomorphize_type(bcx, method_ty)
311 traits::VtableFnPointer(fn_ty) => {
312 let trait_closure_kind = bcx.tcx().lang_items.fn_trait_kind(trait_id).unwrap();
313 let llfn = trans_fn_pointer_shim(bcx.ccx(), trait_closure_kind, fn_ty);
317 ty: monomorphize_type(bcx, method_ty)
320 traits::VtableObject(ref data) => {
321 let idx = traits::get_vtable_index_of_object_method(bcx.tcx(), data, method_id);
322 if let Some(self_expr) = self_expr {
323 if let ty::TyBareFn(_, ref fty) = monomorphize_type(bcx, method_ty).sty {
324 let ty = bcx.tcx().mk_fn(None, opaque_method_ty(bcx.tcx(), fty));
325 return trans_trait_callee(bcx, ty, idx, self_expr, arg_cleanup_scope);
328 let datum = trans_object_shim(bcx.ccx(),
329 data.upcast_trait_ref.clone(),
332 Callee { bcx: bcx, data: Fn(datum.val), ty: datum.ty }
334 traits::VtableBuiltin(..) |
335 traits::VtableDefaultImpl(..) |
336 traits::VtableParam(..) => {
338 &format!("resolved vtable bad vtable {:?} in trans",
344 /// Creates a concatenated set of substitutions which includes those from the impl and those from
345 /// the method. This are some subtle complications here. Statically, we have a list of type
346 /// parameters like `[T0, T1, T2, M1, M2, M3]` where `Tn` are type parameters that appear on the
347 /// receiver. For example, if the receiver is a method parameter `A` with a bound like
348 /// `trait<B,C,D>` then `Tn` would be `[B,C,D]`.
350 /// The weird part is that the type `A` might now be bound to any other type, such as `foo<X>`.
351 /// In that case, the vector we want is: `[X, M1, M2, M3]`. Therefore, what we do now is to slice
352 /// off the method type parameters and append them to the type parameters from the type that the
353 /// receiver is mapped to.
354 fn combine_impl_and_methods_tps<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
355 node: ExprOrMethodCall,
356 rcvr_substs: subst::Substs<'tcx>)
357 -> subst::Substs<'tcx>
361 let node_substs = node_id_substs(ccx, node, bcx.fcx.param_substs);
363 debug!("rcvr_substs={:?}", rcvr_substs);
364 debug!("node_substs={:?}", node_substs);
366 // Break apart the type parameters from the node and type
367 // parameters from the receiver.
368 let node_method = node_substs.types.split().fns;
369 let subst::SeparateVecsPerParamSpace {
373 } = rcvr_substs.types.clone().split();
374 assert!(rcvr_method.is_empty());
376 regions: subst::ErasedRegions,
377 types: subst::VecPerParamSpace::new(rcvr_type, rcvr_self, node_method)
381 /// Create a method callee where the method is coming from a trait object (e.g., Box<Trait> type).
382 /// In this case, we must pull the fn pointer out of the vtable that is packaged up with the
383 /// object. Objects are represented as a pair, so we first evaluate the self expression and then
384 /// extract the self data and vtable out of the pair.
385 fn trans_trait_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
386 opaque_fn_ty: Ty<'tcx>,
388 self_expr: &hir::Expr,
389 arg_cleanup_scope: cleanup::ScopeId)
390 -> Callee<'blk, 'tcx> {
391 let _icx = push_ctxt("meth::trans_trait_callee");
394 // Translate self_datum and take ownership of the value by
395 // converting to an rvalue.
396 let self_datum = unpack_datum!(
397 bcx, expr::trans(bcx, self_expr));
399 let llval = if bcx.fcx.type_needs_drop(self_datum.ty) {
400 let self_datum = unpack_datum!(
401 bcx, self_datum.to_rvalue_datum(bcx, "trait_callee"));
403 // Convert to by-ref since `trans_trait_callee_from_llval` wants it
405 let self_datum = unpack_datum!(
406 bcx, self_datum.to_ref_datum(bcx));
408 // Arrange cleanup in case something should go wrong before the
409 // actual call occurs.
410 self_datum.add_clean(bcx.fcx, arg_cleanup_scope)
412 // We don't have to do anything about cleanups for &Trait and &mut Trait.
413 assert!(self_datum.kind.is_by_ref());
417 let llself = Load(bcx, expr::get_dataptr(bcx, llval));
418 let llvtable = Load(bcx, expr::get_meta(bcx, llval));
419 trans_trait_callee_from_llval(bcx, opaque_fn_ty, vtable_index, llself, llvtable)
422 /// Same as `trans_trait_callee()` above, except that it is given a by-ref pointer to the object
424 fn trans_trait_callee_from_llval<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
425 opaque_fn_ty: Ty<'tcx>,
429 -> Callee<'blk, 'tcx> {
430 let _icx = push_ctxt("meth::trans_trait_callee");
433 // Load the data pointer from the object.
434 debug!("trans_trait_callee_from_llval(callee_ty={}, vtable_index={}, llself={}, llvtable={})",
437 bcx.val_to_string(llself),
438 bcx.val_to_string(llvtable));
440 // Replace the self type (&Self or Box<Self>) with an opaque pointer.
441 let mptr = Load(bcx, GEPi(bcx, llvtable, &[vtable_index + VTABLE_OFFSET]));
442 let llcallee_ty = type_of_fn_from_ty(ccx, opaque_fn_ty);
446 data: TraitItem(MethodData {
447 llfn: PointerCast(bcx, mptr, llcallee_ty.ptr_to()),
448 llself: PointerCast(bcx, llself, Type::i8p(ccx)),
454 /// Generate a shim function that allows an object type like `SomeTrait` to
455 /// implement the type `SomeTrait`. Imagine a trait definition:
457 /// trait SomeTrait { fn get(&self) -> i32; ... }
459 /// And a generic bit of code:
461 /// fn foo<T:SomeTrait>(t: &T) {
462 /// let x = SomeTrait::get;
466 /// What is the value of `x` when `foo` is invoked with `T=SomeTrait`?
467 /// The answer is that it is a shim function generated by this routine:
469 /// fn shim(t: &SomeTrait) -> i32 {
470 /// // ... call t.get() virtually ...
473 /// In fact, all virtual calls can be thought of as normal trait calls
474 /// that go through this shim function.
475 fn trans_object_shim<'a, 'tcx>(
476 ccx: &'a CrateContext<'a, 'tcx>,
477 upcast_trait_ref: ty::PolyTraitRef<'tcx>,
480 -> Datum<'tcx, Rvalue>
482 let _icx = push_ctxt("trans_object_shim");
485 debug!("trans_object_shim(upcast_trait_ref={:?}, method_id={:?})",
489 // Upcast to the trait in question and extract out the substitutions.
490 let upcast_trait_ref = tcx.erase_late_bound_regions(&upcast_trait_ref);
491 let object_substs = upcast_trait_ref.substs.clone().erase_regions();
492 debug!("trans_object_shim: object_substs={:?}", object_substs);
494 // Lookup the type of this method as declared in the trait and apply substitutions.
495 let method_ty = match tcx.impl_or_trait_item(method_id) {
496 ty::MethodTraitItem(method) => method,
498 tcx.sess.bug("can't create a method shim for a non-method item")
501 let fty = monomorphize::apply_param_substs(tcx, &object_substs, &method_ty.fty);
502 let fty = tcx.mk_bare_fn(fty);
503 let method_ty = opaque_method_ty(tcx, fty);
504 debug!("trans_object_shim: fty={:?} method_ty={:?}", fty, method_ty);
507 let shim_fn_ty = tcx.mk_fn(None, fty);
508 let method_bare_fn_ty = tcx.mk_fn(None, method_ty);
509 let function_name = link::mangle_internal_name_by_type_and_seq(ccx, shim_fn_ty, "object_shim");
510 let llfn = declare::define_internal_rust_fn(ccx, &function_name, shim_fn_ty);
512 let sig = ccx.tcx().erase_late_bound_regions(&fty.sig);
513 let sig = infer::normalize_associated_type(ccx.tcx(), &sig);
515 let empty_substs = tcx.mk_substs(Substs::trans_empty());
516 let (block_arena, fcx): (TypedArena<_>, FunctionContext);
517 block_arena = TypedArena::new();
518 fcx = new_fn_ctxt(ccx,
526 let mut bcx = init_function(&fcx, false, sig.output);
528 let llargs = get_params(fcx.llfn);
530 let self_idx = fcx.arg_offset();
531 let llself = llargs[self_idx];
532 let llvtable = llargs[self_idx + 1];
534 debug!("trans_object_shim: llself={}, llvtable={}",
535 bcx.val_to_string(llself), bcx.val_to_string(llvtable));
537 assert!(!fcx.needs_ret_allocas);
540 fcx.llretslotptr.get().map(
541 |_| expr::SaveIn(fcx.get_ret_slot(bcx, sig.output, "ret_slot")));
543 debug!("trans_object_shim: method_offset_in_vtable={}",
546 bcx = trans_call_inner(bcx,
548 |bcx, _| trans_trait_callee_from_llval(bcx,
552 ArgVals(&llargs[(self_idx + 2)..]),
555 finish_fn(&fcx, bcx, sig.output, DebugLoc::None);
557 immediate_rvalue(llfn, shim_fn_ty)
560 /// Creates a returns a dynamic vtable for the given type and vtable origin.
561 /// This is used only for objects.
563 /// The `trait_ref` encodes the erased self type. Hence if we are
564 /// making an object `Foo<Trait>` from a value of type `Foo<T>`, then
565 /// `trait_ref` would map `T:Trait`.
566 pub fn get_vtable<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
567 trait_ref: ty::PolyTraitRef<'tcx>,
568 param_substs: &'tcx subst::Substs<'tcx>)
572 let _icx = push_ctxt("meth::get_vtable");
574 debug!("get_vtable(trait_ref={:?})", trait_ref);
577 match ccx.vtables().borrow().get(&trait_ref) {
578 Some(&val) => { return val }
582 // Not in the cache. Build it.
583 let methods = traits::supertraits(tcx, trait_ref.clone()).flat_map(|trait_ref| {
584 let vtable = fulfill_obligation(ccx, DUMMY_SP, trait_ref.clone());
586 // Should default trait error here?
587 traits::VtableDefaultImpl(_) |
588 traits::VtableBuiltin(_) => {
589 Vec::new().into_iter()
592 traits::VtableImplData {
596 emit_vtable_methods(ccx, id, substs, param_substs).into_iter()
598 traits::VtableClosure(
599 traits::VtableClosureData {
603 let trait_closure_kind = tcx.lang_items.fn_trait_kind(trait_ref.def_id()).unwrap();
604 let llfn = closure::trans_closure_method(ccx,
608 vec![llfn].into_iter()
610 traits::VtableFnPointer(bare_fn_ty) => {
611 let trait_closure_kind = tcx.lang_items.fn_trait_kind(trait_ref.def_id()).unwrap();
612 vec![trans_fn_pointer_shim(ccx, trait_closure_kind, bare_fn_ty)].into_iter()
614 traits::VtableObject(ref data) => {
615 // this would imply that the Self type being erased is
616 // an object type; this cannot happen because we
617 // cannot cast an unsized type into a trait object
619 &format!("cannot get vtable for an object type: {:?}",
622 traits::VtableParam(..) => {
624 &format!("resolved vtable for {:?} to bad vtable {:?} in trans",
631 let size_ty = sizing_type_of(ccx, trait_ref.self_ty());
632 let size = machine::llsize_of_alloc(ccx, size_ty);
633 let align = align_of(ccx, trait_ref.self_ty());
635 let components: Vec<_> = vec![
636 // Generate a destructor for the vtable.
637 glue::get_drop_glue(ccx, trait_ref.self_ty()),
640 ].into_iter().chain(methods).collect();
642 let vtable_const = C_struct(ccx, &components, false);
643 let align = machine::llalign_of_pref(ccx, val_ty(vtable_const));
644 let vtable = consts::addr_of(ccx, vtable_const, align, "vtable");
646 ccx.vtables().borrow_mut().insert(trait_ref, vtable);
650 fn emit_vtable_methods<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
652 substs: subst::Substs<'tcx>,
653 param_substs: &'tcx subst::Substs<'tcx>)
658 debug!("emit_vtable_methods(impl_id={:?}, substs={:?}, param_substs={:?})",
663 let trt_id = match tcx.impl_trait_ref(impl_id) {
664 Some(t_id) => t_id.def_id,
665 None => ccx.sess().bug("make_impl_vtable: don't know how to \
666 make a vtable for a type impl!")
669 tcx.populate_implementations_for_trait_if_necessary(trt_id);
671 let nullptr = C_null(Type::nil(ccx).ptr_to());
672 let trait_item_def_ids = tcx.trait_item_def_ids(trt_id);
676 // Filter out non-method items.
677 .filter_map(|item_def_id| {
679 ty::MethodTraitItemId(def_id) => Some(def_id),
684 // Now produce pointers for each remaining method. If the
685 // method could never be called from this object, just supply
687 .map(|trait_method_def_id| {
688 debug!("emit_vtable_methods: trait_method_def_id={:?}",
689 trait_method_def_id);
691 let trait_method_type = match tcx.impl_or_trait_item(trait_method_def_id) {
692 ty::MethodTraitItem(m) => m,
693 _ => ccx.sess().bug("should be a method, not other assoc item"),
695 let name = trait_method_type.name;
697 // Some methods cannot be called on an object; skip those.
698 if !traits::is_vtable_safe_method(tcx, trt_id, &trait_method_type) {
699 debug!("emit_vtable_methods: not vtable safe");
703 debug!("emit_vtable_methods: trait_method_type={:?}",
706 // The substitutions we have are on the impl, so we grab
707 // the method type from the impl to substitute into.
708 let mth = tcx.get_impl_method(impl_id, substs.clone(), name);
710 debug!("emit_vtable_methods: mth={:?}", mth);
712 // If this is a default method, it's possible that it
713 // relies on where clauses that do not hold for this
714 // particular set of type parameters. Note that this
715 // method could then never be called, so we do not want to
716 // try and trans it, in that case. Issue #23435.
718 let predicates = mth.method.predicates.predicates.subst(tcx, &mth.substs);
719 if !normalize_and_test_predicates(ccx, predicates.into_vec()) {
720 debug!("emit_vtable_methods: predicates do not hold");
725 trans_fn_ref_with_substs(ccx,
734 /// Replace the self type (&Self or Box<Self>) with an opaque pointer.
735 fn opaque_method_ty<'tcx>(tcx: &ty::ctxt<'tcx>, method_ty: &ty::BareFnTy<'tcx>)
736 -> &'tcx ty::BareFnTy<'tcx> {
737 let mut inputs = method_ty.sig.0.inputs.clone();
738 inputs[0] = tcx.mk_mut_ptr(tcx.mk_mach_int(ast::TyI8));
740 tcx.mk_bare_fn(ty::BareFnTy {
741 unsafety: method_ty.unsafety,
743 sig: ty::Binder(ty::FnSig {
745 output: method_ty.sig.0.output,
746 variadic: method_ty.sig.0.variadic,