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.
11 //! Handles translation of callees as well as other call-related
12 //! things. Callees are a superset of normal rust values and sometimes
13 //! have different representations. In particular, top-level fn items
14 //! and methods are represented as just a fn ptr and not a full
17 pub use self::AutorefArg::*;
18 pub use self::CalleeData::*;
19 pub use self::CallArgs::*;
21 use arena::TypedArena;
24 use llvm::{self, ValueRef, get_params};
25 use metadata::csearch;
28 use middle::subst::{Subst, Substs};
35 use trans::cleanup::CleanupMethods;
37 use trans::common::{self, Block, Result, NodeIdAndSpan, ExprId, CrateContext,
38 ExprOrMethodCall, FunctionContext, MethodCallKey};
41 use trans::debuginfo::{DebugLoc, ToDebugLoc};
49 use trans::monomorphize;
50 use trans::type_::Type;
52 use middle::ty::{self, Ty, HasTypeFlags, RegionEscape};
53 use middle::ty::MethodCall;
56 use syntax::abi as synabi;
60 #[derive(Copy, Clone)]
61 pub struct MethodData {
66 pub enum CalleeData<'tcx> {
67 // Constructor for enum variant/tuple-like-struct
69 NamedTupleConstructor(subst::Substs<'tcx>, ty::Disr),
71 // Represents a (possibly monomorphized) top-level fn item or method
72 // item. Note that this is just the fn-ptr and is not a Rust closure
73 // value (which is a pair).
74 Fn(/* llfn */ ValueRef),
76 Intrinsic(ast::NodeId, subst::Substs<'tcx>),
81 pub struct Callee<'blk, 'tcx: 'blk> {
82 pub bcx: Block<'blk, 'tcx>,
83 pub data: CalleeData<'tcx>,
86 fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
87 -> Callee<'blk, 'tcx> {
88 let _icx = push_ctxt("trans_callee");
89 debug!("callee::trans(expr={:?})", expr);
91 // pick out special kinds of expressions that can be called:
93 ast::ExprPath(..) => {
94 return trans_def(bcx, bcx.def(expr.id), expr);
99 // any other expressions are closures:
100 return datum_callee(bcx, expr);
102 fn datum_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
103 -> Callee<'blk, 'tcx> {
104 let DatumBlock { bcx, datum, .. } = expr::trans(bcx, expr);
106 ty::TyBareFn(..) => {
107 let llval = datum.to_llscalarish(bcx);
114 bcx.tcx().sess.span_bug(
116 &format!("type of callee is neither bare-fn nor closure: {}",
122 fn fn_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, llfn: ValueRef)
123 -> Callee<'blk, 'tcx> {
130 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
132 ref_expr: &ast::Expr)
133 -> Callee<'blk, 'tcx> {
134 debug!("trans_def(def={:?}, ref_expr={:?})", def, ref_expr);
135 let expr_ty = common::node_id_type(bcx, ref_expr.id);
137 def::DefFn(did, _) if {
138 let maybe_def_id = inline::get_local_instance(bcx.ccx(), did);
139 let maybe_ast_node = maybe_def_id.and_then(|def_id| bcx.tcx().map
141 match maybe_ast_node {
142 Some(ast_map::NodeStructCtor(_)) => true,
146 let substs = common::node_id_substs(bcx.ccx(),
148 bcx.fcx.param_substs);
151 data: NamedTupleConstructor(substs, 0)
154 def::DefFn(did, _) if match expr_ty.sty {
155 ty::TyBareFn(_, ref f) => f.abi == synabi::RustIntrinsic,
158 let substs = common::node_id_substs(bcx.ccx(),
160 bcx.fcx.param_substs);
161 let def_id = inline::maybe_instantiate_inline(bcx.ccx(), did);
162 Callee { bcx: bcx, data: Intrinsic(def_id.node, substs) }
164 def::DefFn(did, _) | def::DefMethod(did, def::FromImpl(_)) => {
165 fn_callee(bcx, trans_fn_ref(bcx.ccx(), did, ExprId(ref_expr.id),
166 bcx.fcx.param_substs).val)
168 def::DefMethod(meth_did, def::FromTrait(trait_did)) => {
169 fn_callee(bcx, meth::trans_static_method_callee(bcx.ccx(),
173 bcx.fcx.param_substs).val)
175 def::DefVariant(tid, vid, _) => {
176 let vinfo = bcx.tcx().enum_variant_with_id(tid, vid);
177 let substs = common::node_id_substs(bcx.ccx(),
179 bcx.fcx.param_substs);
181 // Nullary variants are not callable
182 assert!(!vinfo.args.is_empty());
186 data: NamedTupleConstructor(substs, vinfo.disr_val)
189 def::DefStruct(_) => {
190 let substs = common::node_id_substs(bcx.ccx(),
192 bcx.fcx.param_substs);
195 data: NamedTupleConstructor(substs, 0)
200 def::DefAssociatedConst(..) |
202 def::DefUpvar(..) => {
203 datum_callee(bcx, ref_expr)
205 def::DefMod(..) | def::DefForeignMod(..) | def::DefTrait(..) |
206 def::DefTy(..) | def::DefPrimTy(..) | def::DefAssociatedTy(..) |
207 def::DefUse(..) | def::DefRegion(..) | def::DefLabel(..) |
208 def::DefTyParam(..) | def::DefSelfTy(..) => {
209 bcx.tcx().sess.span_bug(
211 &format!("cannot translate def {:?} \
212 to a callable thing!", def));
218 /// Translates a reference (with id `ref_id`) to the fn/method with id `def_id` into a function
219 /// pointer. This may require monomorphization or inlining.
220 pub fn trans_fn_ref<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
222 node: ExprOrMethodCall,
223 param_substs: &'tcx subst::Substs<'tcx>)
224 -> Datum<'tcx, Rvalue> {
225 let _icx = push_ctxt("trans_fn_ref");
227 let substs = common::node_id_substs(ccx, node, param_substs);
228 debug!("trans_fn_ref(def_id={:?}, node={:?}, substs={:?})",
232 trans_fn_ref_with_substs(ccx, def_id, node, param_substs, substs)
235 fn trans_fn_ref_with_substs_to_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
238 substs: subst::Substs<'tcx>)
239 -> Callee<'blk, 'tcx> {
242 data: Fn(trans_fn_ref_with_substs(bcx.ccx(),
245 bcx.fcx.param_substs,
250 /// Translates an adapter that implements the `Fn` trait for a fn
251 /// pointer. This is basically the equivalent of something like:
254 /// impl<'a> Fn(&'a int) -> &'a int for fn(&int) -> &int {
255 /// extern "rust-abi" fn call(&self, args: (&'a int,)) -> &'a int {
261 /// but for the bare function type given.
262 pub fn trans_fn_pointer_shim<'a, 'tcx>(
263 ccx: &'a CrateContext<'a, 'tcx>,
264 closure_kind: ty::ClosureKind,
265 bare_fn_ty: Ty<'tcx>)
268 let _icx = push_ctxt("trans_fn_pointer_shim");
271 // Normalize the type for better caching.
272 let bare_fn_ty = common::erase_regions(tcx, &bare_fn_ty);
274 // If this is an impl of `Fn` or `FnMut` trait, the receiver is `&self`.
275 let is_by_ref = match closure_kind {
276 ty::FnClosureKind | ty::FnMutClosureKind => true,
277 ty::FnOnceClosureKind => false,
279 let bare_fn_ty_maybe_ref = if is_by_ref {
280 tcx.mk_imm_ref(tcx.mk_region(ty::ReStatic), bare_fn_ty)
285 // Check if we already trans'd this shim.
286 match ccx.fn_pointer_shims().borrow().get(&bare_fn_ty_maybe_ref) {
287 Some(&llval) => { return llval; }
291 debug!("trans_fn_pointer_shim(bare_fn_ty={:?})",
294 // Construct the "tuply" version of `bare_fn_ty`. It takes two arguments: `self`,
295 // which is the fn pointer, and `args`, which is the arguments tuple.
296 let (opt_def_id, sig) =
297 match bare_fn_ty.sty {
298 ty::TyBareFn(opt_def_id,
299 &ty::BareFnTy { unsafety: ast::Unsafety::Normal,
306 tcx.sess.bug(&format!("trans_fn_pointer_shim invoked on invalid type: {}",
310 let sig = tcx.erase_late_bound_regions(sig);
311 let tuple_input_ty = tcx.mk_tup(sig.inputs.to_vec());
312 let tuple_fn_ty = tcx.mk_fn(opt_def_id,
313 tcx.mk_bare_fn(ty::BareFnTy {
314 unsafety: ast::Unsafety::Normal,
315 abi: synabi::RustCall,
316 sig: ty::Binder(ty::FnSig {
317 inputs: vec![bare_fn_ty_maybe_ref,
322 debug!("tuple_fn_ty: {:?}", tuple_fn_ty);
325 let function_name = link::mangle_internal_name_by_type_and_seq(ccx, bare_fn_ty,
327 let llfn = declare::declare_internal_rust_fn(ccx, &function_name[..], tuple_fn_ty);
330 let empty_substs = tcx.mk_substs(Substs::trans_empty());
331 let (block_arena, fcx): (TypedArena<_>, FunctionContext);
332 block_arena = TypedArena::new();
333 fcx = new_fn_ctxt(ccx,
341 let mut bcx = init_function(&fcx, false, sig.output);
343 let llargs = get_params(fcx.llfn);
345 let self_idx = fcx.arg_offset();
346 // the first argument (`self`) will be ptr to the the fn pointer
347 let llfnpointer = if is_by_ref {
348 Load(bcx, llargs[self_idx])
353 assert!(!fcx.needs_ret_allocas);
355 let dest = fcx.llretslotptr.get().map(|_|
356 expr::SaveIn(fcx.get_ret_slot(bcx, sig.output, "ret_slot"))
359 bcx = trans_call_inner(bcx,
362 |bcx, _| Callee { bcx: bcx, data: Fn(llfnpointer) },
363 ArgVals(&llargs[(self_idx + 1)..]),
366 finish_fn(&fcx, bcx, sig.output, DebugLoc::None);
368 ccx.fn_pointer_shims().borrow_mut().insert(bare_fn_ty_maybe_ref, llfn);
373 /// Translates a reference to a fn/method item, monomorphizing and
374 /// inlining as it goes.
378 /// - `ccx`: the crate context
379 /// - `def_id`: def id of the fn or method item being referenced
380 /// - `node`: node id of the reference to the fn/method, if applicable.
381 /// This parameter may be zero; but, if so, the resulting value may not
382 /// have the right type, so it must be cast before being used.
383 /// - `param_substs`: if the `node` is in a polymorphic function, these
384 /// are the substitutions required to monomorphize its type
385 /// - `substs`: values for each of the fn/method's parameters
386 pub fn trans_fn_ref_with_substs<'a, 'tcx>(
387 ccx: &CrateContext<'a, 'tcx>,
389 node: ExprOrMethodCall,
390 param_substs: &'tcx subst::Substs<'tcx>,
391 substs: subst::Substs<'tcx>)
392 -> Datum<'tcx, Rvalue>
394 let _icx = push_ctxt("trans_fn_ref_with_substs");
397 debug!("trans_fn_ref_with_substs(def_id={:?}, node={:?}, \
398 param_substs={:?}, substs={:?})",
404 assert!(!substs.types.needs_infer());
405 assert!(!substs.types.has_escaping_regions());
406 let substs = substs.erase_regions();
408 // Load the info for the appropriate trait if necessary.
409 match tcx.trait_of_item(def_id) {
412 tcx.populate_implementations_for_trait_if_necessary(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 tcx.provided_source(def_id) {
421 (false, def_id, tcx.mk_substs(substs))
424 // There are two relevant substitutions when compiling
425 // default methods. First, there is the substitution for
426 // the type parameters of the impl we are using and the
427 // method we are calling. This substitution is the substs
428 // argument we already have.
429 // In order to compile a default method, though, we need
430 // to consider another substitution: the substitution for
431 // the type parameters on trait; the impl we are using
432 // implements the trait at some particular type
433 // parameters, and we need to substitute for those first.
434 // So, what we need to do is find this substitution and
435 // compose it with the one we already have.
437 let impl_id = tcx.impl_or_trait_item(def_id).container()
439 let impl_or_trait_item = tcx.impl_or_trait_item(source_id);
440 match impl_or_trait_item {
441 ty::MethodTraitItem(method) => {
442 let trait_ref = tcx.impl_trait_ref(impl_id).unwrap();
444 // Compute the first substitution
446 tcx.make_substs_for_receiver_types(&trait_ref, &*method)
450 let new_substs = tcx.mk_substs(first_subst.subst(tcx, &substs));
452 debug!("trans_fn_with_vtables - default method: \
453 substs = {:?}, trait_subst = {:?}, \
454 first_subst = {:?}, new_subst = {:?}",
455 substs, trait_ref.substs,
456 first_subst, new_substs);
458 (true, source_id, new_substs)
461 tcx.sess.bug("trans_fn_ref_with_vtables() tried \
462 to translate a non-method?!")
468 // If this is a closure, redirect to it.
469 match closure::get_or_create_declaration_if_closure(ccx, def_id, substs) {
471 Some(llfn) => return llfn,
474 // Check whether this fn has an inlined copy and, if so, redirect
475 // def_id to the local id of the inlined copy.
476 let def_id = inline::maybe_instantiate_inline(ccx, def_id);
478 // We must monomorphise if the fn has type parameters, is a default method,
479 // or is a named tuple constructor.
480 let must_monomorphise = if !substs.types.is_empty() || is_default {
482 } else if def_id.krate == ast::LOCAL_CRATE {
483 let map_node = session::expect(
485 tcx.map.find(def_id.node),
486 || "local item should be in ast map".to_string());
489 ast_map::NodeVariant(v) => match v.node.kind {
490 ast::TupleVariantKind(ref args) => !args.is_empty(),
493 ast_map::NodeStructCtor(_) => true,
500 debug!("trans_fn_ref_with_substs({:?}) must_monomorphise: {}",
501 def_id, must_monomorphise);
503 // Create a monomorphic version of generic functions
504 if must_monomorphise {
505 // Should be either intra-crate or inlined.
506 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
508 let opt_ref_id = match node {
509 ExprId(id) => if id != 0 { Some(id) } else { None },
510 MethodCallKey(_) => None,
513 let (val, fn_ty, must_cast) =
514 monomorphize::monomorphic_fn(ccx, def_id, substs, opt_ref_id);
515 if must_cast && node != ExprId(0) {
516 // Monotype of the REFERENCE to the function (type params
518 let ref_ty = match node {
519 ExprId(id) => tcx.node_id_to_type(id),
520 MethodCallKey(method_call) => {
521 tcx.tables.borrow().method_map.get(&method_call).unwrap().ty
524 let ref_ty = monomorphize::apply_param_substs(tcx,
527 let llptrty = type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to();
528 if llptrty != common::val_ty(val) {
529 let val = consts::ptrcast(val, llptrty);
530 return Datum::new(val, ref_ty, Rvalue::new(ByValue));
533 return Datum::new(val, fn_ty, Rvalue::new(ByValue));
536 // Type scheme of the function item (may have type params)
537 let fn_type_scheme = tcx.lookup_item_type(def_id);
538 let fn_type = monomorphize::normalize_associated_type(tcx, &fn_type_scheme.ty);
540 // Find the actual function pointer.
542 if def_id.krate == ast::LOCAL_CRATE {
543 // Internal reference.
544 get_item_val(ccx, def_id.node)
546 // External reference.
547 trans_external_path(ccx, def_id, fn_type)
551 // This is subtle and surprising, but sometimes we have to bitcast
552 // the resulting fn pointer. The reason has to do with external
553 // functions. If you have two crates that both bind the same C
554 // library, they may not use precisely the same types: for
555 // example, they will probably each declare their own structs,
556 // which are distinct types from LLVM's point of view (nominal
559 // Now, if those two crates are linked into an application, and
560 // they contain inlined code, you can wind up with a situation
561 // where both of those functions wind up being loaded into this
562 // application simultaneously. In that case, the same function
563 // (from LLVM's point of view) requires two types. But of course
564 // LLVM won't allow one function to have two types.
566 // What we currently do, therefore, is declare the function with
567 // one of the two types (whichever happens to come first) and then
568 // bitcast as needed when the function is referenced to make sure
569 // it has the type we expect.
571 // This can occur on either a crate-local or crate-external
572 // reference. It also occurs when testing libcore and in some
573 // other weird situations. Annoying.
574 let llty = type_of::type_of_fn_from_ty(ccx, fn_type);
575 let llptrty = llty.ptr_to();
576 if common::val_ty(val) != llptrty {
577 debug!("trans_fn_ref_with_vtables(): casting pointer!");
578 val = consts::ptrcast(val, llptrty);
580 debug!("trans_fn_ref_with_vtables(): not casting pointer!");
583 Datum::new(val, fn_type, Rvalue::new(ByValue))
586 // ______________________________________________________________________
589 pub fn trans_call<'a, 'blk, 'tcx>(in_cx: Block<'blk, 'tcx>,
590 call_expr: &ast::Expr,
592 args: CallArgs<'a, 'tcx>,
594 -> Block<'blk, 'tcx> {
595 let _icx = push_ctxt("trans_call");
596 trans_call_inner(in_cx,
597 call_expr.debug_loc(),
598 common::expr_ty_adjusted(in_cx, f),
599 |cx, _| trans(cx, f),
604 pub fn trans_method_call<'a, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
605 call_expr: &ast::Expr,
607 args: CallArgs<'a, 'tcx>,
609 -> Block<'blk, 'tcx> {
610 let _icx = push_ctxt("trans_method_call");
611 debug!("trans_method_call(call_expr={:?})", call_expr);
612 let method_call = MethodCall::expr(call_expr.id);
613 let method_ty = match bcx.tcx().tables.borrow().method_map.get(&method_call) {
614 Some(method) => match method.origin {
615 ty::MethodOrigin::Object(_) => match method.ty.sty {
616 ty::TyBareFn(_, ref fty) => {
617 bcx.tcx().mk_fn(None, meth::opaque_method_ty(bcx.tcx(), fty))
623 None => panic!("method not found in trans_method_call")
627 call_expr.debug_loc(),
628 common::monomorphize_type(bcx, method_ty),
629 |cx, arg_cleanup_scope| {
630 meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
636 pub fn trans_lang_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
639 dest: Option<expr::Dest>,
641 -> Result<'blk, 'tcx> {
642 let fty = if did.krate == ast::LOCAL_CRATE {
643 bcx.tcx().node_id_to_type(did.node)
645 csearch::get_type(bcx.tcx(), did).ty
647 callee::trans_call_inner(bcx,
651 trans_fn_ref_with_substs_to_callee(bcx,
654 subst::Substs::trans_empty())
660 /// This behemoth of a function translates function calls. Unfortunately, in order to generate more
661 /// efficient LLVM output at -O0, it has quite a complex signature (refactoring this into two
662 /// functions seems like a good idea).
664 /// In particular, for lang items, it is invoked with a dest of None, and in that case the return
665 /// value contains the result of the fn. The lang item must not return a structural type or else
666 /// all heck breaks loose.
668 /// For non-lang items, `dest` is always Some, and hence the result is written into memory
669 /// somewhere. Nonetheless we return the actual return value of the function.
670 pub fn trans_call_inner<'a, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
674 args: CallArgs<'a, 'tcx>,
675 dest: Option<expr::Dest>)
676 -> Result<'blk, 'tcx> where
677 F: FnOnce(Block<'blk, 'tcx>, cleanup::ScopeId) -> Callee<'blk, 'tcx>,
679 // Introduce a temporary cleanup scope that will contain cleanups
680 // for the arguments while they are being evaluated. The purpose
681 // this cleanup is to ensure that, should a panic occur while
682 // evaluating argument N, the values for arguments 0...N-1 are all
683 // cleaned up. If no panic occurs, the values are handed off to
684 // the callee, and hence none of the cleanups in this temporary
685 // scope will ever execute.
688 let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
690 let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
691 let mut bcx = callee.bcx;
693 let (abi, ret_ty) = match callee_ty.sty {
694 ty::TyBareFn(_, ref f) => {
695 let output = bcx.tcx().erase_late_bound_regions(&f.sig.output());
698 _ => panic!("expected bare rust fn or closure in trans_call_inner")
701 let (llfn, llself) = match callee.data {
706 (d.llfn, Some(d.llself))
708 Intrinsic(node, substs) => {
709 assert!(abi == synabi::RustIntrinsic);
710 assert!(dest.is_some());
712 let call_info = match debug_loc {
713 DebugLoc::At(id, span) => NodeIdAndSpan { id: id, span: span },
715 bcx.sess().bug("No call info for intrinsic call?")
719 return intrinsic::trans_intrinsic_call(bcx, node, callee_ty,
720 arg_cleanup_scope, args,
721 dest.unwrap(), substs,
724 NamedTupleConstructor(substs, disr) => {
725 assert!(dest.is_some());
726 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
728 let ctor_ty = callee_ty.subst(bcx.tcx(), &substs);
729 return base::trans_named_tuple_constructor(bcx,
738 // Intrinsics should not become actual functions.
739 // We trans them in place in `trans_intrinsic_call`
740 assert!(abi != synabi::RustIntrinsic);
742 let is_rust_fn = abi == synabi::Rust || abi == synabi::RustCall;
744 // Generate a location to store the result. If the user does
745 // not care about the result, just make a stack slot.
746 let opt_llretslot = dest.and_then(|dest| match dest {
747 expr::SaveIn(dst) => Some(dst),
749 let ret_ty = match ret_ty {
750 ty::FnConverging(ret_ty) => ret_ty,
751 ty::FnDiverging => ccx.tcx().mk_nil()
754 type_of::return_uses_outptr(ccx, ret_ty) ||
755 bcx.fcx.type_needs_drop(ret_ty) {
756 // Push the out-pointer if we use an out-pointer for this
757 // return type, otherwise push "undef".
758 if common::type_is_zero_size(ccx, ret_ty) {
759 let llty = type_of::type_of(ccx, ret_ty);
760 Some(common::C_undef(llty.ptr_to()))
762 Some(alloc_ty(bcx, ret_ty, "__llret"))
770 let mut llresult = unsafe {
771 llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
774 // The code below invokes the function, using either the Rust
775 // conventions (if it is a rust fn) or the native conventions
776 // (otherwise). The important part is that, when all is said
777 // and done, either the return value of the function will have been
778 // written in opt_llretslot (if it is Some) or `llresult` will be
779 // set appropriately (otherwise).
781 let mut llargs = Vec::new();
783 if let (ty::FnConverging(ret_ty), Some(mut llretslot)) = (ret_ty, opt_llretslot) {
784 if type_of::return_uses_outptr(ccx, ret_ty) {
785 let llformal_ret_ty = type_of::type_of(ccx, ret_ty).ptr_to();
786 let llret_ty = common::val_ty(llretslot);
787 if llformal_ret_ty != llret_ty {
788 // this could happen due to e.g. subtyping
789 debug!("casting actual return type ({}) to match formal ({})",
790 bcx.llty_str(llret_ty), bcx.llty_str(llformal_ret_ty));
791 llretslot = PointerCast(bcx, llretslot, llformal_ret_ty);
793 llargs.push(llretslot);
797 // Push a trait object's self.
798 if let Some(llself) = llself {
802 // Push the arguments.
803 bcx = trans_args(bcx,
807 cleanup::CustomScope(arg_cleanup_scope),
811 fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
813 // Invoke the actual rust fn and update bcx/llresult.
814 let (llret, b) = base::invoke(bcx,
822 // If the Rust convention for this type is return via
823 // the return value, copy it into llretslot.
824 match (opt_llretslot, ret_ty) {
825 (Some(llretslot), ty::FnConverging(ret_ty)) => {
826 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
827 !common::type_is_zero_size(bcx.ccx(), ret_ty)
829 store_ty(bcx, llret, llretslot, ret_ty)
835 // Lang items are the only case where dest is None, and
836 // they are always Rust fns.
837 assert!(dest.is_some());
839 let mut llargs = Vec::new();
840 let arg_tys = match args {
841 ArgExprs(a) => a.iter().map(|x| common::expr_ty_adjusted(bcx, &**x)).collect(),
842 _ => panic!("expected arg exprs.")
844 bcx = trans_args(bcx,
848 cleanup::CustomScope(arg_cleanup_scope),
851 fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
853 bcx = foreign::trans_native_call(bcx,
856 opt_llretslot.unwrap(),
862 fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_cleanup_scope);
864 // If the caller doesn't care about the result of this fn call,
865 // drop the temporary slot we made.
866 match (dest, opt_llretslot, ret_ty) {
867 (Some(expr::Ignore), Some(llretslot), ty::FnConverging(ret_ty)) => {
868 // drop the value if it is not being saved.
869 bcx = glue::drop_ty(bcx,
873 call_lifetime_end(bcx, llretslot);
878 if ret_ty == ty::FnDiverging {
882 Result::new(bcx, llresult)
885 pub enum CallArgs<'a, 'tcx> {
886 // Supply value of arguments as a list of expressions that must be
887 // translated. This is used in the common case of `foo(bar, qux)`.
888 ArgExprs(&'a [P<ast::Expr>]),
890 // Supply value of arguments as a list of LLVM value refs; frequently
891 // used with lang items and so forth, when the argument is an internal
893 ArgVals(&'a [ValueRef]),
895 // For overloaded operators: `(lhs, Option(rhs, rhs_id), autoref)`. `lhs`
896 // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
897 // the right-hand-side argument (if any). `autoref` indicates whether the `rhs`
898 // arguments should be auto-referenced
899 ArgOverloadedOp(Datum<'tcx, Expr>, Option<(Datum<'tcx, Expr>, ast::NodeId)>, bool),
901 // Supply value of arguments as a list of expressions that must be
902 // translated, for overloaded call operators.
903 ArgOverloadedCall(Vec<&'a ast::Expr>),
906 fn trans_args_under_call_abi<'blk, 'tcx>(
907 mut bcx: Block<'blk, 'tcx>,
908 arg_exprs: &[P<ast::Expr>],
910 llargs: &mut Vec<ValueRef>,
911 arg_cleanup_scope: cleanup::ScopeId,
915 let args = bcx.tcx().erase_late_bound_regions(&fn_ty.fn_args());
917 // Translate the `self` argument first.
919 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
920 bcx = trans_arg_datum(bcx,
928 // Now untuple the rest of the arguments.
929 let tuple_expr = &arg_exprs[1];
930 let tuple_type = common::node_id_type(bcx, tuple_expr.id);
932 match tuple_type.sty {
933 ty::TyTuple(ref field_types) => {
934 let tuple_datum = unpack_datum!(bcx,
935 expr::trans(bcx, &**tuple_expr));
936 let tuple_lvalue_datum =
938 tuple_datum.to_lvalue_datum(bcx,
941 let repr = adt::represent_type(bcx.ccx(), tuple_type);
942 let repr_ptr = &*repr;
943 for (i, field_type) in field_types.iter().enumerate() {
944 let arg_datum = tuple_lvalue_datum.get_element(
948 adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
950 bcx = trans_arg_datum(bcx,
959 bcx.sess().span_bug(tuple_expr.span,
960 "argument to `.call()` wasn't a tuple?!")
967 fn trans_overloaded_call_args<'blk, 'tcx>(
968 mut bcx: Block<'blk, 'tcx>,
969 arg_exprs: Vec<&ast::Expr>,
971 llargs: &mut Vec<ValueRef>,
972 arg_cleanup_scope: cleanup::ScopeId,
974 -> Block<'blk, 'tcx> {
975 // Translate the `self` argument first.
976 let arg_tys = bcx.tcx().erase_late_bound_regions( &fn_ty.fn_args());
978 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, arg_exprs[0]));
979 bcx = trans_arg_datum(bcx,
987 // Now untuple the rest of the arguments.
988 let tuple_type = arg_tys[1];
989 match tuple_type.sty {
990 ty::TyTuple(ref field_types) => {
991 for (i, &field_type) in field_types.iter().enumerate() {
993 unpack_datum!(bcx, expr::trans(bcx, arg_exprs[i + 1]));
994 bcx = trans_arg_datum(bcx,
1003 bcx.sess().span_bug(arg_exprs[0].span,
1004 "argument to `.call()` wasn't a tuple?!")
1011 pub fn trans_args<'a, 'blk, 'tcx>(cx: Block<'blk, 'tcx>,
1012 args: CallArgs<'a, 'tcx>,
1014 llargs: &mut Vec<ValueRef>,
1015 arg_cleanup_scope: cleanup::ScopeId,
1018 -> Block<'blk, 'tcx> {
1019 debug!("trans_args(abi={})", abi);
1021 let _icx = push_ctxt("trans_args");
1022 let arg_tys = cx.tcx().erase_late_bound_regions(&fn_ty.fn_args());
1023 let variadic = fn_ty.fn_sig().0.variadic;
1027 // First we figure out the caller's view of the types of the arguments.
1028 // This will be needed if this is a generic call, because the callee has
1029 // to cast her view of the arguments to the caller's view.
1031 ArgExprs(arg_exprs) => {
1032 if abi == synabi::RustCall {
1033 // This is only used for direct calls to the `call`,
1034 // `call_mut` or `call_once` functions.
1035 return trans_args_under_call_abi(cx,
1043 let num_formal_args = arg_tys.len();
1044 for (i, arg_expr) in arg_exprs.iter().enumerate() {
1045 if i == 0 && ignore_self {
1048 let arg_ty = if i >= num_formal_args {
1050 common::expr_ty_adjusted(cx, &**arg_expr)
1055 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
1056 bcx = trans_arg_datum(bcx, arg_ty, arg_datum,
1062 ArgOverloadedCall(arg_exprs) => {
1063 return trans_overloaded_call_args(cx,
1070 ArgOverloadedOp(lhs, rhs, autoref) => {
1073 bcx = trans_arg_datum(bcx, arg_tys[0], lhs,
1078 if let Some((rhs, rhs_id)) = rhs {
1079 assert_eq!(arg_tys.len(), 2);
1080 bcx = trans_arg_datum(bcx, arg_tys[1], rhs,
1082 if autoref { DoAutorefArg(rhs_id) } else { DontAutorefArg },
1085 assert_eq!(arg_tys.len(), 1);
1089 llargs.push_all(vs);
1096 #[derive(Copy, Clone)]
1097 pub enum AutorefArg {
1099 DoAutorefArg(ast::NodeId)
1102 pub fn trans_arg_datum<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1103 formal_arg_ty: Ty<'tcx>,
1104 arg_datum: Datum<'tcx, Expr>,
1105 arg_cleanup_scope: cleanup::ScopeId,
1106 autoref_arg: AutorefArg,
1107 llargs: &mut Vec<ValueRef>)
1108 -> Block<'blk, 'tcx> {
1109 let _icx = push_ctxt("trans_arg_datum");
1111 let ccx = bcx.ccx();
1113 debug!("trans_arg_datum({:?})",
1116 let arg_datum_ty = arg_datum.ty;
1118 debug!(" arg datum: {}", arg_datum.to_string(bcx.ccx()));
1121 // FIXME(#3548) use the adjustments table
1123 DoAutorefArg(arg_id) => {
1124 // We will pass argument by reference
1125 // We want an lvalue, so that we can pass by reference and
1126 let arg_datum = unpack_datum!(
1127 bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
1128 val = arg_datum.val;
1130 DontAutorefArg if common::type_is_fat_ptr(bcx.tcx(), arg_datum_ty) &&
1131 !bcx.fcx.type_needs_drop(arg_datum_ty) => {
1135 // Make this an rvalue, since we are going to be
1136 // passing ownership.
1137 let arg_datum = unpack_datum!(
1138 bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
1140 // Now that arg_datum is owned, get it into the appropriate
1141 // mode (ref vs value).
1142 let arg_datum = unpack_datum!(
1143 bcx, arg_datum.to_appropriate_datum(bcx));
1145 // Technically, ownership of val passes to the callee.
1146 // However, we must cleanup should we panic before the
1147 // callee is actually invoked.
1148 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
1152 if type_of::arg_is_indirect(ccx, formal_arg_ty) && formal_arg_ty != arg_datum_ty {
1153 // this could happen due to e.g. subtyping
1154 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1155 debug!("casting actual type ({}) to match formal ({})",
1156 bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty));
1157 debug!("Rust types: {:?}; {:?}", arg_datum_ty,
1159 val = PointerCast(bcx, val, llformal_arg_ty);
1162 debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val));
1164 if common::type_is_fat_ptr(bcx.tcx(), formal_arg_ty) {
1165 llargs.push(Load(bcx, expr::get_dataptr(bcx, val)));
1166 llargs.push(Load(bcx, expr::get_len(bcx, val)));