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
23 use lib::llvm::{ValueRef, NoAliasAttribute, StructRetAttribute};
25 use metadata::csearch;
26 use middle::trans::base;
27 use middle::trans::base::*;
28 use middle::trans::build::*;
29 use middle::trans::callee;
30 use middle::trans::cleanup;
31 use middle::trans::cleanup::CleanupMethods;
32 use middle::trans::common;
33 use middle::trans::common::*;
34 use middle::trans::datum::*;
35 use middle::trans::datum::Datum;
36 use middle::trans::expr;
37 use middle::trans::glue;
38 use middle::trans::inline;
39 use middle::trans::meth;
40 use middle::trans::monomorphize;
41 use middle::trans::type_of;
42 use middle::trans::foreign;
44 use middle::subst::Subst;
46 use middle::typeck::coherence::make_substs_for_receiver_types;
47 use util::ppaux::Repr;
49 use middle::trans::type_::Type;
52 use syntax::abi::AbiSet;
55 pub struct MethodData {
61 Closure(Datum<Lvalue>),
63 // Represents a (possibly monomorphized) top-level fn item or method
64 // item. Note that this is just the fn-ptr and is not a Rust closure
65 // value (which is a pair).
66 Fn(/* llfn */ ValueRef),
68 TraitMethod(MethodData)
71 pub struct Callee<'a> {
76 fn trans<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
77 let _icx = push_ctxt("trans_callee");
78 debug!("callee::trans(expr={})", expr.repr(bcx.tcx()));
80 // pick out special kinds of expressions that can be called:
83 return trans_def(bcx, bcx.def(expr.id), expr);
88 // any other expressions are closures:
89 return datum_callee(bcx, expr);
91 fn datum_callee<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
92 let DatumBlock {bcx: mut bcx, datum} = expr::trans(bcx, expr);
93 match ty::get(datum.ty).sty {
94 ty::ty_bare_fn(..) => {
95 let llval = datum.to_llscalarish(bcx);
96 return Callee {bcx: bcx, data: Fn(llval)};
98 ty::ty_closure(..) => {
99 let datum = unpack_datum!(
100 bcx, datum.to_lvalue_datum(bcx, "callee", expr.id));
101 return Callee {bcx: bcx, data: Closure(datum)};
104 bcx.tcx().sess.span_bug(
106 format!("type of callee is neither bare-fn nor closure: {}",
107 bcx.ty_to_str(datum.ty)));
112 fn fn_callee<'a>(bcx: &'a Block<'a>, llfn: ValueRef) -> Callee<'a> {
113 return Callee {bcx: bcx, data: Fn(llfn)};
116 fn trans_def<'a>(bcx: &'a Block<'a>, def: ast::Def, ref_expr: &ast::Expr)
120 ast::DefStaticMethod(did, ast::FromImpl(_), _) => {
121 fn_callee(bcx, trans_fn_ref(bcx, did, ref_expr.id, false))
123 ast::DefStaticMethod(impl_did,
124 ast::FromTrait(trait_did),
126 fn_callee(bcx, meth::trans_static_method_callee(bcx, impl_did,
130 ast::DefVariant(tid, vid, _) => {
131 // nullary variants are not callable
132 assert!(ty::enum_variant_with_id(bcx.tcx(),
134 vid).args.len() > 0u);
135 fn_callee(bcx, trans_fn_ref(bcx, vid, ref_expr.id, false))
137 ast::DefStruct(def_id) => {
138 fn_callee(bcx, trans_fn_ref(bcx, def_id, ref_expr.id, false))
143 ast::DefBinding(..) |
144 ast::DefUpvar(..) => {
145 datum_callee(bcx, ref_expr)
147 ast::DefMod(..) | ast::DefForeignMod(..) | ast::DefTrait(..) |
148 ast::DefTy(..) | ast::DefPrimTy(..) |
149 ast::DefUse(..) | ast::DefTyParamBinder(..) |
150 ast::DefRegion(..) | ast::DefLabel(..) | ast::DefTyParam(..) |
151 ast::DefSelfTy(..) | ast::DefMethod(..) => {
152 bcx.tcx().sess.span_bug(
154 format!("cannot translate def {:?} \
155 to a callable thing!", def));
161 pub fn trans_fn_ref(bcx: &Block, def_id: ast::DefId,
162 ref_id: ast::NodeId, is_method: bool)
166 * Translates a reference (with id `ref_id`) to the fn/method
167 * with id `def_id` into a function pointer. This may require
168 * monomorphization or inlining. */
170 let _icx = push_ctxt("trans_fn_ref");
172 let type_params = node_id_type_params(bcx, ref_id, is_method);
173 let vtables = node_vtables(bcx, ref_id);
174 debug!("trans_fn_ref(def_id={}, ref_id={:?}, type_params={}, vtables={})",
175 def_id.repr(bcx.tcx()), ref_id, type_params.repr(bcx.tcx()),
176 vtables.repr(bcx.tcx()));
177 trans_fn_ref_with_vtables(bcx, def_id, ref_id, is_method, type_params, vtables)
180 fn trans_fn_ref_with_vtables_to_callee<'a>(bcx: &'a Block<'a>,
183 type_params: &[ty::t],
184 vtables: Option<typeck::vtable_res>)
187 data: Fn(trans_fn_ref_with_vtables(bcx, def_id, ref_id, false,
188 type_params, vtables))}
191 fn resolve_default_method_vtables(bcx: &Block,
195 impl_vtables: Option<typeck::vtable_res>)
196 -> (typeck::vtable_res, typeck::vtable_param_res) {
198 // Get the vtables that the impl implements the trait at
199 let impl_res = ty::lookup_impl_vtables(bcx.tcx(), impl_id);
201 // Build up a param_substs that we are going to resolve the
202 // trait_vtables under.
203 let param_substs = Some(@param_substs {
204 tys: substs.tps.clone(),
205 self_ty: substs.self_ty,
206 vtables: impl_vtables,
210 let trait_vtables_fixed = resolve_vtables_under_param_substs(
211 bcx.tcx(), param_substs, impl_res.trait_vtables);
213 // Now we pull any vtables for parameters on the actual method.
214 let num_method_vtables = method.generics.type_param_defs().len();
215 let method_vtables = match impl_vtables {
217 let num_impl_type_parameters =
218 vtables.len() - num_method_vtables;
219 vtables.tailn(num_impl_type_parameters).to_owned()
221 None => vec::from_elem(num_method_vtables, @~[])
224 let param_vtables = @(*trait_vtables_fixed + method_vtables);
226 let self_vtables = resolve_param_vtables_under_param_substs(
227 bcx.tcx(), param_substs, impl_res.self_vtables);
229 (param_vtables, self_vtables)
233 pub fn trans_fn_ref_with_vtables(
235 def_id: ast::DefId, // def id of fn
236 ref_id: ast::NodeId, // node id of use of fn; may be zero if N/A
238 type_params: &[ty::t], // values for fn's ty params
239 vtables: Option<typeck::vtable_res>) // vtables for the call
242 * Translates a reference to a fn/method item, monomorphizing and
243 * inlining as it goes.
247 * - `bcx`: the current block where the reference to the fn occurs
248 * - `def_id`: def id of the fn or method item being referenced
249 * - `ref_id`: node id of the reference to the fn/method, if applicable.
250 * This parameter may be zero; but, if so, the resulting value may not
251 * have the right type, so it must be cast before being used.
252 * - `type_params`: values for each of the fn/method's type parameters
253 * - `vtables`: values for each bound on each of the type parameters
256 let _icx = push_ctxt("trans_fn_ref_with_vtables");
260 debug!("trans_fn_ref_with_vtables(bcx={}, def_id={}, ref_id={:?}, \
261 type_params={}, vtables={})",
263 def_id.repr(bcx.tcx()),
265 type_params.repr(bcx.tcx()),
266 vtables.repr(bcx.tcx()));
268 assert!(type_params.iter().all(|t| !ty::type_needs_infer(*t)));
270 // Polytype of the function item (may have type params)
271 let fn_tpt = ty::lookup_item_type(tcx, def_id);
273 let substs = ty::substs { regions: ty::ErasedRegions,
275 tps: /*bad*/ type_params.to_owned() };
277 // Load the info for the appropriate trait if necessary.
278 match ty::trait_of_method(tcx, def_id) {
281 ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
285 // We need to do a bunch of special handling for default methods.
286 // We need to modify the def_id and our substs in order to monomorphize
288 let (is_default, def_id, substs, self_vtables, vtables) =
289 match ty::provided_source(tcx, def_id) {
290 None => (false, def_id, substs, None, vtables),
292 // There are two relevant substitutions when compiling
293 // default methods. First, there is the substitution for
294 // the type parameters of the impl we are using and the
295 // method we are calling. This substitution is the substs
296 // argument we already have.
297 // In order to compile a default method, though, we need
298 // to consider another substitution: the substitution for
299 // the type parameters on trait; the impl we are using
300 // implements the trait at some particular type
301 // parameters, and we need to substitute for those first.
302 // So, what we need to do is find this substitution and
303 // compose it with the one we already have.
305 let impl_id = ty::method(tcx, def_id).container_id();
306 let method = ty::method(tcx, source_id);
307 let trait_ref = ty::impl_trait_ref(tcx, impl_id)
308 .expect("could not find trait_ref for impl with \
311 // Compute the first substitution
312 let first_subst = make_substs_for_receiver_types(
313 tcx, impl_id, trait_ref, method);
316 let new_substs = first_subst.subst(tcx, &substs);
319 let (param_vtables, self_vtables) =
320 resolve_default_method_vtables(bcx, impl_id,
321 method, &substs, vtables);
323 debug!("trans_fn_with_vtables - default method: \
324 substs = {}, trait_subst = {}, \
325 first_subst = {}, new_subst = {}, \
327 self_vtable = {}, param_vtables = {}",
328 substs.repr(tcx), trait_ref.substs.repr(tcx),
329 first_subst.repr(tcx), new_substs.repr(tcx),
331 self_vtables.repr(tcx), param_vtables.repr(tcx));
334 new_substs, Some(self_vtables), Some(param_vtables))
338 // Check whether this fn has an inlined copy and, if so, redirect
339 // def_id to the local id of the inlined copy.
341 if def_id.krate != ast::LOCAL_CRATE {
342 inline::maybe_instantiate_inline(ccx, def_id)
348 // We must monomorphise if the fn has type parameters, is a rust
349 // intrinsic, or is a default method. In particular, if we see an
350 // intrinsic that is inlined from a different crate, we want to reemit the
351 // intrinsic instead of trying to call it in the other crate.
352 let must_monomorphise = if type_params.len() > 0 || is_default {
354 } else if def_id.krate == ast::LOCAL_CRATE {
355 let map_node = session::expect(
357 ccx.tcx.map.find(def_id.node),
358 || format!("local item should be in ast map"));
361 ast_map::NodeForeignItem(_) => {
362 ccx.tcx.map.get_foreign_abis(def_id.node).is_intrinsic()
370 // Create a monomorphic verison of generic functions
371 if must_monomorphise {
372 // Should be either intra-crate or inlined.
373 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
375 let (val, must_cast) =
376 monomorphize::monomorphic_fn(ccx, def_id, &substs,
377 vtables, self_vtables,
380 if must_cast && ref_id != 0 {
381 // Monotype of the REFERENCE to the function (type params
383 let ref_ty = if is_method {
384 let t = bcx.ccx().maps.method_map.borrow().get().get(&ref_id).ty;
385 monomorphize_type(bcx, t)
387 node_id_type(bcx, ref_id)
391 bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
396 // Find the actual function pointer.
398 if def_id.krate == ast::LOCAL_CRATE {
399 // Internal reference.
400 get_item_val(ccx, def_id.node)
402 // External reference.
403 trans_external_path(ccx, def_id, fn_tpt.ty)
407 // This is subtle and surprising, but sometimes we have to bitcast
408 // the resulting fn pointer. The reason has to do with external
409 // functions. If you have two crates that both bind the same C
410 // library, they may not use precisely the same types: for
411 // example, they will probably each declare their own structs,
412 // which are distinct types from LLVM's point of view (nominal
415 // Now, if those two crates are linked into an application, and
416 // they contain inlined code, you can wind up with a situation
417 // where both of those functions wind up being loaded into this
418 // application simultaneously. In that case, the same function
419 // (from LLVM's point of view) requires two types. But of course
420 // LLVM won't allow one function to have two types.
422 // What we currently do, therefore, is declare the function with
423 // one of the two types (whichever happens to come first) and then
424 // bitcast as needed when the function is referenced to make sure
425 // it has the type we expect.
427 // This can occur on either a crate-local or crate-external
428 // reference. It also occurs when testing libcore and in some
429 // other weird situations. Annoying.
430 let llty = type_of::type_of_fn_from_ty(ccx, fn_tpt.ty);
431 let llptrty = llty.ptr_to();
432 if val_ty(val) != llptrty {
433 val = BitCast(bcx, val, llptrty);
439 // ______________________________________________________________________
442 pub fn trans_call<'a>(
443 in_cx: &'a Block<'a>,
449 let _icx = push_ctxt("trans_call");
450 trans_call_inner(in_cx,
451 Some(common::expr_info(call_ex)),
453 |cx, _| trans(cx, f),
458 pub fn trans_method_call<'a>(
465 let _icx = push_ctxt("trans_method_call");
466 debug!("trans_method_call(call_ex={})", call_ex.repr(bcx.tcx()));
467 let method_ty = bcx.ccx().maps.method_map.borrow().get().get(&call_ex.id).ty;
470 Some(common::expr_info(call_ex)),
471 monomorphize_type(bcx, method_ty),
472 |cx, arg_cleanup_scope| {
473 meth::trans_method_callee(cx, call_ex.id, rcvr, arg_cleanup_scope)
479 pub fn trans_lang_call<'a>(
483 dest: Option<expr::Dest>)
485 let fty = if did.krate == ast::LOCAL_CRATE {
486 ty::node_id_to_type(bcx.ccx().tcx, did.node)
488 csearch::get_type(bcx.ccx().tcx, did).ty
490 callee::trans_call_inner(bcx,
494 trans_fn_ref_with_vtables_to_callee(bcx,
504 pub fn trans_lang_call_with_type_params<'a>(
508 type_params: &[ty::t],
512 if did.krate == ast::LOCAL_CRATE {
513 fty = ty::node_id_to_type(bcx.tcx(), did.node);
515 fty = csearch::get_type(bcx.tcx(), did).ty;
518 return callee::trans_call_inner(
524 trans_fn_ref_with_vtables_to_callee(bcx, did, 0,
531 let substituted = ty::subst_tps(callee.bcx.tcx(),
535 let llfnty = type_of::type_of(callee.bcx.ccx(),
537 new_llval = PointerCast(callee.bcx, llfn, llfnty);
541 Callee { bcx: callee.bcx, data: Fn(new_llval) }
543 ArgVals(args), Some(dest)).bcx;
546 pub fn trans_call_inner<'a>(
548 call_info: Option<NodeInfo>,
550 get_callee: |bcx: &'a Block<'a>,
551 arg_cleanup_scope: cleanup::ScopeId|
554 dest: Option<expr::Dest>)
557 * This behemoth of a function translates function calls.
558 * Unfortunately, in order to generate more efficient LLVM
559 * output at -O0, it has quite a complex signature (refactoring
560 * this into two functions seems like a good idea).
562 * In particular, for lang items, it is invoked with a dest of
563 * None, and in that case the return value contains the result of
564 * the fn. The lang item must not return a structural type or else
565 * all heck breaks loose.
567 * For non-lang items, `dest` is always Some, and hence the result
568 * is written into memory somewhere. Nonetheless we return the
569 * actual return value of the function.
572 // Introduce a temporary cleanup scope that will contain cleanups
573 // for the arguments while they are being evaluated. The purpose
574 // this cleanup is to ensure that, should a failure occur while
575 // evaluating argument N, the values for arguments 0...N-1 are all
576 // cleaned up. If no failure occurs, the values are handed off to
577 // the callee, and hence none of the cleanups in this temporary
578 // scope will ever execute.
581 let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
583 let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
584 let mut bcx = callee.bcx;
586 let (llfn, llenv, llself) = match callee.data {
591 (d.llfn, None, Some(d.llself))
594 // Closures are represented as (llfn, llclosure) pair:
595 // load the requisite values out.
596 let pair = d.to_llref();
597 let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]);
598 let llfn = Load(bcx, llfn);
599 let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]);
600 let llenv = Load(bcx, llenv);
601 (llfn, Some(llenv), None)
605 let (abi, ret_ty) = match ty::get(callee_ty).sty {
606 ty::ty_bare_fn(ref f) => (f.abis, f.sig.output),
607 ty::ty_closure(ref f) => (AbiSet::Rust(), f.sig.output),
608 _ => fail!("expected bare rust fn or closure in trans_call_inner")
614 // Generate a location to store the result. If the user does
615 // not care about the result, just make a stack slot.
616 let opt_llretslot = match dest {
618 assert!(!type_of::return_uses_outptr(ccx, ret_ty));
621 Some(expr::SaveIn(dst)) => Some(dst),
622 Some(expr::Ignore) => {
623 if !type_is_zero_size(ccx, ret_ty) {
624 Some(alloc_ty(bcx, ret_ty, "__llret"))
626 let llty = type_of::type_of(ccx, ret_ty);
627 Some(C_undef(llty.ptr_to()))
632 let mut llresult = unsafe {
633 llvm::LLVMGetUndef(Type::nil().ptr_to().to_ref())
636 // The code below invokes the function, using either the Rust
637 // conventions (if it is a rust fn) or the native conventions
638 // (otherwise). The important part is that, when all is sad
639 // and done, either the return value of the function will have been
640 // written in opt_llretslot (if it is Some) or `llresult` will be
641 // set appropriately (otherwise).
643 let mut llargs = ~[];
645 // Push the out-pointer if we use an out-pointer for this
646 // return type, otherwise push "undef".
647 if type_of::return_uses_outptr(ccx, ret_ty) {
648 llargs.push(opt_llretslot.unwrap());
651 // Push the environment (or a trait object's self).
652 match (llenv, llself) {
653 (Some(llenv), None) => llargs.push(llenv),
654 (None, Some(llself)) => llargs.push(llself),
658 // Push the arguments.
659 bcx = trans_args(bcx, args, callee_ty, &mut llargs,
660 cleanup::CustomScope(arg_cleanup_scope),
663 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
665 // A function pointer is called without the declaration
666 // available, so we have to apply any attributes with ABI
667 // implications directly to the call instruction. Right now,
668 // the only attribute we need to worry about is `sret`.
670 if type_of::return_uses_outptr(ccx, ret_ty) {
671 attrs.push((1, StructRetAttribute));
674 // The `noalias` attribute on the return value is useful to a
675 // function ptr caller.
676 match ty::get(ret_ty).sty {
677 // `~` pointer return values never alias because ownership
679 ty::ty_uniq(..) | ty::ty_vec(_, ty::vstore_uniq) => {
680 attrs.push((0, NoAliasAttribute));
685 // Invoke the actual rust fn and update bcx/llresult.
686 let (llret, b) = base::invoke(bcx, llfn, llargs, attrs, call_info);
690 // If the Rust convention for this type is return via
691 // the return value, copy it into llretslot.
692 match opt_llretslot {
694 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
695 !type_is_zero_size(bcx.ccx(), ret_ty)
697 Store(bcx, llret, llretslot);
703 // Lang items are the only case where dest is None, and
704 // they are always Rust fns.
705 assert!(dest.is_some());
707 let mut llargs = ~[];
708 bcx = trans_args(bcx, args, callee_ty, &mut llargs,
709 cleanup::CustomScope(arg_cleanup_scope), false);
710 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
711 let arg_tys = match args {
712 ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, *x)).collect(),
713 _ => fail!("expected arg exprs.")
715 bcx = foreign::trans_native_call(bcx, callee_ty,
716 llfn, opt_llretslot.unwrap(), llargs, arg_tys);
719 // If the caller doesn't care about the result of this fn call,
720 // drop the temporary slot we made.
723 assert!(!type_of::return_uses_outptr(bcx.ccx(), ret_ty));
725 Some(expr::Ignore) => {
726 // drop the value if it is not being saved.
727 bcx = glue::drop_ty(bcx, opt_llretslot.unwrap(), ret_ty);
729 Some(expr::SaveIn(_)) => { }
732 if ty::type_is_bot(ret_ty) {
739 pub enum CallArgs<'a> {
740 ArgExprs(&'a [@ast::Expr]),
741 // HACK used only by trans_overloaded_op.
742 ArgAutorefSecond(&'a ast::Expr, Option<&'a ast::Expr>),
743 ArgVals(&'a [ValueRef])
746 fn trans_args<'a>(cx: &'a Block<'a>,
749 llargs: &mut ~[ValueRef],
750 arg_cleanup_scope: cleanup::ScopeId,
753 let _icx = push_ctxt("trans_args");
754 let arg_tys = ty::ty_fn_args(fn_ty);
755 let variadic = ty::fn_is_variadic(fn_ty);
759 // First we figure out the caller's view of the types of the arguments.
760 // This will be needed if this is a generic call, because the callee has
761 // to cast her view of the arguments to the caller's view.
763 ArgExprs(arg_exprs) => {
764 let num_formal_args = arg_tys.len();
765 for (i, arg_expr) in arg_exprs.iter().enumerate() {
766 if i == 0 && ignore_self {
769 let arg_ty = if i >= num_formal_args {
771 expr_ty_adjusted(cx, *arg_expr)
775 llargs.push(unpack_result!(bcx, {
776 trans_arg_expr(bcx, arg_ty, *arg_expr,
782 ArgAutorefSecond(arg_expr, arg2) => {
785 llargs.push(unpack_result!(bcx, {
786 trans_arg_expr(bcx, arg_tys[0], arg_expr,
793 assert_eq!(arg_tys.len(), 2);
795 llargs.push(unpack_result!(bcx, {
796 trans_arg_expr(bcx, arg_tys[1], arg2_expr,
801 None => assert_eq!(arg_tys.len(), 1)
812 pub enum AutorefArg {
817 pub fn trans_arg_expr<'a>(
819 formal_arg_ty: ty::t,
820 arg_expr: &ast::Expr,
821 arg_cleanup_scope: cleanup::ScopeId,
822 autoref_arg: AutorefArg)
824 let _icx = push_ctxt("trans_arg_expr");
828 debug!("trans_arg_expr(formal_arg_ty=({}), arg_expr={})",
829 formal_arg_ty.repr(bcx.tcx()),
830 arg_expr.repr(bcx.tcx()));
832 // translate the arg expr to a datum
833 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, arg_expr));
834 let arg_datum_ty = arg_datum.ty;
836 debug!(" arg datum: {}", arg_datum.to_str(bcx.ccx()));
839 if ty::type_is_bot(arg_datum_ty) {
840 // For values of type _|_, we generate an
841 // "undef" value, as such a value should never
842 // be inspected. It's important for the value
843 // to have type lldestty (the callee's expected type).
844 let llformal_arg_ty = type_of::type_of(ccx, formal_arg_ty);
846 val = llvm::LLVMGetUndef(llformal_arg_ty.to_ref());
849 // FIXME(#3548) use the adjustments table
852 // We will pass argument by reference
853 // We want an lvalue, so that we can pass by reference and
854 let arg_datum = unpack_datum!(
855 bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_expr.id));
859 // Make this an rvalue, since we are going to be
860 // passing ownership.
861 let arg_datum = unpack_datum!(
862 bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
864 // Now that arg_datum is owned, get it into the appropriate
865 // mode (ref vs value).
866 let arg_datum = unpack_datum!(
867 bcx, arg_datum.to_appropriate_datum(bcx));
869 // Technically, ownership of val passes to the callee.
870 // However, we must cleanup should we fail before the
871 // callee is actually invoked.
872 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
876 if formal_arg_ty != arg_datum_ty {
877 // this could happen due to e.g. subtyping
878 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
879 debug!("casting actual type ({}) to match formal ({})",
880 bcx.val_to_str(val), bcx.llty_str(llformal_arg_ty));
881 val = PointerCast(bcx, val, llformal_arg_ty);
885 debug!("--- trans_arg_expr passing {}", bcx.val_to_str(val));
886 return rslt(bcx, val);