Skip to main content

rustc_codegen_llvm/
type_.rs

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