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>) -> Value {
94 CValueInner::ByRef(ptr) => ptr.get_addr(fx),
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 let (base_addr, offset) = ptr.get_addr_and_offset();
107 if offset == Offset32::new(0) {
113 CValueInner::ByVal(_) | CValueInner::ByValPair(_, _) => None,
117 /// Load a value with layout.abi of scalar
118 pub fn load_scalar<'a>(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> Value {
121 CValueInner::ByRef(ptr) => {
122 let scalar = match layout.abi {
123 layout::Abi::Scalar(ref scalar) => scalar.clone(),
126 let clif_ty = scalar_to_clif_type(fx.tcx, scalar);
127 ptr.load(fx, clif_ty, MemFlags::new())
129 CValueInner::ByVal(value) => value,
130 CValueInner::ByValPair(_, _) => bug!("Please use load_scalar_pair for ByValPair"),
134 /// Load a value pair with layout.abi of scalar pair
135 pub fn load_scalar_pair<'a>(
137 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
138 ) -> (Value, Value) {
141 CValueInner::ByRef(ptr) => {
142 let (a_scalar, b_scalar) = match &layout.abi {
143 layout::Abi::ScalarPair(a, b) => (a, b),
144 _ => unreachable!("load_scalar_pair({:?})", self),
146 let b_offset = scalar_pair_calculate_b_offset(fx.tcx, a_scalar, b_scalar);
147 let clif_ty1 = scalar_to_clif_type(fx.tcx, a_scalar.clone());
148 let clif_ty2 = scalar_to_clif_type(fx.tcx, b_scalar.clone());
149 let val1 = ptr.load(fx, clif_ty1, MemFlags::new());
150 let val2 = ptr.offset(fx, b_offset).load(fx, clif_ty2, MemFlags::new());
153 CValueInner::ByVal(_) => bug!("Please use load_scalar for ByVal"),
154 CValueInner::ByValPair(val1, val2) => (val1, val2),
158 pub fn value_field<'a>(
160 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
164 let ptr = match self.0 {
165 CValueInner::ByRef(ptr) => ptr,
166 _ => bug!("place_field for {:?}", self),
169 let (field_ptr, field_layout) = codegen_field(fx, ptr, None, layout, field);
170 CValue::by_ref(field_ptr, field_layout)
173 pub fn unsize_value<'a>(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>, dest: CPlace<'tcx>) {
174 crate::unsize::coerce_unsized_into(fx, self, dest);
177 /// If `ty` is signed, `const_val` must already be sign extended.
178 pub fn const_val<'a>(
179 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
183 let clif_ty = fx.clif_type(ty).unwrap();
184 let layout = fx.layout_of(ty);
186 let val = match ty.kind {
187 ty::TyKind::Uint(UintTy::U128) | ty::TyKind::Int(IntTy::I128) => {
188 let lsb = fx.bcx.ins().iconst(types::I64, const_val as u64 as i64);
192 .iconst(types::I64, (const_val >> 64) as u64 as i64);
193 fx.bcx.ins().iconcat(lsb, msb)
195 ty::TyKind::Bool => {
197 const_val == 0 || const_val == 1,
198 "Invalid bool 0x{:032X}",
201 fx.bcx.ins().iconst(types::I8, const_val as i64)
203 ty::TyKind::Uint(_) | ty::TyKind::Ref(..) | ty::TyKind::RawPtr(..) => fx
206 .iconst(clif_ty, u64::try_from(const_val).expect("uint") as i64),
207 ty::TyKind::Int(_) => fx.bcx.ins().iconst(clif_ty, const_val as i128 as i64),
209 "CValue::const_val for non bool/integer/pointer type {:?} is not allowed",
214 CValue::by_val(val, layout)
217 pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
218 CValue(self.0, layout)
222 /// A place where you can write a value to or read a value from
223 #[derive(Debug, Copy, Clone)]
224 pub struct CPlace<'tcx> {
226 layout: TyLayout<'tcx>,
229 #[derive(Debug, Copy, Clone)]
230 pub enum CPlaceInner {
232 Addr(Pointer, Option<Value>),
237 impl<'tcx> CPlace<'tcx> {
238 pub fn layout(&self) -> TyLayout<'tcx> {
242 pub fn inner(&self) -> &CPlaceInner {
246 pub fn no_place(layout: TyLayout<'tcx>) -> CPlace<'tcx> {
248 inner: CPlaceInner::NoPlace,
253 pub fn new_stack_slot(
254 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
257 let layout = fx.layout_of(ty);
258 assert!(!layout.is_unsized());
259 if layout.size.bytes() == 0 {
261 inner: CPlaceInner::NoPlace,
266 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
267 kind: StackSlotKind::ExplicitSlot,
268 size: layout.size.bytes() as u32,
272 inner: CPlaceInner::Stack(stack_slot),
278 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
280 layout: TyLayout<'tcx>,
283 .declare_var(mir_var(local), fx.clif_type(layout.ty).unwrap());
285 inner: CPlaceInner::Var(local),
290 pub fn for_ptr(ptr: Pointer, layout: TyLayout<'tcx>) -> CPlace<'tcx> {
292 inner: CPlaceInner::Addr(ptr, None),
297 pub fn for_ptr_with_extra(ptr: Pointer, extra: Value, layout: TyLayout<'tcx>) -> CPlace<'tcx> {
299 inner: CPlaceInner::Addr(ptr, Some(extra)),
304 pub fn to_cvalue(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> CValue<'tcx> {
305 let layout = self.layout();
307 CPlaceInner::Var(var) => {
308 let val = fx.bcx.use_var(mir_var(var));
309 fx.bcx.set_val_label(val, cranelift::codegen::ir::ValueLabel::from_u32(var.as_u32()));
310 CValue::by_val(val, layout)
312 CPlaceInner::Addr(ptr, extra) => {
313 assert!(extra.is_none(), "unsized values are not yet supported");
314 CValue::by_ref(ptr, layout)
316 CPlaceInner::Stack(stack_slot) => CValue::by_ref(
317 Pointer::new(fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0)),
320 CPlaceInner::NoPlace => CValue::by_ref(
321 Pointer::const_addr(fx, i64::try_from(self.layout.align.pref.bytes()).unwrap()),
327 pub fn to_ptr(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> Pointer {
328 match self.to_ptr_maybe_unsized(fx) {
330 (_, Some(_)) => bug!("Expected sized cplace, found {:?}", self),
334 pub fn to_addr(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> Value {
335 self.to_ptr(fx).get_addr(fx)
338 pub fn to_ptr_maybe_unsized(
340 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
341 ) -> (Pointer, Option<Value>) {
343 CPlaceInner::Addr(ptr, extra) => (ptr, extra),
344 CPlaceInner::Stack(stack_slot) => (
345 Pointer::new(fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0)),
348 CPlaceInner::NoPlace => {
350 Pointer::const_addr(fx, i64::try_from(self.layout.align.pref.bytes()).unwrap()),
354 CPlaceInner::Var(_) => bug!("Expected CPlace::Addr, found CPlace::Var"),
358 pub fn to_addr_maybe_unsized(
360 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
361 ) -> (Value, Option<Value>) {
362 let (ptr, extra) = self.to_ptr_maybe_unsized(fx);
363 (ptr.get_addr(fx), extra)
366 pub fn write_cvalue(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>, from: CValue<'tcx>) {
367 use rustc::hir::Mutability::*;
369 let from_ty = from.layout().ty;
370 let to_ty = self.layout().ty;
372 fn assert_assignable<'tcx>(
373 fx: &FunctionCx<'_, 'tcx, impl Backend>,
377 match (&from_ty.kind, &to_ty.kind) {
378 (ty::Ref(_, t, Immutable), ty::Ref(_, u, Immutable))
379 | (ty::Ref(_, t, Mutable), ty::Ref(_, u, Immutable))
380 | (ty::Ref(_, t, Mutable), ty::Ref(_, u, Mutable)) => {
381 assert_assignable(fx, t, u);
382 // &mut T -> &T is allowed
383 // &'a T -> &'b T is allowed
385 (ty::Ref(_, _, Immutable), ty::Ref(_, _, Mutable)) => panic!(
386 "Cant assign value of type {} to place of type {}",
389 (ty::FnPtr(_), ty::FnPtr(_)) => {
390 let from_sig = fx.tcx.normalize_erasing_late_bound_regions(
391 ParamEnv::reveal_all(),
392 &from_ty.fn_sig(fx.tcx),
394 let to_sig = fx.tcx.normalize_erasing_late_bound_regions(
395 ParamEnv::reveal_all(),
396 &to_ty.fn_sig(fx.tcx),
400 "Can't write fn ptr with incompatible sig {:?} to place with sig {:?}\n\n{:#?}",
401 from_sig, to_sig, fx,
403 // fn(&T) -> for<'l> fn(&'l T) is allowed
405 (ty::Dynamic(from_traits, _), ty::Dynamic(to_traits, _)) => {
408 .normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), from_traits);
411 .normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), to_traits);
413 from_traits, to_traits,
414 "Can't write trait object of incompatible traits {:?} to place with traits {:?}\n\n{:#?}",
415 from_traits, to_traits, fx,
417 // dyn for<'r> Trait<'r> -> dyn Trait<'_> is allowed
423 "Can't write value with incompatible type {:?} to place with type {:?}\n\n{:#?}",
432 assert_assignable(fx, from_ty, to_ty);
434 let dst_layout = self.layout();
435 let to_ptr = match self.inner {
436 CPlaceInner::Var(var) => {
437 let data = from.load_scalar(fx);
438 fx.bcx.set_val_label(data, cranelift::codegen::ir::ValueLabel::from_u32(var.as_u32()));
439 fx.bcx.def_var(mir_var(var), data);
442 CPlaceInner::Addr(ptr, None) => ptr,
443 CPlaceInner::Stack(stack_slot) => {
444 Pointer::new(fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0))
446 CPlaceInner::NoPlace => {
447 if dst_layout.abi != Abi::Uninhabited {
448 assert_eq!(dst_layout.size.bytes(), 0, "{:?}", dst_layout);
452 CPlaceInner::Addr(_, Some(_)) => bug!("Can't write value to unsized place {:?}", self),
456 CValueInner::ByVal(val) => {
457 to_ptr.store(fx, val, MemFlags::new());
459 CValueInner::ByValPair(value, extra) => match dst_layout.abi {
460 Abi::ScalarPair(ref a_scalar, ref b_scalar) => {
461 let b_offset = scalar_pair_calculate_b_offset(fx.tcx, a_scalar, b_scalar);
462 to_ptr.store(fx, value, MemFlags::new());
463 to_ptr.offset(fx, b_offset).store(fx, extra, MemFlags::new());
466 "Non ScalarPair abi {:?} for ByValPair CValue",
470 CValueInner::ByRef(from_ptr) => {
471 let from_addr = from_ptr.get_addr(fx);
472 let to_addr = to_ptr.get_addr(fx);
473 let src_layout = from.1;
474 let size = dst_layout.size.bytes();
475 let src_align = src_layout.align.abi.bytes() as u8;
476 let dst_align = dst_layout.align.abi.bytes() as u8;
477 fx.bcx.emit_small_memcpy(
478 fx.module.target_config(),
491 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
494 let layout = self.layout();
495 let (base, extra) = self.to_ptr_maybe_unsized(fx);
497 let (field_ptr, field_layout) = codegen_field(fx, base, extra, layout, field);
498 if field_layout.is_unsized() {
499 CPlace::for_ptr_with_extra(field_ptr, extra.unwrap(), field_layout)
501 CPlace::for_ptr(field_ptr, field_layout)
507 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
510 let (elem_layout, ptr) = match self.layout().ty.kind {
511 ty::Array(elem_ty, _) => (fx.layout_of(elem_ty), self.to_ptr(fx)),
512 ty::Slice(elem_ty) => (fx.layout_of(elem_ty), self.to_ptr_maybe_unsized(fx).0),
513 _ => bug!("place_index({:?})", self.layout().ty),
519 .imul_imm(index, elem_layout.size.bytes() as i64);
521 CPlace::for_ptr(ptr.offset_value(fx, offset), elem_layout)
524 pub fn place_deref(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>) -> CPlace<'tcx> {
525 let inner_layout = fx.layout_of(self.layout().ty.builtin_deref(true).unwrap().ty);
526 if has_ptr_meta(fx.tcx, inner_layout.ty) {
527 let (addr, extra) = self.to_cvalue(fx).load_scalar_pair(fx);
528 CPlace::for_ptr_with_extra(Pointer::new(addr), extra, inner_layout)
530 CPlace::for_ptr(Pointer::new(self.to_cvalue(fx).load_scalar(fx)), inner_layout)
534 pub fn write_place_ref(self, fx: &mut FunctionCx<'_, 'tcx, impl Backend>, dest: CPlace<'tcx>) {
535 if has_ptr_meta(fx.tcx, self.layout().ty) {
536 let (value, extra) = self.to_addr_maybe_unsized(fx);
537 let ptr = CValue::by_val_pair(
539 extra.expect("unsized type without metadata"),
542 dest.write_cvalue(fx, ptr);
544 let ptr = CValue::by_val(self.to_addr(fx), dest.layout());
545 dest.write_cvalue(fx, ptr);
549 pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
550 assert!(!self.layout().is_unsized());
552 CPlaceInner::NoPlace => {
553 assert!(layout.size.bytes() == 0);
563 pub fn downcast_variant(
565 fx: &FunctionCx<'_, 'tcx, impl Backend>,
568 let layout = self.layout().for_variant(fx, variant);
569 self.unchecked_cast_to(layout)