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;
22 use llvm::{ValueRef, get_param};
24 use metadata::csearch;
27 use middle::subst::{Subst, VecPerParamSpace};
28 use middle::trans::adt;
29 use middle::trans::base;
30 use middle::trans::base::*;
31 use middle::trans::build::*;
32 use middle::trans::callee;
33 use middle::trans::cleanup;
34 use middle::trans::cleanup::CleanupMethods;
35 use middle::trans::closure;
36 use middle::trans::common;
37 use middle::trans::common::*;
38 use middle::trans::datum::*;
39 use middle::trans::datum::{Datum, KindOps};
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;
51 use middle::typeck::coherence::make_substs_for_receiver_types;
52 use middle::typeck::MethodCall;
53 use util::ppaux::Repr;
57 use synabi = syntax::abi;
59 pub struct MethodData {
65 Closure(Datum<Lvalue>),
67 // Constructor for enum variant/tuple-like-struct
69 TupleVariantConstructor(subst::Substs, 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),
78 TraitMethod(MethodData)
81 pub struct Callee<'a> {
82 pub bcx: &'a Block<'a>,
86 fn trans<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
87 let _icx = push_ctxt("trans_callee");
88 debug!("callee::trans(expr={})", expr.repr(bcx.tcx()));
90 // pick out special kinds of expressions that can be called:
93 return trans_def(bcx, bcx.def(expr.id), expr);
98 // any other expressions are closures:
99 return datum_callee(bcx, expr);
101 fn datum_callee<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
102 let DatumBlock {bcx: mut bcx, datum} = expr::trans(bcx, expr);
103 match ty::get(datum.ty).sty {
104 ty::ty_bare_fn(..) => {
105 let llval = datum.to_llscalarish(bcx);
111 ty::ty_closure(..) => {
112 let datum = unpack_datum!(
113 bcx, datum.to_lvalue_datum(bcx, "callee", expr.id));
116 data: Closure(datum),
120 bcx.tcx().sess.span_bug(
122 format!("type of callee is neither bare-fn nor closure: \
124 bcx.ty_to_string(datum.ty)).as_slice());
129 fn fn_callee<'a>(bcx: &'a Block<'a>, llfn: ValueRef) -> Callee<'a> {
136 fn trans_def<'a>(bcx: &'a Block<'a>, def: def::Def, ref_expr: &ast::Expr)
138 debug!("trans_def(def={}, ref_expr={})", def.repr(bcx.tcx()), ref_expr.repr(bcx.tcx()));
139 let expr_ty = node_id_type(bcx, ref_expr.id);
141 def::DefFn(did, _) if match ty::get(expr_ty).sty {
142 ty::ty_bare_fn(ref f) => f.abi == synabi::RustIntrinsic,
145 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
146 let def_id = if did.krate != ast::LOCAL_CRATE {
147 inline::maybe_instantiate_inline(bcx.ccx(), did)
151 Callee { bcx: bcx, data: Intrinsic(def_id.node, substs) }
154 def::DefStaticMethod(did, def::FromImpl(_), _) => {
155 fn_callee(bcx, trans_fn_ref(bcx, did, ExprId(ref_expr.id)))
157 def::DefStaticMethod(impl_did,
158 def::FromTrait(trait_did),
160 fn_callee(bcx, meth::trans_static_method_callee(bcx, impl_did,
164 def::DefVariant(tid, vid, _) => {
165 let vinfo = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
166 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
168 // Nullary variants are not callable
169 assert!(vinfo.args.len() > 0u);
173 data: TupleVariantConstructor(substs, vinfo.disr_val)
176 def::DefStruct(def_id) => {
177 fn_callee(bcx, trans_fn_ref(bcx, def_id, ExprId(ref_expr.id)))
182 def::DefBinding(..) |
183 def::DefUpvar(..) => {
184 datum_callee(bcx, ref_expr)
186 def::DefMod(..) | def::DefForeignMod(..) | def::DefTrait(..) |
187 def::DefTy(..) | def::DefPrimTy(..) |
188 def::DefUse(..) | def::DefTyParamBinder(..) |
189 def::DefRegion(..) | def::DefLabel(..) | def::DefTyParam(..) |
190 def::DefSelfTy(..) | def::DefMethod(..) => {
191 bcx.tcx().sess.span_bug(
193 format!("cannot translate def {:?} \
194 to a callable thing!", def).as_slice());
200 pub fn trans_fn_ref(bcx: &Block, def_id: ast::DefId, node: ExprOrMethodCall) -> ValueRef {
202 * Translates a reference (with id `ref_id`) to the fn/method
203 * with id `def_id` into a function pointer. This may require
204 * monomorphization or inlining.
207 let _icx = push_ctxt("trans_fn_ref");
209 let substs = node_id_substs(bcx, node);
210 let vtable_key = match node {
211 ExprId(id) => MethodCall::expr(id),
212 MethodCall(method_call) => method_call
214 let vtables = node_vtables(bcx, vtable_key);
215 debug!("trans_fn_ref(def_id={}, node={:?}, substs={}, vtables={})",
216 def_id.repr(bcx.tcx()),
218 substs.repr(bcx.tcx()),
219 vtables.repr(bcx.tcx()));
220 trans_fn_ref_with_vtables(bcx, def_id, node, substs, vtables)
223 fn trans_fn_ref_with_vtables_to_callee<'a>(bcx: &'a Block<'a>,
226 substs: subst::Substs,
227 vtables: typeck::vtable_res)
231 data: Fn(trans_fn_ref_with_vtables(bcx,
239 fn resolve_default_method_vtables(bcx: &Block,
241 substs: &subst::Substs,
242 impl_vtables: typeck::vtable_res)
243 -> typeck::vtable_res
245 // Get the vtables that the impl implements the trait at
246 let impl_res = ty::lookup_impl_vtables(bcx.tcx(), impl_id);
248 // Build up a param_substs that we are going to resolve the
249 // trait_vtables under.
250 let param_substs = param_substs {
251 substs: (*substs).clone(),
252 vtables: impl_vtables.clone()
255 let mut param_vtables = resolve_vtables_under_param_substs(
256 bcx.tcx(), ¶m_substs, &impl_res);
258 // Now we pull any vtables for parameters on the actual method.
259 param_vtables.push_all(subst::FnSpace,
260 impl_vtables.get_slice(subst::FnSpace));
265 /// Translates the adapter that deconstructs a `Box<Trait>` object into
266 /// `Trait` so that a by-value self method can be called.
267 pub fn trans_unboxing_shim(bcx: &Block,
268 llshimmedfn: ValueRef,
270 method_id: ast::DefId,
271 substs: subst::Substs)
273 let _icx = push_ctxt("trans_unboxing_shim");
277 // Transform the self type to `Box<self_type>`.
278 let self_type = *method.fty.sig.inputs.get(0);
279 let boxed_self_type = ty::mk_uniq(tcx, self_type);
280 let boxed_function_type = ty::FnSig {
281 binder_id: method.fty.sig.binder_id,
282 inputs: method.fty.sig.inputs.iter().enumerate().map(|(i, typ)| {
289 output: method.fty.sig.output,
292 let boxed_function_type = ty::BareFnTy {
293 fn_style: method.fty.fn_style,
295 sig: boxed_function_type,
297 let boxed_function_type =
298 ty::mk_bare_fn(tcx, boxed_function_type).subst(tcx, &substs);
300 ty::mk_bare_fn(tcx, method.fty.clone()).subst(tcx, &substs);
302 let function_name = ty::with_path(tcx, method_id, |path| {
303 link::mangle_internal_name_by_path_and_seq(path, "unboxing_shim")
305 let llfn = decl_internal_rust_fn(ccx,
307 function_name.as_slice());
309 let block_arena = TypedArena::new();
310 let empty_param_substs = param_substs::empty();
311 let return_type = ty::ty_fn_ret(boxed_function_type);
312 let fcx = new_fn_ctxt(ccx,
320 let mut bcx = init_function(&fcx, false, return_type);
322 // Create the substituted versions of the self type.
323 let arg_scope = fcx.push_custom_cleanup_scope();
324 let arg_scope_id = cleanup::CustomScope(arg_scope);
325 let boxed_arg_types = ty::ty_fn_args(boxed_function_type);
326 let boxed_self_type = *boxed_arg_types.get(0);
327 let arg_types = ty::ty_fn_args(function_type);
328 let self_type = *arg_types.get(0);
329 let boxed_self_kind = arg_kind(&fcx, boxed_self_type);
331 // Create a datum for self.
332 let llboxedself = get_param(fcx.llfn, fcx.arg_pos(0) as u32);
333 let llboxedself = Datum::new(llboxedself,
338 llboxedself.to_lvalue_datum_in_scope(bcx,
342 // This `Load` is needed because lvalue data are always by-ref.
343 let llboxedself = Load(bcx, boxed_self.val);
345 let llself = if type_is_immediate(ccx, self_type) {
346 let llboxedself = Load(bcx, llboxedself);
347 immediate_rvalue(llboxedself, self_type)
349 let llself = rvalue_scratch_datum(bcx, self_type, "self");
350 memcpy_ty(bcx, llself.val, llboxedself, self_type);
354 // Make sure we don't free the box twice!
355 boxed_self.kind.post_store(bcx, boxed_self.val, boxed_self_type);
357 // Schedule a cleanup to free the box.
358 fcx.schedule_free_value(arg_scope_id,
360 cleanup::HeapExchange,
363 // Now call the function.
364 let mut llshimmedargs = vec!(llself.val);
365 for i in range(1, arg_types.len()) {
366 llshimmedargs.push(get_param(fcx.llfn, fcx.arg_pos(i) as u32));
368 bcx = trans_call_inner(bcx,
374 data: Fn(llshimmedfn),
377 ArgVals(llshimmedargs.as_slice()),
378 match fcx.llretptr.get() {
380 Some(llretptr) => Some(expr::SaveIn(llretptr)),
383 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
384 finish_fn(&fcx, bcx, return_type);
389 pub fn trans_fn_ref_with_vtables(
391 def_id: ast::DefId, // def id of fn
392 node: ExprOrMethodCall, // node id of use of fn; may be zero if N/A
393 substs: subst::Substs, // values for fn's ty params
394 vtables: typeck::vtable_res) // vtables for the call
398 * Translates a reference to a fn/method item, monomorphizing and
399 * inlining as it goes.
403 * - `bcx`: the current block where the reference to the fn occurs
404 * - `def_id`: def id of the fn or method item being referenced
405 * - `node`: node id of the reference to the fn/method, if applicable.
406 * This parameter may be zero; but, if so, the resulting value may not
407 * have the right type, so it must be cast before being used.
408 * - `substs`: values for each of the fn/method's parameters
409 * - `vtables`: values for each bound on each of the type parameters
412 let _icx = push_ctxt("trans_fn_ref_with_vtables");
416 debug!("trans_fn_ref_with_vtables(bcx={}, def_id={}, node={:?}, \
417 substs={}, vtables={})",
424 assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
426 // Load the info for the appropriate trait if necessary.
427 match ty::trait_of_method(tcx, def_id) {
430 ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
434 // We need to do a bunch of special handling for default methods.
435 // We need to modify the def_id and our substs in order to monomorphize
437 let (is_default, def_id, substs, vtables) =
438 match ty::provided_source(tcx, def_id) {
439 None => (false, def_id, substs, vtables),
441 // There are two relevant substitutions when compiling
442 // default methods. First, there is the substitution for
443 // the type parameters of the impl we are using and the
444 // method we are calling. This substitution is the substs
445 // argument we already have.
446 // In order to compile a default method, though, we need
447 // to consider another substitution: the substitution for
448 // the type parameters on trait; the impl we are using
449 // implements the trait at some particular type
450 // parameters, and we need to substitute for those first.
451 // So, what we need to do is find this substitution and
452 // compose it with the one we already have.
454 let impl_id = ty::method(tcx, def_id).container_id();
455 let method = ty::method(tcx, source_id);
456 let trait_ref = ty::impl_trait_ref(tcx, impl_id)
457 .expect("could not find trait_ref for impl with \
460 // Compute the first substitution
461 let first_subst = make_substs_for_receiver_types(
462 tcx, &*trait_ref, &*method);
465 let new_substs = first_subst.subst(tcx, &substs);
467 debug!("trans_fn_with_vtables - default method: \
468 substs = {}, trait_subst = {}, \
469 first_subst = {}, new_subst = {}, \
471 substs.repr(tcx), trait_ref.substs.repr(tcx),
472 first_subst.repr(tcx), new_substs.repr(tcx),
476 resolve_default_method_vtables(bcx, impl_id, &substs, vtables);
478 debug!("trans_fn_with_vtables - default method: \
480 param_vtables.repr(tcx));
482 (true, source_id, new_substs, param_vtables)
486 // If this is an unboxed closure, redirect to it.
487 match closure::get_or_create_declaration_if_unboxed_closure(ccx, def_id) {
489 Some(llfn) => return llfn,
492 // Check whether this fn has an inlined copy and, if so, redirect
493 // def_id to the local id of the inlined copy.
495 if def_id.krate != ast::LOCAL_CRATE {
496 inline::maybe_instantiate_inline(ccx, def_id)
502 // We must monomorphise if the fn has type parameters or is a default method.
503 let must_monomorphise = !substs.types.is_empty() || is_default;
505 // Create a monomorphic version of generic functions
506 if must_monomorphise {
507 // Should be either intra-crate or inlined.
508 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
510 let opt_ref_id = match node {
511 ExprId(id) => if id != 0 { Some(id) } else { None },
512 MethodCall(_) => None,
515 let (val, must_cast) =
516 monomorphize::monomorphic_fn(ccx, def_id, &substs,
517 vtables, opt_ref_id);
519 if must_cast && node != ExprId(0) {
520 // Monotype of the REFERENCE to the function (type params
522 let ref_ty = match node {
523 ExprId(id) => node_id_type(bcx, id),
524 MethodCall(method_call) => {
525 let t = bcx.tcx().method_map.borrow().get(&method_call).ty;
526 monomorphize_type(bcx, t)
531 bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
536 // Polytype of the function item (may have type params)
537 let fn_tpt = ty::lookup_item_type(tcx, def_id);
539 // Find the actual function pointer.
541 if def_id.krate == ast::LOCAL_CRATE {
542 // Internal reference.
543 get_item_val(ccx, def_id.node)
545 // External reference.
546 trans_external_path(ccx, def_id, fn_tpt.ty)
550 // This is subtle and surprising, but sometimes we have to bitcast
551 // the resulting fn pointer. The reason has to do with external
552 // functions. If you have two crates that both bind the same C
553 // library, they may not use precisely the same types: for
554 // example, they will probably each declare their own structs,
555 // which are distinct types from LLVM's point of view (nominal
558 // Now, if those two crates are linked into an application, and
559 // they contain inlined code, you can wind up with a situation
560 // where both of those functions wind up being loaded into this
561 // application simultaneously. In that case, the same function
562 // (from LLVM's point of view) requires two types. But of course
563 // LLVM won't allow one function to have two types.
565 // What we currently do, therefore, is declare the function with
566 // one of the two types (whichever happens to come first) and then
567 // bitcast as needed when the function is referenced to make sure
568 // it has the type we expect.
570 // This can occur on either a crate-local or crate-external
571 // reference. It also occurs when testing libcore and in some
572 // other weird situations. Annoying.
573 let llty = type_of::type_of_fn_from_ty(ccx, fn_tpt.ty);
574 let llptrty = llty.ptr_to();
575 if val_ty(val) != llptrty {
576 debug!("trans_fn_ref_with_vtables(): casting pointer!");
577 val = BitCast(bcx, val, llptrty);
579 debug!("trans_fn_ref_with_vtables(): not casting pointer!");
585 // ______________________________________________________________________
588 pub fn trans_call<'a>(
589 in_cx: &'a Block<'a>,
595 let _icx = push_ctxt("trans_call");
596 trans_call_inner(in_cx,
597 Some(common::expr_info(call_ex)),
599 |cx, _| trans(cx, f),
604 pub fn trans_method_call<'a>(
611 let _icx = push_ctxt("trans_method_call");
612 debug!("trans_method_call(call_ex={})", call_ex.repr(bcx.tcx()));
613 let method_call = MethodCall::expr(call_ex.id);
614 let method_ty = bcx.tcx().method_map.borrow().get(&method_call).ty;
617 Some(common::expr_info(call_ex)),
618 monomorphize_type(bcx, method_ty),
619 |cx, arg_cleanup_scope| {
620 meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
626 pub fn trans_lang_call<'a>(
630 dest: Option<expr::Dest>)
632 let fty = if did.krate == ast::LOCAL_CRATE {
633 ty::node_id_to_type(bcx.tcx(), did.node)
635 csearch::get_type(bcx.tcx(), did).ty
637 callee::trans_call_inner(bcx,
641 trans_fn_ref_with_vtables_to_callee(bcx,
644 subst::Substs::empty(),
645 VecPerParamSpace::empty())
651 pub fn trans_call_inner<'a>(
653 call_info: Option<NodeInfo>,
655 get_callee: |bcx: &'a Block<'a>,
656 arg_cleanup_scope: cleanup::ScopeId|
659 dest: Option<expr::Dest>)
662 * This behemoth of a function translates function calls.
663 * Unfortunately, in order to generate more efficient LLVM
664 * output at -O0, it has quite a complex signature (refactoring
665 * this into two functions seems like a good idea).
667 * In particular, for lang items, it is invoked with a dest of
668 * None, and in that case the return value contains the result of
669 * the fn. The lang item must not return a structural type or else
670 * all heck breaks loose.
672 * For non-lang items, `dest` is always Some, and hence the result
673 * is written into memory somewhere. Nonetheless we return the
674 * actual return value of the function.
677 // Introduce a temporary cleanup scope that will contain cleanups
678 // for the arguments while they are being evaluated. The purpose
679 // this cleanup is to ensure that, should a failure occur while
680 // evaluating argument N, the values for arguments 0...N-1 are all
681 // cleaned up. If no failure occurs, the values are handed off to
682 // the callee, and hence none of the cleanups in this temporary
683 // scope will ever execute.
686 let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
688 let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
689 let mut bcx = callee.bcx;
691 let (abi, ret_ty) = match ty::get(callee_ty).sty {
692 ty::ty_bare_fn(ref f) => (f.abi, f.sig.output),
693 ty::ty_closure(ref f) => (f.abi, f.sig.output),
694 _ => fail!("expected bare rust fn or closure in trans_call_inner")
697 let (llfn, llenv, llself) = match callee.data {
702 (d.llfn, None, Some(d.llself))
705 // Closures are represented as (llfn, llclosure) pair:
706 // load the requisite values out.
707 let pair = d.to_llref();
708 let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]);
709 let llfn = Load(bcx, llfn);
710 let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]);
711 let llenv = Load(bcx, llenv);
712 (llfn, Some(llenv), None)
714 Intrinsic(node, substs) => {
715 assert!(abi == synabi::RustIntrinsic);
716 assert!(dest.is_some());
718 return intrinsic::trans_intrinsic_call(bcx, node, callee_ty,
719 arg_cleanup_scope, args,
720 dest.unwrap(), substs);
722 TupleVariantConstructor(substs, disr) => {
723 assert!(dest.is_some());
724 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
726 let ctor_ty = callee_ty.subst(bcx.tcx(), &substs);
727 return base::trans_enum_variant_constructor(bcx, ctor_ty, disr,
728 args, dest.unwrap());
732 // Intrinsics should not become actual functions.
733 // We trans them in place in `trans_intrinsic_call`
734 assert!(abi != synabi::RustIntrinsic);
736 // Generate a location to store the result. If the user does
737 // not care about the result, just make a stack slot.
738 let opt_llretslot = match dest {
740 assert!(!type_of::return_uses_outptr(ccx, ret_ty));
743 Some(expr::SaveIn(dst)) => Some(dst),
744 Some(expr::Ignore) => {
745 if !type_is_zero_size(ccx, ret_ty) {
746 Some(alloc_ty(bcx, ret_ty, "__llret"))
748 let llty = type_of::type_of(ccx, ret_ty);
749 Some(C_undef(llty.ptr_to()))
754 let mut llresult = unsafe {
755 llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
758 // The code below invokes the function, using either the Rust
759 // conventions (if it is a rust fn) or the native conventions
760 // (otherwise). The important part is that, when all is sad
761 // and done, either the return value of the function will have been
762 // written in opt_llretslot (if it is Some) or `llresult` will be
763 // set appropriately (otherwise).
764 if abi == synabi::Rust || abi == synabi::RustCall {
765 let mut llargs = Vec::new();
767 // Push the out-pointer if we use an out-pointer for this
768 // return type, otherwise push "undef".
769 if type_of::return_uses_outptr(ccx, ret_ty) {
770 llargs.push(opt_llretslot.unwrap());
773 // Push the environment (or a trait object's self).
774 match (llenv, llself) {
775 (Some(llenv), None) => {
778 (None, Some(llself)) => llargs.push(llself),
782 // Push the arguments.
783 bcx = trans_args(bcx,
787 cleanup::CustomScope(arg_cleanup_scope),
791 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
793 // Invoke the actual rust fn and update bcx/llresult.
794 let (llret, b) = base::invoke(bcx,
802 // If the Rust convention for this type is return via
803 // the return value, copy it into llretslot.
804 match opt_llretslot {
806 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
807 !type_is_zero_size(bcx.ccx(), ret_ty)
809 store_ty(bcx, llret, llretslot, ret_ty)
815 // Lang items are the only case where dest is None, and
816 // they are always Rust fns.
817 assert!(dest.is_some());
819 let mut llargs = Vec::new();
820 let arg_tys = match args {
821 ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, &**x)).collect(),
822 _ => fail!("expected arg exprs.")
824 bcx = trans_args(bcx,
828 cleanup::CustomScope(arg_cleanup_scope),
831 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
832 bcx = foreign::trans_native_call(bcx, callee_ty,
833 llfn, opt_llretslot.unwrap(),
834 llargs.as_slice(), arg_tys);
837 // If the caller doesn't care about the result of this fn call,
838 // drop the temporary slot we made.
841 assert!(!type_of::return_uses_outptr(bcx.ccx(), ret_ty));
843 Some(expr::Ignore) => {
844 // drop the value if it is not being saved.
845 bcx = glue::drop_ty(bcx, opt_llretslot.unwrap(), ret_ty);
847 Some(expr::SaveIn(_)) => { }
850 if ty::type_is_bot(ret_ty) {
854 Result::new(bcx, llresult)
857 pub enum CallArgs<'a> {
858 // Supply value of arguments as a list of expressions that must be
859 // translated. This is used in the common case of `foo(bar, qux)`.
860 ArgExprs(&'a [Gc<ast::Expr>]),
862 // Supply value of arguments as a list of LLVM value refs; frequently
863 // used with lang items and so forth, when the argument is an internal
865 ArgVals(&'a [ValueRef]),
867 // For overloaded operators: `(lhs, Option(rhs, rhs_id))`. `lhs`
868 // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
869 // the right-hand-side (if any).
870 ArgOverloadedOp(Datum<Expr>, Option<(Datum<Expr>, ast::NodeId)>),
872 // Supply value of arguments as a list of expressions that must be
873 // translated, for overloaded call operators.
874 ArgOverloadedCall(&'a [Gc<ast::Expr>]),
877 fn trans_args_under_call_abi<'a>(
878 mut bcx: &'a Block<'a>,
879 arg_exprs: &[Gc<ast::Expr>],
881 llargs: &mut Vec<ValueRef>,
882 arg_cleanup_scope: cleanup::ScopeId,
885 // Translate the `self` argument first.
886 let arg_tys = ty::ty_fn_args(fn_ty);
888 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
889 llargs.push(unpack_result!(bcx, {
898 // Now untuple the rest of the arguments.
899 let tuple_expr = arg_exprs[1];
900 let tuple_type = node_id_type(bcx, tuple_expr.id);
902 match ty::get(tuple_type).sty {
903 ty::ty_tup(ref field_types) => {
904 let tuple_datum = unpack_datum!(bcx,
905 expr::trans(bcx, &*tuple_expr));
906 let tuple_lvalue_datum =
908 tuple_datum.to_lvalue_datum(bcx,
911 let repr = adt::represent_type(bcx.ccx(), tuple_type);
912 let repr_ptr = &*repr;
913 for i in range(0, field_types.len()) {
914 let arg_datum = tuple_lvalue_datum.get_element(
917 adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
919 let arg_datum = arg_datum.to_expr_datum();
921 unpack_datum!(bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
923 unpack_datum!(bcx, arg_datum.to_appropriate_datum(bcx));
924 llargs.push(arg_datum.add_clean(bcx.fcx, arg_cleanup_scope));
929 bcx.sess().span_bug(tuple_expr.span,
930 "argument to `.call()` wasn't a tuple?!")
937 fn trans_overloaded_call_args<'a>(
938 mut bcx: &'a Block<'a>,
939 arg_exprs: &[Gc<ast::Expr>],
941 llargs: &mut Vec<ValueRef>,
942 arg_cleanup_scope: cleanup::ScopeId,
945 // Translate the `self` argument first.
946 let arg_tys = ty::ty_fn_args(fn_ty);
948 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
949 llargs.push(unpack_result!(bcx, {
958 // Now untuple the rest of the arguments.
959 let tuple_type = *arg_tys.get(1);
960 match ty::get(tuple_type).sty {
961 ty::ty_tup(ref field_types) => {
962 for (i, &field_type) in field_types.iter().enumerate() {
964 unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[i + 1]));
965 llargs.push(unpack_result!(bcx, {
976 bcx.sess().span_bug(arg_exprs[0].span,
977 "argument to `.call()` wasn't a tuple?!")
984 pub fn trans_args<'a>(
988 llargs: &mut Vec<ValueRef> ,
989 arg_cleanup_scope: cleanup::ScopeId,
993 debug!("trans_args(abi={})", abi);
995 let _icx = push_ctxt("trans_args");
996 let arg_tys = ty::ty_fn_args(fn_ty);
997 let variadic = ty::fn_is_variadic(fn_ty);
1001 // First we figure out the caller's view of the types of the arguments.
1002 // This will be needed if this is a generic call, because the callee has
1003 // to cast her view of the arguments to the caller's view.
1005 ArgExprs(arg_exprs) => {
1006 if abi == synabi::RustCall {
1007 // This is only used for direct calls to the `call`,
1008 // `call_mut` or `call_once` functions.
1009 return trans_args_under_call_abi(cx,
1017 let num_formal_args = arg_tys.len();
1018 for (i, arg_expr) in arg_exprs.iter().enumerate() {
1019 if i == 0 && ignore_self {
1022 let arg_ty = if i >= num_formal_args {
1024 expr_ty_adjusted(cx, &**arg_expr)
1029 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
1030 llargs.push(unpack_result!(bcx, {
1031 trans_arg_datum(bcx, arg_ty, arg_datum,
1037 ArgOverloadedCall(arg_exprs) => {
1038 return trans_overloaded_call_args(cx,
1045 ArgOverloadedOp(lhs, rhs) => {
1048 llargs.push(unpack_result!(bcx, {
1049 trans_arg_datum(bcx, *arg_tys.get(0), lhs,
1055 Some((rhs, rhs_id)) => {
1056 assert_eq!(arg_tys.len(), 2);
1058 llargs.push(unpack_result!(bcx, {
1059 trans_arg_datum(bcx, *arg_tys.get(1), rhs,
1061 DoAutorefArg(rhs_id))
1064 None => assert_eq!(arg_tys.len(), 1)
1068 llargs.push_all(vs);
1075 pub enum AutorefArg {
1077 DoAutorefArg(ast::NodeId)
1080 pub fn trans_arg_datum<'a>(
1082 formal_arg_ty: ty::t,
1083 arg_datum: Datum<Expr>,
1084 arg_cleanup_scope: cleanup::ScopeId,
1085 autoref_arg: AutorefArg)
1087 let _icx = push_ctxt("trans_arg_datum");
1089 let ccx = bcx.ccx();
1091 debug!("trans_arg_datum({})",
1092 formal_arg_ty.repr(bcx.tcx()));
1094 let arg_datum_ty = arg_datum.ty;
1096 debug!(" arg datum: {}", arg_datum.to_string(bcx.ccx()));
1099 if ty::type_is_bot(arg_datum_ty) {
1100 // For values of type _|_, we generate an
1101 // "undef" value, as such a value should never
1102 // be inspected. It's important for the value
1103 // to have type lldestty (the callee's expected type).
1104 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1106 val = llvm::LLVMGetUndef(llformal_arg_ty.to_ref());
1109 // FIXME(#3548) use the adjustments table
1111 DoAutorefArg(arg_id) => {
1112 // We will pass argument by reference
1113 // We want an lvalue, so that we can pass by reference and
1114 let arg_datum = unpack_datum!(
1115 bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
1116 val = arg_datum.val;
1119 // Make this an rvalue, since we are going to be
1120 // passing ownership.
1121 let arg_datum = unpack_datum!(
1122 bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
1124 // Now that arg_datum is owned, get it into the appropriate
1125 // mode (ref vs value).
1126 let arg_datum = unpack_datum!(
1127 bcx, arg_datum.to_appropriate_datum(bcx));
1129 // Technically, ownership of val passes to the callee.
1130 // However, we must cleanup should we fail before the
1131 // callee is actually invoked.
1132 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
1136 if formal_arg_ty != arg_datum_ty {
1137 // this could happen due to e.g. subtyping
1138 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1139 debug!("casting actual type ({}) to match formal ({})",
1140 bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty));
1141 val = PointerCast(bcx, val, llformal_arg_ty);
1145 debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val));
1146 Result::new(bcx, val)