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