]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/glue.rs
auto merge of #13967 : richo/rust/features/ICE-fails, r=alexcrichton
[rust.git] / src / librustc / middle / 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 lib::llvm::{llvm, ValueRef, True};
19 use lib;
20 use middle::lang_items::{FreeFnLangItem, ExchangeFreeFnLangItem};
21 use middle::trans::adt;
22 use middle::trans::base::*;
23 use middle::trans::build::*;
24 use middle::trans::callee;
25 use middle::trans::cleanup;
26 use middle::trans::cleanup::CleanupMethods;
27 use middle::trans::common::*;
28 use middle::trans::expr;
29 use middle::trans::machine::*;
30 use middle::trans::reflect;
31 use middle::trans::tvec;
32 use middle::trans::type_::Type;
33 use middle::trans::type_of::{type_of, sizing_type_of};
34 use middle::ty;
35 use util::ppaux::ty_to_short_str;
36 use util::ppaux;
37
38 use arena::TypedArena;
39 use std::c_str::ToCStr;
40 use std::cell::Cell;
41 use libc::c_uint;
42 use syntax::ast;
43 use syntax::parse::token;
44
45 pub fn trans_free<'a>(cx: &'a Block<'a>, v: ValueRef) -> &'a Block<'a> {
46     let _icx = push_ctxt("trans_free");
47     callee::trans_lang_call(cx,
48         langcall(cx, None, "", FreeFnLangItem),
49         [PointerCast(cx, v, Type::i8p(cx.ccx()))],
50         Some(expr::Ignore)).bcx
51 }
52
53 pub fn trans_exchange_free<'a>(cx: &'a Block<'a>, v: ValueRef)
54                            -> &'a Block<'a> {
55     let _icx = push_ctxt("trans_exchange_free");
56     callee::trans_lang_call(cx,
57         langcall(cx, None, "", ExchangeFreeFnLangItem),
58         [PointerCast(cx, v, Type::i8p(cx.ccx()))],
59         Some(expr::Ignore)).bcx
60 }
61
62 pub fn take_ty<'a>(bcx: &'a Block<'a>, v: ValueRef, t: ty::t)
63                -> &'a Block<'a> {
64     // NB: v is an *alias* of type t here, not a direct value.
65     let _icx = push_ctxt("take_ty");
66     match ty::get(t).sty {
67         ty::ty_box(_) => incr_refcnt_of_boxed(bcx, v),
68         _ if ty::type_is_structural(t)
69           && ty::type_needs_drop(bcx.tcx(), t) => {
70             iter_structural_ty(bcx, v, t, take_ty)
71         }
72         _ => bcx
73     }
74 }
75
76 fn get_drop_glue_type(ccx: &CrateContext, t: ty::t) -> ty::t {
77     let tcx = ccx.tcx();
78     if !ty::type_needs_drop(tcx, t) {
79         return ty::mk_i8();
80     }
81     match ty::get(t).sty {
82         ty::ty_box(typ) if !ty::type_needs_drop(tcx, typ) =>
83             ty::mk_box(tcx, ty::mk_i8()),
84
85         ty::ty_uniq(typ) if !ty::type_needs_drop(tcx, typ) => {
86             match ty::get(typ).sty {
87                 ty::ty_vec(_, None) | ty::ty_str => t,
88                 _ => {
89                     let llty = sizing_type_of(ccx, typ);
90                     // Unique boxes do not allocate for zero-size types. The standard
91                     // library may assume that `free` is never called on the pointer
92                     // returned for `Box<ZeroSizeType>`.
93                     if llsize_of_alloc(ccx, llty) == 0 {
94                         ty::mk_i8()
95                     } else {
96                         ty::mk_uniq(tcx, ty::mk_i8())
97                     }
98                         }
99                     }
100                 }
101         _ => t
102     }
103 }
104
105 pub fn drop_ty<'a>(bcx: &'a Block<'a>, v: ValueRef, t: ty::t)
106                -> &'a Block<'a> {
107     // NB: v is an *alias* of type t here, not a direct value.
108     let _icx = push_ctxt("drop_ty");
109     let ccx = bcx.ccx();
110     if ty::type_needs_drop(bcx.tcx(), t) {
111         let glue = get_drop_glue(ccx, t);
112         let glue_type = get_drop_glue_type(ccx, t);
113         let ptr = if glue_type != t {
114             PointerCast(bcx, v, type_of(ccx, glue_type).ptr_to())
115         } else {
116             v
117         };
118         Call(bcx, glue, [ptr], []);
119     }
120     bcx
121 }
122
123 pub fn drop_ty_immediate<'a>(bcx: &'a Block<'a>, v: ValueRef, t: ty::t)
124                          -> &'a Block<'a> {
125     let _icx = push_ctxt("drop_ty_immediate");
126     let vp = alloca(bcx, type_of(bcx.ccx(), t), "");
127     Store(bcx, v, vp);
128     drop_ty(bcx, vp, t)
129 }
130
131 pub fn get_drop_glue(ccx: &CrateContext, t: ty::t) -> ValueRef {
132     let t = get_drop_glue_type(ccx, t);
133     match ccx.drop_glues.borrow().find(&t) {
134         Some(&glue) => return glue,
135         _ => { }
136     }
137
138     let llfnty = Type::glue_fn(ccx, type_of(ccx, t).ptr_to());
139     let glue = declare_generic_glue(ccx, t, llfnty, "drop");
140
141     ccx.drop_glues.borrow_mut().insert(t, glue);
142
143     make_generic_glue(ccx, t, glue, make_drop_glue, "drop");
144
145     glue
146 }
147
148 pub fn lazily_emit_visit_glue(ccx: &CrateContext, ti: &tydesc_info) -> ValueRef {
149     let _icx = push_ctxt("lazily_emit_visit_glue");
150
151     let llfnty = Type::glue_fn(ccx, type_of(ccx, ti.ty).ptr_to());
152
153     match ti.visit_glue.get() {
154         Some(visit_glue) => visit_glue,
155         None => {
156             debug!("+++ lazily_emit_tydesc_glue VISIT {}", ppaux::ty_to_str(ccx.tcx(), ti.ty));
157             let glue_fn = declare_generic_glue(ccx, ti.ty, llfnty, "visit");
158             ti.visit_glue.set(Some(glue_fn));
159             make_generic_glue(ccx, ti.ty, glue_fn, make_visit_glue, "visit");
160             debug!("--- lazily_emit_tydesc_glue VISIT {}", ppaux::ty_to_str(ccx.tcx(), ti.ty));
161             glue_fn
162         }
163     }
164 }
165
166 // See [Note-arg-mode]
167 pub fn call_visit_glue(bcx: &Block, v: ValueRef, tydesc: ValueRef,
168                        static_ti: Option<&tydesc_info>) {
169     let _icx = push_ctxt("call_tydesc_glue_full");
170     let ccx = bcx.ccx();
171     // NB: Don't short-circuit even if this block is unreachable because
172     // GC-based cleanup needs to the see that the roots are live.
173     if bcx.unreachable.get() && !ccx.sess().no_landing_pads() { return; }
174
175     let static_glue_fn = static_ti.map(|sti| lazily_emit_visit_glue(ccx, sti));
176
177     // When static type info is available, avoid casting to a generic pointer.
178     let llrawptr = if static_glue_fn.is_none() {
179         PointerCast(bcx, v, Type::i8p(ccx))
180     } else {
181         v
182     };
183
184     let llfn = {
185         match static_glue_fn {
186             None => {
187                 // Select out the glue function to call from the tydesc
188                 let llfnptr = GEPi(bcx, tydesc, [0u, abi::tydesc_field_visit_glue]);
189                 Load(bcx, llfnptr)
190             }
191             Some(sgf) => sgf
192         }
193     };
194
195     Call(bcx, llfn, [llrawptr], []);
196 }
197
198 fn make_visit_glue<'a>(bcx: &'a Block<'a>, v: ValueRef, t: ty::t)
199                    -> &'a Block<'a> {
200     let _icx = push_ctxt("make_visit_glue");
201     let mut bcx = bcx;
202     let (visitor_trait, object_ty) = match ty::visitor_object_ty(bcx.tcx(),
203                                                                  ty::ReStatic) {
204         Ok(pair) => pair,
205         Err(s) => {
206             bcx.tcx().sess.fatal(s);
207         }
208     };
209     let v = PointerCast(bcx, v, type_of(bcx.ccx(), object_ty).ptr_to());
210     bcx = reflect::emit_calls_to_trait_visit_ty(bcx, t, v, visitor_trait.def_id);
211     bcx
212 }
213
214 fn trans_struct_drop_flag<'a>(bcx: &'a Block<'a>,
215                               t: ty::t,
216                               v0: ValueRef,
217                               dtor_did: ast::DefId,
218                               class_did: ast::DefId,
219                               substs: &ty::substs)
220                               -> &'a Block<'a> {
221     let repr = adt::represent_type(bcx.ccx(), t);
222     let drop_flag = adt::trans_drop_flag_ptr(bcx, &*repr, v0);
223     with_cond(bcx, IsNotNull(bcx, Load(bcx, drop_flag)), |cx| {
224         trans_struct_drop(cx, t, v0, dtor_did, class_did, substs)
225     })
226 }
227
228 fn trans_struct_drop<'a>(bcx: &'a Block<'a>,
229                          t: ty::t,
230                          v0: ValueRef,
231                          dtor_did: ast::DefId,
232                          class_did: ast::DefId,
233                          substs: &ty::substs)
234                          -> &'a Block<'a> {
235     let repr = adt::represent_type(bcx.ccx(), t);
236
237     // Find and call the actual destructor
238     let dtor_addr = get_res_dtor(bcx.ccx(), dtor_did,
239                                  class_did, substs.tps.as_slice());
240
241     // The second argument is the "self" argument for drop
242     let params = unsafe {
243         let ty = Type::from_ref(llvm::LLVMTypeOf(dtor_addr));
244         ty.element_type().func_params()
245     };
246
247     // Class dtors have no explicit args, so the params should
248     // just consist of the environment (self)
249     assert_eq!(params.len(), 1);
250
251     // Be sure to put all of the fields into a scope so we can use an invoke
252     // instruction to call the user destructor but still call the field
253     // destructors if the user destructor fails.
254     let field_scope = bcx.fcx.push_custom_cleanup_scope();
255
256     let self_arg = PointerCast(bcx, v0, *params.get(0));
257     let args = vec!(self_arg);
258
259     // Add all the fields as a value which needs to be cleaned at the end of
260     // this scope.
261     let field_tys = ty::struct_fields(bcx.tcx(), class_did, substs);
262     for (i, fld) in field_tys.iter().enumerate() {
263         let llfld_a = adt::trans_field_ptr(bcx, &*repr, v0, 0, i);
264         bcx.fcx.schedule_drop_mem(cleanup::CustomScope(field_scope),
265                                   llfld_a,
266                                   fld.mt.ty);
267     }
268
269     let (_, bcx) = invoke(bcx, dtor_addr, args, [], None);
270
271     bcx.fcx.pop_and_trans_custom_cleanup_scope(bcx, field_scope)
272 }
273
274 fn make_drop_glue<'a>(bcx: &'a Block<'a>, v0: ValueRef, t: ty::t) -> &'a Block<'a> {
275     // NB: v0 is an *alias* of type t here, not a direct value.
276     let _icx = push_ctxt("make_drop_glue");
277     match ty::get(t).sty {
278         ty::ty_box(body_ty) => {
279             decr_refcnt_maybe_free(bcx, v0, body_ty)
280         }
281         ty::ty_uniq(content_ty) => {
282             let llbox = Load(bcx, v0);
283             let not_null = IsNotNull(bcx, llbox);
284             match ty::get(content_ty).sty {
285                 ty::ty_vec(mt, None) => {
286                     with_cond(bcx, not_null, |bcx| {
287                         let bcx = tvec::make_drop_glue_unboxed(bcx, llbox, mt.ty);
288                         trans_exchange_free(bcx, llbox)
289                     })
290                 }
291                 ty::ty_str => {
292                     with_cond(bcx, not_null, |bcx| {
293                         let unit_ty = ty::sequence_element_type(bcx.tcx(), t);
294                         let bcx = tvec::make_drop_glue_unboxed(bcx, llbox, unit_ty);
295                         trans_exchange_free(bcx, llbox)
296                     })
297                 }
298                 _ => {
299                     with_cond(bcx, not_null, |bcx| {
300                         let bcx = drop_ty(bcx, llbox, content_ty);
301                         trans_exchange_free(bcx, llbox)
302                     })
303                 }
304             }
305         }
306         ty::ty_struct(did, ref substs) => {
307             let tcx = bcx.tcx();
308             match ty::ty_dtor(tcx, did) {
309                 ty::TraitDtor(dtor, true) => {
310                     trans_struct_drop_flag(bcx, t, v0, dtor, did, substs)
311                 }
312                 ty::TraitDtor(dtor, false) => {
313                     trans_struct_drop(bcx, t, v0, dtor, did, substs)
314                 }
315                 ty::NoDtor => {
316                     // No dtor? Just the default case
317                     iter_structural_ty(bcx, v0, t, drop_ty)
318                 }
319             }
320         }
321         ty::ty_trait(box ty::TyTrait { store: ty::UniqTraitStore, .. }) => {
322             let lluniquevalue = GEPi(bcx, v0, [0, abi::trt_field_box]);
323             // Only drop the value when it is non-null
324             with_cond(bcx, IsNotNull(bcx, Load(bcx, lluniquevalue)), |bcx| {
325                 let dtor_ptr = Load(bcx, GEPi(bcx, v0, [0, abi::trt_field_vtable]));
326                 let dtor = Load(bcx, dtor_ptr);
327                 Call(bcx, dtor, [PointerCast(bcx, lluniquevalue, Type::i8p(bcx.ccx()))], []);
328                 bcx
329             })
330         }
331         ty::ty_closure(ref f) if f.store == ty::UniqTraitStore => {
332             let box_cell_v = GEPi(bcx, v0, [0u, abi::fn_field_box]);
333             let env = Load(bcx, box_cell_v);
334             let env_ptr_ty = Type::at_box(bcx.ccx(), Type::i8(bcx.ccx())).ptr_to();
335             let env = PointerCast(bcx, env, env_ptr_ty);
336             with_cond(bcx, IsNotNull(bcx, env), |bcx| {
337                 let dtor_ptr = GEPi(bcx, env, [0u, abi::box_field_tydesc]);
338                 let dtor = Load(bcx, dtor_ptr);
339                 let cdata = GEPi(bcx, env, [0u, abi::box_field_body]);
340                 Call(bcx, dtor, [PointerCast(bcx, cdata, Type::i8p(bcx.ccx()))], []);
341
342                 // Free the environment itself
343                 trans_exchange_free(bcx, env)
344             })
345         }
346         _ => {
347             if ty::type_needs_drop(bcx.tcx(), t) &&
348                 ty::type_is_structural(t) {
349                 iter_structural_ty(bcx, v0, t, drop_ty)
350             } else {
351                 bcx
352             }
353         }
354     }
355 }
356
357 fn decr_refcnt_maybe_free<'a>(bcx: &'a Block<'a>,
358                               box_ptr_ptr: ValueRef,
359                               t: ty::t) -> &'a Block<'a> {
360     let _icx = push_ctxt("decr_refcnt_maybe_free");
361     let fcx = bcx.fcx;
362     let ccx = bcx.ccx();
363
364     let decr_bcx = fcx.new_temp_block("decr");
365     let free_bcx = fcx.new_temp_block("free");
366     let next_bcx = fcx.new_temp_block("next");
367
368     let box_ptr = Load(bcx, box_ptr_ptr);
369     let llnotnull = IsNotNull(bcx, box_ptr);
370     CondBr(bcx, llnotnull, decr_bcx.llbb, next_bcx.llbb);
371
372     let rc_ptr = GEPi(decr_bcx, box_ptr, [0u, abi::box_field_refcnt]);
373     let rc = Sub(decr_bcx, Load(decr_bcx, rc_ptr), C_int(ccx, 1));
374     Store(decr_bcx, rc, rc_ptr);
375     CondBr(decr_bcx, IsNull(decr_bcx, rc), free_bcx.llbb, next_bcx.llbb);
376
377     let v = Load(free_bcx, box_ptr_ptr);
378     let body = GEPi(free_bcx, v, [0u, abi::box_field_body]);
379     let free_bcx = drop_ty(free_bcx, body, t);
380     let free_bcx = trans_free(free_bcx, v);
381     Br(free_bcx, next_bcx.llbb);
382
383     next_bcx
384 }
385
386 fn incr_refcnt_of_boxed<'a>(bcx: &'a Block<'a>,
387                             box_ptr_ptr: ValueRef) -> &'a Block<'a> {
388     let _icx = push_ctxt("incr_refcnt_of_boxed");
389     let ccx = bcx.ccx();
390     let box_ptr = Load(bcx, box_ptr_ptr);
391     let rc_ptr = GEPi(bcx, box_ptr, [0u, abi::box_field_refcnt]);
392     let rc = Load(bcx, rc_ptr);
393     let rc = Add(bcx, rc, C_int(ccx, 1));
394     Store(bcx, rc, rc_ptr);
395     bcx
396 }
397
398
399 // Generates the declaration for (but doesn't emit) a type descriptor.
400 pub fn declare_tydesc(ccx: &CrateContext, t: ty::t) -> tydesc_info {
401     // If emit_tydescs already ran, then we shouldn't be creating any new
402     // tydescs.
403     assert!(!ccx.finished_tydescs.get());
404
405     let llty = type_of(ccx, t);
406
407     if ccx.sess().count_type_sizes() {
408         println!("{}\t{}", llsize_of_real(ccx, llty),
409                  ppaux::ty_to_str(ccx.tcx(), t));
410     }
411
412     let llsize = llsize_of(ccx, llty);
413     let llalign = llalign_of(ccx, llty);
414     let name = mangle_internal_name_by_type_and_seq(ccx, t, "tydesc");
415     debug!("+++ declare_tydesc {} {}", ppaux::ty_to_str(ccx.tcx(), t), name);
416     let gvar = name.with_c_str(|buf| {
417         unsafe {
418             llvm::LLVMAddGlobal(ccx.llmod, ccx.tydesc_type().to_ref(), buf)
419         }
420     });
421     note_unique_llvm_symbol(ccx, name);
422
423     let ty_name = token::intern_and_get_ident(ppaux::ty_to_str(ccx.tcx(), t));
424     let ty_name = C_str_slice(ccx, ty_name);
425
426     debug!("--- declare_tydesc {}", ppaux::ty_to_str(ccx.tcx(), t));
427     tydesc_info {
428         ty: t,
429         tydesc: gvar,
430         size: llsize,
431         align: llalign,
432         name: ty_name,
433         visit_glue: Cell::new(None),
434     }
435 }
436
437 fn declare_generic_glue(ccx: &CrateContext, t: ty::t, llfnty: Type,
438                         name: &str) -> ValueRef {
439     let _icx = push_ctxt("declare_generic_glue");
440     let fn_nm = mangle_internal_name_by_type_and_seq(ccx, t, "glue_".to_owned() + name);
441     debug!("{} is for type {}", fn_nm, ppaux::ty_to_str(ccx.tcx(), t));
442     let llfn = decl_cdecl_fn(ccx.llmod, fn_nm, llfnty, ty::mk_nil());
443     note_unique_llvm_symbol(ccx, fn_nm);
444     return llfn;
445 }
446
447 fn make_generic_glue(ccx: &CrateContext,
448                      t: ty::t,
449                      llfn: ValueRef,
450                      helper: <'a> |&'a Block<'a>, ValueRef, ty::t|
451                                   -> &'a Block<'a>,
452                      name: &str)
453                      -> ValueRef {
454     let _icx = push_ctxt("make_generic_glue");
455     let glue_name = format!("glue {} {}", name, ty_to_short_str(ccx.tcx(), t));
456     let _s = StatRecorder::new(ccx, glue_name);
457
458     let arena = TypedArena::new();
459     let fcx = new_fn_ctxt(ccx, llfn, -1, false, ty::mk_nil(), None, None, &arena);
460
461     init_function(&fcx, false, ty::mk_nil());
462
463     lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
464     ccx.stats.n_glues_created.set(ccx.stats.n_glues_created.get() + 1u);
465     // All glue functions take values passed *by alias*; this is a
466     // requirement since in many contexts glue is invoked indirectly and
467     // the caller has no idea if it's dealing with something that can be
468     // passed by value.
469     //
470     // llfn is expected be declared to take a parameter of the appropriate
471     // type, so we don't need to explicitly cast the function parameter.
472
473     let bcx = fcx.entry_bcx.borrow().clone().unwrap();
474     let llrawptr0 = unsafe { llvm::LLVMGetParam(llfn, fcx.arg_pos(0) as c_uint) };
475     let bcx = helper(bcx, llrawptr0, t);
476     finish_fn(&fcx, bcx);
477
478     llfn
479 }
480
481 pub fn emit_tydescs(ccx: &CrateContext) {
482     let _icx = push_ctxt("emit_tydescs");
483     // As of this point, allow no more tydescs to be created.
484     ccx.finished_tydescs.set(true);
485     let glue_fn_ty = Type::generic_glue_fn(ccx).ptr_to();
486     for (_, ti) in ccx.tydescs.borrow().iter() {
487         // Each of the glue functions needs to be cast to a generic type
488         // before being put into the tydesc because we only have a singleton
489         // tydesc type. Then we'll recast each function to its real type when
490         // calling it.
491         let drop_glue = unsafe {
492             llvm::LLVMConstPointerCast(get_drop_glue(ccx, ti.ty), glue_fn_ty.to_ref())
493         };
494         ccx.stats.n_real_glues.set(ccx.stats.n_real_glues.get() + 1);
495         let visit_glue =
496             match ti.visit_glue.get() {
497               None => {
498                   ccx.stats.n_null_glues.set(ccx.stats.n_null_glues.get() +
499                                              1u);
500                   C_null(glue_fn_ty)
501               }
502               Some(v) => {
503                 unsafe {
504                     ccx.stats.n_real_glues.set(ccx.stats.n_real_glues.get() +
505                                                1);
506                     llvm::LLVMConstPointerCast(v, glue_fn_ty.to_ref())
507                 }
508               }
509             };
510
511         let tydesc = C_named_struct(ccx.tydesc_type(),
512                                     [ti.size, // size
513                                      ti.align, // align
514                                      drop_glue, // drop_glue
515                                      visit_glue, // visit_glue
516                                      ti.name]); // name
517
518         unsafe {
519             let gvar = ti.tydesc;
520             llvm::LLVMSetInitializer(gvar, tydesc);
521             llvm::LLVMSetGlobalConstant(gvar, True);
522             lib::llvm::SetLinkage(gvar, lib::llvm::InternalLinkage);
523         }
524     };
525 }