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 lib::llvm::ValueRef;
25 use metadata::csearch;
28 use middle::subst::{Subst, VecPerParamSpace};
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::common;
36 use middle::trans::common::*;
37 use middle::trans::datum::*;
38 use middle::trans::datum::{Datum, KindOps};
39 use middle::trans::expr;
40 use middle::trans::glue;
41 use middle::trans::inline;
42 use middle::trans::foreign;
43 use middle::trans::meth;
44 use middle::trans::monomorphize;
45 use middle::trans::type_::Type;
46 use middle::trans::type_of;
49 use middle::typeck::coherence::make_substs_for_receiver_types;
50 use middle::typeck::MethodCall;
51 use util::ppaux::Repr;
55 use synabi = syntax::abi;
58 pub struct MethodData {
64 Closure(Datum<Lvalue>),
66 // Represents a (possibly monomorphized) top-level fn item or method
67 // item. Note that this is just the fn-ptr and is not a Rust closure
68 // value (which is a pair).
69 Fn(/* llfn */ ValueRef),
71 TraitMethod(MethodData)
74 pub struct Callee<'a> {
75 pub bcx: &'a Block<'a>,
79 fn trans<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
80 let _icx = push_ctxt("trans_callee");
81 debug!("callee::trans(expr={})", expr.repr(bcx.tcx()));
83 // pick out special kinds of expressions that can be called:
86 return trans_def(bcx, bcx.def(expr.id), expr);
91 // any other expressions are closures:
92 return datum_callee(bcx, expr);
94 fn datum_callee<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
95 let DatumBlock {bcx: mut bcx, datum} = expr::trans(bcx, expr);
96 match ty::get(datum.ty).sty {
97 ty::ty_bare_fn(..) => {
98 let llval = datum.to_llscalarish(bcx);
99 return Callee {bcx: bcx, data: Fn(llval)};
101 ty::ty_closure(..) => {
102 let datum = unpack_datum!(
103 bcx, datum.to_lvalue_datum(bcx, "callee", expr.id));
104 return Callee {bcx: bcx, data: Closure(datum)};
107 bcx.tcx().sess.span_bug(
109 format!("type of callee is neither bare-fn nor closure: \
111 bcx.ty_to_str(datum.ty)).as_slice());
116 fn fn_callee<'a>(bcx: &'a Block<'a>, llfn: ValueRef) -> Callee<'a> {
117 return Callee {bcx: bcx, data: Fn(llfn)};
120 fn trans_def<'a>(bcx: &'a Block<'a>, def: def::Def, ref_expr: &ast::Expr)
124 def::DefStaticMethod(did, def::FromImpl(_), _) => {
125 fn_callee(bcx, trans_fn_ref(bcx, did, ExprId(ref_expr.id)))
127 def::DefStaticMethod(impl_did,
128 def::FromTrait(trait_did),
130 fn_callee(bcx, meth::trans_static_method_callee(bcx, impl_did,
134 def::DefVariant(tid, vid, _) => {
135 // nullary variants are not callable
136 assert!(ty::enum_variant_with_id(bcx.tcx(),
138 vid).args.len() > 0u);
139 fn_callee(bcx, trans_fn_ref(bcx, vid, ExprId(ref_expr.id)))
141 def::DefStruct(def_id) => {
142 fn_callee(bcx, trans_fn_ref(bcx, def_id, ExprId(ref_expr.id)))
147 def::DefBinding(..) |
148 def::DefUpvar(..) => {
149 datum_callee(bcx, ref_expr)
151 def::DefMod(..) | def::DefForeignMod(..) | def::DefTrait(..) |
152 def::DefTy(..) | def::DefPrimTy(..) |
153 def::DefUse(..) | def::DefTyParamBinder(..) |
154 def::DefRegion(..) | def::DefLabel(..) | def::DefTyParam(..) |
155 def::DefSelfTy(..) | def::DefMethod(..) => {
156 bcx.tcx().sess.span_bug(
158 format!("cannot translate def {:?} \
159 to a callable thing!", def).as_slice());
165 pub fn trans_fn_ref(bcx: &Block, def_id: ast::DefId, node: ExprOrMethodCall) -> ValueRef {
167 * Translates a reference (with id `ref_id`) to the fn/method
168 * with id `def_id` into a function pointer. This may require
169 * monomorphization or inlining.
172 let _icx = push_ctxt("trans_fn_ref");
174 let substs = node_id_substs(bcx, node);
175 let vtable_key = match node {
176 ExprId(id) => MethodCall::expr(id),
177 MethodCall(method_call) => method_call
179 let vtables = node_vtables(bcx, vtable_key);
180 debug!("trans_fn_ref(def_id={}, node={:?}, substs={}, vtables={})",
181 def_id.repr(bcx.tcx()),
183 substs.repr(bcx.tcx()),
184 vtables.repr(bcx.tcx()));
185 trans_fn_ref_with_vtables(bcx, def_id, node, substs, vtables)
188 fn trans_fn_ref_with_vtables_to_callee<'a>(bcx: &'a Block<'a>,
191 substs: subst::Substs,
192 vtables: typeck::vtable_res)
195 data: Fn(trans_fn_ref_with_vtables(bcx, def_id, ExprId(ref_id),
199 fn resolve_default_method_vtables(bcx: &Block,
201 substs: &subst::Substs,
202 impl_vtables: typeck::vtable_res)
203 -> typeck::vtable_res
205 // Get the vtables that the impl implements the trait at
206 let impl_res = ty::lookup_impl_vtables(bcx.tcx(), impl_id);
208 // Build up a param_substs that we are going to resolve the
209 // trait_vtables under.
210 let param_substs = param_substs {
211 substs: (*substs).clone(),
212 vtables: impl_vtables.clone()
215 let mut param_vtables = resolve_vtables_under_param_substs(
216 bcx.tcx(), ¶m_substs, &impl_res);
218 // Now we pull any vtables for parameters on the actual method.
219 param_vtables.push_all(subst::FnSpace,
220 impl_vtables.get_slice(subst::FnSpace));
225 /// Translates the adapter that deconstructs a `Box<Trait>` object into
226 /// `Trait` so that a by-value self method can be called.
227 pub fn trans_unboxing_shim(bcx: &Block,
228 llshimmedfn: ValueRef,
230 method_id: ast::DefId,
231 substs: subst::Substs)
233 let _icx = push_ctxt("trans_unboxing_shim");
237 // Transform the self type to `Box<self_type>`.
238 let self_type = *method.fty.sig.inputs.get(0);
239 let boxed_self_type = ty::mk_uniq(tcx, self_type);
240 let boxed_function_type = ty::FnSig {
241 binder_id: method.fty.sig.binder_id,
242 inputs: method.fty.sig.inputs.iter().enumerate().map(|(i, typ)| {
249 output: method.fty.sig.output,
252 let boxed_function_type = ty::BareFnTy {
253 fn_style: method.fty.fn_style,
255 sig: boxed_function_type,
257 let boxed_function_type =
258 ty::mk_bare_fn(tcx, boxed_function_type).subst(tcx, &substs);
260 ty::mk_bare_fn(tcx, method.fty.clone()).subst(tcx, &substs);
262 let function_name = ty::with_path(tcx, method_id, |path| {
263 link::mangle_internal_name_by_path_and_seq(path, "unboxing_shim")
265 let llfn = decl_internal_rust_fn(ccx,
267 function_name.as_slice());
269 let block_arena = TypedArena::new();
270 let empty_param_substs = param_substs::empty();
271 let return_type = ty::ty_fn_ret(boxed_function_type);
272 let fcx = new_fn_ctxt(ccx,
280 init_function(&fcx, false, return_type);
282 // Create the substituted versions of the self type.
283 let mut bcx = fcx.entry_bcx.borrow().clone().unwrap();
284 let arg_scope = fcx.push_custom_cleanup_scope();
285 let arg_scope_id = cleanup::CustomScope(arg_scope);
286 let boxed_arg_types = ty::ty_fn_args(boxed_function_type);
287 let boxed_self_type = *boxed_arg_types.get(0);
288 let arg_types = ty::ty_fn_args(function_type);
289 let self_type = *arg_types.get(0);
290 let boxed_self_kind = arg_kind(&fcx, boxed_self_type);
292 // Create a datum for self.
293 let llboxedself = unsafe {
294 llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(0) as u32)
296 let llboxedself = Datum::new(llboxedself,
301 llboxedself.to_lvalue_datum_in_scope(bcx,
305 // This `Load` is needed because lvalue data are always by-ref.
306 let llboxedself = Load(bcx, boxed_self.val);
308 let llself = if type_is_immediate(ccx, self_type) {
309 let llboxedself = Load(bcx, llboxedself);
310 immediate_rvalue(llboxedself, self_type)
312 let llself = rvalue_scratch_datum(bcx, self_type, "self");
313 memcpy_ty(bcx, llself.val, llboxedself, self_type);
317 // Make sure we don't free the box twice!
318 boxed_self.kind.post_store(bcx, boxed_self.val, boxed_self_type);
320 // Schedule a cleanup to free the box.
321 fcx.schedule_free_value(arg_scope_id,
323 cleanup::HeapExchange,
326 // Now call the function.
327 let mut llshimmedargs = vec!(llself.val);
328 for i in range(1, arg_types.len()) {
329 llshimmedargs.push(unsafe {
330 llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(i) as u32)
333 bcx = trans_call_inner(bcx,
339 data: Fn(llshimmedfn),
342 ArgVals(llshimmedargs.as_slice()),
343 match fcx.llretptr.get() {
345 Some(llretptr) => Some(expr::SaveIn(llretptr)),
348 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
349 finish_fn(&fcx, bcx);
354 pub fn trans_fn_ref_with_vtables(
356 def_id: ast::DefId, // def id of fn
357 node: ExprOrMethodCall, // node id of use of fn; may be zero if N/A
358 substs: subst::Substs, // values for fn's ty params
359 vtables: typeck::vtable_res) // vtables for the call
363 * Translates a reference to a fn/method item, monomorphizing and
364 * inlining as it goes.
368 * - `bcx`: the current block where the reference to the fn occurs
369 * - `def_id`: def id of the fn or method item being referenced
370 * - `node`: node id of the reference to the fn/method, if applicable.
371 * This parameter may be zero; but, if so, the resulting value may not
372 * have the right type, so it must be cast before being used.
373 * - `substs`: values for each of the fn/method's parameters
374 * - `vtables`: values for each bound on each of the type parameters
377 let _icx = push_ctxt("trans_fn_ref_with_vtables");
381 debug!("trans_fn_ref_with_vtables(bcx={}, def_id={}, node={:?}, \
382 substs={}, vtables={})",
389 assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
391 // Polytype of the function item (may have type params)
392 let fn_tpt = ty::lookup_item_type(tcx, def_id);
394 // Load the info for the appropriate trait if necessary.
395 match ty::trait_of_method(tcx, def_id) {
398 ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
402 // We need to do a bunch of special handling for default methods.
403 // We need to modify the def_id and our substs in order to monomorphize
405 let (is_default, def_id, substs, vtables) =
406 match ty::provided_source(tcx, def_id) {
407 None => (false, def_id, substs, vtables),
409 // There are two relevant substitutions when compiling
410 // default methods. First, there is the substitution for
411 // the type parameters of the impl we are using and the
412 // method we are calling. This substitution is the substs
413 // argument we already have.
414 // In order to compile a default method, though, we need
415 // to consider another substitution: the substitution for
416 // the type parameters on trait; the impl we are using
417 // implements the trait at some particular type
418 // parameters, and we need to substitute for those first.
419 // So, what we need to do is find this substitution and
420 // compose it with the one we already have.
422 let impl_id = ty::method(tcx, def_id).container_id();
423 let method = ty::method(tcx, source_id);
424 let trait_ref = ty::impl_trait_ref(tcx, impl_id)
425 .expect("could not find trait_ref for impl with \
428 // Compute the first substitution
429 let first_subst = make_substs_for_receiver_types(
430 tcx, &*trait_ref, &*method);
433 let new_substs = first_subst.subst(tcx, &substs);
435 debug!("trans_fn_with_vtables - default method: \
436 substs = {}, trait_subst = {}, \
437 first_subst = {}, new_subst = {}, \
439 substs.repr(tcx), trait_ref.substs.repr(tcx),
440 first_subst.repr(tcx), new_substs.repr(tcx),
444 resolve_default_method_vtables(bcx, impl_id, &substs, vtables);
446 debug!("trans_fn_with_vtables - default method: \
448 param_vtables.repr(tcx));
450 (true, source_id, new_substs, param_vtables)
454 // Check whether this fn has an inlined copy and, if so, redirect
455 // def_id to the local id of the inlined copy.
457 if def_id.krate != ast::LOCAL_CRATE {
458 inline::maybe_instantiate_inline(ccx, def_id)
464 // We must monomorphise if the fn has type parameters, is a rust
465 // intrinsic, or is a default method. In particular, if we see an
466 // intrinsic that is inlined from a different crate, we want to reemit the
467 // intrinsic instead of trying to call it in the other crate.
468 let must_monomorphise = if !substs.types.is_empty() || is_default {
470 } else if def_id.krate == ast::LOCAL_CRATE {
471 let map_node = session::expect(
473 tcx.map.find(def_id.node),
474 || "local item should be in ast map".to_string());
477 ast_map::NodeForeignItem(_) => {
478 tcx.map.get_foreign_abi(def_id.node) == synabi::RustIntrinsic
486 // Create a monomorphic version of generic functions
487 if must_monomorphise {
488 // Should be either intra-crate or inlined.
489 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
491 let opt_ref_id = match node {
492 ExprId(id) => if id != 0 { Some(id) } else { None },
493 MethodCall(_) => None,
496 let (val, must_cast) =
497 monomorphize::monomorphic_fn(ccx, def_id, &substs,
498 vtables, opt_ref_id);
500 if must_cast && node != ExprId(0) {
501 // Monotype of the REFERENCE to the function (type params
503 let ref_ty = match node {
504 ExprId(id) => node_id_type(bcx, id),
505 MethodCall(method_call) => {
506 let t = bcx.tcx().method_map.borrow().get(&method_call).ty;
507 monomorphize_type(bcx, t)
512 bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
517 // Find the actual function pointer.
519 if def_id.krate == ast::LOCAL_CRATE {
520 // Internal reference.
521 get_item_val(ccx, def_id.node)
523 // External reference.
524 trans_external_path(ccx, def_id, fn_tpt.ty)
528 // This is subtle and surprising, but sometimes we have to bitcast
529 // the resulting fn pointer. The reason has to do with external
530 // functions. If you have two crates that both bind the same C
531 // library, they may not use precisely the same types: for
532 // example, they will probably each declare their own structs,
533 // which are distinct types from LLVM's point of view (nominal
536 // Now, if those two crates are linked into an application, and
537 // they contain inlined code, you can wind up with a situation
538 // where both of those functions wind up being loaded into this
539 // application simultaneously. In that case, the same function
540 // (from LLVM's point of view) requires two types. But of course
541 // LLVM won't allow one function to have two types.
543 // What we currently do, therefore, is declare the function with
544 // one of the two types (whichever happens to come first) and then
545 // bitcast as needed when the function is referenced to make sure
546 // it has the type we expect.
548 // This can occur on either a crate-local or crate-external
549 // reference. It also occurs when testing libcore and in some
550 // other weird situations. Annoying.
551 let llty = type_of::type_of_fn_from_ty(ccx, fn_tpt.ty);
552 let llptrty = llty.ptr_to();
553 if val_ty(val) != llptrty {
554 val = BitCast(bcx, val, llptrty);
560 // ______________________________________________________________________
563 pub fn trans_call<'a>(
564 in_cx: &'a Block<'a>,
570 let _icx = push_ctxt("trans_call");
571 trans_call_inner(in_cx,
572 Some(common::expr_info(call_ex)),
574 |cx, _| trans(cx, f),
579 pub fn trans_method_call<'a>(
586 let _icx = push_ctxt("trans_method_call");
587 debug!("trans_method_call(call_ex={})", call_ex.repr(bcx.tcx()));
588 let method_call = MethodCall::expr(call_ex.id);
589 let method_ty = bcx.tcx().method_map.borrow().get(&method_call).ty;
592 Some(common::expr_info(call_ex)),
593 monomorphize_type(bcx, method_ty),
594 |cx, arg_cleanup_scope| {
595 meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
601 pub fn trans_lang_call<'a>(
605 dest: Option<expr::Dest>)
607 let fty = if did.krate == ast::LOCAL_CRATE {
608 ty::node_id_to_type(bcx.tcx(), did.node)
610 csearch::get_type(bcx.tcx(), did).ty
612 callee::trans_call_inner(bcx,
616 trans_fn_ref_with_vtables_to_callee(bcx,
619 subst::Substs::empty(),
620 VecPerParamSpace::empty())
626 pub fn trans_call_inner<'a>(
628 call_info: Option<NodeInfo>,
630 get_callee: |bcx: &'a Block<'a>,
631 arg_cleanup_scope: cleanup::ScopeId|
634 dest: Option<expr::Dest>)
637 * This behemoth of a function translates function calls.
638 * Unfortunately, in order to generate more efficient LLVM
639 * output at -O0, it has quite a complex signature (refactoring
640 * this into two functions seems like a good idea).
642 * In particular, for lang items, it is invoked with a dest of
643 * None, and in that case the return value contains the result of
644 * the fn. The lang item must not return a structural type or else
645 * all heck breaks loose.
647 * For non-lang items, `dest` is always Some, and hence the result
648 * is written into memory somewhere. Nonetheless we return the
649 * actual return value of the function.
652 // Introduce a temporary cleanup scope that will contain cleanups
653 // for the arguments while they are being evaluated. The purpose
654 // this cleanup is to ensure that, should a failure occur while
655 // evaluating argument N, the values for arguments 0...N-1 are all
656 // cleaned up. If no failure occurs, the values are handed off to
657 // the callee, and hence none of the cleanups in this temporary
658 // scope will ever execute.
661 let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
663 let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
664 let mut bcx = callee.bcx;
666 let (llfn, llenv, llself) = match callee.data {
671 (d.llfn, None, Some(d.llself))
674 // Closures are represented as (llfn, llclosure) pair:
675 // load the requisite values out.
676 let pair = d.to_llref();
677 let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]);
678 let llfn = Load(bcx, llfn);
679 let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]);
680 let llenv = Load(bcx, llenv);
681 (llfn, Some(llenv), None)
685 let (abi, ret_ty) = match ty::get(callee_ty).sty {
686 ty::ty_bare_fn(ref f) => (f.abi, f.sig.output),
687 ty::ty_closure(ref f) => (synabi::Rust, f.sig.output),
688 _ => fail!("expected bare rust fn or closure in trans_call_inner")
690 let is_rust_fn = abi == synabi::Rust || abi == synabi::RustIntrinsic;
692 // Generate a location to store the result. If the user does
693 // not care about the result, just make a stack slot.
694 let opt_llretslot = match dest {
696 assert!(!type_of::return_uses_outptr(ccx, ret_ty));
699 Some(expr::SaveIn(dst)) => Some(dst),
700 Some(expr::Ignore) => {
701 if !type_is_zero_size(ccx, ret_ty) {
702 Some(alloc_ty(bcx, ret_ty, "__llret"))
704 let llty = type_of::type_of(ccx, ret_ty);
705 Some(C_undef(llty.ptr_to()))
710 let mut llresult = unsafe {
711 llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
714 // The code below invokes the function, using either the Rust
715 // conventions (if it is a rust fn) or the native conventions
716 // (otherwise). The important part is that, when all is sad
717 // and done, either the return value of the function will have been
718 // written in opt_llretslot (if it is Some) or `llresult` will be
719 // set appropriately (otherwise).
721 let mut llargs = Vec::new();
723 // Push the out-pointer if we use an out-pointer for this
724 // return type, otherwise push "undef".
725 if type_of::return_uses_outptr(ccx, ret_ty) {
726 llargs.push(opt_llretslot.unwrap());
729 // Push the environment (or a trait object's self).
730 match (llenv, llself) {
731 (Some(llenv), None) => {
734 (None, Some(llself)) => llargs.push(llself),
738 // Push the arguments.
739 bcx = trans_args(bcx, args, callee_ty, &mut llargs,
740 cleanup::CustomScope(arg_cleanup_scope),
743 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
745 // Invoke the actual rust fn and update bcx/llresult.
746 let (llret, b) = base::invoke(bcx,
754 // If the Rust convention for this type is return via
755 // the return value, copy it into llretslot.
756 match opt_llretslot {
758 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
759 !type_is_zero_size(bcx.ccx(), ret_ty)
761 Store(bcx, llret, llretslot);
767 // Lang items are the only case where dest is None, and
768 // they are always Rust fns.
769 assert!(dest.is_some());
771 let mut llargs = Vec::new();
772 let arg_tys = match args {
773 ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, &**x)).collect(),
774 _ => fail!("expected arg exprs.")
776 bcx = trans_args(bcx, args, callee_ty, &mut llargs,
777 cleanup::CustomScope(arg_cleanup_scope), false);
778 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
779 bcx = foreign::trans_native_call(bcx, callee_ty,
780 llfn, opt_llretslot.unwrap(),
781 llargs.as_slice(), arg_tys);
784 // If the caller doesn't care about the result of this fn call,
785 // drop the temporary slot we made.
788 assert!(!type_of::return_uses_outptr(bcx.ccx(), ret_ty));
790 Some(expr::Ignore) => {
791 // drop the value if it is not being saved.
792 bcx = glue::drop_ty(bcx, opt_llretslot.unwrap(), ret_ty);
794 Some(expr::SaveIn(_)) => { }
797 if ty::type_is_bot(ret_ty) {
801 Result::new(bcx, llresult)
804 pub enum CallArgs<'a> {
805 // Supply value of arguments as a list of expressions that must be
806 // translated. This is used in the common case of `foo(bar, qux)`.
807 ArgExprs(&'a [Gc<ast::Expr>]),
809 // Supply value of arguments as a list of LLVM value refs; frequently
810 // used with lang items and so forth, when the argument is an internal
812 ArgVals(&'a [ValueRef]),
814 // For overloaded operators: `(lhs, Option(rhs, rhs_id))`. `lhs`
815 // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
816 // the right-hand-side (if any).
817 ArgOverloadedOp(Datum<Expr>, Option<(Datum<Expr>, ast::NodeId)>),
820 fn trans_args<'a>(cx: &'a Block<'a>,
823 llargs: &mut Vec<ValueRef> ,
824 arg_cleanup_scope: cleanup::ScopeId,
827 let _icx = push_ctxt("trans_args");
828 let arg_tys = ty::ty_fn_args(fn_ty);
829 let variadic = ty::fn_is_variadic(fn_ty);
833 // First we figure out the caller's view of the types of the arguments.
834 // This will be needed if this is a generic call, because the callee has
835 // to cast her view of the arguments to the caller's view.
837 ArgExprs(arg_exprs) => {
838 let num_formal_args = arg_tys.len();
839 for (i, arg_expr) in arg_exprs.iter().enumerate() {
840 if i == 0 && ignore_self {
843 let arg_ty = if i >= num_formal_args {
845 expr_ty_adjusted(cx, &**arg_expr)
850 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
851 llargs.push(unpack_result!(bcx, {
852 trans_arg_datum(bcx, arg_ty, arg_datum,
858 ArgOverloadedOp(lhs, rhs) => {
861 llargs.push(unpack_result!(bcx, {
862 trans_arg_datum(bcx, *arg_tys.get(0), lhs,
868 Some((rhs, rhs_id)) => {
869 assert_eq!(arg_tys.len(), 2);
871 llargs.push(unpack_result!(bcx, {
872 trans_arg_datum(bcx, *arg_tys.get(1), rhs,
874 DoAutorefArg(rhs_id))
877 None => assert_eq!(arg_tys.len(), 1)
888 pub enum AutorefArg {
890 DoAutorefArg(ast::NodeId)
893 pub fn trans_arg_datum<'a>(
895 formal_arg_ty: ty::t,
896 arg_datum: Datum<Expr>,
897 arg_cleanup_scope: cleanup::ScopeId,
898 autoref_arg: AutorefArg)
900 let _icx = push_ctxt("trans_arg_datum");
904 debug!("trans_arg_datum({})",
905 formal_arg_ty.repr(bcx.tcx()));
907 let arg_datum_ty = arg_datum.ty;
909 debug!(" arg datum: {}", arg_datum.to_str(bcx.ccx()));
912 if ty::type_is_bot(arg_datum_ty) {
913 // For values of type _|_, we generate an
914 // "undef" value, as such a value should never
915 // be inspected. It's important for the value
916 // to have type lldestty (the callee's expected type).
917 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
919 val = llvm::LLVMGetUndef(llformal_arg_ty.to_ref());
922 // FIXME(#3548) use the adjustments table
924 DoAutorefArg(arg_id) => {
925 // We will pass argument by reference
926 // We want an lvalue, so that we can pass by reference and
927 let arg_datum = unpack_datum!(
928 bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
932 // Make this an rvalue, since we are going to be
933 // passing ownership.
934 let arg_datum = unpack_datum!(
935 bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
937 // Now that arg_datum is owned, get it into the appropriate
938 // mode (ref vs value).
939 let arg_datum = unpack_datum!(
940 bcx, arg_datum.to_appropriate_datum(bcx));
942 // Technically, ownership of val passes to the callee.
943 // However, we must cleanup should we fail before the
944 // callee is actually invoked.
945 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
949 if formal_arg_ty != arg_datum_ty {
950 // this could happen due to e.g. subtyping
951 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
952 debug!("casting actual type ({}) to match formal ({})",
953 bcx.val_to_str(val), bcx.llty_str(llformal_arg_ty));
954 val = PointerCast(bcx, val, llformal_arg_ty);
958 debug!("--- trans_arg_datum passing {}", bcx.val_to_str(val));
959 Result::new(bcx, val)