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
19 use arena::TypedArena;
23 use llvm::{ValueRef, get_param};
25 use metadata::csearch;
28 use middle::subst::{Subst};
29 use middle::trans::adt;
30 use middle::trans::base;
31 use middle::trans::base::*;
32 use middle::trans::build::*;
33 use middle::trans::callee;
34 use middle::trans::cleanup;
35 use middle::trans::cleanup::CleanupMethods;
36 use middle::trans::closure;
37 use middle::trans::common;
38 use middle::trans::common::*;
39 use middle::trans::datum::*;
40 use middle::trans::expr;
41 use middle::trans::glue;
42 use middle::trans::inline;
43 use middle::trans::foreign;
44 use middle::trans::intrinsic;
45 use middle::trans::meth;
46 use middle::trans::monomorphize;
47 use middle::trans::type_::Type;
48 use middle::trans::type_of;
50 use middle::typeck::coherence::make_substs_for_receiver_types;
51 use middle::typeck::MethodCall;
52 use util::ppaux::Repr;
53 use util::ppaux::ty_to_string;
55 use syntax::abi as synabi;
60 pub struct MethodData {
66 Closure(Datum<Lvalue>),
68 // Constructor for enum variant/tuple-like-struct
70 NamedTupleConstructor(subst::Substs, ty::Disr),
72 // Represents a (possibly monomorphized) top-level fn item or method
73 // item. Note that this is just the fn-ptr and is not a Rust closure
74 // value (which is a pair).
75 Fn(/* llfn */ ValueRef),
77 Intrinsic(ast::NodeId, subst::Substs),
82 pub struct Callee<'blk, 'tcx: 'blk> {
83 pub bcx: Block<'blk, 'tcx>,
87 fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
88 -> Callee<'blk, 'tcx> {
89 let _icx = push_ctxt("trans_callee");
90 debug!("callee::trans(expr={})", expr.repr(bcx.tcx()));
92 // pick out special kinds of expressions that can be called:
95 return trans_def(bcx, bcx.def(expr.id), expr);
100 // any other expressions are closures:
101 return datum_callee(bcx, expr);
103 fn datum_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
104 -> Callee<'blk, 'tcx> {
105 let DatumBlock {bcx: mut bcx, datum} = expr::trans(bcx, expr);
106 match ty::get(datum.ty).sty {
107 ty::ty_bare_fn(..) => {
108 let llval = datum.to_llscalarish(bcx);
114 ty::ty_closure(..) => {
115 let datum = unpack_datum!(
116 bcx, datum.to_lvalue_datum(bcx, "callee", expr.id));
119 data: Closure(datum),
123 bcx.tcx().sess.span_bug(
125 format!("type of callee is neither bare-fn nor closure: \
127 bcx.ty_to_string(datum.ty)).as_slice());
132 fn fn_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, llfn: ValueRef)
133 -> Callee<'blk, 'tcx> {
140 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, def: def::Def, ref_expr: &ast::Expr)
141 -> Callee<'blk, 'tcx> {
142 debug!("trans_def(def={}, ref_expr={})", def.repr(bcx.tcx()), ref_expr.repr(bcx.tcx()));
143 let expr_ty = node_id_type(bcx, ref_expr.id);
145 def::DefFn(did, _) if {
146 let maybe_def_id = inline::get_local_instance(bcx.ccx(), did);
147 let maybe_ast_node = maybe_def_id.and_then(|def_id| bcx.tcx().map
149 match maybe_ast_node {
150 Some(ast_map::NodeStructCtor(_)) => true,
154 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
157 data: NamedTupleConstructor(substs, 0)
160 def::DefFn(did, _) if match ty::get(expr_ty).sty {
161 ty::ty_bare_fn(ref f) => f.abi == synabi::RustIntrinsic,
164 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
165 let def_id = inline::maybe_instantiate_inline(bcx.ccx(), did);
166 Callee { bcx: bcx, data: Intrinsic(def_id.node, substs) }
169 def::DefStaticMethod(did, def::FromImpl(_), _) => {
170 fn_callee(bcx, trans_fn_ref(bcx, did, ExprId(ref_expr.id)))
172 def::DefStaticMethod(impl_did,
173 def::FromTrait(trait_did),
175 fn_callee(bcx, meth::trans_static_method_callee(bcx, impl_did,
179 def::DefVariant(tid, vid, _) => {
180 let vinfo = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
181 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
183 // Nullary variants are not callable
184 assert!(vinfo.args.len() > 0u);
188 data: NamedTupleConstructor(substs, vinfo.disr_val)
191 def::DefStruct(_) => {
192 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
195 data: NamedTupleConstructor(substs, 0)
200 def::DefUpvar(..) => {
201 datum_callee(bcx, ref_expr)
203 def::DefMod(..) | def::DefForeignMod(..) | def::DefTrait(..) |
204 def::DefTy(..) | def::DefPrimTy(..) | def::DefAssociatedTy(..) |
205 def::DefUse(..) | def::DefTyParamBinder(..) |
206 def::DefRegion(..) | def::DefLabel(..) | def::DefTyParam(..) |
207 def::DefSelfTy(..) | def::DefMethod(..) => {
208 bcx.tcx().sess.span_bug(
210 format!("cannot translate def {:?} \
211 to a callable thing!", def).as_slice());
217 pub fn trans_fn_ref(bcx: Block, def_id: ast::DefId, node: ExprOrMethodCall) -> ValueRef {
219 * Translates a reference (with id `ref_id`) to the fn/method
220 * with id `def_id` into a function pointer. This may require
221 * monomorphization or inlining.
224 let _icx = push_ctxt("trans_fn_ref");
226 let substs = node_id_substs(bcx, node);
227 debug!("trans_fn_ref(def_id={}, node={:?}, substs={})",
228 def_id.repr(bcx.tcx()),
230 substs.repr(bcx.tcx()));
231 trans_fn_ref_with_substs(bcx, def_id, node, substs)
234 fn trans_fn_ref_with_substs_to_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
237 substs: subst::Substs)
238 -> Callee<'blk, 'tcx> {
241 data: Fn(trans_fn_ref_with_substs(bcx,
248 /// Translates the adapter that deconstructs a `Box<Trait>` object into
249 /// `Trait` so that a by-value self method can be called.
250 pub fn trans_unboxing_shim(bcx: Block,
251 llshimmedfn: ValueRef,
253 method_id: ast::DefId,
254 substs: subst::Substs)
256 let _icx = push_ctxt("trans_unboxing_shim");
260 // Transform the self type to `Box<self_type>`.
261 let self_type = *fty.sig.inputs.get(0);
262 let boxed_self_type = ty::mk_uniq(tcx, self_type);
263 let boxed_function_type = ty::FnSig {
264 binder_id: fty.sig.binder_id,
265 inputs: fty.sig.inputs.iter().enumerate().map(|(i, typ)| {
272 output: fty.sig.output,
275 let boxed_function_type = ty::BareFnTy {
276 fn_style: fty.fn_style,
278 sig: boxed_function_type,
280 let boxed_function_type =
281 ty::mk_bare_fn(tcx, boxed_function_type).subst(tcx, &substs);
283 ty::mk_bare_fn(tcx, (*fty).clone()).subst(tcx, &substs);
285 let function_name = ty::with_path(tcx, method_id, |path| {
286 link::mangle_internal_name_by_path_and_seq(path, "unboxing_shim")
288 let llfn = decl_internal_rust_fn(ccx,
290 function_name.as_slice());
292 let block_arena = TypedArena::new();
293 let empty_param_substs = param_substs::empty();
294 let return_type = ty::ty_fn_ret(boxed_function_type);
295 let fcx = new_fn_ctxt(ccx,
303 let mut bcx = init_function(&fcx, false, return_type);
305 // Create the substituted versions of the self type.
306 let arg_scope = fcx.push_custom_cleanup_scope();
307 let arg_scope_id = cleanup::CustomScope(arg_scope);
308 let boxed_arg_types = ty::ty_fn_args(boxed_function_type);
309 let boxed_self_type = *boxed_arg_types.get(0);
310 let arg_types = ty::ty_fn_args(function_type);
311 let self_type = *arg_types.get(0);
312 let boxed_self_kind = arg_kind(&fcx, boxed_self_type);
314 // Create a datum for self.
315 let llboxedself = get_param(fcx.llfn, fcx.arg_pos(0) as u32);
316 let llboxedself = Datum::new(llboxedself,
321 llboxedself.to_lvalue_datum_in_scope(bcx,
325 // This `Load` is needed because lvalue data are always by-ref.
326 let llboxedself = Load(bcx, boxed_self.val);
328 let llself = if type_is_immediate(ccx, self_type) {
329 let llboxedself = Load(bcx, llboxedself);
330 immediate_rvalue(llboxedself, self_type)
332 let llself = rvalue_scratch_datum(bcx, self_type, "self");
333 memcpy_ty(bcx, llself.val, llboxedself, self_type);
337 // Make sure we don't free the box twice!
338 boxed_self.kind.post_store(bcx, boxed_self.val, boxed_self_type);
340 // Schedule a cleanup to free the box.
341 fcx.schedule_free_value(arg_scope_id,
343 cleanup::HeapExchange,
346 // Now call the function.
347 let mut llshimmedargs = vec!(llself.val);
348 for i in range(1, arg_types.len()) {
349 llshimmedargs.push(get_param(fcx.llfn, fcx.arg_pos(i) as u32));
351 assert!(!fcx.needs_ret_allocas);
352 let dest = match fcx.llretslotptr.get() {
353 Some(_) => Some(expr::SaveIn(fcx.get_ret_slot(bcx, return_type, "ret_slot"))),
356 bcx = trans_call_inner(bcx,
362 data: Fn(llshimmedfn),
365 ArgVals(llshimmedargs.as_slice()),
368 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
369 finish_fn(&fcx, bcx, return_type);
374 pub fn trans_fn_ref_with_substs(
376 def_id: ast::DefId, // def id of fn
377 node: ExprOrMethodCall, // node id of use of fn; may be zero if N/A
378 substs: subst::Substs) // vtables for the call
382 * Translates a reference to a fn/method item, monomorphizing and
383 * inlining as it goes.
387 * - `bcx`: the current block where the reference to the fn occurs
388 * - `def_id`: def id of the fn or method item being referenced
389 * - `node`: node id of the reference to the fn/method, if applicable.
390 * This parameter may be zero; but, if so, the resulting value may not
391 * have the right type, so it must be cast before being used.
392 * - `substs`: values for each of the fn/method's parameters
395 let _icx = push_ctxt("trans_fn_ref_with_substs");
399 debug!("trans_fn_ref_with_substs(bcx={}, def_id={}, node={:?}, \
406 assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
408 // Load the info for the appropriate trait if necessary.
409 match ty::trait_of_item(tcx, def_id) {
412 ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
416 // We need to do a bunch of special handling for default methods.
417 // We need to modify the def_id and our substs in order to monomorphize
419 let (is_default, def_id, substs) = match ty::provided_source(tcx, def_id) {
420 None => (false, def_id, substs),
422 // There are two relevant substitutions when compiling
423 // default methods. First, there is the substitution for
424 // the type parameters of the impl we are using and the
425 // method we are calling. This substitution is the substs
426 // argument we already have.
427 // In order to compile a default method, though, we need
428 // to consider another substitution: the substitution for
429 // the type parameters on trait; the impl we are using
430 // implements the trait at some particular type
431 // parameters, and we need to substitute for those first.
432 // So, what we need to do is find this substitution and
433 // compose it with the one we already have.
435 let impl_id = ty::impl_or_trait_item(tcx, def_id).container()
437 let impl_or_trait_item = ty::impl_or_trait_item(tcx, source_id);
438 match impl_or_trait_item {
439 ty::MethodTraitItem(method) => {
440 let trait_ref = ty::impl_trait_ref(tcx, impl_id)
441 .expect("could not find trait_ref for impl with \
444 // Compute the first substitution
445 let first_subst = make_substs_for_receiver_types(
446 tcx, &*trait_ref, &*method);
449 let new_substs = first_subst.subst(tcx, &substs);
451 debug!("trans_fn_with_vtables - default method: \
452 substs = {}, trait_subst = {}, \
453 first_subst = {}, new_subst = {}",
454 substs.repr(tcx), trait_ref.substs.repr(tcx),
455 first_subst.repr(tcx), new_substs.repr(tcx));
457 (true, source_id, new_substs)
459 ty::TypeTraitItem(_) => {
460 bcx.tcx().sess.bug("trans_fn_ref_with_vtables() tried \
461 to translate an associated type?!")
467 // If this is an unboxed closure, redirect to it.
468 match closure::get_or_create_declaration_if_unboxed_closure(ccx, def_id) {
470 Some(llfn) => return llfn,
473 // Check whether this fn has an inlined copy and, if so, redirect
474 // def_id to the local id of the inlined copy.
475 let def_id = inline::maybe_instantiate_inline(ccx, def_id);
477 // We must monomorphise if the fn has type parameters, is a default method,
478 // or is a named tuple constructor.
479 let must_monomorphise = if !substs.types.is_empty() || is_default {
481 } else if def_id.krate == ast::LOCAL_CRATE {
482 let map_node = session::expect(
484 tcx.map.find(def_id.node),
485 || "local item should be in ast map".to_string());
488 ast_map::NodeVariant(v) => match v.node.kind {
489 ast::TupleVariantKind(ref args) => args.len() > 0,
492 ast_map::NodeStructCtor(_) => true,
499 // Create a monomorphic version of generic functions
500 if must_monomorphise {
501 // Should be either intra-crate or inlined.
502 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
504 let opt_ref_id = match node {
505 ExprId(id) => if id != 0 { Some(id) } else { None },
506 MethodCall(_) => None,
509 let (val, must_cast) =
510 monomorphize::monomorphic_fn(ccx, def_id, &substs, opt_ref_id);
512 if must_cast && node != ExprId(0) {
513 // Monotype of the REFERENCE to the function (type params
515 let ref_ty = match node {
516 ExprId(id) => node_id_type(bcx, id),
517 MethodCall(method_call) => {
518 let t = bcx.tcx().method_map.borrow().get(&method_call).ty;
519 monomorphize_type(bcx, t)
524 bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
529 // Polytype of the function item (may have type params)
530 let fn_tpt = ty::lookup_item_type(tcx, def_id);
532 // Find the actual function pointer.
534 if def_id.krate == ast::LOCAL_CRATE {
535 // Internal reference.
536 get_item_val(ccx, def_id.node)
538 // External reference.
539 trans_external_path(ccx, def_id, fn_tpt.ty)
543 // This is subtle and surprising, but sometimes we have to bitcast
544 // the resulting fn pointer. The reason has to do with external
545 // functions. If you have two crates that both bind the same C
546 // library, they may not use precisely the same types: for
547 // example, they will probably each declare their own structs,
548 // which are distinct types from LLVM's point of view (nominal
551 // Now, if those two crates are linked into an application, and
552 // they contain inlined code, you can wind up with a situation
553 // where both of those functions wind up being loaded into this
554 // application simultaneously. In that case, the same function
555 // (from LLVM's point of view) requires two types. But of course
556 // LLVM won't allow one function to have two types.
558 // What we currently do, therefore, is declare the function with
559 // one of the two types (whichever happens to come first) and then
560 // bitcast as needed when the function is referenced to make sure
561 // it has the type we expect.
563 // This can occur on either a crate-local or crate-external
564 // reference. It also occurs when testing libcore and in some
565 // other weird situations. Annoying.
566 let llty = type_of::type_of_fn_from_ty(ccx, fn_tpt.ty);
567 let llptrty = llty.ptr_to();
568 if val_ty(val) != llptrty {
569 debug!("trans_fn_ref_with_vtables(): casting pointer!");
570 val = BitCast(bcx, val, llptrty);
572 debug!("trans_fn_ref_with_vtables(): not casting pointer!");
578 // ______________________________________________________________________
581 pub fn trans_call<'blk, 'tcx>(in_cx: Block<'blk, 'tcx>,
586 -> Block<'blk, 'tcx> {
587 let _icx = push_ctxt("trans_call");
588 trans_call_inner(in_cx,
589 Some(common::expr_info(call_ex)),
591 |cx, _| trans(cx, f),
596 pub fn trans_method_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
601 -> Block<'blk, 'tcx> {
602 let _icx = push_ctxt("trans_method_call");
603 debug!("trans_method_call(call_ex={})", call_ex.repr(bcx.tcx()));
604 let method_call = MethodCall::expr(call_ex.id);
605 let method_ty = bcx.tcx().method_map.borrow().get(&method_call).ty;
608 Some(common::expr_info(call_ex)),
609 monomorphize_type(bcx, method_ty),
610 |cx, arg_cleanup_scope| {
611 meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
617 pub fn trans_lang_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
620 dest: Option<expr::Dest>)
621 -> Result<'blk, 'tcx> {
622 let fty = if did.krate == ast::LOCAL_CRATE {
623 ty::node_id_to_type(bcx.tcx(), did.node)
625 csearch::get_type(bcx.tcx(), did).ty
627 callee::trans_call_inner(bcx,
631 trans_fn_ref_with_substs_to_callee(bcx,
634 subst::Substs::empty())
640 pub fn trans_call_inner<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
641 call_info: Option<NodeInfo>,
643 get_callee: |bcx: Block<'blk, 'tcx>,
644 arg_cleanup_scope: cleanup::ScopeId|
645 -> Callee<'blk, 'tcx>,
647 dest: Option<expr::Dest>)
648 -> Result<'blk, 'tcx> {
650 * This behemoth of a function translates function calls.
651 * Unfortunately, in order to generate more efficient LLVM
652 * output at -O0, it has quite a complex signature (refactoring
653 * this into two functions seems like a good idea).
655 * In particular, for lang items, it is invoked with a dest of
656 * None, and in that case the return value contains the result of
657 * the fn. The lang item must not return a structural type or else
658 * all heck breaks loose.
660 * For non-lang items, `dest` is always Some, and hence the result
661 * is written into memory somewhere. Nonetheless we return the
662 * actual return value of the function.
665 // Introduce a temporary cleanup scope that will contain cleanups
666 // for the arguments while they are being evaluated. The purpose
667 // this cleanup is to ensure that, should a failure occur while
668 // evaluating argument N, the values for arguments 0...N-1 are all
669 // cleaned up. If no failure occurs, the values are handed off to
670 // the callee, and hence none of the cleanups in this temporary
671 // scope will ever execute.
674 let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
676 let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
677 let mut bcx = callee.bcx;
679 let (abi, ret_ty) = match ty::get(callee_ty).sty {
680 ty::ty_bare_fn(ref f) => (f.abi, f.sig.output),
681 ty::ty_closure(ref f) => (f.abi, f.sig.output),
682 _ => fail!("expected bare rust fn or closure in trans_call_inner")
685 let (llfn, llenv, llself) = match callee.data {
690 (d.llfn, None, Some(d.llself))
693 // Closures are represented as (llfn, llclosure) pair:
694 // load the requisite values out.
695 let pair = d.to_llref();
696 let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]);
697 let llfn = Load(bcx, llfn);
698 let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]);
699 let llenv = Load(bcx, llenv);
700 (llfn, Some(llenv), None)
702 Intrinsic(node, substs) => {
703 assert!(abi == synabi::RustIntrinsic);
704 assert!(dest.is_some());
706 let call_info = call_info.expect("no call info for intrinsic call?");
707 return intrinsic::trans_intrinsic_call(bcx, node, callee_ty,
708 arg_cleanup_scope, args,
709 dest.unwrap(), substs,
712 NamedTupleConstructor(substs, disr) => {
713 assert!(dest.is_some());
714 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
716 let ctor_ty = callee_ty.subst(bcx.tcx(), &substs);
717 return base::trans_named_tuple_constructor(bcx, ctor_ty, disr,
718 args, dest.unwrap());
722 // Intrinsics should not become actual functions.
723 // We trans them in place in `trans_intrinsic_call`
724 assert!(abi != synabi::RustIntrinsic);
726 let is_rust_fn = abi == synabi::Rust || abi == synabi::RustCall;
728 // Generate a location to store the result. If the user does
729 // not care about the result, just make a stack slot.
730 let opt_llretslot = match dest {
732 assert!(!type_of::return_uses_outptr(ccx, ret_ty));
735 Some(expr::SaveIn(dst)) => Some(dst),
736 Some(expr::Ignore) if !is_rust_fn ||
737 type_of::return_uses_outptr(ccx, ret_ty) ||
738 ty::type_needs_drop(bcx.tcx(), ret_ty) => {
739 if !type_is_zero_size(ccx, ret_ty) {
740 Some(alloc_ty(bcx, ret_ty, "__llret"))
742 let llty = type_of::type_of(ccx, ret_ty);
743 Some(C_undef(llty.ptr_to()))
746 Some(expr::Ignore) => None
749 let mut llresult = unsafe {
750 llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
753 // The code below invokes the function, using either the Rust
754 // conventions (if it is a rust fn) or the native conventions
755 // (otherwise). The important part is that, when all is said
756 // and done, either the return value of the function will have been
757 // written in opt_llretslot (if it is Some) or `llresult` will be
758 // set appropriately (otherwise).
760 let mut llargs = Vec::new();
762 // Push the out-pointer if we use an out-pointer for this
763 // return type, otherwise push "undef".
764 if type_of::return_uses_outptr(ccx, ret_ty) {
765 llargs.push(opt_llretslot.unwrap());
768 // Push the environment (or a trait object's self).
769 match (llenv, llself) {
770 (Some(llenv), None) => {
773 (None, Some(llself)) => llargs.push(llself),
777 // Push the arguments.
778 bcx = trans_args(bcx,
782 cleanup::CustomScope(arg_cleanup_scope),
786 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
788 // Invoke the actual rust fn and update bcx/llresult.
789 let (llret, b) = base::invoke(bcx,
798 // If the Rust convention for this type is return via
799 // the return value, copy it into llretslot.
800 match opt_llretslot {
802 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
803 !type_is_zero_size(bcx.ccx(), ret_ty)
805 store_ty(bcx, llret, llretslot, ret_ty)
811 // Lang items are the only case where dest is None, and
812 // they are always Rust fns.
813 assert!(dest.is_some());
815 let mut llargs = Vec::new();
816 let arg_tys = match args {
817 ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, &**x)).collect(),
818 _ => fail!("expected arg exprs.")
820 bcx = trans_args(bcx,
824 cleanup::CustomScope(arg_cleanup_scope),
827 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
828 bcx = foreign::trans_native_call(bcx, callee_ty,
829 llfn, opt_llretslot.unwrap(),
830 llargs.as_slice(), arg_tys);
833 // If the caller doesn't care about the result of this fn call,
834 // drop the temporary slot we made.
835 match (dest, opt_llretslot) {
836 (Some(expr::Ignore), Some(llretslot)) => {
837 // drop the value if it is not being saved.
838 bcx = glue::drop_ty(bcx, llretslot, ret_ty);
839 call_lifetime_end(bcx, llretslot);
844 if ty::type_is_bot(ret_ty) {
848 Result::new(bcx, llresult)
851 pub enum CallArgs<'a> {
852 // Supply value of arguments as a list of expressions that must be
853 // translated. This is used in the common case of `foo(bar, qux)`.
854 ArgExprs(&'a [P<ast::Expr>]),
856 // Supply value of arguments as a list of LLVM value refs; frequently
857 // used with lang items and so forth, when the argument is an internal
859 ArgVals(&'a [ValueRef]),
861 // For overloaded operators: `(lhs, Vec(rhs, rhs_id))`. `lhs`
862 // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
863 // the right-hand-side arguments (if any).
864 ArgOverloadedOp(Datum<Expr>, Vec<(Datum<Expr>, ast::NodeId)>),
866 // Supply value of arguments as a list of expressions that must be
867 // translated, for overloaded call operators.
868 ArgOverloadedCall(Vec<&'a ast::Expr>),
871 fn trans_args_under_call_abi<'blk, 'tcx>(
872 mut bcx: Block<'blk, 'tcx>,
873 arg_exprs: &[P<ast::Expr>],
875 llargs: &mut Vec<ValueRef>,
876 arg_cleanup_scope: cleanup::ScopeId,
878 -> Block<'blk, 'tcx> {
879 // Translate the `self` argument first.
880 let arg_tys = ty::ty_fn_args(fn_ty);
882 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
883 llargs.push(unpack_result!(bcx, {
892 // Now untuple the rest of the arguments.
893 let tuple_expr = &arg_exprs[1];
894 let tuple_type = node_id_type(bcx, tuple_expr.id);
896 match ty::get(tuple_type).sty {
897 ty::ty_tup(ref field_types) => {
898 let tuple_datum = unpack_datum!(bcx,
899 expr::trans(bcx, &**tuple_expr));
900 let tuple_lvalue_datum =
902 tuple_datum.to_lvalue_datum(bcx,
905 let repr = adt::represent_type(bcx.ccx(), tuple_type);
906 let repr_ptr = &*repr;
907 for i in range(0, field_types.len()) {
908 let arg_datum = tuple_lvalue_datum.get_element(
912 adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
914 let arg_datum = arg_datum.to_expr_datum();
916 unpack_datum!(bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
918 unpack_datum!(bcx, arg_datum.to_appropriate_datum(bcx));
919 llargs.push(arg_datum.add_clean(bcx.fcx, arg_cleanup_scope));
924 bcx.sess().span_bug(tuple_expr.span,
925 "argument to `.call()` wasn't a tuple?!")
932 fn trans_overloaded_call_args<'blk, 'tcx>(
933 mut bcx: Block<'blk, 'tcx>,
934 arg_exprs: Vec<&ast::Expr>,
936 llargs: &mut Vec<ValueRef>,
937 arg_cleanup_scope: cleanup::ScopeId,
939 -> Block<'blk, 'tcx> {
940 // Translate the `self` argument first.
941 let arg_tys = ty::ty_fn_args(fn_ty);
943 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, arg_exprs[0]));
944 llargs.push(unpack_result!(bcx, {
953 // Now untuple the rest of the arguments.
954 let tuple_type = *arg_tys.get(1);
955 match ty::get(tuple_type).sty {
956 ty::ty_tup(ref field_types) => {
957 for (i, &field_type) in field_types.iter().enumerate() {
959 unpack_datum!(bcx, expr::trans(bcx, arg_exprs[i + 1]));
960 llargs.push(unpack_result!(bcx, {
971 bcx.sess().span_bug(arg_exprs[0].span,
972 "argument to `.call()` wasn't a tuple?!")
979 pub fn trans_args<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
982 llargs: &mut Vec<ValueRef> ,
983 arg_cleanup_scope: cleanup::ScopeId,
986 -> Block<'blk, 'tcx> {
987 debug!("trans_args(abi={})", abi);
989 let _icx = push_ctxt("trans_args");
990 let arg_tys = ty::ty_fn_args(fn_ty);
991 let variadic = ty::fn_is_variadic(fn_ty);
995 // First we figure out the caller's view of the types of the arguments.
996 // This will be needed if this is a generic call, because the callee has
997 // to cast her view of the arguments to the caller's view.
999 ArgExprs(arg_exprs) => {
1000 if abi == synabi::RustCall {
1001 // This is only used for direct calls to the `call`,
1002 // `call_mut` or `call_once` functions.
1003 return trans_args_under_call_abi(cx,
1011 let num_formal_args = arg_tys.len();
1012 for (i, arg_expr) in arg_exprs.iter().enumerate() {
1013 if i == 0 && ignore_self {
1016 let arg_ty = if i >= num_formal_args {
1018 expr_ty_adjusted(cx, &**arg_expr)
1023 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
1024 llargs.push(unpack_result!(bcx, {
1025 trans_arg_datum(bcx, arg_ty, arg_datum,
1031 ArgOverloadedCall(arg_exprs) => {
1032 return trans_overloaded_call_args(cx,
1039 ArgOverloadedOp(lhs, rhs) => {
1042 llargs.push(unpack_result!(bcx, {
1043 trans_arg_datum(bcx, *arg_tys.get(0), lhs,
1048 assert_eq!(arg_tys.len(), 1 + rhs.len());
1049 for (rhs, rhs_id) in rhs.move_iter() {
1050 llargs.push(unpack_result!(bcx, {
1051 trans_arg_datum(bcx, *arg_tys.get(1), rhs,
1053 DoAutorefArg(rhs_id))
1058 llargs.push_all(vs);
1065 pub enum AutorefArg {
1067 DoAutorefArg(ast::NodeId)
1070 pub fn trans_arg_datum<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1071 formal_arg_ty: ty::t,
1072 arg_datum: Datum<Expr>,
1073 arg_cleanup_scope: cleanup::ScopeId,
1074 autoref_arg: AutorefArg)
1075 -> Result<'blk, 'tcx> {
1076 let _icx = push_ctxt("trans_arg_datum");
1078 let ccx = bcx.ccx();
1080 debug!("trans_arg_datum({})",
1081 formal_arg_ty.repr(bcx.tcx()));
1083 let arg_datum_ty = arg_datum.ty;
1085 debug!(" arg datum: {}", arg_datum.to_string(bcx.ccx()));
1088 if ty::type_is_bot(arg_datum_ty) {
1089 // For values of type _|_, we generate an
1090 // "undef" value, as such a value should never
1091 // be inspected. It's important for the value
1092 // to have type lldestty (the callee's expected type).
1093 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1095 val = llvm::LLVMGetUndef(llformal_arg_ty.to_ref());
1098 // FIXME(#3548) use the adjustments table
1100 DoAutorefArg(arg_id) => {
1101 // We will pass argument by reference
1102 // We want an lvalue, so that we can pass by reference and
1103 let arg_datum = unpack_datum!(
1104 bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
1105 val = arg_datum.val;
1108 // Make this an rvalue, since we are going to be
1109 // passing ownership.
1110 let arg_datum = unpack_datum!(
1111 bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
1113 // Now that arg_datum is owned, get it into the appropriate
1114 // mode (ref vs value).
1115 let arg_datum = unpack_datum!(
1116 bcx, arg_datum.to_appropriate_datum(bcx));
1118 // Technically, ownership of val passes to the callee.
1119 // However, we must cleanup should we fail before the
1120 // callee is actually invoked.
1121 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
1125 if formal_arg_ty != arg_datum_ty {
1126 // this could happen due to e.g. subtyping
1127 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1128 debug!("casting actual type ({}) to match formal ({})",
1129 bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty));
1130 debug!("Rust types: {}; {}", ty_to_string(bcx.tcx(), arg_datum_ty),
1131 ty_to_string(bcx.tcx(), formal_arg_ty));
1132 val = PointerCast(bcx, val, llformal_arg_ty);
1136 debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val));
1137 Result::new(bcx, val)