]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/callee.rs
auto merge of #15999 : Kimundi/rust/fix_folder, r=nikomatsakis
[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                           TranslateItems);
344     let mut bcx = init_function(&fcx, false, return_type);
345
346     // Create the substituted versions of the self type.
347     let arg_scope = fcx.push_custom_cleanup_scope();
348     let arg_scope_id = cleanup::CustomScope(arg_scope);
349     let boxed_arg_types = ty::ty_fn_args(boxed_function_type);
350     let boxed_self_type = *boxed_arg_types.get(0);
351     let arg_types = ty::ty_fn_args(function_type);
352     let self_type = *arg_types.get(0);
353     let boxed_self_kind = arg_kind(&fcx, boxed_self_type);
354
355     // Create a datum for self.
356     let llboxedself = get_param(fcx.llfn, fcx.arg_pos(0) as u32);
357     let llboxedself = Datum::new(llboxedself,
358                                  boxed_self_type,
359                                  boxed_self_kind);
360     let boxed_self =
361         unpack_datum!(bcx,
362                       llboxedself.to_lvalue_datum_in_scope(bcx,
363                                                            "boxedself",
364                                                            arg_scope_id));
365
366     // This `Load` is needed because lvalue data are always by-ref.
367     let llboxedself = Load(bcx, boxed_self.val);
368
369     let llself = if type_is_immediate(ccx, self_type) {
370         let llboxedself = Load(bcx, llboxedself);
371         immediate_rvalue(llboxedself, self_type)
372     } else {
373         let llself = rvalue_scratch_datum(bcx, self_type, "self");
374         memcpy_ty(bcx, llself.val, llboxedself, self_type);
375         llself
376     };
377
378     // Make sure we don't free the box twice!
379     boxed_self.kind.post_store(bcx, boxed_self.val, boxed_self_type);
380
381     // Schedule a cleanup to free the box.
382     fcx.schedule_free_value(arg_scope_id,
383                             llboxedself,
384                             cleanup::HeapExchange,
385                             self_type);
386
387     // Now call the function.
388     let mut llshimmedargs = vec!(llself.val);
389     for i in range(1, arg_types.len()) {
390         llshimmedargs.push(get_param(fcx.llfn, fcx.arg_pos(i) as u32));
391     }
392     bcx = trans_call_inner(bcx,
393                            None,
394                            function_type,
395                            |bcx, _| {
396                                Callee {
397                                    bcx: bcx,
398                                    data: Fn(llshimmedfn),
399                                }
400                            },
401                            ArgVals(llshimmedargs.as_slice()),
402                            match fcx.llretptr.get() {
403                                None => None,
404                                Some(llretptr) => Some(expr::SaveIn(llretptr)),
405                            }).bcx;
406
407     bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
408     finish_fn(&fcx, bcx, return_type);
409
410     llfn
411 }
412
413 pub fn trans_fn_ref_with_vtables(
414     bcx: &Block,                 //
415     def_id: ast::DefId,          // def id of fn
416     node: ExprOrMethodCall,      // node id of use of fn; may be zero if N/A
417     substs: subst::Substs,       // values for fn's ty params
418     vtables: typeck::vtable_res) // vtables for the call
419     -> ValueRef
420 {
421     /*!
422      * Translates a reference to a fn/method item, monomorphizing and
423      * inlining as it goes.
424      *
425      * # Parameters
426      *
427      * - `bcx`: the current block where the reference to the fn occurs
428      * - `def_id`: def id of the fn or method item being referenced
429      * - `node`: node id of the reference to the fn/method, if applicable.
430      *   This parameter may be zero; but, if so, the resulting value may not
431      *   have the right type, so it must be cast before being used.
432      * - `substs`: values for each of the fn/method's parameters
433      * - `vtables`: values for each bound on each of the type parameters
434      */
435
436     let _icx = push_ctxt("trans_fn_ref_with_vtables");
437     let ccx = bcx.ccx();
438     let tcx = bcx.tcx();
439
440     debug!("trans_fn_ref_with_vtables(bcx={}, def_id={}, node={:?}, \
441             substs={}, vtables={})",
442            bcx.to_str(),
443            def_id.repr(tcx),
444            node,
445            substs.repr(tcx),
446            vtables.repr(tcx));
447
448     assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
449
450     // Load the info for the appropriate trait if necessary.
451     match ty::trait_of_method(tcx, def_id) {
452         None => {}
453         Some(trait_id) => {
454             ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
455         }
456     }
457
458     // We need to do a bunch of special handling for default methods.
459     // We need to modify the def_id and our substs in order to monomorphize
460     // the function.
461     let (is_default, def_id, substs, vtables) =
462         match ty::provided_source(tcx, def_id) {
463         None => (false, def_id, substs, vtables),
464         Some(source_id) => {
465             // There are two relevant substitutions when compiling
466             // default methods. First, there is the substitution for
467             // the type parameters of the impl we are using and the
468             // method we are calling. This substitution is the substs
469             // argument we already have.
470             // In order to compile a default method, though, we need
471             // to consider another substitution: the substitution for
472             // the type parameters on trait; the impl we are using
473             // implements the trait at some particular type
474             // parameters, and we need to substitute for those first.
475             // So, what we need to do is find this substitution and
476             // compose it with the one we already have.
477
478             let impl_id = ty::method(tcx, def_id).container_id();
479             let method = ty::method(tcx, source_id);
480             let trait_ref = ty::impl_trait_ref(tcx, impl_id)
481                 .expect("could not find trait_ref for impl with \
482                          default methods");
483
484             // Compute the first substitution
485             let first_subst = make_substs_for_receiver_types(
486                 tcx, &*trait_ref, &*method);
487
488             // And compose them
489             let new_substs = first_subst.subst(tcx, &substs);
490
491             debug!("trans_fn_with_vtables - default method: \
492                     substs = {}, trait_subst = {}, \
493                     first_subst = {}, new_subst = {}, \
494                     vtables = {}",
495                    substs.repr(tcx), trait_ref.substs.repr(tcx),
496                    first_subst.repr(tcx), new_substs.repr(tcx),
497                    vtables.repr(tcx));
498
499             let param_vtables =
500                 resolve_default_method_vtables(bcx, impl_id, &substs, vtables);
501
502             debug!("trans_fn_with_vtables - default method: \
503                     param_vtables = {}",
504                    param_vtables.repr(tcx));
505
506             (true, source_id, new_substs, param_vtables)
507         }
508     };
509
510     // If this is an unboxed closure, redirect to it.
511     match closure::get_or_create_declaration_if_unboxed_closure(ccx, def_id) {
512         None => {}
513         Some(llfn) => return llfn,
514     }
515
516     // Check whether this fn has an inlined copy and, if so, redirect
517     // def_id to the local id of the inlined copy.
518     let def_id = {
519         if def_id.krate != ast::LOCAL_CRATE {
520             inline::maybe_instantiate_inline(ccx, def_id)
521         } else {
522             def_id
523         }
524     };
525
526     // We must monomorphise if the fn has type parameters, is a default method,
527     // or is a named tuple constructor.
528     let must_monomorphise = if !substs.types.is_empty() || is_default {
529         true
530     } else if def_id.krate == ast::LOCAL_CRATE {
531         let map_node = session::expect(
532             ccx.sess(),
533             tcx.map.find(def_id.node),
534             || "local item should be in ast map".to_string());
535
536         match map_node {
537             ast_map::NodeVariant(v) => match v.node.kind {
538                 ast::TupleVariantKind(ref args) => args.len() > 0,
539                 _ => false
540             },
541             ast_map::NodeStructCtor(_) => true,
542             _ => false
543         }
544     } else {
545         false
546     };
547
548     // Create a monomorphic version of generic functions
549     if must_monomorphise {
550         // Should be either intra-crate or inlined.
551         assert_eq!(def_id.krate, ast::LOCAL_CRATE);
552
553         let opt_ref_id = match node {
554             ExprId(id) => if id != 0 { Some(id) } else { None },
555             MethodCall(_) => None,
556         };
557
558         let (val, must_cast) =
559             monomorphize::monomorphic_fn(ccx, def_id, &substs,
560                                          vtables, opt_ref_id);
561         let mut val = val;
562         if must_cast && node != ExprId(0) {
563             // Monotype of the REFERENCE to the function (type params
564             // are subst'd)
565             let ref_ty = match node {
566                 ExprId(id) => node_id_type(bcx, id),
567                 MethodCall(method_call) => {
568                     let t = bcx.tcx().method_map.borrow().get(&method_call).ty;
569                     monomorphize_type(bcx, t)
570                 }
571             };
572
573             val = PointerCast(
574                 bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
575         }
576         return val;
577     }
578
579     // Polytype of the function item (may have type params)
580     let fn_tpt = ty::lookup_item_type(tcx, def_id);
581
582     // Find the actual function pointer.
583     let mut val = {
584         if def_id.krate == ast::LOCAL_CRATE {
585             // Internal reference.
586             get_item_val(ccx, def_id.node)
587         } else {
588             // External reference.
589             trans_external_path(ccx, def_id, fn_tpt.ty)
590         }
591     };
592
593     // This is subtle and surprising, but sometimes we have to bitcast
594     // the resulting fn pointer.  The reason has to do with external
595     // functions.  If you have two crates that both bind the same C
596     // library, they may not use precisely the same types: for
597     // example, they will probably each declare their own structs,
598     // which are distinct types from LLVM's point of view (nominal
599     // types).
600     //
601     // Now, if those two crates are linked into an application, and
602     // they contain inlined code, you can wind up with a situation
603     // where both of those functions wind up being loaded into this
604     // application simultaneously. In that case, the same function
605     // (from LLVM's point of view) requires two types. But of course
606     // LLVM won't allow one function to have two types.
607     //
608     // What we currently do, therefore, is declare the function with
609     // one of the two types (whichever happens to come first) and then
610     // bitcast as needed when the function is referenced to make sure
611     // it has the type we expect.
612     //
613     // This can occur on either a crate-local or crate-external
614     // reference. It also occurs when testing libcore and in some
615     // other weird situations. Annoying.
616     let llty = type_of::type_of_fn_from_ty(ccx, fn_tpt.ty);
617     let llptrty = llty.ptr_to();
618     if val_ty(val) != llptrty {
619         debug!("trans_fn_ref_with_vtables(): casting pointer!");
620         val = BitCast(bcx, val, llptrty);
621     } else {
622         debug!("trans_fn_ref_with_vtables(): not casting pointer!");
623     }
624
625     val
626 }
627
628 // ______________________________________________________________________
629 // Translating calls
630
631 pub fn trans_call<'a>(
632                   in_cx: &'a Block<'a>,
633                   call_ex: &ast::Expr,
634                   f: &ast::Expr,
635                   args: CallArgs,
636                   dest: expr::Dest)
637                   -> &'a Block<'a> {
638     let _icx = push_ctxt("trans_call");
639     trans_call_inner(in_cx,
640                      Some(common::expr_info(call_ex)),
641                      expr_ty(in_cx, f),
642                      |cx, _| trans(cx, f),
643                      args,
644                      Some(dest)).bcx
645 }
646
647 pub fn trans_method_call<'a>(
648                          bcx: &'a Block<'a>,
649                          call_ex: &ast::Expr,
650                          rcvr: &ast::Expr,
651                          args: CallArgs,
652                          dest: expr::Dest)
653                          -> &'a Block<'a> {
654     let _icx = push_ctxt("trans_method_call");
655     debug!("trans_method_call(call_ex={})", call_ex.repr(bcx.tcx()));
656     let method_call = MethodCall::expr(call_ex.id);
657     let method_ty = bcx.tcx().method_map.borrow().get(&method_call).ty;
658     trans_call_inner(
659         bcx,
660         Some(common::expr_info(call_ex)),
661         monomorphize_type(bcx, method_ty),
662         |cx, arg_cleanup_scope| {
663             meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
664         },
665         args,
666         Some(dest)).bcx
667 }
668
669 pub fn trans_lang_call<'a>(
670                        bcx: &'a Block<'a>,
671                        did: ast::DefId,
672                        args: &[ValueRef],
673                        dest: Option<expr::Dest>)
674                        -> Result<'a> {
675     let fty = if did.krate == ast::LOCAL_CRATE {
676         ty::node_id_to_type(bcx.tcx(), did.node)
677     } else {
678         csearch::get_type(bcx.tcx(), did).ty
679     };
680     callee::trans_call_inner(bcx,
681                              None,
682                              fty,
683                              |bcx, _| {
684                                 trans_fn_ref_with_vtables_to_callee(bcx,
685                                                                     did,
686                                                                     0,
687                                                                     subst::Substs::empty(),
688                                                                     VecPerParamSpace::empty())
689                              },
690                              ArgVals(args),
691                              dest)
692 }
693
694 pub fn trans_call_inner<'a>(
695                         bcx: &'a Block<'a>,
696                         call_info: Option<NodeInfo>,
697                         callee_ty: ty::t,
698                         get_callee: |bcx: &'a Block<'a>,
699                                      arg_cleanup_scope: cleanup::ScopeId|
700                                      -> Callee<'a>,
701                         args: CallArgs,
702                         dest: Option<expr::Dest>)
703                         -> Result<'a> {
704     /*!
705      * This behemoth of a function translates function calls.
706      * Unfortunately, in order to generate more efficient LLVM
707      * output at -O0, it has quite a complex signature (refactoring
708      * this into two functions seems like a good idea).
709      *
710      * In particular, for lang items, it is invoked with a dest of
711      * None, and in that case the return value contains the result of
712      * the fn. The lang item must not return a structural type or else
713      * all heck breaks loose.
714      *
715      * For non-lang items, `dest` is always Some, and hence the result
716      * is written into memory somewhere. Nonetheless we return the
717      * actual return value of the function.
718      */
719
720     // Introduce a temporary cleanup scope that will contain cleanups
721     // for the arguments while they are being evaluated. The purpose
722     // this cleanup is to ensure that, should a failure occur while
723     // evaluating argument N, the values for arguments 0...N-1 are all
724     // cleaned up. If no failure occurs, the values are handed off to
725     // the callee, and hence none of the cleanups in this temporary
726     // scope will ever execute.
727     let fcx = bcx.fcx;
728     let ccx = fcx.ccx;
729     let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
730
731     let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
732     let mut bcx = callee.bcx;
733
734     let (abi, ret_ty) = match ty::get(callee_ty).sty {
735         ty::ty_bare_fn(ref f) => (f.abi, f.sig.output),
736         ty::ty_closure(ref f) => (f.abi, f.sig.output),
737         _ => fail!("expected bare rust fn or closure in trans_call_inner")
738     };
739
740     let (llfn, llenv, llself) = match callee.data {
741         Fn(llfn) => {
742             (llfn, None, None)
743         }
744         TraitMethod(d) => {
745             (d.llfn, None, Some(d.llself))
746         }
747         Closure(d) => {
748             // Closures are represented as (llfn, llclosure) pair:
749             // load the requisite values out.
750             let pair = d.to_llref();
751             let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]);
752             let llfn = Load(bcx, llfn);
753             let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]);
754             let llenv = Load(bcx, llenv);
755             (llfn, Some(llenv), None)
756         }
757         Intrinsic(node, substs) => {
758             assert!(abi == synabi::RustIntrinsic);
759             assert!(dest.is_some());
760
761             return intrinsic::trans_intrinsic_call(bcx, node, callee_ty,
762                                                    arg_cleanup_scope, args,
763                                                    dest.unwrap(), substs);
764         }
765         NamedTupleConstructor(substs, disr) => {
766             assert!(dest.is_some());
767             fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
768
769             let ctor_ty = callee_ty.subst(bcx.tcx(), &substs);
770             return base::trans_named_tuple_constructor(bcx, ctor_ty, disr,
771                                                        args, dest.unwrap());
772         }
773     };
774
775     // Intrinsics should not become actual functions.
776     // We trans them in place in `trans_intrinsic_call`
777     assert!(abi != synabi::RustIntrinsic);
778
779     let is_rust_fn = abi == synabi::Rust || abi == synabi::RustCall;
780
781     // Generate a location to store the result. If the user does
782     // not care about the result, just make a stack slot.
783     let opt_llretslot = match dest {
784         None => {
785             assert!(!type_of::return_uses_outptr(ccx, ret_ty));
786             None
787         }
788         Some(expr::SaveIn(dst)) => Some(dst),
789         Some(expr::Ignore) if !is_rust_fn ||
790                 type_of::return_uses_outptr(ccx, ret_ty) ||
791                 ty::type_needs_drop(bcx.tcx(), ret_ty) => {
792             if !type_is_zero_size(ccx, ret_ty) {
793                 Some(alloc_ty(bcx, ret_ty, "__llret"))
794             } else {
795                 let llty = type_of::type_of(ccx, ret_ty);
796                 Some(C_undef(llty.ptr_to()))
797             }
798         }
799         Some(expr::Ignore) => None
800     };
801
802     let mut llresult = unsafe {
803         llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
804     };
805
806     // The code below invokes the function, using either the Rust
807     // conventions (if it is a rust fn) or the native conventions
808     // (otherwise).  The important part is that, when all is sad
809     // and done, either the return value of the function will have been
810     // written in opt_llretslot (if it is Some) or `llresult` will be
811     // set appropriately (otherwise).
812     if is_rust_fn {
813         let mut llargs = Vec::new();
814
815         // Push the out-pointer if we use an out-pointer for this
816         // return type, otherwise push "undef".
817         if type_of::return_uses_outptr(ccx, ret_ty) {
818             llargs.push(opt_llretslot.unwrap());
819         }
820
821         // Push the environment (or a trait object's self).
822         match (llenv, llself) {
823             (Some(llenv), None) => {
824                 llargs.push(llenv)
825             },
826             (None, Some(llself)) => llargs.push(llself),
827             _ => {}
828         }
829
830         // Push the arguments.
831         bcx = trans_args(bcx,
832                          args,
833                          callee_ty,
834                          &mut llargs,
835                          cleanup::CustomScope(arg_cleanup_scope),
836                          llself.is_some(),
837                          abi);
838
839         fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
840
841         // Invoke the actual rust fn and update bcx/llresult.
842         let (llret, b) = base::invoke(bcx,
843                                       llfn,
844                                       llargs,
845                                       callee_ty,
846                                       call_info);
847         bcx = b;
848         llresult = llret;
849
850         // If the Rust convention for this type is return via
851         // the return value, copy it into llretslot.
852         match opt_llretslot {
853             Some(llretslot) => {
854                 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
855                     !type_is_zero_size(bcx.ccx(), ret_ty)
856                 {
857                     store_ty(bcx, llret, llretslot, ret_ty)
858                 }
859             }
860             None => {}
861         }
862     } else {
863         // Lang items are the only case where dest is None, and
864         // they are always Rust fns.
865         assert!(dest.is_some());
866
867         let mut llargs = Vec::new();
868         let arg_tys = match args {
869             ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, &**x)).collect(),
870             _ => fail!("expected arg exprs.")
871         };
872         bcx = trans_args(bcx,
873                          args,
874                          callee_ty,
875                          &mut llargs,
876                          cleanup::CustomScope(arg_cleanup_scope),
877                          false,
878                          abi);
879         fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
880         bcx = foreign::trans_native_call(bcx, callee_ty,
881                                          llfn, opt_llretslot.unwrap(),
882                                          llargs.as_slice(), arg_tys);
883     }
884
885     // If the caller doesn't care about the result of this fn call,
886     // drop the temporary slot we made.
887     match (dest, opt_llretslot) {
888         (Some(expr::Ignore), Some(llretslot)) => {
889             // drop the value if it is not being saved.
890             bcx = glue::drop_ty(bcx, llretslot, ret_ty);
891             call_lifetime_end(bcx, llretslot);
892         }
893         _ => {}
894     }
895
896     if ty::type_is_bot(ret_ty) {
897         Unreachable(bcx);
898     }
899
900     Result::new(bcx, llresult)
901 }
902
903 pub enum CallArgs<'a> {
904     // Supply value of arguments as a list of expressions that must be
905     // translated. This is used in the common case of `foo(bar, qux)`.
906     ArgExprs(&'a [Gc<ast::Expr>]),
907
908     // Supply value of arguments as a list of LLVM value refs; frequently
909     // used with lang items and so forth, when the argument is an internal
910     // value.
911     ArgVals(&'a [ValueRef]),
912
913     // For overloaded operators: `(lhs, Option(rhs, rhs_id))`. `lhs`
914     // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
915     // the right-hand-side (if any).
916     ArgOverloadedOp(Datum<Expr>, Option<(Datum<Expr>, ast::NodeId)>),
917
918     // Supply value of arguments as a list of expressions that must be
919     // translated, for overloaded call operators.
920     ArgOverloadedCall(&'a [Gc<ast::Expr>]),
921 }
922
923 fn trans_args_under_call_abi<'a>(
924                              mut bcx: &'a Block<'a>,
925                              arg_exprs: &[Gc<ast::Expr>],
926                              fn_ty: ty::t,
927                              llargs: &mut Vec<ValueRef>,
928                              arg_cleanup_scope: cleanup::ScopeId,
929                              ignore_self: bool)
930                              -> &'a Block<'a> {
931     // Translate the `self` argument first.
932     let arg_tys = ty::ty_fn_args(fn_ty);
933     if !ignore_self {
934         let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
935         llargs.push(unpack_result!(bcx, {
936             trans_arg_datum(bcx,
937                             *arg_tys.get(0),
938                             arg_datum,
939                             arg_cleanup_scope,
940                             DontAutorefArg)
941         }))
942     }
943
944     // Now untuple the rest of the arguments.
945     let tuple_expr = arg_exprs[1];
946     let tuple_type = node_id_type(bcx, tuple_expr.id);
947
948     match ty::get(tuple_type).sty {
949         ty::ty_tup(ref field_types) => {
950             let tuple_datum = unpack_datum!(bcx,
951                                             expr::trans(bcx, &*tuple_expr));
952             let tuple_lvalue_datum =
953                 unpack_datum!(bcx,
954                               tuple_datum.to_lvalue_datum(bcx,
955                                                           "args",
956                                                           tuple_expr.id));
957             let repr = adt::represent_type(bcx.ccx(), tuple_type);
958             let repr_ptr = &*repr;
959             for i in range(0, field_types.len()) {
960                 let arg_datum = tuple_lvalue_datum.get_element(
961                     *field_types.get(i),
962                     |srcval| {
963                         adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
964                     });
965                 let arg_datum = arg_datum.to_expr_datum();
966                 let arg_datum =
967                     unpack_datum!(bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
968                 let arg_datum =
969                     unpack_datum!(bcx, arg_datum.to_appropriate_datum(bcx));
970                 llargs.push(arg_datum.add_clean(bcx.fcx, arg_cleanup_scope));
971             }
972         }
973         ty::ty_nil => {}
974         _ => {
975             bcx.sess().span_bug(tuple_expr.span,
976                                 "argument to `.call()` wasn't a tuple?!")
977         }
978     };
979
980     bcx
981 }
982
983 fn trans_overloaded_call_args<'a>(
984                               mut bcx: &'a Block<'a>,
985                               arg_exprs: &[Gc<ast::Expr>],
986                               fn_ty: ty::t,
987                               llargs: &mut Vec<ValueRef>,
988                               arg_cleanup_scope: cleanup::ScopeId,
989                               ignore_self: bool)
990                               -> &'a Block<'a> {
991     // Translate the `self` argument first.
992     let arg_tys = ty::ty_fn_args(fn_ty);
993     if !ignore_self {
994         let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
995         llargs.push(unpack_result!(bcx, {
996             trans_arg_datum(bcx,
997                             *arg_tys.get(0),
998                             arg_datum,
999                             arg_cleanup_scope,
1000                             DontAutorefArg)
1001         }))
1002     }
1003
1004     // Now untuple the rest of the arguments.
1005     let tuple_type = *arg_tys.get(1);
1006     match ty::get(tuple_type).sty {
1007         ty::ty_tup(ref field_types) => {
1008             for (i, &field_type) in field_types.iter().enumerate() {
1009                 let arg_datum =
1010                     unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[i + 1]));
1011                 llargs.push(unpack_result!(bcx, {
1012                     trans_arg_datum(bcx,
1013                                     field_type,
1014                                     arg_datum,
1015                                     arg_cleanup_scope,
1016                                     DontAutorefArg)
1017                 }))
1018             }
1019         }
1020         ty::ty_nil => {}
1021         _ => {
1022             bcx.sess().span_bug(arg_exprs[0].span,
1023                                 "argument to `.call()` wasn't a tuple?!")
1024         }
1025     };
1026
1027     bcx
1028 }
1029
1030 pub fn trans_args<'a>(
1031                   cx: &'a Block<'a>,
1032                   args: CallArgs,
1033                   fn_ty: ty::t,
1034                   llargs: &mut Vec<ValueRef> ,
1035                   arg_cleanup_scope: cleanup::ScopeId,
1036                   ignore_self: bool,
1037                   abi: synabi::Abi)
1038                   -> &'a Block<'a> {
1039     debug!("trans_args(abi={})", abi);
1040
1041     let _icx = push_ctxt("trans_args");
1042     let arg_tys = ty::ty_fn_args(fn_ty);
1043     let variadic = ty::fn_is_variadic(fn_ty);
1044
1045     let mut bcx = cx;
1046
1047     // First we figure out the caller's view of the types of the arguments.
1048     // This will be needed if this is a generic call, because the callee has
1049     // to cast her view of the arguments to the caller's view.
1050     match args {
1051         ArgExprs(arg_exprs) => {
1052             if abi == synabi::RustCall {
1053                 // This is only used for direct calls to the `call`,
1054                 // `call_mut` or `call_once` functions.
1055                 return trans_args_under_call_abi(cx,
1056                                                  arg_exprs,
1057                                                  fn_ty,
1058                                                  llargs,
1059                                                  arg_cleanup_scope,
1060                                                  ignore_self)
1061             }
1062
1063             let num_formal_args = arg_tys.len();
1064             for (i, arg_expr) in arg_exprs.iter().enumerate() {
1065                 if i == 0 && ignore_self {
1066                     continue;
1067                 }
1068                 let arg_ty = if i >= num_formal_args {
1069                     assert!(variadic);
1070                     expr_ty_adjusted(cx, &**arg_expr)
1071                 } else {
1072                     *arg_tys.get(i)
1073                 };
1074
1075                 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
1076                 llargs.push(unpack_result!(bcx, {
1077                     trans_arg_datum(bcx, arg_ty, arg_datum,
1078                                     arg_cleanup_scope,
1079                                     DontAutorefArg)
1080                 }));
1081             }
1082         }
1083         ArgOverloadedCall(arg_exprs) => {
1084             return trans_overloaded_call_args(cx,
1085                                               arg_exprs,
1086                                               fn_ty,
1087                                               llargs,
1088                                               arg_cleanup_scope,
1089                                               ignore_self)
1090         }
1091         ArgOverloadedOp(lhs, rhs) => {
1092             assert!(!variadic);
1093
1094             llargs.push(unpack_result!(bcx, {
1095                 trans_arg_datum(bcx, *arg_tys.get(0), lhs,
1096                                 arg_cleanup_scope,
1097                                 DontAutorefArg)
1098             }));
1099
1100             match rhs {
1101                 Some((rhs, rhs_id)) => {
1102                     assert_eq!(arg_tys.len(), 2);
1103
1104                     llargs.push(unpack_result!(bcx, {
1105                         trans_arg_datum(bcx, *arg_tys.get(1), rhs,
1106                                         arg_cleanup_scope,
1107                                         DoAutorefArg(rhs_id))
1108                     }));
1109                 }
1110                 None => assert_eq!(arg_tys.len(), 1)
1111             }
1112         }
1113         ArgVals(vs) => {
1114             llargs.push_all(vs);
1115         }
1116     }
1117
1118     bcx
1119 }
1120
1121 pub enum AutorefArg {
1122     DontAutorefArg,
1123     DoAutorefArg(ast::NodeId)
1124 }
1125
1126 pub fn trans_arg_datum<'a>(
1127                       bcx: &'a Block<'a>,
1128                       formal_arg_ty: ty::t,
1129                       arg_datum: Datum<Expr>,
1130                       arg_cleanup_scope: cleanup::ScopeId,
1131                       autoref_arg: AutorefArg)
1132                       -> Result<'a> {
1133     let _icx = push_ctxt("trans_arg_datum");
1134     let mut bcx = bcx;
1135     let ccx = bcx.ccx();
1136
1137     debug!("trans_arg_datum({})",
1138            formal_arg_ty.repr(bcx.tcx()));
1139
1140     let arg_datum_ty = arg_datum.ty;
1141
1142     debug!("   arg datum: {}", arg_datum.to_string(bcx.ccx()));
1143
1144     let mut val;
1145     if ty::type_is_bot(arg_datum_ty) {
1146         // For values of type _|_, we generate an
1147         // "undef" value, as such a value should never
1148         // be inspected. It's important for the value
1149         // to have type lldestty (the callee's expected type).
1150         let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1151         unsafe {
1152             val = llvm::LLVMGetUndef(llformal_arg_ty.to_ref());
1153         }
1154     } else {
1155         // FIXME(#3548) use the adjustments table
1156         match autoref_arg {
1157             DoAutorefArg(arg_id) => {
1158                 // We will pass argument by reference
1159                 // We want an lvalue, so that we can pass by reference and
1160                 let arg_datum = unpack_datum!(
1161                     bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
1162                 val = arg_datum.val;
1163             }
1164             DontAutorefArg => {
1165                 // Make this an rvalue, since we are going to be
1166                 // passing ownership.
1167                 let arg_datum = unpack_datum!(
1168                     bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
1169
1170                 // Now that arg_datum is owned, get it into the appropriate
1171                 // mode (ref vs value).
1172                 let arg_datum = unpack_datum!(
1173                     bcx, arg_datum.to_appropriate_datum(bcx));
1174
1175                 // Technically, ownership of val passes to the callee.
1176                 // However, we must cleanup should we fail before the
1177                 // callee is actually invoked.
1178                 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
1179             }
1180         }
1181
1182         if formal_arg_ty != arg_datum_ty {
1183             // this could happen due to e.g. subtyping
1184             let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1185             debug!("casting actual type ({}) to match formal ({})",
1186                    bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty));
1187             val = PointerCast(bcx, val, llformal_arg_ty);
1188         }
1189     }
1190
1191     debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val));
1192     Result::new(bcx, val)
1193 }