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