3 use cranelift::codegen::ir::immediates::Offset32;
5 fn codegen_field<'tcx>(
6 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
9 layout: TyLayout<'tcx>,
11 ) -> (Pointer, TyLayout<'tcx>) {
12 let field_offset = layout.fields.offset(field.index());
13 let field_layout = layout.field(&*fx, field.index());
15 let simple = |fx: &mut FunctionCx<_>| {
17 base.offset_i64(fx, i64::try_from(field_offset.bytes()).unwrap()),
22 if let Some(extra) = extra {
23 if !field_layout.is_unsized() {
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);
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);
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);
45 base.offset_value(fx, offset),
55 fn scalar_pair_calculate_b_offset(tcx: TyCtxt<'_>, a_scalar: &Scalar, b_scalar: &Scalar) -> Offset32 {
56 let b_offset = a_scalar
59 .align_to(b_scalar.value.align(&tcx).abi);
60 Offset32::new(b_offset.bytes().try_into().unwrap())
64 #[derive(Debug, Copy, Clone)]
65 pub struct CValue<'tcx>(CValueInner, TyLayout<'tcx>);
67 #[derive(Debug, Copy, Clone)]
71 ByValPair(Value, Value),
74 impl<'tcx> CValue<'tcx> {
75 pub fn by_ref(ptr: Pointer, layout: TyLayout<'tcx>) -> CValue<'tcx> {
76 CValue(CValueInner::ByRef(ptr), layout)
79 pub fn by_val(value: Value, layout: TyLayout<'tcx>) -> CValue<'tcx> {
80 CValue(CValueInner::ByVal(value), layout)
83 pub fn by_val_pair(value: Value, extra: Value, layout: TyLayout<'tcx>) -> CValue<'tcx> {
84 CValue(CValueInner::ByValPair(value, extra), layout)
87 pub fn layout(&self) -> TyLayout<'tcx> {
91 pub fn force_stack<'a>(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> Pointer {
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);
103 pub fn try_to_addr(self) -> Option<Value> {
105 CValueInner::ByRef(ptr) => {
106 if let Some((base_addr, offset)) = ptr.try_get_addr_and_offset() {
107 if offset == Offset32::new(0) {
116 CValueInner::ByVal(_) | CValueInner::ByValPair(_, _) => None,
120 /// Load a value with layout.abi of scalar
121 pub fn load_scalar<'a>(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> Value {
124 CValueInner::ByRef(ptr) => {
125 let scalar = match layout.abi {
126 layout::Abi::Scalar(ref scalar) => scalar.clone(),
129 let clif_ty = scalar_to_clif_type(fx.tcx, scalar);
130 ptr.load(fx, clif_ty, MemFlags::new())
132 CValueInner::ByVal(value) => value,
133 CValueInner::ByValPair(_, _) => bug!("Please use load_scalar_pair for ByValPair"),
137 /// Load a value pair with layout.abi of scalar pair
138 pub fn load_scalar_pair<'a>(
140 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
141 ) -> (Value, Value) {
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),
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());
156 CValueInner::ByVal(_) => bug!("Please use load_scalar for ByVal"),
157 CValueInner::ByValPair(val1, val2) => (val1, val2),
161 pub fn value_field<'a>(
163 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
167 let ptr = match self.0 {
168 CValueInner::ByRef(ptr) => ptr,
169 _ => bug!("place_field for {:?}", self),
172 let (field_ptr, field_layout) = codegen_field(fx, ptr, None, layout, field);
173 CValue::by_ref(field_ptr, field_layout)
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);
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>,
186 let clif_ty = fx.clif_type(ty).unwrap();
187 let layout = fx.layout_of(ty);
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);
195 .iconst(types::I64, (const_val >> 64) as u64 as i64);
196 fx.bcx.ins().iconcat(lsb, msb)
198 ty::TyKind::Bool => {
200 const_val == 0 || const_val == 1,
201 "Invalid bool 0x{:032X}",
204 fx.bcx.ins().iconst(types::I8, const_val as i64)
206 ty::TyKind::Uint(_) | ty::TyKind::Ref(..) | ty::TyKind::RawPtr(..) => fx
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),
212 "CValue::const_val for non bool/integer/pointer type {:?} is not allowed",
217 CValue::by_val(val, layout)
220 pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
221 CValue(self.0, layout)
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> {
229 layout: TyLayout<'tcx>,
232 #[derive(Debug, Copy, Clone)]
233 pub enum CPlaceInner {
235 Addr(Pointer, Option<Value>),
239 impl<'tcx> CPlace<'tcx> {
240 pub fn layout(&self) -> TyLayout<'tcx> {
244 pub fn inner(&self) -> &CPlaceInner {
248 pub fn no_place(layout: TyLayout<'tcx>) -> CPlace<'tcx> {
250 inner: CPlaceInner::NoPlace,
255 pub fn new_stack_slot(
256 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
259 let layout = fx.layout_of(ty);
260 assert!(!layout.is_unsized());
261 if layout.size.bytes() == 0 {
263 inner: CPlaceInner::NoPlace,
268 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
269 kind: StackSlotKind::ExplicitSlot,
270 size: layout.size.bytes() as u32,
274 inner: CPlaceInner::Addr(Pointer::stack_slot(stack_slot), None),
280 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
282 layout: TyLayout<'tcx>,
285 .declare_var(mir_var(local), fx.clif_type(layout.ty).unwrap());
287 inner: CPlaceInner::Var(local),
292 pub fn for_ptr(ptr: Pointer, layout: TyLayout<'tcx>) -> CPlace<'tcx> {
294 inner: CPlaceInner::Addr(ptr, None),
299 pub fn for_ptr_with_extra(ptr: Pointer, extra: Value, layout: TyLayout<'tcx>) -> CPlace<'tcx> {
301 inner: CPlaceInner::Addr(ptr, Some(extra)),
306 pub fn to_cvalue(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> CValue<'tcx> {
307 let layout = self.layout();
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)
314 CPlaceInner::Addr(ptr, extra) => {
315 assert!(extra.is_none(), "unsized values are not yet supported");
316 CValue::by_ref(ptr, layout)
318 CPlaceInner::NoPlace => CValue::by_ref(
319 Pointer::const_addr(fx, i64::try_from(self.layout.align.pref.bytes()).unwrap()),
325 pub fn to_ptr(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> Pointer {
326 match self.to_ptr_maybe_unsized(fx) {
328 (_, Some(_)) => bug!("Expected sized cplace, found {:?}", self),
332 pub fn to_ptr_maybe_unsized(
334 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
335 ) -> (Pointer, Option<Value>) {
337 CPlaceInner::Addr(ptr, extra) => (ptr, extra),
338 CPlaceInner::NoPlace => {
340 Pointer::const_addr(fx, i64::try_from(self.layout.align.pref.bytes()).unwrap()),
344 CPlaceInner::Var(_) => bug!("Expected CPlace::Addr, found CPlace::Var"),
348 pub fn write_cvalue(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>, from: CValue<'tcx>) {
349 use rustc::hir::Mutability::*;
351 let from_ty = from.layout().ty;
352 let to_ty = self.layout().ty;
354 fn assert_assignable<'tcx>(
355 fx: &FunctionCx<'_, 'tcx, impl Backend>,
359 match (&from_ty.kind, &to_ty.kind) {
360 (ty::Ref(_, t, Immutable), ty::Ref(_, u, Immutable))
361 | (ty::Ref(_, t, Mutable), ty::Ref(_, u, Immutable))
362 | (ty::Ref(_, t, Mutable), ty::Ref(_, u, Mutable)) => {
363 assert_assignable(fx, t, u);
364 // &mut T -> &T is allowed
365 // &'a T -> &'b T is allowed
367 (ty::Ref(_, _, Immutable), ty::Ref(_, _, Mutable)) => panic!(
368 "Cant assign value of type {} to place of type {}",
371 (ty::FnPtr(_), ty::FnPtr(_)) => {
372 let from_sig = fx.tcx.normalize_erasing_late_bound_regions(
373 ParamEnv::reveal_all(),
374 &from_ty.fn_sig(fx.tcx),
376 let to_sig = fx.tcx.normalize_erasing_late_bound_regions(
377 ParamEnv::reveal_all(),
378 &to_ty.fn_sig(fx.tcx),
382 "Can't write fn ptr with incompatible sig {:?} to place with sig {:?}\n\n{:#?}",
383 from_sig, to_sig, fx,
385 // fn(&T) -> for<'l> fn(&'l T) is allowed
387 (ty::Dynamic(from_traits, _), ty::Dynamic(to_traits, _)) => {
390 .normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), from_traits);
393 .normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), to_traits);
395 from_traits, to_traits,
396 "Can't write trait object of incompatible traits {:?} to place with traits {:?}\n\n{:#?}",
397 from_traits, to_traits, fx,
399 // dyn for<'r> Trait<'r> -> dyn Trait<'_> is allowed
405 "Can't write value with incompatible type {:?} to place with type {:?}\n\n{:#?}",
414 assert_assignable(fx, from_ty, to_ty);
416 let dst_layout = self.layout();
417 let to_ptr = match self.inner {
418 CPlaceInner::Var(var) => {
419 let data = from.load_scalar(fx);
420 fx.bcx.set_val_label(data, cranelift::codegen::ir::ValueLabel::from_u32(var.as_u32()));
421 fx.bcx.def_var(mir_var(var), data);
424 CPlaceInner::Addr(ptr, None) => ptr,
425 CPlaceInner::NoPlace => {
426 if dst_layout.abi != Abi::Uninhabited {
427 assert_eq!(dst_layout.size.bytes(), 0, "{:?}", dst_layout);
431 CPlaceInner::Addr(_, Some(_)) => bug!("Can't write value to unsized place {:?}", self),
435 CValueInner::ByVal(val) => {
436 to_ptr.store(fx, val, MemFlags::new());
438 CValueInner::ByValPair(value, extra) => match dst_layout.abi {
439 Abi::ScalarPair(ref a_scalar, ref b_scalar) => {
440 let b_offset = scalar_pair_calculate_b_offset(fx.tcx, a_scalar, b_scalar);
441 to_ptr.store(fx, value, MemFlags::new());
442 to_ptr.offset(fx, b_offset).store(fx, extra, MemFlags::new());
445 "Non ScalarPair abi {:?} for ByValPair CValue",
449 CValueInner::ByRef(from_ptr) => {
450 let from_addr = from_ptr.get_addr(fx);
451 let to_addr = to_ptr.get_addr(fx);
452 let src_layout = from.1;
453 let size = dst_layout.size.bytes();
454 let src_align = src_layout.align.abi.bytes() as u8;
455 let dst_align = dst_layout.align.abi.bytes() as u8;
456 fx.bcx.emit_small_memcpy(
457 fx.module.target_config(),
470 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
473 let layout = self.layout();
474 let (base, extra) = self.to_ptr_maybe_unsized(fx);
476 let (field_ptr, field_layout) = codegen_field(fx, base, extra, layout, field);
477 if field_layout.is_unsized() {
478 CPlace::for_ptr_with_extra(field_ptr, extra.unwrap(), field_layout)
480 CPlace::for_ptr(field_ptr, field_layout)
486 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
489 let (elem_layout, ptr) = match self.layout().ty.kind {
490 ty::Array(elem_ty, _) => (fx.layout_of(elem_ty), self.to_ptr(fx)),
491 ty::Slice(elem_ty) => (fx.layout_of(elem_ty), self.to_ptr_maybe_unsized(fx).0),
492 _ => bug!("place_index({:?})", self.layout().ty),
498 .imul_imm(index, elem_layout.size.bytes() as i64);
500 CPlace::for_ptr(ptr.offset_value(fx, offset), elem_layout)
503 pub fn place_deref(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> CPlace<'tcx> {
504 let inner_layout = fx.layout_of(self.layout().ty.builtin_deref(true).unwrap().ty);
505 if has_ptr_meta(fx.tcx, inner_layout.ty) {
506 let (addr, extra) = self.to_cvalue(fx).load_scalar_pair(fx);
507 CPlace::for_ptr_with_extra(Pointer::new(addr), extra, inner_layout)
509 CPlace::for_ptr(Pointer::new(self.to_cvalue(fx).load_scalar(fx)), inner_layout)
513 pub fn write_place_ref(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>, dest: CPlace<'tcx>) {
514 if has_ptr_meta(fx.tcx, self.layout().ty) {
515 let (ptr, extra) = self.to_ptr_maybe_unsized(fx);
516 let ptr = CValue::by_val_pair(
518 extra.expect("unsized type without metadata"),
521 dest.write_cvalue(fx, ptr);
523 let ptr = CValue::by_val(self.to_ptr(fx).get_addr(fx), dest.layout());
524 dest.write_cvalue(fx, ptr);
528 pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
529 assert!(!self.layout().is_unsized());
531 CPlaceInner::NoPlace => {
532 assert!(layout.size.bytes() == 0);
542 pub fn downcast_variant(
544 fx: &FunctionCx<'_, 'tcx, impl Backend>,
547 let layout = self.layout().for_variant(fx, variant);
548 self.unchecked_cast_to(layout)