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