rustc_codegen_llvm/
type_.rs

1use std::{fmt, ptr};
2
3use libc::{c_char, c_uint};
4use rustc_abi::{AddressSpace, Align, Integer, Reg, Size};
5use rustc_codegen_ssa::common::TypeKind;
6use rustc_codegen_ssa::traits::*;
7use rustc_data_structures::small_c_str::SmallCStr;
8use rustc_middle::bug;
9use rustc_middle::ty::layout::TyAndLayout;
10use rustc_middle::ty::{self, Ty};
11use rustc_target::callconv::{CastTarget, FnAbi};
12
13use crate::abi::{FnAbiLlvmExt, LlvmType};
14use crate::context::{CodegenCx, SimpleCx};
15pub(crate) use crate::llvm::Type;
16use crate::llvm::{Bool, False, Metadata, True};
17use crate::type_of::LayoutLlvmExt;
18use crate::value::Value;
19use crate::{common, llvm};
20
21impl PartialEq for Type {
22    fn eq(&self, other: &Self) -> bool {
23        ptr::eq(self, other)
24    }
25}
26
27impl fmt::Debug for Type {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        f.write_str(
30            &llvm::build_string(|s| unsafe {
31                llvm::LLVMRustWriteTypeToString(self, s);
32            })
33            .expect("non-UTF8 type description from LLVM"),
34        )
35    }
36}
37
38impl<'ll> CodegenCx<'ll, '_> {}
39impl<'ll> SimpleCx<'ll> {
40    pub(crate) fn type_named_struct(&self, name: &str) -> &'ll Type {
41        let name = SmallCStr::new(name);
42        unsafe { llvm::LLVMStructCreateNamed(self.llcx, name.as_ptr()) }
43    }
44
45    pub(crate) fn set_struct_body(&self, ty: &'ll Type, els: &[&'ll Type], packed: bool) {
46        unsafe { llvm::LLVMStructSetBody(ty, els.as_ptr(), els.len() as c_uint, packed as Bool) }
47    }
48    pub(crate) fn type_void(&self) -> &'ll Type {
49        unsafe { llvm::LLVMVoidTypeInContext(self.llcx) }
50    }
51    pub(crate) fn type_token(&self) -> &'ll Type {
52        unsafe { llvm::LLVMTokenTypeInContext(self.llcx) }
53    }
54
55    pub(crate) fn type_metadata(&self) -> &'ll Type {
56        unsafe { llvm::LLVMMetadataTypeInContext(self.llcx) }
57    }
58
59    ///x Creates an integer type with the given number of bits, e.g., i24
60    pub(crate) fn type_ix(&self, num_bits: u64) -> &'ll Type {
61        unsafe { llvm::LLVMIntTypeInContext(self.llcx, num_bits as c_uint) }
62    }
63
64    pub(crate) fn type_vector(&self, ty: &'ll Type, len: u64) -> &'ll Type {
65        unsafe { llvm::LLVMVectorType(ty, len as c_uint) }
66    }
67
68    pub(crate) fn func_params_types(&self, ty: &'ll Type) -> Vec<&'ll Type> {
69        unsafe {
70            let n_args = llvm::LLVMCountParamTypes(ty) as usize;
71            let mut args = Vec::with_capacity(n_args);
72            llvm::LLVMGetParamTypes(ty, args.as_mut_ptr());
73            args.set_len(n_args);
74            args
75        }
76    }
77}
78impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
79    pub(crate) fn type_bool(&self) -> &'ll Type {
80        self.type_i8()
81    }
82
83    pub(crate) fn type_int_from_ty(&self, t: ty::IntTy) -> &'ll Type {
84        match t {
85            ty::IntTy::Isize => self.type_isize(),
86            ty::IntTy::I8 => self.type_i8(),
87            ty::IntTy::I16 => self.type_i16(),
88            ty::IntTy::I32 => self.type_i32(),
89            ty::IntTy::I64 => self.type_i64(),
90            ty::IntTy::I128 => self.type_i128(),
91        }
92    }
93
94    pub(crate) fn type_uint_from_ty(&self, t: ty::UintTy) -> &'ll Type {
95        match t {
96            ty::UintTy::Usize => self.type_isize(),
97            ty::UintTy::U8 => self.type_i8(),
98            ty::UintTy::U16 => self.type_i16(),
99            ty::UintTy::U32 => self.type_i32(),
100            ty::UintTy::U64 => self.type_i64(),
101            ty::UintTy::U128 => self.type_i128(),
102        }
103    }
104
105    pub(crate) fn type_float_from_ty(&self, t: ty::FloatTy) -> &'ll Type {
106        match t {
107            ty::FloatTy::F16 => self.type_f16(),
108            ty::FloatTy::F32 => self.type_f32(),
109            ty::FloatTy::F64 => self.type_f64(),
110            ty::FloatTy::F128 => self.type_f128(),
111        }
112    }
113
114    /// Return an LLVM type that has at most the required alignment,
115    /// and exactly the required size, as a best-effort padding array.
116    pub(crate) fn type_padding_filler(&self, size: Size, align: Align) -> &'ll Type {
117        let unit = Integer::approximate_align(self, align);
118        let size = size.bytes();
119        let unit_size = unit.size().bytes();
120        assert_eq!(size % unit_size, 0);
121        self.type_array(self.type_from_integer(unit), size / unit_size)
122    }
123}
124impl<'ll> SimpleCx<'ll> {
125    pub(crate) fn type_variadic_func(&self, args: &[&'ll Type], ret: &'ll Type) -> &'ll Type {
126        unsafe { llvm::LLVMFunctionType(ret, args.as_ptr(), args.len() as c_uint, True) }
127    }
128
129    pub(crate) fn type_i1(&self) -> &'ll Type {
130        unsafe { llvm::LLVMInt1TypeInContext(self.llcx) }
131    }
132
133    pub(crate) fn type_struct(&self, els: &[&'ll Type], packed: bool) -> &'ll Type {
134        unsafe {
135            llvm::LLVMStructTypeInContext(
136                self.llcx,
137                els.as_ptr(),
138                els.len() as c_uint,
139                packed as Bool,
140            )
141        }
142    }
143}
144
145impl<'ll, 'tcx> BaseTypeCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
146    fn type_i8(&self) -> &'ll Type {
147        unsafe { llvm::LLVMInt8TypeInContext(self.llcx) }
148    }
149
150    fn type_i16(&self) -> &'ll Type {
151        unsafe { llvm::LLVMInt16TypeInContext(self.llcx) }
152    }
153
154    fn type_i32(&self) -> &'ll Type {
155        unsafe { llvm::LLVMInt32TypeInContext(self.llcx) }
156    }
157
158    fn type_i64(&self) -> &'ll Type {
159        unsafe { llvm::LLVMInt64TypeInContext(self.llcx) }
160    }
161
162    fn type_i128(&self) -> &'ll Type {
163        unsafe { llvm::LLVMIntTypeInContext(self.llcx, 128) }
164    }
165
166    fn type_isize(&self) -> &'ll Type {
167        self.isize_ty
168    }
169
170    fn type_f16(&self) -> &'ll Type {
171        unsafe { llvm::LLVMHalfTypeInContext(self.llcx) }
172    }
173
174    fn type_f32(&self) -> &'ll Type {
175        unsafe { llvm::LLVMFloatTypeInContext(self.llcx) }
176    }
177
178    fn type_f64(&self) -> &'ll Type {
179        unsafe { llvm::LLVMDoubleTypeInContext(self.llcx) }
180    }
181
182    fn type_f128(&self) -> &'ll Type {
183        unsafe { llvm::LLVMFP128TypeInContext(self.llcx) }
184    }
185
186    fn type_func(&self, args: &[&'ll Type], ret: &'ll Type) -> &'ll Type {
187        unsafe { llvm::LLVMFunctionType(ret, args.as_ptr(), args.len() as c_uint, False) }
188    }
189
190    fn type_kind(&self, ty: &'ll Type) -> TypeKind {
191        unsafe { llvm::LLVMRustGetTypeKind(ty).to_generic() }
192    }
193
194    fn type_ptr(&self) -> &'ll Type {
195        self.type_ptr_ext(AddressSpace::DATA)
196    }
197
198    fn type_ptr_ext(&self, address_space: AddressSpace) -> &'ll Type {
199        unsafe { llvm::LLVMPointerTypeInContext(self.llcx, address_space.0) }
200    }
201
202    fn element_type(&self, ty: &'ll Type) -> &'ll Type {
203        match self.type_kind(ty) {
204            TypeKind::Array | TypeKind::Vector => unsafe { llvm::LLVMGetElementType(ty) },
205            TypeKind::Pointer => bug!("element_type is not supported for opaque pointers"),
206            other => bug!("element_type called on unsupported type {other:?}"),
207        }
208    }
209
210    fn vector_length(&self, ty: &'ll Type) -> usize {
211        unsafe { llvm::LLVMGetVectorSize(ty) as usize }
212    }
213
214    fn float_width(&self, ty: &'ll Type) -> usize {
215        match self.type_kind(ty) {
216            TypeKind::Half => 16,
217            TypeKind::Float => 32,
218            TypeKind::Double => 64,
219            TypeKind::X86_FP80 => 80,
220            TypeKind::FP128 | TypeKind::PPC_FP128 => 128,
221            other => bug!("llvm_float_width called on a non-float type {other:?}"),
222        }
223    }
224
225    fn int_width(&self, ty: &'ll Type) -> u64 {
226        unsafe { llvm::LLVMGetIntTypeWidth(ty) as u64 }
227    }
228
229    fn val_ty(&self, v: &'ll Value) -> &'ll Type {
230        common::val_ty(v)
231    }
232
233    fn type_array(&self, ty: &'ll Type, len: u64) -> &'ll Type {
234        unsafe { llvm::LLVMArrayType2(ty, len) }
235    }
236}
237
238impl Type {
239    /// Creates an integer type with the given number of bits, e.g., i24
240    pub(crate) fn ix_llcx(llcx: &llvm::Context, num_bits: u64) -> &Type {
241        unsafe { llvm::LLVMIntTypeInContext(llcx, num_bits as c_uint) }
242    }
243
244    pub(crate) fn ptr_llcx(llcx: &llvm::Context) -> &Type {
245        unsafe { llvm::LLVMPointerTypeInContext(llcx, AddressSpace::DATA.0) }
246    }
247}
248
249impl<'ll, 'tcx> LayoutTypeCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
250    fn backend_type(&self, layout: TyAndLayout<'tcx>) -> &'ll Type {
251        layout.llvm_type(self)
252    }
253    fn immediate_backend_type(&self, layout: TyAndLayout<'tcx>) -> &'ll Type {
254        layout.immediate_llvm_type(self)
255    }
256    fn is_backend_immediate(&self, layout: TyAndLayout<'tcx>) -> bool {
257        layout.is_llvm_immediate()
258    }
259    fn is_backend_scalar_pair(&self, layout: TyAndLayout<'tcx>) -> bool {
260        layout.is_llvm_scalar_pair()
261    }
262    fn scalar_pair_element_backend_type(
263        &self,
264        layout: TyAndLayout<'tcx>,
265        index: usize,
266        immediate: bool,
267    ) -> &'ll Type {
268        layout.scalar_pair_element_llvm_type(self, index, immediate)
269    }
270    fn cast_backend_type(&self, ty: &CastTarget) -> &'ll Type {
271        ty.llvm_type(self)
272    }
273    fn fn_decl_backend_type(&self, fn_abi: &FnAbi<'tcx, Ty<'tcx>>) -> &'ll Type {
274        fn_abi.llvm_type(self)
275    }
276    fn fn_ptr_backend_type(&self, fn_abi: &FnAbi<'tcx, Ty<'tcx>>) -> &'ll Type {
277        fn_abi.ptr_to_llvm_type(self)
278    }
279    fn reg_backend_type(&self, ty: &Reg) -> &'ll Type {
280        ty.llvm_type(self)
281    }
282}
283
284impl<'ll, 'tcx> TypeMembershipCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
285    fn add_type_metadata(&self, function: &'ll Value, typeid: String) {
286        let typeid_metadata = self.typeid_metadata(typeid).unwrap();
287        unsafe {
288            let v = [llvm::LLVMValueAsMetadata(self.const_usize(0)), typeid_metadata];
289            llvm::LLVMRustGlobalAddMetadata(
290                function,
291                llvm::MD_type as c_uint,
292                llvm::LLVMMDNodeInContext2(self.llcx, v.as_ptr(), v.len()),
293            )
294        }
295    }
296
297    fn set_type_metadata(&self, function: &'ll Value, typeid: String) {
298        let typeid_metadata = self.typeid_metadata(typeid).unwrap();
299        unsafe {
300            let v = [llvm::LLVMValueAsMetadata(self.const_usize(0)), typeid_metadata];
301            llvm::LLVMGlobalSetMetadata(
302                function,
303                llvm::MD_type as c_uint,
304                llvm::LLVMMDNodeInContext2(self.llcx, v.as_ptr(), v.len()),
305            )
306        }
307    }
308
309    fn typeid_metadata(&self, typeid: String) -> Option<&'ll Metadata> {
310        Some(unsafe {
311            llvm::LLVMMDStringInContext2(self.llcx, typeid.as_ptr() as *const c_char, typeid.len())
312        })
313    }
314
315    fn add_kcfi_type_metadata(&self, function: &'ll Value, kcfi_typeid: u32) {
316        let kcfi_type_metadata = self.const_u32(kcfi_typeid);
317        unsafe {
318            llvm::LLVMRustGlobalAddMetadata(
319                function,
320                llvm::MD_kcfi_type as c_uint,
321                llvm::LLVMMDNodeInContext2(
322                    self.llcx,
323                    &llvm::LLVMValueAsMetadata(kcfi_type_metadata),
324                    1,
325                ),
326            )
327        }
328    }
329
330    fn set_kcfi_type_metadata(&self, function: &'ll Value, kcfi_typeid: u32) {
331        let kcfi_type_metadata = self.const_u32(kcfi_typeid);
332        unsafe {
333            llvm::LLVMGlobalSetMetadata(
334                function,
335                llvm::MD_kcfi_type as c_uint,
336                llvm::LLVMMDNodeInContext2(
337                    self.llcx,
338                    &llvm::LLVMValueAsMetadata(kcfi_type_metadata),
339                    1,
340                ),
341            )
342        }
343    }
344}