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