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 lib::llvm::ValueRef;
24 use metadata::csearch;
27 use middle::subst::{Subst, VecPerParamSpace};
28 use middle::trans::base;
29 use middle::trans::base::*;
30 use middle::trans::build::*;
31 use middle::trans::callee;
32 use middle::trans::cleanup;
33 use middle::trans::cleanup::CleanupMethods;
34 use middle::trans::common;
35 use middle::trans::common::*;
36 use middle::trans::datum::*;
37 use middle::trans::datum::{Datum, KindOps};
38 use middle::trans::expr;
39 use middle::trans::glue;
40 use middle::trans::inline;
41 use middle::trans::foreign;
42 use middle::trans::intrinsic;
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;
57 pub struct MethodData {
63 Closure(Datum<Lvalue>),
65 // Represents a (possibly monomorphized) top-level fn item or method
66 // item. Note that this is just the fn-ptr and is not a Rust closure
67 // value (which is a pair).
68 Fn(/* llfn */ ValueRef),
70 Intrinsic(ast::NodeId, subst::Substs),
72 TraitMethod(MethodData)
75 pub struct Callee<'a> {
76 pub bcx: &'a Block<'a>,
80 fn trans<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
81 let _icx = push_ctxt("trans_callee");
82 debug!("callee::trans(expr={})", expr.repr(bcx.tcx()));
84 // pick out special kinds of expressions that can be called:
87 return trans_def(bcx, bcx.def(expr.id), expr);
92 // any other expressions are closures:
93 return datum_callee(bcx, expr);
95 fn datum_callee<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
96 let DatumBlock {bcx: mut bcx, datum} = expr::trans(bcx, expr);
97 match ty::get(datum.ty).sty {
98 ty::ty_bare_fn(..) => {
99 let llval = datum.to_llscalarish(bcx);
100 return Callee {bcx: bcx, data: Fn(llval)};
102 ty::ty_closure(..) => {
103 let datum = unpack_datum!(
104 bcx, datum.to_lvalue_datum(bcx, "callee", expr.id));
105 return Callee {bcx: bcx, data: Closure(datum)};
108 bcx.tcx().sess.span_bug(
110 format!("type of callee is neither bare-fn nor closure: \
112 bcx.ty_to_string(datum.ty)).as_slice());
117 fn fn_callee<'a>(bcx: &'a Block<'a>, llfn: ValueRef) -> Callee<'a> {
118 return Callee {bcx: bcx, data: Fn(llfn)};
121 fn trans_def<'a>(bcx: &'a Block<'a>, def: def::Def, ref_expr: &ast::Expr)
123 debug!("trans_def(def={}, ref_expr={})", def.repr(bcx.tcx()), ref_expr.repr(bcx.tcx()));
124 let expr_ty = node_id_type(bcx, ref_expr.id);
126 def::DefFn(did, _) if match ty::get(expr_ty).sty {
127 ty::ty_bare_fn(ref f) => f.abi == synabi::RustIntrinsic,
130 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
131 let def_id = if did.krate != ast::LOCAL_CRATE {
132 inline::maybe_instantiate_inline(bcx.ccx(), did)
136 Callee { bcx: bcx, data: Intrinsic(def_id.node, substs) }
139 def::DefStaticMethod(did, def::FromImpl(_), _) => {
140 fn_callee(bcx, trans_fn_ref(bcx, did, ExprId(ref_expr.id)))
142 def::DefStaticMethod(impl_did,
143 def::FromTrait(trait_did),
145 fn_callee(bcx, meth::trans_static_method_callee(bcx, impl_did,
149 def::DefVariant(tid, vid, _) => {
150 // nullary variants are not callable
151 assert!(ty::enum_variant_with_id(bcx.tcx(),
153 vid).args.len() > 0u);
154 fn_callee(bcx, trans_fn_ref(bcx, vid, ExprId(ref_expr.id)))
156 def::DefStruct(def_id) => {
157 fn_callee(bcx, trans_fn_ref(bcx, def_id, ExprId(ref_expr.id)))
162 def::DefBinding(..) |
163 def::DefUpvar(..) => {
164 datum_callee(bcx, ref_expr)
166 def::DefMod(..) | def::DefForeignMod(..) | def::DefTrait(..) |
167 def::DefTy(..) | def::DefPrimTy(..) |
168 def::DefUse(..) | def::DefTyParamBinder(..) |
169 def::DefRegion(..) | def::DefLabel(..) | def::DefTyParam(..) |
170 def::DefSelfTy(..) | def::DefMethod(..) => {
171 bcx.tcx().sess.span_bug(
173 format!("cannot translate def {:?} \
174 to a callable thing!", def).as_slice());
180 pub fn trans_fn_ref(bcx: &Block, def_id: ast::DefId, node: ExprOrMethodCall) -> ValueRef {
182 * Translates a reference (with id `ref_id`) to the fn/method
183 * with id `def_id` into a function pointer. This may require
184 * monomorphization or inlining.
187 let _icx = push_ctxt("trans_fn_ref");
189 let substs = node_id_substs(bcx, node);
190 let vtable_key = match node {
191 ExprId(id) => MethodCall::expr(id),
192 MethodCall(method_call) => method_call
194 let vtables = node_vtables(bcx, vtable_key);
195 debug!("trans_fn_ref(def_id={}, node={:?}, substs={}, vtables={})",
196 def_id.repr(bcx.tcx()),
198 substs.repr(bcx.tcx()),
199 vtables.repr(bcx.tcx()));
200 trans_fn_ref_with_vtables(bcx, def_id, node, substs, vtables)
203 fn trans_fn_ref_with_vtables_to_callee<'a>(bcx: &'a Block<'a>,
206 substs: subst::Substs,
207 vtables: typeck::vtable_res)
210 data: Fn(trans_fn_ref_with_vtables(bcx, def_id, ExprId(ref_id),
214 fn resolve_default_method_vtables(bcx: &Block,
216 substs: &subst::Substs,
217 impl_vtables: typeck::vtable_res)
218 -> typeck::vtable_res
220 // Get the vtables that the impl implements the trait at
221 let impl_res = ty::lookup_impl_vtables(bcx.tcx(), impl_id);
223 // Build up a param_substs that we are going to resolve the
224 // trait_vtables under.
225 let param_substs = param_substs {
226 substs: (*substs).clone(),
227 vtables: impl_vtables.clone()
230 let mut param_vtables = resolve_vtables_under_param_substs(
231 bcx.tcx(), ¶m_substs, &impl_res);
233 // Now we pull any vtables for parameters on the actual method.
234 param_vtables.push_all(subst::FnSpace,
235 impl_vtables.get_slice(subst::FnSpace));
240 /// Translates the adapter that deconstructs a `Box<Trait>` object into
241 /// `Trait` so that a by-value self method can be called.
242 pub fn trans_unboxing_shim(bcx: &Block,
243 llshimmedfn: ValueRef,
245 method_id: ast::DefId,
246 substs: subst::Substs)
248 let _icx = push_ctxt("trans_unboxing_shim");
252 // Transform the self type to `Box<self_type>`.
253 let self_type = *method.fty.sig.inputs.get(0);
254 let boxed_self_type = ty::mk_uniq(tcx, self_type);
255 let boxed_function_type = ty::FnSig {
256 binder_id: method.fty.sig.binder_id,
257 inputs: method.fty.sig.inputs.iter().enumerate().map(|(i, typ)| {
264 output: method.fty.sig.output,
267 let boxed_function_type = ty::BareFnTy {
268 fn_style: method.fty.fn_style,
270 sig: boxed_function_type,
272 let boxed_function_type =
273 ty::mk_bare_fn(tcx, boxed_function_type).subst(tcx, &substs);
275 ty::mk_bare_fn(tcx, method.fty.clone()).subst(tcx, &substs);
277 let function_name = ty::with_path(tcx, method_id, |path| {
278 link::mangle_internal_name_by_path_and_seq(path, "unboxing_shim")
280 let llfn = decl_internal_rust_fn(ccx,
282 function_name.as_slice());
284 let block_arena = TypedArena::new();
285 let empty_param_substs = param_substs::empty();
286 let return_type = ty::ty_fn_ret(boxed_function_type);
287 let fcx = new_fn_ctxt(ccx,
295 let mut bcx = init_function(&fcx, false, return_type);
297 // Create the substituted versions of the self type.
298 let arg_scope = fcx.push_custom_cleanup_scope();
299 let arg_scope_id = cleanup::CustomScope(arg_scope);
300 let boxed_arg_types = ty::ty_fn_args(boxed_function_type);
301 let boxed_self_type = *boxed_arg_types.get(0);
302 let arg_types = ty::ty_fn_args(function_type);
303 let self_type = *arg_types.get(0);
304 let boxed_self_kind = arg_kind(&fcx, boxed_self_type);
306 // Create a datum for self.
307 let llboxedself = unsafe {
308 llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(0) as u32)
310 let llboxedself = Datum::new(llboxedself,
315 llboxedself.to_lvalue_datum_in_scope(bcx,
319 // This `Load` is needed because lvalue data are always by-ref.
320 let llboxedself = Load(bcx, boxed_self.val);
322 let llself = if type_is_immediate(ccx, self_type) {
323 let llboxedself = Load(bcx, llboxedself);
324 immediate_rvalue(llboxedself, self_type)
326 let llself = rvalue_scratch_datum(bcx, self_type, "self");
327 memcpy_ty(bcx, llself.val, llboxedself, self_type);
331 // Make sure we don't free the box twice!
332 boxed_self.kind.post_store(bcx, boxed_self.val, boxed_self_type);
334 // Schedule a cleanup to free the box.
335 fcx.schedule_free_value(arg_scope_id,
337 cleanup::HeapExchange,
340 // Now call the function.
341 let mut llshimmedargs = vec!(llself.val);
342 for i in range(1, arg_types.len()) {
343 llshimmedargs.push(unsafe {
344 llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(i) as u32)
347 bcx = trans_call_inner(bcx,
353 data: Fn(llshimmedfn),
356 ArgVals(llshimmedargs.as_slice()),
357 match fcx.llretptr.get() {
359 Some(llretptr) => Some(expr::SaveIn(llretptr)),
362 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
363 finish_fn(&fcx, bcx, return_type);
368 pub fn trans_fn_ref_with_vtables(
370 def_id: ast::DefId, // def id of fn
371 node: ExprOrMethodCall, // node id of use of fn; may be zero if N/A
372 substs: subst::Substs, // values for fn's ty params
373 vtables: typeck::vtable_res) // vtables for the call
377 * Translates a reference to a fn/method item, monomorphizing and
378 * inlining as it goes.
382 * - `bcx`: the current block where the reference to the fn occurs
383 * - `def_id`: def id of the fn or method item being referenced
384 * - `node`: node id of the reference to the fn/method, if applicable.
385 * This parameter may be zero; but, if so, the resulting value may not
386 * have the right type, so it must be cast before being used.
387 * - `substs`: values for each of the fn/method's parameters
388 * - `vtables`: values for each bound on each of the type parameters
391 let _icx = push_ctxt("trans_fn_ref_with_vtables");
395 debug!("trans_fn_ref_with_vtables(bcx={}, def_id={}, node={:?}, \
396 substs={}, vtables={})",
403 assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
405 // Polytype of the function item (may have type params)
406 let fn_tpt = ty::lookup_item_type(tcx, def_id);
408 // Load the info for the appropriate trait if necessary.
409 match ty::trait_of_method(tcx, def_id) {
412 ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
416 // We need to do a bunch of special handling for default methods.
417 // We need to modify the def_id and our substs in order to monomorphize
419 let (is_default, def_id, substs, vtables) =
420 match ty::provided_source(tcx, def_id) {
421 None => (false, def_id, substs, vtables),
423 // There are two relevant substitutions when compiling
424 // default methods. First, there is the substitution for
425 // the type parameters of the impl we are using and the
426 // method we are calling. This substitution is the substs
427 // argument we already have.
428 // In order to compile a default method, though, we need
429 // to consider another substitution: the substitution for
430 // the type parameters on trait; the impl we are using
431 // implements the trait at some particular type
432 // parameters, and we need to substitute for those first.
433 // So, what we need to do is find this substitution and
434 // compose it with the one we already have.
436 let impl_id = ty::method(tcx, def_id).container_id();
437 let method = ty::method(tcx, source_id);
438 let trait_ref = ty::impl_trait_ref(tcx, impl_id)
439 .expect("could not find trait_ref for impl with \
442 // Compute the first substitution
443 let first_subst = make_substs_for_receiver_types(
444 tcx, &*trait_ref, &*method);
447 let new_substs = first_subst.subst(tcx, &substs);
449 debug!("trans_fn_with_vtables - default method: \
450 substs = {}, trait_subst = {}, \
451 first_subst = {}, new_subst = {}, \
453 substs.repr(tcx), trait_ref.substs.repr(tcx),
454 first_subst.repr(tcx), new_substs.repr(tcx),
458 resolve_default_method_vtables(bcx, impl_id, &substs, vtables);
460 debug!("trans_fn_with_vtables - default method: \
462 param_vtables.repr(tcx));
464 (true, source_id, new_substs, param_vtables)
468 // Check whether this fn has an inlined copy and, if so, redirect
469 // def_id to the local id of the inlined copy.
471 if def_id.krate != ast::LOCAL_CRATE {
472 inline::maybe_instantiate_inline(ccx, def_id)
478 // We must monomorphise if the fn has type parameters or is a default method.
479 let must_monomorphise = !substs.types.is_empty() || is_default;
481 // Create a monomorphic version of generic functions
482 if must_monomorphise {
483 // Should be either intra-crate or inlined.
484 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
486 let opt_ref_id = match node {
487 ExprId(id) => if id != 0 { Some(id) } else { None },
488 MethodCall(_) => None,
491 let (val, must_cast) =
492 monomorphize::monomorphic_fn(ccx, def_id, &substs,
493 vtables, opt_ref_id);
495 if must_cast && node != ExprId(0) {
496 // Monotype of the REFERENCE to the function (type params
498 let ref_ty = match node {
499 ExprId(id) => node_id_type(bcx, id),
500 MethodCall(method_call) => {
501 let t = bcx.tcx().method_map.borrow().get(&method_call).ty;
502 monomorphize_type(bcx, t)
507 bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
512 // Find the actual function pointer.
514 if def_id.krate == ast::LOCAL_CRATE {
515 // Internal reference.
516 get_item_val(ccx, def_id.node)
518 // External reference.
519 trans_external_path(ccx, def_id, fn_tpt.ty)
523 // This is subtle and surprising, but sometimes we have to bitcast
524 // the resulting fn pointer. The reason has to do with external
525 // functions. If you have two crates that both bind the same C
526 // library, they may not use precisely the same types: for
527 // example, they will probably each declare their own structs,
528 // which are distinct types from LLVM's point of view (nominal
531 // Now, if those two crates are linked into an application, and
532 // they contain inlined code, you can wind up with a situation
533 // where both of those functions wind up being loaded into this
534 // application simultaneously. In that case, the same function
535 // (from LLVM's point of view) requires two types. But of course
536 // LLVM won't allow one function to have two types.
538 // What we currently do, therefore, is declare the function with
539 // one of the two types (whichever happens to come first) and then
540 // bitcast as needed when the function is referenced to make sure
541 // it has the type we expect.
543 // This can occur on either a crate-local or crate-external
544 // reference. It also occurs when testing libcore and in some
545 // other weird situations. Annoying.
546 let llty = type_of::type_of_fn_from_ty(ccx, fn_tpt.ty);
547 let llptrty = llty.ptr_to();
548 if val_ty(val) != llptrty {
549 val = BitCast(bcx, val, llptrty);
555 // ______________________________________________________________________
558 pub fn trans_call<'a>(
559 in_cx: &'a Block<'a>,
565 let _icx = push_ctxt("trans_call");
566 trans_call_inner(in_cx,
567 Some(common::expr_info(call_ex)),
569 |cx, _| trans(cx, f),
574 pub fn trans_method_call<'a>(
581 let _icx = push_ctxt("trans_method_call");
582 debug!("trans_method_call(call_ex={})", call_ex.repr(bcx.tcx()));
583 let method_call = MethodCall::expr(call_ex.id);
584 let method_ty = bcx.tcx().method_map.borrow().get(&method_call).ty;
587 Some(common::expr_info(call_ex)),
588 monomorphize_type(bcx, method_ty),
589 |cx, arg_cleanup_scope| {
590 meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
596 pub fn trans_lang_call<'a>(
600 dest: Option<expr::Dest>)
602 let fty = if did.krate == ast::LOCAL_CRATE {
603 ty::node_id_to_type(bcx.tcx(), did.node)
605 csearch::get_type(bcx.tcx(), did).ty
607 callee::trans_call_inner(bcx,
611 trans_fn_ref_with_vtables_to_callee(bcx,
614 subst::Substs::empty(),
615 VecPerParamSpace::empty())
621 pub fn trans_call_inner<'a>(
623 call_info: Option<NodeInfo>,
625 get_callee: |bcx: &'a Block<'a>,
626 arg_cleanup_scope: cleanup::ScopeId|
629 dest: Option<expr::Dest>)
632 * This behemoth of a function translates function calls.
633 * Unfortunately, in order to generate more efficient LLVM
634 * output at -O0, it has quite a complex signature (refactoring
635 * this into two functions seems like a good idea).
637 * In particular, for lang items, it is invoked with a dest of
638 * None, and in that case the return value contains the result of
639 * the fn. The lang item must not return a structural type or else
640 * all heck breaks loose.
642 * For non-lang items, `dest` is always Some, and hence the result
643 * is written into memory somewhere. Nonetheless we return the
644 * actual return value of the function.
647 // Introduce a temporary cleanup scope that will contain cleanups
648 // for the arguments while they are being evaluated. The purpose
649 // this cleanup is to ensure that, should a failure occur while
650 // evaluating argument N, the values for arguments 0...N-1 are all
651 // cleaned up. If no failure occurs, the values are handed off to
652 // the callee, and hence none of the cleanups in this temporary
653 // scope will ever execute.
656 let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
658 let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
659 let mut bcx = callee.bcx;
661 let (abi, ret_ty) = match ty::get(callee_ty).sty {
662 ty::ty_bare_fn(ref f) => (f.abi, f.sig.output),
663 ty::ty_closure(ref f) => (synabi::Rust, f.sig.output),
664 _ => fail!("expected bare rust fn or closure in trans_call_inner")
667 let (llfn, llenv, llself) = match callee.data {
672 (d.llfn, None, Some(d.llself))
675 // Closures are represented as (llfn, llclosure) pair:
676 // load the requisite values out.
677 let pair = d.to_llref();
678 let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]);
679 let llfn = Load(bcx, llfn);
680 let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]);
681 let llenv = Load(bcx, llenv);
682 (llfn, Some(llenv), None)
684 Intrinsic(node, substs) => {
685 assert!(abi == synabi::RustIntrinsic);
686 assert!(dest.is_some());
688 return intrinsic::trans_intrinsic_call(bcx, node, callee_ty,
689 arg_cleanup_scope, args,
690 dest.unwrap(), substs);
694 // Intrinsics should not become actual functions.
695 // We trans them in place in `trans_intrinsic_call`
696 assert!(abi != synabi::RustIntrinsic);
698 // Generate a location to store the result. If the user does
699 // not care about the result, just make a stack slot.
700 let opt_llretslot = match dest {
702 assert!(!type_of::return_uses_outptr(ccx, ret_ty));
705 Some(expr::SaveIn(dst)) => Some(dst),
706 Some(expr::Ignore) => {
707 if !type_is_zero_size(ccx, ret_ty) {
708 Some(alloc_ty(bcx, ret_ty, "__llret"))
710 let llty = type_of::type_of(ccx, ret_ty);
711 Some(C_undef(llty.ptr_to()))
716 let mut llresult = unsafe {
717 llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
720 // The code below invokes the function, using either the Rust
721 // conventions (if it is a rust fn) or the native conventions
722 // (otherwise). The important part is that, when all is sad
723 // and done, either the return value of the function will have been
724 // written in opt_llretslot (if it is Some) or `llresult` will be
725 // set appropriately (otherwise).
726 if abi == synabi::Rust {
727 let mut llargs = Vec::new();
729 // Push the out-pointer if we use an out-pointer for this
730 // return type, otherwise push "undef".
731 if type_of::return_uses_outptr(ccx, ret_ty) {
732 llargs.push(opt_llretslot.unwrap());
735 // Push the environment (or a trait object's self).
736 match (llenv, llself) {
737 (Some(llenv), None) => {
740 (None, Some(llself)) => llargs.push(llself),
744 // Push the arguments.
745 bcx = trans_args(bcx, args, callee_ty, &mut llargs,
746 cleanup::CustomScope(arg_cleanup_scope),
749 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
751 // Invoke the actual rust fn and update bcx/llresult.
752 let (llret, b) = base::invoke(bcx,
760 // If the Rust convention for this type is return via
761 // the return value, copy it into llretslot.
762 match opt_llretslot {
764 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
765 !type_is_zero_size(bcx.ccx(), ret_ty)
767 store_ty(bcx, llret, llretslot, ret_ty)
773 // Lang items are the only case where dest is None, and
774 // they are always Rust fns.
775 assert!(dest.is_some());
777 let mut llargs = Vec::new();
778 let arg_tys = match args {
779 ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, &**x)).collect(),
780 _ => fail!("expected arg exprs.")
782 bcx = trans_args(bcx, args, callee_ty, &mut llargs,
783 cleanup::CustomScope(arg_cleanup_scope), false);
784 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
785 bcx = foreign::trans_native_call(bcx, callee_ty,
786 llfn, opt_llretslot.unwrap(),
787 llargs.as_slice(), arg_tys);
790 // If the caller doesn't care about the result of this fn call,
791 // drop the temporary slot we made.
794 assert!(!type_of::return_uses_outptr(bcx.ccx(), ret_ty));
796 Some(expr::Ignore) => {
797 // drop the value if it is not being saved.
798 bcx = glue::drop_ty(bcx, opt_llretslot.unwrap(), ret_ty);
800 Some(expr::SaveIn(_)) => { }
803 if ty::type_is_bot(ret_ty) {
807 Result::new(bcx, llresult)
810 pub enum CallArgs<'a> {
811 // Supply value of arguments as a list of expressions that must be
812 // translated. This is used in the common case of `foo(bar, qux)`.
813 ArgExprs(&'a [Gc<ast::Expr>]),
815 // Supply value of arguments as a list of LLVM value refs; frequently
816 // used with lang items and so forth, when the argument is an internal
818 ArgVals(&'a [ValueRef]),
820 // For overloaded operators: `(lhs, Option(rhs, rhs_id))`. `lhs`
821 // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
822 // the right-hand-side (if any).
823 ArgOverloadedOp(Datum<Expr>, Option<(Datum<Expr>, ast::NodeId)>),
826 pub fn trans_args<'a>(cx: &'a Block<'a>,
829 llargs: &mut Vec<ValueRef> ,
830 arg_cleanup_scope: cleanup::ScopeId,
833 let _icx = push_ctxt("trans_args");
834 let arg_tys = ty::ty_fn_args(fn_ty);
835 let variadic = ty::fn_is_variadic(fn_ty);
839 // First we figure out the caller's view of the types of the arguments.
840 // This will be needed if this is a generic call, because the callee has
841 // to cast her view of the arguments to the caller's view.
843 ArgExprs(arg_exprs) => {
844 let num_formal_args = arg_tys.len();
845 for (i, arg_expr) in arg_exprs.iter().enumerate() {
846 if i == 0 && ignore_self {
849 let arg_ty = if i >= num_formal_args {
851 expr_ty_adjusted(cx, &**arg_expr)
856 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
857 llargs.push(unpack_result!(bcx, {
858 trans_arg_datum(bcx, arg_ty, arg_datum,
864 ArgOverloadedOp(lhs, rhs) => {
867 llargs.push(unpack_result!(bcx, {
868 trans_arg_datum(bcx, *arg_tys.get(0), lhs,
874 Some((rhs, rhs_id)) => {
875 assert_eq!(arg_tys.len(), 2);
877 llargs.push(unpack_result!(bcx, {
878 trans_arg_datum(bcx, *arg_tys.get(1), rhs,
880 DoAutorefArg(rhs_id))
883 None => assert_eq!(arg_tys.len(), 1)
894 pub enum AutorefArg {
896 DoAutorefArg(ast::NodeId)
899 pub fn trans_arg_datum<'a>(
901 formal_arg_ty: ty::t,
902 arg_datum: Datum<Expr>,
903 arg_cleanup_scope: cleanup::ScopeId,
904 autoref_arg: AutorefArg)
906 let _icx = push_ctxt("trans_arg_datum");
910 debug!("trans_arg_datum({})",
911 formal_arg_ty.repr(bcx.tcx()));
913 let arg_datum_ty = arg_datum.ty;
915 debug!(" arg datum: {}", arg_datum.to_string(bcx.ccx()));
918 if ty::type_is_bot(arg_datum_ty) {
919 // For values of type _|_, we generate an
920 // "undef" value, as such a value should never
921 // be inspected. It's important for the value
922 // to have type lldestty (the callee's expected type).
923 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
925 val = llvm::LLVMGetUndef(llformal_arg_ty.to_ref());
928 // FIXME(#3548) use the adjustments table
930 DoAutorefArg(arg_id) => {
931 // We will pass argument by reference
932 // We want an lvalue, so that we can pass by reference and
933 let arg_datum = unpack_datum!(
934 bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
938 // Make this an rvalue, since we are going to be
939 // passing ownership.
940 let arg_datum = unpack_datum!(
941 bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
943 // Now that arg_datum is owned, get it into the appropriate
944 // mode (ref vs value).
945 let arg_datum = unpack_datum!(
946 bcx, arg_datum.to_appropriate_datum(bcx));
948 // Technically, ownership of val passes to the callee.
949 // However, we must cleanup should we fail before the
950 // callee is actually invoked.
951 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
955 if formal_arg_ty != arg_datum_ty {
956 // this could happen due to e.g. subtyping
957 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
958 debug!("casting actual type ({}) to match formal ({})",
959 bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty));
960 val = PointerCast(bcx, val, llformal_arg_ty);
964 debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val));
965 Result::new(bcx, val)