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, VecPerParamSpace};
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::datum::{Datum, KindOps};
41 use middle::trans::expr;
42 use middle::trans::glue;
43 use middle::trans::inline;
44 use middle::trans::foreign;
45 use middle::trans::intrinsic;
46 use middle::trans::meth;
47 use middle::trans::monomorphize;
48 use middle::trans::type_::Type;
49 use middle::trans::type_of;
52 use middle::typeck::coherence::make_substs_for_receiver_types;
53 use middle::typeck::MethodCall;
54 use util::ppaux::Repr;
59 use synabi = syntax::abi;
61 pub struct MethodData {
67 Closure(Datum<Lvalue>),
69 // Constructor for enum variant/tuple-like-struct
71 NamedTupleConstructor(subst::Substs, ty::Disr),
73 // Represents a (possibly monomorphized) top-level fn item or method
74 // item. Note that this is just the fn-ptr and is not a Rust closure
75 // value (which is a pair).
76 Fn(/* llfn */ ValueRef),
78 Intrinsic(ast::NodeId, subst::Substs),
80 TraitMethod(MethodData)
83 pub struct Callee<'a> {
84 pub bcx: &'a Block<'a>,
88 fn trans<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
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<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
104 let DatumBlock {bcx: mut bcx, datum} = expr::trans(bcx, expr);
105 match ty::get(datum.ty).sty {
106 ty::ty_bare_fn(..) => {
107 let llval = datum.to_llscalarish(bcx);
113 ty::ty_closure(..) => {
114 let datum = unpack_datum!(
115 bcx, datum.to_lvalue_datum(bcx, "callee", expr.id));
118 data: Closure(datum),
122 bcx.tcx().sess.span_bug(
124 format!("type of callee is neither bare-fn nor closure: \
126 bcx.ty_to_string(datum.ty)).as_slice());
131 fn fn_callee<'a>(bcx: &'a Block<'a>, llfn: ValueRef) -> Callee<'a> {
138 fn trans_def<'a>(bcx: &'a Block<'a>, def: def::Def, ref_expr: &ast::Expr)
140 debug!("trans_def(def={}, ref_expr={})", def.repr(bcx.tcx()), ref_expr.repr(bcx.tcx()));
141 let expr_ty = node_id_type(bcx, ref_expr.id);
143 def::DefFn(did, _) if {
144 let def_id = if did.krate != ast::LOCAL_CRATE {
145 inline::maybe_instantiate_inline(bcx.ccx(), did)
149 match bcx.tcx().map.find(def_id.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 = if did.krate != ast::LOCAL_CRATE {
166 inline::maybe_instantiate_inline(bcx.ccx(), did)
170 Callee { bcx: bcx, data: Intrinsic(def_id.node, substs) }
173 def::DefStaticMethod(did, def::FromImpl(_), _) => {
174 fn_callee(bcx, trans_fn_ref(bcx, did, ExprId(ref_expr.id)))
176 def::DefStaticMethod(impl_did,
177 def::FromTrait(trait_did),
179 fn_callee(bcx, meth::trans_static_method_callee(bcx, impl_did,
183 def::DefVariant(tid, vid, _) => {
184 let vinfo = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
185 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
187 // Nullary variants are not callable
188 assert!(vinfo.args.len() > 0u);
192 data: NamedTupleConstructor(substs, vinfo.disr_val)
195 def::DefStruct(_) => {
196 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
199 data: NamedTupleConstructor(substs, 0)
205 def::DefBinding(..) |
206 def::DefUpvar(..) => {
207 datum_callee(bcx, ref_expr)
209 def::DefMod(..) | def::DefForeignMod(..) | def::DefTrait(..) |
210 def::DefTy(..) | def::DefPrimTy(..) |
211 def::DefUse(..) | def::DefTyParamBinder(..) |
212 def::DefRegion(..) | def::DefLabel(..) | def::DefTyParam(..) |
213 def::DefSelfTy(..) | def::DefMethod(..) => {
214 bcx.tcx().sess.span_bug(
216 format!("cannot translate def {:?} \
217 to a callable thing!", def).as_slice());
223 pub fn trans_fn_ref(bcx: &Block, def_id: ast::DefId, node: ExprOrMethodCall) -> ValueRef {
225 * Translates a reference (with id `ref_id`) to the fn/method
226 * with id `def_id` into a function pointer. This may require
227 * monomorphization or inlining.
230 let _icx = push_ctxt("trans_fn_ref");
232 let substs = node_id_substs(bcx, node);
233 let vtable_key = match node {
234 ExprId(id) => MethodCall::expr(id),
235 MethodCall(method_call) => method_call
237 let vtables = node_vtables(bcx, vtable_key);
238 debug!("trans_fn_ref(def_id={}, node={:?}, substs={}, vtables={})",
239 def_id.repr(bcx.tcx()),
241 substs.repr(bcx.tcx()),
242 vtables.repr(bcx.tcx()));
243 trans_fn_ref_with_vtables(bcx, def_id, node, substs, vtables)
246 fn trans_fn_ref_with_vtables_to_callee<'a>(bcx: &'a Block<'a>,
249 substs: subst::Substs,
250 vtables: typeck::vtable_res)
254 data: Fn(trans_fn_ref_with_vtables(bcx,
262 fn resolve_default_method_vtables(bcx: &Block,
264 substs: &subst::Substs,
265 impl_vtables: typeck::vtable_res)
266 -> typeck::vtable_res
268 // Get the vtables that the impl implements the trait at
269 let impl_res = ty::lookup_impl_vtables(bcx.tcx(), impl_id);
271 // Build up a param_substs that we are going to resolve the
272 // trait_vtables under.
273 let param_substs = param_substs {
274 substs: (*substs).clone(),
275 vtables: impl_vtables.clone()
278 let mut param_vtables = resolve_vtables_under_param_substs(
279 bcx.tcx(), ¶m_substs, &impl_res);
281 // Now we pull any vtables for parameters on the actual method.
282 param_vtables.push_all(subst::FnSpace,
283 impl_vtables.get_slice(subst::FnSpace));
288 /// Translates the adapter that deconstructs a `Box<Trait>` object into
289 /// `Trait` so that a by-value self method can be called.
290 pub fn trans_unboxing_shim(bcx: &Block,
291 llshimmedfn: ValueRef,
293 method_id: ast::DefId,
294 substs: subst::Substs)
296 let _icx = push_ctxt("trans_unboxing_shim");
300 // Transform the self type to `Box<self_type>`.
301 let self_type = *method.fty.sig.inputs.get(0);
302 let boxed_self_type = ty::mk_uniq(tcx, self_type);
303 let boxed_function_type = ty::FnSig {
304 binder_id: method.fty.sig.binder_id,
305 inputs: method.fty.sig.inputs.iter().enumerate().map(|(i, typ)| {
312 output: method.fty.sig.output,
315 let boxed_function_type = ty::BareFnTy {
316 fn_style: method.fty.fn_style,
318 sig: boxed_function_type,
320 let boxed_function_type =
321 ty::mk_bare_fn(tcx, boxed_function_type).subst(tcx, &substs);
323 ty::mk_bare_fn(tcx, method.fty.clone()).subst(tcx, &substs);
325 let function_name = ty::with_path(tcx, method_id, |path| {
326 link::mangle_internal_name_by_path_and_seq(path, "unboxing_shim")
328 let llfn = decl_internal_rust_fn(ccx,
330 function_name.as_slice());
332 let block_arena = TypedArena::new();
333 let empty_param_substs = param_substs::empty();
334 let return_type = ty::ty_fn_ret(boxed_function_type);
335 let fcx = new_fn_ctxt(ccx,
343 let mut bcx = init_function(&fcx, false, return_type);
345 // Create the substituted versions of the self type.
346 let arg_scope = fcx.push_custom_cleanup_scope();
347 let arg_scope_id = cleanup::CustomScope(arg_scope);
348 let boxed_arg_types = ty::ty_fn_args(boxed_function_type);
349 let boxed_self_type = *boxed_arg_types.get(0);
350 let arg_types = ty::ty_fn_args(function_type);
351 let self_type = *arg_types.get(0);
352 let boxed_self_kind = arg_kind(&fcx, boxed_self_type);
354 // Create a datum for self.
355 let llboxedself = get_param(fcx.llfn, fcx.arg_pos(0) as u32);
356 let llboxedself = Datum::new(llboxedself,
361 llboxedself.to_lvalue_datum_in_scope(bcx,
365 // This `Load` is needed because lvalue data are always by-ref.
366 let llboxedself = Load(bcx, boxed_self.val);
368 let llself = if type_is_immediate(ccx, self_type) {
369 let llboxedself = Load(bcx, llboxedself);
370 immediate_rvalue(llboxedself, self_type)
372 let llself = rvalue_scratch_datum(bcx, self_type, "self");
373 memcpy_ty(bcx, llself.val, llboxedself, self_type);
377 // Make sure we don't free the box twice!
378 boxed_self.kind.post_store(bcx, boxed_self.val, boxed_self_type);
380 // Schedule a cleanup to free the box.
381 fcx.schedule_free_value(arg_scope_id,
383 cleanup::HeapExchange,
386 // Now call the function.
387 let mut llshimmedargs = vec!(llself.val);
388 for i in range(1, arg_types.len()) {
389 llshimmedargs.push(get_param(fcx.llfn, fcx.arg_pos(i) as u32));
391 bcx = trans_call_inner(bcx,
397 data: Fn(llshimmedfn),
400 ArgVals(llshimmedargs.as_slice()),
401 match fcx.llretptr.get() {
403 Some(llretptr) => Some(expr::SaveIn(llretptr)),
406 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
407 finish_fn(&fcx, bcx, return_type);
412 pub fn trans_fn_ref_with_vtables(
414 def_id: ast::DefId, // def id of fn
415 node: ExprOrMethodCall, // node id of use of fn; may be zero if N/A
416 substs: subst::Substs, // values for fn's ty params
417 vtables: typeck::vtable_res) // vtables for the call
421 * Translates a reference to a fn/method item, monomorphizing and
422 * inlining as it goes.
426 * - `bcx`: the current block where the reference to the fn occurs
427 * - `def_id`: def id of the fn or method item being referenced
428 * - `node`: node id of the reference to the fn/method, if applicable.
429 * This parameter may be zero; but, if so, the resulting value may not
430 * have the right type, so it must be cast before being used.
431 * - `substs`: values for each of the fn/method's parameters
432 * - `vtables`: values for each bound on each of the type parameters
435 let _icx = push_ctxt("trans_fn_ref_with_vtables");
439 debug!("trans_fn_ref_with_vtables(bcx={}, def_id={}, node={:?}, \
440 substs={}, vtables={})",
447 assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
449 // Load the info for the appropriate trait if necessary.
450 match ty::trait_of_method(tcx, def_id) {
453 ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
457 // We need to do a bunch of special handling for default methods.
458 // We need to modify the def_id and our substs in order to monomorphize
460 let (is_default, def_id, substs, vtables) =
461 match ty::provided_source(tcx, def_id) {
462 None => (false, def_id, substs, vtables),
464 // There are two relevant substitutions when compiling
465 // default methods. First, there is the substitution for
466 // the type parameters of the impl we are using and the
467 // method we are calling. This substitution is the substs
468 // argument we already have.
469 // In order to compile a default method, though, we need
470 // to consider another substitution: the substitution for
471 // the type parameters on trait; the impl we are using
472 // implements the trait at some particular type
473 // parameters, and we need to substitute for those first.
474 // So, what we need to do is find this substitution and
475 // compose it with the one we already have.
477 let impl_id = ty::method(tcx, def_id).container_id();
478 let method = ty::method(tcx, source_id);
479 let trait_ref = ty::impl_trait_ref(tcx, impl_id)
480 .expect("could not find trait_ref for impl with \
483 // Compute the first substitution
484 let first_subst = make_substs_for_receiver_types(
485 tcx, &*trait_ref, &*method);
488 let new_substs = first_subst.subst(tcx, &substs);
490 debug!("trans_fn_with_vtables - default method: \
491 substs = {}, trait_subst = {}, \
492 first_subst = {}, new_subst = {}, \
494 substs.repr(tcx), trait_ref.substs.repr(tcx),
495 first_subst.repr(tcx), new_substs.repr(tcx),
499 resolve_default_method_vtables(bcx, impl_id, &substs, vtables);
501 debug!("trans_fn_with_vtables - default method: \
503 param_vtables.repr(tcx));
505 (true, source_id, new_substs, param_vtables)
509 // If this is an unboxed closure, redirect to it.
510 match closure::get_or_create_declaration_if_unboxed_closure(ccx, def_id) {
512 Some(llfn) => return llfn,
515 // Check whether this fn has an inlined copy and, if so, redirect
516 // def_id to the local id of the inlined copy.
518 if def_id.krate != ast::LOCAL_CRATE {
519 inline::maybe_instantiate_inline(ccx, def_id)
525 // We must monomorphise if the fn has type parameters, is a default method,
526 // or is a named tuple constructor.
527 let must_monomorphise = if !substs.types.is_empty() || is_default {
529 } else if def_id.krate == ast::LOCAL_CRATE {
530 let map_node = session::expect(
532 tcx.map.find(def_id.node),
533 || "local item should be in ast map".to_string());
536 ast_map::NodeVariant(v) => match v.node.kind {
537 ast::TupleVariantKind(ref args) => args.len() > 0,
540 ast_map::NodeStructCtor(_) => true,
547 // Create a monomorphic version of generic functions
548 if must_monomorphise {
549 // Should be either intra-crate or inlined.
550 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
552 let opt_ref_id = match node {
553 ExprId(id) => if id != 0 { Some(id) } else { None },
554 MethodCall(_) => None,
557 let (val, must_cast) =
558 monomorphize::monomorphic_fn(ccx, def_id, &substs,
559 vtables, opt_ref_id);
561 if must_cast && node != ExprId(0) {
562 // Monotype of the REFERENCE to the function (type params
564 let ref_ty = match node {
565 ExprId(id) => node_id_type(bcx, id),
566 MethodCall(method_call) => {
567 let t = bcx.tcx().method_map.borrow().get(&method_call).ty;
568 monomorphize_type(bcx, t)
573 bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
578 // Polytype of the function item (may have type params)
579 let fn_tpt = ty::lookup_item_type(tcx, def_id);
581 // Find the actual function pointer.
583 if def_id.krate == ast::LOCAL_CRATE {
584 // Internal reference.
585 get_item_val(ccx, def_id.node)
587 // External reference.
588 trans_external_path(ccx, def_id, fn_tpt.ty)
592 // This is subtle and surprising, but sometimes we have to bitcast
593 // the resulting fn pointer. The reason has to do with external
594 // functions. If you have two crates that both bind the same C
595 // library, they may not use precisely the same types: for
596 // example, they will probably each declare their own structs,
597 // which are distinct types from LLVM's point of view (nominal
600 // Now, if those two crates are linked into an application, and
601 // they contain inlined code, you can wind up with a situation
602 // where both of those functions wind up being loaded into this
603 // application simultaneously. In that case, the same function
604 // (from LLVM's point of view) requires two types. But of course
605 // LLVM won't allow one function to have two types.
607 // What we currently do, therefore, is declare the function with
608 // one of the two types (whichever happens to come first) and then
609 // bitcast as needed when the function is referenced to make sure
610 // it has the type we expect.
612 // This can occur on either a crate-local or crate-external
613 // reference. It also occurs when testing libcore and in some
614 // other weird situations. Annoying.
615 let llty = type_of::type_of_fn_from_ty(ccx, fn_tpt.ty);
616 let llptrty = llty.ptr_to();
617 if val_ty(val) != llptrty {
618 debug!("trans_fn_ref_with_vtables(): casting pointer!");
619 val = BitCast(bcx, val, llptrty);
621 debug!("trans_fn_ref_with_vtables(): not casting pointer!");
627 // ______________________________________________________________________
630 pub fn trans_call<'a>(
631 in_cx: &'a Block<'a>,
637 let _icx = push_ctxt("trans_call");
638 trans_call_inner(in_cx,
639 Some(common::expr_info(call_ex)),
641 |cx, _| trans(cx, f),
646 pub fn trans_method_call<'a>(
653 let _icx = push_ctxt("trans_method_call");
654 debug!("trans_method_call(call_ex={})", call_ex.repr(bcx.tcx()));
655 let method_call = MethodCall::expr(call_ex.id);
656 let method_ty = bcx.tcx().method_map.borrow().get(&method_call).ty;
659 Some(common::expr_info(call_ex)),
660 monomorphize_type(bcx, method_ty),
661 |cx, arg_cleanup_scope| {
662 meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
668 pub fn trans_lang_call<'a>(
672 dest: Option<expr::Dest>)
674 let fty = if did.krate == ast::LOCAL_CRATE {
675 ty::node_id_to_type(bcx.tcx(), did.node)
677 csearch::get_type(bcx.tcx(), did).ty
679 callee::trans_call_inner(bcx,
683 trans_fn_ref_with_vtables_to_callee(bcx,
686 subst::Substs::empty(),
687 VecPerParamSpace::empty())
693 pub fn trans_call_inner<'a>(
695 call_info: Option<NodeInfo>,
697 get_callee: |bcx: &'a Block<'a>,
698 arg_cleanup_scope: cleanup::ScopeId|
701 dest: Option<expr::Dest>)
704 * This behemoth of a function translates function calls.
705 * Unfortunately, in order to generate more efficient LLVM
706 * output at -O0, it has quite a complex signature (refactoring
707 * this into two functions seems like a good idea).
709 * In particular, for lang items, it is invoked with a dest of
710 * None, and in that case the return value contains the result of
711 * the fn. The lang item must not return a structural type or else
712 * all heck breaks loose.
714 * For non-lang items, `dest` is always Some, and hence the result
715 * is written into memory somewhere. Nonetheless we return the
716 * actual return value of the function.
719 // Introduce a temporary cleanup scope that will contain cleanups
720 // for the arguments while they are being evaluated. The purpose
721 // this cleanup is to ensure that, should a failure occur while
722 // evaluating argument N, the values for arguments 0...N-1 are all
723 // cleaned up. If no failure occurs, the values are handed off to
724 // the callee, and hence none of the cleanups in this temporary
725 // scope will ever execute.
728 let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
730 let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
731 let mut bcx = callee.bcx;
733 let (abi, ret_ty) = match ty::get(callee_ty).sty {
734 ty::ty_bare_fn(ref f) => (f.abi, f.sig.output),
735 ty::ty_closure(ref f) => (f.abi, f.sig.output),
736 _ => fail!("expected bare rust fn or closure in trans_call_inner")
739 let (llfn, llenv, llself) = match callee.data {
744 (d.llfn, None, Some(d.llself))
747 // Closures are represented as (llfn, llclosure) pair:
748 // load the requisite values out.
749 let pair = d.to_llref();
750 let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]);
751 let llfn = Load(bcx, llfn);
752 let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]);
753 let llenv = Load(bcx, llenv);
754 (llfn, Some(llenv), None)
756 Intrinsic(node, substs) => {
757 assert!(abi == synabi::RustIntrinsic);
758 assert!(dest.is_some());
760 return intrinsic::trans_intrinsic_call(bcx, node, callee_ty,
761 arg_cleanup_scope, args,
762 dest.unwrap(), substs);
764 NamedTupleConstructor(substs, disr) => {
765 assert!(dest.is_some());
766 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
768 let ctor_ty = callee_ty.subst(bcx.tcx(), &substs);
769 return base::trans_named_tuple_constructor(bcx, ctor_ty, disr,
770 args, dest.unwrap());
774 // Intrinsics should not become actual functions.
775 // We trans them in place in `trans_intrinsic_call`
776 assert!(abi != synabi::RustIntrinsic);
778 // Generate a location to store the result. If the user does
779 // not care about the result, just make a stack slot.
780 let opt_llretslot = match dest {
782 assert!(!type_of::return_uses_outptr(ccx, ret_ty));
785 Some(expr::SaveIn(dst)) => Some(dst),
786 Some(expr::Ignore) => {
787 if !type_is_zero_size(ccx, ret_ty) {
788 Some(alloc_ty(bcx, ret_ty, "__llret"))
790 let llty = type_of::type_of(ccx, ret_ty);
791 Some(C_undef(llty.ptr_to()))
796 let mut llresult = unsafe {
797 llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
800 // The code below invokes the function, using either the Rust
801 // conventions (if it is a rust fn) or the native conventions
802 // (otherwise). The important part is that, when all is sad
803 // and done, either the return value of the function will have been
804 // written in opt_llretslot (if it is Some) or `llresult` will be
805 // set appropriately (otherwise).
806 if abi == synabi::Rust || abi == synabi::RustCall {
807 let mut llargs = Vec::new();
809 // Push the out-pointer if we use an out-pointer for this
810 // return type, otherwise push "undef".
811 if type_of::return_uses_outptr(ccx, ret_ty) {
812 llargs.push(opt_llretslot.unwrap());
815 // Push the environment (or a trait object's self).
816 match (llenv, llself) {
817 (Some(llenv), None) => {
820 (None, Some(llself)) => llargs.push(llself),
824 // Push the arguments.
825 bcx = trans_args(bcx,
829 cleanup::CustomScope(arg_cleanup_scope),
833 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
835 // Invoke the actual rust fn and update bcx/llresult.
836 let (llret, b) = base::invoke(bcx,
844 // If the Rust convention for this type is return via
845 // the return value, copy it into llretslot.
846 match opt_llretslot {
848 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
849 !type_is_zero_size(bcx.ccx(), ret_ty)
851 store_ty(bcx, llret, llretslot, ret_ty)
857 // Lang items are the only case where dest is None, and
858 // they are always Rust fns.
859 assert!(dest.is_some());
861 let mut llargs = Vec::new();
862 let arg_tys = match args {
863 ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, &**x)).collect(),
864 _ => fail!("expected arg exprs.")
866 bcx = trans_args(bcx,
870 cleanup::CustomScope(arg_cleanup_scope),
873 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
874 bcx = foreign::trans_native_call(bcx, callee_ty,
875 llfn, opt_llretslot.unwrap(),
876 llargs.as_slice(), arg_tys);
879 // If the caller doesn't care about the result of this fn call,
880 // drop the temporary slot we made.
883 assert!(!type_of::return_uses_outptr(bcx.ccx(), ret_ty));
885 Some(expr::Ignore) => {
886 // drop the value if it is not being saved.
887 bcx = glue::drop_ty(bcx, opt_llretslot.unwrap(), ret_ty);
889 Some(expr::SaveIn(_)) => { }
892 if ty::type_is_bot(ret_ty) {
896 Result::new(bcx, llresult)
899 pub enum CallArgs<'a> {
900 // Supply value of arguments as a list of expressions that must be
901 // translated. This is used in the common case of `foo(bar, qux)`.
902 ArgExprs(&'a [Gc<ast::Expr>]),
904 // Supply value of arguments as a list of LLVM value refs; frequently
905 // used with lang items and so forth, when the argument is an internal
907 ArgVals(&'a [ValueRef]),
909 // For overloaded operators: `(lhs, Option(rhs, rhs_id))`. `lhs`
910 // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
911 // the right-hand-side (if any).
912 ArgOverloadedOp(Datum<Expr>, Option<(Datum<Expr>, ast::NodeId)>),
914 // Supply value of arguments as a list of expressions that must be
915 // translated, for overloaded call operators.
916 ArgOverloadedCall(&'a [Gc<ast::Expr>]),
919 fn trans_args_under_call_abi<'a>(
920 mut bcx: &'a Block<'a>,
921 arg_exprs: &[Gc<ast::Expr>],
923 llargs: &mut Vec<ValueRef>,
924 arg_cleanup_scope: cleanup::ScopeId,
927 // Translate the `self` argument first.
928 let arg_tys = ty::ty_fn_args(fn_ty);
930 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
931 llargs.push(unpack_result!(bcx, {
940 // Now untuple the rest of the arguments.
941 let tuple_expr = arg_exprs[1];
942 let tuple_type = node_id_type(bcx, tuple_expr.id);
944 match ty::get(tuple_type).sty {
945 ty::ty_tup(ref field_types) => {
946 let tuple_datum = unpack_datum!(bcx,
947 expr::trans(bcx, &*tuple_expr));
948 let tuple_lvalue_datum =
950 tuple_datum.to_lvalue_datum(bcx,
953 let repr = adt::represent_type(bcx.ccx(), tuple_type);
954 let repr_ptr = &*repr;
955 for i in range(0, field_types.len()) {
956 let arg_datum = tuple_lvalue_datum.get_element(
959 adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
961 let arg_datum = arg_datum.to_expr_datum();
963 unpack_datum!(bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
965 unpack_datum!(bcx, arg_datum.to_appropriate_datum(bcx));
966 llargs.push(arg_datum.add_clean(bcx.fcx, arg_cleanup_scope));
971 bcx.sess().span_bug(tuple_expr.span,
972 "argument to `.call()` wasn't a tuple?!")
979 fn trans_overloaded_call_args<'a>(
980 mut bcx: &'a Block<'a>,
981 arg_exprs: &[Gc<ast::Expr>],
983 llargs: &mut Vec<ValueRef>,
984 arg_cleanup_scope: cleanup::ScopeId,
987 // Translate the `self` argument first.
988 let arg_tys = ty::ty_fn_args(fn_ty);
990 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
991 llargs.push(unpack_result!(bcx, {
1000 // Now untuple the rest of the arguments.
1001 let tuple_type = *arg_tys.get(1);
1002 match ty::get(tuple_type).sty {
1003 ty::ty_tup(ref field_types) => {
1004 for (i, &field_type) in field_types.iter().enumerate() {
1006 unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[i + 1]));
1007 llargs.push(unpack_result!(bcx, {
1008 trans_arg_datum(bcx,
1018 bcx.sess().span_bug(arg_exprs[0].span,
1019 "argument to `.call()` wasn't a tuple?!")
1026 pub fn trans_args<'a>(
1030 llargs: &mut Vec<ValueRef> ,
1031 arg_cleanup_scope: cleanup::ScopeId,
1035 debug!("trans_args(abi={})", abi);
1037 let _icx = push_ctxt("trans_args");
1038 let arg_tys = ty::ty_fn_args(fn_ty);
1039 let variadic = ty::fn_is_variadic(fn_ty);
1043 // First we figure out the caller's view of the types of the arguments.
1044 // This will be needed if this is a generic call, because the callee has
1045 // to cast her view of the arguments to the caller's view.
1047 ArgExprs(arg_exprs) => {
1048 if abi == synabi::RustCall {
1049 // This is only used for direct calls to the `call`,
1050 // `call_mut` or `call_once` functions.
1051 return trans_args_under_call_abi(cx,
1059 let num_formal_args = arg_tys.len();
1060 for (i, arg_expr) in arg_exprs.iter().enumerate() {
1061 if i == 0 && ignore_self {
1064 let arg_ty = if i >= num_formal_args {
1066 expr_ty_adjusted(cx, &**arg_expr)
1071 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
1072 llargs.push(unpack_result!(bcx, {
1073 trans_arg_datum(bcx, arg_ty, arg_datum,
1079 ArgOverloadedCall(arg_exprs) => {
1080 return trans_overloaded_call_args(cx,
1087 ArgOverloadedOp(lhs, rhs) => {
1090 llargs.push(unpack_result!(bcx, {
1091 trans_arg_datum(bcx, *arg_tys.get(0), lhs,
1097 Some((rhs, rhs_id)) => {
1098 assert_eq!(arg_tys.len(), 2);
1100 llargs.push(unpack_result!(bcx, {
1101 trans_arg_datum(bcx, *arg_tys.get(1), rhs,
1103 DoAutorefArg(rhs_id))
1106 None => assert_eq!(arg_tys.len(), 1)
1110 llargs.push_all(vs);
1117 pub enum AutorefArg {
1119 DoAutorefArg(ast::NodeId)
1122 pub fn trans_arg_datum<'a>(
1124 formal_arg_ty: ty::t,
1125 arg_datum: Datum<Expr>,
1126 arg_cleanup_scope: cleanup::ScopeId,
1127 autoref_arg: AutorefArg)
1129 let _icx = push_ctxt("trans_arg_datum");
1131 let ccx = bcx.ccx();
1133 debug!("trans_arg_datum({})",
1134 formal_arg_ty.repr(bcx.tcx()));
1136 let arg_datum_ty = arg_datum.ty;
1138 debug!(" arg datum: {}", arg_datum.to_string(bcx.ccx()));
1141 if ty::type_is_bot(arg_datum_ty) {
1142 // For values of type _|_, we generate an
1143 // "undef" value, as such a value should never
1144 // be inspected. It's important for the value
1145 // to have type lldestty (the callee's expected type).
1146 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1148 val = llvm::LLVMGetUndef(llformal_arg_ty.to_ref());
1151 // FIXME(#3548) use the adjustments table
1153 DoAutorefArg(arg_id) => {
1154 // We will pass argument by reference
1155 // We want an lvalue, so that we can pass by reference and
1156 let arg_datum = unpack_datum!(
1157 bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
1158 val = arg_datum.val;
1161 // Make this an rvalue, since we are going to be
1162 // passing ownership.
1163 let arg_datum = unpack_datum!(
1164 bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
1166 // Now that arg_datum is owned, get it into the appropriate
1167 // mode (ref vs value).
1168 let arg_datum = unpack_datum!(
1169 bcx, arg_datum.to_appropriate_datum(bcx));
1171 // Technically, ownership of val passes to the callee.
1172 // However, we must cleanup should we fail before the
1173 // callee is actually invoked.
1174 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
1178 if formal_arg_ty != arg_datum_ty {
1179 // this could happen due to e.g. subtyping
1180 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1181 debug!("casting actual type ({}) to match formal ({})",
1182 bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty));
1183 val = PointerCast(bcx, val, llformal_arg_ty);
1187 debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val));
1188 Result::new(bcx, val)