]> git.lizzy.rs Git - rust.git/blob - src/unsize.rs
Use anonymous lifetimes where possible
[rust.git] / src / unsize.rs
1 use crate::prelude::*;
2
3 // Adapted from https://github.com/rust-lang/rust/blob/2a663555ddf36f6b041445894a8c175cd1bc718c/src/librustc_codegen_ssa/base.rs#L159-L307
4
5 /// Retrieve the information we are losing (making dynamic) in an unsizing
6 /// adjustment.
7 ///
8 /// The `old_info` argument is a bit funny. It is intended for use
9 /// in an upcast, where the new vtable for an object will be derived
10 /// from the old one.
11 pub fn unsized_info<'tcx>(
12     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
13     source: Ty<'tcx>,
14     target: Ty<'tcx>,
15     old_info: Option<Value>,
16 ) -> Value {
17     let (source, target) =
18         fx.tcx.struct_lockstep_tails_erasing_lifetimes(source, target, ParamEnv::reveal_all());
19     match (&source.sty, &target.sty) {
20         (&ty::Array(_, len), &ty::Slice(_)) => fx
21             .bcx
22             .ins()
23             .iconst(
24                 fx.pointer_type,
25                 len.eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64,
26             ),
27         (&ty::Dynamic(..), &ty::Dynamic(..)) => {
28             // For now, upcasts are limited to changes in marker
29             // traits, and hence never actually require an actual
30             // change to the vtable.
31             old_info.expect("unsized_info: missing old info for trait upcast")
32         }
33         (_, &ty::Dynamic(ref data, ..)) => crate::vtable::get_vtable(fx, source, data.principal()),
34         _ => bug!(
35             "unsized_info: invalid unsizing {:?} -> {:?}",
36             source,
37             target
38         ),
39     }
40 }
41
42 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
43 pub fn unsize_thin_ptr<'tcx>(
44     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
45     src: Value,
46     src_ty: Ty<'tcx>,
47     dst_ty: Ty<'tcx>,
48 ) -> (Value, Value) {
49     match (&src_ty.sty, &dst_ty.sty) {
50         (&ty::Ref(_, a, _), &ty::Ref(_, b, _))
51         | (&ty::Ref(_, a, _), &ty::RawPtr(ty::TypeAndMut { ty: b, .. }))
52         | (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }), &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
53             assert!(!fx.layout_of(a).is_unsized());
54             (src, unsized_info(fx, a, b, None))
55         }
56         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
57             let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
58             assert!(!fx.layout_of(a).is_unsized());
59             (src, unsized_info(fx, a, b, None))
60         }
61         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
62             assert_eq!(def_a, def_b);
63
64             let src_layout = fx.layout_of(src_ty);
65             let dst_layout = fx.layout_of(dst_ty);
66             let mut result = None;
67             for i in 0..src_layout.fields.count() {
68                 let src_f = src_layout.field(fx, i);
69                 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
70                 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
71                 if src_f.is_zst() {
72                     continue;
73                 }
74                 assert_eq!(src_layout.size, src_f.size);
75
76                 let dst_f = dst_layout.field(fx, i);
77                 assert_ne!(src_f.ty, dst_f.ty);
78                 assert_eq!(result, None);
79                 result = Some(unsize_thin_ptr(fx, src, src_f.ty, dst_f.ty));
80             }
81             result.unwrap()
82         }
83         _ => bug!("unsize_thin_ptr: called on bad types"),
84     }
85 }
86
87 /// Coerce `src`, which is a reference to a value of type `src_ty`,
88 /// to a value of type `dst_ty` and store the result in `dst`
89 pub fn coerce_unsized_into<'tcx>(
90     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
91     src: CValue<'tcx>,
92     dst: CPlace<'tcx>,
93 ) {
94     let src_ty = src.layout().ty;
95     let dst_ty = dst.layout().ty;
96     let mut coerce_ptr = || {
97         let (base, info) = if fx
98             .layout_of(src.layout().ty.builtin_deref(true).unwrap().ty)
99             .is_unsized()
100         {
101             // fat-ptr to fat-ptr unsize preserves the vtable
102             // i.e., &'a fmt::Debug+Send => &'a fmt::Debug
103             src.load_scalar_pair(fx)
104         } else {
105             let base = src.load_scalar(fx);
106             unsize_thin_ptr(fx, base, src_ty, dst_ty)
107         };
108         dst.write_cvalue(fx, CValue::by_val_pair(base, info, dst.layout()));
109     };
110     match (&src_ty.sty, &dst_ty.sty) {
111         (&ty::Ref(..), &ty::Ref(..))
112         | (&ty::Ref(..), &ty::RawPtr(..))
113         | (&ty::RawPtr(..), &ty::RawPtr(..)) => coerce_ptr(),
114         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
115             assert_eq!(def_a, def_b);
116
117             for i in 0..def_a.variants[VariantIdx::new(0)].fields.len() {
118                 let src_f = src.value_field(fx, mir::Field::new(i));
119                 let dst_f = dst.place_field(fx, mir::Field::new(i));
120
121                 if dst_f.layout().is_zst() {
122                     continue;
123                 }
124
125                 if src_f.layout().ty == dst_f.layout().ty {
126                     dst_f.write_cvalue(fx, src_f);
127                 } else {
128                     coerce_unsized_into(fx, src_f, dst_f);
129                 }
130             }
131         }
132         _ => bug!(
133             "coerce_unsized_into: invalid coercion {:?} -> {:?}",
134             src_ty,
135             dst_ty
136         ),
137     }
138 }
139
140 // Adapted from https://github.com/rust-lang/rust/blob/2a663555ddf36f6b041445894a8c175cd1bc718c/src/librustc_codegen_ssa/glue.rs
141
142 pub fn size_and_align_of_dst<'tcx>(
143     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
144     ty: Ty<'tcx>,
145     info: Value,
146 ) -> (Value, Value) {
147     let layout = fx.layout_of(ty);
148     if !layout.is_unsized() {
149         let size = fx
150             .bcx
151             .ins()
152             .iconst(fx.pointer_type, layout.size.bytes() as i64);
153         let align = fx
154             .bcx
155             .ins()
156             .iconst(fx.pointer_type, layout.align.abi.bytes() as i64);
157         return (size, align);
158     }
159     match ty.sty {
160         ty::Dynamic(..) => {
161             // load size/align from vtable
162             (
163                 crate::vtable::size_of_obj(fx, info),
164                 crate::vtable::min_align_of_obj(fx, info),
165             )
166         }
167         ty::Slice(_) | ty::Str => {
168             let unit = layout.field(fx, 0);
169             // The info in this case is the length of the str, so the size is that
170             // times the unit size.
171             (
172                 fx.bcx.ins().imul_imm(info, unit.size.bytes() as i64),
173                 fx.bcx
174                     .ins()
175                     .iconst(fx.pointer_type, unit.align.abi.bytes() as i64),
176             )
177         }
178         _ => {
179             // First get the size of all statically known fields.
180             // Don't use size_of because it also rounds up to alignment, which we
181             // want to avoid, as the unsized field's alignment could be smaller.
182             assert!(!ty.is_simd());
183
184             let i = layout.fields.count() - 1;
185             let sized_size = layout.fields.offset(i).bytes();
186             let sized_align = layout.align.abi.bytes();
187             let sized_align = fx.bcx.ins().iconst(fx.pointer_type, sized_align as i64);
188
189             // Recurse to get the size of the dynamically sized field (must be
190             // the last field).
191             let field_ty = layout.field(fx, i).ty;
192             let (unsized_size, mut unsized_align) = size_and_align_of_dst(fx, field_ty, info);
193
194             // FIXME (#26403, #27023): We should be adding padding
195             // to `sized_size` (to accommodate the `unsized_align`
196             // required of the unsized field that follows) before
197             // summing it with `sized_size`. (Note that since #26403
198             // is unfixed, we do not yet add the necessary padding
199             // here. But this is where the add would go.)
200
201             // Return the sum of sizes and max of aligns.
202             let size = fx.bcx.ins().iadd_imm(unsized_size, sized_size as i64);
203
204             // Packed types ignore the alignment of their fields.
205             if let ty::Adt(def, _) = ty.sty {
206                 if def.repr.packed() {
207                     unsized_align = sized_align;
208                 }
209             }
210
211             // Choose max of two known alignments (combined value must
212             // be aligned according to more restrictive of the two).
213             let cmp = fx
214                 .bcx
215                 .ins()
216                 .icmp(IntCC::UnsignedGreaterThan, sized_align, unsized_align);
217             let align = fx.bcx.ins().select(cmp, sized_align, unsized_align);
218
219             // Issue #27023: must add any necessary padding to `size`
220             // (to make it a multiple of `align`) before returning it.
221             //
222             // Namely, the returned size should be, in C notation:
223             //
224             //   `size + ((size & (align-1)) ? align : 0)`
225             //
226             // emulated via the semi-standard fast bit trick:
227             //
228             //   `(size + (align-1)) & -align`
229             let addend = fx.bcx.ins().iadd_imm(align, -1);
230             let add = fx.bcx.ins().iadd(size, addend);
231             let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
232             let neg = fx.bcx.ins().isub(zero, align);
233             let size = fx.bcx.ins().band(add, neg);
234
235             (size, align)
236         }
237     }
238 }