]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/callee.rs
rollup merge of #17355 : gamazeps/issue17210
[rust.git] / src / librustc / middle / trans / callee.rs
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.
4 //
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.
10
11 /*!
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
16  * closure.
17  */
18
19 use arena::TypedArena;
20 use back::abi;
21 use back::link;
22 use driver::session;
23 use llvm::{ValueRef, get_param};
24 use llvm;
25 use metadata::csearch;
26 use middle::def;
27 use middle::subst;
28 use middle::subst::{Subst};
29 use middle::trans::adt;
30 use middle::trans::base;
31 use middle::trans::base::*;
32 use middle::trans::build::*;
33 use middle::trans::callee;
34 use middle::trans::cleanup;
35 use middle::trans::cleanup::CleanupMethods;
36 use middle::trans::closure;
37 use middle::trans::common;
38 use middle::trans::common::*;
39 use middle::trans::datum::*;
40 use middle::trans::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;
49 use middle::ty;
50 use middle::typeck::coherence::make_substs_for_receiver_types;
51 use middle::typeck::MethodCall;
52 use util::ppaux::Repr;
53 use util::ppaux::ty_to_string;
54
55 use syntax::abi as synabi;
56 use syntax::ast;
57 use syntax::ast_map;
58 use syntax::ptr::P;
59
60 pub struct MethodData {
61     pub llfn: ValueRef,
62     pub llself: ValueRef,
63 }
64
65 pub enum CalleeData {
66     Closure(Datum<Lvalue>),
67
68     // Constructor for enum variant/tuple-like-struct
69     // i.e. Some, Ok
70     NamedTupleConstructor(subst::Substs, ty::Disr),
71
72     // Represents a (possibly monomorphized) top-level fn item or method
73     // item. Note that this is just the fn-ptr and is not a Rust closure
74     // value (which is a pair).
75     Fn(/* llfn */ ValueRef),
76
77     Intrinsic(ast::NodeId, subst::Substs),
78
79     TraitItem(MethodData)
80 }
81
82 pub struct Callee<'blk, 'tcx: 'blk> {
83     pub bcx: Block<'blk, 'tcx>,
84     pub data: CalleeData,
85 }
86
87 fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
88                      -> Callee<'blk, 'tcx> {
89     let _icx = push_ctxt("trans_callee");
90     debug!("callee::trans(expr={})", expr.repr(bcx.tcx()));
91
92     // pick out special kinds of expressions that can be called:
93     match expr.node {
94         ast::ExprPath(_) => {
95             return trans_def(bcx, bcx.def(expr.id), expr);
96         }
97         _ => {}
98     }
99
100     // any other expressions are closures:
101     return datum_callee(bcx, expr);
102
103     fn datum_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
104                                 -> Callee<'blk, 'tcx> {
105         let DatumBlock {bcx: mut bcx, datum} = expr::trans(bcx, expr);
106         match ty::get(datum.ty).sty {
107             ty::ty_bare_fn(..) => {
108                 let llval = datum.to_llscalarish(bcx);
109                 return Callee {
110                     bcx: bcx,
111                     data: Fn(llval),
112                 };
113             }
114             ty::ty_closure(..) => {
115                 let datum = unpack_datum!(
116                     bcx, datum.to_lvalue_datum(bcx, "callee", expr.id));
117                 return Callee {
118                     bcx: bcx,
119                     data: Closure(datum),
120                 };
121             }
122             _ => {
123                 bcx.tcx().sess.span_bug(
124                     expr.span,
125                     format!("type of callee is neither bare-fn nor closure: \
126                              {}",
127                             bcx.ty_to_string(datum.ty)).as_slice());
128             }
129         }
130     }
131
132     fn fn_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, llfn: ValueRef)
133                              -> Callee<'blk, 'tcx> {
134         return Callee {
135             bcx: bcx,
136             data: Fn(llfn),
137         };
138     }
139
140     fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, def: def::Def, ref_expr: &ast::Expr)
141                              -> Callee<'blk, 'tcx> {
142         debug!("trans_def(def={}, ref_expr={})", def.repr(bcx.tcx()), ref_expr.repr(bcx.tcx()));
143         let expr_ty = node_id_type(bcx, ref_expr.id);
144         match def {
145             def::DefFn(did, _) if {
146                 let maybe_def_id = inline::get_local_instance(bcx.ccx(), did);
147                 let maybe_ast_node = maybe_def_id.and_then(|def_id| bcx.tcx().map
148                                                                              .find(def_id.node));
149                 match maybe_ast_node {
150                     Some(ast_map::NodeStructCtor(_)) => true,
151                     _ => false
152                 }
153             } => {
154                 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
155                 Callee {
156                     bcx: bcx,
157                     data: NamedTupleConstructor(substs, 0)
158                 }
159             }
160             def::DefFn(did, _) if match ty::get(expr_ty).sty {
161                 ty::ty_bare_fn(ref f) => f.abi == synabi::RustIntrinsic,
162                 _ => false
163             } => {
164                 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
165                 let def_id = inline::maybe_instantiate_inline(bcx.ccx(), did);
166                 Callee { bcx: bcx, data: Intrinsic(def_id.node, substs) }
167             }
168             def::DefFn(did, _) |
169             def::DefStaticMethod(did, def::FromImpl(_), _) => {
170                 fn_callee(bcx, trans_fn_ref(bcx, did, ExprId(ref_expr.id)))
171             }
172             def::DefStaticMethod(impl_did,
173                                  def::FromTrait(trait_did),
174                                  _) => {
175                 fn_callee(bcx, meth::trans_static_method_callee(bcx, impl_did,
176                                                                 trait_did,
177                                                                 ref_expr.id))
178             }
179             def::DefVariant(tid, vid, _) => {
180                 let vinfo = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
181                 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
182
183                 // Nullary variants are not callable
184                 assert!(vinfo.args.len() > 0u);
185
186                 Callee {
187                     bcx: bcx,
188                     data: NamedTupleConstructor(substs, vinfo.disr_val)
189                 }
190             }
191             def::DefStruct(_) => {
192                 let substs = node_id_substs(bcx, ExprId(ref_expr.id));
193                 Callee {
194                     bcx: bcx,
195                     data: NamedTupleConstructor(substs, 0)
196                 }
197             }
198             def::DefStatic(..) |
199             def::DefLocal(..) |
200             def::DefUpvar(..) => {
201                 datum_callee(bcx, ref_expr)
202             }
203             def::DefMod(..) | def::DefForeignMod(..) | def::DefTrait(..) |
204             def::DefTy(..) | def::DefPrimTy(..) | def::DefAssociatedTy(..) |
205             def::DefUse(..) | def::DefTyParamBinder(..) |
206             def::DefRegion(..) | def::DefLabel(..) | def::DefTyParam(..) |
207             def::DefSelfTy(..) | def::DefMethod(..) => {
208                 bcx.tcx().sess.span_bug(
209                     ref_expr.span,
210                     format!("cannot translate def {:?} \
211                              to a callable thing!", def).as_slice());
212             }
213         }
214     }
215 }
216
217 pub fn trans_fn_ref(bcx: Block, def_id: ast::DefId, node: ExprOrMethodCall) -> ValueRef {
218     /*!
219      * Translates a reference (with id `ref_id`) to the fn/method
220      * with id `def_id` into a function pointer.  This may require
221      * monomorphization or inlining.
222      */
223
224     let _icx = push_ctxt("trans_fn_ref");
225
226     let substs = node_id_substs(bcx, node);
227     debug!("trans_fn_ref(def_id={}, node={:?}, substs={})",
228            def_id.repr(bcx.tcx()),
229            node,
230            substs.repr(bcx.tcx()));
231     trans_fn_ref_with_substs(bcx, def_id, node, substs)
232 }
233
234 fn trans_fn_ref_with_substs_to_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
235                                                   def_id: ast::DefId,
236                                                   ref_id: ast::NodeId,
237                                                   substs: subst::Substs)
238                                                   -> Callee<'blk, 'tcx> {
239     Callee {
240         bcx: bcx,
241         data: Fn(trans_fn_ref_with_substs(bcx,
242                                           def_id,
243                                           ExprId(ref_id),
244                                           substs)),
245     }
246 }
247
248 /// Translates the adapter that deconstructs a `Box<Trait>` object into
249 /// `Trait` so that a by-value self method can be called.
250 pub fn trans_unboxing_shim(bcx: Block,
251                            llshimmedfn: ValueRef,
252                            fty: &ty::BareFnTy,
253                            method_id: ast::DefId,
254                            substs: subst::Substs)
255                            -> ValueRef {
256     let _icx = push_ctxt("trans_unboxing_shim");
257     let ccx = bcx.ccx();
258     let tcx = bcx.tcx();
259
260     // Transform the self type to `Box<self_type>`.
261     let self_type = *fty.sig.inputs.get(0);
262     let boxed_self_type = ty::mk_uniq(tcx, self_type);
263     let boxed_function_type = ty::FnSig {
264         binder_id: fty.sig.binder_id,
265         inputs: fty.sig.inputs.iter().enumerate().map(|(i, typ)| {
266             if i == 0 {
267                 boxed_self_type
268             } else {
269                 *typ
270             }
271         }).collect(),
272         output: fty.sig.output,
273         variadic: false,
274     };
275     let boxed_function_type = ty::BareFnTy {
276         fn_style: fty.fn_style,
277         abi: fty.abi,
278         sig: boxed_function_type,
279     };
280     let boxed_function_type =
281         ty::mk_bare_fn(tcx, boxed_function_type).subst(tcx, &substs);
282     let function_type =
283         ty::mk_bare_fn(tcx, (*fty).clone()).subst(tcx, &substs);
284
285     let function_name = ty::with_path(tcx, method_id, |path| {
286         link::mangle_internal_name_by_path_and_seq(path, "unboxing_shim")
287     });
288     let llfn = decl_internal_rust_fn(ccx,
289                                      boxed_function_type,
290                                      function_name.as_slice());
291
292     let block_arena = TypedArena::new();
293     let empty_param_substs = param_substs::empty();
294     let return_type = ty::ty_fn_ret(boxed_function_type);
295     let fcx = new_fn_ctxt(ccx,
296                           llfn,
297                           ast::DUMMY_NODE_ID,
298                           false,
299                           return_type,
300                           &empty_param_substs,
301                           None,
302                           &block_arena);
303     let mut bcx = init_function(&fcx, false, return_type);
304
305     // Create the substituted versions of the self type.
306     let arg_scope = fcx.push_custom_cleanup_scope();
307     let arg_scope_id = cleanup::CustomScope(arg_scope);
308     let boxed_arg_types = ty::ty_fn_args(boxed_function_type);
309     let boxed_self_type = *boxed_arg_types.get(0);
310     let arg_types = ty::ty_fn_args(function_type);
311     let self_type = *arg_types.get(0);
312     let boxed_self_kind = arg_kind(&fcx, boxed_self_type);
313
314     // Create a datum for self.
315     let llboxedself = get_param(fcx.llfn, fcx.arg_pos(0) as u32);
316     let llboxedself = Datum::new(llboxedself,
317                                  boxed_self_type,
318                                  boxed_self_kind);
319     let boxed_self =
320         unpack_datum!(bcx,
321                       llboxedself.to_lvalue_datum_in_scope(bcx,
322                                                            "boxedself",
323                                                            arg_scope_id));
324
325     // This `Load` is needed because lvalue data are always by-ref.
326     let llboxedself = Load(bcx, boxed_self.val);
327
328     let llself = if type_is_immediate(ccx, self_type) {
329         let llboxedself = Load(bcx, llboxedself);
330         immediate_rvalue(llboxedself, self_type)
331     } else {
332         let llself = rvalue_scratch_datum(bcx, self_type, "self");
333         memcpy_ty(bcx, llself.val, llboxedself, self_type);
334         llself
335     };
336
337     // Make sure we don't free the box twice!
338     boxed_self.kind.post_store(bcx, boxed_self.val, boxed_self_type);
339
340     // Schedule a cleanup to free the box.
341     fcx.schedule_free_value(arg_scope_id,
342                             llboxedself,
343                             cleanup::HeapExchange,
344                             self_type);
345
346     // Now call the function.
347     let mut llshimmedargs = vec!(llself.val);
348     for i in range(1, arg_types.len()) {
349         llshimmedargs.push(get_param(fcx.llfn, fcx.arg_pos(i) as u32));
350     }
351     assert!(!fcx.needs_ret_allocas);
352     let dest = match fcx.llretslotptr.get() {
353         Some(_) => Some(expr::SaveIn(fcx.get_ret_slot(bcx, return_type, "ret_slot"))),
354         None => None
355     };
356     bcx = trans_call_inner(bcx,
357                            None,
358                            function_type,
359                            |bcx, _| {
360                                Callee {
361                                    bcx: bcx,
362                                    data: Fn(llshimmedfn),
363                                }
364                            },
365                            ArgVals(llshimmedargs.as_slice()),
366                            dest).bcx;
367
368     bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
369     finish_fn(&fcx, bcx, return_type);
370
371     llfn
372 }
373
374 pub fn trans_fn_ref_with_substs(
375     bcx: Block,                  //
376     def_id: ast::DefId,          // def id of fn
377     node: ExprOrMethodCall,      // node id of use of fn; may be zero if N/A
378     substs: subst::Substs)       // vtables for the call
379     -> ValueRef
380 {
381     /*!
382      * Translates a reference to a fn/method item, monomorphizing and
383      * inlining as it goes.
384      *
385      * # Parameters
386      *
387      * - `bcx`: the current block where the reference to the fn occurs
388      * - `def_id`: def id of the fn or method item being referenced
389      * - `node`: node id of the reference to the fn/method, if applicable.
390      *   This parameter may be zero; but, if so, the resulting value may not
391      *   have the right type, so it must be cast before being used.
392      * - `substs`: values for each of the fn/method's parameters
393      */
394
395     let _icx = push_ctxt("trans_fn_ref_with_substs");
396     let ccx = bcx.ccx();
397     let tcx = bcx.tcx();
398
399     debug!("trans_fn_ref_with_substs(bcx={}, def_id={}, node={:?}, \
400             substs={})",
401            bcx.to_str(),
402            def_id.repr(tcx),
403            node,
404            substs.repr(tcx));
405
406     assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
407
408     // Load the info for the appropriate trait if necessary.
409     match ty::trait_of_item(tcx, def_id) {
410         None => {}
411         Some(trait_id) => {
412             ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
413         }
414     }
415
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
418     // the function.
419     let (is_default, def_id, substs) = match ty::provided_source(tcx, def_id) {
420         None => (false, def_id, substs),
421         Some(source_id) => {
422             // There are two relevant substitutions when compiling
423             // default methods. First, there is the substitution for
424             // the type parameters of the impl we are using and the
425             // method we are calling. This substitution is the substs
426             // argument we already have.
427             // In order to compile a default method, though, we need
428             // to consider another substitution: the substitution for
429             // the type parameters on trait; the impl we are using
430             // implements the trait at some particular type
431             // parameters, and we need to substitute for those first.
432             // So, what we need to do is find this substitution and
433             // compose it with the one we already have.
434
435             let impl_id = ty::impl_or_trait_item(tcx, def_id).container()
436                                                              .id();
437             let impl_or_trait_item = ty::impl_or_trait_item(tcx, source_id);
438             match impl_or_trait_item {
439                 ty::MethodTraitItem(method) => {
440                     let trait_ref = ty::impl_trait_ref(tcx, impl_id)
441                         .expect("could not find trait_ref for impl with \
442                                  default methods");
443
444                     // Compute the first substitution
445                     let first_subst = make_substs_for_receiver_types(
446                         tcx, &*trait_ref, &*method);
447
448                     // And compose them
449                     let new_substs = first_subst.subst(tcx, &substs);
450
451                     debug!("trans_fn_with_vtables - default method: \
452                             substs = {}, trait_subst = {}, \
453                             first_subst = {}, new_subst = {}",
454                            substs.repr(tcx), trait_ref.substs.repr(tcx),
455                            first_subst.repr(tcx), new_substs.repr(tcx));
456
457                     (true, source_id, new_substs)
458                 }
459                 ty::TypeTraitItem(_) => {
460                     bcx.tcx().sess.bug("trans_fn_ref_with_vtables() tried \
461                                         to translate an associated type?!")
462                 }
463             }
464         }
465     };
466
467     // If this is an unboxed closure, redirect to it.
468     match closure::get_or_create_declaration_if_unboxed_closure(ccx, def_id) {
469         None => {}
470         Some(llfn) => return llfn,
471     }
472
473     // Check whether this fn has an inlined copy and, if so, redirect
474     // def_id to the local id of the inlined copy.
475     let def_id = inline::maybe_instantiate_inline(ccx, def_id);
476
477     // We must monomorphise if the fn has type parameters, is a default method,
478     // or is a named tuple constructor.
479     let must_monomorphise = if !substs.types.is_empty() || is_default {
480         true
481     } else if def_id.krate == ast::LOCAL_CRATE {
482         let map_node = session::expect(
483             ccx.sess(),
484             tcx.map.find(def_id.node),
485             || "local item should be in ast map".to_string());
486
487         match map_node {
488             ast_map::NodeVariant(v) => match v.node.kind {
489                 ast::TupleVariantKind(ref args) => args.len() > 0,
490                 _ => false
491             },
492             ast_map::NodeStructCtor(_) => true,
493             _ => false
494         }
495     } else {
496         false
497     };
498
499     // Create a monomorphic version of generic functions
500     if must_monomorphise {
501         // Should be either intra-crate or inlined.
502         assert_eq!(def_id.krate, ast::LOCAL_CRATE);
503
504         let opt_ref_id = match node {
505             ExprId(id) => if id != 0 { Some(id) } else { None },
506             MethodCall(_) => None,
507         };
508
509         let (val, must_cast) =
510             monomorphize::monomorphic_fn(ccx, def_id, &substs, opt_ref_id);
511         let mut val = val;
512         if must_cast && node != ExprId(0) {
513             // Monotype of the REFERENCE to the function (type params
514             // are subst'd)
515             let ref_ty = match node {
516                 ExprId(id) => node_id_type(bcx, id),
517                 MethodCall(method_call) => {
518                     let t = bcx.tcx().method_map.borrow().get(&method_call).ty;
519                     monomorphize_type(bcx, t)
520                 }
521             };
522
523             val = PointerCast(
524                 bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
525         }
526         return val;
527     }
528
529     // Polytype of the function item (may have type params)
530     let fn_tpt = ty::lookup_item_type(tcx, def_id);
531
532     // Find the actual function pointer.
533     let mut val = {
534         if def_id.krate == ast::LOCAL_CRATE {
535             // Internal reference.
536             get_item_val(ccx, def_id.node)
537         } else {
538             // External reference.
539             trans_external_path(ccx, def_id, fn_tpt.ty)
540         }
541     };
542
543     // This is subtle and surprising, but sometimes we have to bitcast
544     // the resulting fn pointer.  The reason has to do with external
545     // functions.  If you have two crates that both bind the same C
546     // library, they may not use precisely the same types: for
547     // example, they will probably each declare their own structs,
548     // which are distinct types from LLVM's point of view (nominal
549     // types).
550     //
551     // Now, if those two crates are linked into an application, and
552     // they contain inlined code, you can wind up with a situation
553     // where both of those functions wind up being loaded into this
554     // application simultaneously. In that case, the same function
555     // (from LLVM's point of view) requires two types. But of course
556     // LLVM won't allow one function to have two types.
557     //
558     // What we currently do, therefore, is declare the function with
559     // one of the two types (whichever happens to come first) and then
560     // bitcast as needed when the function is referenced to make sure
561     // it has the type we expect.
562     //
563     // This can occur on either a crate-local or crate-external
564     // reference. It also occurs when testing libcore and in some
565     // other weird situations. Annoying.
566     let llty = type_of::type_of_fn_from_ty(ccx, fn_tpt.ty);
567     let llptrty = llty.ptr_to();
568     if val_ty(val) != llptrty {
569         debug!("trans_fn_ref_with_vtables(): casting pointer!");
570         val = BitCast(bcx, val, llptrty);
571     } else {
572         debug!("trans_fn_ref_with_vtables(): not casting pointer!");
573     }
574
575     val
576 }
577
578 // ______________________________________________________________________
579 // Translating calls
580
581 pub fn trans_call<'blk, 'tcx>(in_cx: Block<'blk, 'tcx>,
582                               call_ex: &ast::Expr,
583                               f: &ast::Expr,
584                               args: CallArgs,
585                               dest: expr::Dest)
586                               -> Block<'blk, 'tcx> {
587     let _icx = push_ctxt("trans_call");
588     trans_call_inner(in_cx,
589                      Some(common::expr_info(call_ex)),
590                      expr_ty(in_cx, f),
591                      |cx, _| trans(cx, f),
592                      args,
593                      Some(dest)).bcx
594 }
595
596 pub fn trans_method_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
597                                      call_ex: &ast::Expr,
598                                      rcvr: &ast::Expr,
599                                      args: CallArgs,
600                                      dest: expr::Dest)
601                                      -> Block<'blk, 'tcx> {
602     let _icx = push_ctxt("trans_method_call");
603     debug!("trans_method_call(call_ex={})", call_ex.repr(bcx.tcx()));
604     let method_call = MethodCall::expr(call_ex.id);
605     let method_ty = bcx.tcx().method_map.borrow().get(&method_call).ty;
606     trans_call_inner(
607         bcx,
608         Some(common::expr_info(call_ex)),
609         monomorphize_type(bcx, method_ty),
610         |cx, arg_cleanup_scope| {
611             meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
612         },
613         args,
614         Some(dest)).bcx
615 }
616
617 pub fn trans_lang_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
618                                    did: ast::DefId,
619                                    args: &[ValueRef],
620                                    dest: Option<expr::Dest>)
621                                    -> Result<'blk, 'tcx> {
622     let fty = if did.krate == ast::LOCAL_CRATE {
623         ty::node_id_to_type(bcx.tcx(), did.node)
624     } else {
625         csearch::get_type(bcx.tcx(), did).ty
626     };
627     callee::trans_call_inner(bcx,
628                              None,
629                              fty,
630                              |bcx, _| {
631                                 trans_fn_ref_with_substs_to_callee(bcx,
632                                                                    did,
633                                                                    0,
634                                                                    subst::Substs::empty())
635                              },
636                              ArgVals(args),
637                              dest)
638 }
639
640 pub fn trans_call_inner<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
641                                     call_info: Option<NodeInfo>,
642                                     callee_ty: ty::t,
643                                     get_callee: |bcx: Block<'blk, 'tcx>,
644                                                 arg_cleanup_scope: cleanup::ScopeId|
645                                                 -> Callee<'blk, 'tcx>,
646                                     args: CallArgs,
647                                     dest: Option<expr::Dest>)
648                                     -> Result<'blk, 'tcx> {
649     /*!
650      * This behemoth of a function translates function calls.
651      * Unfortunately, in order to generate more efficient LLVM
652      * output at -O0, it has quite a complex signature (refactoring
653      * this into two functions seems like a good idea).
654      *
655      * In particular, for lang items, it is invoked with a dest of
656      * None, and in that case the return value contains the result of
657      * the fn. The lang item must not return a structural type or else
658      * all heck breaks loose.
659      *
660      * For non-lang items, `dest` is always Some, and hence the result
661      * is written into memory somewhere. Nonetheless we return the
662      * actual return value of the function.
663      */
664
665     // Introduce a temporary cleanup scope that will contain cleanups
666     // for the arguments while they are being evaluated. The purpose
667     // this cleanup is to ensure that, should a failure occur while
668     // evaluating argument N, the values for arguments 0...N-1 are all
669     // cleaned up. If no failure occurs, the values are handed off to
670     // the callee, and hence none of the cleanups in this temporary
671     // scope will ever execute.
672     let fcx = bcx.fcx;
673     let ccx = fcx.ccx;
674     let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
675
676     let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
677     let mut bcx = callee.bcx;
678
679     let (abi, ret_ty) = match ty::get(callee_ty).sty {
680         ty::ty_bare_fn(ref f) => (f.abi, f.sig.output),
681         ty::ty_closure(ref f) => (f.abi, f.sig.output),
682         _ => fail!("expected bare rust fn or closure in trans_call_inner")
683     };
684
685     let (llfn, llenv, llself) = match callee.data {
686         Fn(llfn) => {
687             (llfn, None, None)
688         }
689         TraitItem(d) => {
690             (d.llfn, None, Some(d.llself))
691         }
692         Closure(d) => {
693             // Closures are represented as (llfn, llclosure) pair:
694             // load the requisite values out.
695             let pair = d.to_llref();
696             let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]);
697             let llfn = Load(bcx, llfn);
698             let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]);
699             let llenv = Load(bcx, llenv);
700             (llfn, Some(llenv), None)
701         }
702         Intrinsic(node, substs) => {
703             assert!(abi == synabi::RustIntrinsic);
704             assert!(dest.is_some());
705
706             let call_info = call_info.expect("no call info for intrinsic call?");
707             return intrinsic::trans_intrinsic_call(bcx, node, callee_ty,
708                                                    arg_cleanup_scope, args,
709                                                    dest.unwrap(), substs,
710                                                    call_info);
711         }
712         NamedTupleConstructor(substs, disr) => {
713             assert!(dest.is_some());
714             fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
715
716             let ctor_ty = callee_ty.subst(bcx.tcx(), &substs);
717             return base::trans_named_tuple_constructor(bcx, ctor_ty, disr,
718                                                        args, dest.unwrap());
719         }
720     };
721
722     // Intrinsics should not become actual functions.
723     // We trans them in place in `trans_intrinsic_call`
724     assert!(abi != synabi::RustIntrinsic);
725
726     let is_rust_fn = abi == synabi::Rust || abi == synabi::RustCall;
727
728     // Generate a location to store the result. If the user does
729     // not care about the result, just make a stack slot.
730     let opt_llretslot = match dest {
731         None => {
732             assert!(!type_of::return_uses_outptr(ccx, ret_ty));
733             None
734         }
735         Some(expr::SaveIn(dst)) => Some(dst),
736         Some(expr::Ignore) if !is_rust_fn ||
737                 type_of::return_uses_outptr(ccx, ret_ty) ||
738                 ty::type_needs_drop(bcx.tcx(), ret_ty) => {
739             if !type_is_zero_size(ccx, ret_ty) {
740                 Some(alloc_ty(bcx, ret_ty, "__llret"))
741             } else {
742                 let llty = type_of::type_of(ccx, ret_ty);
743                 Some(C_undef(llty.ptr_to()))
744             }
745         }
746         Some(expr::Ignore) => None
747     };
748
749     let mut llresult = unsafe {
750         llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
751     };
752
753     // The code below invokes the function, using either the Rust
754     // conventions (if it is a rust fn) or the native conventions
755     // (otherwise).  The important part is that, when all is said
756     // and done, either the return value of the function will have been
757     // written in opt_llretslot (if it is Some) or `llresult` will be
758     // set appropriately (otherwise).
759     if is_rust_fn {
760         let mut llargs = Vec::new();
761
762         // Push the out-pointer if we use an out-pointer for this
763         // return type, otherwise push "undef".
764         if type_of::return_uses_outptr(ccx, ret_ty) {
765             llargs.push(opt_llretslot.unwrap());
766         }
767
768         // Push the environment (or a trait object's self).
769         match (llenv, llself) {
770             (Some(llenv), None) => {
771                 llargs.push(llenv)
772             },
773             (None, Some(llself)) => llargs.push(llself),
774             _ => {}
775         }
776
777         // Push the arguments.
778         bcx = trans_args(bcx,
779                          args,
780                          callee_ty,
781                          &mut llargs,
782                          cleanup::CustomScope(arg_cleanup_scope),
783                          llself.is_some(),
784                          abi);
785
786         fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
787
788         // Invoke the actual rust fn and update bcx/llresult.
789         let (llret, b) = base::invoke(bcx,
790                                       llfn,
791                                       llargs,
792                                       callee_ty,
793                                       call_info,
794                                       dest.is_none());
795         bcx = b;
796         llresult = llret;
797
798         // If the Rust convention for this type is return via
799         // the return value, copy it into llretslot.
800         match opt_llretslot {
801             Some(llretslot) => {
802                 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
803                     !type_is_zero_size(bcx.ccx(), ret_ty)
804                 {
805                     store_ty(bcx, llret, llretslot, ret_ty)
806                 }
807             }
808             None => {}
809         }
810     } else {
811         // Lang items are the only case where dest is None, and
812         // they are always Rust fns.
813         assert!(dest.is_some());
814
815         let mut llargs = Vec::new();
816         let arg_tys = match args {
817             ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, &**x)).collect(),
818             _ => fail!("expected arg exprs.")
819         };
820         bcx = trans_args(bcx,
821                          args,
822                          callee_ty,
823                          &mut llargs,
824                          cleanup::CustomScope(arg_cleanup_scope),
825                          false,
826                          abi);
827         fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
828         bcx = foreign::trans_native_call(bcx, callee_ty,
829                                          llfn, opt_llretslot.unwrap(),
830                                          llargs.as_slice(), arg_tys);
831     }
832
833     // If the caller doesn't care about the result of this fn call,
834     // drop the temporary slot we made.
835     match (dest, opt_llretslot) {
836         (Some(expr::Ignore), Some(llretslot)) => {
837             // drop the value if it is not being saved.
838             bcx = glue::drop_ty(bcx, llretslot, ret_ty);
839             call_lifetime_end(bcx, llretslot);
840         }
841         _ => {}
842     }
843
844     if ty::type_is_bot(ret_ty) {
845         Unreachable(bcx);
846     }
847
848     Result::new(bcx, llresult)
849 }
850
851 pub enum CallArgs<'a> {
852     // Supply value of arguments as a list of expressions that must be
853     // translated. This is used in the common case of `foo(bar, qux)`.
854     ArgExprs(&'a [P<ast::Expr>]),
855
856     // Supply value of arguments as a list of LLVM value refs; frequently
857     // used with lang items and so forth, when the argument is an internal
858     // value.
859     ArgVals(&'a [ValueRef]),
860
861     // For overloaded operators: `(lhs, Vec(rhs, rhs_id))`. `lhs`
862     // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
863     // the right-hand-side arguments (if any).
864     ArgOverloadedOp(Datum<Expr>, Vec<(Datum<Expr>, ast::NodeId)>),
865
866     // Supply value of arguments as a list of expressions that must be
867     // translated, for overloaded call operators.
868     ArgOverloadedCall(Vec<&'a ast::Expr>),
869 }
870
871 fn trans_args_under_call_abi<'blk, 'tcx>(
872                              mut bcx: Block<'blk, 'tcx>,
873                              arg_exprs: &[P<ast::Expr>],
874                              fn_ty: ty::t,
875                              llargs: &mut Vec<ValueRef>,
876                              arg_cleanup_scope: cleanup::ScopeId,
877                              ignore_self: bool)
878                              -> Block<'blk, 'tcx> {
879     // Translate the `self` argument first.
880     let arg_tys = ty::ty_fn_args(fn_ty);
881     if !ignore_self {
882         let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
883         llargs.push(unpack_result!(bcx, {
884             trans_arg_datum(bcx,
885                             *arg_tys.get(0),
886                             arg_datum,
887                             arg_cleanup_scope,
888                             DontAutorefArg)
889         }))
890     }
891
892     // Now untuple the rest of the arguments.
893     let tuple_expr = &arg_exprs[1];
894     let tuple_type = node_id_type(bcx, tuple_expr.id);
895
896     match ty::get(tuple_type).sty {
897         ty::ty_tup(ref field_types) => {
898             let tuple_datum = unpack_datum!(bcx,
899                                             expr::trans(bcx, &**tuple_expr));
900             let tuple_lvalue_datum =
901                 unpack_datum!(bcx,
902                               tuple_datum.to_lvalue_datum(bcx,
903                                                           "args",
904                                                           tuple_expr.id));
905             let repr = adt::represent_type(bcx.ccx(), tuple_type);
906             let repr_ptr = &*repr;
907             for i in range(0, field_types.len()) {
908                 let arg_datum = tuple_lvalue_datum.get_element(
909                     bcx,
910                     *field_types.get(i),
911                     |srcval| {
912                         adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
913                     });
914                 let arg_datum = arg_datum.to_expr_datum();
915                 let arg_datum =
916                     unpack_datum!(bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
917                 let arg_datum =
918                     unpack_datum!(bcx, arg_datum.to_appropriate_datum(bcx));
919                 llargs.push(arg_datum.add_clean(bcx.fcx, arg_cleanup_scope));
920             }
921         }
922         ty::ty_nil => {}
923         _ => {
924             bcx.sess().span_bug(tuple_expr.span,
925                                 "argument to `.call()` wasn't a tuple?!")
926         }
927     };
928
929     bcx
930 }
931
932 fn trans_overloaded_call_args<'blk, 'tcx>(
933                               mut bcx: Block<'blk, 'tcx>,
934                               arg_exprs: Vec<&ast::Expr>,
935                               fn_ty: ty::t,
936                               llargs: &mut Vec<ValueRef>,
937                               arg_cleanup_scope: cleanup::ScopeId,
938                               ignore_self: bool)
939                               -> Block<'blk, 'tcx> {
940     // Translate the `self` argument first.
941     let arg_tys = ty::ty_fn_args(fn_ty);
942     if !ignore_self {
943         let arg_datum = unpack_datum!(bcx, expr::trans(bcx, arg_exprs[0]));
944         llargs.push(unpack_result!(bcx, {
945             trans_arg_datum(bcx,
946                             *arg_tys.get(0),
947                             arg_datum,
948                             arg_cleanup_scope,
949                             DontAutorefArg)
950         }))
951     }
952
953     // Now untuple the rest of the arguments.
954     let tuple_type = *arg_tys.get(1);
955     match ty::get(tuple_type).sty {
956         ty::ty_tup(ref field_types) => {
957             for (i, &field_type) in field_types.iter().enumerate() {
958                 let arg_datum =
959                     unpack_datum!(bcx, expr::trans(bcx, arg_exprs[i + 1]));
960                 llargs.push(unpack_result!(bcx, {
961                     trans_arg_datum(bcx,
962                                     field_type,
963                                     arg_datum,
964                                     arg_cleanup_scope,
965                                     DontAutorefArg)
966                 }))
967             }
968         }
969         ty::ty_nil => {}
970         _ => {
971             bcx.sess().span_bug(arg_exprs[0].span,
972                                 "argument to `.call()` wasn't a tuple?!")
973         }
974     };
975
976     bcx
977 }
978
979 pub fn trans_args<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
980                               args: CallArgs,
981                               fn_ty: ty::t,
982                               llargs: &mut Vec<ValueRef> ,
983                               arg_cleanup_scope: cleanup::ScopeId,
984                               ignore_self: bool,
985                               abi: synabi::Abi)
986                               -> Block<'blk, 'tcx> {
987     debug!("trans_args(abi={})", abi);
988
989     let _icx = push_ctxt("trans_args");
990     let arg_tys = ty::ty_fn_args(fn_ty);
991     let variadic = ty::fn_is_variadic(fn_ty);
992
993     let mut bcx = cx;
994
995     // First we figure out the caller's view of the types of the arguments.
996     // This will be needed if this is a generic call, because the callee has
997     // to cast her view of the arguments to the caller's view.
998     match args {
999         ArgExprs(arg_exprs) => {
1000             if abi == synabi::RustCall {
1001                 // This is only used for direct calls to the `call`,
1002                 // `call_mut` or `call_once` functions.
1003                 return trans_args_under_call_abi(cx,
1004                                                  arg_exprs,
1005                                                  fn_ty,
1006                                                  llargs,
1007                                                  arg_cleanup_scope,
1008                                                  ignore_self)
1009             }
1010
1011             let num_formal_args = arg_tys.len();
1012             for (i, arg_expr) in arg_exprs.iter().enumerate() {
1013                 if i == 0 && ignore_self {
1014                     continue;
1015                 }
1016                 let arg_ty = if i >= num_formal_args {
1017                     assert!(variadic);
1018                     expr_ty_adjusted(cx, &**arg_expr)
1019                 } else {
1020                     *arg_tys.get(i)
1021                 };
1022
1023                 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
1024                 llargs.push(unpack_result!(bcx, {
1025                     trans_arg_datum(bcx, arg_ty, arg_datum,
1026                                     arg_cleanup_scope,
1027                                     DontAutorefArg)
1028                 }));
1029             }
1030         }
1031         ArgOverloadedCall(arg_exprs) => {
1032             return trans_overloaded_call_args(cx,
1033                                               arg_exprs,
1034                                               fn_ty,
1035                                               llargs,
1036                                               arg_cleanup_scope,
1037                                               ignore_self)
1038         }
1039         ArgOverloadedOp(lhs, rhs) => {
1040             assert!(!variadic);
1041
1042             llargs.push(unpack_result!(bcx, {
1043                 trans_arg_datum(bcx, *arg_tys.get(0), lhs,
1044                                 arg_cleanup_scope,
1045                                 DontAutorefArg)
1046             }));
1047
1048             assert_eq!(arg_tys.len(), 1 + rhs.len());
1049             for (rhs, rhs_id) in rhs.move_iter() {
1050                 llargs.push(unpack_result!(bcx, {
1051                     trans_arg_datum(bcx, *arg_tys.get(1), rhs,
1052                                     arg_cleanup_scope,
1053                                     DoAutorefArg(rhs_id))
1054                 }));
1055             }
1056         }
1057         ArgVals(vs) => {
1058             llargs.push_all(vs);
1059         }
1060     }
1061
1062     bcx
1063 }
1064
1065 pub enum AutorefArg {
1066     DontAutorefArg,
1067     DoAutorefArg(ast::NodeId)
1068 }
1069
1070 pub fn trans_arg_datum<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1071                                    formal_arg_ty: ty::t,
1072                                    arg_datum: Datum<Expr>,
1073                                    arg_cleanup_scope: cleanup::ScopeId,
1074                                    autoref_arg: AutorefArg)
1075                                    -> Result<'blk, 'tcx> {
1076     let _icx = push_ctxt("trans_arg_datum");
1077     let mut bcx = bcx;
1078     let ccx = bcx.ccx();
1079
1080     debug!("trans_arg_datum({})",
1081            formal_arg_ty.repr(bcx.tcx()));
1082
1083     let arg_datum_ty = arg_datum.ty;
1084
1085     debug!("   arg datum: {}", arg_datum.to_string(bcx.ccx()));
1086
1087     let mut val;
1088     if ty::type_is_bot(arg_datum_ty) {
1089         // For values of type _|_, we generate an
1090         // "undef" value, as such a value should never
1091         // be inspected. It's important for the value
1092         // to have type lldestty (the callee's expected type).
1093         let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1094         unsafe {
1095             val = llvm::LLVMGetUndef(llformal_arg_ty.to_ref());
1096         }
1097     } else {
1098         // FIXME(#3548) use the adjustments table
1099         match autoref_arg {
1100             DoAutorefArg(arg_id) => {
1101                 // We will pass argument by reference
1102                 // We want an lvalue, so that we can pass by reference and
1103                 let arg_datum = unpack_datum!(
1104                     bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
1105                 val = arg_datum.val;
1106             }
1107             DontAutorefArg => {
1108                 // Make this an rvalue, since we are going to be
1109                 // passing ownership.
1110                 let arg_datum = unpack_datum!(
1111                     bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
1112
1113                 // Now that arg_datum is owned, get it into the appropriate
1114                 // mode (ref vs value).
1115                 let arg_datum = unpack_datum!(
1116                     bcx, arg_datum.to_appropriate_datum(bcx));
1117
1118                 // Technically, ownership of val passes to the callee.
1119                 // However, we must cleanup should we fail before the
1120                 // callee is actually invoked.
1121                 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
1122             }
1123         }
1124
1125         if formal_arg_ty != arg_datum_ty {
1126             // this could happen due to e.g. subtyping
1127             let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1128             debug!("casting actual type ({}) to match formal ({})",
1129                    bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty));
1130             debug!("Rust types: {}; {}", ty_to_string(bcx.tcx(), arg_datum_ty),
1131                                          ty_to_string(bcx.tcx(), formal_arg_ty));
1132             val = PointerCast(bcx, val, llformal_arg_ty);
1133         }
1134     }
1135
1136     debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val));
1137     Result::new(bcx, val)
1138 }