]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/callee.rs
73adcec71e46227b8ff8b9df2053ef34247e749b
[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::closure;
31 use middle::trans::common;
32 use middle::trans::common::*;
33 use middle::trans::datum::*;
34 use middle::trans::datum::Datum;
35 use middle::trans::expr;
36 use middle::trans::glue;
37 use middle::trans::inline;
38 use middle::trans::meth;
39 use middle::trans::monomorphize;
40 use middle::trans::type_of;
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::ast_map;
51 use syntax::visit;
52
53 // Represents a (possibly monomorphized) top-level fn item or method
54 // item.  Note that this is just the fn-ptr and is not a Rust closure
55 // value (which is a pair).
56 pub struct FnData {
57     llfn: ValueRef,
58 }
59
60 pub struct MethodData {
61     llfn: ValueRef,
62     llself: ValueRef,
63     temp_cleanup: Option<ValueRef>,
64     self_ty: ty::t,
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: block,
76     data: CalleeData
77 }
78
79 pub fn trans(bcx: 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: 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: block, fd: FnData) -> Callee {
114         return Callee {bcx: bcx, data: Fn(fd)};
115     }
116
117     fn trans_def(bcx: 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: block,
159                               def_id: ast::def_id,
160                               ref_id: ast::node_id) -> 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: block,
166                     def_id: ast::def_id,
167                     ref_id: ast::node_id) -> 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: block,
186         def_id: ast::def_id,
187         ref_id: ast::node_id,
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 get_impl_resolutions(bcx: block,
197                         impl_id: ast::def_id)
198                          -> typeck::vtable_res {
199     if impl_id.crate == ast::local_crate {
200         bcx.ccx().maps.vtable_map.get_copy(&impl_id.node)
201     } else {
202         // XXX: This is a temporary hack to work around not properly
203         // exporting information about resolutions for impls.
204         // This doesn't actually work if the trait has param bounds,
205         // but it does allow us to survive the case when it does not.
206         let trait_ref = ty::impl_trait_ref(bcx.tcx(), impl_id).get();
207         @vec::from_elem(trait_ref.substs.tps.len(), @~[])
208     }
209 }
210
211 fn resolve_default_method_vtables(bcx: block,
212                                   impl_id: ast::def_id,
213                                   method: &ty::Method,
214                                   substs: &ty::substs,
215                                   impl_vtables: Option<typeck::vtable_res>)
216                                  -> typeck::vtable_res {
217
218     // Get the vtables that the impl implements the trait at
219     let trait_vtables = get_impl_resolutions(bcx, impl_id);
220
221     // Build up a param_substs that we are going to resolve the
222     // trait_vtables under.
223     let param_substs = Some(@param_substs {
224         tys: substs.tps.clone(),
225         self_ty: substs.self_ty,
226         vtables: impl_vtables,
227         self_vtable: None
228     });
229
230     let trait_vtables_fixed = resolve_vtables_under_param_substs(
231         bcx.tcx(), param_substs, trait_vtables);
232
233     // Now we pull any vtables for parameters on the actual method.
234     let num_method_vtables = method.generics.type_param_defs.len();
235     let method_vtables = match impl_vtables {
236         Some(vtables) => {
237             let num_impl_type_parameters =
238                 vtables.len() - num_method_vtables;
239             vtables.tailn(num_impl_type_parameters).to_owned()
240         },
241         None => vec::from_elem(num_method_vtables, @~[])
242     };
243
244     @(*trait_vtables_fixed + method_vtables)
245 }
246
247
248 pub fn trans_fn_ref_with_vtables(
249         bcx: block,            //
250         def_id: ast::def_id,   // def id of fn
251         ref_id: ast::node_id,  // node id of use of fn; may be zero if N/A
252         type_params: &[ty::t], // values for fn's ty params
253         vtables: Option<typeck::vtable_res>) // vtables for the call
254      -> FnData {
255     //!
256     //
257     // Translates a reference to a fn/method item, monomorphizing and
258     // inlining as it goes.
259     //
260     // # Parameters
261     //
262     // - `bcx`: the current block where the reference to the fn occurs
263     // - `def_id`: def id of the fn or method item being referenced
264     // - `ref_id`: node id of the reference to the fn/method, if applicable.
265     //   This parameter may be zero; but, if so, the resulting value may not
266     //   have the right type, so it must be cast before being used.
267     // - `type_params`: values for each of the fn/method's type parameters
268     // - `vtables`: values for each bound on each of the type parameters
269
270     let _icx = push_ctxt("trans_fn_ref_with_vtables");
271     let ccx = bcx.ccx();
272     let tcx = ccx.tcx;
273
274     debug!("trans_fn_ref_with_vtables(bcx=%s, def_id=%s, ref_id=%?, \
275             type_params=%s, vtables=%s)",
276            bcx.to_str(),
277            def_id.repr(bcx.tcx()),
278            ref_id,
279            type_params.repr(bcx.tcx()),
280            vtables.repr(bcx.tcx()));
281
282     assert!(type_params.iter().all(|t| !ty::type_needs_infer(*t)));
283
284     // Polytype of the function item (may have type params)
285     let fn_tpt = ty::lookup_item_type(tcx, def_id);
286
287     // For simplicity, we want to use the Subst trait when composing
288     // substitutions for default methods.  The subst trait does
289     // substitutions with regions, though, so we put a dummy self
290     // region parameter in to keep it from failing. This is a hack.
291     let substs = ty::substs { self_r: Some(ty::re_empty),
292                               self_ty: None,
293                               tps: /*bad*/ type_params.to_owned() };
294
295
296     // We need to do a bunch of special handling for default methods.
297     // We need to modify the def_id and our substs in order to monomorphize
298     // the function.
299     let (is_default, def_id, substs, self_vtable, vtables) =
300         match ty::provided_source(tcx, def_id) {
301         None => (false, def_id, substs, None, vtables),
302         Some(source_id) => {
303             // There are two relevant substitutions when compiling
304             // default methods. First, there is the substitution for
305             // the type parameters of the impl we are using and the
306             // method we are calling. This substitution is the substs
307             // argument we already have.
308             // In order to compile a default method, though, we need
309             // to consider another substitution: the substitution for
310             // the type parameters on trait; the impl we are using
311             // implements the trait at some particular type
312             // parameters, and we need to substitute for those first.
313             // So, what we need to do is find this substitution and
314             // compose it with the one we already have.
315
316             let impl_id = ty::method(tcx, def_id).container_id;
317             let method = ty::method(tcx, source_id);
318             let trait_ref = ty::impl_trait_ref(tcx, impl_id)
319                 .expect("could not find trait_ref for impl with \
320                          default methods");
321
322             // Get all of the type params for the receiver
323             let param_defs = method.generics.type_param_defs;
324             let receiver_substs =
325                 type_params.initn(param_defs.len()).to_owned();
326             let receiver_vtables = match vtables {
327                 None => @~[],
328                 Some(call_vtables) => {
329                     @call_vtables.initn(param_defs.len()).to_owned()
330                 }
331             };
332
333             let self_vtable =
334                 typeck::vtable_static(impl_id, receiver_substs,
335                                       receiver_vtables);
336             // Compute the first substitution
337             let first_subst = make_substs_for_receiver_types(
338                 tcx, impl_id, trait_ref, method);
339
340             // And compose them
341             let new_substs = first_subst.subst(tcx, &substs);
342
343
344             let vtables =
345                 resolve_default_method_vtables(bcx, impl_id,
346                                                method, &new_substs, vtables);
347
348             debug!("trans_fn_with_vtables - default method: \
349                     substs = %s, trait_subst = %s, \
350                     first_subst = %s, new_subst = %s, \
351                     self_vtable = %s, vtables = %s",
352                    substs.repr(tcx), trait_ref.substs.repr(tcx),
353                    first_subst.repr(tcx), new_substs.repr(tcx),
354                    self_vtable.repr(tcx), vtables.repr(tcx));
355
356             (true, source_id,
357              new_substs, Some(self_vtable), Some(vtables))
358         }
359     };
360
361     // Check whether this fn has an inlined copy and, if so, redirect
362     // def_id to the local id of the inlined copy.
363     let def_id = {
364         if def_id.crate != ast::local_crate {
365             inline::maybe_instantiate_inline(ccx, def_id)
366         } else {
367             def_id
368         }
369     };
370
371     // We must monomorphise if the fn has type parameters, is a rust
372     // intrinsic, or is a default method.  In particular, if we see an
373     // intrinsic that is inlined from a different crate, we want to reemit the
374     // intrinsic instead of trying to call it in the other crate.
375     let must_monomorphise;
376     if type_params.len() > 0 || is_default {
377         must_monomorphise = true;
378     } else if def_id.crate == ast::local_crate {
379         let map_node = session::expect(
380             ccx.sess,
381             ccx.tcx.items.find(&def_id.node),
382             || fmt!("local item should be in ast map"));
383
384         match *map_node {
385             ast_map::node_foreign_item(_, abis, _, _) => {
386                 must_monomorphise = abis.is_intrinsic()
387             }
388             _ => {
389                 must_monomorphise = false;
390             }
391         }
392     } else {
393         must_monomorphise = false;
394     }
395
396     // Create a monomorphic verison of generic functions
397     if must_monomorphise {
398         // Should be either intra-crate or inlined.
399         assert_eq!(def_id.crate, ast::local_crate);
400
401         let (val, must_cast) =
402             monomorphize::monomorphic_fn(ccx, def_id, &substs,
403                                          vtables, self_vtable,
404                                          Some(ref_id));
405         let mut val = val;
406         if must_cast && ref_id != 0 {
407             // Monotype of the REFERENCE to the function (type params
408             // are subst'd)
409             let ref_ty = common::node_id_type(bcx, ref_id);
410
411             val = PointerCast(
412                 bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
413         }
414         return FnData {llfn: val};
415     }
416
417     // Find the actual function pointer.
418     let val = {
419         if def_id.crate == ast::local_crate {
420             // Internal reference.
421             get_item_val(ccx, def_id.node)
422         } else {
423             // External reference.
424             trans_external_path(ccx, def_id, fn_tpt.ty)
425         }
426     };
427
428     return FnData {llfn: val};
429 }
430
431 // ______________________________________________________________________
432 // Translating calls
433
434 pub fn trans_call(in_cx: block,
435                   call_ex: @ast::expr,
436                   f: @ast::expr,
437                   args: CallArgs,
438                   id: ast::node_id,
439                   dest: expr::Dest)
440                   -> block {
441     let _icx = push_ctxt("trans_call");
442     trans_call_inner(in_cx,
443                      call_ex.info(),
444                      expr_ty(in_cx, f),
445                      node_id_type(in_cx, id),
446                      |cx| trans(cx, f),
447                      args,
448                      Some(dest),
449                      DontAutorefArg).bcx
450 }
451
452 pub fn trans_method_call(in_cx: block,
453                          call_ex: @ast::expr,
454                          callee_id: ast::node_id,
455                          rcvr: @ast::expr,
456                          args: CallArgs,
457                          dest: expr::Dest)
458                          -> block {
459     let _icx = push_ctxt("trans_method_call");
460     debug!("trans_method_call(call_ex=%s, rcvr=%s)",
461            call_ex.repr(in_cx.tcx()),
462            rcvr.repr(in_cx.tcx()));
463     trans_call_inner(
464         in_cx,
465         call_ex.info(),
466         node_id_type(in_cx, callee_id),
467         expr_ty(in_cx, call_ex),
468         |cx| {
469             match cx.ccx().maps.method_map.find_copy(&call_ex.id) {
470                 Some(origin) => {
471                     debug!("origin for %s: %s",
472                            call_ex.repr(in_cx.tcx()),
473                            origin.repr(in_cx.tcx()));
474
475                     meth::trans_method_callee(cx,
476                                               callee_id,
477                                               rcvr,
478                                               origin)
479                 }
480                 None => {
481                     cx.tcx().sess.span_bug(call_ex.span, "method call expr wasn't in method map")
482                 }
483             }
484         },
485         args,
486         Some(dest),
487         DontAutorefArg).bcx
488 }
489
490 pub fn trans_lang_call(bcx: block,
491                        did: ast::def_id,
492                        args: &[ValueRef],
493                        dest: Option<expr::Dest>)
494     -> Result {
495     let fty = if did.crate == ast::local_crate {
496         ty::node_id_to_type(bcx.ccx().tcx, did.node)
497     } else {
498         csearch::get_type(bcx.ccx().tcx, did).ty
499     };
500     let rty = ty::ty_fn_ret(fty);
501     callee::trans_call_inner(bcx,
502                              None,
503                              fty,
504                              rty,
505                              |bcx| {
506                                 trans_fn_ref_with_vtables_to_callee(bcx,
507                                                                     did,
508                                                                     0,
509                                                                     [],
510                                                                     None)
511                              },
512                              ArgVals(args),
513                              dest,
514                              DontAutorefArg)
515 }
516
517 pub fn trans_lang_call_with_type_params(bcx: block,
518                                         did: ast::def_id,
519                                         args: &[ValueRef],
520                                         type_params: &[ty::t],
521                                         dest: expr::Dest)
522     -> block {
523     let fty;
524     if did.crate == ast::local_crate {
525         fty = ty::node_id_to_type(bcx.tcx(), did.node);
526     } else {
527         fty = csearch::get_type(bcx.tcx(), did).ty;
528     }
529
530     let rty = ty::ty_fn_ret(fty);
531     return callee::trans_call_inner(
532         bcx, None, fty, rty,
533         |bcx| {
534             let callee =
535                 trans_fn_ref_with_vtables_to_callee(bcx, did, 0,
536                                                     type_params,
537                                                     None);
538
539             let new_llval;
540             match callee.data {
541                 Fn(fn_data) => {
542                     let substituted = ty::subst_tps(callee.bcx.tcx(),
543                                                     type_params,
544                                                     None,
545                                                     fty);
546                     let llfnty = type_of::type_of(callee.bcx.ccx(),
547                                                       substituted);
548                     new_llval = PointerCast(callee.bcx, fn_data.llfn, llfnty);
549                 }
550                 _ => fail!()
551             }
552             Callee { bcx: callee.bcx, data: Fn(FnData { llfn: new_llval }) }
553         },
554         ArgVals(args), Some(dest), DontAutorefArg).bcx;
555 }
556
557 pub fn body_contains_ret(body: &ast::Block) -> bool {
558     let cx = @mut false;
559     visit::visit_block(body, (cx, visit::mk_vt(@visit::Visitor {
560         visit_item: |_i, (_cx, _v)| { },
561         visit_expr: |e: @ast::expr, (cx, v): (@mut bool, visit::vt<@mut bool>)| {
562             if !*cx {
563                 match e.node {
564                   ast::expr_ret(_) => *cx = true,
565                   _ => visit::visit_expr(e, (cx, v)),
566                 }
567             }
568         },
569         ..*visit::default_visitor()
570     })));
571     *cx
572 }
573
574 // See [Note-arg-mode]
575 pub fn trans_call_inner(in_cx: block,
576                         call_info: Option<NodeInfo>,
577                         fn_expr_ty: ty::t,
578                         ret_ty: ty::t,
579                         get_callee: &fn(block) -> Callee,
580                         args: CallArgs,
581                         dest: Option<expr::Dest>,
582                         autoref_arg: AutorefArg)
583                         -> Result {
584     do base::with_scope_result(in_cx, call_info, "call") |cx| {
585         let ret_in_loop = match args {
586           ArgExprs(args) => {
587             args.len() > 0u && match args.last().node {
588               ast::expr_loop_body(@ast::expr {
589                 node: ast::expr_fn_block(_, ref body),
590                 _
591               }) =>  body_contains_ret(body),
592               _ => false
593             }
594           }
595           _ => false
596         };
597
598         let callee = get_callee(cx);
599         let mut bcx = callee.bcx;
600         let ccx = cx.ccx();
601         let ret_flag = if ret_in_loop {
602             let flag = alloca(bcx, Type::bool(), "__ret_flag");
603             Store(bcx, C_bool(false), flag);
604             Some(flag)
605         } else {
606             None
607         };
608
609         let (llfn, llenv) = unsafe {
610             match callee.data {
611                 Fn(d) => {
612                     (d.llfn, llvm::LLVMGetUndef(Type::opaque_box(ccx).ptr_to().to_ref()))
613                 }
614                 Method(d) => {
615                     // Weird but true: we pass self in the *environment* slot!
616                     (d.llfn, d.llself)
617                 }
618                 Closure(d) => {
619                     // Closures are represented as (llfn, llclosure) pair:
620                     // load the requisite values out.
621                     let pair = d.to_ref_llval(bcx);
622                     let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]);
623                     let llfn = Load(bcx, llfn);
624                     let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]);
625                     let llenv = Load(bcx, llenv);
626                     (llfn, llenv)
627                 }
628             }
629         };
630
631         let llretslot = trans_ret_slot(bcx, fn_expr_ty, dest);
632
633         let mut llargs = ~[];
634
635         if !ty::type_is_immediate(bcx.tcx(), ret_ty) {
636             llargs.push(llretslot);
637         }
638
639         llargs.push(llenv);
640         bcx = trans_args(bcx, args, fn_expr_ty,
641                          ret_flag, autoref_arg, &mut llargs);
642
643
644         // Now that the arguments have finished evaluating, we need to revoke
645         // the cleanup for the self argument
646         match callee.data {
647             Method(d) => {
648                 for d.temp_cleanup.iter().advance |&v| {
649                     revoke_clean(bcx, v);
650                 }
651             }
652             _ => {}
653         }
654
655         // Uncomment this to debug calls.
656         /*
657         io::println(fmt!("calling: %s", bcx.val_to_str(llfn)));
658         for llargs.iter().advance |llarg| {
659             io::println(fmt!("arg: %s", bcx.val_to_str(*llarg)));
660         }
661         io::println("---");
662         */
663
664         // If the block is terminated, then one or more of the args
665         // has type _|_. Since that means it diverges, the code for
666         // the call itself is unreachable.
667         let (llresult, new_bcx) = base::invoke(bcx, llfn, llargs);
668         bcx = new_bcx;
669
670         match dest {
671             None => { assert!(ty::type_is_immediate(bcx.tcx(), ret_ty)) }
672             Some(expr::Ignore) => {
673                 // drop the value if it is not being saved.
674                 if ty::type_needs_drop(bcx.tcx(), ret_ty) {
675                     if ty::type_is_immediate(bcx.tcx(), ret_ty) {
676                         let llscratchptr = alloc_ty(bcx, ret_ty, "__ret");
677                         Store(bcx, llresult, llscratchptr);
678                         bcx = glue::drop_ty(bcx, llscratchptr, ret_ty);
679                     } else {
680                         bcx = glue::drop_ty(bcx, llretslot, ret_ty);
681                     }
682                 }
683             }
684             Some(expr::SaveIn(lldest)) => {
685                 // If this is an immediate, store into the result location.
686                 // (If this was not an immediate, the result will already be
687                 // directly written into the output slot.)
688                 if ty::type_is_immediate(bcx.tcx(), ret_ty) {
689                     Store(bcx, llresult, lldest);
690                 }
691             }
692         }
693
694         if ty::type_is_bot(ret_ty) {
695             Unreachable(bcx);
696         } else if ret_in_loop {
697             let ret_flag_result = bool_to_i1(bcx, Load(bcx, ret_flag.get()));
698             bcx = do with_cond(bcx, ret_flag_result) |bcx| {
699                 {
700                     let r = bcx.fcx.loop_ret;
701                     for r.iter().advance |&(flagptr, _)| {
702                         Store(bcx, C_bool(true), flagptr);
703                         Store(bcx, C_bool(false), bcx.fcx.llretptr.get());
704                     }
705                 }
706                 base::cleanup_and_leave(bcx, None, Some(bcx.fcx.get_llreturn()));
707                 Unreachable(bcx);
708                 bcx
709             }
710         }
711         rslt(bcx, llresult)
712     }
713 }
714
715
716 pub enum CallArgs<'self> {
717     ArgExprs(&'self [@ast::expr]),
718     ArgVals(&'self [ValueRef])
719 }
720
721 pub fn trans_ret_slot(bcx: block, fn_ty: ty::t, dest: Option<expr::Dest>)
722                       -> ValueRef {
723     let retty = ty::ty_fn_ret(fn_ty);
724
725     match dest {
726         Some(expr::SaveIn(dst)) => dst,
727         _ => {
728             if ty::type_is_immediate(bcx.tcx(), retty) {
729                 unsafe {
730                     llvm::LLVMGetUndef(Type::nil().ptr_to().to_ref())
731                 }
732             } else {
733                 alloc_ty(bcx, retty, "__trans_ret_slot")
734             }
735         }
736     }
737 }
738
739 pub fn trans_args(cx: block,
740                   args: CallArgs,
741                   fn_ty: ty::t,
742                   ret_flag: Option<ValueRef>,
743                   autoref_arg: AutorefArg,
744                   llargs: &mut ~[ValueRef]) -> block
745 {
746     let _icx = push_ctxt("trans_args");
747     let mut temp_cleanups = ~[];
748     let arg_tys = ty::ty_fn_args(fn_ty);
749
750     let mut bcx = cx;
751
752     // First we figure out the caller's view of the types of the arguments.
753     // This will be needed if this is a generic call, because the callee has
754     // to cast her view of the arguments to the caller's view.
755     match args {
756       ArgExprs(arg_exprs) => {
757         let last = arg_exprs.len() - 1u;
758         for arg_exprs.iter().enumerate().advance |(i, arg_expr)| {
759             let arg_val = unpack_result!(bcx, {
760                 trans_arg_expr(bcx,
761                                arg_tys[i],
762                                ty::ByCopy,
763                                *arg_expr,
764                                &mut temp_cleanups,
765                                if i == last { ret_flag } else { None },
766                                autoref_arg)
767             });
768             llargs.push(arg_val);
769         }
770       }
771       ArgVals(vs) => {
772         llargs.push_all(vs);
773       }
774     }
775
776     // now that all arguments have been successfully built, we can revoke any
777     // temporary cleanups, as they are only needed if argument construction
778     // should fail (for example, cleanup of copy mode args).
779     for temp_cleanups.iter().advance |c| {
780         revoke_clean(bcx, *c)
781     }
782
783     bcx
784 }
785
786 pub enum AutorefArg {
787     DontAutorefArg,
788     DoAutorefArg
789 }
790
791 // temp_cleanups: cleanups that should run only if failure occurs before the
792 // call takes place:
793 pub fn trans_arg_expr(bcx: block,
794                       formal_arg_ty: ty::t,
795                       self_mode: ty::SelfMode,
796                       arg_expr: @ast::expr,
797                       temp_cleanups: &mut ~[ValueRef],
798                       ret_flag: Option<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             ret_flag=%?)",
805            formal_arg_ty.repr(bcx.tcx()),
806            self_mode,
807            arg_expr.repr(bcx.tcx()),
808            ret_flag.map(|v| bcx.val_to_str(*v)));
809
810     // translate the arg expr to a datum
811     let arg_datumblock = match ret_flag {
812         None => expr::trans_to_datum(bcx, arg_expr),
813
814         // If there is a ret_flag, this *must* be a loop body
815         Some(_) => {
816             match arg_expr.node {
817                 ast::expr_loop_body(
818                     blk @ @ast::expr {
819                         node: ast::expr_fn_block(ref decl, ref body),
820                         _
821                     }) => {
822                     let scratch_ty = expr_ty(bcx, arg_expr);
823                     let scratch = alloc_ty(bcx, scratch_ty, "__ret_flag");
824                     let arg_ty = expr_ty(bcx, arg_expr);
825                     let sigil = ty::ty_closure_sigil(arg_ty);
826                     let bcx = closure::trans_expr_fn(
827                         bcx, sigil, decl, body, arg_expr.id,
828                         blk.id, Some(ret_flag), expr::SaveIn(scratch));
829                     DatumBlock {bcx: bcx,
830                                 datum: Datum {val: scratch,
831                                               ty: scratch_ty,
832                                               mode: ByRef(RevokeClean)}}
833                 }
834                 _ => {
835                     bcx.sess().impossible_case(
836                         arg_expr.span, "ret_flag with non-loop-body expr");
837                 }
838             }
839         }
840     };
841     let arg_datum = arg_datumblock.datum;
842     let bcx = arg_datumblock.bcx;
843
844     debug!("   arg datum: %s", arg_datum.to_str(bcx.ccx()));
845
846     let mut val;
847     if ty::type_is_bot(arg_datum.ty) {
848         // For values of type _|_, we generate an
849         // "undef" value, as such a value should never
850         // be inspected. It's important for the value
851         // to have type lldestty (the callee's expected type).
852         let llformal_arg_ty = type_of::type_of(ccx, formal_arg_ty);
853         unsafe {
854             val = llvm::LLVMGetUndef(llformal_arg_ty.to_ref());
855         }
856     } else {
857         // FIXME(#3548) use the adjustments table
858         match autoref_arg {
859             DoAutorefArg => {
860                 val = arg_datum.to_ref_llval(bcx);
861             }
862             DontAutorefArg => {
863                 match self_mode {
864                     ty::ByRef => {
865                         // This assertion should really be valid, but because
866                         // the explicit self code currently passes by-ref, it
867                         // does not hold.
868                         //
869                         //assert !bcx.ccx().maps.moves_map.contains_key(
870                         //    &arg_expr.id);
871                         debug!("by ref arg with type %s, storing to scratch",
872                                bcx.ty_to_str(arg_datum.ty));
873                         let scratch = scratch_datum(bcx, arg_datum.ty,
874                                                     "__self", false);
875
876                         arg_datum.store_to_datum(bcx,
877                                                  INIT,
878                                                  scratch);
879
880                         // Technically, ownership of val passes to the callee.
881                         // However, we must cleanup should we fail before the
882                         // callee is actually invoked.
883                         scratch.add_clean(bcx);
884                         temp_cleanups.push(scratch.val);
885
886                         val = scratch.to_ref_llval(bcx);
887                     }
888                     ty::ByCopy => {
889                         if ty::type_needs_drop(bcx.tcx(), arg_datum.ty) ||
890                                 arg_datum.appropriate_mode(bcx.tcx()).is_by_ref() {
891                             debug!("by copy arg with type %s, storing to scratch",
892                                    bcx.ty_to_str(arg_datum.ty));
893                             let scratch = scratch_datum(bcx, arg_datum.ty,
894                                                         "__arg", false);
895
896                             arg_datum.store_to_datum(bcx,
897                                                      INIT,
898                                                      scratch);
899
900                             // Technically, ownership of val passes to the callee.
901                             // However, we must cleanup should we fail before the
902                             // callee is actually invoked.
903                             scratch.add_clean(bcx);
904                             temp_cleanups.push(scratch.val);
905
906                             match scratch.appropriate_mode(bcx.tcx()) {
907                                 ByValue => val = Load(bcx, scratch.val),
908                                 ByRef(_) => val = scratch.val,
909                             }
910                         } else {
911                             debug!("by copy arg with type %s", bcx.ty_to_str(arg_datum.ty));
912                             match arg_datum.mode {
913                                 ByRef(_) => val = Load(bcx, arg_datum.val),
914                                 ByValue => val = arg_datum.val,
915                             }
916                         }
917                     }
918                 }
919             }
920         }
921
922         if formal_arg_ty != arg_datum.ty {
923             // this could happen due to e.g. subtyping
924             let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, &formal_arg_ty);
925             debug!("casting actual type (%s) to match formal (%s)",
926                    bcx.val_to_str(val), bcx.llty_str(llformal_arg_ty));
927             val = PointerCast(bcx, val, llformal_arg_ty);
928         }
929     }
930
931     debug!("--- trans_arg_expr passing %s", bcx.val_to_str(val));
932     return rslt(bcx, val);
933 }