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