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
#[llvm_versions(8.0..=latest)]
use llvm_sys::core::LLVMGlobalSetMetadata;
#[llvm_versions(4.0..=7.0)]
use llvm_sys::core::{
    LLVMDeleteGlobal, LLVMGetAlignment, LLVMGetDLLStorageClass, LLVMGetInitializer, LLVMGetLinkage, LLVMGetNextGlobal,
    LLVMGetPreviousGlobal, LLVMGetSection, LLVMGetThreadLocalMode, LLVMGetVisibility, LLVMIsDeclaration,
    LLVMIsExternallyInitialized, LLVMIsGlobalConstant, LLVMIsThreadLocal, LLVMSetAlignment, LLVMSetDLLStorageClass,
    LLVMSetExternallyInitialized, LLVMSetGlobalConstant, LLVMSetInitializer, LLVMSetLinkage, LLVMSetSection,
    LLVMSetThreadLocal, LLVMSetThreadLocalMode, LLVMSetVisibility,
};
#[llvm_versions(8.0..=latest)]
use llvm_sys::core::{
    LLVMDeleteGlobal, LLVMGetAlignment, LLVMGetDLLStorageClass, LLVMGetInitializer, LLVMGetLinkage, LLVMGetNextGlobal,
    LLVMGetPreviousGlobal, LLVMGetThreadLocalMode, LLVMGetVisibility, LLVMIsDeclaration, LLVMIsExternallyInitialized,
    LLVMIsGlobalConstant, LLVMIsThreadLocal, LLVMSetAlignment, LLVMSetDLLStorageClass, LLVMSetExternallyInitialized,
    LLVMSetGlobalConstant, LLVMSetInitializer, LLVMSetLinkage, LLVMSetThreadLocal, LLVMSetThreadLocalMode,
    LLVMSetVisibility,
};
#[llvm_versions(7.0..=latest)]
use llvm_sys::core::{LLVMGetUnnamedAddress, LLVMSetUnnamedAddress};
#[llvm_versions(4.0..=6.0)]
use llvm_sys::core::{LLVMHasUnnamedAddr, LLVMSetUnnamedAddr};
use llvm_sys::prelude::LLVMValueRef;
use llvm_sys::LLVMThreadLocalMode;
#[llvm_versions(7.0..=latest)]
use llvm_sys::LLVMUnnamedAddr;

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

#[llvm_versions(7.0..=latest)]
use crate::comdat::Comdat;
use crate::module::Linkage;
use crate::values::traits::AsValueRef;
#[llvm_versions(8.0..=latest)]
use crate::values::MetadataValue;
use crate::values::{BasicValue, BasicValueEnum, PointerValue, Value};
use crate::{DLLStorageClass, GlobalVisibility, ThreadLocalMode};

use super::AnyValue;

// REVIEW: GlobalValues are always PointerValues. With SubTypes, we should
// compress this into a PointerValue<Global> type
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
pub struct GlobalValue<'ctx> {
    global_value: Value<'ctx>,
}

impl<'ctx> GlobalValue<'ctx> {
    /// Get a value from an [LLVMValueRef].
    ///
    /// # Safety
    ///
    /// The ref must be valid and of type global.
    pub unsafe fn new(value: LLVMValueRef) -> Self {
        assert!(!value.is_null());

        GlobalValue {
            global_value: Value::new(value),
        }
    }

    /// Get name of the `GlobalValue`.
    pub fn get_name(&self) -> &CStr {
        self.global_value.get_name()
    }

    /// Set name of the `GlobalValue`.
    pub fn set_name(&self, name: &str) {
        self.global_value.set_name(name)
    }

    pub fn get_previous_global(self) -> Option<GlobalValue<'ctx>> {
        let value = unsafe { LLVMGetPreviousGlobal(self.as_value_ref()) };

        if value.is_null() {
            return None;
        }

        unsafe { Some(GlobalValue::new(value)) }
    }

    pub fn get_next_global(self) -> Option<GlobalValue<'ctx>> {
        let value = unsafe { LLVMGetNextGlobal(self.as_value_ref()) };

        if value.is_null() {
            return None;
        }

        unsafe { Some(GlobalValue::new(value)) }
    }

    pub fn get_dll_storage_class(self) -> DLLStorageClass {
        let dll_storage_class = unsafe { LLVMGetDLLStorageClass(self.as_value_ref()) };

        DLLStorageClass::new(dll_storage_class)
    }

    pub fn set_dll_storage_class(self, dll_storage_class: DLLStorageClass) {
        unsafe { LLVMSetDLLStorageClass(self.as_value_ref(), dll_storage_class.into()) }
    }

    pub fn get_initializer(self) -> Option<BasicValueEnum<'ctx>> {
        let value = unsafe { LLVMGetInitializer(self.as_value_ref()) };

        if value.is_null() {
            return None;
        }

        unsafe { Some(BasicValueEnum::new(value)) }
    }

    // SubType: This input type should be tied to the BasicType
    pub fn set_initializer(self, value: &dyn BasicValue<'ctx>) {
        unsafe { LLVMSetInitializer(self.as_value_ref(), value.as_value_ref()) }
    }

    pub fn is_thread_local(self) -> bool {
        unsafe { LLVMIsThreadLocal(self.as_value_ref()) == 1 }
    }

    // TODOC: Setting this to true is the same as setting GeneralDynamicTLSModel
    pub fn set_thread_local(self, is_thread_local: bool) {
        unsafe { LLVMSetThreadLocal(self.as_value_ref(), is_thread_local as i32) }
    }

    pub fn get_thread_local_mode(self) -> Option<ThreadLocalMode> {
        let thread_local_mode = unsafe { LLVMGetThreadLocalMode(self.as_value_ref()) };

        ThreadLocalMode::new(thread_local_mode)
    }

    // REVIEW: Does this have any bad behavior if it isn't thread local or just a noop?
    // or should it call self.set_thread_local(true)?
    pub fn set_thread_local_mode(self, thread_local_mode: Option<ThreadLocalMode>) {
        let thread_local_mode = match thread_local_mode {
            Some(mode) => mode.as_llvm_mode(),
            None => LLVMThreadLocalMode::LLVMNotThreadLocal,
        };

        unsafe { LLVMSetThreadLocalMode(self.as_value_ref(), thread_local_mode) }
    }

    // SubType: This should be moved into the type. GlobalValue<Initialized/Uninitialized>
    /// Determines whether or not a `GlobalValue` is a declaration or a definition.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use inkwell::context::Context;
    ///
    /// let context = Context::create();
    /// let builder = context.create_builder();
    /// let module = context.create_module("my_mod");
    /// let void_type = context.void_type();
    /// let fn_type = void_type.fn_type(&[], false);
    /// let fn_value = module.add_function("my_func", fn_type, None);
    ///
    /// assert!(fn_value.as_global_value().is_declaration());
    ///
    /// context.append_basic_block(fn_value, "entry");
    ///
    /// assert!(!fn_value.as_global_value().is_declaration());
    /// ```
    pub fn is_declaration(self) -> bool {
        unsafe { LLVMIsDeclaration(self.as_value_ref()) == 1 }
    }

    #[llvm_versions(4.0..=6.0)]
    pub fn has_unnamed_addr(self) -> bool {
        unsafe { LLVMHasUnnamedAddr(self.as_value_ref()) == 1 }
    }

    #[llvm_versions(7.0..=latest)]
    pub fn has_unnamed_addr(self) -> bool {
        unsafe { LLVMGetUnnamedAddress(self.as_value_ref()) == LLVMUnnamedAddr::LLVMGlobalUnnamedAddr }
    }

    #[llvm_versions(4.0..=6.0)]
    pub fn set_unnamed_addr(self, has_unnamed_addr: bool) {
        unsafe { LLVMSetUnnamedAddr(self.as_value_ref(), has_unnamed_addr as i32) }
    }

    #[llvm_versions(7.0..=latest)]
    pub fn set_unnamed_addr(self, has_unnamed_addr: bool) {
        unsafe {
            if has_unnamed_addr {
                LLVMSetUnnamedAddress(self.as_value_ref(), UnnamedAddress::Global.into())
            } else {
                LLVMSetUnnamedAddress(self.as_value_ref(), UnnamedAddress::None.into())
            }
        }
    }

    pub fn is_constant(self) -> bool {
        unsafe { LLVMIsGlobalConstant(self.as_value_ref()) == 1 }
    }

    pub fn set_constant(self, is_constant: bool) {
        unsafe { LLVMSetGlobalConstant(self.as_value_ref(), is_constant as i32) }
    }

    pub fn is_externally_initialized(self) -> bool {
        unsafe { LLVMIsExternallyInitialized(self.as_value_ref()) == 1 }
    }

    pub fn set_externally_initialized(self, externally_initialized: bool) {
        unsafe { LLVMSetExternallyInitialized(self.as_value_ref(), externally_initialized as i32) }
    }

    pub fn set_visibility(self, visibility: GlobalVisibility) {
        unsafe { LLVMSetVisibility(self.as_value_ref(), visibility.into()) }
    }

    pub fn get_visibility(self) -> GlobalVisibility {
        let visibility = unsafe { LLVMGetVisibility(self.as_value_ref()) };

        GlobalVisibility::new(visibility)
    }

    /// Get section, this global value belongs to
    pub fn get_section(&self) -> Option<&CStr> {
        self.global_value.get_section()
    }

    /// Set section, this global value belongs to
    pub fn set_section(self, section: Option<&str>) {
        self.global_value.set_section(section)
    }

    pub unsafe fn delete(self) {
        LLVMDeleteGlobal(self.as_value_ref())
    }

    pub fn as_pointer_value(self) -> PointerValue<'ctx> {
        unsafe { PointerValue::new(self.as_value_ref()) }
    }

    pub fn get_alignment(self) -> u32 {
        unsafe { LLVMGetAlignment(self.as_value_ref()) }
    }

    pub fn set_alignment(self, alignment: u32) {
        unsafe { LLVMSetAlignment(self.as_value_ref(), alignment) }
    }

    /// Sets a metadata of the given type on the GlobalValue
    #[llvm_versions(8.0..=latest)]
    pub fn set_metadata(self, metadata: MetadataValue<'ctx>, kind_id: u32) {
        unsafe { LLVMGlobalSetMetadata(self.as_value_ref(), kind_id, metadata.as_metadata_ref()) }
    }

    /// Gets a `Comdat` assigned to this `GlobalValue`, if any.
    #[llvm_versions(7.0..=latest)]
    pub fn get_comdat(self) -> Option<Comdat> {
        use llvm_sys::comdat::LLVMGetComdat;

        let comdat_ptr = unsafe { LLVMGetComdat(self.as_value_ref()) };

        if comdat_ptr.is_null() {
            return None;
        }

        unsafe { Some(Comdat::new(comdat_ptr)) }
    }

    /// Assigns a `Comdat` to this `GlobalValue`.
    #[llvm_versions(7.0..=latest)]
    pub fn set_comdat(self, comdat: Comdat) {
        use llvm_sys::comdat::LLVMSetComdat;

        unsafe { LLVMSetComdat(self.as_value_ref(), comdat.0) }
    }

    #[llvm_versions(7.0..=latest)]
    pub fn get_unnamed_address(self) -> UnnamedAddress {
        use llvm_sys::core::LLVMGetUnnamedAddress;

        let unnamed_address = unsafe { LLVMGetUnnamedAddress(self.as_value_ref()) };

        UnnamedAddress::new(unnamed_address)
    }

    #[llvm_versions(7.0..=latest)]
    pub fn set_unnamed_address(self, address: UnnamedAddress) {
        use llvm_sys::core::LLVMSetUnnamedAddress;

        unsafe { LLVMSetUnnamedAddress(self.as_value_ref(), address.into()) }
    }

    pub fn get_linkage(self) -> Linkage {
        unsafe { LLVMGetLinkage(self.as_value_ref()).into() }
    }

    pub fn set_linkage(self, linkage: Linkage) {
        unsafe { LLVMSetLinkage(self.as_value_ref(), linkage.into()) }
    }
}

unsafe impl AsValueRef for GlobalValue<'_> {
    fn as_value_ref(&self) -> LLVMValueRef {
        self.global_value.value
    }
}

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

/// This enum determines the significance of a `GlobalValue`'s address.
#[llvm_versions(7.0..=latest)]
#[llvm_enum(LLVMUnnamedAddr)]
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum UnnamedAddress {
    /// Address of the `GlobalValue` is significant.
    #[llvm_variant(LLVMNoUnnamedAddr)]
    None,

    /// Address of the `GlobalValue` is locally insignificant.
    #[llvm_variant(LLVMLocalUnnamedAddr)]
    Local,

    /// Address of the `GlobalValue` is globally insignificant.
    #[llvm_variant(LLVMGlobalUnnamedAddr)]
    Global,
}