]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/src/unsize.rs
Rollup merge of #86811 - soerenmeier:remove_remaining, r=yaahc
[rust.git] / compiler / rustc_codegen_cranelift / src / unsize.rs
1 //! Codegen of the [`PointerCast::Unsize`] operation.
2 //!
3 //! [`PointerCast::Unsize`]: `rustc_middle::ty::adjustment::PointerCast::Unsize`
4
5 use crate::prelude::*;
6
7 // Adapted from https://github.com/rust-lang/rust/blob/2a663555ddf36f6b041445894a8c175cd1bc718c/src/librustc_codegen_ssa/base.rs#L159-L307
8
9 /// Retrieve the information we are losing (making dynamic) in an unsizing
10 /// adjustment.
11 ///
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
14 /// from the old one.
15 pub(crate) fn unsized_info<'tcx>(
16     fx: &mut FunctionCx<'_, '_, 'tcx>,
17     source: Ty<'tcx>,
18     target: Ty<'tcx>,
19     old_info: Option<Value>,
20 ) -> 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
25             .bcx
26             .ins()
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")
33         }
34         (_, &ty::Dynamic(ref data, ..)) => crate::vtable::get_vtable(fx, source, data.principal()),
35         _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
36     }
37 }
38
39 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
40 fn unsize_thin_ptr<'tcx>(
41     fx: &mut FunctionCx<'_, '_, 'tcx>,
42     src: Value,
43     src_layout: TyAndLayout<'tcx>,
44     dst_layout: TyAndLayout<'tcx>,
45 ) -> (Value, Value) {
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))
52         }
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))
57         }
58         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
59             assert_eq!(def_a, def_b);
60
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);
66                 if src_f.is_zst() {
67                     continue;
68                 }
69                 assert_eq!(src_layout.size, src_f.size);
70
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));
75             }
76             result.unwrap()
77         }
78         _ => bug!("unsize_thin_ptr: called on bad types"),
79     }
80 }
81
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>,
86     src: CValue<'tcx>,
87     dst: CPlace<'tcx>,
88 ) {
89     let src_ty = src.layout().ty;
90     let dst_ty = dst.layout().ty;
91     let mut coerce_ptr = || {
92         let (base, info) =
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)
97             } else {
98                 let base = src.load_scalar(fx);
99                 unsize_thin_ptr(fx, base, src.layout(), dst.layout())
100             };
101         dst.write_cvalue(fx, CValue::by_val_pair(base, info, dst.layout()));
102     };
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);
109
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));
113
114                 if dst_f.layout().is_zst() {
115                     continue;
116                 }
117
118                 if src_f.layout().ty == dst_f.layout().ty {
119                     dst_f.write_cvalue(fx, src_f);
120                 } else {
121                     coerce_unsized_into(fx, src_f, dst_f);
122                 }
123             }
124         }
125         _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty),
126     }
127 }
128
129 // Adapted from https://github.com/rust-lang/rust/blob/2a663555ddf36f6b041445894a8c175cd1bc718c/src/librustc_codegen_ssa/glue.rs
130
131 pub(crate) fn size_and_align_of_dst<'tcx>(
132     fx: &mut FunctionCx<'_, '_, 'tcx>,
133     layout: TyAndLayout<'tcx>,
134     info: Value,
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);
140     }
141     match layout.ty.kind() {
142         ty::Dynamic(..) => {
143             // load size/align from vtable
144             (crate::vtable::size_of_obj(fx, info), crate::vtable::min_align_of_obj(fx, info))
145         }
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.
150             (
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),
153             )
154         }
155         _ => {
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());
160
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);
165
166             // Recurse to get the size of the dynamically sized field (must be
167             // the last field).
168             let field_layout = layout.field(fx, i);
169             let (unsized_size, mut unsized_align) = size_and_align_of_dst(fx, field_layout, info);
170
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.)
177
178             // Return the sum of sizes and max of aligns.
179             let size = fx.bcx.ins().iadd_imm(unsized_size, sized_size as i64);
180
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;
185                 }
186             }
187
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);
192
193             // Issue #27023: must add any necessary padding to `size`
194             // (to make it a multiple of `align`) before returning it.
195             //
196             // Namely, the returned size should be, in C notation:
197             //
198             //   `size + ((size & (align-1)) ? align : 0)`
199             //
200             // emulated via the semi-standard fast bit trick:
201             //
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);
207
208             (size, align)
209         }
210     }
211 }