inkwell/types/
struct_type.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
use llvm_sys::core::{
    LLVMConstNamedStruct, LLVMCountStructElementTypes, LLVMGetStructElementTypes, LLVMGetStructName,
    LLVMIsOpaqueStruct, LLVMIsPackedStruct, LLVMStructGetTypeAtIndex, LLVMStructSetBody,
};
use llvm_sys::prelude::{LLVMTypeRef, LLVMValueRef};

use std::ffi::CStr;
use std::fmt::{self, Display};
use std::mem::forget;

use crate::context::ContextRef;
use crate::support::LLVMString;
use crate::types::enums::BasicMetadataTypeEnum;
use crate::types::traits::AsTypeRef;
use crate::types::{ArrayType, BasicTypeEnum, FunctionType, PointerType, Type};
use crate::values::{ArrayValue, AsValueRef, BasicValueEnum, IntValue, StructValue};
use crate::AddressSpace;

/// A `StructType` is the type of a heterogeneous container of types.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct StructType<'ctx> {
    struct_type: Type<'ctx>,
}

impl<'ctx> StructType<'ctx> {
    /// Create `StructType` from [`LLVMTypeRef`]
    ///
    /// # Safety
    /// Undefined behavior, if referenced type isn't struct type
    pub unsafe fn new(struct_type: LLVMTypeRef) -> Self {
        assert!(!struct_type.is_null());

        StructType {
            struct_type: Type::new(struct_type),
        }
    }

    /// Gets the type of a field belonging to this `StructType`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use inkwell::context::Context;
    ///
    /// let context = Context::create();
    /// let f32_type = context.f32_type();
    /// let struct_type = context.struct_type(&[f32_type.into()], false);
    ///
    /// assert_eq!(struct_type.get_field_type_at_index(0).unwrap().into_float_type(), f32_type);
    /// ```
    pub fn get_field_type_at_index(self, index: u32) -> Option<BasicTypeEnum<'ctx>> {
        // LLVM doesn't seem to just return null if opaque.
        // TODO: One day, with SubTypes (& maybe specialization?) we could just
        // impl this method for non opaque structs only
        if self.is_opaque() {
            return None;
        }

        // OoB indexing seems to be unchecked and therefore is UB
        if index >= self.count_fields() {
            return None;
        }

        Some(unsafe { self.get_field_type_at_index_unchecked(index) })
    }

    /// Gets the type of a field belonging to this `StructType`.
    ///
    /// # Safety
    ///
    /// The index must be less than [StructType::count_fields] and the struct must not be opaque.
    pub unsafe fn get_field_type_at_index_unchecked(self, index: u32) -> BasicTypeEnum<'ctx> {
        unsafe { BasicTypeEnum::new(LLVMStructGetTypeAtIndex(self.as_type_ref(), index)) }
    }

    /// Creates a `StructValue` based on this `StructType`'s definition.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use inkwell::context::Context;
    ///
    /// let context = Context::create();
    /// let f32_type = context.f32_type();
    /// let f32_zero = f32_type.const_float(0.);
    /// let struct_type = context.struct_type(&[f32_type.into()], false);
    /// let struct_val = struct_type.const_named_struct(&[f32_zero.into()]);
    /// ```
    pub fn const_named_struct(self, values: &[BasicValueEnum<'ctx>]) -> StructValue<'ctx> {
        let mut args: Vec<LLVMValueRef> = values.iter().map(|val| val.as_value_ref()).collect();
        unsafe {
            StructValue::new(LLVMConstNamedStruct(
                self.as_type_ref(),
                args.as_mut_ptr(),
                args.len() as u32,
            ))
        }
    }

    /// Creates a constant zero value of this `StructType`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use inkwell::context::Context;
    ///
    /// let context = Context::create();
    /// let f32_type = context.f32_type();
    /// let struct_type = context.struct_type(&[f32_type.into(), f32_type.into()], false);
    /// let struct_zero = struct_type.const_zero();
    /// ```
    pub fn const_zero(self) -> StructValue<'ctx> {
        unsafe { StructValue::new(self.struct_type.const_zero()) }
    }

    // TODO: impl it only for StructType<T*>?
    /// Gets the size of this `StructType`. Value may vary depending on the target architecture.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use inkwell::context::Context;
    ///
    /// let context = Context::create();
    /// let f32_type = context.f32_type();
    /// let f32_struct_type = context.struct_type(&[f32_type.into()], false);
    /// let f32_struct_type_size = f32_struct_type.size_of();
    /// ```
    pub fn size_of(self) -> Option<IntValue<'ctx>> {
        self.struct_type.size_of()
    }

    /// Gets the alignment of this `StructType`. Value may vary depending on the target architecture.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use inkwell::context::Context;
    ///
    /// let context = Context::create();
    /// let f32_type = context.f32_type();
    /// let struct_type = context.struct_type(&[f32_type.into(), f32_type.into()], false);
    /// let struct_type_alignment = struct_type.get_alignment();
    /// ```
    pub fn get_alignment(self) -> IntValue<'ctx> {
        self.struct_type.get_alignment()
    }

    /// Gets a reference to the `Context` this `StructType` was created in.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use inkwell::context::Context;
    ///
    /// let context = Context::create();
    /// let f32_type = context.f32_type();
    /// let struct_type = context.struct_type(&[f32_type.into(), f32_type.into()], false);
    ///
    /// assert_eq!(struct_type.get_context(), context);
    /// ```
    pub fn get_context(self) -> ContextRef<'ctx> {
        self.struct_type.get_context()
    }

    /// Gets this `StructType`'s name.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use inkwell::context::Context;
    ///
    /// let context = Context::create();
    /// let f32_type = context.f32_type();
    /// let struct_type = context.opaque_struct_type("opaque_struct");
    ///
    /// assert_eq!(struct_type.get_name().unwrap().to_str().unwrap(), "opaque_struct");
    /// ```
    pub fn get_name(&self) -> Option<&CStr> {
        let name = unsafe { LLVMGetStructName(self.as_type_ref()) };

        if name.is_null() {
            return None;
        }

        let c_str = unsafe { CStr::from_ptr(name) };

        Some(c_str)
    }

    /// Creates a `PointerType` with this `StructType` for its element type.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use inkwell::AddressSpace;
    /// use inkwell::context::Context;
    ///
    /// let context = Context::create();
    /// let f32_type = context.f32_type();
    /// let struct_type = context.struct_type(&[f32_type.into(), f32_type.into()], false);
    /// let struct_ptr_type = struct_type.ptr_type(AddressSpace::default());
    ///
    /// #[cfg(any(
    ///     feature = "llvm4-0",
    ///     feature = "llvm5-0",
    ///     feature = "llvm6-0",
    ///     feature = "llvm7-0",
    ///     feature = "llvm8-0",
    ///     feature = "llvm9-0",
    ///     feature = "llvm10-0",
    ///     feature = "llvm11-0",
    ///     feature = "llvm12-0",
    ///     feature = "llvm13-0",
    ///     feature = "llvm14-0"
    /// ))]
    /// assert_eq!(struct_ptr_type.get_element_type().into_struct_type(), struct_type);
    /// ```
    #[cfg_attr(
        any(
            feature = "llvm15-0",
            feature = "llvm16-0",
            feature = "llvm17-0",
            feature = "llvm18-0"
        ),
        deprecated(
            note = "Starting from version 15.0, LLVM doesn't differentiate between pointer types. Use Context::ptr_type instead."
        )
    )]
    pub fn ptr_type(self, address_space: AddressSpace) -> PointerType<'ctx> {
        self.struct_type.ptr_type(address_space)
    }

    /// Creates a `FunctionType` with this `StructType` for its return type.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use inkwell::context::Context;
    ///
    /// let context = Context::create();
    /// let f32_type = context.f32_type();
    /// let struct_type = context.struct_type(&[f32_type.into(), f32_type.into()], false);
    /// let fn_type = struct_type.fn_type(&[], false);
    /// ```
    pub fn fn_type(self, param_types: &[BasicMetadataTypeEnum<'ctx>], is_var_args: bool) -> FunctionType<'ctx> {
        self.struct_type.fn_type(param_types, is_var_args)
    }

    /// Creates an `ArrayType` with this `StructType` for its element type.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use inkwell::context::Context;
    ///
    /// let context = Context::create();
    /// let f32_type = context.f32_type();
    /// let struct_type = context.struct_type(&[f32_type.into(), f32_type.into()], false);
    /// let struct_array_type = struct_type.array_type(3);
    ///
    /// assert_eq!(struct_array_type.len(), 3);
    /// assert_eq!(struct_array_type.get_element_type().into_struct_type(), struct_type);
    /// ```
    pub fn array_type(self, size: u32) -> ArrayType<'ctx> {
        self.struct_type.array_type(size)
    }

    /// Determines whether or not a `StructType` is packed.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use inkwell::context::Context;
    ///
    /// let context = Context::create();
    /// let f32_type = context.f32_type();
    /// let struct_type = context.struct_type(&[f32_type.into(), f32_type.into()], false);
    ///
    /// assert!(struct_type.is_packed());
    /// ```
    pub fn is_packed(self) -> bool {
        unsafe { LLVMIsPackedStruct(self.as_type_ref()) == 1 }
    }

    /// Determines whether or not a `StructType` is opaque.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use inkwell::context::Context;
    ///
    /// let context = Context::create();
    /// let f32_type = context.f32_type();
    /// let struct_type = context.opaque_struct_type("opaque_struct");
    ///
    /// assert!(struct_type.is_opaque());
    /// ```
    pub fn is_opaque(self) -> bool {
        unsafe { LLVMIsOpaqueStruct(self.as_type_ref()) == 1 }
    }

    /// Counts the number of field types.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use inkwell::context::Context;
    ///
    /// let context = Context::create();
    /// let f32_type = context.f32_type();
    /// let i8_type = context.i8_type();
    /// let struct_type = context.struct_type(&[f32_type.into(), i8_type.into()], false);
    ///
    /// assert_eq!(struct_type.count_fields(), 2);
    /// ```
    pub fn count_fields(self) -> u32 {
        unsafe { LLVMCountStructElementTypes(self.as_type_ref()) }
    }

    /// Gets this `StructType`'s field types.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use inkwell::context::Context;
    ///
    /// let context = Context::create();
    /// let f32_type = context.f32_type();
    /// let i8_type = context.i8_type();
    /// let struct_type = context.struct_type(&[f32_type.into(), i8_type.into()], false);
    ///
    /// assert_eq!(struct_type.get_field_types(), &[f32_type.into(), i8_type.into()]);
    /// ```
    pub fn get_field_types(self) -> Vec<BasicTypeEnum<'ctx>> {
        let count = self.count_fields();
        let mut raw_vec: Vec<LLVMTypeRef> = Vec::with_capacity(count as usize);
        let ptr = raw_vec.as_mut_ptr();

        forget(raw_vec);

        let raw_vec = unsafe {
            LLVMGetStructElementTypes(self.as_type_ref(), ptr);

            Vec::from_raw_parts(ptr, count as usize, count as usize)
        };

        raw_vec.iter().map(|val| unsafe { BasicTypeEnum::new(*val) }).collect()
    }

    /// Get a struct field iterator.
    pub fn get_field_types_iter(self) -> FieldTypesIter<'ctx> {
        FieldTypesIter {
            st: self,
            i: 0,
            count: if self.is_opaque() { 0 } else { self.count_fields() },
        }
    }

    /// Print the definition of a `StructType` to `LLVMString`.
    pub fn print_to_string(self) -> LLVMString {
        self.struct_type.print_to_string()
    }

    /// Creates an undefined instance of a `StructType`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use inkwell::context::Context;
    ///
    /// let context = Context::create();
    /// let f32_type = context.f32_type();
    /// let i8_type = context.i8_type();
    /// let struct_type = context.struct_type(&[f32_type.into(), i8_type.into()], false);
    /// let struct_type_undef = struct_type.get_undef();
    ///
    /// assert!(struct_type_undef.is_undef());
    /// ```
    pub fn get_undef(self) -> StructValue<'ctx> {
        unsafe { StructValue::new(self.struct_type.get_undef()) }
    }

    /// Creates a poison instance of a `StructType`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use inkwell::context::Context;
    /// use inkwell::values::AnyValue;
    ///
    /// let context = Context::create();
    /// let f32_type = context.f32_type();
    /// let i8_type = context.i8_type();
    /// let struct_type = context.struct_type(&[f32_type.into(), i8_type.into()], false);
    /// let struct_type_poison = struct_type.get_poison();
    ///
    /// assert!(struct_type_poison.is_poison());
    /// ```
    #[llvm_versions(12..)]
    pub fn get_poison(self) -> StructValue<'ctx> {
        unsafe { StructValue::new(self.struct_type.get_poison()) }
    }

    /// Defines the body of a `StructType`.
    ///
    /// If the struct is an opaque type, it will no longer be after this call.
    ///
    /// Resetting the `packed` state of a non-opaque struct type may not work.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use inkwell::context::Context;
    ///
    /// let context = Context::create();
    /// let f32_type = context.f32_type();
    /// let opaque_struct_type = context.opaque_struct_type("opaque_struct");
    ///
    /// opaque_struct_type.set_body(&[f32_type.into()], false);
    ///
    /// assert!(!opaque_struct_type.is_opaque());
    /// ```
    pub fn set_body(self, field_types: &[BasicTypeEnum<'ctx>], packed: bool) -> bool {
        let is_opaque = self.is_opaque();
        let mut field_types: Vec<LLVMTypeRef> = field_types.iter().map(|val| val.as_type_ref()).collect();
        unsafe {
            LLVMStructSetBody(
                self.as_type_ref(),
                field_types.as_mut_ptr(),
                field_types.len() as u32,
                packed as i32,
            );
        }

        is_opaque
    }

    /// Creates a constant `ArrayValue`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use inkwell::context::Context;
    ///
    /// let context = Context::create();
    /// let f32_type = context.f32_type();
    /// let struct_type = context.struct_type(&[f32_type.into(), f32_type.into()], false);
    /// let struct_val = struct_type.const_named_struct(&[]);
    /// let struct_array = struct_type.const_array(&[struct_val, struct_val]);
    ///
    /// assert!(struct_array.is_const());
    /// ```
    pub fn const_array(self, values: &[StructValue<'ctx>]) -> ArrayValue<'ctx> {
        unsafe { ArrayValue::new_const_array(&self, values) }
    }
}

unsafe impl AsTypeRef for StructType<'_> {
    fn as_type_ref(&self) -> LLVMTypeRef {
        self.struct_type.ty
    }
}

impl Display for StructType<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.print_to_string())
    }
}

/// Iterate over all `BasicTypeEnum`s in a struct.
#[derive(Debug)]
pub struct FieldTypesIter<'ctx> {
    st: StructType<'ctx>,
    i: u32,
    count: u32,
}

impl<'ctx> Iterator for FieldTypesIter<'ctx> {
    type Item = BasicTypeEnum<'ctx>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.i < self.count {
            let result = unsafe { self.st.get_field_type_at_index_unchecked(self.i) };
            self.i += 1;
            Some(result)
        } else {
            None
        }
    }
}