]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/glue.rs
auto merge of #19628 : jbranchaud/rust/add-string-as-string-doctest, r=steveklabnik
[rust.git] / src / librustc_trans / trans / glue.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //!
12 //
13 // Code relating to taking, dropping, etc as well as type descriptors.
14
15
16 use back::abi;
17 use back::link::*;
18 use llvm::{ValueRef, True, get_param};
19 use llvm;
20 use middle::lang_items::ExchangeFreeFnLangItem;
21 use middle::subst;
22 use middle::subst::{Subst, Substs};
23 use trans::adt;
24 use trans::base::*;
25 use trans::build::*;
26 use trans::callee;
27 use trans::cleanup;
28 use trans::cleanup::CleanupMethods;
29 use trans::common::*;
30 use trans::datum;
31 use trans::debuginfo;
32 use trans::expr;
33 use trans::machine::*;
34 use trans::tvec;
35 use trans::type_::Type;
36 use trans::type_of::{type_of, sizing_type_of, align_of};
37 use middle::ty::{mod, Ty};
38 use util::ppaux::{ty_to_short_str, Repr};
39 use util::ppaux;
40
41 use arena::TypedArena;
42 use std::c_str::ToCStr;
43 use libc::c_uint;
44 use syntax::ast;
45 use syntax::parse::token;
46
47 pub fn trans_exchange_free_dyn<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef,
48                                            size: ValueRef, align: ValueRef)
49                                            -> Block<'blk, 'tcx> {
50     let _icx = push_ctxt("trans_exchange_free");
51     let ccx = cx.ccx();
52     callee::trans_lang_call(cx,
53         langcall(cx, None, "", ExchangeFreeFnLangItem),
54         &[PointerCast(cx, v, Type::i8p(ccx)), size, align],
55         Some(expr::Ignore)).bcx
56 }
57
58 pub fn trans_exchange_free<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef,
59                                        size: u64, align: u32) -> Block<'blk, 'tcx> {
60     trans_exchange_free_dyn(cx, v, C_uint(cx.ccx(), size),
61                                    C_uint(cx.ccx(), align))
62 }
63
64 pub fn trans_exchange_free_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ptr: ValueRef,
65                                           content_ty: Ty<'tcx>) -> Block<'blk, 'tcx> {
66     assert!(ty::type_is_sized(bcx.ccx().tcx(), content_ty));
67     let sizing_type = sizing_type_of(bcx.ccx(), content_ty);
68     let content_size = llsize_of_alloc(bcx.ccx(), sizing_type);
69
70     // `Box<ZeroSizeType>` does not allocate.
71     if content_size != 0 {
72         let content_align = align_of(bcx.ccx(), content_ty);
73         trans_exchange_free(bcx, ptr, content_size, content_align)
74     } else {
75         bcx
76     }
77 }
78
79 pub fn get_drop_glue_type<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
80                                     t: Ty<'tcx>) -> Ty<'tcx> {
81     let tcx = ccx.tcx();
82     // Even if there is no dtor for t, there might be one deeper down and we
83     // might need to pass in the vtable ptr.
84     if !ty::type_is_sized(tcx, t) {
85         return t
86     }
87     if !ty::type_needs_drop(tcx, t) {
88         return ty::mk_i8();
89     }
90     match t.sty {
91         ty::ty_uniq(typ) if !ty::type_needs_drop(tcx, typ)
92                          && ty::type_is_sized(tcx, typ) => {
93             let llty = sizing_type_of(ccx, typ);
94             // `Box<ZeroSizeType>` does not allocate.
95             if llsize_of_alloc(ccx, llty) == 0 {
96                 ty::mk_i8()
97             } else {
98                 t
99             }
100         }
101         _ => t
102     }
103 }
104
105 pub fn drop_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
106                            v: ValueRef,
107                            t: Ty<'tcx>,
108                            source_location: Option<NodeInfo>)
109                            -> Block<'blk, 'tcx> {
110     // NB: v is an *alias* of type t here, not a direct value.
111     debug!("drop_ty(t={})", t.repr(bcx.tcx()));
112     let _icx = push_ctxt("drop_ty");
113     if ty::type_needs_drop(bcx.tcx(), t) {
114         let ccx = bcx.ccx();
115         let glue = get_drop_glue(ccx, t);
116         let glue_type = get_drop_glue_type(ccx, t);
117         let ptr = if glue_type != t {
118             PointerCast(bcx, v, type_of(ccx, glue_type).ptr_to())
119         } else {
120             v
121         };
122
123         match source_location {
124             Some(sl) => debuginfo::set_source_location(bcx.fcx, sl.id, sl.span),
125             None => debuginfo::clear_source_location(bcx.fcx)
126         };
127
128         Call(bcx, glue, &[ptr], None);
129     }
130     bcx
131 }
132
133 pub fn drop_ty_immediate<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
134                                      v: ValueRef,
135                                      t: Ty<'tcx>,
136                                      source_location: Option<NodeInfo>)
137                                      -> Block<'blk, 'tcx> {
138     let _icx = push_ctxt("drop_ty_immediate");
139     let vp = alloca(bcx, type_of(bcx.ccx(), t), "");
140     Store(bcx, v, vp);
141     drop_ty(bcx, vp, t, source_location)
142 }
143
144 pub fn get_drop_glue<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> ValueRef {
145     debug!("make drop glue for {}", ppaux::ty_to_string(ccx.tcx(), t));
146     let t = get_drop_glue_type(ccx, t);
147     debug!("drop glue type {}", ppaux::ty_to_string(ccx.tcx(), t));
148     match ccx.drop_glues().borrow().get(&t) {
149         Some(&glue) => return glue,
150         _ => { }
151     }
152
153     let llty = if ty::type_is_sized(ccx.tcx(), t) {
154         type_of(ccx, t).ptr_to()
155     } else {
156         type_of(ccx, ty::mk_uniq(ccx.tcx(), t)).ptr_to()
157     };
158
159     let llfnty = Type::glue_fn(ccx, llty);
160
161     let (glue, new_sym) = match ccx.available_drop_glues().borrow().get(&t) {
162         Some(old_sym) => {
163             let glue = decl_cdecl_fn(ccx, old_sym.as_slice(), llfnty, ty::mk_nil(ccx.tcx()));
164             (glue, None)
165         },
166         None => {
167             let (sym, glue) = declare_generic_glue(ccx, t, llfnty, "drop");
168             (glue, Some(sym))
169         },
170     };
171
172     ccx.drop_glues().borrow_mut().insert(t, glue);
173
174     // To avoid infinite recursion, don't `make_drop_glue` until after we've
175     // added the entry to the `drop_glues` cache.
176     match new_sym {
177         Some(sym) => {
178             ccx.available_drop_glues().borrow_mut().insert(t, sym);
179             // We're creating a new drop glue, so also generate a body.
180             make_generic_glue(ccx, t, glue, make_drop_glue, "drop");
181         },
182         None => {},
183     }
184
185     glue
186 }
187
188 fn trans_struct_drop_flag<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
189                                       t: Ty<'tcx>,
190                                       v0: ValueRef,
191                                       dtor_did: ast::DefId,
192                                       class_did: ast::DefId,
193                                       substs: &subst::Substs<'tcx>)
194                                       -> Block<'blk, 'tcx> {
195     let repr = adt::represent_type(bcx.ccx(), t);
196     let struct_data = if ty::type_is_sized(bcx.tcx(), t) {
197         v0
198     } else {
199         let llval = GEPi(bcx, v0, &[0, abi::FAT_PTR_ADDR]);
200         Load(bcx, llval)
201     };
202     let drop_flag = unpack_datum!(bcx, adt::trans_drop_flag_ptr(bcx, &*repr, struct_data));
203     with_cond(bcx, load_ty(bcx, drop_flag.val, ty::mk_bool()), |cx| {
204         trans_struct_drop(cx, t, v0, dtor_did, class_did, substs)
205     })
206 }
207
208 fn trans_struct_drop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
209                                  t: Ty<'tcx>,
210                                  v0: ValueRef,
211                                  dtor_did: ast::DefId,
212                                  class_did: ast::DefId,
213                                  substs: &subst::Substs<'tcx>)
214                                  -> Block<'blk, 'tcx> {
215     let repr = adt::represent_type(bcx.ccx(), t);
216
217     // Find and call the actual destructor
218     let dtor_addr = get_res_dtor(bcx.ccx(), dtor_did, t,
219                                  class_did, substs);
220
221     // The first argument is the "self" argument for drop
222     let params = unsafe {
223         let ty = Type::from_ref(llvm::LLVMTypeOf(dtor_addr));
224         ty.element_type().func_params()
225     };
226
227     let fty = ty::lookup_item_type(bcx.tcx(), dtor_did).ty.subst(bcx.tcx(), substs);
228     let self_ty = match fty.sty {
229         ty::ty_bare_fn(ref f) => {
230             assert!(f.sig.inputs.len() == 1);
231             f.sig.inputs[0]
232         }
233         _ => bcx.sess().bug(format!("Expected function type, found {}",
234                                     bcx.ty_to_string(fty)).as_slice())
235     };
236
237     let (struct_data, info) = if ty::type_is_sized(bcx.tcx(), t) {
238         (v0, None)
239     } else {
240         let data = GEPi(bcx, v0, &[0, abi::FAT_PTR_ADDR]);
241         let info = GEPi(bcx, v0, &[0, abi::FAT_PTR_EXTRA]);
242         (Load(bcx, data), Some(Load(bcx, info)))
243     };
244
245     adt::fold_variants(bcx, &*repr, struct_data, |variant_cx, st, value| {
246         // Be sure to put all of the fields into a scope so we can use an invoke
247         // instruction to call the user destructor but still call the field
248         // destructors if the user destructor panics.
249         let field_scope = variant_cx.fcx.push_custom_cleanup_scope();
250
251         // Class dtors have no explicit args, so the params should
252         // just consist of the environment (self).
253         assert_eq!(params.len(), 1);
254         let self_arg = if ty::type_is_fat_ptr(bcx.tcx(), self_ty) {
255             // The dtor expects a fat pointer, so make one, even if we have to fake it.
256             let boxed_ty = ty::mk_open(bcx.tcx(), t);
257             let scratch = datum::rvalue_scratch_datum(bcx, boxed_ty, "__fat_ptr_drop_self");
258             Store(bcx, value, GEPi(bcx, scratch.val, &[0, abi::FAT_PTR_ADDR]));
259             Store(bcx,
260                   // If we just had a thin pointer, make a fat pointer by sticking
261                   // null where we put the unsizing info. This works because t
262                   // is a sized type, so we will only unpack the fat pointer, never
263                   // use the fake info.
264                   info.unwrap_or(C_null(Type::i8p(bcx.ccx()))),
265                   GEPi(bcx, scratch.val, &[0, abi::FAT_PTR_EXTRA]));
266             PointerCast(variant_cx, scratch.val, params[0])
267         } else {
268             PointerCast(variant_cx, value, params[0])
269         };
270         let args = vec!(self_arg);
271
272         // Add all the fields as a value which needs to be cleaned at the end of
273         // this scope. Iterate in reverse order so a Drop impl doesn't reverse
274         // the order in which fields get dropped.
275         for (i, ty) in st.fields.iter().enumerate().rev() {
276             let llfld_a = adt::struct_field_ptr(variant_cx, &*st, value, i, false);
277
278             let val = if ty::type_is_sized(bcx.tcx(), *ty) {
279                 llfld_a
280             } else {
281                 let boxed_ty = ty::mk_open(bcx.tcx(), *ty);
282                 let scratch = datum::rvalue_scratch_datum(bcx, boxed_ty, "__fat_ptr_drop_field");
283                 Store(bcx, llfld_a, GEPi(bcx, scratch.val, &[0, abi::FAT_PTR_ADDR]));
284                 Store(bcx, info.unwrap(), GEPi(bcx, scratch.val, &[0, abi::FAT_PTR_EXTRA]));
285                 scratch.val
286             };
287             variant_cx.fcx.schedule_drop_mem(cleanup::CustomScope(field_scope),
288                                              val, *ty);
289         }
290
291         let dtor_ty = ty::mk_ctor_fn(bcx.tcx(),
292                                      &[get_drop_glue_type(bcx.ccx(), t)],
293                                      ty::mk_nil(bcx.tcx()));
294         let (_, variant_cx) = invoke(variant_cx, dtor_addr, args[], dtor_ty, None, false);
295
296         variant_cx.fcx.pop_and_trans_custom_cleanup_scope(variant_cx, field_scope);
297         variant_cx
298     })
299 }
300
301 fn size_and_align_of_dst<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, t: Ty<'tcx>, info: ValueRef)
302                                      -> (ValueRef, ValueRef) {
303     debug!("calculate size of DST: {}; with lost info: {}",
304            bcx.ty_to_string(t), bcx.val_to_string(info));
305     if ty::type_is_sized(bcx.tcx(), t) {
306         let sizing_type = sizing_type_of(bcx.ccx(), t);
307         let size = C_uint(bcx.ccx(), llsize_of_alloc(bcx.ccx(), sizing_type));
308         let align = C_uint(bcx.ccx(), align_of(bcx.ccx(), t));
309         return (size, align);
310     }
311     match t.sty {
312         ty::ty_struct(id, ref substs) => {
313             let ccx = bcx.ccx();
314             // First get the size of all statically known fields.
315             // Don't use type_of::sizing_type_of because that expects t to be sized.
316             assert!(!ty::type_is_simd(bcx.tcx(), t));
317             let repr = adt::represent_type(ccx, t);
318             let sizing_type = adt::sizing_type_of(ccx, &*repr, true);
319             let sized_size = C_uint(ccx, llsize_of_alloc(ccx, sizing_type));
320             let sized_align = C_uint(ccx, llalign_of_min(ccx, sizing_type));
321
322             // Recurse to get the size of the dynamically sized field (must be
323             // the last field).
324             let fields = ty::struct_fields(bcx.tcx(), id, substs);
325             let last_field = fields[fields.len()-1];
326             let field_ty = last_field.mt.ty;
327             let (unsized_size, unsized_align) = size_and_align_of_dst(bcx, field_ty, info);
328
329             // Return the sum of sizes and max of aligns.
330             let size = Add(bcx, sized_size, unsized_size);
331             let align = Select(bcx,
332                                ICmp(bcx, llvm::IntULT, sized_align, unsized_align),
333                                sized_align,
334                                unsized_align);
335             (size, align)
336         }
337         ty::ty_trait(..) => {
338             // info points to the vtable and the second entry in the vtable is the
339             // dynamic size of the object.
340             let info = PointerCast(bcx, info, Type::int(bcx.ccx()).ptr_to());
341             let size_ptr = GEPi(bcx, info, &[1u]);
342             let align_ptr = GEPi(bcx, info, &[2u]);
343             (Load(bcx, size_ptr), Load(bcx, align_ptr))
344         }
345         ty::ty_vec(unit_ty, None) => {
346             // The info in this case is the length of the vec, so the size is that
347             // times the unit size.
348             let llunit_ty = sizing_type_of(bcx.ccx(), unit_ty);
349             let unit_size = llsize_of_alloc(bcx.ccx(), llunit_ty);
350             (Mul(bcx, info, C_uint(bcx.ccx(), unit_size)), C_uint(bcx.ccx(), 8u))
351         }
352         _ => bcx.sess().bug(format!("Unexpected unsized type, found {}",
353                                     bcx.ty_to_string(t)).as_slice())
354     }
355 }
356
357 fn make_drop_glue<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, v0: ValueRef, t: Ty<'tcx>)
358                               -> Block<'blk, 'tcx> {
359     // NB: v0 is an *alias* of type t here, not a direct value.
360     let _icx = push_ctxt("make_drop_glue");
361     match t.sty {
362         ty::ty_uniq(content_ty) => {
363             match content_ty.sty {
364                 ty::ty_vec(ty, None) => {
365                     tvec::make_drop_glue_unboxed(bcx, v0, ty, true)
366                 }
367                 ty::ty_str => {
368                     let unit_ty = ty::sequence_element_type(bcx.tcx(), content_ty);
369                     tvec::make_drop_glue_unboxed(bcx, v0, unit_ty, true)
370                 }
371                 ty::ty_trait(..) => {
372                     let lluniquevalue = GEPi(bcx, v0, &[0, abi::FAT_PTR_ADDR]);
373                     // Only drop the value when it is non-null
374                     let concrete_ptr = Load(bcx, lluniquevalue);
375                     with_cond(bcx, IsNotNull(bcx, concrete_ptr), |bcx| {
376                         let dtor_ptr = Load(bcx, GEPi(bcx, v0, &[0, abi::FAT_PTR_EXTRA]));
377                         let dtor = Load(bcx, dtor_ptr);
378                         Call(bcx,
379                              dtor,
380                              &[PointerCast(bcx, lluniquevalue, Type::i8p(bcx.ccx()))],
381                              None);
382                         bcx
383                     })
384                 }
385                 ty::ty_struct(..) if !ty::type_is_sized(bcx.tcx(), content_ty) => {
386                     let llval = GEPi(bcx, v0, &[0, abi::FAT_PTR_ADDR]);
387                     let llbox = Load(bcx, llval);
388                     let not_null = IsNotNull(bcx, llbox);
389                     with_cond(bcx, not_null, |bcx| {
390                         let bcx = drop_ty(bcx, v0, content_ty, None);
391                         let info = GEPi(bcx, v0, &[0, abi::FAT_PTR_EXTRA]);
392                         let info = Load(bcx, info);
393                         let (llsize, llalign) = size_and_align_of_dst(bcx, content_ty, info);
394                         trans_exchange_free_dyn(bcx, llbox, llsize, llalign)
395                     })
396                 }
397                 _ => {
398                     assert!(ty::type_is_sized(bcx.tcx(), content_ty));
399                     let llval = v0;
400                     let llbox = Load(bcx, llval);
401                     let not_null = IsNotNull(bcx, llbox);
402                     with_cond(bcx, not_null, |bcx| {
403                         let bcx = drop_ty(bcx, llbox, content_ty, None);
404                         trans_exchange_free_ty(bcx, llbox, content_ty)
405                     })
406                 }
407             }
408         }
409         ty::ty_struct(did, ref substs) | ty::ty_enum(did, ref substs) => {
410             let tcx = bcx.tcx();
411             match ty::ty_dtor(tcx, did) {
412                 ty::TraitDtor(dtor, true) => {
413                     // FIXME(16758) Since the struct is unsized, it is hard to
414                     // find the drop flag (which is at the end of the struct).
415                     // Lets just ignore the flag and pretend everything will be
416                     // OK.
417                     if ty::type_is_sized(bcx.tcx(), t) {
418                         trans_struct_drop_flag(bcx, t, v0, dtor, did, substs)
419                     } else {
420                         // Give the user a heads up that we are doing something
421                         // stupid and dangerous.
422                         bcx.sess().warn(format!("Ignoring drop flag in destructor for {}\
423                                                  because the struct is unsized. See issue\
424                                                  #16758",
425                                                 bcx.ty_to_string(t)).as_slice());
426                         trans_struct_drop(bcx, t, v0, dtor, did, substs)
427                     }
428                 }
429                 ty::TraitDtor(dtor, false) => {
430                     trans_struct_drop(bcx, t, v0, dtor, did, substs)
431                 }
432                 ty::NoDtor => {
433                     // No dtor? Just the default case
434                     iter_structural_ty(bcx, v0, t, |bb, vv, tt| drop_ty(bb, vv, tt, None))
435                 }
436             }
437         }
438         ty::ty_unboxed_closure(..) => iter_structural_ty(bcx,
439                                                          v0,
440                                                          t,
441                                                          |bb, vv, tt| drop_ty(bb, vv, tt, None)),
442         ty::ty_closure(ref f) if f.store == ty::UniqTraitStore => {
443             let box_cell_v = GEPi(bcx, v0, &[0u, abi::FAT_PTR_EXTRA]);
444             let env = Load(bcx, box_cell_v);
445             let env_ptr_ty = Type::at_box(bcx.ccx(), Type::i8(bcx.ccx())).ptr_to();
446             let env = PointerCast(bcx, env, env_ptr_ty);
447             with_cond(bcx, IsNotNull(bcx, env), |bcx| {
448                 let dtor_ptr = GEPi(bcx, env, &[0u, abi::BOX_FIELD_DROP_GLUE]);
449                 let dtor = Load(bcx, dtor_ptr);
450                 Call(bcx, dtor, &[PointerCast(bcx, box_cell_v, Type::i8p(bcx.ccx()))], None);
451                 bcx
452             })
453         }
454         ty::ty_trait(..) => {
455             // No need to do a null check here (as opposed to the Box<trait case
456             // above), because this happens for a trait field in an unsized
457             // struct. If anything is null, it is the whole struct and we won't
458             // get here.
459             let lluniquevalue = GEPi(bcx, v0, &[0, abi::FAT_PTR_ADDR]);
460             let dtor_ptr = Load(bcx, GEPi(bcx, v0, &[0, abi::FAT_PTR_EXTRA]));
461             let dtor = Load(bcx, dtor_ptr);
462             Call(bcx,
463                  dtor,
464                  &[PointerCast(bcx, Load(bcx, lluniquevalue), Type::i8p(bcx.ccx()))],
465                  None);
466             bcx
467         }
468         ty::ty_vec(ty, None) => tvec::make_drop_glue_unboxed(bcx, v0, ty, false),
469         _ => {
470             assert!(ty::type_is_sized(bcx.tcx(), t));
471             if ty::type_needs_drop(bcx.tcx(), t) &&
472                 ty::type_is_structural(t) {
473                 iter_structural_ty(bcx, v0, t, |bb, vv, tt| drop_ty(bb, vv, tt, None))
474             } else {
475                 bcx
476             }
477         }
478     }
479 }
480
481 // Generates the declaration for (but doesn't emit) a type descriptor.
482 pub fn declare_tydesc<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>)
483                                 -> tydesc_info<'tcx> {
484     // If emit_tydescs already ran, then we shouldn't be creating any new
485     // tydescs.
486     assert!(!ccx.finished_tydescs().get());
487
488     let llty = type_of(ccx, t);
489
490     if ccx.sess().count_type_sizes() {
491         println!("{}\t{}", llsize_of_real(ccx, llty),
492                  ppaux::ty_to_string(ccx.tcx(), t));
493     }
494
495     let llsize = llsize_of(ccx, llty);
496     let llalign = llalign_of(ccx, llty);
497     let name = mangle_internal_name_by_type_and_seq(ccx, t, "tydesc");
498     debug!("+++ declare_tydesc {} {}", ppaux::ty_to_string(ccx.tcx(), t), name);
499     let gvar = name.with_c_str(|buf| {
500         unsafe {
501             llvm::LLVMAddGlobal(ccx.llmod(), ccx.tydesc_type().to_ref(), buf)
502         }
503     });
504     note_unique_llvm_symbol(ccx, name);
505
506     let ty_name = token::intern_and_get_ident(
507         ppaux::ty_to_string(ccx.tcx(), t).as_slice());
508     let ty_name = C_str_slice(ccx, ty_name);
509
510     debug!("--- declare_tydesc {}", ppaux::ty_to_string(ccx.tcx(), t));
511     tydesc_info {
512         ty: t,
513         tydesc: gvar,
514         size: llsize,
515         align: llalign,
516         name: ty_name,
517     }
518 }
519
520 fn declare_generic_glue<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>,
521                                   llfnty: Type, name: &str) -> (String, ValueRef) {
522     let _icx = push_ctxt("declare_generic_glue");
523     let fn_nm = mangle_internal_name_by_type_and_seq(
524         ccx,
525         t,
526         format!("glue_{}", name).as_slice());
527     let llfn = decl_cdecl_fn(ccx, fn_nm.as_slice(), llfnty, ty::mk_nil(ccx.tcx()));
528     note_unique_llvm_symbol(ccx, fn_nm.clone());
529     return (fn_nm, llfn);
530 }
531
532 fn make_generic_glue<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
533                                t: Ty<'tcx>,
534                                llfn: ValueRef,
535                                helper: for<'blk> |Block<'blk, 'tcx>, ValueRef, Ty<'tcx>|
536                                                   -> Block<'blk, 'tcx>,
537                                name: &str)
538                                -> ValueRef {
539     let _icx = push_ctxt("make_generic_glue");
540     let glue_name = format!("glue {} {}", name, ty_to_short_str(ccx.tcx(), t));
541     let _s = StatRecorder::new(ccx, glue_name);
542
543     let arena = TypedArena::new();
544     let empty_param_substs = Substs::trans_empty();
545     let fcx = new_fn_ctxt(ccx, llfn, ast::DUMMY_NODE_ID, false,
546                           ty::FnConverging(ty::mk_nil(ccx.tcx())),
547                           &empty_param_substs, None, &arena);
548
549     let bcx = init_function(&fcx, false, ty::FnConverging(ty::mk_nil(ccx.tcx())));
550
551     update_linkage(ccx, llfn, None, OriginalTranslation);
552
553     ccx.stats().n_glues_created.set(ccx.stats().n_glues_created.get() + 1u);
554     // All glue functions take values passed *by alias*; this is a
555     // requirement since in many contexts glue is invoked indirectly and
556     // the caller has no idea if it's dealing with something that can be
557     // passed by value.
558     //
559     // llfn is expected be declared to take a parameter of the appropriate
560     // type, so we don't need to explicitly cast the function parameter.
561
562     let llrawptr0 = get_param(llfn, fcx.arg_pos(0) as c_uint);
563     let bcx = helper(bcx, llrawptr0, t);
564     finish_fn(&fcx, bcx, ty::FnConverging(ty::mk_nil(ccx.tcx())));
565
566     llfn
567 }
568
569 pub fn emit_tydescs(ccx: &CrateContext) {
570     let _icx = push_ctxt("emit_tydescs");
571     // As of this point, allow no more tydescs to be created.
572     ccx.finished_tydescs().set(true);
573     let glue_fn_ty = Type::generic_glue_fn(ccx).ptr_to();
574     for (_, ti) in ccx.tydescs().borrow().iter() {
575         // Each of the glue functions needs to be cast to a generic type
576         // before being put into the tydesc because we only have a singleton
577         // tydesc type. Then we'll recast each function to its real type when
578         // calling it.
579         let drop_glue = unsafe {
580             llvm::LLVMConstPointerCast(get_drop_glue(ccx, ti.ty), glue_fn_ty.to_ref())
581         };
582         ccx.stats().n_real_glues.set(ccx.stats().n_real_glues.get() + 1);
583
584         let tydesc = C_named_struct(ccx.tydesc_type(),
585                                     &[ti.size, // size
586                                       ti.align, // align
587                                       drop_glue, // drop_glue
588                                       ti.name]); // name
589
590         unsafe {
591             let gvar = ti.tydesc;
592             llvm::LLVMSetInitializer(gvar, tydesc);
593             llvm::LLVMSetGlobalConstant(gvar, True);
594             llvm::SetLinkage(gvar, llvm::InternalLinkage);
595         }
596     };
597 }