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