-
Notifications
You must be signed in to change notification settings - Fork 95
/
rvalue.rs
1698 lines (1618 loc) · 78.5 KB
/
rvalue.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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Kani Contributors
// SPDX-License-Identifier: Apache-2.0 OR MIT
use crate::codegen_cprover_gotoc::codegen::PropertyClass;
use crate::codegen_cprover_gotoc::codegen::place::ProjectedPlace;
use crate::codegen_cprover_gotoc::codegen::ty_stable::pointee_type_stable;
use crate::codegen_cprover_gotoc::utils::{dynamic_fat_ptr, slice_fat_ptr};
use crate::codegen_cprover_gotoc::{GotocCtx, VtableCtx};
use crate::kani_middle::abi::LayoutOf;
use crate::kani_middle::coercion::{
CoerceUnsizedInfo, CoerceUnsizedIterator, CoercionBaseStable, extract_unsize_casting_stable,
};
use crate::unwrap_or_return_codegen_unimplemented;
use cbmc::MachineModel;
use cbmc::goto_program::{
ARITH_OVERFLOW_OVERFLOWED_FIELD, ARITH_OVERFLOW_RESULT_FIELD, BinaryOperator, Expr, Location,
Stmt, Type, arithmetic_overflow_result_type,
};
use cbmc::{InternString, InternedString, btree_string_map};
use num::bigint::BigInt;
use rustc_middle::ty::{TyCtxt, TypingEnv, VtblEntry};
use rustc_smir::rustc_internal;
use rustc_target::abi::{FieldsShape, TagEncoding, Variants};
use stable_mir::abi::{Primitive, Scalar, ValueAbi};
use stable_mir::mir::mono::Instance;
use stable_mir::mir::{
AggregateKind, BinOp, CastKind, NullOp, Operand, Place, PointerCoercion, Rvalue, UnOp,
};
use stable_mir::ty::{ClosureKind, IntTy, RigidTy, Size, Ty, TyConst, TyKind, UintTy, VariantIdx};
use std::collections::BTreeMap;
use tracing::{debug, trace, warn};
impl GotocCtx<'_> {
fn codegen_comparison(&mut self, op: &BinOp, e1: &Operand, e2: &Operand) -> Expr {
let left_op = self.codegen_operand_stable(e1);
let right_op = self.codegen_operand_stable(e2);
let left_ty = self.operand_ty_stable(e1);
let right_ty = self.operand_ty_stable(e2);
let res_ty = op.ty(left_ty, right_ty);
let is_float = matches!(left_ty.kind(), TyKind::RigidTy(RigidTy::Float(..)));
self.comparison_expr(op, left_op, right_op, res_ty, is_float)
}
/// This function codegen comparison for fat pointers.
/// Fat pointer comparison must compare the raw data pointer as well as its metadata portion.
///
/// Since vtable pointer comparison is not well defined and it has many nuances, we decided to
/// fail if the user code performs such comparison.
///
/// See <https://github.com/model-checking/kani/issues/327> for more details.
fn codegen_comparison_fat_ptr(
&mut self,
op: &BinOp,
left_op: &Operand,
right_op: &Operand,
loc: Location,
) -> Expr {
debug!(?op, ?left_op, ?right_op, "codegen_comparison_fat_ptr");
let left_typ = self.operand_ty_stable(left_op);
let right_typ = self.operand_ty_stable(right_op);
assert_eq!(left_typ, right_typ, "Cannot compare pointers of different types");
assert!(self.is_fat_pointer_stable(left_typ));
if self.is_vtable_fat_pointer_stable(left_typ) {
// Codegen an assertion failure since vtable comparison is not stable.
let ret_type = Type::Bool;
let body = vec![
self.codegen_assert_assume_false(
PropertyClass::SafetyCheck,
format!("Reached unstable vtable comparison '{op:?}'").as_str(),
loc,
),
ret_type.nondet().as_stmt(loc).with_location(loc),
];
Expr::statement_expression(body, ret_type, loc)
} else {
// Compare data pointer.
let res_ty = op.ty(left_typ, right_typ);
let left_ptr = self.codegen_operand_stable(left_op);
let left_data = left_ptr.clone().member("data", &self.symbol_table);
let right_ptr = self.codegen_operand_stable(right_op);
let right_data = right_ptr.clone().member("data", &self.symbol_table);
let data_cmp =
self.comparison_expr(op, left_data.clone(), right_data.clone(), res_ty, false);
// Compare the slice metadata (this logic could be adapted to compare vtable if needed).
let left_len = left_ptr.member("len", &self.symbol_table);
let right_len = right_ptr.member("len", &self.symbol_table);
let metadata_cmp = self.comparison_expr(op, left_len, right_len, res_ty, false);
// Join the results.
// https://github.com/rust-lang/rust/pull/29781
match op {
// Only equal if both parts are equal.
BinOp::Eq => data_cmp.and(metadata_cmp),
// It is different if any is different.
BinOp::Ne => data_cmp.or(metadata_cmp),
// If data is different, only compare data.
// If data is equal, apply operator to metadata.
BinOp::Lt | BinOp::Le | BinOp::Ge | BinOp::Gt => {
let data_eq = self.comparison_expr(
&BinOp::Eq,
left_data.clone(),
right_data.clone(),
res_ty,
false,
);
let data_strict_comp = self.comparison_expr(
&get_strict_operator(op),
left_data,
right_data,
res_ty,
false,
);
data_strict_comp.or(data_eq.and(metadata_cmp))
}
_ => unreachable!("Unexpected operator {:?}", op),
}
}
}
fn codegen_unchecked_scalar_binop(&mut self, op: &BinOp, e1: &Operand, e2: &Operand) -> Expr {
let ce1 = self.codegen_operand_stable(e1);
let ce2 = self.codegen_operand_stable(e2);
match op {
BinOp::BitAnd => ce1.bitand(ce2),
BinOp::BitOr => ce1.bitor(ce2),
BinOp::BitXor => ce1.bitxor(ce2),
BinOp::Div => ce1.div(ce2),
BinOp::Rem => ce1.rem(ce2),
BinOp::ShlUnchecked => ce1.shl(ce2),
BinOp::ShrUnchecked => {
if self.operand_ty_stable(e1).kind().is_signed() {
ce1.ashr(ce2)
} else {
ce1.lshr(ce2)
}
}
_ => unreachable!("Unexpected {:?}", op),
}
}
fn codegen_scalar_binop(&mut self, op: &BinOp, e1: &Operand, e2: &Operand) -> Expr {
let ce1 = self.codegen_operand_stable(e1);
let ce2 = self.codegen_operand_stable(e2);
match op {
BinOp::Add => ce1.plus(ce2),
BinOp::Sub => ce1.sub(ce2),
BinOp::Mul => ce1.mul(ce2),
BinOp::Shl => ce1.shl(ce2),
BinOp::Shr => {
if self.operand_ty_stable(e1).kind().is_signed() {
ce1.ashr(ce2)
} else {
ce1.lshr(ce2)
}
}
_ => unreachable!(),
}
}
/// Codegens expressions of the type `let a = [4u8; 6];`
fn codegen_rvalue_repeat(&mut self, op: &Operand, sz: &TyConst, loc: Location) -> Expr {
let op_expr = self.codegen_operand_stable(op);
let width = sz.eval_target_usize().unwrap();
op_expr.array_constant(width).with_location(loc)
}
fn codegen_rvalue_len(&mut self, p: &Place, loc: Location) -> Expr {
let pt = self.place_ty_stable(p);
match pt.kind() {
TyKind::RigidTy(RigidTy::Array(_, sz)) => self.codegen_const_ty(&sz, loc),
TyKind::RigidTy(RigidTy::Slice(_)) => {
unwrap_or_return_codegen_unimplemented!(self, self.codegen_place_stable(p, loc))
.fat_ptr_goto_expr
.unwrap()
.member("len", &self.symbol_table)
}
_ => unreachable!("Len(_) called on type that has no length: {:?}", pt),
}
}
/// Generate code for a binary operation with an overflow check.
fn codegen_binop_with_overflow_check(
&mut self,
op: &BinOp,
left_op: &Operand,
right_op: &Operand,
loc: Location,
) -> Expr {
debug!(?op, "codegen_binop_with_overflow_check");
let left = self.codegen_operand_stable(left_op);
let right = self.codegen_operand_stable(right_op);
let ret_type = left.typ().clone();
let (bin_op, op_name) = match op {
BinOp::AddUnchecked => (BinaryOperator::OverflowResultPlus, "unchecked_add"),
BinOp::SubUnchecked => (BinaryOperator::OverflowResultMinus, "unchecked_sub"),
BinOp::MulUnchecked => (BinaryOperator::OverflowResultMult, "unchecked_mul"),
_ => unreachable!("Expected Add/Sub/Mul but got {op:?}"),
};
// Create CBMC result type and add to the symbol table.
let res_type = arithmetic_overflow_result_type(left.typ().clone());
let tag = res_type.tag().unwrap();
let struct_tag =
self.ensure_struct(tag, tag, |_, _| res_type.components().unwrap().clone());
let res = left.overflow_op(bin_op, right);
// store the result in a temporary variable
let (var, decl) = self.decl_temp_variable(struct_tag, Some(res), loc);
// cast into result type
let check = self.codegen_assert(
var.clone()
.member(ARITH_OVERFLOW_OVERFLOWED_FIELD, &self.symbol_table)
.cast_to(Type::c_bool())
.not(),
PropertyClass::ArithmeticOverflow,
format!("attempt to compute `{op_name}` which would overflow").as_str(),
loc,
);
Expr::statement_expression(
vec![
decl,
check,
var.member(ARITH_OVERFLOW_RESULT_FIELD, &self.symbol_table).as_stmt(loc),
],
ret_type,
loc,
)
}
/// Generate code for a binary operation with an overflow and returns a tuple (res, overflow).
pub fn codegen_binop_with_overflow(
&mut self,
bin_op: BinaryOperator,
left: Expr,
right: Expr,
expected_typ: Type,
loc: Location,
) -> Expr {
// Create CBMC result type and add to the symbol table.
let res_type = arithmetic_overflow_result_type(left.typ().clone());
let tag = res_type.tag().unwrap();
let struct_tag =
self.ensure_struct(tag, tag, |_, _| res_type.components().unwrap().clone());
let res = left.overflow_op(bin_op, right);
// store the result in a temporary variable
let (var, decl) = self.decl_temp_variable(struct_tag, Some(res), loc);
// cast into result type
let cast = Expr::struct_expr_from_values(
expected_typ.clone(),
vec![
var.clone().member(ARITH_OVERFLOW_RESULT_FIELD, &self.symbol_table),
var.member(ARITH_OVERFLOW_OVERFLOWED_FIELD, &self.symbol_table)
.cast_to(Type::c_bool()),
],
&self.symbol_table,
);
Expr::statement_expression(vec![decl, cast.as_stmt(loc)], expected_typ, loc)
}
/// Generate code for a binary arithmetic operation with UB / overflow checks in place.
fn codegen_rvalue_checked_binary_op(
&mut self,
op: &BinOp,
e1: &Operand,
e2: &Operand,
res_ty: Ty,
) -> Expr {
let ce1 = self.codegen_operand_stable(e1);
let ce2 = self.codegen_operand_stable(e2);
fn shift_max(t: Ty, mm: &MachineModel) -> Expr {
match t.kind() {
TyKind::RigidTy(RigidTy::Int(k)) => match k {
IntTy::I8 => Expr::int_constant(7, Type::signed_int(8)),
IntTy::I16 => Expr::int_constant(15, Type::signed_int(16)),
IntTy::I32 => Expr::int_constant(31, Type::signed_int(32)),
IntTy::I64 => Expr::int_constant(63, Type::signed_int(64)),
IntTy::I128 => Expr::int_constant(127, Type::signed_int(128)),
IntTy::Isize => Expr::int_constant(mm.pointer_width - 1, Type::ssize_t()),
},
TyKind::RigidTy(RigidTy::Uint(k)) => match k {
UintTy::U8 => Expr::int_constant(7, Type::unsigned_int(8)),
UintTy::U16 => Expr::int_constant(15, Type::unsigned_int(16)),
UintTy::U32 => Expr::int_constant(31, Type::unsigned_int(32)),
UintTy::U64 => Expr::int_constant(63, Type::unsigned_int(64)),
UintTy::U128 => Expr::int_constant(127, Type::unsigned_int(128)),
UintTy::Usize => Expr::int_constant(mm.pointer_width - 1, Type::size_t()),
},
_ => unreachable!(),
}
}
match op {
BinOp::Add => {
let res_type = self.codegen_ty_stable(res_ty);
self.codegen_binop_with_overflow(
BinaryOperator::OverflowResultPlus,
ce1,
ce2,
res_type,
Location::None,
)
}
BinOp::Sub => {
let res_type = self.codegen_ty_stable(res_ty);
self.codegen_binop_with_overflow(
BinaryOperator::OverflowResultMinus,
ce1,
ce2,
res_type,
Location::None,
)
}
BinOp::Mul => {
let res_type = self.codegen_ty_stable(res_ty);
self.codegen_binop_with_overflow(
BinaryOperator::OverflowResultMult,
ce1,
ce2,
res_type,
Location::None,
)
}
BinOp::Shl => {
let t1 = self.operand_ty_stable(e1);
let max = shift_max(t1, self.symbol_table.machine_model());
Expr::struct_expr_from_values(
self.codegen_ty_stable(res_ty),
vec![
ce1.shl(ce2.clone()),
ce2.cast_to(self.codegen_ty_stable(t1)).gt(max).cast_to(Type::c_bool()),
],
&self.symbol_table,
)
}
BinOp::Shr => {
let t1 = self.operand_ty_stable(e1);
let max = shift_max(t1, self.symbol_table.machine_model());
Expr::struct_expr_from_values(
self.codegen_ty_stable(res_ty),
vec![
if t1.kind().is_signed() {
ce1.ashr(ce2.clone())
} else {
ce1.lshr(ce2.clone())
},
ce2.cast_to(self.codegen_ty_stable(t1)).gt(max).cast_to(Type::c_bool()),
],
&self.symbol_table,
)
}
_ => unreachable!(),
}
}
fn codegen_rvalue_binary_op(
&mut self,
ty: Ty,
op: &BinOp,
e1: &Operand,
e2: &Operand,
loc: Location,
) -> Expr {
match op {
BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Shl | BinOp::Shr => {
self.codegen_scalar_binop(op, e1, e2)
}
BinOp::ShlUnchecked | BinOp::ShrUnchecked => {
let result = self.codegen_unchecked_scalar_binop(op, e1, e2);
let check = self.check_unchecked_shift_distance(e1, e2, loc);
Expr::statement_expression(
vec![check, result.clone().as_stmt(loc)],
result.typ().clone(),
loc,
)
}
BinOp::AddUnchecked | BinOp::MulUnchecked | BinOp::SubUnchecked => {
self.codegen_binop_with_overflow_check(op, e1, e2, loc)
}
BinOp::Div | BinOp::Rem => {
let result = self.codegen_unchecked_scalar_binop(op, e1, e2);
if self.operand_ty_stable(e1).kind().is_integral() {
let is_rem = matches!(op, BinOp::Rem);
let check = self.check_div_overflow(e1, e2, is_rem, loc);
Expr::statement_expression(
vec![check, result.clone().as_stmt(loc)],
result.typ().clone(),
loc,
)
} else {
result
}
}
BinOp::BitXor | BinOp::BitAnd | BinOp::BitOr => {
self.codegen_unchecked_scalar_binop(op, e1, e2)
}
BinOp::Eq | BinOp::Lt | BinOp::Le | BinOp::Ne | BinOp::Ge | BinOp::Gt | BinOp::Cmp => {
let op_ty = self.operand_ty_stable(e1);
if self.is_fat_pointer_stable(op_ty) {
self.codegen_comparison_fat_ptr(op, e1, e2, loc)
} else {
self.codegen_comparison(op, e1, e2)
}
}
// https://doc.rust-lang.org/std/primitive.pointer.html#method.offset
BinOp::Offset => {
let ce1 = self.codegen_operand_stable(e1);
let ce2 = self.codegen_operand_stable(e2);
// Check that computing `offset` in bytes would not overflow
let (offset_bytes, bytes_overflow_check) = self.count_in_bytes(
ce2.clone().cast_to(Type::ssize_t()),
pointee_type_stable(ty).unwrap(),
Type::ssize_t(),
"offset",
loc,
);
// Check that the computation would not overflow an `isize` which is UB:
// https://doc.rust-lang.org/std/primitive.pointer.html#method.offset
// These checks may allow a wrapping-around behavior in CBMC:
// https://github.com/model-checking/kani/issues/1150
// Note(std): We don't check that the starting or resulting pointer stay
// within bounds of the object they point to. Doing so causes spurious
// failures due to the usage of these intrinsics in the standard library.
// See <https://github.com/model-checking/kani/issues/1233> for more details.
// Note that this is one of the safety conditions for `offset`:
// <https://doc.rust-lang.org/std/primitive.pointer.html#safety-2>
let overflow_res = ce1.clone().cast_to(Type::ssize_t()).add_overflow(offset_bytes);
let overflow_check = self.codegen_assert_assume(
overflow_res.overflowed.not(),
PropertyClass::ArithmeticOverflow,
"attempt to compute offset which would overflow",
loc,
);
let res = ce1.clone().plus(ce2);
Expr::statement_expression(
vec![bytes_overflow_check, overflow_check, res.as_stmt(loc)],
ce1.typ().clone(),
loc,
)
}
}
}
/// Check that a division does not overflow.
/// For integer types, division by zero is UB, as is MIN / -1 for signed.
/// Note that the compiler already inserts these checks for regular division.
/// However, since <https://github.com/rust-lang/rust/pull/112168>, unchecked divisions are
/// lowered to `BinOp::Div`. Prefer adding duplicated checks for now.
fn check_div_overflow(
&mut self,
dividend: &Operand,
divisor: &Operand,
is_remainder: bool,
loc: Location,
) -> Stmt {
let divisor_expr = self.codegen_operand_stable(divisor);
let msg = if is_remainder {
"attempt to calculate the remainder with a divisor of zero"
} else {
"attempt to divide by zero"
};
let div_by_zero_check = self.codegen_assert_assume(
divisor_expr.clone().is_zero().not(),
PropertyClass::ArithmeticOverflow,
msg,
loc,
);
if self.operand_ty_stable(dividend).kind().is_signed() {
let dividend_expr = self.codegen_operand_stable(dividend);
let overflow_msg = if is_remainder {
"attempt to calculate the remainder with overflow"
} else {
"attempt to divide with overflow"
};
let overflow_expr = dividend_expr
.clone()
.eq(dividend_expr.typ().min_int_expr(self.symbol_table.machine_model()))
.and(divisor_expr.clone().eq(Expr::int_constant(-1, divisor_expr.typ().clone())));
let overflow_check = self.codegen_assert_assume(
overflow_expr.not(),
PropertyClass::ArithmeticOverflow,
overflow_msg,
loc,
);
Stmt::block(vec![overflow_check, div_by_zero_check], loc)
} else {
div_by_zero_check
}
}
/// Check for valid unchecked shift distance.
/// Shifts on an integer of type T are UB if shift distance < 0 or >= T::BITS.
fn check_unchecked_shift_distance(
&mut self,
value: &Operand,
distance: &Operand,
loc: Location,
) -> Stmt {
let value_expr = self.codegen_operand_stable(value);
let distance_expr = self.codegen_operand_stable(distance);
let value_width = value_expr.typ().sizeof_in_bits(&self.symbol_table);
let value_width_expr = Expr::int_constant(value_width, distance_expr.typ().clone());
let excessive_distance_check = self.codegen_assert_assume(
distance_expr.clone().lt(value_width_expr),
PropertyClass::ArithmeticOverflow,
"attempt to shift by excessive shift distance",
loc,
);
if distance_expr.typ().is_signed(self.symbol_table.machine_model()) {
let negative_distance_check = self.codegen_assert_assume(
distance_expr.is_non_negative(),
PropertyClass::ArithmeticOverflow,
"attempt to shift by negative distance",
loc,
);
Stmt::block(vec![negative_distance_check, excessive_distance_check], loc)
} else {
excessive_distance_check
}
}
/// Create an initializer for a coroutine struct.
fn codegen_rvalue_coroutine(&mut self, operands: &[Operand], ty: Ty) -> Expr {
let layout = self.layout_of_stable(ty);
let discriminant_field = match &layout.variants {
Variants::Multiple { tag_encoding: TagEncoding::Direct, tag_field, .. } => tag_field,
_ => unreachable!(
"Expected coroutines to have multiple variants and direct encoding, but found: {layout:?}"
),
};
let overall_t = self.codegen_ty_stable(ty);
let direct_fields = overall_t.lookup_field("direct_fields", &self.symbol_table).unwrap();
let direct_fields_expr = Expr::struct_expr_from_values(
direct_fields.typ(),
layout
.fields
.index_by_increasing_offset()
.map(|idx| {
let field_ty = layout.field(self, idx).ty;
if idx == *discriminant_field {
Expr::int_constant(0, self.codegen_ty(field_ty))
} else {
self.codegen_operand_stable(&operands[idx])
}
})
.collect(),
&self.symbol_table,
);
Expr::union_expr(overall_t, "direct_fields", direct_fields_expr, &self.symbol_table)
}
/// This code will generate an expression that initializes an enumeration.
///
/// It will first create a temporary variant with the same enum type.
/// Initialize the case structure and set its discriminant.
/// Finally, it will return the temporary value.
fn codegen_rvalue_enum_aggregate(
&mut self,
variant_index: VariantIdx,
operands: &[Operand],
res_ty: Ty,
loc: Location,
) -> Expr {
let mut stmts = vec![];
let typ = self.codegen_ty_stable(res_ty);
// 1- Create a temporary value of the enum type.
tracing::debug!(?typ, ?res_ty, "aggregate_enum");
let (temp_var, decl) = self.decl_temp_variable(typ.clone(), None, loc);
stmts.push(decl);
if !operands.is_empty() {
// 2- Initialize the members of the temporary variant.
let initial_projection =
ProjectedPlace::try_from_ty(temp_var.clone(), res_ty, self).unwrap();
let variant_proj = self.codegen_variant_lvalue(initial_projection, variant_index, loc);
let variant_expr = variant_proj.goto_expr.clone();
let layout = self.layout_of_stable(res_ty);
let fields = match &layout.variants {
Variants::Single { index } => {
if *index != rustc_internal::internal(self.tcx, variant_index) {
// This may occur if all variants except for the one pointed by
// index can never be constructed. Generic code might still try
// to initialize the non-existing invariant.
trace!(?res_ty, ?variant_index, "Unreachable invariant");
return Expr::nondet(typ);
}
&layout.fields
}
Variants::Multiple { variants, .. } => {
&variants[rustc_internal::internal(self.tcx, variant_index)].fields
}
};
trace!(?variant_expr, ?fields, ?operands, "codegen_aggregate enum");
let init_struct = Expr::struct_expr_from_values(
variant_expr.typ().clone(),
fields
.index_by_increasing_offset()
.map(|idx| self.codegen_operand_stable(&operands[idx]))
.collect(),
&self.symbol_table,
);
let assign_case = variant_proj.goto_expr.assign(init_struct, loc);
stmts.push(assign_case);
}
// 3- Set discriminant.
let set_discriminant =
self.codegen_set_discriminant(res_ty, temp_var.clone(), variant_index, loc);
stmts.push(set_discriminant);
// 4- Return temporary variable.
stmts.push(temp_var.as_stmt(loc));
Expr::statement_expression(stmts, typ, loc)
}
fn codegen_rvalue_aggregate(
&mut self,
aggregate: &AggregateKind,
operands: &[Operand],
res_ty: Ty,
loc: Location,
) -> Expr {
match *aggregate {
AggregateKind::Array(_et) => {
let typ = self.codegen_ty_stable(res_ty);
Expr::array_expr(
typ,
operands.iter().map(|o| self.codegen_operand_stable(o)).collect(),
)
}
AggregateKind::Adt(_, _, _, _, Some(active_field_index)) => {
assert!(res_ty.kind().is_union());
assert_eq!(operands.len(), 1);
let typ = self.codegen_ty_stable(res_ty);
let components = typ.lookup_components(&self.symbol_table).unwrap();
Expr::union_expr(
typ,
components[active_field_index].name(),
self.codegen_operand_stable(&operands[0usize]),
&self.symbol_table,
)
}
AggregateKind::Adt(_, _, _, _, _) if res_ty.kind().is_simd() => {
let typ = self.codegen_ty_stable(res_ty);
let layout = self.layout_of_stable(res_ty);
trace!(shape=?layout.fields, "codegen_rvalue_aggregate");
assert!(!operands.is_empty(), "SIMD vector cannot be empty");
if operands.len() == 1 {
let data = self.codegen_operand_stable(&operands[0]);
if data.typ().is_array() {
// Array-based SIMD representation.
data.transmute_to(typ, &self.symbol_table)
} else {
// Multi field-based representation with one field.
Expr::vector_expr(typ, vec![data])
}
} else {
// Multi field SIMD representation.
Expr::vector_expr(
typ,
layout
.fields
.index_by_increasing_offset()
.map(|idx| self.codegen_operand_stable(&operands[idx]))
.collect(),
)
}
}
AggregateKind::Adt(_, variant_index, ..) if res_ty.kind().is_enum() => {
self.codegen_rvalue_enum_aggregate(variant_index, operands, res_ty, loc)
}
AggregateKind::Adt(..) | AggregateKind::Closure(..) | AggregateKind::Tuple => {
let typ = self.codegen_ty_stable(res_ty);
let layout = self.layout_of_stable(res_ty);
Expr::struct_expr_from_values(
typ,
layout
.fields
.index_by_increasing_offset()
.map(|idx| self.codegen_operand_stable(&operands[idx]))
.collect(),
&self.symbol_table,
)
}
AggregateKind::RawPtr(pointee_ty, _) => {
// We expect two operands: "data" and "meta"
assert!(operands.len() == 2);
let typ = self.codegen_ty_stable(res_ty);
let layout = self.layout_of_stable(res_ty);
assert!(layout.ty.is_unsafe_ptr());
let data = self.codegen_operand_stable(&operands[0]);
match pointee_ty.kind() {
TyKind::RigidTy(RigidTy::Slice(inner_ty)) => {
let pointee_goto_typ = self.codegen_ty_stable(inner_ty);
// cast data to pointer with specified type
let data_cast =
data.cast_to(Type::Pointer { typ: Box::new(pointee_goto_typ) });
let meta = self.codegen_operand_stable(&operands[1]);
slice_fat_ptr(typ, data_cast, meta, &self.symbol_table)
}
TyKind::RigidTy(RigidTy::Str) => {
let pointee_goto_typ = Type::unsigned_int(8);
// cast data to pointer with specified type
let data_cast =
data.cast_to(Type::Pointer { typ: Box::new(pointee_goto_typ) });
let meta = self.codegen_operand_stable(&operands[1]);
slice_fat_ptr(typ, data_cast, meta, &self.symbol_table)
}
TyKind::RigidTy(RigidTy::Adt(..)) => {
let layout = LayoutOf::new(pointee_ty);
let pointee_goto_typ = self.codegen_ty_stable(pointee_ty);
let data_cast =
data.cast_to(Type::Pointer { typ: Box::new(pointee_goto_typ) });
layout.unsized_tail().map_or(data_cast.clone(), |tail| {
let meta = self.codegen_operand_stable(&operands[1]);
match tail.kind().rigid().unwrap() {
RigidTy::Foreign(..) => data_cast,
RigidTy::Slice(..) | RigidTy::Str => {
slice_fat_ptr(typ, data_cast, meta, &self.symbol_table)
}
RigidTy::Dynamic(..) => {
let vtable_expr = meta
.member("_vtable_ptr", &self.symbol_table)
.member("pointer", &self.symbol_table)
.cast_to(
typ.lookup_field_type("vtable", &self.symbol_table)
.unwrap(),
);
dynamic_fat_ptr(typ, data_cast, vtable_expr, &self.symbol_table)
}
_ => {
unreachable!("Unexpected unsized tail: {tail:?}");
}
}
})
}
TyKind::RigidTy(RigidTy::Dynamic(..)) => {
let pointee_goto_typ = self.codegen_ty_stable(pointee_ty);
let data_cast =
data.cast_to(Type::Pointer { typ: Box::new(pointee_goto_typ) });
let meta = self.codegen_operand_stable(&operands[1]);
let vtable_expr = meta
.member("_vtable_ptr", &self.symbol_table)
.member("pointer", &self.symbol_table)
.cast_to(typ.lookup_field_type("vtable", &self.symbol_table).unwrap());
dynamic_fat_ptr(typ, data_cast, vtable_expr, &self.symbol_table)
}
_ => {
let pointee_goto_typ = self.codegen_ty_stable(pointee_ty);
data.cast_to(Type::Pointer { typ: Box::new(pointee_goto_typ) })
}
}
}
AggregateKind::Coroutine(_, _, _) => self.codegen_rvalue_coroutine(&operands, res_ty),
}
}
pub fn codegen_rvalue_stable(&mut self, rv: &Rvalue, loc: Location) -> Expr {
let res_ty = self.rvalue_ty_stable(rv);
debug!(?rv, ?res_ty, "codegen_rvalue");
match rv {
Rvalue::Use(p) => self.codegen_operand_stable(p),
Rvalue::Repeat(op, sz) => self.codegen_rvalue_repeat(op, sz, loc),
Rvalue::Ref(_, _, p) | Rvalue::AddressOf(_, p) => {
let place_ref = self.codegen_place_ref_stable(&p, loc);
let place_ref_type = place_ref.typ().clone();
match self.codegen_raw_ptr_deref_validity_check(
&p,
place_ref.clone(),
self.place_ty_stable(p),
&loc,
) {
Some((ptr_alignment_check_expr, ptr_validity_check_expr)) => {
Expr::statement_expression(
vec![
ptr_alignment_check_expr,
ptr_validity_check_expr,
place_ref.as_stmt(loc),
],
place_ref_type,
loc,
)
}
None => place_ref,
}
}
Rvalue::Len(p) => self.codegen_rvalue_len(p, loc),
// Rust has begun distinguishing "ptr -> num" and "num -> ptr" (providence-relevant casts) but we do not yet:
// Should we? Tracking ticket: https://github.com/model-checking/kani/issues/1274
Rvalue::Cast(
CastKind::IntToInt
| CastKind::FloatToFloat
| CastKind::FloatToInt
| CastKind::IntToFloat
| CastKind::FnPtrToPtr
| CastKind::PtrToPtr
| CastKind::PointerExposeAddress
| CastKind::PointerWithExposedProvenance,
e,
t,
) => self.codegen_misc_cast(e, *t),
Rvalue::Cast(CastKind::DynStar, _, _) => {
let ty = self.codegen_ty_stable(res_ty);
self.codegen_unimplemented_expr(
"CastKind::DynStar",
ty,
loc,
"https://github.com/model-checking/kani/issues/1784",
)
}
Rvalue::Cast(CastKind::PointerCoercion(k), e, t) => {
self.codegen_pointer_cast(k, e, *t, loc)
}
Rvalue::Cast(CastKind::Transmute, operand, ty) => {
let goto_typ = self.codegen_ty_stable(*ty);
self.codegen_operand_stable(operand).transmute_to(goto_typ, &self.symbol_table)
}
Rvalue::BinaryOp(op, e1, e2) => self.codegen_rvalue_binary_op(res_ty, op, e1, e2, loc),
Rvalue::CheckedBinaryOp(op, e1, e2) => {
self.codegen_rvalue_checked_binary_op(op, e1, e2, res_ty)
}
Rvalue::NullaryOp(k, t) => {
let layout = self.layout_of_stable(*t);
match k {
NullOp::SizeOf => Expr::int_constant(layout.size.bytes_usize(), Type::size_t())
.with_size_of_annotation(self.codegen_ty_stable(*t)),
NullOp::AlignOf => Expr::int_constant(layout.align.abi.bytes(), Type::size_t()),
NullOp::OffsetOf(fields) => Expr::int_constant(
self.tcx
.offset_of_subfield(
TypingEnv::fully_monomorphized(),
layout,
fields.iter().map(|(var_idx, field_idx)| {
(
rustc_internal::internal(self.tcx, var_idx),
(*field_idx).into(),
)
}),
)
.bytes(),
Type::size_t(),
),
NullOp::UbChecks => Expr::c_false(),
}
}
Rvalue::ShallowInitBox(ref operand, content_ty) => {
// The behaviour of ShallowInitBox is simply transmuting *mut u8 to Box<T>.
// See https://github.com/rust-lang/compiler-team/issues/460 for more details.
let operand = self.codegen_operand_stable(operand);
let box_ty = Ty::new_box(*content_ty);
let box_ty = self.codegen_ty_stable(box_ty);
let cbmc_t = self.codegen_ty_stable(*content_ty);
let box_contents = operand.cast_to(cbmc_t.to_pointer());
self.box_value(box_contents, box_ty)
}
Rvalue::UnaryOp(op, e) => match op {
UnOp::Not => {
if self.operand_ty_stable(e).kind().is_bool() {
self.codegen_operand_stable(e).not()
} else {
self.codegen_operand_stable(e).bitnot()
}
}
UnOp::Neg => self.codegen_operand_stable(e).neg(),
UnOp::PtrMetadata => {
let src_goto_expr = self.codegen_operand_stable(e);
let dst_goto_typ = self.codegen_ty_stable(res_ty);
debug!(
"PtrMetadata |{:?}| with result type |{:?}|",
src_goto_expr, dst_goto_typ
);
if let Some(_vtable_typ) =
src_goto_expr.typ().lookup_field_type("vtable", &self.symbol_table)
{
let vtable_expr = src_goto_expr.member("vtable", &self.symbol_table);
let dst_components =
dst_goto_typ.lookup_components(&self.symbol_table).unwrap();
assert_eq!(dst_components.len(), 2);
assert_eq!(dst_components[0].name(), "_vtable_ptr");
assert!(dst_components[0].typ().is_struct_like());
assert_eq!(dst_components[1].name(), "_phantom");
self.assert_is_rust_phantom_data_like(&dst_components[1].typ());
// accessing pointer type of _vtable_ptr, which is wrapped in NonNull
let vtable_ptr_typ = dst_goto_typ
.lookup_field_type("_vtable_ptr", &self.symbol_table)
.unwrap()
.lookup_components(&self.symbol_table)
.unwrap()[0]
.typ();
Expr::struct_expr(
dst_goto_typ.clone(),
btree_string_map![
(
"_vtable_ptr",
Expr::struct_expr_from_values(
dst_goto_typ
.lookup_field_type("_vtable_ptr", &self.symbol_table)
.unwrap(),
vec![vtable_expr.clone().cast_to(vtable_ptr_typ)],
&self.symbol_table
)
),
(
"_phantom",
Expr::struct_expr(
dst_components[1].typ(),
[].into(),
&self.symbol_table
)
)
],
&self.symbol_table,
)
} else if let Some(len_typ) =
src_goto_expr.typ().lookup_field_type("len", &self.symbol_table)
{
assert_eq!(len_typ, dst_goto_typ);
src_goto_expr.member("len", &self.symbol_table)
} else {
unreachable!(
"fat pointer with neither vtable nor len: {:?}",
src_goto_expr
);
}
}
},
Rvalue::Discriminant(p) => {
let place = unwrap_or_return_codegen_unimplemented!(
self,
self.codegen_place_stable(p, loc)
)
.goto_expr;
let pt = self.place_ty_stable(p);
self.codegen_get_discriminant(place, pt, res_ty)
}
Rvalue::Aggregate(ref k, operands) => {
self.codegen_rvalue_aggregate(k, operands, res_ty, loc)
}
Rvalue::ThreadLocalRef(def_id) => {
// Since Kani is single-threaded, we treat a thread local like a static variable:
self.store_concurrent_construct("thread local (replaced by static variable)", loc);
self.codegen_thread_local_pointer(*def_id)
}
// A CopyForDeref is equivalent to a read from a place at the codegen level.
// https://github.com/rust-lang/rust/blob/1673f1450eeaf4a5452e086db0fe2ae274a0144f/compiler/rustc_middle/src/mir/syntax.rs#L1055
Rvalue::CopyForDeref(place) => {
unwrap_or_return_codegen_unimplemented!(self, self.codegen_place_stable(place, loc))
.goto_expr
}
}
}
pub fn codegen_discriminant_field(&self, place: Expr, ty: Ty) -> Expr {
let layout = self.layout_of_stable(ty);
assert!(
matches!(&layout.variants, Variants::Multiple {
tag_encoding: TagEncoding::Direct,
..
}),
"discriminant field (`case`) only exists for multiple variants and direct encoding"
);
let expr = if ty.kind().is_coroutine() {
// Coroutines are translated somewhat differently from enums (see [`GotoCtx::codegen_ty_coroutine`]).
// As a consequence, the discriminant is accessed as `.direct_fields.case` instead of just `.case`.
place.member("direct_fields", &self.symbol_table)
} else {
place
};
expr.member("case", &self.symbol_table)
}
/// e: ty
/// get the discriminant of e, of type res_ty
pub fn codegen_get_discriminant(&mut self, e: Expr, ty: Ty, res_ty: Ty) -> Expr {
let layout = self.layout_of_stable(ty);
match &layout.variants {
Variants::Single { index } => {
let discr_val = layout
.ty
.discriminant_for_variant(self.tcx, *index)
.map_or(index.as_u32() as u128, |discr| discr.val);
Expr::int_constant(discr_val, self.codegen_ty_stable(res_ty))
}
Variants::Multiple { tag_encoding, .. } => match tag_encoding {
TagEncoding::Direct => {
self.codegen_discriminant_field(e, ty).cast_to(self.codegen_ty_stable(res_ty))
}
TagEncoding::Niche { untagged_variant, niche_variants, niche_start } => {
// This code follows the logic in the ssa codegen backend:
// https://github.com/rust-lang/rust/blob/fee75fbe11b1fad5d93c723234178b2a329a3c03/compiler/rustc_codegen_ssa/src/mir/place.rs#L247
// See also the cranelift backend:
// https://github.com/rust-lang/rust/blob/05d22212e89588e7c443cc6b9bc0e4e02fdfbc8d/compiler/rustc_codegen_cranelift/src/discriminant.rs#L116
let offset = match &layout.fields {
FieldsShape::Arbitrary { offsets, .. } => offsets[0usize.into()],
_ => unreachable!("niche encoding must have arbitrary fields"),
};