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