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