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