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.
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.
13 // Code relating to drop glue.
19 use llvm::{ValueRef, get_param};
20 use middle::lang_items::BoxFreeFnLangItem;
21 use rustc::ty::subst::{Substs};
23 use rustc::ty::{self, layout, AdtDef, AdtKind, Ty, TypeFoldable};
24 use rustc::ty::subst::Kind;
25 use rustc::mir::tcx::LvalueTy;
26 use mir::lvalue::LvalueRef;
30 use cleanup::CleanupScope;
34 use trans_item::TransItem;
36 use type_of::{type_of, sizing_type_of, align_of};
42 use mir::lvalue::Alignment;
44 pub fn trans_exchange_free_ty<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, ptr: LvalueRef<'tcx>) {
45 let content_ty = ptr.ty.to_ty(bcx.tcx());
46 let def_id = langcall(bcx.tcx(), None, "", BoxFreeFnLangItem);
47 let substs = bcx.tcx().mk_substs(iter::once(Kind::from(content_ty)));
48 let callee = Callee::def(bcx.ccx, def_id, substs);
50 let fn_ty = callee.direct_fn_type(bcx.ccx, &[]);
52 let llret = bcx.call(callee.reify(bcx.ccx),
53 &[ptr.llval, ptr.llextra][..1 + ptr.has_extra() as usize], None);
54 fn_ty.apply_attrs_callsite(llret);
57 pub fn get_drop_glue_type<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Ty<'tcx> {
58 assert!(t.is_normalized_for_trans());
60 let t = scx.tcx().erase_regions(&t);
62 // Even if there is no dtor for t, there might be one deeper down and we
63 // might need to pass in the vtable ptr.
64 if !scx.type_is_sized(t) {
68 // FIXME (#22815): note that type_needs_drop conservatively
69 // approximates in some cases and may say a type expression
70 // requires drop glue when it actually does not.
72 // (In this case it is not clear whether any harm is done, i.e.
73 // erroneously returning `t` in some cases where we could have
74 // returned `tcx.types.i8` does not appear unsound. The impact on
75 // code quality is unknown at this time.)
77 if !scx.type_needs_drop(t) {
78 return scx.tcx().types.i8;
81 ty::TyAdt(def, _) if def.is_box() => {
82 let typ = t.boxed_ty();
83 if !scx.type_needs_drop(typ) && scx.type_is_sized(typ) {
84 scx.tcx().infer_ctxt((), traits::Reveal::All).enter(|infcx| {
85 let layout = t.layout(&infcx).unwrap();
86 if layout.size(&scx.tcx().data_layout).bytes() == 0 {
87 // `Box<ZeroSizeType>` does not allocate.
101 fn drop_ty<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, args: LvalueRef<'tcx>) {
102 call_drop_glue(bcx, args, false, None)
105 pub fn call_drop_glue<'a, 'tcx>(
106 bcx: &Builder<'a, 'tcx>,
107 mut args: LvalueRef<'tcx>,
109 funclet: Option<&'a Funclet>,
111 let t = args.ty.to_ty(bcx.tcx());
112 // NB: v is an *alias* of type t here, not a direct value.
113 debug!("call_drop_glue(t={:?}, skip_dtor={})", t, skip_dtor);
114 if bcx.ccx.shared().type_needs_drop(t) {
116 let g = if skip_dtor {
117 DropGlueKind::TyContents(t)
121 let glue = get_drop_glue_core(ccx, g);
122 let glue_type = get_drop_glue_type(ccx.shared(), t);
124 args.llval = bcx.pointercast(args.llval, type_of(ccx, glue_type).ptr_to());
127 // No drop-hint ==> call standard drop glue
128 bcx.call(glue, &[args.llval, args.llextra][..1 + args.has_extra() as usize],
129 funclet.map(|b| b.bundle()));
133 pub fn get_drop_glue<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> ValueRef {
134 get_drop_glue_core(ccx, DropGlueKind::Ty(t))
137 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
138 pub enum DropGlueKind<'tcx> {
139 /// The normal path; runs the dtor, and then recurs on the contents
141 /// Skips the dtor, if any, for ty; drops the contents directly.
142 /// Note that the dtor is only skipped at the most *shallow*
143 /// level, namely, an `impl Drop for Ty` itself. So, for example,
144 /// if Ty is Newtype(S) then only the Drop impl for Newtype itself
145 /// will be skipped, while the Drop impl for S, if any, will be
147 TyContents(Ty<'tcx>),
150 impl<'tcx> DropGlueKind<'tcx> {
151 pub fn ty(&self) -> Ty<'tcx> {
152 match *self { DropGlueKind::Ty(t) | DropGlueKind::TyContents(t) => t }
155 pub fn map_ty<F>(&self, mut f: F) -> DropGlueKind<'tcx> where F: FnMut(Ty<'tcx>) -> Ty<'tcx>
158 DropGlueKind::Ty(t) => DropGlueKind::Ty(f(t)),
159 DropGlueKind::TyContents(t) => DropGlueKind::TyContents(f(t)),
164 fn get_drop_glue_core<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, g: DropGlueKind<'tcx>) -> ValueRef {
165 let g = g.map_ty(|t| get_drop_glue_type(ccx.shared(), t));
166 match ccx.drop_glues().borrow().get(&g) {
167 Some(&(glue, _)) => glue,
169 bug!("Could not find drop glue for {:?} -- {} -- {}.",
171 TransItem::DropGlue(g).to_raw_string(),
172 ccx.codegen_unit().name());
177 pub fn implement_drop_glue<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, g: DropGlueKind<'tcx>) {
178 assert_eq!(g.ty(), get_drop_glue_type(ccx.shared(), g.ty()));
179 let (llfn, _) = ccx.drop_glues().borrow().get(&g).unwrap().clone();
181 let mut bcx = Builder::new_block(ccx, llfn, "entry-block");
183 ccx.stats().n_glues_created.set(ccx.stats().n_glues_created.get() + 1);
184 // All glue functions take values passed *by alias*; this is a
185 // requirement since in many contexts glue is invoked indirectly and
186 // the caller has no idea if it's dealing with something that can be
189 // llfn is expected be declared to take a parameter of the appropriate
190 // type, so we don't need to explicitly cast the function parameter.
192 // NB: v0 is an *alias* of type t here, not a direct value.
193 // Only drop the value when it ... well, we used to check for
194 // non-null, (and maybe we need to continue doing so), but we now
195 // must definitely check for special bit-patterns corresponding to
196 // the special dtor markings.
199 let value = get_param(llfn, 0);
200 let ptr = if ccx.shared().type_is_sized(t) {
201 LvalueRef::new_sized_ty(value, t, Alignment::AbiAligned)
203 LvalueRef::new_unsized_ty(value, get_param(llfn, 1), t, Alignment::AbiAligned)
206 let skip_dtor = match g {
207 DropGlueKind::Ty(_) => false,
208 DropGlueKind::TyContents(_) => true
211 let bcx = match t.sty {
212 ty::TyAdt(def, _) if def.is_box() => {
213 // Support for Box is built-in as yet and its drop glue is special
214 // despite having a dummy Drop impl in the library.
216 let content_ty = t.boxed_ty();
217 let ptr = if !bcx.ccx.shared().type_is_sized(content_ty) {
218 let llbox = bcx.load(get_dataptr(&bcx, ptr.llval), None);
219 let info = bcx.load(get_meta(&bcx, ptr.llval), None);
220 LvalueRef::new_unsized_ty(llbox, info, content_ty, Alignment::AbiAligned)
222 LvalueRef::new_sized_ty(
223 bcx.load(ptr.llval, None),
224 content_ty, Alignment::AbiAligned)
227 trans_exchange_free_ty(&bcx, ptr);
230 ty::TyDynamic(..) => {
231 // No support in vtable for distinguishing destroying with
232 // versus without calling Drop::drop. Assert caller is
233 // okay with always calling the Drop impl, if any.
235 let dtor = bcx.load(ptr.llextra, None);
236 bcx.call(dtor, &[ptr.llval], None);
239 ty::TyAdt(def, ..) if def.has_dtor(bcx.tcx()) && !skip_dtor => {
240 let shallow_drop = def.is_union();
243 // Be sure to put the contents into a scope so we can use an invoke
244 // instruction to call the user destructor but still call the field
245 // destructors if the user destructor panics.
247 // FIXME (#14875) panic-in-drop semantics might be unsupported; we
248 // might well consider changing below to more direct code.
249 // Issue #23611: schedule cleanup of contents, re-inspecting the
250 // discriminant (if any) in case of variant swap in drop code.
251 let contents_scope = if !shallow_drop {
252 CleanupScope::schedule_drop_adt_contents(&bcx, ptr)
256 let drop_trait_def_id = tcx.lang_items.drop_trait().unwrap();
257 let drop_method = tcx.associated_items(drop_trait_def_id)
258 .find(|it| it.kind == ty::AssociatedKind::Method)
260 let self_type_substs = tcx.mk_substs_trait(t, &[]);
261 let callee = Callee::def(bcx.ccx, drop_method, self_type_substs);
262 let fn_ty = callee.direct_fn_type(bcx.ccx, &[]);
264 let args = &[ptr.llval, ptr.llextra][..1 + ptr.has_extra() as usize];
265 if let Some(landing_pad) = contents_scope.landing_pad {
266 let normal_bcx = bcx.build_sibling_block("normal-return");
267 llret = bcx.invoke(callee.reify(ccx), args, normal_bcx.llbb(), landing_pad, None);
270 llret = bcx.call(callee.reify(bcx.ccx), args, None);
272 fn_ty.apply_attrs_callsite(llret);
273 contents_scope.trans(&bcx);
276 ty::TyAdt(def, ..) if def.is_union() => {
280 if bcx.ccx.shared().type_needs_drop(t) {
281 drop_structural_ty(bcx, ptr)
290 pub fn size_and_align_of_dst<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, t: Ty<'tcx>, info: ValueRef)
291 -> (ValueRef, ValueRef) {
292 debug!("calculate size of DST: {}; with lost info: {:?}",
294 if bcx.ccx.shared().type_is_sized(t) {
295 let sizing_type = sizing_type_of(bcx.ccx, t);
296 let size = llsize_of_alloc(bcx.ccx, sizing_type);
297 let align = align_of(bcx.ccx, t);
298 debug!("size_and_align_of_dst t={} info={:?} size: {} align: {}",
299 t, Value(info), size, align);
300 let size = C_uint(bcx.ccx, size);
301 let align = C_uint(bcx.ccx, align);
302 return (size, align);
305 ty::TyAdt(def, substs) => {
307 // First get the size of all statically known fields.
308 // Don't use type_of::sizing_type_of because that expects t to be sized,
309 // and it also rounds up to alignment, which we want to avoid,
310 // as the unsized field's alignment could be smaller.
311 assert!(!t.is_simd());
312 let layout = ccx.layout_of(t);
313 debug!("DST {} layout: {:?}", t, layout);
315 let (sized_size, sized_align) = match *layout {
316 ty::layout::Layout::Univariant { ref variant, .. } => {
317 (variant.offsets.last().map_or(0, |o| o.bytes()), variant.align.abi())
320 bug!("size_and_align_of_dst: expcted Univariant for `{}`, found {:#?}",
324 debug!("DST {} statically sized prefix size: {} align: {}",
325 t, sized_size, sized_align);
326 let sized_size = C_uint(ccx, sized_size);
327 let sized_align = C_uint(ccx, sized_align);
329 // Recurse to get the size of the dynamically sized field (must be
331 let last_field = def.struct_variant().fields.last().unwrap();
332 let field_ty = monomorphize::field_ty(bcx.tcx(), substs, last_field);
333 let (unsized_size, unsized_align) = size_and_align_of_dst(bcx, field_ty, info);
335 // FIXME (#26403, #27023): We should be adding padding
336 // to `sized_size` (to accommodate the `unsized_align`
337 // required of the unsized field that follows) before
338 // summing it with `sized_size`. (Note that since #26403
339 // is unfixed, we do not yet add the necessary padding
340 // here. But this is where the add would go.)
342 // Return the sum of sizes and max of aligns.
343 let size = bcx.add(sized_size, unsized_size);
345 // Choose max of two known alignments (combined value must
346 // be aligned according to more restrictive of the two).
347 let align = match (const_to_opt_u128(sized_align, false),
348 const_to_opt_u128(unsized_align, false)) {
349 (Some(sized_align), Some(unsized_align)) => {
350 // If both alignments are constant, (the sized_align should always be), then
351 // pick the correct alignment statically.
352 C_uint(ccx, std::cmp::max(sized_align, unsized_align) as u64)
354 _ => bcx.select(bcx.icmp(llvm::IntUGT, sized_align, unsized_align),
359 // Issue #27023: must add any necessary padding to `size`
360 // (to make it a multiple of `align`) before returning it.
362 // Namely, the returned size should be, in C notation:
364 // `size + ((size & (align-1)) ? align : 0)`
366 // emulated via the semi-standard fast bit trick:
368 // `(size + (align-1)) & -align`
370 let addend = bcx.sub(align, C_uint(bcx.ccx, 1_u64));
371 let size = bcx.and(bcx.add(size, addend), bcx.neg(align));
375 ty::TyDynamic(..) => {
376 // info points to the vtable and the second entry in the vtable is the
377 // dynamic size of the object.
378 let info = bcx.pointercast(info, Type::int(bcx.ccx).ptr_to());
379 let size_ptr = bcx.gepi(info, &[1]);
380 let align_ptr = bcx.gepi(info, &[2]);
382 let size = bcx.load(size_ptr, None);
383 let align = bcx.load(align_ptr, None);
385 // Vtable loads are invariant
386 bcx.set_invariant_load(size);
387 bcx.set_invariant_load(align);
391 ty::TySlice(_) | ty::TyStr => {
392 let unit_ty = t.sequence_element_type(bcx.tcx());
393 // The info in this case is the length of the str, so the size is that
394 // times the unit size.
395 let llunit_ty = sizing_type_of(bcx.ccx, unit_ty);
396 let unit_align = llalign_of_min(bcx.ccx, llunit_ty);
397 let unit_size = llsize_of_alloc(bcx.ccx, llunit_ty);
398 (bcx.mul(info, C_uint(bcx.ccx, unit_size)),
399 C_uint(bcx.ccx, unit_align))
401 _ => bug!("Unexpected unsized type, found {}", t)
405 // Iterates through the elements of a structural type, dropping them.
406 fn drop_structural_ty<'a, 'tcx>(
407 cx: Builder<'a, 'tcx>,
408 mut ptr: LvalueRef<'tcx>
409 ) -> Builder<'a, 'tcx> {
410 fn iter_variant_fields<'a, 'tcx>(
411 cx: &'a Builder<'a, 'tcx>,
413 adt_def: &'tcx AdtDef,
414 variant_index: usize,
415 substs: &'tcx Substs<'tcx>
417 let variant = &adt_def.variants[variant_index];
419 for (i, field) in variant.fields.iter().enumerate() {
420 let arg = monomorphize::field_ty(tcx, substs, field);
421 let (field_ptr, align) = av.trans_field_ptr(&cx, i);
422 drop_ty(&cx, LvalueRef::new_sized_ty(field_ptr, arg, align));
427 let t = ptr.ty.to_ty(cx.tcx());
429 ty::TyClosure(def_id, substs) => {
430 for (i, upvar_ty) in substs.upvar_tys(def_id, cx.tcx()).enumerate() {
431 let (llupvar, align) = ptr.trans_field_ptr(&cx, i);
432 drop_ty(&cx, LvalueRef::new_sized_ty(llupvar, upvar_ty, align));
435 ty::TyArray(_, n) => {
436 let base = get_dataptr(&cx, ptr.llval);
437 let len = C_uint(cx.ccx, n);
438 let unit_ty = t.sequence_element_type(cx.tcx());
439 cx = tvec::slice_for_each(&cx, base, unit_ty, len,
440 |bb, vv| drop_ty(bb, LvalueRef::new_sized_ty(vv, unit_ty, ptr.alignment)));
442 ty::TySlice(_) | ty::TyStr => {
443 let unit_ty = t.sequence_element_type(cx.tcx());
444 cx = tvec::slice_for_each(&cx, ptr.llval, unit_ty, ptr.llextra,
445 |bb, vv| drop_ty(bb, LvalueRef::new_sized_ty(vv, unit_ty, ptr.alignment)));
447 ty::TyTuple(ref args, _) => {
448 for (i, arg) in args.iter().enumerate() {
449 let (llfld_a, align) = ptr.trans_field_ptr(&cx, i);
450 drop_ty(&cx, LvalueRef::new_sized_ty(llfld_a, *arg, align));
453 ty::TyAdt(adt, substs) => match adt.adt_kind() {
455 for (i, field) in adt.variants[0].fields.iter().enumerate() {
456 let field_ty = monomorphize::field_ty(cx.tcx(), substs, field);
457 let (llval, align) = ptr.trans_field_ptr(&cx, i);
458 let field_ptr = if cx.ccx.shared().type_is_sized(field_ty) {
459 LvalueRef::new_sized_ty(llval, field_ty, align)
461 LvalueRef::new_unsized_ty(llval, ptr.llextra, field_ty, align)
463 drop_ty(&cx, field_ptr);
467 bug!("Union in `glue::drop_structural_ty`");
470 let n_variants = adt.variants.len();
472 // NB: we must hit the discriminant first so that structural
473 // comparison know not to proceed when the discriminants differ.
475 // Obtain a representation of the discriminant sufficient to translate
476 // destructuring; this may or may not involve the actual discriminant.
477 let l = cx.ccx.layout_of(t);
479 layout::Univariant { .. } |
480 layout::UntaggedUnion { .. } => {
482 assert!(n_variants == 1);
483 ptr.ty = LvalueTy::Downcast {
488 iter_variant_fields(&cx, ptr, &adt, 0, substs);
491 layout::CEnum { .. } |
492 layout::General { .. } |
493 layout::RawNullablePointer { .. } |
494 layout::StructWrappedNullablePointer { .. } => {
495 let lldiscrim_a = adt::trans_get_discr(
496 &cx, t, ptr.llval, ptr.alignment, None, false);
498 // Create a fall-through basic block for the "else" case of
499 // the switch instruction we're about to generate. Note that
500 // we do **not** use an Unreachable instruction here, even
501 // though most of the time this basic block will never be hit.
503 // When an enum is dropped it's contents are currently
504 // overwritten to DTOR_DONE, which means the discriminant
505 // could have changed value to something not within the actual
506 // range of the discriminant. Currently this function is only
507 // used for drop glue so in this case we just return quickly
508 // from the outer function, and any other use case will only
509 // call this for an already-valid enum in which case the `ret
510 // void` will never be hit.
511 let ret_void_cx = cx.build_sibling_block("enum-iter-ret-void");
512 ret_void_cx.ret_void();
513 let llswitch = cx.switch(lldiscrim_a, ret_void_cx.llbb(), n_variants);
514 let next_cx = cx.build_sibling_block("enum-iter-next");
516 for (i, discr) in adt.discriminants(cx.tcx()).enumerate() {
517 let variant_cx_name = format!("enum-iter-variant-{}", i);
518 let variant_cx = cx.build_sibling_block(&variant_cx_name);
519 let case_val = adt::trans_case(&cx, t, Disr::from(discr));
520 variant_cx.add_case(llswitch, case_val, variant_cx.llbb());
521 ptr.ty = LvalueTy::Downcast {
526 iter_variant_fields(&variant_cx, ptr, &adt, i, substs);
527 variant_cx.br(next_cx.llbb());
531 _ => bug!("{} is not an enum.", t),
537 cx.sess().unimpl(&format!("type in drop_structural_ty: {}", t))