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;
17 use middle::trans::base::*;
18 use middle::trans::build::*;
19 use middle::trans::callee::*;
20 use middle::trans::callee;
21 use middle::trans::cleanup;
22 use middle::trans::common::*;
23 use middle::trans::datum::*;
24 use middle::trans::expr::{SaveIn, Ignore};
25 use middle::trans::expr;
26 use middle::trans::glue;
27 use middle::trans::monomorphize;
28 use middle::trans::type_::Type;
29 use middle::trans::type_of::*;
32 use middle::typeck::MethodCall;
33 use util::common::indenter;
34 use util::ppaux::Repr;
36 use std::c_str::ToCStr;
38 use syntax::abi::Rust;
39 use syntax::parse::token;
40 use syntax::{ast, ast_map, visit};
41 use syntax::ast_util::PostExpansionMethod;
44 The main "translation" pass for methods. Generates code
45 for non-monomorphized methods only. Other methods will
46 be generated once they are invoked with specific type parameters,
47 see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`.
49 pub fn trans_impl(ccx: &CrateContext,
51 methods: &[Gc<ast::Method>],
52 generics: &ast::Generics,
54 let _icx = push_ctxt("meth::trans_impl");
57 debug!("trans_impl(name={}, id={:?})", name.repr(tcx), id);
59 // Both here and below with generic methods, be sure to recurse and look for
60 // items that we need to translate.
61 if !generics.ty_params.is_empty() {
62 let mut v = TransItemVisitor{ ccx: ccx };
63 for method in methods.iter() {
64 visit::walk_method_helper(&mut v, &**method, ());
68 for method in methods.iter() {
69 if method.pe_generics().ty_params.len() == 0u {
70 let llfn = get_item_val(ccx, method.id);
72 &*method.pe_fn_decl(),
75 ¶m_substs::empty(),
79 let mut v = TransItemVisitor{ ccx: ccx };
80 visit::walk_method_helper(&mut v, &**method, ());
85 pub fn trans_method_callee<'a>(
87 method_call: MethodCall,
88 self_expr: Option<&ast::Expr>,
89 arg_cleanup_scope: cleanup::ScopeId)
91 let _icx = push_ctxt("meth::trans_method_callee");
93 let (origin, method_ty) = match bcx.tcx().method_map
94 .borrow().find(&method_call) {
96 debug!("trans_method_callee({:?}, method={})",
97 method_call, method.repr(bcx.tcx()));
98 (method.origin, method.ty)
101 bcx.sess().span_bug(bcx.tcx().map.span(method_call.expr_id),
102 "method call expr wasn't in method map")
107 typeck::MethodStatic(did) => {
110 data: Fn(callee::trans_fn_ref(bcx, did, MethodCall(method_call)))
113 typeck::MethodParam(typeck::MethodParam {
119 ty::populate_implementations_for_trait_if_necessary(
123 let vtbl = find_vtable(bcx.tcx(), bcx.fcx.param_substs, p, b);
124 trans_monomorphized_callee(bcx, method_call,
128 typeck::MethodObject(ref mt) => {
129 let self_expr = match self_expr {
130 Some(self_expr) => self_expr,
132 bcx.sess().span_bug(bcx.tcx().map.span(method_call.expr_id),
133 "self expr wasn't provided for trait object \
134 callee (trying to call overloaded op?)")
137 trans_trait_callee(bcx,
138 monomorphize_type(bcx, method_ty),
146 pub fn trans_static_method_callee(bcx: &Block,
147 method_id: ast::DefId,
148 trait_id: ast::DefId,
149 expr_id: ast::NodeId)
151 let _icx = push_ctxt("meth::trans_static_method_callee");
154 debug!("trans_static_method_callee(method_id={:?}, trait_id={}, \
157 ty::item_path_str(bcx.tcx(), trait_id),
159 let _indenter = indenter();
161 ty::populate_implementations_for_trait_if_necessary(bcx.tcx(), trait_id);
163 let mname = if method_id.krate == ast::LOCAL_CRATE {
164 match bcx.tcx().map.get(method_id.node) {
165 ast_map::NodeTraitMethod(method) => {
166 let ident = match *method {
167 ast::Required(ref m) => m.ident,
168 ast::Provided(ref m) => m.pe_ident()
172 _ => fail!("callee is not a trait method")
175 csearch::get_item_path(bcx.tcx(), method_id).last().unwrap().name()
177 debug!("trans_static_method_callee: method_id={:?}, expr_id={:?}, \
178 name={}", method_id, expr_id, token::get_name(mname));
180 let vtable_key = MethodCall::expr(expr_id);
181 let vtbls = resolve_vtables_in_fn_ctxt(
183 ccx.tcx.vtable_map.borrow().get(&vtable_key));
185 match *vtbls.get_self().unwrap().get(0) {
186 typeck::vtable_static(impl_did, ref rcvr_substs, ref rcvr_origins) => {
187 assert!(rcvr_substs.types.all(|t| !ty::type_needs_infer(*t)));
189 let mth_id = method_with_name(ccx, impl_did, mname);
190 let (callee_substs, callee_origins) =
191 combine_impl_and_methods_tps(
192 bcx, ExprId(expr_id),
193 (*rcvr_substs).clone(), (*rcvr_origins).clone());
195 let llfn = trans_fn_ref_with_vtables(bcx, mth_id, ExprId(expr_id),
199 let callee_ty = node_id_type(bcx, expr_id);
200 let llty = type_of_fn_from_ty(ccx, callee_ty).ptr_to();
201 PointerCast(bcx, llfn, llty)
204 fail!("vtable_param left in monomorphized \
205 function's vtable substs");
210 fn method_with_name(ccx: &CrateContext,
212 name: ast::Name) -> ast::DefId {
213 match ccx.impl_method_cache.borrow().find_copy(&(impl_id, name)) {
218 let methods = ccx.tcx.impl_methods.borrow();
219 let methods = methods.find(&impl_id)
220 .expect("could not find impl while translating");
221 let meth_did = methods.iter().find(|&did| ty::method(&ccx.tcx, *did).ident.name == name)
222 .expect("could not find method while translating");
224 ccx.impl_method_cache.borrow_mut().insert((impl_id, name), *meth_did);
228 fn trans_monomorphized_callee<'a>(bcx: &'a Block<'a>,
229 method_call: MethodCall,
230 trait_id: ast::DefId,
232 vtbl: typeck::vtable_origin)
234 let _icx = push_ctxt("meth::trans_monomorphized_callee");
236 typeck::vtable_static(impl_did, rcvr_substs, rcvr_origins) => {
238 let mname = ty::trait_method(ccx.tcx(), trait_id, n_method).ident;
239 let mth_id = method_with_name(bcx.ccx(), impl_did, mname.name);
241 // create a concatenated set of substitutions which includes
242 // those from the impl and those from the method:
243 let (callee_substs, callee_origins) =
244 combine_impl_and_methods_tps(
245 bcx, MethodCall(method_call), rcvr_substs, rcvr_origins);
247 // translate the function
248 let llfn = trans_fn_ref_with_vtables(bcx,
250 MethodCall(method_call),
254 Callee { bcx: bcx, data: Fn(llfn) }
256 typeck::vtable_param(..) => {
258 "vtable_param left in monomorphized function's vtable substs");
260 typeck::vtable_error => {
262 "vtable_error left in monomorphized function's vtable substs");
267 fn combine_impl_and_methods_tps(bcx: &Block,
268 node: ExprOrMethodCall,
269 rcvr_substs: subst::Substs,
270 rcvr_origins: typeck::vtable_res)
271 -> (subst::Substs, typeck::vtable_res)
274 * Creates a concatenated set of substitutions which includes
275 * those from the impl and those from the method. This are
276 * some subtle complications here. Statically, we have a list
277 * of type parameters like `[T0, T1, T2, M1, M2, M3]` where
278 * `Tn` are type parameters that appear on the receiver. For
279 * example, if the receiver is a method parameter `A` with a
280 * bound like `trait<B,C,D>` then `Tn` would be `[B,C,D]`.
282 * The weird part is that the type `A` might now be bound to
283 * any other type, such as `foo<X>`. In that case, the vector
284 * we want is: `[X, M1, M2, M3]`. Therefore, what we do now is
285 * to slice off the method type parameters and append them to
286 * the type parameters from the type that the receiver is
292 let vtable_key = match node {
293 ExprId(id) => MethodCall::expr(id),
294 MethodCall(method_call) => method_call
296 let node_substs = node_id_substs(bcx, node);
297 let node_vtables = node_vtables(bcx, vtable_key);
299 debug!("rcvr_substs={:?}", rcvr_substs.repr(ccx.tcx()));
300 debug!("node_substs={:?}", node_substs.repr(ccx.tcx()));
302 // Break apart the type parameters from the node and type
303 // parameters from the receiver.
304 let (_, _, node_method) = node_substs.types.split();
305 let (rcvr_type, rcvr_self, rcvr_method) = rcvr_substs.types.clone().split();
306 assert!(rcvr_method.is_empty());
307 let ty_substs = subst::Substs {
308 regions: subst::ErasedRegions,
309 types: subst::VecPerParamSpace::new(rcvr_type, rcvr_self, node_method)
312 // Now do the same work for the vtables.
313 let (rcvr_type, rcvr_self, rcvr_method) = rcvr_origins.split();
314 let (_, _, node_method) = node_vtables.split();
315 assert!(rcvr_method.is_empty());
316 let vtables = subst::VecPerParamSpace::new(rcvr_type, rcvr_self, node_method);
321 fn trans_trait_callee<'a>(bcx: &'a Block<'a>,
324 self_expr: &ast::Expr,
325 arg_cleanup_scope: cleanup::ScopeId)
328 * Create a method callee where the method is coming from a trait
329 * object (e.g., Box<Trait> type). In this case, we must pull the fn
330 * pointer out of the vtable that is packaged up with the object.
331 * Objects are represented as a pair, so we first evaluate the self
332 * expression and then extract the self data and vtable out of the
336 let _icx = push_ctxt("meth::trans_trait_callee");
339 // Translate self_datum and take ownership of the value by
340 // converting to an rvalue.
341 let self_datum = unpack_datum!(
342 bcx, expr::trans(bcx, self_expr));
344 let llval = if ty::type_needs_drop(bcx.tcx(), self_datum.ty) {
345 let self_datum = unpack_datum!(
346 bcx, self_datum.to_rvalue_datum(bcx, "trait_callee"));
348 // Convert to by-ref since `trans_trait_callee_from_llval` wants it
350 let self_datum = unpack_datum!(
351 bcx, self_datum.to_ref_datum(bcx));
353 // Arrange cleanup in case something should go wrong before the
354 // actual call occurs.
355 self_datum.add_clean(bcx.fcx, arg_cleanup_scope)
357 // We don't have to do anything about cleanups for &Trait and &mut Trait.
358 assert!(self_datum.kind.is_by_ref());
362 trans_trait_callee_from_llval(bcx, method_ty, n_method, llval)
365 pub fn trans_trait_callee_from_llval<'a>(bcx: &'a Block<'a>,
371 * Same as `trans_trait_callee()` above, except that it is given
372 * a by-ref pointer to the object pair.
375 let _icx = push_ctxt("meth::trans_trait_callee");
378 // Load the data pointer from the object.
379 debug!("(translating trait callee) loading second index from pair");
380 let llboxptr = GEPi(bcx, llpair, [0u, abi::trt_field_box]);
381 let llbox = Load(bcx, llboxptr);
382 let llself = PointerCast(bcx, llbox, Type::i8p(ccx));
384 // Load the function from the vtable and cast it to the expected type.
385 debug!("(translating trait callee) loading method");
386 // Replace the self type (&Self or Box<Self>) with an opaque pointer.
387 let llcallee_ty = match ty::get(callee_ty).sty {
388 ty::ty_bare_fn(ref f) if f.abi == Rust => {
389 type_of_rust_fn(ccx, true, f.sig.inputs.slice_from(1), f.sig.output)
392 ccx.sess().bug("meth::trans_trait_callee given non-bare-rust-fn");
395 let llvtable = Load(bcx,
398 [0u, abi::trt_field_vtable]),
399 Type::vtable(ccx).ptr_to().ptr_to()));
400 let mptr = Load(bcx, GEPi(bcx, llvtable, [0u, n_method + 1]));
401 let mptr = PointerCast(bcx, mptr, llcallee_ty.ptr_to());
405 data: TraitMethod(MethodData {
412 /// Creates a returns a dynamic vtable for the given type and vtable origin.
413 /// This is used only for objects.
414 fn get_vtable(bcx: &Block,
416 origins: typeck::vtable_param_res)
419 debug!("get_vtable(self_ty={}, origins={})",
420 self_ty.repr(bcx.tcx()),
421 origins.repr(bcx.tcx()));
424 let _icx = push_ctxt("meth::get_vtable");
427 let hash_id = (self_ty, monomorphize::make_vtable_id(ccx, origins.get(0)));
428 match ccx.vtables.borrow().find(&hash_id) {
429 Some(&val) => { return val }
433 // Not in the cache. Actually build it.
434 let methods = origins.move_iter().flat_map(|origin| {
436 typeck::vtable_static(id, substs, sub_vtables) => {
437 emit_vtable_methods(bcx, id, substs, sub_vtables).move_iter()
439 _ => ccx.sess().bug("get_vtable: expected a static origin"),
443 // Generate a destructor for the vtable.
444 let drop_glue = glue::get_drop_glue(ccx, self_ty);
445 let vtable = make_vtable(ccx, drop_glue, methods);
447 ccx.vtables.borrow_mut().insert(hash_id, vtable);
451 /// Helper function to declare and initialize the vtable.
452 pub fn make_vtable<I: Iterator<ValueRef>>(ccx: &CrateContext,
456 let _icx = push_ctxt("meth::make_vtable");
458 let components: Vec<_> = Some(drop_glue).move_iter().chain(ptrs).collect();
461 let tbl = C_struct(ccx, components.as_slice(), false);
462 let sym = token::gensym("vtable");
463 let vt_gvar = format!("vtable{}", sym).with_c_str(|buf| {
464 llvm::LLVMAddGlobal(ccx.llmod, val_ty(tbl).to_ref(), buf)
466 llvm::LLVMSetInitializer(vt_gvar, tbl);
467 llvm::LLVMSetGlobalConstant(vt_gvar, llvm::True);
468 llvm::SetLinkage(vt_gvar, llvm::InternalLinkage);
473 fn emit_vtable_methods(bcx: &Block,
475 substs: subst::Substs,
476 vtables: typeck::vtable_res)
481 let trt_id = match ty::impl_trait_ref(tcx, impl_id) {
482 Some(t_id) => t_id.def_id,
483 None => ccx.sess().bug("make_impl_vtable: don't know how to \
484 make a vtable for a type impl!")
487 ty::populate_implementations_for_trait_if_necessary(bcx.tcx(), trt_id);
489 let trait_method_def_ids = ty::trait_method_def_ids(tcx, trt_id);
490 trait_method_def_ids.iter().map(|method_def_id| {
491 let ident = ty::method(tcx, *method_def_id).ident;
492 // The substitutions we have are on the impl, so we grab
493 // the method type from the impl to substitute into.
494 let m_id = method_with_name(ccx, impl_id, ident.name);
495 let m = ty::method(tcx, m_id);
496 debug!("(making impl vtable) emitting method {} at subst {}",
499 if m.generics.has_type_params(subst::FnSpace) ||
500 ty::type_has_self(ty::mk_bare_fn(tcx, m.fty.clone())) {
501 debug!("(making impl vtable) method has self or type params: {}",
502 token::get_ident(ident));
503 C_null(Type::nil(ccx).ptr_to())
505 let mut fn_ref = trans_fn_ref_with_vtables(bcx,
510 if m.explicit_self == ty::ByValueExplicitSelfCategory {
511 fn_ref = trans_unboxing_shim(bcx,
522 pub fn trans_trait_cast<'a>(bcx: &'a Block<'a>,
528 * Generates the code to convert from a pointer (`Box<T>`, `&T`, etc)
529 * into an object (`Box<Trait>`, `&Trait`, etc). This means creating a
530 * pair where the first word is the vtable and the second word is
535 let _icx = push_ctxt("meth::trans_cast");
537 let lldest = match dest {
539 return datum.clean(bcx, "trait_cast", id);
546 let llbox_ty = type_of(bcx.ccx(), datum.ty);
548 // Store the pointer into the first half of pair.
549 let mut llboxdest = GEPi(bcx, lldest, [0u, abi::trt_field_box]);
550 llboxdest = PointerCast(bcx, llboxdest, llbox_ty.ptr_to());
551 bcx = datum.store_to(bcx, llboxdest);
553 // Store the vtable into the second half of pair.
555 let vtable_map = ccx.tcx.vtable_map.borrow();
556 // This trait cast might be because of implicit coercion
557 let method_call = match ccx.tcx.adjustments.borrow().find(&id) {
558 Some(&ty::AutoObject(..)) => MethodCall::autoobject(id),
559 _ => MethodCall::expr(id)
561 let vres = vtable_map.get(&method_call).get_self().unwrap();
562 resolve_param_vtables_under_param_substs(ccx.tcx(), bcx.fcx.param_substs, vres)
564 let vtable = get_vtable(bcx, v_ty, origins);
565 let llvtabledest = GEPi(bcx, lldest, [0u, abi::trt_field_vtable]);
566 let llvtabledest = PointerCast(bcx, llvtabledest, val_ty(vtable).ptr_to());
567 Store(bcx, vtable, llvtabledest);