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;
53 use syntax::visit::Visitor;
55 // Represents a (possibly monomorphized) top-level fn item or method
56 // item. Note that this is just the fn-ptr and is not a Rust closure
57 // value (which is a pair).
62 pub struct MethodData {
65 temp_cleanup: Option<ValueRef>,
66 self_mode: ty::SelfMode,
80 pub fn trans(bcx: @mut Block, expr: @ast::expr) -> Callee {
81 let _icx = push_ctxt("trans_callee");
82 debug!("callee::trans(expr=%s)", expr.repr(bcx.tcx()));
84 // pick out special kinds of expressions that can be called:
86 ast::expr_path(_) => {
87 return trans_def(bcx, bcx.def(expr.id), expr);
92 // any other expressions are closures:
93 return datum_callee(bcx, expr);
95 fn datum_callee(bcx: @mut Block, expr: @ast::expr) -> Callee {
96 let DatumBlock {bcx, datum} = expr::trans_to_datum(bcx, expr);
97 match ty::get(datum.ty).sty {
98 ty::ty_bare_fn(*) => {
99 let llval = datum.to_appropriate_llval(bcx);
100 return Callee {bcx: bcx, data: Fn(FnData {llfn: llval})};
102 ty::ty_closure(*) => {
103 return Callee {bcx: bcx, data: Closure(datum)};
106 bcx.tcx().sess.span_bug(
108 fmt!("Type of callee is neither bare-fn nor closure: %s",
109 bcx.ty_to_str(datum.ty)));
114 fn fn_callee(bcx: @mut Block, fd: FnData) -> Callee {
115 return Callee {bcx: bcx, data: Fn(fd)};
118 fn trans_def(bcx: @mut Block, def: ast::def, ref_expr: @ast::expr) -> Callee {
120 ast::def_fn(did, _) | ast::def_static_method(did, None, _) => {
121 fn_callee(bcx, trans_fn_ref(bcx, did, ref_expr.id))
123 ast::def_static_method(impl_did, Some(trait_did), _) => {
124 fn_callee(bcx, meth::trans_static_method_callee(bcx, impl_did,
128 ast::def_variant(tid, vid) => {
129 // nullary variants are not callable
130 assert!(ty::enum_variant_with_id(bcx.tcx(),
132 vid).args.len() > 0u);
133 fn_callee(bcx, trans_fn_ref(bcx, vid, ref_expr.id))
135 ast::def_struct(def_id) => {
136 fn_callee(bcx, trans_fn_ref(bcx, def_id, ref_expr.id))
141 ast::def_binding(*) |
143 ast::def_self(*) => {
144 datum_callee(bcx, ref_expr)
146 ast::def_mod(*) | ast::def_foreign_mod(*) | ast::def_trait(*) |
147 ast::def_ty(*) | ast::def_prim_ty(*) |
148 ast::def_use(*) | ast::def_typaram_binder(*) |
149 ast::def_region(*) | ast::def_label(*) | ast::def_ty_param(*) |
150 ast::def_self_ty(*) | ast::def_method(*) => {
151 bcx.tcx().sess.span_bug(
153 fmt!("Cannot translate def %? \
154 to a callable thing!", def));
160 pub fn trans_fn_ref_to_callee(bcx: @mut Block,
162 ref_id: ast::NodeId) -> Callee {
164 data: Fn(trans_fn_ref(bcx, def_id, ref_id))}
167 pub fn trans_fn_ref(bcx: @mut Block,
169 ref_id: ast::NodeId) -> FnData {
172 * Translates a reference (with id `ref_id`) to the fn/method
173 * with id `def_id` into a function pointer. This may require
174 * monomorphization or inlining. */
176 let _icx = push_ctxt("trans_fn_ref");
178 let type_params = node_id_type_params(bcx, ref_id);
179 let vtables = node_vtables(bcx, ref_id);
180 debug!("trans_fn_ref(def_id=%s, ref_id=%?, type_params=%s, vtables=%s)",
181 def_id.repr(bcx.tcx()), ref_id, type_params.repr(bcx.tcx()),
182 vtables.repr(bcx.tcx()));
183 trans_fn_ref_with_vtables(bcx, def_id, ref_id, type_params, vtables)
186 pub fn trans_fn_ref_with_vtables_to_callee(
190 type_params: &[ty::t],
191 vtables: Option<typeck::vtable_res>)
194 data: Fn(trans_fn_ref_with_vtables(bcx, def_id, ref_id,
195 type_params, vtables))}
198 fn resolve_default_method_vtables(bcx: @mut Block,
199 impl_id: ast::def_id,
202 impl_vtables: Option<typeck::vtable_res>)
203 -> (typeck::vtable_res, typeck::vtable_param_res) {
205 // Get the vtables that the impl implements the trait at
206 let impl_res = ty::lookup_impl_vtables(bcx.tcx(), impl_id);
208 // Build up a param_substs that we are going to resolve the
209 // trait_vtables under.
210 let param_substs = Some(@param_substs {
211 tys: substs.tps.clone(),
212 self_ty: substs.self_ty,
213 vtables: impl_vtables,
217 let trait_vtables_fixed = resolve_vtables_under_param_substs(
218 bcx.tcx(), param_substs, impl_res.trait_vtables);
220 // Now we pull any vtables for parameters on the actual method.
221 let num_method_vtables = method.generics.type_param_defs.len();
222 let method_vtables = match impl_vtables {
224 let num_impl_type_parameters =
225 vtables.len() - num_method_vtables;
226 vtables.tailn(num_impl_type_parameters).to_owned()
228 None => vec::from_elem(num_method_vtables, @~[])
231 let param_vtables = @(*trait_vtables_fixed + method_vtables);
233 let self_vtables = resolve_param_vtables_under_param_substs(
234 bcx.tcx(), param_substs, impl_res.self_vtables);
236 (param_vtables, self_vtables)
240 pub fn trans_fn_ref_with_vtables(
242 def_id: ast::def_id, // def id of fn
243 ref_id: ast::NodeId, // node id of use of fn; may be zero if N/A
244 type_params: &[ty::t], // values for fn's ty params
245 vtables: Option<typeck::vtable_res>) // vtables for the call
248 * Translates a reference to a fn/method item, monomorphizing and
249 * inlining as it goes.
253 * - `bcx`: the current block where the reference to the fn occurs
254 * - `def_id`: def id of the fn or method item being referenced
255 * - `ref_id`: node id of the reference to the fn/method, if applicable.
256 * This parameter may be zero; but, if so, the resulting value may not
257 * have the right type, so it must be cast before being used.
258 * - `type_params`: values for each of the fn/method's type parameters
259 * - `vtables`: values for each bound on each of the type parameters
262 let _icx = push_ctxt("trans_fn_ref_with_vtables");
266 debug!("trans_fn_ref_with_vtables(bcx=%s, def_id=%s, ref_id=%?, \
267 type_params=%s, vtables=%s)",
269 def_id.repr(bcx.tcx()),
271 type_params.repr(bcx.tcx()),
272 vtables.repr(bcx.tcx()));
274 assert!(type_params.iter().all(|t| !ty::type_needs_infer(*t)));
276 // Polytype of the function item (may have type params)
277 let fn_tpt = ty::lookup_item_type(tcx, def_id);
279 let substs = ty::substs { regions: ty::ErasedRegions,
281 tps: /*bad*/ type_params.to_owned() };
283 // We need to do a bunch of special handling for default methods.
284 // We need to modify the def_id and our substs in order to monomorphize
286 let (is_default, def_id, substs, self_vtables, vtables) =
287 match ty::provided_source(tcx, def_id) {
288 None => (false, def_id, substs, None, vtables),
290 // There are two relevant substitutions when compiling
291 // default methods. First, there is the substitution for
292 // the type parameters of the impl we are using and the
293 // method we are calling. This substitution is the substs
294 // argument we already have.
295 // In order to compile a default method, though, we need
296 // to consider another substitution: the substitution for
297 // the type parameters on trait; the impl we are using
298 // implements the trait at some particular type
299 // parameters, and we need to substitute for those first.
300 // So, what we need to do is find this substitution and
301 // compose it with the one we already have.
303 let impl_id = ty::method(tcx, def_id).container_id;
304 let method = ty::method(tcx, source_id);
305 let trait_ref = ty::impl_trait_ref(tcx, impl_id)
306 .expect("could not find trait_ref for impl with \
309 // Compute the first substitution
310 let first_subst = make_substs_for_receiver_types(
311 tcx, impl_id, trait_ref, method);
314 let new_substs = first_subst.subst(tcx, &substs);
317 let (param_vtables, self_vtables) =
318 resolve_default_method_vtables(bcx, impl_id,
319 method, &substs, vtables);
321 debug!("trans_fn_with_vtables - default method: \
322 substs = %s, trait_subst = %s, \
323 first_subst = %s, new_subst = %s, \
325 self_vtable = %s, param_vtables = %s",
326 substs.repr(tcx), trait_ref.substs.repr(tcx),
327 first_subst.repr(tcx), new_substs.repr(tcx),
329 self_vtables.repr(tcx), param_vtables.repr(tcx));
332 new_substs, Some(self_vtables), Some(param_vtables))
336 // Check whether this fn has an inlined copy and, if so, redirect
337 // def_id to the local id of the inlined copy.
339 if def_id.crate != ast::LOCAL_CRATE {
340 inline::maybe_instantiate_inline(ccx, def_id)
346 // We must monomorphise if the fn has type parameters, is a rust
347 // intrinsic, or is a default method. In particular, if we see an
348 // intrinsic that is inlined from a different crate, we want to reemit the
349 // intrinsic instead of trying to call it in the other crate.
350 let must_monomorphise;
351 if type_params.len() > 0 || is_default {
352 must_monomorphise = true;
353 } else if def_id.crate == ast::LOCAL_CRATE {
354 let map_node = session::expect(
356 ccx.tcx.items.find(&def_id.node),
357 || fmt!("local item should be in ast map"));
360 ast_map::node_foreign_item(_, abis, _, _) => {
361 must_monomorphise = abis.is_intrinsic()
364 must_monomorphise = false;
368 must_monomorphise = false;
371 // Create a monomorphic verison of generic functions
372 if must_monomorphise {
373 // Should be either intra-crate or inlined.
374 assert_eq!(def_id.crate, ast::LOCAL_CRATE);
376 let (val, must_cast) =
377 monomorphize::monomorphic_fn(ccx, def_id, &substs,
378 vtables, self_vtables,
381 if must_cast && ref_id != 0 {
382 // Monotype of the REFERENCE to the function (type params
384 let ref_ty = common::node_id_type(bcx, ref_id);
387 bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
389 return FnData {llfn: val};
392 // Find the actual function pointer.
394 if def_id.crate == ast::LOCAL_CRATE {
395 // Internal reference.
396 get_item_val(ccx, def_id.node)
398 // External reference.
399 trans_external_path(ccx, def_id, fn_tpt.ty)
403 // This is subtle and surprising, but sometimes we have to bitcast
404 // the resulting fn pointer. The reason has to do with external
405 // functions. If you have two crates that both bind the same C
406 // library, they may not use precisely the same types: for
407 // example, they will probably each declare their own structs,
408 // which are distinct types from LLVM's point of view (nominal
411 // Now, if those two crates are linked into an application, and
412 // they contain inlined code, you can wind up with a situation
413 // where both of those functions wind up being loaded into this
414 // application simultaneously. In that case, the same function
415 // (from LLVM's point of view) requires two types. But of course
416 // LLVM won't allow one function to have two types.
418 // What we currently do, therefore, is declare the function with
419 // one of the two types (whichever happens to come first) and then
420 // bitcast as needed when the function is referenced to make sure
421 // it has the type we expect.
423 // This can occur on either a crate-local or crate-external
424 // reference. It also occurs when testing libcore and in some
425 // other weird situations. Annoying.
426 let llty = type_of::type_of_fn_from_ty(ccx, fn_tpt.ty);
427 let llptrty = llty.ptr_to();
428 if val_ty(val) != llptrty {
429 val = BitCast(bcx, val, llptrty);
432 return FnData {llfn: val};
435 // ______________________________________________________________________
438 pub fn trans_call(in_cx: @mut Block,
445 let _icx = push_ctxt("trans_call");
446 trans_call_inner(in_cx,
449 node_id_type(in_cx, id),
456 pub fn trans_method_call(in_cx: @mut Block,
458 callee_id: ast::NodeId,
463 let _icx = push_ctxt("trans_method_call");
464 debug!("trans_method_call(call_ex=%s, rcvr=%s)",
465 call_ex.repr(in_cx.tcx()),
466 rcvr.repr(in_cx.tcx()));
470 node_id_type(in_cx, callee_id),
471 expr_ty(in_cx, call_ex),
473 match cx.ccx().maps.method_map.find_copy(&call_ex.id) {
475 debug!("origin for %s: %s",
476 call_ex.repr(in_cx.tcx()),
477 origin.repr(in_cx.tcx()));
479 meth::trans_method_callee(cx,
485 cx.tcx().sess.span_bug(call_ex.span, "method call expr wasn't in method map")
494 pub fn trans_lang_call(bcx: @mut Block,
497 dest: Option<expr::Dest>)
499 let fty = if did.crate == ast::LOCAL_CRATE {
500 ty::node_id_to_type(bcx.ccx().tcx, did.node)
502 csearch::get_type(bcx.ccx().tcx, did).ty
504 let rty = ty::ty_fn_ret(fty);
505 callee::trans_call_inner(bcx,
510 trans_fn_ref_with_vtables_to_callee(bcx,
521 pub fn trans_lang_call_with_type_params(bcx: @mut Block,
524 type_params: &[ty::t],
528 if did.crate == ast::LOCAL_CRATE {
529 fty = ty::node_id_to_type(bcx.tcx(), did.node);
531 fty = csearch::get_type(bcx.tcx(), did).ty;
534 let rty = ty::ty_fn_ret(fty);
535 return callee::trans_call_inner(
539 trans_fn_ref_with_vtables_to_callee(bcx, did, 0,
546 let substituted = ty::subst_tps(callee.bcx.tcx(),
550 let llfnty = type_of::type_of(callee.bcx.ccx(),
552 new_llval = PointerCast(callee.bcx, fn_data.llfn, llfnty);
556 Callee { bcx: callee.bcx, data: Fn(FnData { llfn: new_llval }) }
558 ArgVals(args), Some(dest), DontAutorefArg).bcx;
562 struct CalleeTranslationVisitor;
564 impl Visitor<@mut bool> for CalleeTranslationVisitor {
566 fn visit_item(&mut self, _:@ast::item, _:@mut bool) { }
568 fn visit_expr(&mut self, e:@ast::expr, cx:@mut bool) {
572 ast::expr_ret(_) => *cx = true,
573 _ => visit::walk_expr(self, e, cx),
580 pub fn body_contains_ret(body: &ast::Block) -> bool {
582 let mut v = CalleeTranslationVisitor;
583 visit::walk_block(&mut v, body, cx);
587 pub fn trans_call_inner(in_cx: @mut Block,
588 call_info: Option<NodeInfo>,
591 get_callee: &fn(@mut Block) -> Callee,
593 dest: Option<expr::Dest>,
594 autoref_arg: AutorefArg)
597 * This behemoth of a function translates function calls.
598 * Unfortunately, in order to generate more efficient LLVM
599 * output at -O0, it has quite a complex signature (refactoring
600 * this into two functions seems like a good idea).
602 * In particular, for lang items, it is invoked with a dest of
607 do base::with_scope_result(in_cx, call_info, "call") |cx| {
608 let callee = get_callee(cx);
609 let mut bcx = callee.bcx;
612 let (llfn, llenv) = unsafe {
615 (d.llfn, llvm::LLVMGetUndef(Type::opaque_box(ccx).ptr_to().to_ref()))
618 // Weird but true: we pass self in the *environment* slot!
622 // Closures are represented as (llfn, llclosure) pair:
623 // load the requisite values out.
624 let pair = d.to_ref_llval(bcx);
625 let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]);
626 let llfn = Load(bcx, llfn);
627 let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]);
628 let llenv = Load(bcx, llenv);
634 let abi = match ty::get(callee_ty).sty {
635 ty::ty_bare_fn(ref f) => f.abis,
642 // Generate a location to store the result. If the user does
643 // not care about the result, just make a stack slot.
644 let opt_llretslot = match dest {
646 assert!(!type_of::return_uses_outptr(in_cx.tcx(), ret_ty));
649 Some(expr::SaveIn(dst)) => Some(dst),
650 Some(expr::Ignore) => {
651 if !ty::type_is_voidish(ret_ty) {
652 Some(alloc_ty(bcx, ret_ty, "__llret"))
655 Some(llvm::LLVMGetUndef(Type::nil().ptr_to().to_ref()))
661 let mut llresult = unsafe {
662 llvm::LLVMGetUndef(Type::nil().ptr_to().to_ref())
665 // The code below invokes the function, using either the Rust
666 // conventions (if it is a rust fn) or the native conventions
667 // (otherwise). The important part is that, when all is sad
668 // and done, either the return value of the function will have been
669 // written in opt_llretslot (if it is Some) or `llresult` will be
670 // set appropriately (otherwise).
672 let mut llargs = ~[];
674 // Push the out-pointer if we use an out-pointer for this
675 // return type, otherwise push "undef".
676 if type_of::return_uses_outptr(in_cx.tcx(), ret_ty) {
677 llargs.push(opt_llretslot.unwrap());
680 // Push the environment.
683 // Push the arguments.
684 bcx = trans_args(bcx, args, callee_ty,
685 autoref_arg, &mut llargs);
687 // Now that the arguments have finished evaluating, we
688 // need to revoke the cleanup for the self argument
691 for &v in d.temp_cleanup.iter() {
692 revoke_clean(bcx, v);
698 // Invoke the actual rust fn and update bcx/llresult.
699 let (llret, b) = base::invoke(bcx, llfn, llargs);
703 // If the Rust convention for this type is return via
704 // the return value, copy it into llretslot.
705 match opt_llretslot {
707 if !type_of::return_uses_outptr(bcx.tcx(), ret_ty) &&
708 !ty::type_is_voidish(ret_ty)
710 Store(bcx, llret, llretslot);
716 // Lang items are the only case where dest is None, and
717 // they are always Rust fns.
718 assert!(dest.is_some());
720 let mut llargs = ~[];
721 bcx = trans_args(bcx, args, callee_ty,
722 autoref_arg, &mut llargs);
723 bcx = foreign::trans_native_call(bcx, callee_ty,
724 llfn, opt_llretslot.unwrap(), llargs);
727 // If the caller doesn't care about the result of this fn call,
728 // drop the temporary slot we made.
731 assert!(!type_of::return_uses_outptr(bcx.tcx(), ret_ty));
733 Some(expr::Ignore) => {
734 // drop the value if it is not being saved.
735 bcx = glue::drop_ty(bcx, opt_llretslot.unwrap(), ret_ty);
737 Some(expr::SaveIn(_)) => { }
740 if ty::type_is_bot(ret_ty) {
748 pub enum CallArgs<'self> {
749 ArgExprs(&'self [@ast::expr]),
750 ArgVals(&'self [ValueRef])
753 pub fn trans_args(cx: @mut Block,
756 autoref_arg: AutorefArg,
757 llargs: &mut ~[ValueRef]) -> @mut Block
759 let _icx = push_ctxt("trans_args");
760 let mut temp_cleanups = ~[];
761 let arg_tys = ty::ty_fn_args(fn_ty);
765 // First we figure out the caller's view of the types of the arguments.
766 // This will be needed if this is a generic call, because the callee has
767 // to cast her view of the arguments to the caller's view.
769 ArgExprs(arg_exprs) => {
770 for (i, arg_expr) in arg_exprs.iter().enumerate() {
771 let arg_val = unpack_result!(bcx, {
779 llargs.push(arg_val);
787 // now that all arguments have been successfully built, we can revoke any
788 // temporary cleanups, as they are only needed if argument construction
789 // should fail (for example, cleanup of copy mode args).
790 for c in temp_cleanups.iter() {
791 revoke_clean(bcx, *c)
797 pub enum AutorefArg {
802 // temp_cleanups: cleanups that should run only if failure occurs before the
804 pub fn trans_arg_expr(bcx: @mut Block,
805 formal_arg_ty: ty::t,
806 self_mode: ty::SelfMode,
807 arg_expr: @ast::expr,
808 temp_cleanups: &mut ~[ValueRef],
809 autoref_arg: AutorefArg) -> Result {
810 let _icx = push_ctxt("trans_arg_expr");
813 debug!("trans_arg_expr(formal_arg_ty=(%s), self_mode=%?, arg_expr=%s)",
814 formal_arg_ty.repr(bcx.tcx()),
816 arg_expr.repr(bcx.tcx()));
818 // translate the arg expr to a datum
819 let arg_datumblock = expr::trans_to_datum(bcx, arg_expr);
820 let arg_datum = arg_datumblock.datum;
821 let bcx = arg_datumblock.bcx;
823 debug!(" arg datum: %s", arg_datum.to_str(bcx.ccx()));
826 if ty::type_is_bot(arg_datum.ty) {
827 // For values of type _|_, we generate an
828 // "undef" value, as such a value should never
829 // be inspected. It's important for the value
830 // to have type lldestty (the callee's expected type).
831 let llformal_arg_ty = type_of::type_of(ccx, formal_arg_ty);
833 val = llvm::LLVMGetUndef(llformal_arg_ty.to_ref());
836 // FIXME(#3548) use the adjustments table
839 val = arg_datum.to_ref_llval(bcx);
842 let need_scratch = ty::type_needs_drop(bcx.tcx(), arg_datum.ty) ||
843 (bcx.expr_is_lval(arg_expr) &&
844 arg_datum.appropriate_mode(bcx.tcx()).is_by_ref());
846 let arg_datum = if need_scratch {
847 let scratch = scratch_datum(bcx, arg_datum.ty, "__self", false);
848 arg_datum.store_to_datum(bcx, INIT, scratch);
850 // Technically, ownership of val passes to the callee.
851 // However, we must cleanup should we fail before the
852 // callee is actually invoked.
853 scratch.add_clean(bcx);
854 temp_cleanups.push(scratch.val);
861 val = match self_mode {
863 debug!("by ref arg with type %s", bcx.ty_to_str(arg_datum.ty));
864 arg_datum.to_ref_llval(bcx)
867 debug!("by copy arg with type %s", bcx.ty_to_str(arg_datum.ty));
868 arg_datum.to_appropriate_llval(bcx)
874 if formal_arg_ty != arg_datum.ty {
875 // this could happen due to e.g. subtyping
876 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
877 debug!("casting actual type (%s) to match formal (%s)",
878 bcx.val_to_str(val), bcx.llty_str(llformal_arg_ty));
879 val = PointerCast(bcx, val, llformal_arg_ty);
883 debug!("--- trans_arg_expr passing %s", bcx.val_to_str(val));
884 return rslt(bcx, val);