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