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.
12 * Handles translation of callees as well as other call-related
13 * things. Callees are a superset of normal rust values and sometimes
14 * have different representations. In particular, top-level fn items
15 * and methods are represented as just a fn ptr and not a full
23 use lib::llvm::ValueRef;
25 use metadata::csearch;
26 use middle::trans::base;
27 use middle::trans::base::*;
28 use middle::trans::build::*;
29 use middle::trans::callee;
30 use middle::trans::common;
31 use middle::trans::common::*;
32 use middle::trans::datum::*;
33 use middle::trans::datum::Datum;
34 use middle::trans::expr;
35 use middle::trans::glue;
36 use middle::trans::inline;
37 use middle::trans::meth;
38 use middle::trans::monomorphize;
39 use middle::trans::type_of;
40 use middle::trans::foreign;
42 use middle::subst::Subst;
44 use middle::typeck::coherence::make_substs_for_receiver_types;
45 use util::ppaux::Repr;
47 use middle::trans::type_::Type;
50 use syntax::abi::AbiSet;
54 // Represents a (possibly monomorphized) top-level fn item or method
55 // item. Note that this is just the fn-ptr and is not a Rust closure
56 // value (which is a pair).
61 pub struct MethodData {
64 temp_cleanup: Option<ValueRef>,
65 self_mode: ty::SelfMode,
79 pub fn trans(bcx: @mut Block, expr: @ast::expr) -> Callee {
80 let _icx = push_ctxt("trans_callee");
81 debug!("callee::trans(expr=%s)", expr.repr(bcx.tcx()));
83 // pick out special kinds of expressions that can be called:
85 ast::expr_path(_) => {
86 return trans_def(bcx, bcx.def(expr.id), expr);
91 // any other expressions are closures:
92 return datum_callee(bcx, expr);
94 fn datum_callee(bcx: @mut Block, expr: @ast::expr) -> Callee {
95 let DatumBlock {bcx, datum} = expr::trans_to_datum(bcx, expr);
96 match ty::get(datum.ty).sty {
97 ty::ty_bare_fn(*) => {
98 let llval = datum.to_appropriate_llval(bcx);
99 return Callee {bcx: bcx, data: Fn(FnData {llfn: llval})};
101 ty::ty_closure(*) => {
102 return Callee {bcx: bcx, data: Closure(datum)};
105 bcx.tcx().sess.span_bug(
107 fmt!("Type of callee is neither bare-fn nor closure: %s",
108 bcx.ty_to_str(datum.ty)));
113 fn fn_callee(bcx: @mut Block, fd: FnData) -> Callee {
114 return Callee {bcx: bcx, data: Fn(fd)};
117 fn trans_def(bcx: @mut Block, def: ast::def, ref_expr: @ast::expr) -> Callee {
119 ast::def_fn(did, _) | ast::def_static_method(did, None, _) => {
120 fn_callee(bcx, trans_fn_ref(bcx, did, ref_expr.id))
122 ast::def_static_method(impl_did, Some(trait_did), _) => {
123 fn_callee(bcx, meth::trans_static_method_callee(bcx, impl_did,
127 ast::def_variant(tid, vid) => {
128 // nullary variants are not callable
129 assert!(ty::enum_variant_with_id(bcx.tcx(),
131 vid).args.len() > 0u);
132 fn_callee(bcx, trans_fn_ref(bcx, vid, ref_expr.id))
134 ast::def_struct(def_id) => {
135 fn_callee(bcx, trans_fn_ref(bcx, def_id, ref_expr.id))
139 ast::def_binding(*) |
141 ast::def_self(*) => {
142 datum_callee(bcx, ref_expr)
144 ast::def_mod(*) | ast::def_foreign_mod(*) | ast::def_trait(*) |
145 ast::def_static(*) | ast::def_ty(*) | ast::def_prim_ty(*) |
146 ast::def_use(*) | ast::def_typaram_binder(*) |
147 ast::def_region(*) | ast::def_label(*) | ast::def_ty_param(*) |
148 ast::def_self_ty(*) | ast::def_method(*) => {
149 bcx.tcx().sess.span_bug(
151 fmt!("Cannot translate def %? \
152 to a callable thing!", def));
158 pub fn trans_fn_ref_to_callee(bcx: @mut Block,
160 ref_id: ast::NodeId) -> Callee {
162 data: Fn(trans_fn_ref(bcx, def_id, ref_id))}
165 pub fn trans_fn_ref(bcx: @mut Block,
167 ref_id: ast::NodeId) -> FnData {
170 * Translates a reference (with id `ref_id`) to the fn/method
171 * with id `def_id` into a function pointer. This may require
172 * monomorphization or inlining. */
174 let _icx = push_ctxt("trans_fn_ref");
176 let type_params = node_id_type_params(bcx, ref_id);
177 let vtables = node_vtables(bcx, ref_id);
178 debug!("trans_fn_ref(def_id=%s, ref_id=%?, type_params=%s, vtables=%s)",
179 def_id.repr(bcx.tcx()), ref_id, type_params.repr(bcx.tcx()),
180 vtables.repr(bcx.tcx()));
181 trans_fn_ref_with_vtables(bcx, def_id, ref_id, type_params, vtables)
184 pub fn trans_fn_ref_with_vtables_to_callee(
188 type_params: &[ty::t],
189 vtables: Option<typeck::vtable_res>)
192 data: Fn(trans_fn_ref_with_vtables(bcx, def_id, ref_id,
193 type_params, vtables))}
196 fn resolve_default_method_vtables(bcx: @mut Block,
197 impl_id: ast::def_id,
200 impl_vtables: Option<typeck::vtable_res>)
201 -> (typeck::vtable_res, typeck::vtable_param_res) {
203 // Get the vtables that the impl implements the trait at
204 let impl_res = ty::lookup_impl_vtables(bcx.tcx(), impl_id);
206 // Build up a param_substs that we are going to resolve the
207 // trait_vtables under.
208 let param_substs = Some(@param_substs {
209 tys: substs.tps.clone(),
210 self_ty: substs.self_ty,
211 vtables: impl_vtables,
215 let trait_vtables_fixed = resolve_vtables_under_param_substs(
216 bcx.tcx(), param_substs, impl_res.trait_vtables);
218 // Now we pull any vtables for parameters on the actual method.
219 let num_method_vtables = method.generics.type_param_defs.len();
220 let method_vtables = match impl_vtables {
222 let num_impl_type_parameters =
223 vtables.len() - num_method_vtables;
224 vtables.tailn(num_impl_type_parameters).to_owned()
226 None => vec::from_elem(num_method_vtables, @~[])
229 let param_vtables = @(*trait_vtables_fixed + method_vtables);
231 let self_vtables = resolve_param_vtables_under_param_substs(
232 bcx.tcx(), param_substs, impl_res.self_vtables);
234 (param_vtables, self_vtables)
238 pub fn trans_fn_ref_with_vtables(
240 def_id: ast::def_id, // def id of fn
241 ref_id: ast::NodeId, // node id of use of fn; may be zero if N/A
242 type_params: &[ty::t], // values for fn's ty params
243 vtables: Option<typeck::vtable_res>) // vtables for the call
246 * Translates a reference to a fn/method item, monomorphizing and
247 * inlining as it goes.
251 * - `bcx`: the current block where the reference to the fn occurs
252 * - `def_id`: def id of the fn or method item being referenced
253 * - `ref_id`: node id of the reference to the fn/method, if applicable.
254 * This parameter may be zero; but, if so, the resulting value may not
255 * have the right type, so it must be cast before being used.
256 * - `type_params`: values for each of the fn/method's type parameters
257 * - `vtables`: values for each bound on each of the type parameters
260 let _icx = push_ctxt("trans_fn_ref_with_vtables");
264 debug!("trans_fn_ref_with_vtables(bcx=%s, def_id=%s, ref_id=%?, \
265 type_params=%s, vtables=%s)",
267 def_id.repr(bcx.tcx()),
269 type_params.repr(bcx.tcx()),
270 vtables.repr(bcx.tcx()));
272 assert!(type_params.iter().all(|t| !ty::type_needs_infer(*t)));
274 // Polytype of the function item (may have type params)
275 let fn_tpt = ty::lookup_item_type(tcx, def_id);
277 let substs = ty::substs { regions: ty::ErasedRegions,
279 tps: /*bad*/ type_params.to_owned() };
281 // We need to do a bunch of special handling for default methods.
282 // We need to modify the def_id and our substs in order to monomorphize
284 let (is_default, def_id, substs, self_vtables, vtables) =
285 match ty::provided_source(tcx, def_id) {
286 None => (false, def_id, substs, None, vtables),
288 // There are two relevant substitutions when compiling
289 // default methods. First, there is the substitution for
290 // the type parameters of the impl we are using and the
291 // method we are calling. This substitution is the substs
292 // argument we already have.
293 // In order to compile a default method, though, we need
294 // to consider another substitution: the substitution for
295 // the type parameters on trait; the impl we are using
296 // implements the trait at some particular type
297 // parameters, and we need to substitute for those first.
298 // So, what we need to do is find this substitution and
299 // compose it with the one we already have.
301 let impl_id = ty::method(tcx, def_id).container_id;
302 let method = ty::method(tcx, source_id);
303 let trait_ref = ty::impl_trait_ref(tcx, impl_id)
304 .expect("could not find trait_ref for impl with \
307 // Compute the first substitution
308 let first_subst = make_substs_for_receiver_types(
309 tcx, impl_id, trait_ref, method);
312 let new_substs = first_subst.subst(tcx, &substs);
315 let (param_vtables, self_vtables) =
316 resolve_default_method_vtables(bcx, impl_id,
317 method, &substs, vtables);
319 debug!("trans_fn_with_vtables - default method: \
320 substs = %s, trait_subst = %s, \
321 first_subst = %s, new_subst = %s, \
323 self_vtable = %s, param_vtables = %s",
324 substs.repr(tcx), trait_ref.substs.repr(tcx),
325 first_subst.repr(tcx), new_substs.repr(tcx),
327 self_vtables.repr(tcx), param_vtables.repr(tcx));
330 new_substs, Some(self_vtables), Some(param_vtables))
334 // Check whether this fn has an inlined copy and, if so, redirect
335 // def_id to the local id of the inlined copy.
337 if def_id.crate != ast::LOCAL_CRATE {
338 inline::maybe_instantiate_inline(ccx, def_id)
344 // We must monomorphise if the fn has type parameters, is a rust
345 // intrinsic, or is a default method. In particular, if we see an
346 // intrinsic that is inlined from a different crate, we want to reemit the
347 // intrinsic instead of trying to call it in the other crate.
348 let must_monomorphise;
349 if type_params.len() > 0 || is_default {
350 must_monomorphise = true;
351 } else if def_id.crate == ast::LOCAL_CRATE {
352 let map_node = session::expect(
354 ccx.tcx.items.find(&def_id.node),
355 || fmt!("local item should be in ast map"));
358 ast_map::node_foreign_item(_, abis, _, _) => {
359 must_monomorphise = abis.is_intrinsic()
362 must_monomorphise = false;
366 must_monomorphise = false;
369 // Create a monomorphic verison of generic functions
370 if must_monomorphise {
371 // Should be either intra-crate or inlined.
372 assert_eq!(def_id.crate, ast::LOCAL_CRATE);
374 let (val, must_cast) =
375 monomorphize::monomorphic_fn(ccx, def_id, &substs,
376 vtables, self_vtables,
379 if must_cast && ref_id != 0 {
380 // Monotype of the REFERENCE to the function (type params
382 let ref_ty = common::node_id_type(bcx, ref_id);
385 bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
387 return FnData {llfn: val};
390 // Find the actual function pointer.
392 if def_id.crate == ast::LOCAL_CRATE {
393 // Internal reference.
394 get_item_val(ccx, def_id.node)
396 // External reference.
397 trans_external_path(ccx, def_id, fn_tpt.ty)
401 // This is subtle and surprising, but sometimes we have to bitcast
402 // the resulting fn pointer. The reason has to do with external
403 // functions. If you have two crates that both bind the same C
404 // library, they may not use precisely the same types: for
405 // example, they will probably each declare their own structs,
406 // which are distinct types from LLVM's point of view (nominal
409 // Now, if those two crates are linked into an application, and
410 // they contain inlined code, you can wind up with a situation
411 // where both of those functions wind up being loaded into this
412 // application simultaneously. In that case, the same function
413 // (from LLVM's point of view) requires two types. But of course
414 // LLVM won't allow one function to have two types.
416 // What we currently do, therefore, is declare the function with
417 // one of the two types (whichever happens to come first) and then
418 // bitcast as needed when the function is referenced to make sure
419 // it has the type we expect.
421 // This can occur on either a crate-local or crate-external
422 // reference. It also occurs when testing libcore and in some
423 // other weird situations. Annoying.
424 let llty = type_of::type_of_fn_from_ty(ccx, fn_tpt.ty);
425 let llptrty = llty.ptr_to();
426 if val_ty(val) != llptrty {
427 val = BitCast(bcx, val, llptrty);
430 return FnData {llfn: val};
433 // ______________________________________________________________________
436 pub fn trans_call(in_cx: @mut Block,
443 let _icx = push_ctxt("trans_call");
444 trans_call_inner(in_cx,
447 node_id_type(in_cx, id),
454 pub fn trans_method_call(in_cx: @mut Block,
456 callee_id: ast::NodeId,
461 let _icx = push_ctxt("trans_method_call");
462 debug!("trans_method_call(call_ex=%s, rcvr=%s)",
463 call_ex.repr(in_cx.tcx()),
464 rcvr.repr(in_cx.tcx()));
468 node_id_type(in_cx, callee_id),
469 expr_ty(in_cx, call_ex),
471 match cx.ccx().maps.method_map.find_copy(&call_ex.id) {
473 debug!("origin for %s: %s",
474 call_ex.repr(in_cx.tcx()),
475 origin.repr(in_cx.tcx()));
477 meth::trans_method_callee(cx,
483 cx.tcx().sess.span_bug(call_ex.span, "method call expr wasn't in method map")
492 pub fn trans_lang_call(bcx: @mut Block,
495 dest: Option<expr::Dest>)
497 let fty = if did.crate == ast::LOCAL_CRATE {
498 ty::node_id_to_type(bcx.ccx().tcx, did.node)
500 csearch::get_type(bcx.ccx().tcx, did).ty
502 let rty = ty::ty_fn_ret(fty);
503 callee::trans_call_inner(bcx,
508 trans_fn_ref_with_vtables_to_callee(bcx,
519 pub fn trans_lang_call_with_type_params(bcx: @mut Block,
522 type_params: &[ty::t],
526 if did.crate == ast::LOCAL_CRATE {
527 fty = ty::node_id_to_type(bcx.tcx(), did.node);
529 fty = csearch::get_type(bcx.tcx(), did).ty;
532 let rty = ty::ty_fn_ret(fty);
533 return callee::trans_call_inner(
537 trans_fn_ref_with_vtables_to_callee(bcx, did, 0,
544 let substituted = ty::subst_tps(callee.bcx.tcx(),
548 let llfnty = type_of::type_of(callee.bcx.ccx(),
550 new_llval = PointerCast(callee.bcx, fn_data.llfn, llfnty);
554 Callee { bcx: callee.bcx, data: Fn(FnData { llfn: new_llval }) }
556 ArgVals(args), Some(dest), DontAutorefArg).bcx;
559 pub fn body_contains_ret(body: &ast::Block) -> bool {
561 oldvisit::visit_block(body, (cx, oldvisit::mk_vt(@oldvisit::Visitor {
562 visit_item: |_i, (_cx, _v)| { },
563 visit_expr: |e: @ast::expr,
564 (cx, v): (@mut bool, oldvisit::vt<@mut bool>)| {
567 ast::expr_ret(_) => *cx = true,
568 _ => oldvisit::visit_expr(e, (cx, v)),
572 ..*oldvisit::default_visitor()
577 pub fn trans_call_inner(in_cx: @mut Block,
578 call_info: Option<NodeInfo>,
581 get_callee: &fn(@mut Block) -> Callee,
583 dest: Option<expr::Dest>,
584 autoref_arg: AutorefArg)
587 * This behemoth of a function translates function calls.
588 * Unfortunately, in order to generate more efficient LLVM
589 * output at -O0, it has quite a complex signature (refactoring
590 * this into two functions seems like a good idea).
592 * In particular, for lang items, it is invoked with a dest of
597 do base::with_scope_result(in_cx, call_info, "call") |cx| {
598 let callee = get_callee(cx);
599 let mut bcx = callee.bcx;
602 let (llfn, llenv) = unsafe {
605 (d.llfn, llvm::LLVMGetUndef(Type::opaque_box(ccx).ptr_to().to_ref()))
608 // Weird but true: we pass self in the *environment* slot!
612 // Closures are represented as (llfn, llclosure) pair:
613 // load the requisite values out.
614 let pair = d.to_ref_llval(bcx);
615 let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]);
616 let llfn = Load(bcx, llfn);
617 let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]);
618 let llenv = Load(bcx, llenv);
624 let abi = match ty::get(callee_ty).sty {
625 ty::ty_bare_fn(ref f) => f.abis,
632 // Generate a location to store the result. If the user does
633 // not care about the result, just make a stack slot.
634 let opt_llretslot = match dest {
636 assert!(!type_of::return_uses_outptr(in_cx.tcx(), ret_ty));
639 Some(expr::SaveIn(dst)) => Some(dst),
640 Some(expr::Ignore) => {
641 if !ty::type_is_voidish(ret_ty) {
642 Some(alloc_ty(bcx, ret_ty, "__llret"))
645 Some(llvm::LLVMGetUndef(Type::nil().ptr_to().to_ref()))
651 let mut llresult = unsafe {
652 llvm::LLVMGetUndef(Type::nil().ptr_to().to_ref())
655 // The code below invokes the function, using either the Rust
656 // conventions (if it is a rust fn) or the native conventions
657 // (otherwise). The important part is that, when all is sad
658 // and done, either the return value of the function will have been
659 // written in opt_llretslot (if it is Some) or `llresult` will be
660 // set appropriately (otherwise).
662 let mut llargs = ~[];
664 // Push the out-pointer if we use an out-pointer for this
665 // return type, otherwise push "undef".
666 if type_of::return_uses_outptr(in_cx.tcx(), ret_ty) {
667 llargs.push(opt_llretslot.unwrap());
670 // Push the environment.
673 // Push the arguments.
674 bcx = trans_args(bcx, args, callee_ty,
675 autoref_arg, &mut llargs);
677 // Now that the arguments have finished evaluating, we
678 // need to revoke the cleanup for the self argument
681 for &v in d.temp_cleanup.iter() {
682 revoke_clean(bcx, v);
688 // Invoke the actual rust fn and update bcx/llresult.
689 let (llret, b) = base::invoke(bcx, llfn, llargs);
693 // If the Rust convention for this type is return via
694 // the return value, copy it into llretslot.
695 match opt_llretslot {
697 if !type_of::return_uses_outptr(bcx.tcx(), ret_ty) &&
698 !ty::type_is_voidish(ret_ty)
700 Store(bcx, llret, llretslot);
706 // Lang items are the only case where dest is None, and
707 // they are always Rust fns.
708 assert!(dest.is_some());
710 let mut llargs = ~[];
711 bcx = trans_args(bcx, args, callee_ty,
712 autoref_arg, &mut llargs);
713 bcx = foreign::trans_native_call(bcx, callee_ty,
714 llfn, opt_llretslot.unwrap(), llargs);
717 // If the caller doesn't care about the result of this fn call,
718 // drop the temporary slot we made.
721 assert!(!type_of::return_uses_outptr(bcx.tcx(), ret_ty));
723 Some(expr::Ignore) => {
724 // drop the value if it is not being saved.
725 bcx = glue::drop_ty(bcx, opt_llretslot.unwrap(), ret_ty);
727 Some(expr::SaveIn(_)) => { }
730 if ty::type_is_bot(ret_ty) {
738 pub enum CallArgs<'self> {
739 ArgExprs(&'self [@ast::expr]),
740 ArgVals(&'self [ValueRef])
743 pub fn trans_args(cx: @mut Block,
746 autoref_arg: AutorefArg,
747 llargs: &mut ~[ValueRef]) -> @mut Block
749 let _icx = push_ctxt("trans_args");
750 let mut temp_cleanups = ~[];
751 let arg_tys = ty::ty_fn_args(fn_ty);
755 // First we figure out the caller's view of the types of the arguments.
756 // This will be needed if this is a generic call, because the callee has
757 // to cast her view of the arguments to the caller's view.
759 ArgExprs(arg_exprs) => {
760 for (i, arg_expr) in arg_exprs.iter().enumerate() {
761 let arg_val = unpack_result!(bcx, {
769 llargs.push(arg_val);
777 // now that all arguments have been successfully built, we can revoke any
778 // temporary cleanups, as they are only needed if argument construction
779 // should fail (for example, cleanup of copy mode args).
780 for c in temp_cleanups.iter() {
781 revoke_clean(bcx, *c)
787 pub enum AutorefArg {
792 // temp_cleanups: cleanups that should run only if failure occurs before the
794 pub fn trans_arg_expr(bcx: @mut Block,
795 formal_arg_ty: ty::t,
796 self_mode: ty::SelfMode,
797 arg_expr: @ast::expr,
798 temp_cleanups: &mut ~[ValueRef],
799 autoref_arg: AutorefArg) -> Result {
800 let _icx = push_ctxt("trans_arg_expr");
803 debug!("trans_arg_expr(formal_arg_ty=(%s), self_mode=%?, arg_expr=%s)",
804 formal_arg_ty.repr(bcx.tcx()),
806 arg_expr.repr(bcx.tcx()));
808 // translate the arg expr to a datum
809 let arg_datumblock = expr::trans_to_datum(bcx, arg_expr);
810 let arg_datum = arg_datumblock.datum;
811 let bcx = arg_datumblock.bcx;
813 debug!(" arg datum: %s", arg_datum.to_str(bcx.ccx()));
816 if ty::type_is_bot(arg_datum.ty) {
817 // For values of type _|_, we generate an
818 // "undef" value, as such a value should never
819 // be inspected. It's important for the value
820 // to have type lldestty (the callee's expected type).
821 let llformal_arg_ty = type_of::type_of(ccx, formal_arg_ty);
823 val = llvm::LLVMGetUndef(llformal_arg_ty.to_ref());
826 // FIXME(#3548) use the adjustments table
829 val = arg_datum.to_ref_llval(bcx);
832 let need_scratch = ty::type_needs_drop(bcx.tcx(), arg_datum.ty) ||
833 (bcx.expr_is_lval(arg_expr) &&
834 arg_datum.appropriate_mode(bcx.tcx()).is_by_ref());
836 let arg_datum = if need_scratch {
837 let scratch = scratch_datum(bcx, arg_datum.ty, "__self", false);
838 arg_datum.store_to_datum(bcx, INIT, scratch);
840 // Technically, ownership of val passes to the callee.
841 // However, we must cleanup should we fail before the
842 // callee is actually invoked.
843 scratch.add_clean(bcx);
844 temp_cleanups.push(scratch.val);
851 val = match self_mode {
853 debug!("by ref arg with type %s", bcx.ty_to_str(arg_datum.ty));
854 arg_datum.to_ref_llval(bcx)
857 debug!("by copy arg with type %s", bcx.ty_to_str(arg_datum.ty));
858 arg_datum.to_appropriate_llval(bcx)
864 if formal_arg_ty != arg_datum.ty {
865 // this could happen due to e.g. subtyping
866 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
867 debug!("casting actual type (%s) to match formal (%s)",
868 bcx.val_to_str(val), bcx.llty_str(llformal_arg_ty));
869 val = PointerCast(bcx, val, llformal_arg_ty);
873 debug!("--- trans_arg_expr passing %s", bcx.val_to_str(val));
874 return rslt(bcx, val);