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) =
23 .struct_lockstep_tails_erasing_lifetimes(source, target, ParamEnv::reveal_all());
24 match (&source.kind(), &target.kind()) {
25 (&ty::Array(_, len), &ty::Slice(_)) => fx.bcx.ins().iconst(
27 len.eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64,
29 (&ty::Dynamic(..), &ty::Dynamic(..)) => {
30 // For now, upcasts are limited to changes in marker
31 // traits, and hence never actually require an actual
32 // change to the vtable.
33 old_info.expect("unsized_info: missing old info for trait upcast")
35 (_, &ty::Dynamic(ref data, ..)) => {
36 crate::vtable::get_vtable(fx, fx.layout_of(source), data.principal())
39 "unsized_info: invalid unsizing {:?} -> {:?}",
46 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
47 fn unsize_thin_ptr<'tcx>(
48 fx: &mut FunctionCx<'_, '_, 'tcx>,
50 src_layout: TyAndLayout<'tcx>,
51 dst_layout: TyAndLayout<'tcx>,
53 match (&src_layout.ty.kind(), &dst_layout.ty.kind()) {
54 (&ty::Ref(_, a, _), &ty::Ref(_, b, _))
55 | (&ty::Ref(_, a, _), &ty::RawPtr(ty::TypeAndMut { ty: b, .. }))
56 | (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }), &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
57 assert!(!fx.layout_of(a).is_unsized());
58 (src, unsized_info(fx, a, b, None))
60 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
61 let (a, b) = (src_layout.ty.boxed_ty(), dst_layout.ty.boxed_ty());
62 assert!(!fx.layout_of(a).is_unsized());
63 (src, unsized_info(fx, a, b, None))
65 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
66 assert_eq!(def_a, def_b);
68 let mut result = None;
69 for i in 0..src_layout.fields.count() {
70 let src_f = src_layout.field(fx, i);
71 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
72 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
76 assert_eq!(src_layout.size, src_f.size);
78 let dst_f = dst_layout.field(fx, i);
79 assert_ne!(src_f.ty, dst_f.ty);
80 assert_eq!(result, None);
81 result = Some(unsize_thin_ptr(fx, src, src_f, dst_f));
85 _ => bug!("unsize_thin_ptr: called on bad types"),
89 /// Coerce `src`, which is a reference to a value of type `src_ty`,
90 /// to a value of type `dst_ty` and store the result in `dst`
91 pub(crate) fn coerce_unsized_into<'tcx>(
92 fx: &mut FunctionCx<'_, '_, 'tcx>,
96 let src_ty = src.layout().ty;
97 let dst_ty = dst.layout().ty;
98 let mut coerce_ptr = || {
99 let (base, info) = if fx
100 .layout_of(src.layout().ty.builtin_deref(true).unwrap().ty)
103 // fat-ptr to fat-ptr unsize preserves the vtable
104 // i.e., &'a fmt::Debug+Send => &'a fmt::Debug
105 src.load_scalar_pair(fx)
107 let base = src.load_scalar(fx);
108 unsize_thin_ptr(fx, base, src.layout(), dst.layout())
110 dst.write_cvalue(fx, CValue::by_val_pair(base, info, dst.layout()));
112 match (&src_ty.kind(), &dst_ty.kind()) {
113 (&ty::Ref(..), &ty::Ref(..))
114 | (&ty::Ref(..), &ty::RawPtr(..))
115 | (&ty::RawPtr(..), &ty::RawPtr(..)) => coerce_ptr(),
116 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
117 assert_eq!(def_a, def_b);
119 for i in 0..def_a.variants[VariantIdx::new(0)].fields.len() {
120 let src_f = src.value_field(fx, mir::Field::new(i));
121 let dst_f = dst.place_field(fx, mir::Field::new(i));
123 if dst_f.layout().is_zst() {
127 if src_f.layout().ty == dst_f.layout().ty {
128 dst_f.write_cvalue(fx, src_f);
130 coerce_unsized_into(fx, src_f, dst_f);
135 "coerce_unsized_into: invalid coercion {:?} -> {:?}",
142 // Adapted from https://github.com/rust-lang/rust/blob/2a663555ddf36f6b041445894a8c175cd1bc718c/src/librustc_codegen_ssa/glue.rs
144 pub(crate) fn size_and_align_of_dst<'tcx>(
145 fx: &mut FunctionCx<'_, '_, 'tcx>,
146 layout: TyAndLayout<'tcx>,
148 ) -> (Value, Value) {
149 if !layout.is_unsized() {
153 .iconst(fx.pointer_type, layout.size.bytes() as i64);
157 .iconst(fx.pointer_type, layout.align.abi.bytes() as i64);
158 return (size, align);
160 match layout.ty.kind() {
162 // load size/align from vtable
164 crate::vtable::size_of_obj(fx, info),
165 crate::vtable::min_align_of_obj(fx, info),
168 ty::Slice(_) | ty::Str => {
169 let unit = layout.field(fx, 0);
170 // The info in this case is the length of the str, so the size is that
171 // times the unit size.
173 fx.bcx.ins().imul_imm(info, unit.size.bytes() as i64),
176 .iconst(fx.pointer_type, unit.align.abi.bytes() as i64),
180 // First get the size of all statically known fields.
181 // Don't use size_of because it also rounds up to alignment, which we
182 // want to avoid, as the unsized field's alignment could be smaller.
183 assert!(!layout.ty.is_simd());
185 let i = layout.fields.count() - 1;
186 let sized_size = layout.fields.offset(i).bytes();
187 let sized_align = layout.align.abi.bytes();
188 let sized_align = fx.bcx.ins().iconst(fx.pointer_type, sized_align as i64);
190 // Recurse to get the size of the dynamically sized field (must be
192 let field_layout = layout.field(fx, i);
193 let (unsized_size, mut unsized_align) = size_and_align_of_dst(fx, field_layout, info);
195 // FIXME (#26403, #27023): We should be adding padding
196 // to `sized_size` (to accommodate the `unsized_align`
197 // required of the unsized field that follows) before
198 // summing it with `sized_size`. (Note that since #26403
199 // is unfixed, we do not yet add the necessary padding
200 // here. But this is where the add would go.)
202 // Return the sum of sizes and max of aligns.
203 let size = fx.bcx.ins().iadd_imm(unsized_size, sized_size as i64);
205 // Packed types ignore the alignment of their fields.
206 if let ty::Adt(def, _) = layout.ty.kind() {
207 if def.repr.packed() {
208 unsized_align = sized_align;
212 // Choose max of two known alignments (combined value must
213 // be aligned according to more restrictive of the two).
217 .icmp(IntCC::UnsignedGreaterThan, sized_align, unsized_align);
218 let align = fx.bcx.ins().select(cmp, sized_align, unsized_align);
220 // Issue #27023: must add any necessary padding to `size`
221 // (to make it a multiple of `align`) before returning it.
223 // Namely, the returned size should be, in C notation:
225 // `size + ((size & (align-1)) ? align : 0)`
227 // emulated via the semi-standard fast bit trick:
229 // `(size + (align-1)) & -align`
230 let addend = fx.bcx.ins().iadd_imm(align, -1);
231 let add = fx.bcx.ins().iadd(size, addend);
232 let neg = fx.bcx.ins().ineg(align);
233 let size = fx.bcx.ins().band(add, neg);