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.
14 use lib::llvm::ValueRef;
16 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::common::*;
22 use middle::trans::datum::*;
23 use middle::trans::expr::{SaveIn, Ignore};
24 use middle::trans::expr;
25 use middle::trans::glue;
26 use middle::trans::monomorphize;
27 use middle::trans::type_of::*;
30 use util::common::indenter;
31 use util::ppaux::Repr;
33 use middle::trans::type_::Type;
35 use std::c_str::ToCStr;
37 use syntax::ast_map::{path, path_mod, path_name};
39 use syntax::{ast, ast_map};
42 The main "translation" pass for methods. Generates code
43 for non-monomorphized methods only. Other methods will
44 be generated once they are invoked with specific type parameters,
45 see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`.
47 pub fn trans_impl(ccx: @mut CrateContext,
50 methods: &[@ast::method],
51 generics: &ast::Generics,
53 let _icx = push_ctxt("impl::trans_impl");
56 debug!("trans_impl(path=%s, name=%s, id=%?)",
57 path.repr(tcx), name.repr(tcx), id);
59 if !generics.ty_params.is_empty() { return; }
60 let sub_path = vec::append_one(path, path_name(name));
61 for method in methods.iter() {
62 if method.generics.ty_params.len() == 0u {
63 let llfn = get_item_val(ccx, method.id);
64 let path = vec::append_one(sub_path.clone(),
65 path_name(method.ident));
76 /// Translates a (possibly monomorphized) method body.
79 /// * `path`: the path to the method
80 /// * `method`: the AST node for the method
81 /// * `param_substs`: if this is a generic method, the current values for
82 /// type parameters and so forth, else none
83 /// * `llfn`: the LLVM ValueRef for the method
84 /// * `impl_id`: the node ID of the impl this method is inside
86 /// XXX(pcwalton) Can we take `path` by reference?
87 pub fn trans_method(ccx: @mut CrateContext,
90 param_substs: Option<@param_substs>,
92 // figure out how self is being passed
93 let self_arg = match method.explicit_self.node {
98 // determine the (monomorphized) type that `self` maps to for
100 let self_ty = ty::node_id_to_type(ccx.tcx, method.self_id);
101 let self_ty = match param_substs {
103 Some(@param_substs {tys: ref tys, self_ty: ref self_sub, _}) => {
104 ty::subst_tps(ccx.tcx, *tys, *self_sub, self_ty)
107 debug!("calling trans_fn with self_ty %s",
108 self_ty.repr(ccx.tcx));
109 match method.explicit_self.node {
110 ast::sty_value => impl_self(self_ty, ty::ByRef),
111 _ => impl_self(self_ty, ty::ByCopy),
116 // generate the actual code
128 pub fn trans_self_arg(bcx: @mut Block,
130 temp_cleanups: &mut ~[ValueRef],
131 mentry: typeck::method_map_entry) -> Result {
132 let _icx = push_ctxt("impl::trans_self_arg");
134 // self is passed as an opaque box in the environment slot
135 let self_ty = ty::mk_opaque_box(bcx.tcx());
144 pub fn trans_method_callee(bcx: @mut Block,
145 callee_id: ast::NodeId,
147 mentry: typeck::method_map_entry)
149 let _icx = push_ctxt("impl::trans_method_callee");
151 debug!("trans_method_callee(callee_id=%?, this=%s, mentry=%s)",
153 bcx.expr_to_str(this),
154 mentry.repr(bcx.tcx()));
156 match mentry.origin {
157 typeck::method_static(did) => {
158 let callee_fn = callee::trans_fn_ref(bcx, did, callee_id);
159 let mut temp_cleanups = ~[];
160 let Result {bcx, val} = trans_self_arg(bcx, this, &mut temp_cleanups, mentry);
163 data: Method(MethodData {
164 llfn: callee_fn.llfn,
166 temp_cleanup: temp_cleanups.head_opt().map_move(|v| *v),
167 self_mode: mentry.self_mode,
171 typeck::method_param(typeck::method_param {
177 match bcx.fcx.param_substs {
179 let vtbl = find_vtable(bcx.tcx(), substs,
181 trans_monomorphized_callee(bcx, callee_id, this, mentry,
184 // how to get rid of this?
185 None => fail!("trans_method_callee: missing param_substs")
189 typeck::method_trait(_, off) => {
190 trans_trait_callee(bcx,
198 pub fn trans_static_method_callee(bcx: @mut Block,
199 method_id: ast::def_id,
200 trait_id: ast::def_id,
201 callee_id: ast::NodeId)
203 let _icx = push_ctxt("impl::trans_static_method_callee");
206 debug!("trans_static_method_callee(method_id=%?, trait_id=%s, \
209 ty::item_path_str(bcx.tcx(), trait_id),
211 let _indenter = indenter();
213 // When we translate a static fn defined in a trait like:
215 // trait<T1...Tn> Trait {
216 // fn foo<M1...Mn>(...) {...}
219 // this winds up being translated as something like:
221 // fn foo<T1...Tn,self: Trait<T1...Tn>,M1...Mn>(...) {...}
223 // So when we see a call to this function foo, we have to figure
224 // out which impl the `Trait<T1...Tn>` bound on the type `self` was
226 let bound_index = ty::lookup_trait_def(bcx.tcx(), trait_id).
227 generics.type_param_defs.len();
229 let mname = if method_id.crate == ast::LOCAL_CRATE {
230 match bcx.tcx().items.get_copy(&method_id.node) {
231 ast_map::node_trait_method(trait_method, _, _) => {
232 ast_util::trait_method_to_ty_method(trait_method).ident
234 _ => fail!("callee is not a trait method")
237 let path = csearch::get_item_path(bcx.tcx(), method_id);
238 match path[path.len()-1] {
239 path_name(s) => { s }
240 path_mod(_) => { fail!("path doesn't have a name?") }
243 debug!("trans_static_method_callee: method_id=%?, callee_id=%?, \
244 name=%s", method_id, callee_id, ccx.sess.str_of(mname));
246 let vtbls = resolve_vtables_in_fn_ctxt(
247 bcx.fcx, ccx.maps.vtable_map.get_copy(&callee_id));
249 match vtbls[bound_index][0] {
250 typeck::vtable_static(impl_did, ref rcvr_substs, rcvr_origins) => {
251 assert!(rcvr_substs.iter().all(|t| !ty::type_needs_infer(*t)));
253 let mth_id = method_with_name(bcx.ccx(), impl_did, mname);
254 let (callee_substs, callee_origins) =
255 combine_impl_and_methods_tps(
256 bcx, mth_id, callee_id,
257 *rcvr_substs, rcvr_origins);
259 let FnData {llfn: lval} =
260 trans_fn_ref_with_vtables(bcx,
264 Some(callee_origins));
266 let callee_ty = node_id_type(bcx, callee_id);
267 let llty = type_of_fn_from_ty(ccx, callee_ty).ptr_to();
268 FnData {llfn: PointerCast(bcx, lval, llty)}
271 fail!("vtable_param left in monomorphized \
272 function's vtable substs");
277 pub fn method_with_name(ccx: &mut CrateContext,
278 impl_id: ast::def_id,
279 name: ast::ident) -> ast::def_id {
280 let meth_id_opt = ccx.impl_method_cache.find_copy(&(impl_id, name));
286 let imp = ccx.tcx.impls.find(&impl_id)
287 .expect("could not find impl while translating");
288 let meth = imp.methods.iter().find(|m| m.ident == name)
289 .expect("could not find method while translating");
291 ccx.impl_method_cache.insert((impl_id, name), meth.def_id);
295 pub fn trans_monomorphized_callee(bcx: @mut Block,
296 callee_id: ast::NodeId,
298 mentry: typeck::method_map_entry,
299 trait_id: ast::def_id,
301 vtbl: typeck::vtable_origin)
303 let _icx = push_ctxt("impl::trans_monomorphized_callee");
305 typeck::vtable_static(impl_did, ref rcvr_substs, rcvr_origins) => {
307 let mname = ty::trait_method(ccx.tcx, trait_id, n_method).ident;
308 let mth_id = method_with_name(bcx.ccx(), impl_did, mname);
310 // obtain the `self` value:
311 let mut temp_cleanups = ~[];
312 let Result {bcx, val: llself_val} =
313 trans_self_arg(bcx, base, &mut temp_cleanups, mentry);
315 // create a concatenated set of substitutions which includes
316 // those from the impl and those from the method:
317 let (callee_substs, callee_origins) =
318 combine_impl_and_methods_tps(
319 bcx, mth_id, callee_id,
320 *rcvr_substs, rcvr_origins);
322 // translate the function
323 let callee = trans_fn_ref_with_vtables(bcx,
327 Some(callee_origins));
329 // create a llvalue that represents the fn ptr
330 let fn_ty = node_id_type(bcx, callee_id);
331 let llfn_ty = type_of_fn_from_ty(ccx, fn_ty).ptr_to();
332 let llfn_val = PointerCast(bcx, callee.llfn, llfn_ty);
334 // combine the self environment with the rest
337 data: Method(MethodData {
340 temp_cleanup: temp_cleanups.head_opt().map_move(|v| *v),
341 self_mode: mentry.self_mode,
345 typeck::vtable_param(*) => {
346 fail!("vtable_param left in monomorphized function's vtable substs");
352 pub fn combine_impl_and_methods_tps(bcx: @mut Block,
353 mth_did: ast::def_id,
354 callee_id: ast::NodeId,
355 rcvr_substs: &[ty::t],
356 rcvr_origins: typeck::vtable_res)
357 -> (~[ty::t], typeck::vtable_res) {
360 * Creates a concatenated set of substitutions which includes
361 * those from the impl and those from the method. This are
362 * some subtle complications here. Statically, we have a list
363 * of type parameters like `[T0, T1, T2, M1, M2, M3]` where
364 * `Tn` are type parameters that appear on the receiver. For
365 * example, if the receiver is a method parameter `A` with a
366 * bound like `trait<B,C,D>` then `Tn` would be `[B,C,D]`.
368 * The weird part is that the type `A` might now be bound to
369 * any other type, such as `foo<X>`. In that case, the vector
370 * we want is: `[X, M1, M2, M3]`. Therefore, what we do now is
371 * to slice off the method type parameters and append them to
372 * the type parameters from the type that the receiver is
376 let method = ty::method(ccx.tcx, mth_did);
377 let n_m_tps = method.generics.type_param_defs.len();
378 let node_substs = node_id_type_params(bcx, callee_id);
379 debug!("rcvr_substs=%?", rcvr_substs.repr(ccx.tcx));
381 = vec::append(rcvr_substs.to_owned(),
382 node_substs.tailn(node_substs.len() - n_m_tps));
383 debug!("n_m_tps=%?", n_m_tps);
384 debug!("node_substs=%?", node_substs.repr(ccx.tcx));
385 debug!("ty_substs=%?", ty_substs.repr(ccx.tcx));
388 // Now, do the same work for the vtables. The vtables might not
389 // exist, in which case we need to make them.
390 let r_m_origins = match node_vtables(bcx, callee_id) {
392 None => @vec::from_elem(node_substs.len(), @~[])
395 = @vec::append(rcvr_origins.to_owned(),
396 r_m_origins.tailn(r_m_origins.len() - n_m_tps));
398 return (ty_substs, vtables);
402 pub fn trans_trait_callee(bcx: @mut Block,
403 callee_id: ast::NodeId,
405 self_expr: @ast::expr)
408 * Create a method callee where the method is coming from a trait
409 * object (e.g., @Trait type). In this case, we must pull the fn
410 * pointer out of the vtable that is packaged up with the object.
411 * Objects are represented as a pair, so we first evaluate the self
412 * expression and then extract the self data and vtable out of the
416 let _icx = push_ctxt("impl::trans_trait_callee");
419 let self_ty = expr_ty_adjusted(bcx, self_expr);
420 let self_scratch = scratch_datum(bcx, self_ty, "__trait_callee", false);
421 bcx = expr::trans_into(bcx, self_expr, expr::SaveIn(self_scratch.val));
423 // Arrange a temporary cleanup for the object in case something
424 // should go wrong before the method is actually *invoked*.
425 self_scratch.add_clean(bcx);
427 let callee_ty = node_id_type(bcx, callee_id);
428 trans_trait_callee_from_llval(bcx,
432 Some(self_scratch.val))
435 pub fn trans_trait_callee_from_llval(bcx: @mut Block,
439 temp_cleanup: Option<ValueRef>)
442 * Same as `trans_trait_callee()` above, except that it is given
443 * a by-ref pointer to the object pair.
446 let _icx = push_ctxt("impl::trans_trait_callee");
449 // Load the data pointer from the object.
450 debug!("(translating trait callee) loading second index from pair");
451 let llboxptr = GEPi(bcx, llpair, [0u, abi::trt_field_box]);
452 let llbox = Load(bcx, llboxptr);
453 let llself = PointerCast(bcx, llbox, Type::opaque_box(ccx).ptr_to());
455 // Load the function from the vtable and cast it to the expected type.
456 debug!("(translating trait callee) loading method");
457 let llcallee_ty = type_of_fn_from_ty(ccx, callee_ty);
458 let llvtable = Load(bcx,
461 [0u, abi::trt_field_vtable]),
462 Type::vtable().ptr_to().ptr_to()));
463 let mptr = Load(bcx, GEPi(bcx, llvtable, [0u, n_method + 1]));
464 let mptr = PointerCast(bcx, mptr, llcallee_ty.ptr_to());
468 data: Method(MethodData {
471 temp_cleanup: temp_cleanup,
473 // We know that the func declaration is &self, ~self,
474 // or @self, and such functions are always by-copy
475 // (right now, at least).
476 self_mode: ty::ByCopy,
481 pub fn vtable_id(ccx: @mut CrateContext,
482 origin: &typeck::vtable_origin)
485 &typeck::vtable_static(impl_id, ref substs, sub_vtables) => {
486 let psubsts = param_substs {
487 tys: (*substs).clone(),
488 vtables: Some(sub_vtables),
493 monomorphize::make_mono_id(
500 // can't this be checked at the callee?
501 _ => fail!("vtable_id")
505 /// Creates a returns a dynamic vtable for the given type and vtable origin.
506 /// This is used only for objects.
507 pub fn get_vtable(bcx: @mut Block,
509 origin: typeck::vtable_origin)
511 let hash_id = vtable_id(bcx.ccx(), &origin);
512 match bcx.ccx().vtables.find(&hash_id) {
516 typeck::vtable_static(id, substs, sub_vtables) => {
517 make_impl_vtable(bcx, id, self_ty, substs, sub_vtables)
519 _ => fail!("get_vtable: expected a static origin"),
525 /// Helper function to declare and initialize the vtable.
526 pub fn make_vtable(ccx: &mut CrateContext,
527 tydesc: &tydesc_info,
531 let _icx = push_ctxt("impl::make_vtable");
533 let mut components = ~[ tydesc.tydesc ];
534 for &ptr in ptrs.iter() {
538 let tbl = C_struct(components);
539 let vtable = ccx.sess.str_of(gensym_name("vtable"));
540 let vt_gvar = do vtable.to_c_str().with_ref |buf| {
541 llvm::LLVMAddGlobal(ccx.llmod, val_ty(tbl).to_ref(), buf)
543 llvm::LLVMSetInitializer(vt_gvar, tbl);
544 llvm::LLVMSetGlobalConstant(vt_gvar, lib::llvm::True);
545 lib::llvm::SetLinkage(vt_gvar, lib::llvm::InternalLinkage);
550 /// Generates a dynamic vtable for objects.
551 pub fn make_impl_vtable(bcx: @mut Block,
552 impl_id: ast::def_id,
555 vtables: typeck::vtable_res)
558 let _icx = push_ctxt("impl::make_impl_vtable");
561 let trt_id = match ty::impl_trait_ref(tcx, impl_id) {
562 Some(t_id) => t_id.def_id,
563 None => ccx.sess.bug("make_impl_vtable: don't know how to \
564 make a vtable for a type impl!")
567 let trait_method_def_ids = ty::trait_method_def_ids(tcx, trt_id);
568 let methods = do trait_method_def_ids.map |method_def_id| {
569 let im = ty::method(tcx, *method_def_id);
570 let fty = ty::subst_tps(tcx,
573 ty::mk_bare_fn(tcx, im.fty.clone()));
574 if im.generics.has_type_params() || ty::type_has_self(fty) {
575 debug!("(making impl vtable) method has self or type params: %s",
576 tcx.sess.str_of(im.ident));
577 C_null(Type::nil().ptr_to())
579 debug!("(making impl vtable) adding method to vtable: %s",
580 tcx.sess.str_of(im.ident));
581 let m_id = method_with_name(ccx, impl_id, im.ident);
583 trans_fn_ref_with_vtables(bcx, m_id, 0,
584 substs, Some(vtables)).llfn
588 // Generate a type descriptor for the vtable.
589 let tydesc = get_tydesc(ccx, self_ty);
590 glue::lazily_emit_all_tydesc_glue(ccx, tydesc);
592 make_vtable(ccx, tydesc, methods)
595 pub fn trans_trait_cast(bcx: @mut Block,
599 _store: ty::TraitStore)
602 let _icx = push_ctxt("impl::trans_cast");
604 let lldest = match dest {
606 return expr::trans_into(bcx, val, Ignore);
612 let v_ty = expr_ty(bcx, val);
614 let mut llboxdest = GEPi(bcx, lldest, [0u, abi::trt_field_box]);
615 // Just store the pointer into the pair. (Region/borrowed
616 // and boxed trait objects are represented as pairs, and
617 // have no type descriptor field.)
618 llboxdest = PointerCast(bcx,
620 type_of(bcx.ccx(), v_ty).ptr_to());
621 bcx = expr::trans_into(bcx, val, SaveIn(llboxdest));
623 // Store the vtable into the pair or triple.
624 let orig = ccx.maps.vtable_map.get(&id)[0][0].clone();
625 let orig = resolve_vtable_in_fn_ctxt(bcx.fcx, &orig);
626 let vtable = get_vtable(bcx, v_ty, orig);
627 Store(bcx, vtable, PointerCast(bcx,
628 GEPi(bcx, lldest, [0u, abi::trt_field_vtable]),
629 val_ty(vtable).ptr_to()));