]> git.lizzy.rs Git - rust.git/blob - src/value_and_place.rs
Fix load and store for ByValPair values with differently sized components
[rust.git] / src / value_and_place.rs
1 use crate::prelude::*;
2
3 fn codegen_field<'a, 'tcx: 'a>(
4     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
5     base: Value,
6     layout: TyLayout<'tcx>,
7     field: mir::Field,
8 ) -> (Value, TyLayout<'tcx>) {
9     let field_offset = layout.fields.offset(field.index());
10     let field_ty = layout.field(&*fx, field.index());
11     if field_offset.bytes() > 0 {
12         (
13             fx.bcx.ins().iadd_imm(base, field_offset.bytes() as i64),
14             field_ty,
15         )
16     } else {
17         (base, field_ty)
18     }
19 }
20
21 fn scalar_pair_calculate_b_offset(tcx: TyCtxt<'_>, a_scalar: &Scalar, b_scalar: &Scalar) -> i32 {
22     let b_offset = a_scalar.value.size(&tcx).align_to(b_scalar.value.align(&tcx).abi);
23     b_offset.bytes().try_into().unwrap()
24 }
25
26 /// A read-only value
27 #[derive(Debug, Copy, Clone)]
28 pub struct CValue<'tcx>(CValueInner, TyLayout<'tcx>);
29
30 #[derive(Debug, Copy, Clone)]
31 enum CValueInner {
32     ByRef(Value),
33     ByVal(Value),
34     ByValPair(Value, Value),
35 }
36
37 impl<'tcx> CValue<'tcx> {
38     pub fn by_ref(value: Value, layout: TyLayout<'tcx>) -> CValue<'tcx> {
39         CValue(CValueInner::ByRef(value), layout)
40     }
41
42     pub fn by_val(value: Value, layout: TyLayout<'tcx>) -> CValue<'tcx> {
43         CValue(CValueInner::ByVal(value), layout)
44     }
45
46     pub fn by_val_pair(value: Value, extra: Value, layout: TyLayout<'tcx>) -> CValue<'tcx> {
47         CValue(CValueInner::ByValPair(value, extra), layout)
48     }
49
50     pub fn layout(&self) -> TyLayout<'tcx> {
51         self.1
52     }
53
54     pub fn force_stack<'a>(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> Value
55     where
56         'tcx: 'a,
57     {
58         let layout = self.1;
59         match self.0 {
60             CValueInner::ByRef(value) => value,
61             CValueInner::ByVal(_) | CValueInner::ByValPair(_, _) => {
62                 let cplace = CPlace::new_stack_slot(fx, layout.ty);
63                 cplace.write_cvalue(fx, self);
64                 cplace.to_addr(fx)
65             }
66         }
67     }
68
69     /// Load a value with layout.abi of scalar
70     pub fn load_scalar<'a>(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> Value
71     where
72         'tcx: 'a,
73     {
74         let layout = self.1;
75         match self.0 {
76             CValueInner::ByRef(addr) => {
77                 let scalar = match layout.abi {
78                     layout::Abi::Scalar(ref scalar) => scalar.clone(),
79                     _ => unreachable!(),
80                 };
81                 let clif_ty = scalar_to_clif_type(fx.tcx, scalar);
82                 fx.bcx.ins().load(clif_ty, MemFlags::new(), addr, 0)
83             }
84             CValueInner::ByVal(value) => value,
85             CValueInner::ByValPair(_, _) => bug!("Please use load_scalar_pair for ByValPair"),
86         }
87     }
88
89     /// Load a value pair with layout.abi of scalar pair
90     pub fn load_scalar_pair<'a>(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> (Value, Value)
91     where
92         'tcx: 'a,
93     {
94         let layout = self.1;
95         match self.0 {
96             CValueInner::ByRef(addr) => {
97                 let (a_scalar, b_scalar) = match &layout.abi {
98                     layout::Abi::ScalarPair(a, b) => (a, b),
99                     _ => unreachable!(),
100                 };
101                 let b_offset = scalar_pair_calculate_b_offset(fx.tcx, a_scalar, b_scalar);
102                 let clif_ty1 = scalar_to_clif_type(fx.tcx, a_scalar.clone());
103                 let clif_ty2 = scalar_to_clif_type(fx.tcx, b_scalar.clone());
104                 let val1 = fx.bcx.ins().load(clif_ty1, MemFlags::new(), addr, 0);
105                 let val2 = fx.bcx.ins().load(
106                     clif_ty2,
107                     MemFlags::new(),
108                     addr,
109                     b_offset,
110                 );
111                 (val1, val2)
112             }
113             CValueInner::ByVal(_) => bug!("Please use load_scalar for ByVal"),
114             CValueInner::ByValPair(val1, val2) => (val1, val2),
115         }
116     }
117
118     pub fn value_field<'a>(
119         self,
120         fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
121         field: mir::Field,
122     ) -> CValue<'tcx>
123     where
124         'tcx: 'a,
125     {
126         let layout = self.1;
127         let base = match self.0 {
128             CValueInner::ByRef(addr) => addr,
129             _ => bug!("place_field for {:?}", self),
130         };
131
132         let (field_ptr, field_layout) = codegen_field(fx, base, layout, field);
133         CValue::by_ref(field_ptr, field_layout)
134     }
135
136     pub fn unsize_value<'a>(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>, dest: CPlace<'tcx>) {
137         crate::unsize::coerce_unsized_into(fx, self, dest);
138     }
139
140     pub fn const_val<'a>(
141         fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
142         ty: Ty<'tcx>,
143         const_val: i64,
144     ) -> CValue<'tcx>
145     where
146         'tcx: 'a,
147     {
148         let clif_ty = fx.clif_type(ty).unwrap();
149         let layout = fx.layout_of(ty);
150         CValue::by_val(fx.bcx.ins().iconst(clif_ty, const_val), layout)
151     }
152
153     pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
154         CValue(self.0, layout)
155     }
156 }
157
158 /// A place where you can write a value to or read a value from
159 #[derive(Debug, Copy, Clone)]
160 pub enum CPlace<'tcx> {
161     Var(Local, TyLayout<'tcx>),
162     Addr(Value, Option<Value>, TyLayout<'tcx>),
163     Stack(StackSlot, TyLayout<'tcx>),
164     NoPlace(TyLayout<'tcx>),
165 }
166
167 impl<'a, 'tcx: 'a> CPlace<'tcx> {
168     pub fn layout(&self) -> TyLayout<'tcx> {
169         match *self {
170             CPlace::Var(_, layout)
171             | CPlace::Addr(_, _, layout)
172             | CPlace::Stack(_, layout)
173             | CPlace::NoPlace(layout) => layout,
174         }
175     }
176
177     pub fn no_place(layout: TyLayout<'tcx>) -> CPlace<'tcx> {
178         CPlace::NoPlace(layout)
179     }
180
181     pub fn new_stack_slot(
182         fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
183         ty: Ty<'tcx>,
184     ) -> CPlace<'tcx> {
185         let layout = fx.layout_of(ty);
186         assert!(!layout.is_unsized());
187         if layout.size.bytes() == 0 {
188             return CPlace::NoPlace(layout);
189         }
190
191         let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
192             kind: StackSlotKind::ExplicitSlot,
193             size: layout.size.bytes() as u32,
194             offset: None,
195         });
196         CPlace::Stack(stack_slot, layout)
197     }
198
199     pub fn new_var(
200         fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
201         local: Local,
202         layout: TyLayout<'tcx>,
203     ) -> CPlace<'tcx> {
204         fx.bcx
205             .declare_var(mir_var(local), fx.clif_type(layout.ty).unwrap());
206         CPlace::Var(local, layout)
207     }
208
209     pub fn for_addr(addr: Value, layout: TyLayout<'tcx>) -> CPlace<'tcx> {
210         CPlace::Addr(addr, None, layout)
211     }
212
213     pub fn for_addr_with_extra(addr: Value, extra: Value, layout: TyLayout<'tcx>) -> CPlace<'tcx> {
214         CPlace::Addr(addr, Some(extra), layout)
215     }
216
217     pub fn to_cvalue(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> CValue<'tcx> {
218         match self {
219             CPlace::Var(var, layout) => CValue::by_val(fx.bcx.use_var(mir_var(var)), layout),
220             CPlace::Addr(addr, extra, layout) => {
221                 assert!(extra.is_none(), "unsized values are not yet supported");
222                 CValue::by_ref(addr, layout)
223             }
224             CPlace::Stack(stack_slot, layout) => CValue::by_ref(
225                 fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0),
226                 layout,
227             ),
228             CPlace::NoPlace(layout) => CValue::by_ref(
229                 fx.bcx
230                     .ins()
231                     .iconst(fx.pointer_type, fx.pointer_type.bytes() as i64),
232                 layout,
233             ),
234         }
235     }
236
237     pub fn to_addr(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> Value {
238         match self.to_addr_maybe_unsized(fx) {
239             (addr, None) => addr,
240             (_, Some(_)) => bug!("Expected sized cplace, found {:?}", self),
241         }
242     }
243
244     pub fn to_addr_maybe_unsized(
245         self,
246         fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
247     ) -> (Value, Option<Value>) {
248         match self {
249             CPlace::Addr(addr, extra, _layout) => (addr, extra),
250             CPlace::Stack(stack_slot, _layout) => (
251                 fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0),
252                 None,
253             ),
254             CPlace::NoPlace(_) => (fx.bcx.ins().iconst(fx.pointer_type, 45), None),
255             CPlace::Var(_, _) => bug!("Expected CPlace::Addr, found CPlace::Var"),
256         }
257     }
258
259     pub fn write_cvalue(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>, from: CValue<'tcx>) {
260         use rustc::hir::Mutability::*;
261
262         let from_ty = from.layout().ty;
263         let to_ty = self.layout().ty;
264
265         fn assert_assignable<'a, 'tcx: 'a>(fx: &FunctionCx<'a, 'tcx, impl Backend>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) {
266             match (&from_ty.sty, &to_ty.sty) {
267                 (ty::Ref(_, t, MutImmutable), ty::Ref(_, u, MutImmutable))
268                 | (ty::Ref(_, t, MutMutable), ty::Ref(_, u, MutImmutable))
269                 | (ty::Ref(_, t, MutMutable), ty::Ref(_, u, MutMutable)) => {
270                     assert_assignable(fx, t, u);
271                     // &mut T -> &T is allowed
272                     // &'a T -> &'b T is allowed
273                 }
274                 (ty::Ref(_, _, MutImmutable), ty::Ref(_, _, MutMutable)) => {
275                     panic!("Cant assign value of type {} to place of type {}", from_ty, to_ty)
276                 }
277                 (ty::FnPtr(_), ty::FnPtr(_)) => {
278                     let from_sig = fx.tcx.normalize_erasing_late_bound_regions(
279                         ParamEnv::reveal_all(),
280                         &from_ty.fn_sig(fx.tcx),
281                     );
282                     let to_sig = fx.tcx.normalize_erasing_late_bound_regions(
283                         ParamEnv::reveal_all(),
284                         &to_ty.fn_sig(fx.tcx),
285                     );
286                     assert_eq!(
287                         from_sig, to_sig,
288                         "Can't write fn ptr with incompatible sig {:?} to place with sig {:?}\n\n{:#?}",
289                         from_sig, to_sig, fx,
290                     );
291                     // fn(&T) -> for<'l> fn(&'l T) is allowed
292                 }
293                 (ty::Dynamic(from_traits, _), ty::Dynamic(to_traits, _)) => {
294                     let from_traits = fx.tcx.normalize_erasing_late_bound_regions(
295                         ParamEnv::reveal_all(),
296                         from_traits,
297                     );
298                     let to_traits = fx.tcx.normalize_erasing_late_bound_regions(
299                         ParamEnv::reveal_all(),
300                         to_traits,
301                     );
302                     assert_eq!(
303                         from_traits, to_traits,
304                         "Can't write trait object of incompatible traits {:?} to place with traits {:?}\n\n{:#?}",
305                         from_traits, to_traits, fx,
306                     );
307                     // dyn for<'r> Trait<'r> -> dyn Trait<'_> is allowed
308                 }
309                 _ => {
310                     assert_eq!(
311                         from_ty,
312                         to_ty,
313                         "Can't write value with incompatible type {:?} to place with type {:?}\n\n{:#?}",
314                         from_ty,
315                         to_ty,
316                         fx,
317                     );
318                 }
319             }
320         }
321
322         assert_assignable(fx, from_ty, to_ty);
323
324         let (addr, dst_layout) = match self {
325             CPlace::Var(var, _) => {
326                 let data = from.load_scalar(fx);
327                 fx.bcx.def_var(mir_var(var), data);
328                 return;
329             }
330             CPlace::Addr(addr, None, dst_layout) => (addr, dst_layout),
331             CPlace::Stack(stack_slot, dst_layout) => (
332                 fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0),
333                 dst_layout,
334             ),
335             CPlace::NoPlace(layout) => {
336                 if layout.abi != Abi::Uninhabited {
337                     assert_eq!(layout.size.bytes(), 0, "{:?}", layout);
338                 }
339                 return;
340             }
341             CPlace::Addr(_, _, _) => bug!("Can't write value to unsized place {:?}", self),
342         };
343
344         match from.0 {
345             CValueInner::ByVal(val) => {
346                 fx.bcx.ins().store(MemFlags::new(), val, addr, 0);
347             }
348             CValueInner::ByValPair(value, extra) => {
349                 match dst_layout.abi {
350                     Abi::ScalarPair(ref a_scalar, ref b_scalar) => {
351                         let b_offset = scalar_pair_calculate_b_offset(fx.tcx, a_scalar, b_scalar);
352                         fx.bcx.ins().store(MemFlags::new(), value, addr, 0);
353                         fx.bcx.ins().store(
354                             MemFlags::new(),
355                             extra,
356                             addr,
357                             b_offset,
358                         );
359                     }
360                     _ => bug!(
361                         "Non ScalarPair abi {:?} for ByValPair CValue",
362                         dst_layout.abi
363                     ),
364                 }
365             }
366             CValueInner::ByRef(from_addr) => {
367                 let src_layout = from.1;
368                 let size = dst_layout.size.bytes();
369                 let src_align = src_layout.align.abi.bytes() as u8;
370                 let dst_align = dst_layout.align.abi.bytes() as u8;
371                 fx.bcx.emit_small_memcpy(
372                     fx.module.target_config(),
373                     addr,
374                     from_addr,
375                     size,
376                     dst_align,
377                     src_align,
378                 );
379             }
380         }
381     }
382
383     pub fn place_field(
384         self,
385         fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
386         field: mir::Field,
387     ) -> CPlace<'tcx> {
388         let layout = self.layout();
389         let (base, extra) = self.to_addr_maybe_unsized(fx);
390
391         let (field_ptr, field_layout) = codegen_field(fx, base, layout, field);
392         let extra = if field_layout.is_unsized() {
393             assert!(extra.is_some());
394             extra
395         } else {
396             None
397         };
398         CPlace::Addr(field_ptr, extra, field_layout)
399     }
400
401     pub fn place_index(
402         self,
403         fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
404         index: Value,
405     ) -> CPlace<'tcx> {
406         let (elem_layout, addr) = match self.layout().ty.sty {
407             ty::Array(elem_ty, _) => (fx.layout_of(elem_ty), self.to_addr(fx)),
408             ty::Slice(elem_ty) => (fx.layout_of(elem_ty), self.to_addr_maybe_unsized(fx).0),
409             _ => bug!("place_index({:?})", self.layout().ty),
410         };
411
412         let offset = fx
413             .bcx
414             .ins()
415             .imul_imm(index, elem_layout.size.bytes() as i64);
416
417         CPlace::Addr(fx.bcx.ins().iadd(addr, offset), None, elem_layout)
418     }
419
420     pub fn place_deref(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> CPlace<'tcx> {
421         let inner_layout = fx.layout_of(self.layout().ty.builtin_deref(true).unwrap().ty);
422         if !inner_layout.is_unsized() {
423             CPlace::Addr(self.to_cvalue(fx).load_scalar(fx), None, inner_layout)
424         } else {
425             let (addr, extra) = self.to_cvalue(fx).load_scalar_pair(fx);
426             CPlace::Addr(addr, Some(extra), inner_layout)
427         }
428     }
429
430     pub fn write_place_ref(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>, dest: CPlace<'tcx>) {
431         if !self.layout().is_unsized() {
432             let ptr = CValue::by_val(self.to_addr(fx), dest.layout());
433             dest.write_cvalue(fx, ptr);
434         } else {
435             let (value, extra) = self.to_addr_maybe_unsized(fx);
436             let ptr = CValue::by_val_pair(value, extra.expect("unsized type without metadata"), dest.layout());
437             dest.write_cvalue(fx, ptr);
438         }
439     }
440
441     pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
442         assert!(!self.layout().is_unsized());
443         match self {
444             CPlace::Var(var, _) => CPlace::Var(var, layout),
445             CPlace::Addr(addr, extra, _) => CPlace::Addr(addr, extra, layout),
446             CPlace::Stack(stack_slot, _) => CPlace::Stack(stack_slot, layout),
447             CPlace::NoPlace(_) => {
448                 assert!(layout.size.bytes() == 0);
449                 CPlace::NoPlace(layout)
450             }
451         }
452     }
453
454     pub fn downcast_variant(
455         self,
456         fx: &FunctionCx<'a, 'tcx, impl Backend>,
457         variant: VariantIdx,
458     ) -> Self {
459         let layout = self.layout().for_variant(fx, variant);
460         self.unchecked_cast_to(layout)
461     }
462 }