]> git.lizzy.rs Git - rust.git/blob - src/value_and_place.rs
Add clif ir comment for write_cvalue
[rust.git] / src / value_and_place.rs
1 use crate::prelude::*;
2
3 use cranelift_codegen::ir::immediates::Offset32;
4
5 fn codegen_field<'tcx>(
6     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
7     base: Pointer,
8     extra: Option<Value>,
9     layout: TyLayout<'tcx>,
10     field: mir::Field,
11 ) -> (Pointer, TyLayout<'tcx>) {
12     let field_offset = layout.fields.offset(field.index());
13     let field_layout = layout.field(&*fx, field.index());
14
15     let simple = |fx: &mut FunctionCx<_>| {
16         (
17             base.offset_i64(fx, i64::try_from(field_offset.bytes()).unwrap()),
18             field_layout,
19         )
20     };
21
22     if let Some(extra) = extra {
23         if !field_layout.is_unsized() {
24             return simple(fx);
25         }
26         match field_layout.ty.kind {
27             ty::Slice(..) | ty::Str | ty::Foreign(..) => return simple(fx),
28             ty::Adt(def, _) if def.repr.packed() => {
29                 assert_eq!(layout.align.abi.bytes(), 1);
30                 return simple(fx);
31             }
32             _ => {
33                 // We have to align the offset for DST's
34                 let unaligned_offset = field_offset.bytes();
35                 let (_, unsized_align) = crate::unsize::size_and_align_of_dst(fx, field_layout.ty, extra);
36
37                 let one = fx.bcx.ins().iconst(pointer_ty(fx.tcx), 1);
38                 let align_sub_1 = fx.bcx.ins().isub(unsized_align, one);
39                 let and_lhs = fx.bcx.ins().iadd_imm(align_sub_1, unaligned_offset as i64);
40                 let zero = fx.bcx.ins().iconst(pointer_ty(fx.tcx), 0);
41                 let and_rhs = fx.bcx.ins().isub(zero, unsized_align);
42                 let offset = fx.bcx.ins().band(and_lhs, and_rhs);
43
44                 (
45                     base.offset_value(fx, offset),
46                     field_layout,
47                 )
48             }
49         }
50     } else {
51         simple(fx)
52     }
53 }
54
55 fn scalar_pair_calculate_b_offset(tcx: TyCtxt<'_>, a_scalar: &Scalar, b_scalar: &Scalar) -> Offset32 {
56     let b_offset = a_scalar
57         .value
58         .size(&tcx)
59         .align_to(b_scalar.value.align(&tcx).abi);
60     Offset32::new(b_offset.bytes().try_into().unwrap())
61 }
62
63 /// A read-only value
64 #[derive(Debug, Copy, Clone)]
65 pub struct CValue<'tcx>(CValueInner, TyLayout<'tcx>);
66
67 #[derive(Debug, Copy, Clone)]
68 enum CValueInner {
69     ByRef(Pointer),
70     ByVal(Value),
71     ByValPair(Value, Value),
72 }
73
74 impl<'tcx> CValue<'tcx> {
75     pub fn by_ref(ptr: Pointer, layout: TyLayout<'tcx>) -> CValue<'tcx> {
76         CValue(CValueInner::ByRef(ptr), layout)
77     }
78
79     pub fn by_val(value: Value, layout: TyLayout<'tcx>) -> CValue<'tcx> {
80         CValue(CValueInner::ByVal(value), layout)
81     }
82
83     pub fn by_val_pair(value: Value, extra: Value, layout: TyLayout<'tcx>) -> CValue<'tcx> {
84         CValue(CValueInner::ByValPair(value, extra), layout)
85     }
86
87     pub fn layout(&self) -> TyLayout<'tcx> {
88         self.1
89     }
90
91     pub fn force_stack<'a>(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> Pointer {
92         let layout = self.1;
93         match self.0 {
94             CValueInner::ByRef(ptr) => ptr,
95             CValueInner::ByVal(_) | CValueInner::ByValPair(_, _) => {
96                 let cplace = CPlace::new_stack_slot(fx, layout.ty);
97                 cplace.write_cvalue(fx, self);
98                 cplace.to_ptr(fx)
99             }
100         }
101     }
102
103     pub fn try_to_addr(self) -> Option<Value> {
104         match self.0 {
105             CValueInner::ByRef(ptr) => {
106                 if let Some((base_addr, offset)) = ptr.try_get_addr_and_offset() {
107                     if offset == Offset32::new(0) {
108                         Some(base_addr)
109                     } else {
110                         None
111                     }
112                 } else {
113                     None
114                 }
115             }
116             CValueInner::ByVal(_) | CValueInner::ByValPair(_, _) => None,
117         }
118     }
119
120     /// Load a value with layout.abi of scalar
121     pub fn load_scalar<'a>(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> Value {
122         let layout = self.1;
123         match self.0 {
124             CValueInner::ByRef(ptr) => {
125                 let scalar = match layout.abi {
126                     layout::Abi::Scalar(ref scalar) => scalar.clone(),
127                     _ => unreachable!(),
128                 };
129                 let clif_ty = scalar_to_clif_type(fx.tcx, scalar);
130                 ptr.load(fx, clif_ty, MemFlags::new())
131             }
132             CValueInner::ByVal(value) => value,
133             CValueInner::ByValPair(_, _) => bug!("Please use load_scalar_pair for ByValPair"),
134         }
135     }
136
137     /// Load a value pair with layout.abi of scalar pair
138     pub fn load_scalar_pair<'a>(
139         self,
140         fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
141     ) -> (Value, Value) {
142         let layout = self.1;
143         match self.0 {
144             CValueInner::ByRef(ptr) => {
145                 let (a_scalar, b_scalar) = match &layout.abi {
146                     layout::Abi::ScalarPair(a, b) => (a, b),
147                     _ => unreachable!("load_scalar_pair({:?})", self),
148                 };
149                 let b_offset = scalar_pair_calculate_b_offset(fx.tcx, a_scalar, b_scalar);
150                 let clif_ty1 = scalar_to_clif_type(fx.tcx, a_scalar.clone());
151                 let clif_ty2 = scalar_to_clif_type(fx.tcx, b_scalar.clone());
152                 let val1 = ptr.load(fx, clif_ty1, MemFlags::new());
153                 let val2 = ptr.offset(fx, b_offset).load(fx, clif_ty2, MemFlags::new());
154                 (val1, val2)
155             }
156             CValueInner::ByVal(_) => bug!("Please use load_scalar for ByVal"),
157             CValueInner::ByValPair(val1, val2) => (val1, val2),
158         }
159     }
160
161     pub fn value_field<'a>(
162         self,
163         fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
164         field: mir::Field,
165     ) -> CValue<'tcx> {
166         let layout = self.1;
167         let ptr = match self.0 {
168             CValueInner::ByRef(ptr) => ptr,
169             _ => bug!("place_field for {:?}", self),
170         };
171
172         let (field_ptr, field_layout) = codegen_field(fx, ptr, None, layout, field);
173         CValue::by_ref(field_ptr, field_layout)
174     }
175
176     pub fn unsize_value<'a>(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>, dest: CPlace<'tcx>) {
177         crate::unsize::coerce_unsized_into(fx, self, dest);
178     }
179
180     /// If `ty` is signed, `const_val` must already be sign extended.
181     pub fn const_val<'a>(
182         fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
183         ty: Ty<'tcx>,
184         const_val: u128,
185     ) -> CValue<'tcx> {
186         let clif_ty = fx.clif_type(ty).unwrap();
187         let layout = fx.layout_of(ty);
188
189         let val = match ty.kind {
190             ty::TyKind::Uint(UintTy::U128) | ty::TyKind::Int(IntTy::I128) => {
191                 let lsb = fx.bcx.ins().iconst(types::I64, const_val as u64 as i64);
192                 let msb = fx
193                     .bcx
194                     .ins()
195                     .iconst(types::I64, (const_val >> 64) as u64 as i64);
196                 fx.bcx.ins().iconcat(lsb, msb)
197             }
198             ty::TyKind::Bool => {
199                 assert!(
200                     const_val == 0 || const_val == 1,
201                     "Invalid bool 0x{:032X}",
202                     const_val
203                 );
204                 fx.bcx.ins().iconst(types::I8, const_val as i64)
205             }
206             ty::TyKind::Uint(_) | ty::TyKind::Ref(..) | ty::TyKind::RawPtr(..) => fx
207                 .bcx
208                 .ins()
209                 .iconst(clif_ty, u64::try_from(const_val).expect("uint") as i64),
210             ty::TyKind::Int(_) => fx.bcx.ins().iconst(clif_ty, const_val as i128 as i64),
211             _ => panic!(
212                 "CValue::const_val for non bool/integer/pointer type {:?} is not allowed",
213                 ty
214             ),
215         };
216
217         CValue::by_val(val, layout)
218     }
219
220     pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
221         CValue(self.0, layout)
222     }
223 }
224
225 /// A place where you can write a value to or read a value from
226 #[derive(Debug, Copy, Clone)]
227 pub struct CPlace<'tcx> {
228     inner: CPlaceInner,
229     layout: TyLayout<'tcx>,
230 }
231
232 #[derive(Debug, Copy, Clone)]
233 pub enum CPlaceInner {
234     Var(Local),
235     Addr(Pointer, Option<Value>),
236     NoPlace,
237 }
238
239 impl<'tcx> CPlace<'tcx> {
240     pub fn layout(&self) -> TyLayout<'tcx> {
241         self.layout
242     }
243
244     pub fn inner(&self) -> &CPlaceInner {
245         &self.inner
246     }
247
248     pub fn no_place(layout: TyLayout<'tcx>) -> CPlace<'tcx> {
249         CPlace {
250             inner: CPlaceInner::NoPlace,
251             layout,
252         }
253     }
254
255     pub fn new_stack_slot(
256         fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
257         ty: Ty<'tcx>,
258     ) -> CPlace<'tcx> {
259         let layout = fx.layout_of(ty);
260         assert!(!layout.is_unsized());
261         if layout.size.bytes() == 0 {
262             return CPlace {
263                 inner: CPlaceInner::NoPlace,
264                 layout,
265             };
266         }
267
268         let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
269             kind: StackSlotKind::ExplicitSlot,
270             size: layout.size.bytes() as u32,
271             offset: None,
272         });
273         CPlace {
274             inner: CPlaceInner::Addr(Pointer::stack_slot(stack_slot), None),
275             layout,
276         }
277     }
278
279     pub fn new_var(
280         fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
281         local: Local,
282         layout: TyLayout<'tcx>,
283     ) -> CPlace<'tcx> {
284         fx.bcx
285             .declare_var(mir_var(local), fx.clif_type(layout.ty).unwrap());
286         CPlace {
287             inner: CPlaceInner::Var(local),
288             layout,
289         }
290     }
291
292     pub fn for_ptr(ptr: Pointer, layout: TyLayout<'tcx>) -> CPlace<'tcx> {
293         CPlace {
294             inner: CPlaceInner::Addr(ptr, None),
295             layout,
296         }
297     }
298
299     pub fn for_ptr_with_extra(ptr: Pointer, extra: Value, layout: TyLayout<'tcx>) -> CPlace<'tcx> {
300         CPlace {
301             inner: CPlaceInner::Addr(ptr, Some(extra)),
302             layout,
303         }
304     }
305
306     pub fn to_cvalue(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> CValue<'tcx> {
307         let layout = self.layout();
308         match self.inner {
309             CPlaceInner::Var(var) => {
310                 let val = fx.bcx.use_var(mir_var(var));
311                 fx.bcx.set_val_label(val, cranelift_codegen::ir::ValueLabel::from_u32(var.as_u32()));
312                 CValue::by_val(val, layout)
313             }
314             CPlaceInner::Addr(ptr, extra) => {
315                 assert!(extra.is_none(), "unsized values are not yet supported");
316                 CValue::by_ref(ptr, layout)
317             }
318             CPlaceInner::NoPlace => CValue::by_ref(
319                 Pointer::const_addr(fx, i64::try_from(self.layout.align.pref.bytes()).unwrap()),
320                 layout,
321             ),
322         }
323     }
324
325     pub fn to_ptr(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> Pointer {
326         match self.to_ptr_maybe_unsized(fx) {
327             (ptr, None) => ptr,
328             (_, Some(_)) => bug!("Expected sized cplace, found {:?}", self),
329         }
330     }
331
332     pub fn to_ptr_maybe_unsized(
333         self,
334         fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
335     ) -> (Pointer, Option<Value>) {
336         match self.inner {
337             CPlaceInner::Addr(ptr, extra) => (ptr, extra),
338             CPlaceInner::NoPlace => {
339                 (
340                     Pointer::const_addr(fx, i64::try_from(self.layout.align.pref.bytes()).unwrap()),
341                     None,
342                 )
343             }
344             CPlaceInner::Var(_) => bug!("Expected CPlace::Addr, found CPlace::Var"),
345         }
346     }
347
348     pub fn write_cvalue(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>, from: CValue<'tcx>) {
349         #[cfg(debug_assertions)]
350         {
351             use cranelift_codegen::cursor::{Cursor, CursorPosition};
352             let cur_ebb = match fx.bcx.cursor().position() {
353                 CursorPosition::After(ebb) => ebb,
354                 _ => unreachable!(),
355             };
356             fx.add_comment(
357                 fx.bcx.func.layout.last_inst(cur_ebb).unwrap(),
358                 format!("write_cvalue: {:?} <- {:?}",self, from),
359             );
360         }
361
362         let from_ty = from.layout().ty;
363         let to_ty = self.layout().ty;
364
365         fn assert_assignable<'tcx>(
366             fx: &FunctionCx<'_, 'tcx, impl Backend>,
367             from_ty: Ty<'tcx>,
368             to_ty: Ty<'tcx>,
369         ) {
370             match (&from_ty.kind, &to_ty.kind) {
371                 (ty::Ref(_, t, Mutability::Not), ty::Ref(_, u, Mutability::Not))
372                 | (ty::Ref(_, t, Mutability::Mut), ty::Ref(_, u, Mutability::Not))
373                 | (ty::Ref(_, t, Mutability::Mut), ty::Ref(_, u, Mutability::Mut)) => {
374                     assert_assignable(fx, t, u);
375                     // &mut T -> &T is allowed
376                     // &'a T -> &'b T is allowed
377                 }
378                 (ty::Ref(_, _, Mutability::Not), ty::Ref(_, _, Mutability::Mut)) => panic!(
379                     "Cant assign value of type {} to place of type {}",
380                     from_ty, to_ty
381                 ),
382                 (ty::FnPtr(_), ty::FnPtr(_)) => {
383                     let from_sig = fx.tcx.normalize_erasing_late_bound_regions(
384                         ParamEnv::reveal_all(),
385                         &from_ty.fn_sig(fx.tcx),
386                     );
387                     let to_sig = fx.tcx.normalize_erasing_late_bound_regions(
388                         ParamEnv::reveal_all(),
389                         &to_ty.fn_sig(fx.tcx),
390                     );
391                     assert_eq!(
392                         from_sig, to_sig,
393                         "Can't write fn ptr with incompatible sig {:?} to place with sig {:?}\n\n{:#?}",
394                         from_sig, to_sig, fx,
395                     );
396                     // fn(&T) -> for<'l> fn(&'l T) is allowed
397                 }
398                 (ty::Dynamic(from_traits, _), ty::Dynamic(to_traits, _)) => {
399                     let from_traits = fx
400                         .tcx
401                         .normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), from_traits);
402                     let to_traits = fx
403                         .tcx
404                         .normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), to_traits);
405                     assert_eq!(
406                         from_traits, to_traits,
407                         "Can't write trait object of incompatible traits {:?} to place with traits {:?}\n\n{:#?}",
408                         from_traits, to_traits, fx,
409                     );
410                     // dyn for<'r> Trait<'r> -> dyn Trait<'_> is allowed
411                 }
412                 _ => {
413                     assert_eq!(
414                         from_ty,
415                         to_ty,
416                         "Can't write value with incompatible type {:?} to place with type {:?}\n\n{:#?}",
417                         from_ty,
418                         to_ty,
419                         fx,
420                     );
421                 }
422             }
423         }
424
425         assert_assignable(fx, from_ty, to_ty);
426
427         let dst_layout = self.layout();
428         let to_ptr = match self.inner {
429             CPlaceInner::Var(var) => {
430                 let data = from.load_scalar(fx);
431                 fx.bcx.set_val_label(data, cranelift_codegen::ir::ValueLabel::from_u32(var.as_u32()));
432                 fx.bcx.def_var(mir_var(var), data);
433                 return;
434             }
435             CPlaceInner::Addr(ptr, None) => ptr,
436             CPlaceInner::NoPlace => {
437                 if dst_layout.abi != Abi::Uninhabited {
438                     assert_eq!(dst_layout.size.bytes(), 0, "{:?}", dst_layout);
439                 }
440                 return;
441             }
442             CPlaceInner::Addr(_, Some(_)) => bug!("Can't write value to unsized place {:?}", self),
443         };
444
445         match from.0 {
446             CValueInner::ByVal(val) => {
447                 to_ptr.store(fx, val, MemFlags::new());
448             }
449             CValueInner::ByValPair(value, extra) => match dst_layout.abi {
450                 Abi::ScalarPair(ref a_scalar, ref b_scalar) => {
451                     let b_offset = scalar_pair_calculate_b_offset(fx.tcx, a_scalar, b_scalar);
452                     to_ptr.store(fx, value, MemFlags::new());
453                     to_ptr.offset(fx, b_offset).store(fx, extra, MemFlags::new());
454                 }
455                 _ => bug!(
456                     "Non ScalarPair abi {:?} for ByValPair CValue",
457                     dst_layout.abi
458                 ),
459             },
460             CValueInner::ByRef(from_ptr) => {
461                 let from_addr = from_ptr.get_addr(fx);
462                 let to_addr = to_ptr.get_addr(fx);
463                 let src_layout = from.1;
464                 let size = dst_layout.size.bytes();
465                 let src_align = src_layout.align.abi.bytes() as u8;
466                 let dst_align = dst_layout.align.abi.bytes() as u8;
467                 fx.bcx.emit_small_memcpy(
468                     fx.module.target_config(),
469                     to_addr,
470                     from_addr,
471                     size,
472                     dst_align,
473                     src_align,
474                 );
475             }
476         }
477     }
478
479     pub fn place_field(
480         self,
481         fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
482         field: mir::Field,
483     ) -> CPlace<'tcx> {
484         let layout = self.layout();
485         let (base, extra) = self.to_ptr_maybe_unsized(fx);
486
487         let (field_ptr, field_layout) = codegen_field(fx, base, extra, layout, field);
488         if field_layout.is_unsized() {
489             CPlace::for_ptr_with_extra(field_ptr, extra.unwrap(), field_layout)
490         } else {
491             CPlace::for_ptr(field_ptr, field_layout)
492         }
493     }
494
495     pub fn place_index(
496         self,
497         fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
498         index: Value,
499     ) -> CPlace<'tcx> {
500         let (elem_layout, ptr) = match self.layout().ty.kind {
501             ty::Array(elem_ty, _) => (fx.layout_of(elem_ty), self.to_ptr(fx)),
502             ty::Slice(elem_ty) => (fx.layout_of(elem_ty), self.to_ptr_maybe_unsized(fx).0),
503             _ => bug!("place_index({:?})", self.layout().ty),
504         };
505
506         let offset = fx
507             .bcx
508             .ins()
509             .imul_imm(index, elem_layout.size.bytes() as i64);
510
511         CPlace::for_ptr(ptr.offset_value(fx, offset), elem_layout)
512     }
513
514     pub fn place_deref(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> CPlace<'tcx> {
515         let inner_layout = fx.layout_of(self.layout().ty.builtin_deref(true).unwrap().ty);
516         if has_ptr_meta(fx.tcx, inner_layout.ty) {
517             let (addr, extra) = self.to_cvalue(fx).load_scalar_pair(fx);
518             CPlace::for_ptr_with_extra(Pointer::new(addr), extra, inner_layout)
519         } else {
520             CPlace::for_ptr(Pointer::new(self.to_cvalue(fx).load_scalar(fx)), inner_layout)
521         }
522     }
523
524     pub fn write_place_ref(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>, dest: CPlace<'tcx>) {
525         if has_ptr_meta(fx.tcx, self.layout().ty) {
526             let (ptr, extra) = self.to_ptr_maybe_unsized(fx);
527             let ptr = CValue::by_val_pair(
528                 ptr.get_addr(fx),
529                 extra.expect("unsized type without metadata"),
530                 dest.layout(),
531             );
532             dest.write_cvalue(fx, ptr);
533         } else {
534             let ptr = CValue::by_val(self.to_ptr(fx).get_addr(fx), dest.layout());
535             dest.write_cvalue(fx, ptr);
536         }
537     }
538
539     pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
540         assert!(!self.layout().is_unsized());
541         match self.inner {
542             CPlaceInner::NoPlace => {
543                 assert!(layout.size.bytes() == 0);
544             }
545             _ => {}
546         }
547         CPlace {
548             inner: self.inner,
549             layout,
550         }
551     }
552
553     pub fn downcast_variant(
554         self,
555         fx: &FunctionCx<'_, 'tcx, impl Backend>,
556         variant: VariantIdx,
557     ) -> Self {
558         let layout = self.layout().for_variant(fx, variant);
559         self.unchecked_cast_to(layout)
560     }
561 }