llvm_plugin_inkwell/
module.rs

1//! A `Module` represets a single code compilation unit.
2
3use llvm_sys::analysis::{LLVMVerifierFailureAction, LLVMVerifyModule};
4#[allow(deprecated)]
5use llvm_sys::bit_reader::LLVMParseBitcodeInContext;
6use llvm_sys::bit_writer::{LLVMWriteBitcodeToFile, LLVMWriteBitcodeToMemoryBuffer};
7#[llvm_versions(4.0..=14.0)]
8use llvm_sys::core::LLVMGetTypeByName;
9
10use llvm_sys::core::{
11    LLVMAddFunction, LLVMAddGlobal, LLVMAddGlobalInAddressSpace, LLVMAddNamedMetadataOperand, LLVMCloneModule,
12    LLVMDisposeModule, LLVMDumpModule, LLVMGetFirstFunction, LLVMGetFirstGlobal, LLVMGetLastFunction,
13    LLVMGetLastGlobal, LLVMGetModuleContext, LLVMGetModuleIdentifier, LLVMGetNamedFunction, LLVMGetNamedGlobal,
14    LLVMGetNamedMetadataNumOperands, LLVMGetNamedMetadataOperands, LLVMGetTarget, LLVMPrintModuleToFile,
15    LLVMPrintModuleToString, LLVMSetDataLayout, LLVMSetModuleIdentifier, LLVMSetTarget,
16};
17#[llvm_versions(7.0..=latest)]
18use llvm_sys::core::{LLVMAddModuleFlag, LLVMGetModuleFlag};
19#[llvm_versions(13.0..=latest)]
20use llvm_sys::error::LLVMGetErrorMessage;
21use llvm_sys::execution_engine::{
22    LLVMCreateExecutionEngineForModule, LLVMCreateInterpreterForModule, LLVMCreateJITCompilerForModule,
23};
24use llvm_sys::prelude::{LLVMModuleRef, LLVMValueRef};
25#[llvm_versions(13.0..=latest)]
26use llvm_sys::transforms::pass_builder::LLVMRunPasses;
27use llvm_sys::LLVMLinkage;
28#[llvm_versions(7.0..=latest)]
29use llvm_sys::LLVMModuleFlagBehavior;
30
31use std::cell::{Cell, Ref, RefCell};
32use std::ffi::CStr;
33use std::fs::File;
34use std::marker::PhantomData;
35use std::mem::{forget, MaybeUninit};
36use std::path::Path;
37use std::ptr;
38use std::rc::Rc;
39
40#[llvm_versions(7.0..=latest)]
41use crate::comdat::Comdat;
42use crate::context::{AsContextRef, Context, ContextRef};
43use crate::data_layout::DataLayout;
44#[llvm_versions(7.0..=latest)]
45use crate::debug_info::{DICompileUnit, DWARFEmissionKind, DWARFSourceLanguage, DebugInfoBuilder};
46use crate::execution_engine::ExecutionEngine;
47use crate::memory_buffer::MemoryBuffer;
48#[llvm_versions(13.0..=latest)]
49use crate::passes::PassBuilderOptions;
50use crate::support::{to_c_str, LLVMString};
51#[llvm_versions(13.0..=latest)]
52use crate::targets::TargetMachine;
53use crate::targets::{InitializationConfig, Target, TargetTriple};
54use crate::types::{AsTypeRef, BasicType, FunctionType, StructType};
55#[llvm_versions(7.0..=latest)]
56use crate::values::BasicValue;
57use crate::values::{AsValueRef, FunctionValue, GlobalValue, MetadataValue};
58use crate::{AddressSpace, OptimizationLevel};
59
60#[llvm_enum(LLVMLinkage)]
61#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
62/// This enum defines how to link a global variable or function in a module. The variant documenation is
63/// mostly taken straight from LLVM's own documentation except for some minor clarification.
64///
65/// It is illegal for a function declaration to have any linkage type other than external or extern_weak.
66///
67/// All Global Variables, Functions and Aliases can have one of the following DLL storage class: `DLLImport`
68/// & `DLLExport`.
69// REVIEW: Maybe this should go into it's own module?
70pub enum Linkage {
71    /// `Appending` linkage may only be applied to global variables of pointer to array type. When two global
72    /// variables with appending linkage are linked together, the two global arrays are appended together.
73    /// This is the LLVM, typesafe, equivalent of having the system linker append together "sections" with
74    /// identical names when .o files are linked. Unfortunately this doesn't correspond to any feature in .o
75    /// files, so it can only be used for variables like llvm.global_ctors which llvm interprets specially.
76    #[llvm_variant(LLVMAppendingLinkage)]
77    Appending,
78    /// Globals with `AvailableExternally` linkage are never emitted into the object file corresponding to
79    /// the LLVM module. From the linker's perspective, an `AvailableExternally` global is equivalent to an
80    /// external declaration. They exist to allow inlining and other optimizations to take place given
81    /// knowledge of the definition of the global, which is known to be somewhere outside the module. Globals
82    /// with `AvailableExternally` linkage are allowed to be discarded at will, and allow inlining and other
83    /// optimizations. This linkage type is only allowed on definitions, not declarations.
84    #[llvm_variant(LLVMAvailableExternallyLinkage)]
85    AvailableExternally,
86    /// `Common` linkage is most similar to "weak" linkage, but they are used for tentative definitions
87    /// in C, such as "int X;" at global scope. Symbols with Common linkage are merged in the same way as
88    /// weak symbols, and they may not be deleted if unreferenced. `Common` symbols may not have an explicit
89    /// section, must have a zero initializer, and may not be marked 'constant'. Functions and aliases may
90    /// not have `Common` linkage.
91    #[llvm_variant(LLVMCommonLinkage)]
92    Common,
93    /// `DLLExport` causes the compiler to provide a global pointer to a pointer in a DLL, so that it can be
94    /// referenced with the dllimport attribute. On Microsoft Windows targets, the pointer name is formed by
95    /// combining __imp_ and the function or variable name. Since this storage class exists for defining a dll
96    /// interface, the compiler, assembler and linker know it is externally referenced and must refrain from
97    /// deleting the symbol.
98    #[llvm_variant(LLVMDLLExportLinkage)]
99    DLLExport,
100    /// `DLLImport` causes the compiler to reference a function or variable via a global pointer to a pointer
101    /// that is set up by the DLL exporting the symbol. On Microsoft Windows targets, the pointer name is
102    /// formed by combining __imp_ and the function or variable name.
103    #[llvm_variant(LLVMDLLImportLinkage)]
104    DLLImport,
105    /// If none of the other identifiers are used, the global is externally visible, meaning that it
106    /// participates in linkage and can be used to resolve external symbol references.
107    #[llvm_variant(LLVMExternalLinkage)]
108    External,
109    /// The semantics of this linkage follow the ELF object file model: the symbol is weak until linked,
110    /// if not linked, the symbol becomes null instead of being an undefined reference.
111    #[llvm_variant(LLVMExternalWeakLinkage)]
112    ExternalWeak,
113    /// FIXME: Unknown linkage type
114    #[llvm_variant(LLVMGhostLinkage)]
115    Ghost,
116    /// Similar to private, but the value shows as a local symbol (STB_LOCAL in the case of ELF) in the object
117    /// file. This corresponds to the notion of the 'static' keyword in C.
118    #[llvm_variant(LLVMInternalLinkage)]
119    Internal,
120    /// FIXME: Unknown linkage type
121    #[llvm_variant(LLVMLinkerPrivateLinkage)]
122    LinkerPrivate,
123    /// FIXME: Unknown linkage type
124    #[llvm_variant(LLVMLinkerPrivateWeakLinkage)]
125    LinkerPrivateWeak,
126    /// Globals with `LinkOnceAny` linkage are merged with other globals of the same name when linkage occurs.
127    /// This can be used to implement some forms of inline functions, templates, or other code which must be
128    /// generated in each translation unit that uses it, but where the body may be overridden with a more
129    /// definitive definition later. Unreferenced `LinkOnceAny` globals are allowed to be discarded. Note that
130    /// `LinkOnceAny` linkage does not actually allow the optimizer to inline the body of this function into
131    /// callers because it doesn’t know if this definition of the function is the definitive definition within
132    /// the program or whether it will be overridden by a stronger definition. To enable inlining and other
133    /// optimizations, use `LinkOnceODR` linkage.
134    #[llvm_variant(LLVMLinkOnceAnyLinkage)]
135    LinkOnceAny,
136    /// FIXME: Unknown linkage type
137    #[llvm_variant(LLVMLinkOnceODRAutoHideLinkage)]
138    LinkOnceODRAutoHide,
139    /// Some languages allow differing globals to be merged, such as two functions with different semantics.
140    /// Other languages, such as C++, ensure that only equivalent globals are ever merged (the "one definition
141    /// rule" — "ODR"). Such languages can use the `LinkOnceODR` and `WeakODR` linkage types to indicate that
142    /// the global will only be merged with equivalent globals. These linkage types are otherwise the same
143    /// as their non-odr versions.
144    #[llvm_variant(LLVMLinkOnceODRLinkage)]
145    LinkOnceODR,
146    /// Global values with `Private` linkage are only directly accessible by objects in the current module.
147    /// In particular, linking code into a module with a private global value may cause the private to be
148    /// renamed as necessary to avoid collisions. Because the symbol is private to the module, all references
149    /// can be updated. This doesn’t show up in any symbol table in the object file.
150    #[llvm_variant(LLVMPrivateLinkage)]
151    Private,
152    /// `WeakAny` linkage has the same merging semantics as linkonce linkage, except that unreferenced globals
153    /// with weak linkage may not be discarded. This is used for globals that are declared WeakAny in C source code.
154    #[llvm_variant(LLVMWeakAnyLinkage)]
155    WeakAny,
156    /// Some languages allow differing globals to be merged, such as two functions with different semantics.
157    /// Other languages, such as C++, ensure that only equivalent globals are ever merged (the "one definition
158    /// rule" — "ODR"). Such languages can use the `LinkOnceODR` and `WeakODR` linkage types to indicate that
159    /// the global will only be merged with equivalent globals. These linkage types are otherwise the same
160    /// as their non-odr versions.
161    #[llvm_variant(LLVMWeakODRLinkage)]
162    WeakODR,
163}
164
165/// Represents a reference to an LLVM `Module`.
166/// The underlying module will be disposed when dropping this object.
167#[derive(Debug, PartialEq, Eq)]
168pub struct Module<'ctx> {
169    data_layout: RefCell<Option<DataLayout>>,
170    pub(crate) module: Cell<LLVMModuleRef>,
171    pub(crate) owned_by_ee: RefCell<Option<ExecutionEngine<'ctx>>>,
172    _marker: PhantomData<&'ctx Context>,
173}
174
175impl<'ctx> Module<'ctx> {
176    /// Instantiate a new `Module` from a raw LLVM module pointer.
177    ///
178    /// # Safety
179    ///
180    /// No check is being made to ensure the given pointer points to some valid LLVM module.
181    pub unsafe fn new(module: LLVMModuleRef) -> Self {
182        debug_assert!(!module.is_null());
183
184        Module {
185            module: Cell::new(module),
186            owned_by_ee: RefCell::new(None),
187            data_layout: RefCell::new(Some(Module::get_borrowed_data_layout(module))),
188            _marker: PhantomData,
189        }
190    }
191
192    /// Acquires the underlying raw pointer belonging to this `Module` type.
193    pub fn as_mut_ptr(&self) -> LLVMModuleRef {
194        self.module.get()
195    }
196
197    /// Creates a function given its `name` and `ty`, adds it to the `Module`
198    /// and returns it.
199    ///
200    /// An optional `linkage` can be specified, without which the default value
201    /// `Linkage::ExternalLinkage` will be used.
202    ///
203    /// # Example
204    /// ```no_run
205    /// use inkwell::context::Context;
206    /// use inkwell::module::{Module, Linkage};
207    /// use inkwell::types::FunctionType;
208    ///
209    /// let context = Context::create();
210    /// let module = context.create_module("my_module");
211    ///
212    /// let fn_type = context.f32_type().fn_type(&[], false);
213    /// let fn_val = module.add_function("my_function", fn_type, None);
214    ///
215    /// assert_eq!(fn_val.get_name().to_str(), Ok("my_function"));
216    /// assert_eq!(fn_val.get_linkage(), Linkage::External);
217    /// ```
218    pub fn add_function(&self, name: &str, ty: FunctionType<'ctx>, linkage: Option<Linkage>) -> FunctionValue<'ctx> {
219        let c_string = to_c_str(name);
220        let fn_value = unsafe {
221            FunctionValue::new(LLVMAddFunction(self.module.get(), c_string.as_ptr(), ty.as_type_ref()))
222                .expect("add_function should always succeed in adding a new function")
223        };
224
225        if let Some(linkage) = linkage {
226            fn_value.set_linkage(linkage)
227        }
228
229        fn_value
230    }
231
232    /// Gets the `Context` from which this `Module` originates.
233    ///
234    /// # Example
235    /// ```no_run
236    /// use inkwell::context::{Context, ContextRef};
237    /// use inkwell::module::Module;
238    ///
239    /// let local_context = Context::create();
240    /// let local_module = local_context.create_module("my_module");
241    ///
242    /// assert_eq!(local_module.get_context(), local_context);
243    /// ```
244    pub fn get_context(&self) -> ContextRef<'ctx> {
245        unsafe { ContextRef::new(LLVMGetModuleContext(self.module.get())) }
246    }
247
248    /// Gets the first `FunctionValue` defined in this `Module`.
249    ///
250    /// # Example
251    /// ```rust,no_run
252    /// use inkwell::context::Context;
253    /// use inkwell::module::Module;
254    ///
255    /// let context = Context::create();
256    /// let module = context.create_module("my_mod");
257    ///
258    /// assert!(module.get_first_function().is_none());
259    ///
260    /// let void_type = context.void_type();
261    /// let fn_type = void_type.fn_type(&[], false);
262    /// let fn_value = module.add_function("my_fn", fn_type, None);
263    ///
264    /// assert_eq!(fn_value, module.get_first_function().unwrap());
265    /// ```
266    pub fn get_first_function(&self) -> Option<FunctionValue<'ctx>> {
267        unsafe { FunctionValue::new(LLVMGetFirstFunction(self.module.get())) }
268    }
269
270    /// Gets the last `FunctionValue` defined in this `Module`.
271    ///
272    /// # Example
273    /// ```rust,no_run
274    /// use inkwell::context::Context;
275    /// use inkwell::module::Module;
276    ///
277    /// let context = Context::create();
278    /// let module = context.create_module("my_mod");
279    ///
280    /// assert!(module.get_last_function().is_none());
281    ///
282    /// let void_type = context.void_type();
283    /// let fn_type = void_type.fn_type(&[], false);
284    /// let fn_value = module.add_function("my_fn", fn_type, None);
285    ///
286    /// assert_eq!(fn_value, module.get_last_function().unwrap());
287    /// ```
288    pub fn get_last_function(&self) -> Option<FunctionValue<'ctx>> {
289        unsafe { FunctionValue::new(LLVMGetLastFunction(self.module.get())) }
290    }
291
292    /// Gets a `FunctionValue` defined in this `Module` by its name.
293    ///
294    /// # Example
295    /// ```rust,no_run
296    /// use inkwell::context::Context;
297    /// use inkwell::module::Module;
298    ///
299    /// let context = Context::create();
300    /// let module = context.create_module("my_mod");
301    ///
302    /// assert!(module.get_function("my_fn").is_none());
303    ///
304    /// let void_type = context.void_type();
305    /// let fn_type = void_type.fn_type(&[], false);
306    /// let fn_value = module.add_function("my_fn", fn_type, None);
307    ///
308    /// assert_eq!(fn_value, module.get_function("my_fn").unwrap());
309    /// ```
310    pub fn get_function(&self, name: &str) -> Option<FunctionValue<'ctx>> {
311        let c_string = to_c_str(name);
312
313        unsafe { FunctionValue::new(LLVMGetNamedFunction(self.module.get(), c_string.as_ptr())) }
314    }
315
316    /// An iterator over the functions in this `Module`.
317    ///
318    /// ```
319    /// use inkwell::context::Context;
320    /// use inkwell::module::Module;
321    ///
322    /// let context = Context::create();
323    /// let module = context.create_module("my_mod");
324    ///
325    /// assert!(module.get_function("my_fn").is_none());
326    ///
327    /// let void_type = context.void_type();
328    /// let fn_type = void_type.fn_type(&[], false);
329    /// let fn_value = module.add_function("my_fn", fn_type, None);
330    ///
331    /// let names: Vec<String> = module
332    ///     .get_functions()
333    ///     .map(|f| f.get_name().to_string_lossy().to_string())
334    ///     .collect();
335    ///
336    /// assert_eq!(vec!["my_fn".to_owned()], names);
337    /// ```
338    pub fn get_functions(&self) -> FunctionIterator<'ctx> {
339        FunctionIterator::from_module(self)
340    }
341
342    /// Gets a named `StructType` from this `Module`'s `Context`.
343    ///
344    /// # Example
345    ///
346    /// ```rust,no_run
347    /// use inkwell::context::Context;
348    ///
349    /// let context = Context::create();
350    /// let module = context.create_module("my_module");
351    ///
352    /// assert!(module.get_struct_type("foo").is_none());
353    ///
354    /// let opaque = context.opaque_struct_type("foo");
355    ///
356    /// assert_eq!(module.get_struct_type("foo").unwrap(), opaque);
357    /// ```
358    ///
359    #[llvm_versions(4.0..=11.0)]
360    pub fn get_struct_type(&self, name: &str) -> Option<StructType<'ctx>> {
361        let c_string = to_c_str(name);
362
363        let struct_type = unsafe { LLVMGetTypeByName(self.module.get(), c_string.as_ptr()) };
364
365        if struct_type.is_null() {
366            return None;
367        }
368
369        unsafe { Some(StructType::new(struct_type)) }
370    }
371
372    /// Gets a named `StructType` from this `Module`'s `Context`.
373    ///
374    /// # Example
375    ///
376    /// ```rust,no_run
377    /// use inkwell::context::Context;
378    ///
379    /// let context = Context::create();
380    /// let module = context.create_module("my_module");
381    ///
382    /// assert!(module.get_struct_type("foo").is_none());
383    ///
384    /// let opaque = context.opaque_struct_type("foo");
385    ///
386    /// assert_eq!(module.get_struct_type("foo").unwrap(), opaque);
387    /// ```
388    #[llvm_versions(12.0..=latest)]
389    pub fn get_struct_type(&self, name: &str) -> Option<StructType<'ctx>> {
390        self.get_context().get_struct_type(name)
391    }
392
393    /// Assigns a `TargetTriple` to this `Module`.
394    ///
395    /// # Example
396    ///
397    /// ```rust,no_run
398    /// use inkwell::context::Context;
399    /// use inkwell::targets::{Target, TargetTriple};
400    ///
401    /// Target::initialize_x86(&Default::default());
402    /// let context = Context::create();
403    /// let module = context.create_module("mod");
404    /// let triple = TargetTriple::create("x86_64-pc-linux-gnu");
405    ///
406    /// assert_eq!(module.get_triple(), TargetTriple::create(""));
407    ///
408    /// module.set_triple(&triple);
409    ///
410    /// assert_eq!(module.get_triple(), triple);
411    /// ```
412    pub fn set_triple(&self, triple: &TargetTriple) {
413        unsafe { LLVMSetTarget(self.module.get(), triple.as_ptr()) }
414    }
415
416    /// Gets the `TargetTriple` assigned to this `Module`. If none has been
417    /// assigned, the triple will default to "".
418    ///
419    /// # Example
420    ///
421    /// ```rust,no_run
422    /// use inkwell::context::Context;
423    /// use inkwell::targets::{Target, TargetTriple};
424    ///
425    /// Target::initialize_x86(&Default::default());
426    /// let context = Context::create();
427    /// let module = context.create_module("mod");
428    /// let triple = TargetTriple::create("x86_64-pc-linux-gnu");
429    ///
430    /// assert_eq!(module.get_triple(), TargetTriple::create(""));
431    ///
432    /// module.set_triple(&triple);
433    ///
434    /// assert_eq!(module.get_triple(), triple);
435    /// ```
436    pub fn get_triple(&self) -> TargetTriple {
437        // REVIEW: This isn't an owned LLVMString, is it? If so, need to deallocate.
438        let target_str = unsafe { LLVMGetTarget(self.module.get()) };
439
440        unsafe { TargetTriple::new(LLVMString::create_from_c_str(CStr::from_ptr(target_str))) }
441    }
442
443    /// Creates an `ExecutionEngine` from this `Module`.
444    ///
445    /// # Example
446    /// ```no_run
447    /// use inkwell::context::Context;
448    /// use inkwell::module::Module;
449    /// use inkwell::targets::{InitializationConfig, Target};
450    ///
451    /// Target::initialize_native(&InitializationConfig::default()).expect("Failed to initialize native target");
452    ///
453    /// let context = Context::create();
454    /// let module = context.create_module("my_module");
455    /// let execution_engine = module.create_execution_engine().unwrap();
456    ///
457    /// assert_eq!(module.get_context(), context);
458    /// ```
459    // SubType: ExecutionEngine<Basic?>
460    pub fn create_execution_engine(&self) -> Result<ExecutionEngine<'ctx>, LLVMString> {
461        Target::initialize_native(&InitializationConfig::default()).map_err(|mut err_string| {
462            err_string.push('\0');
463
464            LLVMString::create_from_str(&err_string)
465        })?;
466
467        if self.owned_by_ee.borrow().is_some() {
468            let string = "This module is already owned by an ExecutionEngine.\0";
469            return Err(LLVMString::create_from_str(string));
470        }
471
472        let mut execution_engine = MaybeUninit::uninit();
473        let mut err_string = MaybeUninit::uninit();
474        let code = unsafe {
475            // Takes ownership of module
476            LLVMCreateExecutionEngineForModule(
477                execution_engine.as_mut_ptr(),
478                self.module.get(),
479                err_string.as_mut_ptr(),
480            )
481        };
482
483        if code == 1 {
484            unsafe {
485                return Err(LLVMString::new(err_string.assume_init()));
486            }
487        }
488
489        let execution_engine = unsafe { execution_engine.assume_init() };
490        let execution_engine = unsafe { ExecutionEngine::new(Rc::new(execution_engine), false) };
491
492        *self.owned_by_ee.borrow_mut() = Some(execution_engine.clone());
493
494        Ok(execution_engine)
495    }
496
497    /// Creates an interpreter `ExecutionEngine` from this `Module`.
498    ///
499    /// # Example
500    /// ```no_run
501    /// use inkwell::context::Context;
502    /// use inkwell::module::Module;
503    /// use inkwell::targets::{InitializationConfig, Target};
504    ///
505    /// Target::initialize_native(&InitializationConfig::default()).expect("Failed to initialize native target");
506    ///
507    /// let context = Context::create();
508    /// let module = context.create_module("my_module");
509    /// let execution_engine = module.create_interpreter_execution_engine().unwrap();
510    ///
511    /// assert_eq!(module.get_context(), context);
512    /// ```
513    // SubType: ExecutionEngine<Interpreter>
514    pub fn create_interpreter_execution_engine(&self) -> Result<ExecutionEngine<'ctx>, LLVMString> {
515        Target::initialize_native(&InitializationConfig::default()).map_err(|mut err_string| {
516            err_string.push('\0');
517
518            LLVMString::create_from_str(&err_string)
519        })?;
520
521        if self.owned_by_ee.borrow().is_some() {
522            let string = "This module is already owned by an ExecutionEngine.\0";
523            return Err(LLVMString::create_from_str(string));
524        }
525
526        let mut execution_engine = MaybeUninit::uninit();
527        let mut err_string = MaybeUninit::uninit();
528
529        let code = unsafe {
530            // Takes ownership of module
531            LLVMCreateInterpreterForModule(
532                execution_engine.as_mut_ptr(),
533                self.module.get(),
534                err_string.as_mut_ptr(),
535            )
536        };
537
538        if code == 1 {
539            unsafe {
540                return Err(LLVMString::new(err_string.assume_init()));
541            }
542        }
543
544        let execution_engine = unsafe { execution_engine.assume_init() };
545        let execution_engine = unsafe { ExecutionEngine::new(Rc::new(execution_engine), false) };
546
547        *self.owned_by_ee.borrow_mut() = Some(execution_engine.clone());
548
549        Ok(execution_engine)
550    }
551
552    /// Creates a JIT `ExecutionEngine` from this `Module`.
553    ///
554    /// # Example
555    /// ```no_run
556    /// use inkwell::OptimizationLevel;
557    /// use inkwell::context::Context;
558    /// use inkwell::module::Module;
559    /// use inkwell::targets::{InitializationConfig, Target};
560    ///
561    /// Target::initialize_native(&InitializationConfig::default()).expect("Failed to initialize native target");
562    ///
563    /// let context = Context::create();
564    /// let module = context.create_module("my_module");
565    /// let execution_engine = module.create_jit_execution_engine(OptimizationLevel::None).unwrap();
566    ///
567    /// assert_eq!(module.get_context(), context);
568    /// ```
569    // SubType: ExecutionEngine<Jit>
570    pub fn create_jit_execution_engine(
571        &self,
572        opt_level: OptimizationLevel,
573    ) -> Result<ExecutionEngine<'ctx>, LLVMString> {
574        Target::initialize_native(&InitializationConfig::default()).map_err(|mut err_string| {
575            err_string.push('\0');
576
577            LLVMString::create_from_str(&err_string)
578        })?;
579
580        if self.owned_by_ee.borrow().is_some() {
581            let string = "This module is already owned by an ExecutionEngine.\0";
582            return Err(LLVMString::create_from_str(string));
583        }
584
585        let mut execution_engine = MaybeUninit::uninit();
586        let mut err_string = MaybeUninit::uninit();
587
588        let code = unsafe {
589            // Takes ownership of module
590            LLVMCreateJITCompilerForModule(
591                execution_engine.as_mut_ptr(),
592                self.module.get(),
593                opt_level as u32,
594                err_string.as_mut_ptr(),
595            )
596        };
597
598        if code == 1 {
599            unsafe {
600                return Err(LLVMString::new(err_string.assume_init()));
601            }
602        }
603
604        let execution_engine = unsafe { execution_engine.assume_init() };
605        let execution_engine = unsafe { ExecutionEngine::new(Rc::new(execution_engine), true) };
606
607        *self.owned_by_ee.borrow_mut() = Some(execution_engine.clone());
608
609        Ok(execution_engine)
610    }
611
612    /// Creates a `GlobalValue` based on a type in an address space.
613    ///
614    /// # Example
615    ///
616    /// ```no_run
617    /// use inkwell::AddressSpace;
618    /// use inkwell::context::Context;
619    ///
620    /// let context = Context::create();
621    /// let module = context.create_module("mod");
622    /// let i8_type = context.i8_type();
623    /// let global = module.add_global(i8_type, Some(AddressSpace::from(1u16)), "my_global");
624    ///
625    /// assert_eq!(module.get_first_global().unwrap(), global);
626    /// assert_eq!(module.get_last_global().unwrap(), global);
627    /// ```
628    pub fn add_global<T: BasicType<'ctx>>(
629        &self,
630        type_: T,
631        address_space: Option<AddressSpace>,
632        name: &str,
633    ) -> GlobalValue<'ctx> {
634        let c_string = to_c_str(name);
635
636        let value = unsafe {
637            match address_space {
638                Some(address_space) => LLVMAddGlobalInAddressSpace(
639                    self.module.get(),
640                    type_.as_type_ref(),
641                    c_string.as_ptr(),
642                    address_space.0,
643                ),
644                None => LLVMAddGlobal(self.module.get(), type_.as_type_ref(), c_string.as_ptr()),
645            }
646        };
647
648        unsafe { GlobalValue::new(value) }
649    }
650
651    /// Writes a `Module` to a `Path`.
652    ///
653    /// # Example
654    ///
655    /// ```no_run
656    /// use inkwell::context::Context;
657    ///
658    /// use std::path::Path;
659    ///
660    /// let mut path = Path::new("module.bc");
661    ///
662    /// let context = Context::create();
663    /// let module = context.create_module("my_module");
664    /// let void_type = context.void_type();
665    /// let fn_type = void_type.fn_type(&[], false);
666    ///
667    /// module.add_function("my_fn", fn_type, None);
668    /// module.write_bitcode_to_path(&path);
669    /// ```
670    pub fn write_bitcode_to_path(&self, path: &Path) -> bool {
671        let path_str = path.to_str().expect("Did not find a valid Unicode path string");
672        let c_string = to_c_str(path_str);
673
674        unsafe { LLVMWriteBitcodeToFile(self.module.get(), c_string.as_ptr()) == 0 }
675    }
676
677    // See GH issue #6
678    /// `write_bitcode_to_path` should be preferred over this method, as it does not work on all operating systems.
679    pub fn write_bitcode_to_file(&self, file: &File, should_close: bool, unbuffered: bool) -> bool {
680        #[cfg(unix)]
681        {
682            use llvm_sys::bit_writer::LLVMWriteBitcodeToFD;
683            use std::os::unix::io::AsRawFd;
684
685            // REVIEW: as_raw_fd docs suggest it only works in *nix
686            // Also, should_close should maybe be hardcoded to true?
687            unsafe {
688                LLVMWriteBitcodeToFD(
689                    self.module.get(),
690                    file.as_raw_fd(),
691                    should_close as i32,
692                    unbuffered as i32,
693                ) == 0
694            }
695        }
696        #[cfg(not(unix))]
697        return false;
698    }
699
700    /// Writes this `Module` to a `MemoryBuffer`.
701    ///
702    /// # Example
703    ///
704    /// ```no_run
705    /// use inkwell::context::Context;
706    ///
707    /// let context = Context::create();
708    /// let module = context.create_module("mod");
709    /// let void_type = context.void_type();
710    /// let fn_type = void_type.fn_type(&[], false);
711    /// let f = module.add_function("f", fn_type, None);
712    /// let basic_block = context.append_basic_block(f, "entry");
713    /// let builder = context.create_builder();
714    ///
715    /// builder.position_at_end(basic_block);
716    /// builder.build_return(None);
717    ///
718    /// let buffer = module.write_bitcode_to_memory();
719    /// ```
720    pub fn write_bitcode_to_memory(&self) -> MemoryBuffer {
721        let memory_buffer = unsafe { LLVMWriteBitcodeToMemoryBuffer(self.module.get()) };
722
723        unsafe { MemoryBuffer::new(memory_buffer) }
724    }
725
726    /// Ensures that the current `Module` is valid, and returns a `Result`
727    /// that describes whether or not it is, returning a LLVM allocated string on error.
728    ///
729    /// # Remarks
730    /// See also: http://llvm.org/doxygen/Analysis_2Analysis_8cpp_source.html
731    pub fn verify(&self) -> Result<(), LLVMString> {
732        let mut err_str = MaybeUninit::uninit();
733
734        let action = LLVMVerifierFailureAction::LLVMReturnStatusAction;
735
736        let code = unsafe { LLVMVerifyModule(self.module.get(), action, err_str.as_mut_ptr()) };
737
738        let err_str = unsafe { err_str.assume_init() };
739        if code == 1 && !err_str.is_null() {
740            return unsafe { Err(LLVMString::new(err_str)) };
741        }
742
743        Ok(())
744    }
745
746    fn get_borrowed_data_layout(module: LLVMModuleRef) -> DataLayout {
747        let data_layout = unsafe {
748            use llvm_sys::core::LLVMGetDataLayoutStr;
749
750            LLVMGetDataLayoutStr(module)
751        };
752
753        unsafe { DataLayout::new_borrowed(data_layout) }
754    }
755
756    /// Gets a smart pointer to the `DataLayout` belonging to a particular `Module`.
757    ///
758    /// # Example
759    ///
760    /// ```no_run
761    /// use inkwell::OptimizationLevel;
762    /// use inkwell::context::Context;
763    /// use inkwell::targets::{InitializationConfig, Target};
764    ///
765    /// Target::initialize_native(&InitializationConfig::default()).expect("Failed to initialize native target");
766    ///
767    /// let context = Context::create();
768    /// let module = context.create_module("sum");
769    /// let execution_engine = module.create_jit_execution_engine(OptimizationLevel::None).unwrap();
770    /// let target_data = execution_engine.get_target_data();
771    /// let data_layout = target_data.get_data_layout();
772    ///
773    /// module.set_data_layout(&data_layout);
774    ///
775    /// assert_eq!(*module.get_data_layout(), data_layout);
776    /// ```
777    pub fn get_data_layout(&self) -> Ref<DataLayout> {
778        Ref::map(self.data_layout.borrow(), |l| {
779            l.as_ref().expect("DataLayout should always exist until Drop")
780        })
781    }
782
783    // REVIEW: Ensure the replaced string ptr still gets cleaned up by the module (I think it does)
784    // valgrind might come in handy once non jemalloc allocators stabilize
785    /// Sets the `DataLayout` for a particular `Module`.
786    ///
787    /// # Example
788    ///
789    /// ```no_run
790    /// use inkwell::OptimizationLevel;
791    /// use inkwell::context::Context;
792    /// use inkwell::targets::{InitializationConfig, Target};
793    ///
794    /// Target::initialize_native(&InitializationConfig::default()).expect("Failed to initialize native target");
795    ///
796    /// let context = Context::create();
797    /// let module = context.create_module("sum");
798    /// let execution_engine = module.create_jit_execution_engine(OptimizationLevel::None).unwrap();
799    /// let target_data = execution_engine.get_target_data();
800    /// let data_layout = target_data.get_data_layout();
801    ///
802    /// module.set_data_layout(&data_layout);
803    ///
804    /// assert_eq!(*module.get_data_layout(), data_layout);
805    /// ```
806    pub fn set_data_layout(&self, data_layout: &DataLayout) {
807        unsafe {
808            LLVMSetDataLayout(self.module.get(), data_layout.as_ptr());
809        }
810
811        *self.data_layout.borrow_mut() = Some(Module::get_borrowed_data_layout(self.module.get()));
812    }
813
814    /// Prints the content of the `Module` to stderr.
815    pub fn print_to_stderr(&self) {
816        unsafe {
817            LLVMDumpModule(self.module.get());
818        }
819    }
820
821    /// Prints the content of the `Module` to an `LLVMString`.
822    pub fn print_to_string(&self) -> LLVMString {
823        unsafe { LLVMString::new(LLVMPrintModuleToString(self.module.get())) }
824    }
825
826    /// Prints the content of the `Module` to a file.
827    pub fn print_to_file<P: AsRef<Path>>(&self, path: P) -> Result<(), LLVMString> {
828        let path_str = path
829            .as_ref()
830            .to_str()
831            .expect("Did not find a valid Unicode path string");
832        let path = to_c_str(path_str);
833        let mut err_string = MaybeUninit::uninit();
834        let return_code = unsafe {
835            LLVMPrintModuleToFile(
836                self.module.get(),
837                path.as_ptr() as *const ::libc::c_char,
838                err_string.as_mut_ptr(),
839            )
840        };
841
842        if return_code == 1 {
843            unsafe {
844                return Err(LLVMString::new(err_string.assume_init()));
845            }
846        }
847
848        Ok(())
849    }
850
851    /// Prints the content of the `Module` to a `String`.
852    pub fn to_string(&self) -> String {
853        self.print_to_string().to_string()
854    }
855
856    /// Sets the inline assembly for the `Module`.
857    pub fn set_inline_assembly(&self, asm: &str) {
858        #[cfg(any(feature = "llvm4-0", feature = "llvm5-0", feature = "llvm6-0"))]
859        {
860            use llvm_sys::core::LLVMSetModuleInlineAsm;
861
862            let c_string = to_c_str(asm);
863
864            unsafe { LLVMSetModuleInlineAsm(self.module.get(), c_string.as_ptr()) }
865        }
866        #[cfg(not(any(feature = "llvm4-0", feature = "llvm5-0", feature = "llvm6-0")))]
867        {
868            use llvm_sys::core::LLVMSetModuleInlineAsm2;
869
870            unsafe { LLVMSetModuleInlineAsm2(self.module.get(), asm.as_ptr() as *const ::libc::c_char, asm.len()) }
871        }
872    }
873
874    // REVIEW: Should module take ownership of metadata?
875    // REVIEW: Should we return a MetadataValue for the global since it's its own value?
876    // it would be the last item in get_global_metadata I believe
877    // TODOC: Appends your metadata to a global MetadataValue<Node> indexed by key
878    /// Appends a `MetaDataValue` to a global list indexed by a particular key.
879    ///
880    /// # Example
881    ///
882    /// ```no_run
883    /// use inkwell::context::Context;
884    ///
885    /// let context = Context::create();
886    /// let module = context.create_module("my_module");
887    /// let bool_type = context.bool_type();
888    /// let f32_type = context.f32_type();
889    /// let bool_val = bool_type.const_int(0, false);
890    /// let f32_val = f32_type.const_float(0.0);
891    ///
892    /// assert_eq!(module.get_global_metadata_size("my_md"), 0);
893    ///
894    /// let md_string = context.metadata_string("lots of metadata here");
895    /// let md_node = context.metadata_node(&[bool_val.into(), f32_val.into()]);
896    ///
897    /// module.add_global_metadata("my_md", &md_string).unwrap();
898    /// module.add_global_metadata("my_md", &md_node).unwrap();
899    ///
900    /// assert_eq!(module.get_global_metadata_size("my_md"), 2);
901    ///
902    /// let global_md = module.get_global_metadata("my_md");
903    ///
904    /// assert_eq!(global_md.len(), 2);
905    ///
906    /// let (md_0, md_1) = (global_md[0].get_node_values(), global_md[1].get_node_values());
907    ///
908    /// assert_eq!(md_0.len(), 1);
909    /// assert_eq!(md_1.len(), 2);
910    /// assert_eq!(md_0[0].into_metadata_value().get_string_value(), md_string.get_string_value());
911    /// assert_eq!(md_1[0].into_int_value(), bool_val);
912    /// assert_eq!(md_1[1].into_float_value(), f32_val);
913    /// ```
914    pub fn add_global_metadata(&self, key: &str, metadata: &MetadataValue<'ctx>) -> Result<(), &'static str> {
915        if !metadata.is_node() {
916            return Err("metadata is expected to be a node.");
917        }
918
919        let c_string = to_c_str(key);
920        unsafe {
921            LLVMAddNamedMetadataOperand(self.module.get(), c_string.as_ptr(), metadata.as_value_ref());
922        }
923
924        Ok(())
925    }
926
927    // REVIEW: Better name? get_global_metadata_len or _count?
928    /// Obtains the number of `MetaDataValue`s indexed by a particular key.
929    ///
930    /// # Example
931    ///
932    /// ```no_run
933    /// use inkwell::context::Context;
934    ///
935    /// let context = Context::create();
936    /// let module = context.create_module("my_module");
937    /// let bool_type = context.bool_type();
938    /// let f32_type = context.f32_type();
939    /// let bool_val = bool_type.const_int(0, false);
940    /// let f32_val = f32_type.const_float(0.0);
941    ///
942    /// assert_eq!(module.get_global_metadata_size("my_md"), 0);
943    ///
944    /// let md_string = context.metadata_string("lots of metadata here");
945    /// let md_node = context.metadata_node(&[bool_val.into(), f32_val.into()]);
946    ///
947    /// module.add_global_metadata("my_md", &md_string).unwrap();
948    /// module.add_global_metadata("my_md", &md_node).unwrap();
949    ///
950    /// assert_eq!(module.get_global_metadata_size("my_md"), 2);
951    ///
952    /// let global_md = module.get_global_metadata("my_md");
953    ///
954    /// assert_eq!(global_md.len(), 2);
955    ///
956    /// let (md_0, md_1) = (global_md[0].get_node_values(), global_md[1].get_node_values());
957    ///
958    /// assert_eq!(md_0.len(), 1);
959    /// assert_eq!(md_1.len(), 2);
960    /// assert_eq!(md_0[0].into_metadata_value().get_string_value(), md_string.get_string_value());
961    /// assert_eq!(md_1[0].into_int_value(), bool_val);
962    /// assert_eq!(md_1[1].into_float_value(), f32_val);
963    /// ```
964    pub fn get_global_metadata_size(&self, key: &str) -> u32 {
965        let c_string = to_c_str(key);
966
967        unsafe { LLVMGetNamedMetadataNumOperands(self.module.get(), c_string.as_ptr()) }
968    }
969
970    // SubTypes: -> Vec<MetadataValue<Node>>
971    /// Obtains the global `MetaDataValue` node indexed by key, which may contain 1 string or multiple values as its `get_node_values()`
972    ///
973    /// # Example
974    ///
975    /// ```no_run
976    /// use inkwell::context::Context;
977    ///
978    /// let context = Context::create();
979    /// let module = context.create_module("my_module");
980    /// let bool_type = context.bool_type();
981    /// let f32_type = context.f32_type();
982    /// let bool_val = bool_type.const_int(0, false);
983    /// let f32_val = f32_type.const_float(0.0);
984    ///
985    /// assert_eq!(module.get_global_metadata_size("my_md"), 0);
986    ///
987    /// let md_string = context.metadata_string("lots of metadata here");
988    /// let md_node = context.metadata_node(&[bool_val.into(), f32_val.into()]);
989    ///
990    /// module.add_global_metadata("my_md", &md_string).unwrap();
991    /// module.add_global_metadata("my_md", &md_node).unwrap();
992    ///
993    /// assert_eq!(module.get_global_metadata_size("my_md"), 2);
994    ///
995    /// let global_md = module.get_global_metadata("my_md");
996    ///
997    /// assert_eq!(global_md.len(), 2);
998    ///
999    /// let (md_0, md_1) = (global_md[0].get_node_values(), global_md[1].get_node_values());
1000    ///
1001    /// assert_eq!(md_0.len(), 1);
1002    /// assert_eq!(md_1.len(), 2);
1003    /// assert_eq!(md_0[0].into_metadata_value().get_string_value(), md_string.get_string_value());
1004    /// assert_eq!(md_1[0].into_int_value(), bool_val);
1005    /// assert_eq!(md_1[1].into_float_value(), f32_val);
1006    /// ```
1007    pub fn get_global_metadata(&self, key: &str) -> Vec<MetadataValue<'ctx>> {
1008        let c_string = to_c_str(key);
1009        let count = self.get_global_metadata_size(key) as usize;
1010
1011        let mut vec: Vec<LLVMValueRef> = Vec::with_capacity(count);
1012        let ptr = vec.as_mut_ptr();
1013
1014        unsafe {
1015            LLVMGetNamedMetadataOperands(self.module.get(), c_string.as_ptr(), ptr);
1016
1017            vec.set_len(count);
1018        };
1019
1020        vec.iter().map(|val| unsafe { MetadataValue::new(*val) }).collect()
1021    }
1022
1023    /// Gets the first `GlobalValue` in a module.
1024    ///
1025    /// # Example
1026    ///
1027    /// ```no_run
1028    /// use inkwell::AddressSpace;
1029    /// use inkwell::context::Context;
1030    ///
1031    /// let context = Context::create();
1032    /// let i8_type = context.i8_type();
1033    /// let module = context.create_module("mod");
1034    ///
1035    /// assert!(module.get_first_global().is_none());
1036    ///
1037    /// let global = module.add_global(i8_type, Some(AddressSpace::from(4u16)), "my_global");
1038    ///
1039    /// assert_eq!(module.get_first_global().unwrap(), global);
1040    /// ```
1041    pub fn get_first_global(&self) -> Option<GlobalValue<'ctx>> {
1042        let value = unsafe { LLVMGetFirstGlobal(self.module.get()) };
1043
1044        if value.is_null() {
1045            return None;
1046        }
1047
1048        unsafe { Some(GlobalValue::new(value)) }
1049    }
1050
1051    /// Gets the last `GlobalValue` in a module.
1052    ///
1053    /// # Example
1054    ///
1055    /// ```no_run
1056    /// use inkwell::AddressSpace;
1057    /// use inkwell::context::Context;
1058    ///
1059    /// let context = Context::create();
1060    /// let module = context.create_module("mod");
1061    /// let i8_type = context.i8_type();
1062    ///
1063    /// assert!(module.get_last_global().is_none());
1064    ///
1065    /// let global = module.add_global(i8_type, Some(AddressSpace::from(4u16)), "my_global");
1066    ///
1067    /// assert_eq!(module.get_last_global().unwrap(), global);
1068    /// ```
1069    pub fn get_last_global(&self) -> Option<GlobalValue<'ctx>> {
1070        let value = unsafe { LLVMGetLastGlobal(self.module.get()) };
1071
1072        if value.is_null() {
1073            return None;
1074        }
1075
1076        unsafe { Some(GlobalValue::new(value)) }
1077    }
1078
1079    /// Gets a named `GlobalValue` in a module.
1080    ///
1081    /// # Example
1082    ///
1083    /// ```no_run
1084    /// use inkwell::AddressSpace;
1085    /// use inkwell::context::Context;
1086    ///
1087    /// let context = Context::create();
1088    /// let module = context.create_module("mod");
1089    /// let i8_type = context.i8_type();
1090    ///
1091    /// assert!(module.get_global("my_global").is_none());
1092    ///
1093    /// let global = module.add_global(i8_type, Some(AddressSpace::from(4u16)), "my_global");
1094    ///
1095    /// assert_eq!(module.get_global("my_global").unwrap(), global);
1096    /// ```
1097    pub fn get_global(&self, name: &str) -> Option<GlobalValue<'ctx>> {
1098        let c_string = to_c_str(name);
1099        let value = unsafe { LLVMGetNamedGlobal(self.module.get(), c_string.as_ptr()) };
1100
1101        if value.is_null() {
1102            return None;
1103        }
1104
1105        unsafe { Some(GlobalValue::new(value)) }
1106    }
1107
1108    /// An iterator over the globals in this `Module`.
1109    pub fn get_globals(&self) -> GlobalIterator<'ctx> {
1110        GlobalIterator::from_module(self)
1111    }
1112
1113    /// Creates a new `Module` from a `MemoryBuffer` with bitcode.
1114    ///
1115    /// # Example
1116    ///
1117    /// ```no_run
1118    /// use inkwell::context::Context;
1119    /// use inkwell::module::Module;
1120    /// use inkwell::memory_buffer::MemoryBuffer;
1121    /// use std::path::Path;
1122    ///
1123    /// let path = Path::new("foo/bar.bc");
1124    /// let context = Context::create();
1125    /// let buffer = MemoryBuffer::create_from_file(&path).unwrap();
1126    /// let module = Module::parse_bitcode_from_buffer(&buffer, &context);
1127    ///
1128    /// assert_eq!(module.unwrap().get_context(), context);
1129    ///
1130    /// ```
1131    pub fn parse_bitcode_from_buffer(
1132        buffer: &MemoryBuffer,
1133        context: impl AsContextRef<'ctx>,
1134    ) -> Result<Self, LLVMString> {
1135        let mut module = MaybeUninit::uninit();
1136        let mut err_string = MaybeUninit::uninit();
1137
1138        // LLVM has a newer version of this function w/o the error result since 3.8 but this deprecated function
1139        // hasen't yet been removed even in LLVM 8. Seems fine to use instead of switching to their
1140        // error diagnostics handler for now.
1141        #[allow(deprecated)]
1142        let success = unsafe {
1143            LLVMParseBitcodeInContext(
1144                context.as_ctx_ref(),
1145                buffer.memory_buffer,
1146                module.as_mut_ptr(),
1147                err_string.as_mut_ptr(),
1148            )
1149        };
1150
1151        if success != 0 {
1152            unsafe {
1153                return Err(LLVMString::new(err_string.assume_init()));
1154            }
1155        }
1156
1157        unsafe { Ok(Module::new(module.assume_init())) }
1158    }
1159
1160    /// A convenience function for creating a `Module` from a bitcode file for a given context.
1161    ///
1162    /// # Example
1163    ///
1164    /// ```no_run
1165    /// use inkwell::context::Context;
1166    /// use inkwell::module::Module;
1167    /// use std::path::Path;
1168    ///
1169    /// let path = Path::new("foo/bar.bc");
1170    /// let context = Context::create();
1171    /// let module = Module::parse_bitcode_from_path(&path, &context);
1172    ///
1173    /// assert_eq!(module.unwrap().get_context(), context);
1174    ///
1175    /// ```
1176    // LLVMGetBitcodeModuleInContext was a pain to use, so I seem to be able to achieve the same effect
1177    // by reusing create_from_file instead. This is basically just a convenience function.
1178    pub fn parse_bitcode_from_path<P: AsRef<Path>>(
1179        path: P,
1180        context: impl AsContextRef<'ctx>,
1181    ) -> Result<Self, LLVMString> {
1182        let buffer = MemoryBuffer::create_from_file(path.as_ref())?;
1183
1184        Self::parse_bitcode_from_buffer(&buffer, context)
1185    }
1186
1187    /// Gets the name of this `Module`.
1188    ///
1189    /// # Example
1190    ///
1191    /// ```no_run
1192    /// use inkwell::context::Context;
1193    ///
1194    /// let context = Context::create();
1195    /// let module = context.create_module("my_module");
1196    ///
1197    /// assert_eq!(module.get_name().to_str(), Ok("my_mdoule"));
1198    /// ```
1199    pub fn get_name(&self) -> &CStr {
1200        let mut length = 0;
1201        let cstr_ptr = unsafe { LLVMGetModuleIdentifier(self.module.get(), &mut length) };
1202
1203        unsafe { CStr::from_ptr(cstr_ptr) }
1204    }
1205
1206    /// Assigns the name of this `Module`.
1207    ///
1208    /// # Example
1209    ///
1210    /// ```no_run
1211    /// use inkwell::context::Context;
1212    ///
1213    /// let context = Context::create();
1214    /// let module = context.create_module("my_module");
1215    ///
1216    /// module.set_name("my_module2");
1217    ///
1218    /// assert_eq!(module.get_name().to_str(), Ok("my_module2"));
1219    /// ```
1220    pub fn set_name(&self, name: &str) {
1221        unsafe { LLVMSetModuleIdentifier(self.module.get(), name.as_ptr() as *const ::libc::c_char, name.len()) }
1222    }
1223
1224    /// Gets the source file name. It defaults to the module identifier but is separate from it.
1225    ///
1226    /// # Example
1227    ///
1228    /// ```no_run
1229    /// use inkwell::context::Context;
1230    ///
1231    /// let context = Context::create();
1232    /// let module = context.create_module("my_mod");
1233    ///
1234    /// assert_eq!(module.get_source_file_name().to_str(), Ok("my_mod"));
1235    ///
1236    /// module.set_source_file_name("my_mod.rs");
1237    ///
1238    /// assert_eq!(module.get_name().to_str(), Ok("my_mod"));
1239    /// assert_eq!(module.get_source_file_name().to_str(), Ok("my_mod.rs"));
1240    /// ```
1241    #[llvm_versions(7.0..=latest)]
1242    pub fn get_source_file_name(&self) -> &CStr {
1243        use llvm_sys::core::LLVMGetSourceFileName;
1244
1245        let mut len = 0;
1246        let ptr = unsafe { LLVMGetSourceFileName(self.module.get(), &mut len) };
1247
1248        unsafe { CStr::from_ptr(ptr) }
1249    }
1250
1251    /// Sets the source file name. It defaults to the module identifier but is separate from it.
1252    ///
1253    /// # Example
1254    ///
1255    /// ```no_run
1256    /// use inkwell::context::Context;
1257    ///
1258    /// let context = Context::create();
1259    /// let module = context.create_module("my_mod");
1260    ///
1261    /// assert_eq!(module.get_source_file_name().to_str(), Ok("my_mod"));
1262    ///
1263    /// module.set_source_file_name("my_mod.rs");
1264    ///
1265    /// assert_eq!(module.get_name().to_str(), Ok("my_mod"));
1266    /// assert_eq!(module.get_source_file_name().to_str(), Ok("my_mod.rs"));
1267    /// ```
1268    #[llvm_versions(7.0..=latest)]
1269    pub fn set_source_file_name(&self, file_name: &str) {
1270        use llvm_sys::core::LLVMSetSourceFileName;
1271
1272        unsafe {
1273            LLVMSetSourceFileName(
1274                self.module.get(),
1275                file_name.as_ptr() as *const ::libc::c_char,
1276                file_name.len(),
1277            )
1278        }
1279    }
1280
1281    /// Links one module into another. This will merge two `Module`s into one.
1282    ///
1283    /// # Example
1284    ///
1285    /// ```no_run
1286    /// use inkwell::context::Context;
1287    ///
1288    /// let context = Context::create();
1289    /// let module = context.create_module("mod");
1290    /// let module2 = context.create_module("mod2");
1291    ///
1292    /// assert!(module.link_in_module(module2).is_ok());
1293    /// ```
1294    pub fn link_in_module(&self, other: Self) -> Result<(), LLVMString> {
1295        if other.owned_by_ee.borrow().is_some() {
1296            let string = "Cannot link a module which is already owned by an ExecutionEngine.\0";
1297            return Err(LLVMString::create_from_str(string));
1298        }
1299
1300        use crate::support::error_handling::get_error_str_diagnostic_handler;
1301        use libc::c_void;
1302        use llvm_sys::linker::LLVMLinkModules2;
1303
1304        let context = self.get_context();
1305
1306        let mut char_ptr: *mut ::libc::c_char = ptr::null_mut();
1307        let char_ptr_ptr = &mut char_ptr as *mut *mut ::libc::c_char as *mut *mut c_void as *mut c_void;
1308
1309        // Newer LLVM versions don't use an out ptr anymore which was really straightforward...
1310        // Here we assign an error handler to extract the error message, if any, for us.
1311        context.set_diagnostic_handler(get_error_str_diagnostic_handler, char_ptr_ptr);
1312
1313        let code = unsafe { LLVMLinkModules2(self.module.get(), other.module.get()) };
1314
1315        forget(other);
1316
1317        if code == 1 {
1318            debug_assert!(!char_ptr.is_null());
1319
1320            unsafe { Err(LLVMString::new(char_ptr)) }
1321        } else {
1322            Ok(())
1323        }
1324    }
1325
1326    /// Gets the `Comdat` associated with a particular name. If it does not exist, it will be created.
1327    /// A new `Comdat` defaults to a kind of `ComdatSelectionKind::Any`.
1328    #[llvm_versions(7.0..=latest)]
1329    pub fn get_or_insert_comdat(&self, name: &str) -> Comdat {
1330        use llvm_sys::comdat::LLVMGetOrInsertComdat;
1331
1332        let c_string = to_c_str(name);
1333        let comdat_ptr = unsafe { LLVMGetOrInsertComdat(self.module.get(), c_string.as_ptr()) };
1334
1335        unsafe { Comdat::new(comdat_ptr) }
1336    }
1337
1338    /// Gets the `MetadataValue` flag associated with the key in this module, if any.
1339    /// If a `BasicValue` was used to create this flag, it will be wrapped in a `MetadataValue`
1340    /// when returned from this function.
1341    // SubTypes: Might need to return Option<BVE, MV<Enum>, or MV<String>>
1342    #[llvm_versions(7.0..=latest)]
1343    pub fn get_flag(&self, key: &str) -> Option<MetadataValue<'ctx>> {
1344        use llvm_sys::core::LLVMMetadataAsValue;
1345
1346        let flag = unsafe { LLVMGetModuleFlag(self.module.get(), key.as_ptr() as *const ::libc::c_char, key.len()) };
1347
1348        if flag.is_null() {
1349            return None;
1350        }
1351
1352        let flag_value = unsafe { LLVMMetadataAsValue(LLVMGetModuleContext(self.module.get()), flag) };
1353
1354        unsafe { Some(MetadataValue::new(flag_value)) }
1355    }
1356
1357    /// Append a `MetadataValue` as a module wide flag. Note that using the same key twice
1358    /// will likely invalidate the module.
1359    #[llvm_versions(7.0..=latest)]
1360    pub fn add_metadata_flag(&self, key: &str, behavior: FlagBehavior, flag: MetadataValue<'ctx>) {
1361        let md = flag.as_metadata_ref();
1362
1363        unsafe {
1364            LLVMAddModuleFlag(
1365                self.module.get(),
1366                behavior.into(),
1367                key.as_ptr() as *mut ::libc::c_char,
1368                key.len(),
1369                md,
1370            )
1371        }
1372    }
1373
1374    /// Append a `BasicValue` as a module wide flag. Note that using the same key twice
1375    /// will likely invalidate the module.
1376    // REVIEW: What happens if value is not const?
1377    #[llvm_versions(7.0..=latest)]
1378    pub fn add_basic_value_flag<BV: BasicValue<'ctx>>(&self, key: &str, behavior: FlagBehavior, flag: BV) {
1379        use llvm_sys::core::LLVMValueAsMetadata;
1380
1381        let md = unsafe { LLVMValueAsMetadata(flag.as_value_ref()) };
1382
1383        unsafe {
1384            LLVMAddModuleFlag(
1385                self.module.get(),
1386                behavior.into(),
1387                key.as_ptr() as *mut ::libc::c_char,
1388                key.len(),
1389                md,
1390            )
1391        }
1392    }
1393
1394    /// Strips and debug info from the module, if it exists.
1395    #[llvm_versions(6.0..=latest)]
1396    pub fn strip_debug_info(&self) -> bool {
1397        use llvm_sys::debuginfo::LLVMStripModuleDebugInfo;
1398
1399        unsafe { LLVMStripModuleDebugInfo(self.module.get()) == 1 }
1400    }
1401
1402    /// Gets the version of debug metadata contained in this `Module`.
1403    #[llvm_versions(6.0..=latest)]
1404    pub fn get_debug_metadata_version(&self) -> libc::c_uint {
1405        use llvm_sys::debuginfo::LLVMGetModuleDebugMetadataVersion;
1406
1407        unsafe { LLVMGetModuleDebugMetadataVersion(self.module.get()) }
1408    }
1409
1410    /// Creates a `DebugInfoBuilder` for this `Module`.
1411    #[llvm_versions(7.0..=latest)]
1412    pub fn create_debug_info_builder(
1413        &self,
1414        allow_unresolved: bool,
1415        language: DWARFSourceLanguage,
1416        filename: &str,
1417        directory: &str,
1418        producer: &str,
1419        is_optimized: bool,
1420        flags: &str,
1421        runtime_ver: libc::c_uint,
1422        split_name: &str,
1423        kind: DWARFEmissionKind,
1424        dwo_id: libc::c_uint,
1425        split_debug_inlining: bool,
1426        debug_info_for_profiling: bool,
1427        #[cfg(any(
1428            feature = "llvm11-0",
1429            feature = "llvm12-0",
1430            feature = "llvm13-0",
1431            feature = "llvm14-0",
1432            feature = "llvm15-0",
1433            feature = "llvm16-0"
1434        ))]
1435        sysroot: &str,
1436        #[cfg(any(
1437            feature = "llvm11-0",
1438            feature = "llvm12-0",
1439            feature = "llvm13-0",
1440            feature = "llvm14-0",
1441            feature = "llvm15-0",
1442            feature = "llvm16-0"
1443        ))]
1444        sdk: &str,
1445    ) -> (DebugInfoBuilder<'ctx>, DICompileUnit<'ctx>) {
1446        DebugInfoBuilder::new(
1447            self,
1448            allow_unresolved,
1449            language,
1450            filename,
1451            directory,
1452            producer,
1453            is_optimized,
1454            flags,
1455            runtime_ver,
1456            split_name,
1457            kind,
1458            dwo_id,
1459            split_debug_inlining,
1460            debug_info_for_profiling,
1461            #[cfg(any(
1462                feature = "llvm11-0",
1463                feature = "llvm12-0",
1464                feature = "llvm13-0",
1465                feature = "llvm14-0",
1466                feature = "llvm15-0",
1467                feature = "llvm16-0"
1468            ))]
1469            sysroot,
1470            #[cfg(any(
1471                feature = "llvm11-0",
1472                feature = "llvm12-0",
1473                feature = "llvm13-0",
1474                feature = "llvm14-0",
1475                feature = "llvm15-0",
1476                feature = "llvm16-0"
1477            ))]
1478            sdk,
1479        )
1480    }
1481
1482    /// Construct and run a set of passes over a module.
1483    /// This function takes a string with the passes that should be used.
1484    /// The format of this string is the same as opt's -passes argument for the new pass manager.
1485    /// Individual passes may be specified, separated by commas.
1486    /// Full pipelines may also be invoked using default<O3> and friends.
1487    /// See opt for full reference of the Passes format.
1488    #[llvm_versions(13.0..=latest)]
1489    pub fn run_passes(
1490        &self,
1491        passes: &str,
1492        machine: &TargetMachine,
1493        options: PassBuilderOptions,
1494    ) -> Result<(), LLVMString> {
1495        unsafe {
1496            let error = LLVMRunPasses(
1497                self.module.get(),
1498                to_c_str(passes).as_ptr(),
1499                machine.target_machine,
1500                options.options_ref,
1501            );
1502            if error == std::ptr::null_mut() {
1503                Ok(())
1504            } else {
1505                let message = LLVMGetErrorMessage(error);
1506                Err(LLVMString::new(message as *const libc::c_char))
1507            }
1508        }
1509    }
1510}
1511
1512impl Clone for Module<'_> {
1513    fn clone(&self) -> Self {
1514        // REVIEW: Is this just a LLVM 6 bug? We could conditionally compile this assertion for affected versions
1515        let verify = self.verify();
1516
1517        assert!(
1518            verify.is_ok(),
1519            "Cloning a Module seems to segfault when module is not valid. We are preventing that here. Error: {}",
1520            verify.unwrap_err()
1521        );
1522
1523        unsafe { Module::new(LLVMCloneModule(self.module.get())) }
1524    }
1525}
1526
1527// Module owns the data layout string, so LLVMDisposeModule will deallocate it for us.
1528// which is why DataLayout must be called with `new_borrowed`
1529impl Drop for Module<'_> {
1530    fn drop(&mut self) {
1531        if self.owned_by_ee.borrow_mut().take().is_none() {
1532            unsafe {
1533                LLVMDisposeModule(self.module.get());
1534            }
1535        }
1536
1537        // Context & EE will drop naturally if they are unique references at this point
1538    }
1539}
1540
1541#[llvm_versions(7.0..=latest)]
1542#[llvm_enum(LLVMModuleFlagBehavior)]
1543#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
1544/// Defines the operational behavior for a module wide flag. This documenation comes directly
1545/// from the LLVM docs
1546pub enum FlagBehavior {
1547    /// Emits an error if two values disagree, otherwise the resulting value is that of the operands.
1548    #[llvm_variant(LLVMModuleFlagBehaviorError)]
1549    Error,
1550    /// Emits a warning if two values disagree. The result value will be the operand for the
1551    /// flag from the first module being linked.
1552    #[llvm_variant(LLVMModuleFlagBehaviorWarning)]
1553    Warning,
1554    /// Adds a requirement that another module flag be present and have a specified value after
1555    /// linking is performed. The value must be a metadata pair, where the first element of the
1556    /// pair is the ID of the module flag to be restricted, and the second element of the pair
1557    /// is the value the module flag should be restricted to. This behavior can be used to
1558    /// restrict the allowable results (via triggering of an error) of linking IDs with the
1559    /// **Override** behavior.
1560    #[llvm_variant(LLVMModuleFlagBehaviorRequire)]
1561    Require,
1562    /// Uses the specified value, regardless of the behavior or value of the other module. If
1563    /// both modules specify **Override**, but the values differ, an error will be emitted.
1564    #[llvm_variant(LLVMModuleFlagBehaviorOverride)]
1565    Override,
1566    /// Appends the two values, which are required to be metadata nodes.
1567    #[llvm_variant(LLVMModuleFlagBehaviorAppend)]
1568    Append,
1569    /// Appends the two values, which are required to be metadata nodes. However, duplicate
1570    /// entries in the second list are dropped during the append operation.
1571    #[llvm_variant(LLVMModuleFlagBehaviorAppendUnique)]
1572    AppendUnique,
1573}
1574
1575/// Iterate over all `FunctionValue`s in an llvm module
1576#[derive(Debug)]
1577pub struct FunctionIterator<'ctx>(FunctionIteratorInner<'ctx>);
1578
1579/// Inner type so the variants are not publicly visible
1580#[derive(Debug)]
1581enum FunctionIteratorInner<'ctx> {
1582    Empty,
1583    Start(FunctionValue<'ctx>),
1584    Previous(FunctionValue<'ctx>),
1585}
1586
1587impl<'ctx> FunctionIterator<'ctx> {
1588    fn from_module(module: &Module<'ctx>) -> Self {
1589        use FunctionIteratorInner::*;
1590
1591        match module.get_first_function() {
1592            None => Self(Empty),
1593            Some(first) => Self(Start(first)),
1594        }
1595    }
1596}
1597
1598impl<'ctx> Iterator for FunctionIterator<'ctx> {
1599    type Item = FunctionValue<'ctx>;
1600
1601    fn next(&mut self) -> Option<Self::Item> {
1602        use FunctionIteratorInner::*;
1603
1604        match self.0 {
1605            Empty => None,
1606            Start(first) => {
1607                self.0 = Previous(first);
1608
1609                Some(first)
1610            },
1611            Previous(prev) => match prev.get_next_function() {
1612                Some(current) => {
1613                    self.0 = Previous(current);
1614
1615                    Some(current)
1616                },
1617                None => None,
1618            },
1619        }
1620    }
1621}
1622
1623/// Iterate over all `GlobalValue`s in an llvm module
1624#[derive(Debug)]
1625pub struct GlobalIterator<'ctx>(GlobalIteratorInner<'ctx>);
1626
1627/// Inner type so the variants are not publicly visible
1628#[derive(Debug)]
1629enum GlobalIteratorInner<'ctx> {
1630    Empty,
1631    Start(GlobalValue<'ctx>),
1632    Previous(GlobalValue<'ctx>),
1633}
1634
1635impl<'ctx> GlobalIterator<'ctx> {
1636    fn from_module(module: &Module<'ctx>) -> Self {
1637        use GlobalIteratorInner::*;
1638
1639        match module.get_first_global() {
1640            None => Self(Empty),
1641            Some(first) => Self(Start(first)),
1642        }
1643    }
1644}
1645
1646impl<'ctx> Iterator for GlobalIterator<'ctx> {
1647    type Item = GlobalValue<'ctx>;
1648
1649    fn next(&mut self) -> Option<Self::Item> {
1650        use GlobalIteratorInner::*;
1651
1652        match self.0 {
1653            Empty => None,
1654            Start(first) => {
1655                self.0 = Previous(first);
1656
1657                Some(first)
1658            },
1659            Previous(prev) => match prev.get_next_global() {
1660                Some(current) => {
1661                    self.0 = Previous(current);
1662
1663                    Some(current)
1664                },
1665                None => None,
1666            },
1667        }
1668    }
1669}