forked from model-checking/kani
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtyp.rs
More file actions
1770 lines (1669 loc) · 76.5 KB
/
Copy pathtyp.rs
File metadata and controls
1770 lines (1669 loc) · 76.5 KB
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::GotocCtx;
use cbmc::goto_program::{DatatypeComponent, Expr, Location, Parameter, Symbol, SymbolTable, Type};
use cbmc::utils::aggr_tag;
use cbmc::{InternString, InternedString};
use rustc_abi::{
BackendRepr::Vector, FieldIdx, FieldsShape, Float, Integer, LayoutData, Primitive, Size,
TagEncoding, TyAndLayout, VariantIdx, Variants,
};
use rustc_ast::ast::Mutability;
use rustc_index::IndexVec;
use rustc_middle::ty::GenericArgsRef;
use rustc_middle::ty::layout::LayoutOf;
use rustc_middle::ty::print::FmtPrinter;
use rustc_middle::ty::print::with_no_trimmed_paths;
use rustc_middle::ty::{
self, AdtDef, Const, CoroutineArgs, CoroutineArgsExt, FloatTy, Instance, IntTy, PolyFnSig, Ty,
TyCtxt, TyKind, UintTy, VariantDef, VtblEntry,
};
use rustc_middle::ty::{List, TypeFoldable};
use rustc_smir::rustc_internal;
use rustc_span::def_id::DefId;
use stable_mir::abi::{ArgAbi, FnAbi, PassMode};
use stable_mir::mir::Body;
use stable_mir::mir::mono::Instance as InstanceStable;
use tracing::{debug, trace, warn};
/// Map the unit type to an empty struct
///
/// Mapping unit to `void` works for functions with no return type but not for variables with type
/// unit. We treat both uniformly by declaring an empty struct type: `struct Unit {}` and a global
/// variable `struct Unit VoidUnit` returned by all void functions.
const UNIT_TYPE_EMPTY_STRUCT_NAME: &str = "Unit";
pub const FN_RETURN_VOID_VAR_NAME: &str = "VoidUnit";
/// Name for the common vtable structure.
const COMMON_VTABLE_STRUCT_NAME: &str = "Kani::CommonVTable";
const VTABLE_DROP_FIELD: &str = "drop";
pub const VTABLE_SIZE_FIELD: &str = "size";
pub const VTABLE_ALIGN_FIELD: &str = "align";
/// Map the never i.e. `!` type to an empty struct.
/// The never type can appear as a function argument, e.g. in library/core/src/num/error.rs
const NEVER_TYPE_EMPTY_STRUCT_NAME: &str = "Never";
pub trait TypeExt {
fn is_rust_fat_ptr(&self, st: &SymbolTable) -> bool;
fn is_rust_slice_fat_ptr(&self, st: &SymbolTable) -> bool;
fn is_rust_trait_fat_ptr(&self, st: &SymbolTable) -> bool;
fn unit() -> Self;
}
impl TypeExt for Type {
fn is_rust_slice_fat_ptr(&self, st: &SymbolTable) -> bool {
match self {
Type::Struct { components, .. } => {
components.len() == 2
&& components.iter().any(|x| x.name() == "data" && x.typ().is_pointer())
&& components.iter().any(|x| x.name() == "len" && x.typ().is_integer())
}
Type::StructTag(tag) => st.lookup(*tag).unwrap().typ.is_rust_slice_fat_ptr(st),
_ => false,
}
}
fn is_rust_trait_fat_ptr(&self, st: &SymbolTable) -> bool {
match self {
Type::Struct { components, .. } => {
components.len() == 2
&& components.iter().any(|x| x.name() == "data" && x.typ().is_pointer())
&& components.iter().any(|x| x.name() == "vtable" && x.typ().is_pointer())
}
Type::StructTag(tag) => {
st.lookup(tag.to_string()).unwrap().typ.is_rust_trait_fat_ptr(st)
}
_ => false,
}
}
fn is_rust_fat_ptr(&self, st: &SymbolTable) -> bool {
self.is_rust_slice_fat_ptr(st) || self.is_rust_trait_fat_ptr(st)
}
fn unit() -> Self {
// We depend on GotocCtx::codegen_ty_unit() to put the type in the symbol table.
// We don't have access to the symbol table here to do it ourselves.
Type::struct_tag(UNIT_TYPE_EMPTY_STRUCT_NAME)
}
}
/// Function signatures
impl GotocCtx<'_> {
/// This method prints the details of a GotoC type, for debugging purposes.
#[allow(unused)]
pub(crate) fn debug_print_type_recursively(&self, ty: &Type) -> String {
fn debug_write_type(
ctx: &GotocCtx,
ty: &Type,
out: &mut impl std::fmt::Write,
indent: usize,
) -> Result<(), std::fmt::Error> {
match ty {
Type::Array { typ, size } => {
write!(out, "[")?;
debug_write_type(ctx, typ, out, indent + 2)?;
write!(out, "; {size}]")?;
}
Type::Bool => write!(out, "bool")?,
Type::CBitField { typ, width } => {
write!(out, "bitfield(")?;
debug_write_type(ctx, typ, out, indent + 2)?;
write!(out, ", {width}")?;
}
Type::CInteger(int_ty) => {
let name = match int_ty {
cbmc::goto_program::CIntType::Bool => "bool",
cbmc::goto_program::CIntType::Char => "char",
cbmc::goto_program::CIntType::Int => "int",
cbmc::goto_program::CIntType::LongInt => "long int",
cbmc::goto_program::CIntType::SizeT => "size_t",
cbmc::goto_program::CIntType::SSizeT => "ssize_t",
};
write!(out, "{name}")?;
}
Type::Code { .. } => write!(out, "Code")?,
Type::Constructor => todo!(),
Type::Double => write!(out, "f64")?,
Type::Empty => todo!(),
Type::FlexibleArray { .. } => todo!(),
Type::Float => write!(out, "f32")?,
Type::Float16 => write!(out, "f16")?,
Type::Float128 => write!(out, "f128")?,
Type::IncompleteStruct { .. } => todo!(),
Type::IncompleteUnion { .. } => todo!(),
Type::InfiniteArray { .. } => todo!(),
Type::Integer => write!(out, "integer")?,
Type::Pointer { typ } => {
write!(out, "*")?;
debug_write_type(ctx, typ, out, indent)?;
}
Type::Signedbv { width } => write!(out, "i{width}")?,
Type::Struct { tag, components } => {
let pretty_name = if let Some(symbol) = ctx.symbol_table.lookup(aggr_tag(*tag))
{
symbol.pretty_name.unwrap()
} else {
"<no pretty name available>".into()
};
writeln!(out, "struct {tag} ({pretty_name}) {{")?;
for c in components {
match c {
DatatypeComponent::Field { name, typ } => {
write!(out, "{:indent$}{name}: ", "", indent = indent + 2)?;
debug_write_type(ctx, typ, out, indent + 2)?;
writeln!(out, ",")?;
}
DatatypeComponent::Padding { bits, .. } => {
writeln!(
out,
"{:indent$}/* padding: {bits} bits */",
"",
indent = indent + 2
)?;
}
}
}
write!(out, "{:indent$}}}", "")?;
}
Type::StructTag(tag) => {
let ty = &ctx.symbol_table.lookup(*tag).unwrap().typ;
debug_write_type(ctx, ty, out, indent)?;
}
Type::TypeDef { name, typ } => {
write!(out, "typedef {{ {name}: ")?;
debug_write_type(ctx, typ, out, indent + 2)?;
write!(out, "{:indent$}}}", "")?;
}
Type::Union { tag, components } => {
let pretty_name = if let Some(symbol) = ctx.symbol_table.lookup(aggr_tag(*tag))
{
symbol.pretty_name.unwrap()
} else {
"<no pretty name available>".into()
};
writeln!(out, "union {tag} ({pretty_name}) {{ ")?;
for c in components {
match c {
DatatypeComponent::Field { name, typ } => {
write!(out, "{:indent$}{name}: ", "", indent = indent + 2)?;
debug_write_type(ctx, typ, out, indent + 2)?;
writeln!(out, ",")?;
}
DatatypeComponent::Padding { bits, .. } => {
writeln!(
out,
"{:indent$}/* padding: {bits} bits */",
"",
indent = indent + 2
)?;
}
}
}
write!(out, "{:indent$}}}", "")?;
}
Type::UnionTag(tag) => {
let ty = &ctx.symbol_table.lookup(*tag).unwrap().typ;
debug_write_type(ctx, ty, out, indent)?;
}
Type::Unsignedbv { width } => write!(out, "u{width}")?,
Type::VariadicCode { .. } => write!(out, "VariadicCode")?,
Type::Vector { .. } => todo!(),
}
Ok(())
}
let mut out = String::new();
debug_write_type(self, ty, &mut out, 0).unwrap();
out
}
}
impl<'tcx> GotocCtx<'tcx> {
pub fn monomorphize<T>(&self, value: T) -> T
where
T: TypeFoldable<TyCtxt<'tcx>>,
{
// Instance is Some(..) only when current codegen unit is a function.
if let Some(current_fn) = &self.current_fn {
current_fn.instance().instantiate_mir_and_normalize_erasing_regions(
self.tcx,
ty::TypingEnv::fully_monomorphized(),
ty::EarlyBinder::bind(value),
)
} else {
// TODO: confirm with rust team there is no way to monomorphize
// a global value.
value
}
}
/// Is the MIR type a zero-sized type.
pub fn is_zst(&self, t: Ty<'tcx>) -> bool {
self.layout_of(t).is_zst()
}
/// Is the MIR type an unsized type
/// Unsized types can represent:
/// 1- Types that rust cannot infer their type such as ForeignItems.
/// 2- Types that can only be accessed via FatPointer.
pub fn is_unsized(&self, t: Ty<'tcx>) -> bool {
!self
.monomorphize(t)
.is_sized(*self.tcx.at(rustc_span::DUMMY_SP), ty::TypingEnv::fully_monomorphized())
}
/// Generates the type for a single field for a dynamic vtable.
/// In particular, these fields are function pointers.
fn trait_method_vtable_field_type(
&mut self,
instance: Instance<'tcx>,
idx: usize,
) -> DatatypeComponent {
// Gives a binder with function signature
let instance = rustc_internal::stable(instance);
// Gives an Irep Pointer object for the signature
let fn_ty = self.codegen_dynamic_function_sig(instance);
let fn_ptr = fn_ty.to_pointer();
// vtable field name, i.e., 3_vol (idx_method)
let vtable_field_name = self.vtable_field_name(idx);
DatatypeComponent::field(vtable_field_name, fn_ptr)
}
/// Generates a vtable that looks like this:
/// struct io::error::vtable {
/// void *drop_in_place;
/// size_t size;
/// size_t align;
/// int (*f)(int) f1;
/// ...
/// }
/// Ensures that the vtable is added to the symbol table.
fn codegen_trait_vtable_type(&mut self, t: ty::Ty<'tcx>) -> Type {
let struct_name = self.vtable_name(t);
let pretty_name = format!("{}::vtable", self.ty_pretty_name(t));
self.ensure_struct(&struct_name, pretty_name, |ctx, _| ctx.trait_vtable_field_types(t))
}
/// This will codegen the trait data type. Since this is unsized, we just create a typedef.
///
/// This is relevant when generating the layout of unsized types like `RcBox`.
/// ```
/// struct RcBox<T: ?Sized> {
/// strong: Cell<usize>,
/// weak: Cell<usize>,
/// value: T,
/// }
/// ```
///
/// This behaviour is similar to slices, and `value` is not a pointer.
/// `value` is the concrete object in memory which was casted to an unsized type.
pub fn codegen_trait_data(&mut self, t: ty::Ty<'tcx>) -> Type {
let name = self.normalized_trait_name(t);
let inner_name = name.clone() + "Inner";
debug!(typ=?t, kind=?t.kind(), %name, %inner_name,
"codegen_trait_data_type");
self.ensure(inner_name.clone(), |_ctx, _| {
Symbol::typedef(
&inner_name,
&inner_name,
Type::unit().to_typedef(inner_name.clone()),
Location::None,
)
});
Type::unit().to_typedef(inner_name)
}
/// Codegen the pointer type for a concrete object that implements the trait object.
/// I.e.: A trait object is a fat pointer which contains a pointer to a concrete object
/// and a pointer to its vtable. This method returns a type for the first pointer.
pub fn codegen_trait_data_pointer(&mut self, typ: ty::Ty<'tcx>) -> Type {
assert!(self.use_vtable_fat_pointer(typ));
self.codegen_ty(typ).to_pointer()
}
/// A reference to a `Struct<dyn T>` { .., data: T} is translated to
/// struct RefToTrait {
/// `Struct<dyn T>* data`;
/// `Metadata<dyn T>* vtable;`
/// }
/// Note: T is a `typedef` but data represents the space in memory occupied by
/// the concrete type. We just don't know its size during compilation time.
fn codegen_trait_fat_ptr_type(
&mut self,
pointee_type: ty::Ty<'tcx>,
trait_type: ty::Ty<'tcx>,
) -> Type {
trace!(?pointee_type, ?trait_type, "codegen_trait_fat_ptr_type");
let name = self.ty_mangled_name(pointee_type).to_string() + "::FatPtr";
let pretty_name = format!("{}::FatPtr", self.ty_pretty_name(pointee_type));
let data_type = self.codegen_ty(pointee_type).to_pointer();
self.ensure_struct(&name, &pretty_name, |ctx, _| {
// At this point in time, the vtable hasn't been codegen yet.
// However, all we need to know is its name, which we do know.
// See the comment on codegen_ty_ref.
let vtable_name = ctx.vtable_name(trait_type);
vec![
DatatypeComponent::field("data", data_type),
DatatypeComponent::field("vtable", Type::struct_tag(vtable_name).to_pointer()),
]
})
}
/// `drop_in_place` is a function with type &self -> (), the vtable for
/// dynamic trait objects needs a pointer to it
pub fn trait_vtable_drop_type(&mut self, t: ty::Ty<'tcx>) -> Type {
Type::code_with_unnamed_parameters(vec![self.codegen_ty(t).to_pointer()], Type::unit())
.to_pointer()
}
/// Given a trait of type `t`, determine the fields of the struct that will implement its vtable.
///
/// The order of fields (i.e., the layout of a vtable) is not guaranteed by the compiler.
/// We follow the order from the `TyCtxt::COMMON_VTABLE_ENTRIES`.
fn trait_vtable_field_types(&mut self, t: ty::Ty<'tcx>) -> Vec<DatatypeComponent> {
let mut vtable_base = common_vtable_fields(self.trait_vtable_drop_type(t));
if let ty::Dynamic(binder, _, _) = t.kind() {
// The virtual methods on the trait ref. Some auto traits have no methods.
if let Some(principal) = binder.principal() {
let poly = principal.with_self_ty(self.tcx, t);
let poly = self.tcx.instantiate_bound_regions_with_erased(poly);
let poly = self.tcx.erase_regions(poly);
let mut flds = self
.tcx
.vtable_entries(poly)
.iter()
.cloned()
.enumerate()
.filter_map(|(idx, entry)| match entry {
VtblEntry::Method(instance) => {
Some(self.trait_method_vtable_field_type(instance, idx))
}
// TODO: trait upcasting
// https://github.com/model-checking/kani/issues/358
VtblEntry::TraitVPtr(..) => None,
VtblEntry::MetadataDropInPlace
| VtblEntry::MetadataSize
| VtblEntry::MetadataAlign
| VtblEntry::Vacant => None,
})
.collect();
vtable_base.append(&mut flds);
}
debug!(ty=?t, ?vtable_base, "trait_vtable_field_types");
vtable_base
} else {
unreachable!("Expected to get a dynamic object here");
}
}
/// Gives the name for a trait, i.e., `dyn T`. This does not work for `&dyn T`.
pub fn normalized_trait_name(&self, t: Ty<'tcx>) -> String {
assert!(t.is_trait(), "Type {t} must be a trait type (a dynamic type)");
self.ty_mangled_name(t).to_string()
}
/// Gives the vtable name for a type.
/// In some cases, we have &T, in other cases T, so normalize.
///
/// TODO: to handle trait upcasting, this will need to use a
/// poly existential trait type as a part of the key as well.
/// See compiler/rustc_middle/src/ty/vtable.rs
/// <https://github.com/model-checking/kani/issues/358>
pub fn vtable_name(&self, t: Ty<'tcx>) -> String {
format!("{}::vtable", self.normalized_trait_name(t))
}
pub fn ty_pretty_name(&self, t: Ty<'tcx>) -> InternedString {
use crate::rustc_middle::ty::print::Print;
use rustc_hir::def::Namespace;
let mut printer = FmtPrinter::new(self.tcx, Namespace::TypeNS);
// Monomorphizing the type ensures we get a cannonical form for dynamic trait
// objects with auto traits, such as:
// StructTag("tag-std::boxed::Box<(dyn std::error::Error + std::marker::Send + std::marker::Sync)>") }
// StructTag("tag-std::boxed::Box<dyn std::error::Error + std::marker::Send + std::marker::Sync>") }
let t = self.monomorphize(t);
t.print(&mut printer).unwrap();
with_no_trimmed_paths!(printer.into_buffer()).intern()
}
pub fn ty_mangled_name(&self, t: Ty<'tcx>) -> InternedString {
// Crate resolution: mangled names need to be distinct across different versions
// of the same crate that could be pulled in by dependencies. However, Kani's
// treatment of FFI C calls assumes that we generate the same name for #[repr(C)] types
// as the C name, so don't mangle in that case.
// However, there was an issue with different type instantiations being given the same mangled name.
// https://github.com/model-checking/kani/issues/1438.
// Hence we DO mangle the type name if the type has generic type arguments, even if it's #[repr(C)].
// This is not a restriction because C can only access non-generic types anyway.
// TODO: Skipping name mangling is likely insufficient if a dependent crate has two versions of
// linked C libraries
// https://github.com/model-checking/kani/issues/450
match t.kind() {
TyKind::Adt(def, args) if args.is_empty() && def.repr().c() => {
// For non-generic #[repr(C)] types, use the literal path instead of mangling it.
self.tcx.def_path_str(def.did()).intern()
}
_ => {
// This hash is documented to be the same no matter the crate context
let id = self.tcx.type_id_hash(t).as_u128();
format!("_{id}").intern()
}
}
}
#[allow(dead_code)]
pub fn enum_union_name(&self, ty: Ty<'tcx>) -> String {
format!("{}-union", self.ty_mangled_name(ty))
}
#[allow(dead_code)]
pub fn enum_case_struct_name(&self, ty: Ty<'tcx>, case: &VariantDef) -> String {
format!("{}::{}", self.ty_mangled_name(ty), case.name)
}
fn codegen_ty_raw_array(&mut self, elem_ty: Ty<'tcx>, len: Const<'tcx>) -> Type {
let size = self.codegen_const_internal(len, None).int_constant_value().unwrap();
let elemt = self.codegen_ty(elem_ty);
elemt.array_of(size)
}
/// A foreign type is a type that rust does not know the contents of.
/// We handle this by treating it as an incomplete struct.
fn codegen_foreign(&mut self, ty: Ty<'tcx>, defid: DefId) -> Type {
debug!("codegen_foreign {:?} {:?}", ty, defid);
let name = self.ty_mangled_name(ty).intern();
self.ensure(aggr_tag(name), |ctx, _| {
Symbol::incomplete_struct(name, ctx.ty_pretty_name(ty))
});
Type::struct_tag(name)
}
/// Codegens the an initalizer for variables without one.
/// By default, returns `None` which leaves the variable uninitilized.
/// In CBMC, this translates to a NONDET value.
/// In the future, we might want to replace this with `Poison`.
pub fn codegen_default_initializer(&self, _e: &Expr) -> Option<Expr> {
None
}
/// The unit type in Rust is an empty struct in gotoc
pub fn codegen_ty_unit(&mut self) -> Type {
self.ensure_struct(UNIT_TYPE_EMPTY_STRUCT_NAME, "()", |_, _| vec![])
}
/// The common VTable entries.
/// A VTable is an opaque type to the compiler, but they all follow the same structure.
/// The first three entries are always the following:
/// 1- Function pointer to drop in place.
/// 2- The size of the object.
/// 3- The alignment of the object.
/// We use this common structure to extract information out of a vtable. Since we don't have
/// any information about the original type, we use `void*` to encode the drop fn argument type.
pub fn codegen_ty_common_vtable(&mut self) -> Type {
self.ensure_struct(COMMON_VTABLE_STRUCT_NAME, COMMON_VTABLE_STRUCT_NAME, |_, _| {
let drop_type =
Type::code_with_unnamed_parameters(vec![Type::void_pointer()], Type::unit())
.to_pointer();
common_vtable_fields(drop_type)
})
}
/// codegen for types. it finds a C type which corresponds to a rust type.
/// that means [ty] has to be monomorphized before calling this function.
///
/// check `rustc_ty_utils::layout::layout_of_uncached` for LLVM codegen
///
/// also c.f. <https://www.ralfj.de/blog/2020/04/04/layout-debugging.html>
/// c.f. <https://rust-lang.github.io/unsafe-code-guidelines/introduction.html>
pub fn codegen_ty(&mut self, ty: Ty<'tcx>) -> Type {
// TODO: Remove all monomorphize calls
let normalized =
self.tcx.normalize_erasing_regions(ty::TypingEnv::fully_monomorphized(), ty);
let goto_typ = self.codegen_ty_inner(normalized);
if let Some(tag) = goto_typ.tag() {
self.type_map.entry(tag).or_insert_with(|| {
debug!(mir_type=?normalized, gotoc_name=?tag, ?goto_typ, "codegen_ty: new type");
normalized
});
}
goto_typ
}
fn codegen_ty_inner(&mut self, ty: Ty<'tcx>) -> Type {
trace!(typ=?ty, "codegen_ty");
match ty.kind() {
ty::Int(k) => self.codegen_iint(*k),
ty::Bool => Type::c_bool(),
ty::Char => Type::signed_int(32),
ty::Uint(k) => self.codegen_uint(*k),
ty::Float(k) => match k {
FloatTy::F32 => Type::float(),
FloatTy::F64 => Type::double(),
FloatTy::F16 => Type::float16(),
FloatTy::F128 => Type::float128(),
},
ty::Adt(def, _) if def.repr().simd() => self.codegen_vector(ty),
ty::Adt(def, subst) => {
debug!("variants are: {:?}", def.variants());
if def.is_struct() {
self.codegen_struct(ty, def, subst)
} else if def.is_union() {
self.codegen_union(ty, def, subst)
} else {
self.codegen_enum(ty, def, subst)
}
}
ty::Foreign(defid) => self.codegen_foreign(ty, *defid),
ty::Array(et, len) => self.codegen_ty_raw_array(*et, *len),
ty::Dynamic(..) => {
// This is `dyn Trait` not a reference.
self.codegen_trait_data(ty)
}
// As per zulip, a raw slice/str is a variable length array
// https://rust-lang.zulipchat.com/#narrow/stream/182449-t-compiler.2Fhelp/topic/Memory.20layout.20of.20DST
// &[T] -> { data: *const T, len: usize }
// [T] -> memory location (flexible array)
// Note: This is not valid C but CBMC seems to be ok with it.
ty::Slice(e) => self.codegen_ty(*e).flexible_array_of(),
ty::Str => Type::unsigned_int(8).flexible_array_of(),
ty::Ref(_, t, _) | ty::RawPtr(t, _) => self.codegen_ty_ref(*t),
ty::FnDef(def_id, args) => {
let instance = Instance::try_resolve(
self.tcx,
ty::TypingEnv::fully_monomorphized(),
*def_id,
args,
)
.unwrap()
.unwrap();
self.codegen_fndef_type(instance)
}
ty::FnPtr(sig_tys, hdr) => {
let sig = sig_tys.with(*hdr);
self.codegen_function_sig(sig).to_pointer()
}
ty::Closure(_, subst) => self.codegen_ty_closure(ty, subst),
ty::Coroutine(..) => self.codegen_ty_coroutine(ty),
ty::CoroutineClosure(..) => unimplemented!(
"Kani does not yet support coroutine closures. Please post your example at https://github.com/model-checking/kani/issues/3783"
),
ty::Never => self.ensure_struct(NEVER_TYPE_EMPTY_STRUCT_NAME, "!", |_, _| vec![]),
ty::Tuple(ts) => {
if ts.is_empty() {
self.codegen_ty_unit()
} else {
// we do not have to do two insertions for tuple because it is impossible for
// finite tuples to loop.
self.ensure_struct(
self.ty_mangled_name(ty),
self.ty_pretty_name(ty),
|tcx, _| tcx.codegen_ty_tuple_fields(ty, ts),
)
}
}
// This object has the same layout as base. For now, translate this into `(base)`.
// The only difference is the niche.
ty::Pat(base_ty, ..) => {
self.ensure_struct(self.ty_mangled_name(ty), self.ty_pretty_name(ty), |tcx, _| {
tcx.codegen_ty_tuple_like(ty, vec![*base_ty])
})
}
ty::Alias(..) => {
unreachable!("Type should've been normalized already")
}
// shouldn't come to here after mormomorphization
ty::Bound(_, _) | ty::Param(_) => unreachable!("monomorphization bug"),
// type checking remnants which shouldn't be reachable
ty::CoroutineWitness(_, _) | ty::Infer(_) | ty::Placeholder(_) | ty::Error(_) => {
unreachable!("remnants of type checking")
}
ty::UnsafeBinder(_) => todo!(
"Implement support for UnsafeBinder https://github.com/rust-lang/rust/issues/130516"
),
}
}
pub(crate) fn codegen_iint(&self, k: IntTy) -> Type {
match k {
IntTy::I8 => Type::signed_int(8),
IntTy::I16 => Type::signed_int(16),
IntTy::I32 => Type::signed_int(32),
IntTy::I64 => Type::signed_int(64),
IntTy::I128 => Type::signed_int(128),
IntTy::Isize => Type::ssize_t(),
}
}
pub fn codegen_uint(&self, k: UintTy) -> Type {
match k {
UintTy::U8 => Type::unsigned_int(8),
UintTy::U16 => Type::unsigned_int(16),
UintTy::U32 => Type::unsigned_int(32),
UintTy::U64 => Type::unsigned_int(64),
UintTy::U128 => Type::unsigned_int(128),
UintTy::Usize => Type::size_t(),
}
}
fn codegen_ty_tuple_fields(
&mut self,
t: Ty<'tcx>,
tys: &List<Ty<'tcx>>,
) -> Vec<DatatypeComponent> {
self.codegen_ty_tuple_like(t, tys.to_vec())
}
fn codegen_struct_padding(
&self,
current_offset: Size,
next_offset: Size,
idx: usize,
) -> Option<DatatypeComponent> {
assert!(current_offset <= next_offset);
if current_offset < next_offset {
// We need to pad to the next offset
let padding_size = next_offset - current_offset;
let name = format!("$pad{idx}");
Some(DatatypeComponent::padding(name, padding_size.bits()))
} else {
None
}
}
/// Adds padding to ensure that the size of the struct is a multiple of the alignment
fn codegen_alignment_padding(
&self,
size: Size,
layout: &LayoutData<FieldIdx, VariantIdx>,
idx: usize,
) -> Option<DatatypeComponent> {
let align = Size::from_bits(layout.align.abi.bits());
let overhang = Size::from_bits(size.bits() % align.bits());
if overhang != Size::ZERO {
self.codegen_struct_padding(size, size + align - overhang, idx)
} else {
None
}
}
/// generate a struct based on the layout
/// the fields and types are determined by flds while their order is determined by layout.
///
/// once the order is determined, this function also computes padding fields based on the size
/// and the offset of each field as appropriate.
///
/// * name - the name of the struct
/// * flds - list of field name and type pairs, but the order is not specified by this list
/// * layout - layout of the struct
/// * initial_offset - offset which has been accumulated in parent struct, in bits
fn codegen_struct_fields(
&mut self,
flds: Vec<(String, Ty<'tcx>)>,
layout: &LayoutData<FieldIdx, VariantIdx>,
initial_offset: Size,
) -> Vec<DatatypeComponent> {
match &layout.fields {
FieldsShape::Arbitrary { offsets, memory_index } => {
assert_eq!(flds.len(), offsets.len());
assert_eq!(offsets.len(), memory_index.len());
let mut final_fields = Vec::with_capacity(flds.len());
let mut offset = initial_offset;
for idx in layout.fields.index_by_increasing_offset() {
let fld_offset = offsets[rustc_abi::FieldIdx::from(idx)];
let (fld_name, fld_ty) = &flds[idx];
if let Some(padding) =
self.codegen_struct_padding(offset, fld_offset, final_fields.len())
{
final_fields.push(padding)
}
// we insert the actual field
final_fields.push(DatatypeComponent::field(fld_name, self.codegen_ty(*fld_ty)));
let layout = self.layout_of(*fld_ty);
// we compute the overall offset of the end of the current struct
offset = fld_offset + layout.size;
}
final_fields.extend(self.codegen_alignment_padding(
offset,
layout,
final_fields.len(),
));
final_fields
}
// Primitives, such as NEVER, have no fields
FieldsShape::Primitive => vec![],
_ => unreachable!("{}\n{:?}", self.current_fn().readable_name(), layout.fields),
}
}
fn codegen_ty_tuple_like(&mut self, t: Ty<'tcx>, tys: Vec<Ty<'tcx>>) -> Vec<DatatypeComponent> {
let layout = self.layout_of(t);
let flds: Vec<_> =
tys.iter().enumerate().map(|(i, t)| (GotocCtx::tuple_fld_name(i), *t)).collect();
// tuple cannot have other initial offset
self.codegen_struct_fields(flds, &layout.layout.0, Size::ZERO)
}
/// A closure is a struct of all its environments. That is, a closure is
/// just a tuple with a unique type identifier, so that Fn related traits
/// can find its impl.
fn codegen_ty_closure(&mut self, t: Ty<'tcx>, args: ty::GenericArgsRef<'tcx>) -> Type {
self.ensure_struct(self.ty_mangled_name(t), self.ty_pretty_name(t), |ctx, _| {
ctx.codegen_ty_tuple_like(t, args.as_closure().upvar_tys().to_vec())
})
}
/// Translate a coroutine type similarly to an enum with a variant for each suspend point.
///
/// Consider the following coroutine:
/// ```
/// || {
/// let a = true;
/// let b = &a;
/// yield;
/// assert_eq!(b as *const _, &a as *const _);
/// yield;
/// };
/// ```
///
/// Rustc compiles this to something similar to the following enum (but there are differences, see below!),
/// as described at the top of <https://github.com/rust-lang/rust/blob/master/compiler/rustc_mir_transform/src/coroutine.rs>:
///
/// ```ignore
/// enum CoroutineEnum {
/// Unresumed, // initial state of the coroutine
/// Returned, // coroutine has returned
/// Panicked, // coroutine has panicked
/// Suspend0 { b: &bool, a: bool }, // state after suspending (`yield`ing) for the first time
/// Suspend1, // state after suspending (`yield`ing) for the second time
/// }
/// ```
///
/// However, its layout may differ from normal Rust enums in the following ways:
/// * Contrary to enums, the discriminant may not be at offset 0.
/// * Contrary to enums, there may be other fields than the discriminant "at the top level" (outside the variants).
///
/// This means that we CANNOT use the enum translation, which would be roughly as follows:
///
/// ```ignore
/// struct CoroutineEnum {
/// int case; // discriminant
/// union CoroutineEnum-union cases; // variant
/// }
///
/// union CoroutineEnum-union {
/// struct Unresumed variant0;
/// struct Returned variant1;
/// // ...
/// }
/// ```
///
/// Instead, we use the following translation:
///
/// ```ignore
/// union CoroutineEnum {
/// struct DirectFields direct_fields;
/// struct Unresumed coroutine_variant_Unresumed;
/// struct Returned coroutine_variant_Returned;
/// // ...
/// }
///
/// struct DirectFields {
/// // padding (for bool *b in Suspend0 below)
/// char case;
/// // padding (for bool a in Suspend0 below)
/// }
///
/// struct Unresumed {
/// // padding (this variant has no fields)
/// }
///
/// // ...
///
/// struct Suspend0 {
/// bool *coroutine_field_0; // variable b in the coroutine code above
/// // padding (for char case in DirectFields)
/// bool coroutine_field_1; // variable a in the coroutine code above
/// }
/// ```
///
/// Of course, if the coroutine has any other top-level/direct fields, they'd be included in the `DirectFields` struct as well.
fn codegen_ty_coroutine(&mut self, ty: Ty<'tcx>) -> Type {
let coroutine_name = self.ty_mangled_name(ty);
let pretty_name = self.ty_pretty_name(ty);
debug!(?pretty_name, "codeged_ty_coroutine");
self.ensure_union(self.ty_mangled_name(ty), pretty_name, |ctx, _| {
let type_and_layout = ctx.layout_of(ty);
let (discriminant_field, variants) = match &type_and_layout.variants {
Variants::Multiple {
tag_encoding: TagEncoding::Direct,
tag_field,
variants,
..
} => (tag_field, variants),
_ => unreachable!("Coroutines have more than one variant and use direct encoding"),
};
// generate a struct for the direct fields of the layout (fields that don't occur in the variants)
let direct_fields = DatatypeComponent::Field {
name: "direct_fields".into(),
typ: ctx.codegen_coroutine_variant_struct(
coroutine_name,
pretty_name,
type_and_layout,
"DirectFields".into(),
Some(*discriminant_field),
),
};
let mut fields = vec![direct_fields];
for var_idx in variants.indices() {
let variant_name = CoroutineArgs::variant_name(var_idx).into();
fields.push(DatatypeComponent::Field {
name: ctx.coroutine_variant_name(var_idx),
typ: ctx.codegen_coroutine_variant_struct(
coroutine_name,
pretty_name,
type_and_layout.for_variant(ctx, var_idx),
variant_name,
None,
),
});
}
fields
})
}
/// Generates a struct for a variant of the coroutine.
///
/// The field `discriminant_field` should be `Some(idx)` when generating the variant for the direct (top-level) fields of the coroutine.
/// Then the field with the index `idx` will be treated as the discriminant and will be given a special name to work with the rest of the code.
/// The field `discriminant_field` should be `None` when generating an actual variant of the coroutine because those don't contain the discriminant as a field.
fn codegen_coroutine_variant_struct(
&mut self,
coroutine_name: InternedString,
pretty_coroutine_name: InternedString,
type_and_layout: TyAndLayout<'tcx, Ty<'tcx>>,
variant_name: InternedString,
discriminant_field: Option<usize>,
) -> Type {
let struct_name = format!("{coroutine_name}::{variant_name}");
let pretty_struct_name = format!("{pretty_coroutine_name}::{variant_name}");
debug!(?pretty_struct_name, "codeged_coroutine_variant_struct");
self.ensure_struct(struct_name, pretty_struct_name, |ctx, _| {
let mut offset = Size::ZERO;
let mut fields = vec![];
for idx in type_and_layout.fields.index_by_increasing_offset() {
// The discriminant field needs to have a special name to work with the rest of the code.
// If discriminant_field is None, this variant does not have the discriminant as a field.
let field_name = if Some(idx) == discriminant_field {
"case".into()
} else {
ctx.coroutine_field_name(idx)
};
let field_ty = type_and_layout.field(ctx, idx).ty;
let field_offset = type_and_layout.fields.offset(idx);
let field_size = type_and_layout.field(ctx, idx).size;
if let Some(padding) = ctx.codegen_struct_padding(offset, field_offset, idx) {
fields.push(padding);
}
fields.push(DatatypeComponent::Field {
name: field_name,
typ: ctx.codegen_ty(field_ty),
});
offset = field_offset + field_size;
}
fields.extend(ctx.codegen_alignment_padding(
offset,
&type_and_layout.layout.0,
fields.len(),
));
fields
})
}
pub fn coroutine_variant_name(&self, var_idx: VariantIdx) -> InternedString {
format!("coroutine_variant_{}", CoroutineArgs::variant_name(var_idx)).into()
}
pub fn coroutine_field_name(&self, field_idx: usize) -> InternedString {
format!("coroutine_field_{field_idx}").into()
}
/// Codegen "fat pointers" to the given `pointee_type`. These are pointers with metadata.
///
/// There are three kinds of fat pointers:
/// 1. references to slices (`matches!(pointee_type.kind(), ty::Slice(..) | ty::Str)`).
/// 2. references to trait objects (`matches!(pointee_type.kind(), ty::Dynamic)`).
/// 3. references to structs whose last field is a unsized object (slice / trait)
/// - `matches!(pointee_type.kind(), ty::Adt(..) if self.is_unsized(t))
///
fn codegen_fat_ptr(&mut self, pointee_type: Ty<'tcx>) -> Type {
assert!(
!self.use_thin_pointer(pointee_type),
"Generating a fat pointer for a type requiring a thin pointer: {:?}",
pointee_type.kind()
);
if self.use_slice_fat_pointer(pointee_type) {
let pointer_name = match pointee_type.kind() {
ty::Slice(..) => self.ty_mangled_name(pointee_type),
ty::Str => "refstr".intern(),
ty::Adt(..) => format!("&{}", self.ty_mangled_name(pointee_type)).intern(),
kind => unreachable!("Generating a slice fat pointer to {:?}", kind),
};
let pretty_name = format!("&{}", self.ty_pretty_name(pointee_type));
let element_type = match pointee_type.kind() {
ty::Slice(elt_type) => self.codegen_ty(*elt_type),
ty::Str => Type::unsigned_int(8),
// For adt, see https://rust-lang.zulipchat.com/#narrow/stream/182449-t-compiler.2Fhelp
ty::Adt(..) => self.codegen_ty(pointee_type),
kind => unreachable!("Generating a slice fat pointer to {:?}", kind),
};
self.ensure_struct(pointer_name, pretty_name, |_, _| {
vec![
DatatypeComponent::field("data", element_type.to_pointer()),
DatatypeComponent::field("len", Type::size_t()),
]
})
} else if self.use_vtable_fat_pointer(pointee_type) {
// Pointee type can either be `dyn T` or `Struct<dyn T>`.
// The vtable for both cases is the vtable of `dyn T`.
let trait_type = self.extract_trait_type(pointee_type).unwrap();
self.codegen_trait_vtable_type(trait_type);
self.codegen_trait_fat_ptr_type(pointee_type, trait_type)
} else {
unreachable!(
"A pointer is either a thin pointer, slice fat pointer, or vtable fat pointer."
);
}
}
pub fn codegen_ty_ref(&mut self, pointee_type: Ty<'tcx>) -> Type {
// Normalize pointee_type to remove projection and opaque types
trace!(?pointee_type, "codegen_ty_ref");
let pointee_type =
self.tcx.normalize_erasing_regions(ty::TypingEnv::fully_monomorphized(), pointee_type);
if !self.use_thin_pointer(pointee_type) {
return self.codegen_fat_ptr(pointee_type);
}
match pointee_type.kind() {
ty::Dynamic(..) | ty::Slice(_) | ty::Str => {
unreachable!("Should have generated a fat pointer")
}