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