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