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, 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> {
92 pub fn force_stack<'a>(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> Pointer {
95 CValueInner::ByRef(ptr) => ptr,
96 CValueInner::ByVal(_) | CValueInner::ByValPair(_, _) => {
97 let cplace = CPlace::new_stack_slot(fx, layout);
98 cplace.write_cvalue(fx, self);
104 pub fn try_to_addr(self) -> Option<Value> {
106 CValueInner::ByRef(ptr) => {
107 if let Some((base_addr, offset)) = ptr.try_get_addr_and_offset() {
108 if offset == Offset32::new(0) {
117 CValueInner::ByVal(_) | CValueInner::ByValPair(_, _) => None,
121 /// Load a value with layout.abi of scalar
122 pub fn load_scalar<'a>(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> Value {
125 CValueInner::ByRef(ptr) => {
126 let clif_ty = match layout.abi {
127 layout::Abi::Scalar(ref scalar) => scalar_to_clif_type(fx.tcx, scalar.clone()),
128 layout::Abi::Vector { ref element, count } => {
129 scalar_to_clif_type(fx.tcx, element.clone())
130 .by(u16::try_from(count).unwrap()).unwrap()
134 ptr.load(fx, clif_ty, MemFlags::new())
136 CValueInner::ByVal(value) => value,
137 CValueInner::ByValPair(_, _) => bug!("Please use load_scalar_pair for ByValPair"),
141 /// Load a value pair with layout.abi of scalar pair
142 pub fn load_scalar_pair<'a>(
144 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
145 ) -> (Value, Value) {
148 CValueInner::ByRef(ptr) => {
149 let (a_scalar, b_scalar) = match &layout.abi {
150 layout::Abi::ScalarPair(a, b) => (a, b),
151 _ => unreachable!("load_scalar_pair({:?})", self),
153 let b_offset = scalar_pair_calculate_b_offset(fx.tcx, a_scalar, b_scalar);
154 let clif_ty1 = scalar_to_clif_type(fx.tcx, a_scalar.clone());
155 let clif_ty2 = scalar_to_clif_type(fx.tcx, b_scalar.clone());
156 let val1 = ptr.load(fx, clif_ty1, MemFlags::new());
157 let val2 = ptr.offset(fx, b_offset).load(fx, clif_ty2, MemFlags::new());
160 CValueInner::ByVal(_) => bug!("Please use load_scalar for ByVal"),
161 CValueInner::ByValPair(val1, val2) => (val1, val2),
165 pub fn value_field<'a>(
167 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
172 CValueInner::ByVal(val) => {
174 layout::Abi::Vector { element: _, count } => {
175 let count = u8::try_from(count).expect("SIMD type with more than 255 lanes???");
176 let field = u8::try_from(field.index()).unwrap();
177 assert!(field < count);
178 let lane = fx.bcx.ins().extractlane(val, field);
179 let field_layout = layout.field(&*fx, usize::from(field));
180 CValue::by_val(lane, field_layout)
182 _ => unreachable!("value_field for ByVal with abi {:?}", layout.abi),
185 CValueInner::ByRef(ptr) => {
186 let (field_ptr, field_layout) = codegen_field(fx, ptr, None, layout, field);
187 CValue::by_ref(field_ptr, field_layout)
189 _ => bug!("place_field for {:?}", self),
193 pub fn unsize_value<'a>(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>, dest: CPlace<'tcx>) {
194 crate::unsize::coerce_unsized_into(fx, self, dest);
197 /// If `ty` is signed, `const_val` must already be sign extended.
198 pub fn const_val<'a>(
199 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
200 layout: TyLayout<'tcx>,
203 let clif_ty = fx.clif_type(layout.ty).unwrap();
205 let val = match layout.ty.kind {
206 ty::TyKind::Uint(UintTy::U128) | ty::TyKind::Int(IntTy::I128) => {
207 let lsb = fx.bcx.ins().iconst(types::I64, const_val as u64 as i64);
211 .iconst(types::I64, (const_val >> 64) as u64 as i64);
212 fx.bcx.ins().iconcat(lsb, msb)
214 ty::TyKind::Bool => {
216 const_val == 0 || const_val == 1,
217 "Invalid bool 0x{:032X}",
220 fx.bcx.ins().iconst(types::I8, const_val as i64)
222 ty::TyKind::Uint(_) | ty::TyKind::Ref(..) | ty::TyKind::RawPtr(..) => fx
225 .iconst(clif_ty, u64::try_from(const_val).expect("uint") as i64),
226 ty::TyKind::Int(_) => fx.bcx.ins().iconst(clif_ty, const_val as i128 as i64),
228 "CValue::const_val for non bool/integer/pointer type {:?} is not allowed",
233 CValue::by_val(val, layout)
236 pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
237 CValue(self.0, layout)
241 /// A place where you can write a value to or read a value from
242 #[derive(Debug, Copy, Clone)]
243 pub struct CPlace<'tcx> {
245 layout: TyLayout<'tcx>,
248 #[derive(Debug, Copy, Clone)]
249 pub enum CPlaceInner {
251 Addr(Pointer, Option<Value>),
255 impl<'tcx> CPlace<'tcx> {
256 pub fn layout(&self) -> TyLayout<'tcx> {
260 pub fn inner(&self) -> &CPlaceInner {
264 pub fn no_place(layout: TyLayout<'tcx>) -> CPlace<'tcx> {
266 inner: CPlaceInner::NoPlace,
271 pub fn new_stack_slot(
272 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
273 layout: TyLayout<'tcx>,
275 assert!(!layout.is_unsized());
276 if layout.size.bytes() == 0 {
278 inner: CPlaceInner::NoPlace,
283 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
284 kind: StackSlotKind::ExplicitSlot,
285 size: layout.size.bytes() as u32,
289 inner: CPlaceInner::Addr(Pointer::stack_slot(stack_slot), None),
295 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
297 layout: TyLayout<'tcx>,
300 .declare_var(mir_var(local), fx.clif_type(layout.ty).unwrap());
302 inner: CPlaceInner::Var(local),
307 pub fn for_ptr(ptr: Pointer, layout: TyLayout<'tcx>) -> CPlace<'tcx> {
309 inner: CPlaceInner::Addr(ptr, None),
314 pub fn for_ptr_with_extra(ptr: Pointer, extra: Value, layout: TyLayout<'tcx>) -> CPlace<'tcx> {
316 inner: CPlaceInner::Addr(ptr, Some(extra)),
321 pub fn to_cvalue(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> CValue<'tcx> {
322 let layout = self.layout();
324 CPlaceInner::Var(var) => {
325 let val = fx.bcx.use_var(mir_var(var));
326 fx.bcx.set_val_label(val, cranelift_codegen::ir::ValueLabel::from_u32(var.as_u32()));
327 CValue::by_val(val, layout)
329 CPlaceInner::Addr(ptr, extra) => {
330 assert!(extra.is_none(), "unsized values are not yet supported");
331 CValue::by_ref(ptr, layout)
333 CPlaceInner::NoPlace => CValue::by_ref(
334 Pointer::const_addr(fx, i64::try_from(self.layout.align.pref.bytes()).unwrap()),
340 pub fn to_ptr(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> Pointer {
341 match self.to_ptr_maybe_unsized(fx) {
343 (_, Some(_)) => bug!("Expected sized cplace, found {:?}", self),
347 pub fn to_ptr_maybe_unsized(
349 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
350 ) -> (Pointer, Option<Value>) {
352 CPlaceInner::Addr(ptr, extra) => (ptr, extra),
353 CPlaceInner::NoPlace => {
355 Pointer::const_addr(fx, i64::try_from(self.layout.align.pref.bytes()).unwrap()),
359 CPlaceInner::Var(_) => bug!("Expected CPlace::Addr, found CPlace::Var"),
363 pub fn write_cvalue(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>, from: CValue<'tcx>) {
364 #[cfg(debug_assertions)]
366 use cranelift_codegen::cursor::{Cursor, CursorPosition};
367 let cur_ebb = match fx.bcx.cursor().position() {
368 CursorPosition::After(ebb) => ebb,
372 fx.bcx.func.layout.last_inst(cur_ebb).unwrap(),
373 format!("write_cvalue: {:?} <- {:?}",self, from),
377 let from_ty = from.layout().ty;
378 let to_ty = self.layout().ty;
380 fn assert_assignable<'tcx>(
381 fx: &FunctionCx<'_, 'tcx, impl Backend>,
385 match (&from_ty.kind, &to_ty.kind) {
386 (ty::Ref(_, t, Mutability::Not), ty::Ref(_, u, Mutability::Not))
387 | (ty::Ref(_, t, Mutability::Mut), ty::Ref(_, u, Mutability::Not))
388 | (ty::Ref(_, t, Mutability::Mut), ty::Ref(_, u, Mutability::Mut)) => {
389 assert_assignable(fx, t, u);
390 // &mut T -> &T is allowed
391 // &'a T -> &'b T is allowed
393 (ty::Ref(_, _, Mutability::Not), ty::Ref(_, _, Mutability::Mut)) => panic!(
394 "Cant assign value of type {} to place of type {}",
397 (ty::FnPtr(_), ty::FnPtr(_)) => {
398 let from_sig = fx.tcx.normalize_erasing_late_bound_regions(
399 ParamEnv::reveal_all(),
400 &from_ty.fn_sig(fx.tcx),
402 let to_sig = fx.tcx.normalize_erasing_late_bound_regions(
403 ParamEnv::reveal_all(),
404 &to_ty.fn_sig(fx.tcx),
408 "Can't write fn ptr with incompatible sig {:?} to place with sig {:?}\n\n{:#?}",
409 from_sig, to_sig, fx,
411 // fn(&T) -> for<'l> fn(&'l T) is allowed
413 (ty::Dynamic(from_traits, _), ty::Dynamic(to_traits, _)) => {
416 .normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), from_traits);
419 .normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), to_traits);
421 from_traits, to_traits,
422 "Can't write trait object of incompatible traits {:?} to place with traits {:?}\n\n{:#?}",
423 from_traits, to_traits, fx,
425 // dyn for<'r> Trait<'r> -> dyn Trait<'_> is allowed
431 "Can't write value with incompatible type {:?} to place with type {:?}\n\n{:#?}",
440 assert_assignable(fx, from_ty, to_ty);
442 let dst_layout = self.layout();
443 let to_ptr = match self.inner {
444 CPlaceInner::Var(var) => {
445 let data = from.load_scalar(fx);
446 fx.bcx.set_val_label(data, cranelift_codegen::ir::ValueLabel::from_u32(var.as_u32()));
447 fx.bcx.def_var(mir_var(var), data);
450 CPlaceInner::Addr(ptr, None) => ptr,
451 CPlaceInner::NoPlace => {
452 if dst_layout.abi != Abi::Uninhabited {
453 assert_eq!(dst_layout.size.bytes(), 0, "{:?}", dst_layout);
457 CPlaceInner::Addr(_, Some(_)) => bug!("Can't write value to unsized place {:?}", self),
460 match self.layout().abi {
461 // FIXME make Abi::Vector work too
463 let val = from.load_scalar(fx);
464 to_ptr.store(fx, val, MemFlags::new());
467 Abi::ScalarPair(ref a_scalar, ref b_scalar) => {
468 let (value, extra) = from.load_scalar_pair(fx);
469 let b_offset = scalar_pair_calculate_b_offset(fx.tcx, a_scalar, b_scalar);
470 to_ptr.store(fx, value, MemFlags::new());
471 to_ptr.offset(fx, b_offset).store(fx, extra, MemFlags::new());
478 CValueInner::ByVal(val) => {
479 to_ptr.store(fx, val, MemFlags::new());
481 CValueInner::ByValPair(_, _) => {
483 "Non ScalarPair abi {:?} for ByValPair CValue",
487 CValueInner::ByRef(from_ptr) => {
488 let from_addr = from_ptr.get_addr(fx);
489 let to_addr = to_ptr.get_addr(fx);
490 let src_layout = from.1;
491 let size = dst_layout.size.bytes();
492 let src_align = src_layout.align.abi.bytes() as u8;
493 let dst_align = dst_layout.align.abi.bytes() as u8;
494 fx.bcx.emit_small_memcpy(
495 fx.module.target_config(),
508 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
511 let layout = self.layout();
512 let (base, extra) = self.to_ptr_maybe_unsized(fx);
514 let (field_ptr, field_layout) = codegen_field(fx, base, extra, layout, field);
515 if field_layout.is_unsized() {
516 CPlace::for_ptr_with_extra(field_ptr, extra.unwrap(), field_layout)
518 CPlace::for_ptr(field_ptr, field_layout)
524 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
527 let (elem_layout, ptr) = match self.layout().ty.kind {
528 ty::Array(elem_ty, _) => (fx.layout_of(elem_ty), self.to_ptr(fx)),
529 ty::Slice(elem_ty) => (fx.layout_of(elem_ty), self.to_ptr_maybe_unsized(fx).0),
530 _ => bug!("place_index({:?})", self.layout().ty),
536 .imul_imm(index, elem_layout.size.bytes() as i64);
538 CPlace::for_ptr(ptr.offset_value(fx, offset), elem_layout)
541 pub fn place_deref(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> CPlace<'tcx> {
542 let inner_layout = fx.layout_of(self.layout().ty.builtin_deref(true).unwrap().ty);
543 if has_ptr_meta(fx.tcx, inner_layout.ty) {
544 let (addr, extra) = self.to_cvalue(fx).load_scalar_pair(fx);
545 CPlace::for_ptr_with_extra(Pointer::new(addr), extra, inner_layout)
547 CPlace::for_ptr(Pointer::new(self.to_cvalue(fx).load_scalar(fx)), inner_layout)
551 pub fn write_place_ref(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>, dest: CPlace<'tcx>) {
552 if has_ptr_meta(fx.tcx, self.layout().ty) {
553 let (ptr, extra) = self.to_ptr_maybe_unsized(fx);
554 let ptr = CValue::by_val_pair(
556 extra.expect("unsized type without metadata"),
559 dest.write_cvalue(fx, ptr);
561 let ptr = CValue::by_val(self.to_ptr(fx).get_addr(fx), dest.layout());
562 dest.write_cvalue(fx, ptr);
566 pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
567 assert!(!self.layout().is_unsized());
569 CPlaceInner::NoPlace => {
570 assert!(layout.size.bytes() == 0);
580 pub fn downcast_variant(
582 fx: &FunctionCx<'_, 'tcx, impl Backend>,
585 let layout = self.layout().for_variant(fx, variant);
586 self.unchecked_cast_to(layout)