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
use crate::ty::{self, Ty};
use rustc_middle::mir;
use rustc_macros::HashStable;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum IntTy {
U(ty::UintTy),
I,
CEnum,
Bool,
Char,
}
impl IntTy {
pub fn is_signed(self) -> bool {
matches!(self, Self::I)
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum CastTy<'tcx> {
Int(IntTy),
Float,
FnPtr,
Ptr(ty::TypeAndMut<'tcx>),
DynStar,
}
#[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
pub enum CastKind {
CoercionCast,
PtrPtrCast,
PtrAddrCast,
AddrPtrCast,
NumericCast,
EnumCast,
PrimIntCast,
U8CharCast,
ArrayPtrCast,
FnPtrPtrCast,
FnPtrAddrCast,
DynStarCast,
}
impl<'tcx> CastTy<'tcx> {
pub fn from_ty(t: Ty<'tcx>) -> Option<CastTy<'tcx>> {
match *t.kind() {
ty::Bool => Some(CastTy::Int(IntTy::Bool)),
ty::Char => Some(CastTy::Int(IntTy::Char)),
ty::Int(_) => Some(CastTy::Int(IntTy::I)),
ty::Infer(ty::InferTy::IntVar(_)) => Some(CastTy::Int(IntTy::I)),
ty::Infer(ty::InferTy::FloatVar(_)) => Some(CastTy::Float),
ty::Uint(u) => Some(CastTy::Int(IntTy::U(u))),
ty::Float(_) => Some(CastTy::Float),
ty::Adt(d, _) if d.is_enum() && d.is_payloadfree() => Some(CastTy::Int(IntTy::CEnum)),
ty::RawPtr(mt) => Some(CastTy::Ptr(mt)),
ty::FnPtr(..) => Some(CastTy::FnPtr),
ty::Dynamic(_, _, ty::DynStar) => Some(CastTy::DynStar),
_ => None,
}
}
}
pub fn mir_cast_kind<'tcx>(from_ty: Ty<'tcx>, cast_ty: Ty<'tcx>) -> mir::CastKind {
let from = CastTy::from_ty(from_ty);
let cast = CastTy::from_ty(cast_ty);
let cast_kind = match (from, cast) {
(Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Int(_))) => {
mir::CastKind::PointerExposeAddress
}
(Some(CastTy::Int(_)), Some(CastTy::Ptr(_))) => mir::CastKind::PointerFromExposedAddress,
(_, Some(CastTy::DynStar)) => mir::CastKind::DynStar,
(Some(CastTy::Int(_)), Some(CastTy::Int(_))) => mir::CastKind::IntToInt,
(Some(CastTy::FnPtr), Some(CastTy::Ptr(_))) => mir::CastKind::FnPtrToPtr,
(Some(CastTy::Float), Some(CastTy::Int(_))) => mir::CastKind::FloatToInt,
(Some(CastTy::Int(_)), Some(CastTy::Float)) => mir::CastKind::IntToFloat,
(Some(CastTy::Float), Some(CastTy::Float)) => mir::CastKind::FloatToFloat,
(Some(CastTy::Ptr(_)), Some(CastTy::Ptr(_))) => mir::CastKind::PtrToPtr,
(_, _) => {
bug!("Attempting to cast non-castable types {:?} and {:?}", from_ty, cast_ty)
}
};
cast_kind
}