1 //! Codegen of the [`PointerCast::Unsize`] operation.
3 //! [`PointerCast::Unsize`]: `rustc_middle::ty::adjustment::PointerCast::Unsize`
7 // Adapted from https://github.com/rust-lang/rust/blob/2a663555ddf36f6b041445894a8c175cd1bc718c/src/librustc_codegen_ssa/base.rs#L159-L307
9 /// Retrieve the information we are losing (making dynamic) in an unsizing
12 /// The `old_info` argument is a bit funny. It is intended for use
13 /// in an upcast, where the new vtable for an object will be derived
15 pub(crate) fn unsized_info<'tcx>(
16 fx: &mut FunctionCx<'_, '_, 'tcx>,
19 old_info: Option<Value>,
21 let (source, target) =
22 fx.tcx.struct_lockstep_tails_erasing_lifetimes(source, target, ParamEnv::reveal_all());
23 match (&source.kind(), &target.kind()) {
24 (&ty::Array(_, len), &ty::Slice(_)) => fx
27 .iconst(fx.pointer_type, len.eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64),
28 (&ty::Dynamic(..), &ty::Dynamic(..)) => {
29 // For now, upcasts are limited to changes in marker
30 // traits, and hence never actually require an actual
31 // change to the vtable.
32 old_info.expect("unsized_info: missing old info for trait upcast")
34 (_, &ty::Dynamic(ref data, ..)) => crate::vtable::get_vtable(fx, source, data.principal()),
35 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
39 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
40 fn unsize_thin_ptr<'tcx>(
41 fx: &mut FunctionCx<'_, '_, 'tcx>,
43 src_layout: TyAndLayout<'tcx>,
44 dst_layout: TyAndLayout<'tcx>,
46 match (&src_layout.ty.kind(), &dst_layout.ty.kind()) {
47 (&ty::Ref(_, a, _), &ty::Ref(_, b, _))
48 | (&ty::Ref(_, a, _), &ty::RawPtr(ty::TypeAndMut { ty: b, .. }))
49 | (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }), &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
50 assert!(!fx.layout_of(a).is_unsized());
51 (src, unsized_info(fx, a, b, None))
53 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
54 let (a, b) = (src_layout.ty.boxed_ty(), dst_layout.ty.boxed_ty());
55 assert!(!fx.layout_of(a).is_unsized());
56 (src, unsized_info(fx, a, b, None))
58 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
59 assert_eq!(def_a, def_b);
61 let mut result = None;
62 for i in 0..src_layout.fields.count() {
63 let src_f = src_layout.field(fx, i);
64 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
65 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
69 assert_eq!(src_layout.size, src_f.size);
71 let dst_f = dst_layout.field(fx, i);
72 assert_ne!(src_f.ty, dst_f.ty);
73 assert_eq!(result, None);
74 result = Some(unsize_thin_ptr(fx, src, src_f, dst_f));
78 _ => bug!("unsize_thin_ptr: called on bad types"),
82 /// Coerce `src`, which is a reference to a value of type `src_ty`,
83 /// to a value of type `dst_ty` and store the result in `dst`
84 pub(crate) fn coerce_unsized_into<'tcx>(
85 fx: &mut FunctionCx<'_, '_, 'tcx>,
89 let src_ty = src.layout().ty;
90 let dst_ty = dst.layout().ty;
91 let mut coerce_ptr = || {
93 if fx.layout_of(src.layout().ty.builtin_deref(true).unwrap().ty).is_unsized() {
94 // fat-ptr to fat-ptr unsize preserves the vtable
95 // i.e., &'a fmt::Debug+Send => &'a fmt::Debug
96 src.load_scalar_pair(fx)
98 let base = src.load_scalar(fx);
99 unsize_thin_ptr(fx, base, src.layout(), dst.layout())
101 dst.write_cvalue(fx, CValue::by_val_pair(base, info, dst.layout()));
103 match (&src_ty.kind(), &dst_ty.kind()) {
104 (&ty::Ref(..), &ty::Ref(..))
105 | (&ty::Ref(..), &ty::RawPtr(..))
106 | (&ty::RawPtr(..), &ty::RawPtr(..)) => coerce_ptr(),
107 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
108 assert_eq!(def_a, def_b);
110 for i in 0..def_a.variants[VariantIdx::new(0)].fields.len() {
111 let src_f = src.value_field(fx, mir::Field::new(i));
112 let dst_f = dst.place_field(fx, mir::Field::new(i));
114 if dst_f.layout().is_zst() {
118 if src_f.layout().ty == dst_f.layout().ty {
119 dst_f.write_cvalue(fx, src_f);
121 coerce_unsized_into(fx, src_f, dst_f);
125 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty),
129 // Adapted from https://github.com/rust-lang/rust/blob/2a663555ddf36f6b041445894a8c175cd1bc718c/src/librustc_codegen_ssa/glue.rs
131 pub(crate) fn size_and_align_of_dst<'tcx>(
132 fx: &mut FunctionCx<'_, '_, 'tcx>,
133 layout: TyAndLayout<'tcx>,
135 ) -> (Value, Value) {
136 if !layout.is_unsized() {
137 let size = fx.bcx.ins().iconst(fx.pointer_type, layout.size.bytes() as i64);
138 let align = fx.bcx.ins().iconst(fx.pointer_type, layout.align.abi.bytes() as i64);
139 return (size, align);
141 match layout.ty.kind() {
143 // load size/align from vtable
144 (crate::vtable::size_of_obj(fx, info), crate::vtable::min_align_of_obj(fx, info))
146 ty::Slice(_) | ty::Str => {
147 let unit = layout.field(fx, 0);
148 // The info in this case is the length of the str, so the size is that
149 // times the unit size.
151 fx.bcx.ins().imul_imm(info, unit.size.bytes() as i64),
152 fx.bcx.ins().iconst(fx.pointer_type, unit.align.abi.bytes() as i64),
156 // First get the size of all statically known fields.
157 // Don't use size_of because it also rounds up to alignment, which we
158 // want to avoid, as the unsized field's alignment could be smaller.
159 assert!(!layout.ty.is_simd());
161 let i = layout.fields.count() - 1;
162 let sized_size = layout.fields.offset(i).bytes();
163 let sized_align = layout.align.abi.bytes();
164 let sized_align = fx.bcx.ins().iconst(fx.pointer_type, sized_align as i64);
166 // Recurse to get the size of the dynamically sized field (must be
168 let field_layout = layout.field(fx, i);
169 let (unsized_size, mut unsized_align) = size_and_align_of_dst(fx, field_layout, info);
171 // FIXME (#26403, #27023): We should be adding padding
172 // to `sized_size` (to accommodate the `unsized_align`
173 // required of the unsized field that follows) before
174 // summing it with `sized_size`. (Note that since #26403
175 // is unfixed, we do not yet add the necessary padding
176 // here. But this is where the add would go.)
178 // Return the sum of sizes and max of aligns.
179 let size = fx.bcx.ins().iadd_imm(unsized_size, sized_size as i64);
181 // Packed types ignore the alignment of their fields.
182 if let ty::Adt(def, _) = layout.ty.kind() {
183 if def.repr.packed() {
184 unsized_align = sized_align;
188 // Choose max of two known alignments (combined value must
189 // be aligned according to more restrictive of the two).
190 let cmp = fx.bcx.ins().icmp(IntCC::UnsignedGreaterThan, sized_align, unsized_align);
191 let align = fx.bcx.ins().select(cmp, sized_align, unsized_align);
193 // Issue #27023: must add any necessary padding to `size`
194 // (to make it a multiple of `align`) before returning it.
196 // Namely, the returned size should be, in C notation:
198 // `size + ((size & (align-1)) ? align : 0)`
200 // emulated via the semi-standard fast bit trick:
202 // `(size + (align-1)) & -align`
203 let addend = fx.bcx.ins().iadd_imm(align, -1);
204 let add = fx.bcx.ins().iadd(size, addend);
205 let neg = fx.bcx.ins().ineg(align);
206 let size = fx.bcx.ins().band(add, neg);