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;
27 use metadata::csearch;
30 use middle::subst::{Subst, Substs};
37 use trans::cleanup::CleanupMethods;
39 use trans::common::{self, Block, Result, NodeIdAndSpan, ExprId, CrateContext,
40 ExprOrMethodCall, FunctionContext, MethodCallKey};
43 use trans::debuginfo::{DebugLoc, ToDebugLoc};
50 use trans::monomorphize;
51 use trans::type_::Type;
53 use middle::ty::{self, Ty};
54 use middle::ty::MethodCall;
55 use util::ppaux::Repr;
56 use util::ppaux::ty_to_string;
58 use syntax::abi as synabi;
64 pub struct MethodData {
69 pub enum CalleeData<'tcx> {
70 // Constructor for enum variant/tuple-like-struct
72 NamedTupleConstructor(subst::Substs<'tcx>, ty::Disr),
74 // Represents a (possibly monomorphized) top-level fn item or method
75 // item. Note that this is just the fn-ptr and is not a Rust closure
76 // value (which is a pair).
77 Fn(/* llfn */ ValueRef),
79 Intrinsic(ast::NodeId, subst::Substs<'tcx>),
84 pub struct Callee<'blk, 'tcx: 'blk> {
85 pub bcx: Block<'blk, 'tcx>,
86 pub data: CalleeData<'tcx>,
89 fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
90 -> Callee<'blk, 'tcx> {
91 let _icx = push_ctxt("trans_callee");
92 debug!("callee::trans(expr={})", expr.repr(bcx.tcx()));
94 // pick out special kinds of expressions that can be called:
96 ast::ExprPath(_) | ast::ExprQPath(_) => {
97 return trans_def(bcx, bcx.def(expr.id), expr);
102 // any other expressions are closures:
103 return datum_callee(bcx, expr);
105 fn datum_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
106 -> Callee<'blk, 'tcx> {
107 let DatumBlock { bcx, datum, .. } = expr::trans(bcx, expr);
109 ty::ty_bare_fn(..) => {
110 let llval = datum.to_llscalarish(bcx);
117 bcx.tcx().sess.span_bug(
119 &format!("type of callee is neither bare-fn nor closure: \
121 bcx.ty_to_string(datum.ty))[]);
126 fn fn_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, llfn: ValueRef)
127 -> Callee<'blk, 'tcx> {
134 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
136 ref_expr: &ast::Expr)
137 -> Callee<'blk, 'tcx> {
138 debug!("trans_def(def={}, ref_expr={})", def.repr(bcx.tcx()), ref_expr.repr(bcx.tcx()));
139 let expr_ty = common::node_id_type(bcx, ref_expr.id);
141 def::DefFn(did, _) if {
142 let maybe_def_id = inline::get_local_instance(bcx.ccx(), did);
143 let maybe_ast_node = maybe_def_id.and_then(|def_id| bcx.tcx().map
145 match maybe_ast_node {
146 Some(ast_map::NodeStructCtor(_)) => true,
150 let substs = common::node_id_substs(bcx.ccx(),
152 bcx.fcx.param_substs);
155 data: NamedTupleConstructor(substs, 0)
158 def::DefFn(did, _) if match expr_ty.sty {
159 ty::ty_bare_fn(_, ref f) => f.abi == synabi::RustIntrinsic,
162 let substs = common::node_id_substs(bcx.ccx(),
164 bcx.fcx.param_substs);
165 let def_id = inline::maybe_instantiate_inline(bcx.ccx(), did);
166 Callee { bcx: bcx, data: Intrinsic(def_id.node, substs) }
168 def::DefFn(did, _) | def::DefMethod(did, _, def::FromImpl(_)) |
169 def::DefStaticMethod(did, def::FromImpl(_)) => {
170 fn_callee(bcx, trans_fn_ref(bcx.ccx(), did, ExprId(ref_expr.id),
171 bcx.fcx.param_substs).val)
173 def::DefStaticMethod(meth_did, def::FromTrait(trait_did)) |
174 def::DefMethod(meth_did, _, def::FromTrait(trait_did)) => {
175 fn_callee(bcx, meth::trans_static_method_callee(bcx.ccx(),
179 bcx.fcx.param_substs).val)
181 def::DefVariant(tid, vid, _) => {
182 let vinfo = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
183 let substs = common::node_id_substs(bcx.ccx(),
185 bcx.fcx.param_substs);
187 // Nullary variants are not callable
188 assert!(vinfo.args.len() > 0);
192 data: NamedTupleConstructor(substs, vinfo.disr_val)
195 def::DefStruct(_) => {
196 let substs = common::node_id_substs(bcx.ccx(),
198 bcx.fcx.param_substs);
201 data: NamedTupleConstructor(substs, 0)
207 def::DefUpvar(..) => {
208 datum_callee(bcx, ref_expr)
210 def::DefMod(..) | def::DefForeignMod(..) | def::DefTrait(..) |
211 def::DefTy(..) | def::DefPrimTy(..) | def::DefAssociatedTy(..) |
212 def::DefUse(..) | def::DefTyParamBinder(..) |
213 def::DefRegion(..) | def::DefLabel(..) | def::DefTyParam(..) |
214 def::DefSelfTy(..) | def::DefAssociatedPath(..) => {
215 bcx.tcx().sess.span_bug(
217 &format!("cannot translate def {:?} \
218 to a callable thing!", def)[]);
224 /// Translates a reference (with id `ref_id`) to the fn/method with id `def_id` into a function
225 /// pointer. This may require monomorphization or inlining.
226 pub fn trans_fn_ref<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
228 node: ExprOrMethodCall,
229 param_substs: &'tcx subst::Substs<'tcx>)
230 -> Datum<'tcx, Rvalue> {
231 let _icx = push_ctxt("trans_fn_ref");
233 let substs = common::node_id_substs(ccx, node, param_substs);
234 debug!("trans_fn_ref(def_id={}, node={:?}, substs={})",
235 def_id.repr(ccx.tcx()),
237 substs.repr(ccx.tcx()));
238 trans_fn_ref_with_substs(ccx, def_id, node, param_substs, substs)
241 fn trans_fn_ref_with_substs_to_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
244 substs: subst::Substs<'tcx>)
245 -> Callee<'blk, 'tcx> {
248 data: Fn(trans_fn_ref_with_substs(bcx.ccx(),
251 bcx.fcx.param_substs,
256 /// Translates an adapter that implements the `Fn` trait for a fn
257 /// pointer. This is basically the equivalent of something like:
260 /// impl<'a> Fn(&'a int) -> &'a int for fn(&int) -> &int {
261 /// extern "rust-abi" fn call(&self, args: (&'a int,)) -> &'a int {
267 /// but for the bare function type given.
268 pub fn trans_fn_pointer_shim<'a, 'tcx>(
269 ccx: &'a CrateContext<'a, 'tcx>,
270 bare_fn_ty: Ty<'tcx>)
273 let _icx = push_ctxt("trans_fn_pointer_shim");
276 let bare_fn_ty = common::erase_regions(tcx, &bare_fn_ty);
277 match ccx.fn_pointer_shims().borrow().get(&bare_fn_ty) {
278 Some(&llval) => { return llval; }
282 debug!("trans_fn_pointer_shim(bare_fn_ty={})",
283 bare_fn_ty.repr(tcx));
285 // This is an impl of `Fn` trait, so receiver is `&self`.
286 let bare_fn_ty_ref = ty::mk_imm_rptr(tcx, tcx.mk_region(ty::ReStatic), bare_fn_ty);
288 // Construct the "tuply" version of `bare_fn_ty`. It takes two arguments: `self`,
289 // which is the fn pointer, and `args`, which is the arguments tuple.
290 let (opt_def_id, sig) =
291 match bare_fn_ty.sty {
292 ty::ty_bare_fn(opt_def_id,
293 &ty::BareFnTy { unsafety: ast::Unsafety::Normal,
300 tcx.sess.bug(&format!("trans_fn_pointer_shim invoked on invalid type: {}",
301 bare_fn_ty.repr(tcx))[]);
304 let sig = ty::erase_late_bound_regions(tcx, sig);
305 let tuple_input_ty = ty::mk_tup(tcx, sig.inputs.to_vec());
306 let tuple_fn_ty = ty::mk_bare_fn(tcx,
308 tcx.mk_bare_fn(ty::BareFnTy {
309 unsafety: ast::Unsafety::Normal,
310 abi: synabi::RustCall,
311 sig: ty::Binder(ty::FnSig {
312 inputs: vec![bare_fn_ty_ref,
317 debug!("tuple_fn_ty: {}", tuple_fn_ty.repr(tcx));
321 link::mangle_internal_name_by_type_and_seq(ccx, bare_fn_ty,
324 decl_internal_rust_fn(ccx,
329 let empty_substs = tcx.mk_substs(Substs::trans_empty());
330 let (block_arena, fcx): (TypedArena<_>, FunctionContext);
331 block_arena = TypedArena::new();
332 fcx = new_fn_ctxt(ccx,
340 let mut bcx = init_function(&fcx, false, sig.output);
342 // the first argument (`self`) will be ptr to the the fn pointer
344 Load(bcx, get_param(fcx.llfn, fcx.arg_pos(0) as u32));
346 // the remaining arguments will be the untupled values
350 .map(|(i, _)| get_param(fcx.llfn, fcx.arg_pos(i+1) as u32))
352 assert!(!fcx.needs_ret_allocas);
354 let dest = fcx.llretslotptr.get().map(|_|
355 expr::SaveIn(fcx.get_ret_slot(bcx, sig.output, "ret_slot"))
358 bcx = trans_call_inner(bcx,
361 |bcx, _| Callee { bcx: bcx, data: Fn(llfnpointer) },
365 finish_fn(&fcx, bcx, sig.output, DebugLoc::None);
367 ccx.fn_pointer_shims().borrow_mut().insert(bare_fn_ty, llfn);
372 /// Translates a reference to a fn/method item, monomorphizing and
373 /// inlining as it goes.
377 /// - `ccx`: the crate context
378 /// - `def_id`: def id of the fn or method item being referenced
379 /// - `node`: node id of the reference to the fn/method, if applicable.
380 /// This parameter may be zero; but, if so, the resulting value may not
381 /// have the right type, so it must be cast before being used.
382 /// - `param_substs`: if the `node` is in a polymorphic function, these
383 /// are the substitutions required to monomorphize its type
384 /// - `substs`: values for each of the fn/method's parameters
385 pub fn trans_fn_ref_with_substs<'a, 'tcx>(
386 ccx: &CrateContext<'a, 'tcx>,
388 node: ExprOrMethodCall,
389 param_substs: &'tcx subst::Substs<'tcx>,
390 substs: subst::Substs<'tcx>)
391 -> Datum<'tcx, Rvalue>
393 let _icx = push_ctxt("trans_fn_ref_with_substs");
396 debug!("trans_fn_ref_with_substs(def_id={}, node={:?}, \
397 param_substs={}, substs={})",
400 param_substs.repr(tcx),
403 assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
404 assert!(substs.types.all(|t| !ty::type_has_escaping_regions(*t)));
405 let substs = substs.erase_regions();
407 // Load the info for the appropriate trait if necessary.
408 match ty::trait_of_item(tcx, def_id) {
411 ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
415 // We need to do a bunch of special handling for default methods.
416 // We need to modify the def_id and our substs in order to monomorphize
418 let (is_default, def_id, substs) = match ty::provided_source(tcx, def_id) {
420 (false, def_id, tcx.mk_substs(substs))
423 // There are two relevant substitutions when compiling
424 // default methods. First, there is the substitution for
425 // the type parameters of the impl we are using and the
426 // method we are calling. This substitution is the substs
427 // argument we already have.
428 // In order to compile a default method, though, we need
429 // to consider another substitution: the substitution for
430 // the type parameters on trait; the impl we are using
431 // implements the trait at some particular type
432 // parameters, and we need to substitute for those first.
433 // So, what we need to do is find this substitution and
434 // compose it with the one we already have.
436 let impl_id = ty::impl_or_trait_item(tcx, def_id).container()
438 let impl_or_trait_item = ty::impl_or_trait_item(tcx, source_id);
439 match impl_or_trait_item {
440 ty::MethodTraitItem(method) => {
441 let trait_ref = ty::impl_trait_ref(tcx, impl_id).unwrap();
443 // Compute the first substitution
445 ty::make_substs_for_receiver_types(tcx, &*trait_ref, &*method)
449 let new_substs = tcx.mk_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 tcx.sess.bug("trans_fn_ref_with_vtables() tried \
461 to translate an associated type?!")
467 // If this is a closure, redirect to it.
468 match closure::get_or_create_declaration_if_closure(ccx, def_id, substs) {
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 MethodCallKey(_) => None,
509 let (val, fn_ty, must_cast) =
510 monomorphize::monomorphic_fn(ccx, def_id, substs, opt_ref_id);
511 if must_cast && node != ExprId(0) {
512 // Monotype of the REFERENCE to the function (type params
514 let ref_ty = match node {
515 ExprId(id) => ty::node_id_to_type(tcx, id),
516 MethodCallKey(method_call) => {
517 (*tcx.method_map.borrow())[method_call].ty
520 let ref_ty = monomorphize::apply_param_substs(tcx,
523 let llptrty = type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to();
524 if llptrty != common::val_ty(val) {
525 let val = consts::ptrcast(val, llptrty);
526 return Datum::new(val, ref_ty, Rvalue::new(ByValue));
529 return Datum::new(val, fn_ty, Rvalue::new(ByValue));
532 // Type scheme of the function item (may have type params)
533 let fn_type_scheme = ty::lookup_item_type(tcx, def_id);
534 let fn_type = monomorphize::normalize_associated_type(tcx, &fn_type_scheme.ty);
536 // Find the actual function pointer.
538 if def_id.krate == ast::LOCAL_CRATE {
539 // Internal reference.
540 get_item_val(ccx, def_id.node)
542 // External reference.
543 trans_external_path(ccx, def_id, fn_type)
547 // This is subtle and surprising, but sometimes we have to bitcast
548 // the resulting fn pointer. The reason has to do with external
549 // functions. If you have two crates that both bind the same C
550 // library, they may not use precisely the same types: for
551 // example, they will probably each declare their own structs,
552 // which are distinct types from LLVM's point of view (nominal
555 // Now, if those two crates are linked into an application, and
556 // they contain inlined code, you can wind up with a situation
557 // where both of those functions wind up being loaded into this
558 // application simultaneously. In that case, the same function
559 // (from LLVM's point of view) requires two types. But of course
560 // LLVM won't allow one function to have two types.
562 // What we currently do, therefore, is declare the function with
563 // one of the two types (whichever happens to come first) and then
564 // bitcast as needed when the function is referenced to make sure
565 // it has the type we expect.
567 // This can occur on either a crate-local or crate-external
568 // reference. It also occurs when testing libcore and in some
569 // other weird situations. Annoying.
570 let llty = type_of::type_of_fn_from_ty(ccx, fn_type);
571 let llptrty = llty.ptr_to();
572 if common::val_ty(val) != llptrty {
573 debug!("trans_fn_ref_with_vtables(): casting pointer!");
574 val = consts::ptrcast(val, llptrty);
576 debug!("trans_fn_ref_with_vtables(): not casting pointer!");
579 Datum::new(val, fn_type, Rvalue::new(ByValue))
582 // ______________________________________________________________________
585 pub fn trans_call<'a, 'blk, 'tcx>(in_cx: Block<'blk, 'tcx>,
586 call_expr: &ast::Expr,
588 args: CallArgs<'a, 'tcx>,
590 -> Block<'blk, 'tcx> {
591 let _icx = push_ctxt("trans_call");
592 trans_call_inner(in_cx,
593 call_expr.debug_loc(),
594 common::expr_ty_adjusted(in_cx, f),
595 |cx, _| trans(cx, f),
600 pub fn trans_method_call<'a, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
601 call_expr: &ast::Expr,
603 args: CallArgs<'a, 'tcx>,
605 -> Block<'blk, 'tcx> {
606 let _icx = push_ctxt("trans_method_call");
607 debug!("trans_method_call(call_expr={})", call_expr.repr(bcx.tcx()));
608 let method_call = MethodCall::expr(call_expr.id);
609 let method_ty = (*bcx.tcx().method_map.borrow())[method_call].ty;
612 call_expr.debug_loc(),
613 common::monomorphize_type(bcx, method_ty),
614 |cx, arg_cleanup_scope| {
615 meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
621 pub fn trans_lang_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
624 dest: Option<expr::Dest>,
626 -> Result<'blk, 'tcx> {
627 let fty = if did.krate == ast::LOCAL_CRATE {
628 ty::node_id_to_type(bcx.tcx(), did.node)
630 csearch::get_type(bcx.tcx(), did).ty
632 callee::trans_call_inner(bcx,
636 trans_fn_ref_with_substs_to_callee(bcx,
639 subst::Substs::trans_empty())
645 /// This behemoth of a function translates function calls. Unfortunately, in order to generate more
646 /// efficient LLVM output at -O0, it has quite a complex signature (refactoring this into two
647 /// functions seems like a good idea).
649 /// In particular, for lang items, it is invoked with a dest of None, and in that case the return
650 /// value contains the result of the fn. The lang item must not return a structural type or else
651 /// all heck breaks loose.
653 /// For non-lang items, `dest` is always Some, and hence the result is written into memory
654 /// somewhere. Nonetheless we return the actual return value of the function.
655 pub fn trans_call_inner<'a, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
659 args: CallArgs<'a, 'tcx>,
660 dest: Option<expr::Dest>)
661 -> Result<'blk, 'tcx> where
662 F: FnOnce(Block<'blk, 'tcx>, cleanup::ScopeId) -> Callee<'blk, 'tcx>,
664 // Introduce a temporary cleanup scope that will contain cleanups
665 // for the arguments while they are being evaluated. The purpose
666 // this cleanup is to ensure that, should a panic occur while
667 // evaluating argument N, the values for arguments 0...N-1 are all
668 // cleaned up. If no panic occurs, the values are handed off to
669 // the callee, and hence none of the cleanups in this temporary
670 // scope will ever execute.
673 let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
675 let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
676 let mut bcx = callee.bcx;
678 let (abi, ret_ty) = match callee_ty.sty {
679 ty::ty_bare_fn(_, ref f) => {
680 let output = ty::erase_late_bound_regions(bcx.tcx(), &f.sig.output());
683 _ => panic!("expected bare rust fn or closure in trans_call_inner")
686 let (llfn, llenv, llself) = match callee.data {
691 (d.llfn, None, Some(d.llself))
693 Intrinsic(node, substs) => {
694 assert!(abi == synabi::RustIntrinsic);
695 assert!(dest.is_some());
697 let call_info = match debug_loc {
698 DebugLoc::At(id, span) => NodeIdAndSpan { id: id, span: span },
700 bcx.sess().bug("No call info for intrinsic call?")
704 return intrinsic::trans_intrinsic_call(bcx, node, callee_ty,
705 arg_cleanup_scope, args,
706 dest.unwrap(), substs,
709 NamedTupleConstructor(substs, disr) => {
710 assert!(dest.is_some());
711 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
713 let ctor_ty = callee_ty.subst(bcx.tcx(), &substs);
714 return base::trans_named_tuple_constructor(bcx,
723 // Intrinsics should not become actual functions.
724 // We trans them in place in `trans_intrinsic_call`
725 assert!(abi != synabi::RustIntrinsic);
727 let is_rust_fn = abi == synabi::Rust || abi == synabi::RustCall;
729 // Generate a location to store the result. If the user does
730 // not care about the result, just make a stack slot.
731 let opt_llretslot = dest.and_then(|dest| match dest {
732 expr::SaveIn(dst) => Some(dst),
734 let ret_ty = match ret_ty {
735 ty::FnConverging(ret_ty) => ret_ty,
736 ty::FnDiverging => ty::mk_nil(ccx.tcx())
739 type_of::return_uses_outptr(ccx, ret_ty) ||
740 common::type_needs_drop(bcx.tcx(), ret_ty) {
741 // Push the out-pointer if we use an out-pointer for this
742 // return type, otherwise push "undef".
743 if common::type_is_zero_size(ccx, ret_ty) {
744 let llty = type_of::type_of(ccx, ret_ty);
745 Some(common::C_undef(llty.ptr_to()))
747 Some(alloc_ty(bcx, ret_ty, "__llret"))
755 let mut llresult = unsafe {
756 llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
759 // The code below invokes the function, using either the Rust
760 // conventions (if it is a rust fn) or the native conventions
761 // (otherwise). The important part is that, when all is said
762 // and done, either the return value of the function will have been
763 // written in opt_llretslot (if it is Some) or `llresult` will be
764 // set appropriately (otherwise).
766 let mut llargs = Vec::new();
768 if let (ty::FnConverging(ret_ty), Some(llretslot)) = (ret_ty, opt_llretslot) {
769 if type_of::return_uses_outptr(ccx, ret_ty) {
770 llargs.push(llretslot);
774 // Push the environment (or a trait object's self).
775 match (llenv, llself) {
776 (Some(llenv), None) => llargs.push(llenv),
777 (None, Some(llself)) => llargs.push(llself),
781 // Push the arguments.
782 bcx = trans_args(bcx,
786 cleanup::CustomScope(arg_cleanup_scope),
790 fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
792 // Invoke the actual rust fn and update bcx/llresult.
793 let (llret, b) = base::invoke(bcx,
801 // If the Rust convention for this type is return via
802 // the return value, copy it into llretslot.
803 match (opt_llretslot, ret_ty) {
804 (Some(llretslot), ty::FnConverging(ret_ty)) => {
805 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
806 !common::type_is_zero_size(bcx.ccx(), ret_ty)
808 store_ty(bcx, llret, llretslot, ret_ty)
814 // Lang items are the only case where dest is None, and
815 // they are always Rust fns.
816 assert!(dest.is_some());
818 let mut llargs = Vec::new();
819 let arg_tys = match args {
820 ArgExprs(a) => a.iter().map(|x| common::expr_ty(bcx, &**x)).collect(),
821 _ => panic!("expected arg exprs.")
823 bcx = trans_args(bcx,
827 cleanup::CustomScope(arg_cleanup_scope),
830 fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
832 bcx = foreign::trans_native_call(bcx,
835 opt_llretslot.unwrap(),
841 fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_cleanup_scope);
843 // If the caller doesn't care about the result of this fn call,
844 // drop the temporary slot we made.
845 match (dest, opt_llretslot, ret_ty) {
846 (Some(expr::Ignore), Some(llretslot), ty::FnConverging(ret_ty)) => {
847 // drop the value if it is not being saved.
848 bcx = glue::drop_ty(bcx,
852 call_lifetime_end(bcx, llretslot);
857 if ret_ty == ty::FnDiverging {
861 Result::new(bcx, llresult)
864 pub enum CallArgs<'a, 'tcx> {
865 // Supply value of arguments as a list of expressions that must be
866 // translated. This is used in the common case of `foo(bar, qux)`.
867 ArgExprs(&'a [P<ast::Expr>]),
869 // Supply value of arguments as a list of LLVM value refs; frequently
870 // used with lang items and so forth, when the argument is an internal
872 ArgVals(&'a [ValueRef]),
874 // For overloaded operators: `(lhs, Vec(rhs, rhs_id), autoref)`. `lhs`
875 // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
876 // the right-hand-side arguments (if any). `autoref` indicates whether the `rhs`
877 // arguments should be auto-referenced
878 ArgOverloadedOp(Datum<'tcx, Expr>, Vec<(Datum<'tcx, Expr>, ast::NodeId)>, bool),
880 // Supply value of arguments as a list of expressions that must be
881 // translated, for overloaded call operators.
882 ArgOverloadedCall(Vec<&'a ast::Expr>),
885 fn trans_args_under_call_abi<'blk, 'tcx>(
886 mut bcx: Block<'blk, 'tcx>,
887 arg_exprs: &[P<ast::Expr>],
889 llargs: &mut Vec<ValueRef>,
890 arg_cleanup_scope: cleanup::ScopeId,
895 ty::erase_late_bound_regions(
896 bcx.tcx(), &ty::ty_fn_args(fn_ty));
898 // Translate the `self` argument first.
900 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
901 llargs.push(unpack_result!(bcx, {
910 // Now untuple the rest of the arguments.
911 let tuple_expr = &arg_exprs[1];
912 let tuple_type = common::node_id_type(bcx, tuple_expr.id);
914 match tuple_type.sty {
915 ty::ty_tup(ref field_types) => {
916 let tuple_datum = unpack_datum!(bcx,
917 expr::trans(bcx, &**tuple_expr));
918 let tuple_lvalue_datum =
920 tuple_datum.to_lvalue_datum(bcx,
923 let repr = adt::represent_type(bcx.ccx(), tuple_type);
924 let repr_ptr = &*repr;
925 for i in 0..field_types.len() {
926 let arg_datum = tuple_lvalue_datum.get_element(
930 adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
932 let arg_datum = arg_datum.to_expr_datum();
934 unpack_datum!(bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
936 unpack_datum!(bcx, arg_datum.to_appropriate_datum(bcx));
937 llargs.push(arg_datum.add_clean(bcx.fcx, arg_cleanup_scope));
941 bcx.sess().span_bug(tuple_expr.span,
942 "argument to `.call()` wasn't a tuple?!")
949 fn trans_overloaded_call_args<'blk, 'tcx>(
950 mut bcx: Block<'blk, 'tcx>,
951 arg_exprs: Vec<&ast::Expr>,
953 llargs: &mut Vec<ValueRef>,
954 arg_cleanup_scope: cleanup::ScopeId,
956 -> Block<'blk, 'tcx> {
957 // Translate the `self` argument first.
958 let arg_tys = ty::erase_late_bound_regions(bcx.tcx(), &ty::ty_fn_args(fn_ty));
960 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, arg_exprs[0]));
961 llargs.push(unpack_result!(bcx, {
970 // Now untuple the rest of the arguments.
971 let tuple_type = arg_tys[1];
972 match tuple_type.sty {
973 ty::ty_tup(ref field_types) => {
974 for (i, &field_type) in field_types.iter().enumerate() {
976 unpack_datum!(bcx, expr::trans(bcx, arg_exprs[i + 1]));
977 llargs.push(unpack_result!(bcx, {
987 bcx.sess().span_bug(arg_exprs[0].span,
988 "argument to `.call()` wasn't a tuple?!")
995 pub fn trans_args<'a, 'blk, 'tcx>(cx: Block<'blk, 'tcx>,
996 args: CallArgs<'a, 'tcx>,
998 llargs: &mut Vec<ValueRef>,
999 arg_cleanup_scope: cleanup::ScopeId,
1002 -> Block<'blk, 'tcx> {
1003 debug!("trans_args(abi={})", abi);
1005 let _icx = push_ctxt("trans_args");
1006 let arg_tys = ty::erase_late_bound_regions(cx.tcx(), &ty::ty_fn_args(fn_ty));
1007 let variadic = ty::fn_is_variadic(fn_ty);
1011 // First we figure out the caller's view of the types of the arguments.
1012 // This will be needed if this is a generic call, because the callee has
1013 // to cast her view of the arguments to the caller's view.
1015 ArgExprs(arg_exprs) => {
1016 if abi == synabi::RustCall {
1017 // This is only used for direct calls to the `call`,
1018 // `call_mut` or `call_once` functions.
1019 return trans_args_under_call_abi(cx,
1027 let num_formal_args = arg_tys.len();
1028 for (i, arg_expr) in arg_exprs.iter().enumerate() {
1029 if i == 0 && ignore_self {
1032 let arg_ty = if i >= num_formal_args {
1034 common::expr_ty_adjusted(cx, &**arg_expr)
1039 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
1040 llargs.push(unpack_result!(bcx, {
1041 trans_arg_datum(bcx, arg_ty, arg_datum,
1047 ArgOverloadedCall(arg_exprs) => {
1048 return trans_overloaded_call_args(cx,
1055 ArgOverloadedOp(lhs, rhs, autoref) => {
1058 llargs.push(unpack_result!(bcx, {
1059 trans_arg_datum(bcx, arg_tys[0], lhs,
1064 assert_eq!(arg_tys.len(), 1 + rhs.len());
1065 for (rhs, rhs_id) in rhs {
1066 llargs.push(unpack_result!(bcx, {
1067 trans_arg_datum(bcx, arg_tys[1], rhs,
1069 if autoref { DoAutorefArg(rhs_id) } else { DontAutorefArg })
1074 llargs.push_all(vs);
1082 pub enum AutorefArg {
1084 DoAutorefArg(ast::NodeId)
1087 pub fn trans_arg_datum<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1088 formal_arg_ty: Ty<'tcx>,
1089 arg_datum: Datum<'tcx, Expr>,
1090 arg_cleanup_scope: cleanup::ScopeId,
1091 autoref_arg: AutorefArg)
1092 -> Result<'blk, 'tcx> {
1093 let _icx = push_ctxt("trans_arg_datum");
1095 let ccx = bcx.ccx();
1097 debug!("trans_arg_datum({})",
1098 formal_arg_ty.repr(bcx.tcx()));
1100 let arg_datum_ty = arg_datum.ty;
1102 debug!(" arg datum: {}", arg_datum.to_string(bcx.ccx()));
1105 // FIXME(#3548) use the adjustments table
1107 DoAutorefArg(arg_id) => {
1108 // We will pass argument by reference
1109 // We want an lvalue, so that we can pass by reference and
1110 let arg_datum = unpack_datum!(
1111 bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
1112 val = arg_datum.val;
1115 // Make this an rvalue, since we are going to be
1116 // passing ownership.
1117 let arg_datum = unpack_datum!(
1118 bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
1120 // Now that arg_datum is owned, get it into the appropriate
1121 // mode (ref vs value).
1122 let arg_datum = unpack_datum!(
1123 bcx, arg_datum.to_appropriate_datum(bcx));
1125 // Technically, ownership of val passes to the callee.
1126 // However, we must cleanup should we panic before the
1127 // callee is actually invoked.
1128 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
1132 if formal_arg_ty != arg_datum_ty {
1133 // this could happen due to e.g. subtyping
1134 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1135 debug!("casting actual type ({}) to match formal ({})",
1136 bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty));
1137 debug!("Rust types: {}; {}", ty_to_string(bcx.tcx(), arg_datum_ty),
1138 ty_to_string(bcx.tcx(), formal_arg_ty));
1139 val = PointerCast(bcx, val, llformal_arg_ty);
1142 debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val));
1143 Result::new(bcx, val)