]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/callee.rs
Removed some unnecessary RefCells from resolve
[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,
718                                                        ctor_ty,
719                                                        disr,
720                                                        args,
721                                                        dest.unwrap(),
722                                                        call_info);
723         }
724     };
725
726     // Intrinsics should not become actual functions.
727     // We trans them in place in `trans_intrinsic_call`
728     assert!(abi != synabi::RustIntrinsic);
729
730     let is_rust_fn = abi == synabi::Rust || abi == synabi::RustCall;
731
732     // Generate a location to store the result. If the user does
733     // not care about the result, just make a stack slot.
734     let opt_llretslot = match dest {
735         None => {
736             assert!(!type_of::return_uses_outptr(ccx, ret_ty));
737             None
738         }
739         Some(expr::SaveIn(dst)) => Some(dst),
740         Some(expr::Ignore) if !is_rust_fn ||
741                 type_of::return_uses_outptr(ccx, ret_ty) ||
742                 ty::type_needs_drop(bcx.tcx(), ret_ty) => {
743             if !type_is_zero_size(ccx, ret_ty) {
744                 Some(alloc_ty(bcx, ret_ty, "__llret"))
745             } else {
746                 let llty = type_of::type_of(ccx, ret_ty);
747                 Some(C_undef(llty.ptr_to()))
748             }
749         }
750         Some(expr::Ignore) => None
751     };
752
753     let mut llresult = unsafe {
754         llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
755     };
756
757     // The code below invokes the function, using either the Rust
758     // conventions (if it is a rust fn) or the native conventions
759     // (otherwise).  The important part is that, when all is said
760     // and done, either the return value of the function will have been
761     // written in opt_llretslot (if it is Some) or `llresult` will be
762     // set appropriately (otherwise).
763     if is_rust_fn {
764         let mut llargs = Vec::new();
765
766         // Push the out-pointer if we use an out-pointer for this
767         // return type, otherwise push "undef".
768         if type_of::return_uses_outptr(ccx, ret_ty) {
769             llargs.push(opt_llretslot.unwrap());
770         }
771
772         // Push the environment (or a trait object's self).
773         match (llenv, llself) {
774             (Some(llenv), None) => {
775                 llargs.push(llenv)
776             },
777             (None, Some(llself)) => llargs.push(llself),
778             _ => {}
779         }
780
781         // Push the arguments.
782         bcx = trans_args(bcx,
783                          args,
784                          callee_ty,
785                          &mut llargs,
786                          cleanup::CustomScope(arg_cleanup_scope),
787                          llself.is_some(),
788                          abi);
789
790         fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
791
792         // Invoke the actual rust fn and update bcx/llresult.
793         let (llret, b) = base::invoke(bcx,
794                                       llfn,
795                                       llargs,
796                                       callee_ty,
797                                       call_info,
798                                       dest.is_none());
799         bcx = b;
800         llresult = llret;
801
802         // If the Rust convention for this type is return via
803         // the return value, copy it into llretslot.
804         match opt_llretslot {
805             Some(llretslot) => {
806                 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
807                     !type_is_zero_size(bcx.ccx(), ret_ty)
808                 {
809                     store_ty(bcx, llret, llretslot, ret_ty)
810                 }
811             }
812             None => {}
813         }
814     } else {
815         // Lang items are the only case where dest is None, and
816         // they are always Rust fns.
817         assert!(dest.is_some());
818
819         let mut llargs = Vec::new();
820         let arg_tys = match args {
821             ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, &**x)).collect(),
822             _ => fail!("expected arg exprs.")
823         };
824         bcx = trans_args(bcx,
825                          args,
826                          callee_ty,
827                          &mut llargs,
828                          cleanup::CustomScope(arg_cleanup_scope),
829                          false,
830                          abi);
831         fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
832         bcx = foreign::trans_native_call(bcx, callee_ty,
833                                          llfn, opt_llretslot.unwrap(),
834                                          llargs.as_slice(), arg_tys);
835     }
836
837     // If the caller doesn't care about the result of this fn call,
838     // drop the temporary slot we made.
839     match (dest, opt_llretslot) {
840         (Some(expr::Ignore), Some(llretslot)) => {
841             // drop the value if it is not being saved.
842             bcx = glue::drop_ty(bcx, llretslot, ret_ty, call_info);
843             call_lifetime_end(bcx, llretslot);
844         }
845         _ => {}
846     }
847
848     if ty::type_is_bot(ret_ty) {
849         Unreachable(bcx);
850     }
851
852     Result::new(bcx, llresult)
853 }
854
855 pub enum CallArgs<'a> {
856     // Supply value of arguments as a list of expressions that must be
857     // translated. This is used in the common case of `foo(bar, qux)`.
858     ArgExprs(&'a [P<ast::Expr>]),
859
860     // Supply value of arguments as a list of LLVM value refs; frequently
861     // used with lang items and so forth, when the argument is an internal
862     // value.
863     ArgVals(&'a [ValueRef]),
864
865     // For overloaded operators: `(lhs, Vec(rhs, rhs_id))`. `lhs`
866     // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
867     // the right-hand-side arguments (if any).
868     ArgOverloadedOp(Datum<Expr>, Vec<(Datum<Expr>, ast::NodeId)>),
869
870     // Supply value of arguments as a list of expressions that must be
871     // translated, for overloaded call operators.
872     ArgOverloadedCall(Vec<&'a ast::Expr>),
873 }
874
875 fn trans_args_under_call_abi<'blk, 'tcx>(
876                              mut bcx: Block<'blk, 'tcx>,
877                              arg_exprs: &[P<ast::Expr>],
878                              fn_ty: ty::t,
879                              llargs: &mut Vec<ValueRef>,
880                              arg_cleanup_scope: cleanup::ScopeId,
881                              ignore_self: bool)
882                              -> Block<'blk, 'tcx> {
883     // Translate the `self` argument first.
884     let arg_tys = ty::ty_fn_args(fn_ty);
885     if !ignore_self {
886         let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
887         llargs.push(unpack_result!(bcx, {
888             trans_arg_datum(bcx,
889                             *arg_tys.get(0),
890                             arg_datum,
891                             arg_cleanup_scope,
892                             DontAutorefArg)
893         }))
894     }
895
896     // Now untuple the rest of the arguments.
897     let tuple_expr = &arg_exprs[1];
898     let tuple_type = node_id_type(bcx, tuple_expr.id);
899
900     match ty::get(tuple_type).sty {
901         ty::ty_tup(ref field_types) => {
902             let tuple_datum = unpack_datum!(bcx,
903                                             expr::trans(bcx, &**tuple_expr));
904             let tuple_lvalue_datum =
905                 unpack_datum!(bcx,
906                               tuple_datum.to_lvalue_datum(bcx,
907                                                           "args",
908                                                           tuple_expr.id));
909             let repr = adt::represent_type(bcx.ccx(), tuple_type);
910             let repr_ptr = &*repr;
911             for i in range(0, field_types.len()) {
912                 let arg_datum = tuple_lvalue_datum.get_element(
913                     bcx,
914                     *field_types.get(i),
915                     |srcval| {
916                         adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
917                     });
918                 let arg_datum = arg_datum.to_expr_datum();
919                 let arg_datum =
920                     unpack_datum!(bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
921                 let arg_datum =
922                     unpack_datum!(bcx, arg_datum.to_appropriate_datum(bcx));
923                 llargs.push(arg_datum.add_clean(bcx.fcx, arg_cleanup_scope));
924             }
925         }
926         ty::ty_nil => {}
927         _ => {
928             bcx.sess().span_bug(tuple_expr.span,
929                                 "argument to `.call()` wasn't a tuple?!")
930         }
931     };
932
933     bcx
934 }
935
936 fn trans_overloaded_call_args<'blk, 'tcx>(
937                               mut bcx: Block<'blk, 'tcx>,
938                               arg_exprs: Vec<&ast::Expr>,
939                               fn_ty: ty::t,
940                               llargs: &mut Vec<ValueRef>,
941                               arg_cleanup_scope: cleanup::ScopeId,
942                               ignore_self: bool)
943                               -> Block<'blk, 'tcx> {
944     // Translate the `self` argument first.
945     let arg_tys = ty::ty_fn_args(fn_ty);
946     if !ignore_self {
947         let arg_datum = unpack_datum!(bcx, expr::trans(bcx, arg_exprs[0]));
948         llargs.push(unpack_result!(bcx, {
949             trans_arg_datum(bcx,
950                             *arg_tys.get(0),
951                             arg_datum,
952                             arg_cleanup_scope,
953                             DontAutorefArg)
954         }))
955     }
956
957     // Now untuple the rest of the arguments.
958     let tuple_type = *arg_tys.get(1);
959     match ty::get(tuple_type).sty {
960         ty::ty_tup(ref field_types) => {
961             for (i, &field_type) in field_types.iter().enumerate() {
962                 let arg_datum =
963                     unpack_datum!(bcx, expr::trans(bcx, arg_exprs[i + 1]));
964                 llargs.push(unpack_result!(bcx, {
965                     trans_arg_datum(bcx,
966                                     field_type,
967                                     arg_datum,
968                                     arg_cleanup_scope,
969                                     DontAutorefArg)
970                 }))
971             }
972         }
973         ty::ty_nil => {}
974         _ => {
975             bcx.sess().span_bug(arg_exprs[0].span,
976                                 "argument to `.call()` wasn't a tuple?!")
977         }
978     };
979
980     bcx
981 }
982
983 pub fn trans_args<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
984                               args: CallArgs,
985                               fn_ty: ty::t,
986                               llargs: &mut Vec<ValueRef> ,
987                               arg_cleanup_scope: cleanup::ScopeId,
988                               ignore_self: bool,
989                               abi: synabi::Abi)
990                               -> Block<'blk, 'tcx> {
991     debug!("trans_args(abi={})", abi);
992
993     let _icx = push_ctxt("trans_args");
994     let arg_tys = ty::ty_fn_args(fn_ty);
995     let variadic = ty::fn_is_variadic(fn_ty);
996
997     let mut bcx = cx;
998
999     // First we figure out the caller's view of the types of the arguments.
1000     // This will be needed if this is a generic call, because the callee has
1001     // to cast her view of the arguments to the caller's view.
1002     match args {
1003         ArgExprs(arg_exprs) => {
1004             if abi == synabi::RustCall {
1005                 // This is only used for direct calls to the `call`,
1006                 // `call_mut` or `call_once` functions.
1007                 return trans_args_under_call_abi(cx,
1008                                                  arg_exprs,
1009                                                  fn_ty,
1010                                                  llargs,
1011                                                  arg_cleanup_scope,
1012                                                  ignore_self)
1013             }
1014
1015             let num_formal_args = arg_tys.len();
1016             for (i, arg_expr) in arg_exprs.iter().enumerate() {
1017                 if i == 0 && ignore_self {
1018                     continue;
1019                 }
1020                 let arg_ty = if i >= num_formal_args {
1021                     assert!(variadic);
1022                     expr_ty_adjusted(cx, &**arg_expr)
1023                 } else {
1024                     *arg_tys.get(i)
1025                 };
1026
1027                 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
1028                 llargs.push(unpack_result!(bcx, {
1029                     trans_arg_datum(bcx, arg_ty, arg_datum,
1030                                     arg_cleanup_scope,
1031                                     DontAutorefArg)
1032                 }));
1033             }
1034         }
1035         ArgOverloadedCall(arg_exprs) => {
1036             return trans_overloaded_call_args(cx,
1037                                               arg_exprs,
1038                                               fn_ty,
1039                                               llargs,
1040                                               arg_cleanup_scope,
1041                                               ignore_self)
1042         }
1043         ArgOverloadedOp(lhs, rhs) => {
1044             assert!(!variadic);
1045
1046             llargs.push(unpack_result!(bcx, {
1047                 trans_arg_datum(bcx, *arg_tys.get(0), lhs,
1048                                 arg_cleanup_scope,
1049                                 DontAutorefArg)
1050             }));
1051
1052             assert_eq!(arg_tys.len(), 1 + rhs.len());
1053             for (rhs, rhs_id) in rhs.move_iter() {
1054                 llargs.push(unpack_result!(bcx, {
1055                     trans_arg_datum(bcx, *arg_tys.get(1), rhs,
1056                                     arg_cleanup_scope,
1057                                     DoAutorefArg(rhs_id))
1058                 }));
1059             }
1060         }
1061         ArgVals(vs) => {
1062             llargs.push_all(vs);
1063         }
1064     }
1065
1066     bcx
1067 }
1068
1069 pub enum AutorefArg {
1070     DontAutorefArg,
1071     DoAutorefArg(ast::NodeId)
1072 }
1073
1074 pub fn trans_arg_datum<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1075                                    formal_arg_ty: ty::t,
1076                                    arg_datum: Datum<Expr>,
1077                                    arg_cleanup_scope: cleanup::ScopeId,
1078                                    autoref_arg: AutorefArg)
1079                                    -> Result<'blk, 'tcx> {
1080     let _icx = push_ctxt("trans_arg_datum");
1081     let mut bcx = bcx;
1082     let ccx = bcx.ccx();
1083
1084     debug!("trans_arg_datum({})",
1085            formal_arg_ty.repr(bcx.tcx()));
1086
1087     let arg_datum_ty = arg_datum.ty;
1088
1089     debug!("   arg datum: {}", arg_datum.to_string(bcx.ccx()));
1090
1091     let mut val;
1092     if ty::type_is_bot(arg_datum_ty) {
1093         // For values of type _|_, we generate an
1094         // "undef" value, as such a value should never
1095         // be inspected. It's important for the value
1096         // to have type lldestty (the callee's expected type).
1097         let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1098         unsafe {
1099             val = llvm::LLVMGetUndef(llformal_arg_ty.to_ref());
1100         }
1101     } else {
1102         // FIXME(#3548) use the adjustments table
1103         match autoref_arg {
1104             DoAutorefArg(arg_id) => {
1105                 // We will pass argument by reference
1106                 // We want an lvalue, so that we can pass by reference and
1107                 let arg_datum = unpack_datum!(
1108                     bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
1109                 val = arg_datum.val;
1110             }
1111             DontAutorefArg => {
1112                 // Make this an rvalue, since we are going to be
1113                 // passing ownership.
1114                 let arg_datum = unpack_datum!(
1115                     bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
1116
1117                 // Now that arg_datum is owned, get it into the appropriate
1118                 // mode (ref vs value).
1119                 let arg_datum = unpack_datum!(
1120                     bcx, arg_datum.to_appropriate_datum(bcx));
1121
1122                 // Technically, ownership of val passes to the callee.
1123                 // However, we must cleanup should we fail before the
1124                 // callee is actually invoked.
1125                 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
1126             }
1127         }
1128
1129         if formal_arg_ty != arg_datum_ty {
1130             // this could happen due to e.g. subtyping
1131             let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1132             debug!("casting actual type ({}) to match formal ({})",
1133                    bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty));
1134             debug!("Rust types: {}; {}", ty_to_string(bcx.tcx(), arg_datum_ty),
1135                                          ty_to_string(bcx.tcx(), formal_arg_ty));
1136             val = PointerCast(bcx, val, llformal_arg_ty);
1137         }
1138     }
1139
1140     debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val));
1141     Result::new(bcx, val)
1142 }