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