]> git.proxmox.com Git - rustc.git/blob - src/librustc_trans/trans/meth.rs
e61770768db22e5d6bcc786e55c0f098df10a0db
[rustc.git] / src / librustc_trans / trans / meth.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 use arena::TypedArena;
12 use back::abi;
13 use back::link;
14 use llvm::{ValueRef, get_params};
15 use metadata::csearch;
16 use middle::subst::{Subst, Substs};
17 use middle::subst::VecPerParamSpace;
18 use middle::subst;
19 use middle::traits;
20 use middle::ty::ClosureTyper;
21 use rustc::ast_map;
22 use trans::base::*;
23 use trans::build::*;
24 use trans::callee::*;
25 use trans::callee;
26 use trans::cleanup;
27 use trans::closure;
28 use trans::common::*;
29 use trans::consts;
30 use trans::datum::*;
31 use trans::debuginfo::DebugLoc;
32 use trans::declare;
33 use trans::expr::SaveIn;
34 use trans::expr;
35 use trans::glue;
36 use trans::machine;
37 use trans::monomorphize;
38 use trans::type_::Type;
39 use trans::type_of::*;
40 use middle::ty::{self, Ty};
41 use middle::ty::MethodCall;
42
43 use syntax::abi::{Rust, RustCall};
44 use syntax::parse::token;
45 use syntax::{ast, attr, visit};
46 use syntax::codemap::DUMMY_SP;
47 use syntax::ptr::P;
48
49 // drop_glue pointer, size, align.
50 const VTABLE_OFFSET: usize = 3;
51
52 /// The main "translation" pass for methods. Generates code
53 /// for non-monomorphized methods only. Other methods will
54 /// be generated once they are invoked with specific type parameters,
55 /// see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`.
56 pub fn trans_impl(ccx: &CrateContext,
57 name: ast::Ident,
58 impl_items: &[P<ast::ImplItem>],
59 generics: &ast::Generics,
60 id: ast::NodeId) {
61 let _icx = push_ctxt("meth::trans_impl");
62 let tcx = ccx.tcx();
63
64 debug!("trans_impl(name={}, id={})", name, id);
65
66 let mut v = TransItemVisitor { ccx: ccx };
67
68 // Both here and below with generic methods, be sure to recurse and look for
69 // items that we need to translate.
70 if !generics.ty_params.is_empty() {
71 for impl_item in impl_items {
72 match impl_item.node {
73 ast::MethodImplItem(..) => {
74 visit::walk_impl_item(&mut v, impl_item);
75 }
76 _ => {}
77 }
78 }
79 return;
80 }
81 for impl_item in impl_items {
82 match impl_item.node {
83 ast::MethodImplItem(ref sig, ref body) => {
84 if sig.generics.ty_params.is_empty() {
85 let trans_everywhere = attr::requests_inline(&impl_item.attrs);
86 for (ref ccx, is_origin) in ccx.maybe_iter(trans_everywhere) {
87 let llfn = get_item_val(ccx, impl_item.id);
88 let empty_substs = tcx.mk_substs(Substs::trans_empty());
89 trans_fn(ccx, &sig.decl, body, llfn,
90 empty_substs, impl_item.id, &[]);
91 update_linkage(ccx,
92 llfn,
93 Some(impl_item.id),
94 if is_origin { OriginalTranslation } else { InlinedCopy });
95 }
96 }
97 visit::walk_impl_item(&mut v, impl_item);
98 }
99 _ => {}
100 }
101 }
102 }
103
104 pub fn trans_method_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
105 method_call: MethodCall,
106 self_expr: Option<&ast::Expr>,
107 arg_cleanup_scope: cleanup::ScopeId)
108 -> Callee<'blk, 'tcx> {
109 let _icx = push_ctxt("meth::trans_method_callee");
110
111 let (origin, method_ty) =
112 bcx.tcx().method_map
113 .borrow()
114 .get(&method_call)
115 .map(|method| (method.origin.clone(), method.ty))
116 .unwrap();
117
118 match origin {
119 ty::MethodStatic(did) |
120 ty::MethodStaticClosure(did) => {
121 debug!("trans_method_callee: static, {:?}", did);
122 Callee {
123 bcx: bcx,
124 data: Fn(callee::trans_fn_ref(bcx.ccx(),
125 did,
126 MethodCallKey(method_call),
127 bcx.fcx.param_substs).val),
128 }
129 }
130
131 ty::MethodTypeParam(ty::MethodParam {
132 ref trait_ref,
133 method_num,
134 impl_def_id: _
135 }) => {
136 let trait_ref = ty::Binder(bcx.monomorphize(trait_ref));
137 let span = bcx.tcx().map.span(method_call.expr_id);
138 debug!("method_call={:?} trait_ref={:?} trait_ref id={:?} substs={:?}",
139 method_call,
140 trait_ref,
141 trait_ref.0.def_id,
142 trait_ref.0.substs);
143 let origin = fulfill_obligation(bcx.ccx(),
144 span,
145 trait_ref.clone());
146 debug!("origin = {:?}", origin);
147 trans_monomorphized_callee(bcx,
148 method_call,
149 trait_ref.def_id(),
150 method_num,
151 origin)
152 }
153
154 ty::MethodTraitObject(ref mt) => {
155 let self_expr = match self_expr {
156 Some(self_expr) => self_expr,
157 None => {
158 bcx.sess().span_bug(bcx.tcx().map.span(method_call.expr_id),
159 "self expr wasn't provided for trait object \
160 callee (trying to call overloaded op?)")
161 }
162 };
163 trans_trait_callee(bcx,
164 monomorphize_type(bcx, method_ty),
165 mt.vtable_index,
166 self_expr,
167 arg_cleanup_scope)
168 }
169 }
170 }
171
172 pub fn trans_static_method_callee<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
173 method_id: ast::DefId,
174 trait_id: ast::DefId,
175 expr_id: ast::NodeId,
176 param_substs: &'tcx subst::Substs<'tcx>)
177 -> Datum<'tcx, Rvalue>
178 {
179 let _icx = push_ctxt("meth::trans_static_method_callee");
180 let tcx = ccx.tcx();
181
182 debug!("trans_static_method_callee(method_id={:?}, trait_id={}, \
183 expr_id={})",
184 method_id,
185 ty::item_path_str(tcx, trait_id),
186 expr_id);
187
188 let mname = if method_id.krate == ast::LOCAL_CRATE {
189 match tcx.map.get(method_id.node) {
190 ast_map::NodeTraitItem(trait_item) => trait_item.ident.name,
191 _ => panic!("callee is not a trait method")
192 }
193 } else {
194 csearch::get_item_path(tcx, method_id).last().unwrap().name()
195 };
196 debug!("trans_static_method_callee: method_id={:?}, expr_id={}, \
197 name={}", method_id, expr_id, token::get_name(mname));
198
199 // Find the substitutions for the fn itself. This includes
200 // type parameters that belong to the trait but also some that
201 // belong to the method:
202 let rcvr_substs = node_id_substs(ccx, ExprId(expr_id), param_substs);
203 let subst::SeparateVecsPerParamSpace {
204 types: rcvr_type,
205 selfs: rcvr_self,
206 fns: rcvr_method
207 } = rcvr_substs.types.split();
208
209 // Lookup the precise impl being called. To do that, we need to
210 // create a trait reference identifying the self type and other
211 // input type parameters. To create that trait reference, we have
212 // to pick apart the type parameters to identify just those that
213 // pertain to the trait. This is easiest to explain by example:
214 //
215 // trait Convert {
216 // fn from<U:Foo>(n: U) -> Option<Self>;
217 // }
218 // ...
219 // let f = <Vec<int> as Convert>::from::<String>(...)
220 //
221 // Here, in this call, which I've written with explicit UFCS
222 // notation, the set of type parameters will be:
223 //
224 // rcvr_type: [] <-- nothing declared on the trait itself
225 // rcvr_self: [Vec<int>] <-- the self type
226 // rcvr_method: [String] <-- method type parameter
227 //
228 // So we create a trait reference using the first two,
229 // basically corresponding to `<Vec<int> as Convert>`.
230 // The remaining type parameters (`rcvr_method`) will be used below.
231 let trait_substs =
232 Substs::erased(VecPerParamSpace::new(rcvr_type,
233 rcvr_self,
234 Vec::new()));
235 let trait_substs = tcx.mk_substs(trait_substs);
236 debug!("trait_substs={:?}", trait_substs);
237 let trait_ref = ty::Binder(ty::TraitRef { def_id: trait_id,
238 substs: trait_substs });
239 let vtbl = fulfill_obligation(ccx,
240 DUMMY_SP,
241 trait_ref);
242
243 // Now that we know which impl is being used, we can dispatch to
244 // the actual function:
245 match vtbl {
246 traits::VtableImpl(traits::VtableImplData {
247 impl_def_id: impl_did,
248 substs: impl_substs,
249 nested: _ }) =>
250 {
251 assert!(impl_substs.types.all(|t| !ty::type_needs_infer(*t)));
252
253 // Create the substitutions that are in scope. This combines
254 // the type parameters from the impl with those declared earlier.
255 // To see what I mean, consider a possible impl:
256 //
257 // impl<T> Convert for Vec<T> {
258 // fn from<U:Foo>(n: U) { ... }
259 // }
260 //
261 // Recall that we matched `<Vec<int> as Convert>`. Trait
262 // resolution will have given us a substitution
263 // containing `impl_substs=[[T=int],[],[]]` (the type
264 // parameters defined on the impl). We combine
265 // that with the `rcvr_method` from before, which tells us
266 // the type parameters from the *method*, to yield
267 // `callee_substs=[[T=int],[],[U=String]]`.
268 let subst::SeparateVecsPerParamSpace {
269 types: impl_type,
270 selfs: impl_self,
271 fns: _
272 } = impl_substs.types.split();
273 let callee_substs =
274 Substs::erased(VecPerParamSpace::new(impl_type,
275 impl_self,
276 rcvr_method));
277
278 let mth_id = method_with_name(ccx, impl_did, mname);
279 trans_fn_ref_with_substs(ccx, mth_id, ExprId(expr_id),
280 param_substs,
281 callee_substs)
282 }
283 traits::VtableObject(ref data) => {
284 let trait_item_def_ids =
285 ty::trait_item_def_ids(ccx.tcx(), trait_id);
286 let method_offset_in_trait =
287 trait_item_def_ids.iter()
288 .position(|item| item.def_id() == method_id)
289 .unwrap();
290 let (llfn, ty) =
291 trans_object_shim(ccx,
292 data.object_ty,
293 data.upcast_trait_ref.clone(),
294 method_offset_in_trait);
295 immediate_rvalue(llfn, ty)
296 }
297 _ => {
298 tcx.sess.bug(&format!("static call to invalid vtable: {:?}",
299 vtbl));
300 }
301 }
302 }
303
304 fn method_with_name(ccx: &CrateContext, impl_id: ast::DefId, name: ast::Name)
305 -> ast::DefId {
306 match ccx.impl_method_cache().borrow().get(&(impl_id, name)).cloned() {
307 Some(m) => return m,
308 None => {}
309 }
310
311 let impl_items = ccx.tcx().impl_items.borrow();
312 let impl_items =
313 impl_items.get(&impl_id)
314 .expect("could not find impl while translating");
315 let meth_did = impl_items.iter()
316 .find(|&did| {
317 ty::impl_or_trait_item(ccx.tcx(), did.def_id()).name() == name
318 }).expect("could not find method while \
319 translating");
320
321 ccx.impl_method_cache().borrow_mut().insert((impl_id, name),
322 meth_did.def_id());
323 meth_did.def_id()
324 }
325
326 fn trans_monomorphized_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
327 method_call: MethodCall,
328 trait_id: ast::DefId,
329 n_method: usize,
330 vtable: traits::Vtable<'tcx, ()>)
331 -> Callee<'blk, 'tcx> {
332 let _icx = push_ctxt("meth::trans_monomorphized_callee");
333 match vtable {
334 traits::VtableImpl(vtable_impl) => {
335 let ccx = bcx.ccx();
336 let impl_did = vtable_impl.impl_def_id;
337 let mname = match ty::trait_item(ccx.tcx(), trait_id, n_method) {
338 ty::MethodTraitItem(method) => method.name,
339 _ => {
340 bcx.tcx().sess.bug("can't monomorphize a non-method trait \
341 item")
342 }
343 };
344 let mth_id = method_with_name(bcx.ccx(), impl_did, mname);
345
346 // create a concatenated set of substitutions which includes
347 // those from the impl and those from the method:
348 let callee_substs =
349 combine_impl_and_methods_tps(
350 bcx, MethodCallKey(method_call), vtable_impl.substs);
351
352 // translate the function
353 let llfn = trans_fn_ref_with_substs(bcx.ccx(),
354 mth_id,
355 MethodCallKey(method_call),
356 bcx.fcx.param_substs,
357 callee_substs).val;
358
359 Callee { bcx: bcx, data: Fn(llfn) }
360 }
361 traits::VtableClosure(vtable_closure) => {
362 // The substitutions should have no type parameters remaining
363 // after passing through fulfill_obligation
364 let trait_closure_kind = bcx.tcx().lang_items.fn_trait_kind(trait_id).unwrap();
365 let llfn = closure::trans_closure_method(bcx.ccx(),
366 vtable_closure.closure_def_id,
367 vtable_closure.substs,
368 MethodCallKey(method_call),
369 bcx.fcx.param_substs,
370 trait_closure_kind);
371 Callee {
372 bcx: bcx,
373 data: Fn(llfn),
374 }
375 }
376 traits::VtableFnPointer(fn_ty) => {
377 let trait_closure_kind = bcx.tcx().lang_items.fn_trait_kind(trait_id).unwrap();
378 let llfn = trans_fn_pointer_shim(bcx.ccx(), trait_closure_kind, fn_ty);
379 Callee { bcx: bcx, data: Fn(llfn) }
380 }
381 traits::VtableObject(ref data) => {
382 let (llfn, _) = trans_object_shim(bcx.ccx(),
383 data.object_ty,
384 data.upcast_trait_ref.clone(),
385 n_method);
386 Callee { bcx: bcx, data: Fn(llfn) }
387 }
388 traits::VtableBuiltin(..) |
389 traits::VtableDefaultImpl(..) |
390 traits::VtableParam(..) => {
391 bcx.sess().bug(
392 &format!("resolved vtable bad vtable {:?} in trans",
393 vtable));
394 }
395 }
396 }
397
398 /// Creates a concatenated set of substitutions which includes those from the impl and those from
399 /// the method. This are some subtle complications here. Statically, we have a list of type
400 /// parameters like `[T0, T1, T2, M1, M2, M3]` where `Tn` are type parameters that appear on the
401 /// receiver. For example, if the receiver is a method parameter `A` with a bound like
402 /// `trait<B,C,D>` then `Tn` would be `[B,C,D]`.
403 ///
404 /// The weird part is that the type `A` might now be bound to any other type, such as `foo<X>`.
405 /// In that case, the vector we want is: `[X, M1, M2, M3]`. Therefore, what we do now is to slice
406 /// off the method type parameters and append them to the type parameters from the type that the
407 /// receiver is mapped to.
408 fn combine_impl_and_methods_tps<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
409 node: ExprOrMethodCall,
410 rcvr_substs: subst::Substs<'tcx>)
411 -> subst::Substs<'tcx>
412 {
413 let ccx = bcx.ccx();
414
415 let node_substs = node_id_substs(ccx, node, bcx.fcx.param_substs);
416
417 debug!("rcvr_substs={:?}", rcvr_substs);
418 debug!("node_substs={:?}", node_substs);
419
420 // Break apart the type parameters from the node and type
421 // parameters from the receiver.
422 let node_method = node_substs.types.split().fns;
423 let subst::SeparateVecsPerParamSpace {
424 types: rcvr_type,
425 selfs: rcvr_self,
426 fns: rcvr_method
427 } = rcvr_substs.types.clone().split();
428 assert!(rcvr_method.is_empty());
429 subst::Substs {
430 regions: subst::ErasedRegions,
431 types: subst::VecPerParamSpace::new(rcvr_type, rcvr_self, node_method)
432 }
433 }
434
435 /// Create a method callee where the method is coming from a trait object (e.g., Box<Trait> type).
436 /// In this case, we must pull the fn pointer out of the vtable that is packaged up with the
437 /// object. Objects are represented as a pair, so we first evaluate the self expression and then
438 /// extract the self data and vtable out of the pair.
439 fn trans_trait_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
440 method_ty: Ty<'tcx>,
441 vtable_index: usize,
442 self_expr: &ast::Expr,
443 arg_cleanup_scope: cleanup::ScopeId)
444 -> Callee<'blk, 'tcx> {
445 let _icx = push_ctxt("meth::trans_trait_callee");
446 let mut bcx = bcx;
447
448 // Translate self_datum and take ownership of the value by
449 // converting to an rvalue.
450 let self_datum = unpack_datum!(
451 bcx, expr::trans(bcx, self_expr));
452
453 let llval = if bcx.fcx.type_needs_drop(self_datum.ty) {
454 let self_datum = unpack_datum!(
455 bcx, self_datum.to_rvalue_datum(bcx, "trait_callee"));
456
457 // Convert to by-ref since `trans_trait_callee_from_llval` wants it
458 // that way.
459 let self_datum = unpack_datum!(
460 bcx, self_datum.to_ref_datum(bcx));
461
462 // Arrange cleanup in case something should go wrong before the
463 // actual call occurs.
464 self_datum.add_clean(bcx.fcx, arg_cleanup_scope)
465 } else {
466 // We don't have to do anything about cleanups for &Trait and &mut Trait.
467 assert!(self_datum.kind.is_by_ref());
468 self_datum.val
469 };
470
471 let llself = Load(bcx, GEPi(bcx, llval, &[0, abi::FAT_PTR_ADDR]));
472 let llvtable = Load(bcx, GEPi(bcx, llval, &[0, abi::FAT_PTR_EXTRA]));
473 trans_trait_callee_from_llval(bcx, method_ty, vtable_index, llself, llvtable)
474 }
475
476 /// Same as `trans_trait_callee()` above, except that it is given a by-ref pointer to the object
477 /// pair.
478 pub fn trans_trait_callee_from_llval<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
479 callee_ty: Ty<'tcx>,
480 vtable_index: usize,
481 llself: ValueRef,
482 llvtable: ValueRef)
483 -> Callee<'blk, 'tcx> {
484 let _icx = push_ctxt("meth::trans_trait_callee");
485 let ccx = bcx.ccx();
486
487 // Load the data pointer from the object.
488 debug!("trans_trait_callee_from_llval(callee_ty={}, vtable_index={}, llself={}, llvtable={})",
489 callee_ty,
490 vtable_index,
491 bcx.val_to_string(llself),
492 bcx.val_to_string(llvtable));
493
494 // Replace the self type (&Self or Box<Self>) with an opaque pointer.
495 let llcallee_ty = match callee_ty.sty {
496 ty::TyBareFn(_, ref f) if f.abi == Rust || f.abi == RustCall => {
497 let fake_sig =
498 ty::Binder(ty::FnSig {
499 inputs: f.sig.0.inputs[1..].to_vec(),
500 output: f.sig.0.output,
501 variadic: f.sig.0.variadic,
502 });
503 type_of_rust_fn(ccx, Some(Type::i8p(ccx)), &fake_sig, f.abi)
504 }
505 _ => {
506 ccx.sess().bug("meth::trans_trait_callee given non-bare-rust-fn");
507 }
508 };
509 let mptr = Load(bcx, GEPi(bcx, llvtable, &[vtable_index + VTABLE_OFFSET]));
510
511 return Callee {
512 bcx: bcx,
513 data: TraitItem(MethodData {
514 llfn: PointerCast(bcx, mptr, llcallee_ty.ptr_to()),
515 llself: PointerCast(bcx, llself, Type::i8p(ccx)),
516 })
517 };
518 }
519
520 /// Generate a shim function that allows an object type like `SomeTrait` to
521 /// implement the type `SomeTrait`. Imagine a trait definition:
522 ///
523 /// trait SomeTrait { fn get(&self) -> int; ... }
524 ///
525 /// And a generic bit of code:
526 ///
527 /// fn foo<T:SomeTrait>(t: &T) {
528 /// let x = SomeTrait::get;
529 /// x(t)
530 /// }
531 ///
532 /// What is the value of `x` when `foo` is invoked with `T=SomeTrait`?
533 /// The answer is that it it is a shim function generate by this
534 /// routine:
535 ///
536 /// fn shim(t: &SomeTrait) -> int {
537 /// // ... call t.get() virtually ...
538 /// }
539 ///
540 /// In fact, all virtual calls can be thought of as normal trait calls
541 /// that go through this shim function.
542 pub fn trans_object_shim<'a, 'tcx>(
543 ccx: &'a CrateContext<'a, 'tcx>,
544 object_ty: Ty<'tcx>,
545 upcast_trait_ref: ty::PolyTraitRef<'tcx>,
546 method_offset_in_trait: usize)
547 -> (ValueRef, Ty<'tcx>)
548 {
549 let _icx = push_ctxt("trans_object_shim");
550 let tcx = ccx.tcx();
551 let trait_id = upcast_trait_ref.def_id();
552
553 debug!("trans_object_shim(object_ty={:?}, upcast_trait_ref={:?}, method_offset_in_trait={})",
554 object_ty,
555 upcast_trait_ref,
556 method_offset_in_trait);
557
558 let object_trait_ref =
559 match object_ty.sty {
560 ty::TyTrait(ref data) => {
561 data.principal_trait_ref_with_self_ty(tcx, object_ty)
562 }
563 _ => {
564 tcx.sess.bug(&format!("trans_object_shim() called on non-object: {:?}",
565 object_ty));
566 }
567 };
568
569 // Upcast to the trait in question and extract out the substitutions.
570 let upcast_trait_ref = ty::erase_late_bound_regions(tcx, &upcast_trait_ref);
571 let object_substs = upcast_trait_ref.substs.clone().erase_regions();
572 debug!("trans_object_shim: object_substs={:?}", object_substs);
573
574 // Lookup the type of this method as declared in the trait and apply substitutions.
575 let method_ty = match ty::trait_item(tcx, trait_id, method_offset_in_trait) {
576 ty::MethodTraitItem(method) => method,
577 _ => {
578 tcx.sess.bug("can't create a method shim for a non-method item")
579 }
580 };
581 let fty = monomorphize::apply_param_substs(tcx, &object_substs, &method_ty.fty);
582 let fty = tcx.mk_bare_fn(fty);
583 let method_ty = opaque_method_ty(tcx, fty);
584 debug!("trans_object_shim: fty={:?} method_ty={:?}", fty, method_ty);
585
586 //
587 let shim_fn_ty = ty::mk_bare_fn(tcx, None, fty);
588 let method_bare_fn_ty = ty::mk_bare_fn(tcx, None, method_ty);
589 let function_name = link::mangle_internal_name_by_type_and_seq(ccx, shim_fn_ty, "object_shim");
590 let llfn = declare::define_internal_rust_fn(ccx, &function_name, shim_fn_ty).unwrap_or_else(||{
591 ccx.sess().bug(&format!("symbol `{}` already defined", function_name));
592 });
593
594 let sig = ty::erase_late_bound_regions(ccx.tcx(), &fty.sig);
595
596 let empty_substs = tcx.mk_substs(Substs::trans_empty());
597 let (block_arena, fcx): (TypedArena<_>, FunctionContext);
598 block_arena = TypedArena::new();
599 fcx = new_fn_ctxt(ccx,
600 llfn,
601 ast::DUMMY_NODE_ID,
602 false,
603 sig.output,
604 empty_substs,
605 None,
606 &block_arena);
607 let mut bcx = init_function(&fcx, false, sig.output);
608
609 let llargs = get_params(fcx.llfn);
610
611 let self_idx = fcx.arg_offset();
612 let llself = llargs[self_idx];
613 let llvtable = llargs[self_idx + 1];
614
615 debug!("trans_object_shim: llself={}, llvtable={}",
616 bcx.val_to_string(llself), bcx.val_to_string(llvtable));
617
618 assert!(!fcx.needs_ret_allocas);
619
620 let dest =
621 fcx.llretslotptr.get().map(
622 |_| expr::SaveIn(fcx.get_ret_slot(bcx, sig.output, "ret_slot")));
623
624 let method_offset_in_vtable =
625 traits::get_vtable_index_of_object_method(bcx.tcx(),
626 object_trait_ref.clone(),
627 trait_id,
628 method_offset_in_trait);
629 debug!("trans_object_shim: method_offset_in_vtable={}",
630 method_offset_in_vtable);
631
632 bcx = trans_call_inner(bcx,
633 DebugLoc::None,
634 method_bare_fn_ty,
635 |bcx, _| trans_trait_callee_from_llval(bcx,
636 method_bare_fn_ty,
637 method_offset_in_vtable,
638 llself, llvtable),
639 ArgVals(&llargs[(self_idx + 2)..]),
640 dest).bcx;
641
642 finish_fn(&fcx, bcx, sig.output, DebugLoc::None);
643
644 (llfn, method_bare_fn_ty)
645 }
646
647 /// Creates a returns a dynamic vtable for the given type and vtable origin.
648 /// This is used only for objects.
649 ///
650 /// The `trait_ref` encodes the erased self type. Hence if we are
651 /// making an object `Foo<Trait>` from a value of type `Foo<T>`, then
652 /// `trait_ref` would map `T:Trait`.
653 pub fn get_vtable<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
654 trait_ref: ty::PolyTraitRef<'tcx>,
655 param_substs: &'tcx subst::Substs<'tcx>)
656 -> ValueRef
657 {
658 let tcx = ccx.tcx();
659 let _icx = push_ctxt("meth::get_vtable");
660
661 debug!("get_vtable(trait_ref={:?})", trait_ref);
662
663 // Check the cache.
664 match ccx.vtables().borrow().get(&trait_ref) {
665 Some(&val) => { return val }
666 None => { }
667 }
668
669 // Not in the cache. Build it.
670 let methods = traits::supertraits(tcx, trait_ref.clone()).flat_map(|trait_ref| {
671 let vtable = fulfill_obligation(ccx, DUMMY_SP, trait_ref.clone());
672 match vtable {
673 // Should default trait error here?
674 traits::VtableDefaultImpl(_) |
675 traits::VtableBuiltin(_) => {
676 Vec::new().into_iter()
677 }
678 traits::VtableImpl(
679 traits::VtableImplData {
680 impl_def_id: id,
681 substs,
682 nested: _ }) => {
683 emit_vtable_methods(ccx, id, substs, param_substs).into_iter()
684 }
685 traits::VtableClosure(
686 traits::VtableClosureData {
687 closure_def_id,
688 substs,
689 nested: _ }) => {
690 let trait_closure_kind = tcx.lang_items.fn_trait_kind(trait_ref.def_id()).unwrap();
691 let llfn = closure::trans_closure_method(ccx,
692 closure_def_id,
693 substs,
694 ExprId(0),
695 param_substs,
696 trait_closure_kind);
697 vec![llfn].into_iter()
698 }
699 traits::VtableFnPointer(bare_fn_ty) => {
700 let trait_closure_kind = tcx.lang_items.fn_trait_kind(trait_ref.def_id()).unwrap();
701 vec![trans_fn_pointer_shim(ccx, trait_closure_kind, bare_fn_ty)].into_iter()
702 }
703 traits::VtableObject(ref data) => {
704 // this would imply that the Self type being erased is
705 // an object type; this cannot happen because we
706 // cannot cast an unsized type into a trait object
707 tcx.sess.bug(
708 &format!("cannot get vtable for an object type: {:?}",
709 data));
710 }
711 traits::VtableParam(..) => {
712 tcx.sess.bug(
713 &format!("resolved vtable for {:?} to bad vtable {:?} in trans",
714 trait_ref,
715 vtable));
716 }
717 }
718 });
719
720 let size_ty = sizing_type_of(ccx, trait_ref.self_ty());
721 let size = machine::llsize_of_alloc(ccx, size_ty);
722 let align = align_of(ccx, trait_ref.self_ty());
723
724 let components: Vec<_> = vec![
725 // Generate a destructor for the vtable.
726 glue::get_drop_glue(ccx, trait_ref.self_ty()),
727 C_uint(ccx, size),
728 C_uint(ccx, align)
729 ].into_iter().chain(methods).collect();
730
731 let vtable = consts::addr_of(ccx, C_struct(ccx, &components, false), "vtable");
732
733 ccx.vtables().borrow_mut().insert(trait_ref, vtable);
734 vtable
735 }
736
737 fn emit_vtable_methods<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
738 impl_id: ast::DefId,
739 substs: subst::Substs<'tcx>,
740 param_substs: &'tcx subst::Substs<'tcx>)
741 -> Vec<ValueRef>
742 {
743 let tcx = ccx.tcx();
744
745 debug!("emit_vtable_methods(impl_id={:?}, substs={:?}, param_substs={:?})",
746 impl_id,
747 substs,
748 param_substs);
749
750 let trt_id = match ty::impl_trait_ref(tcx, impl_id) {
751 Some(t_id) => t_id.def_id,
752 None => ccx.sess().bug("make_impl_vtable: don't know how to \
753 make a vtable for a type impl!")
754 };
755
756 ty::populate_implementations_for_trait_if_necessary(tcx, trt_id);
757
758 let nullptr = C_null(Type::nil(ccx).ptr_to());
759 let trait_item_def_ids = ty::trait_item_def_ids(tcx, trt_id);
760 trait_item_def_ids
761 .iter()
762
763 // Filter out non-method items.
764 .filter_map(|item_def_id| {
765 match *item_def_id {
766 ty::MethodTraitItemId(def_id) => Some(def_id),
767 _ => None,
768 }
769 })
770
771 // Now produce pointers for each remaining method. If the
772 // method could never be called from this object, just supply
773 // null.
774 .map(|trait_method_def_id| {
775 debug!("emit_vtable_methods: trait_method_def_id={:?}",
776 trait_method_def_id);
777
778 let trait_method_type = match ty::impl_or_trait_item(tcx, trait_method_def_id) {
779 ty::MethodTraitItem(m) => m,
780 _ => ccx.sess().bug("should be a method, not other assoc item"),
781 };
782 let name = trait_method_type.name;
783
784 // Some methods cannot be called on an object; skip those.
785 if !traits::is_vtable_safe_method(tcx, trt_id, &trait_method_type) {
786 debug!("emit_vtable_methods: not vtable safe");
787 return nullptr;
788 }
789
790 debug!("emit_vtable_methods: trait_method_type={:?}",
791 trait_method_type);
792
793 // The substitutions we have are on the impl, so we grab
794 // the method type from the impl to substitute into.
795 let impl_method_def_id = method_with_name(ccx, impl_id, name);
796 let impl_method_type = match ty::impl_or_trait_item(tcx, impl_method_def_id) {
797 ty::MethodTraitItem(m) => m,
798 _ => ccx.sess().bug("should be a method, not other assoc item"),
799 };
800
801 debug!("emit_vtable_methods: impl_method_type={:?}",
802 impl_method_type);
803
804 // If this is a default method, it's possible that it
805 // relies on where clauses that do not hold for this
806 // particular set of type parameters. Note that this
807 // method could then never be called, so we do not want to
808 // try and trans it, in that case. Issue #23435.
809 if ty::provided_source(tcx, impl_method_def_id).is_some() {
810 let predicates = impl_method_type.predicates.predicates.subst(tcx, &substs);
811 if !normalize_and_test_predicates(ccx, predicates.into_vec()) {
812 debug!("emit_vtable_methods: predicates do not hold");
813 return nullptr;
814 }
815 }
816
817 trans_fn_ref_with_substs(ccx,
818 impl_method_def_id,
819 ExprId(0),
820 param_substs,
821 substs.clone()).val
822 })
823 .collect()
824 }
825
826 /// Replace the self type (&Self or Box<Self>) with an opaque pointer.
827 pub fn opaque_method_ty<'tcx>(tcx: &ty::ctxt<'tcx>, method_ty: &ty::BareFnTy<'tcx>)
828 -> &'tcx ty::BareFnTy<'tcx> {
829 let mut inputs = method_ty.sig.0.inputs.clone();
830 inputs[0] = ty::mk_mut_ptr(tcx, ty::mk_mach_int(tcx, ast::TyI8));
831
832 tcx.mk_bare_fn(ty::BareFnTy {
833 unsafety: method_ty.unsafety,
834 abi: method_ty.abi,
835 sig: ty::Binder(ty::FnSig {
836 inputs: inputs,
837 output: method_ty.sig.0.output,
838 variadic: method_ty.sig.0.variadic,
839 }),
840 })
841 }