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