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