inkwell::execution_engine

Struct ExecutionEngine

Source
pub struct ExecutionEngine<'ctx> { /* private fields */ }
Expand description

A reference-counted wrapper around LLVM’s execution engine.

§Note

Cloning this object is essentially just a case of copying a couple pointers and incrementing one or two atomics, so this should be quite cheap to create copies. The underlying LLVM object will be automatically deallocated when there are no more references to it.

Implementations§

Source§

impl<'ctx> ExecutionEngine<'ctx>

Source

pub unsafe fn new( execution_engine: Rc<LLVMExecutionEngineRef>, jit_mode: bool, ) -> Self

Source

pub fn as_mut_ptr(&self) -> LLVMExecutionEngineRef

Acquires the underlying raw pointer belonging to this ExecutionEngine type.

This function probably doesn’t need to be called, but is here due to linking(?) requirements. Bad things happen if we don’t provide it.

This function probably doesn’t need to be called, but is here due to linking(?) requirements. Bad things happen if we don’t provide it.

Source

pub fn add_global_mapping(&self, value: &dyn AnyValue<'ctx>, addr: usize)

Maps the specified value to an address.

§Example
use inkwell::targets::{InitializationConfig, Target};
use inkwell::context::Context;
use inkwell::OptimizationLevel;

Target::initialize_native(&InitializationConfig::default()).unwrap();

extern fn sumf(a: f64, b: f64) -> f64 {
    a + b
}

let context = Context::create();
let module = context.create_module("test");
let builder = context.create_builder();

let ft = context.f64_type();
let fnt = ft.fn_type(&[], false);

let f = module.add_function("test_fn", fnt, None);
let b = context.append_basic_block(f, "entry");

builder.position_at_end(b);

let extf = module.add_function("sumf", ft.fn_type(&[ft.into(), ft.into()], false), None);

let argf = ft.const_float(64.);
let call_site_value = builder.build_call(extf, &[argf.into(), argf.into()], "retv").unwrap();
let retv = call_site_value.try_as_basic_value().left().unwrap().into_float_value();

builder.build_return(Some(&retv)).unwrap();

let mut ee = module.create_jit_execution_engine(OptimizationLevel::None).unwrap();
ee.add_global_mapping(&extf, sumf as usize);

let result = unsafe { ee.run_function(f, &[]) }.as_float(&ft);

assert_eq!(result, 128.);
Source

pub fn add_module(&self, module: &Module<'ctx>) -> Result<(), ()>

Adds a module to an ExecutionEngine.

The method will be Ok(()) if the module does not belong to an ExecutionEngine already and Err(()) otherwise.

use inkwell::targets::{InitializationConfig, Target};
use inkwell::context::Context;
use inkwell::OptimizationLevel;

Target::initialize_native(&InitializationConfig::default()).unwrap();

let context = Context::create();
let module = context.create_module("test");
let mut ee = module.create_jit_execution_engine(OptimizationLevel::None).unwrap();

assert!(ee.add_module(&module).is_err());
Source

pub fn remove_module( &self, module: &Module<'ctx>, ) -> Result<(), RemoveModuleError>

Source

pub unsafe fn get_function<F>( &self, fn_name: &str, ) -> Result<JitFunction<'ctx, F>, FunctionLookupError>

Try to load a function from the execution engine.

If a target hasn’t already been initialized, spurious “function not found” errors may be encountered.

The UnsafeFunctionPointer trait is designed so only unsafe extern "C" functions can be retrieved via the get_function() method. If you get funny type errors then it’s probably because you have specified the wrong calling convention or forgotten to specify the retrieved function as unsafe.

§Examples
let context = Context::create();
let module = context.create_module("test");
let builder = context.create_builder();

// Set up the function signature
let double = context.f64_type();
let sig = double.fn_type(&[], false);

// Add the function to our module
let f = module.add_function("test_fn", sig, None);
let b = context.append_basic_block(f, "entry");
builder.position_at_end(b);

// Insert a return statement
let ret = double.const_float(64.0);
builder.build_return(Some(&ret)).unwrap();

// create the JIT engine
let mut ee = module.create_jit_execution_engine(OptimizationLevel::None).unwrap();

// fetch our JIT'd function and execute it
unsafe {
    let test_fn = ee.get_function::<unsafe extern "C" fn() -> f64>("test_fn").unwrap();
    let return_value = test_fn.call();
    assert_eq!(return_value, 64.0);
}
§Safety

It is the caller’s responsibility to ensure they call the function with the correct signature and calling convention.

The JitFunction wrapper ensures a function won’t accidentally outlive the execution engine it came from, but adding functions after calling this method may invalidate the function pointer.

Source

pub fn get_function_address( &self, fn_name: &str, ) -> Result<usize, FunctionLookupError>

Attempts to look up a function’s address by its name. May return Err if the function cannot be found or some other unknown error has occurred.

It is recommended to use get_function instead of this method when intending to call the function pointer so that you don’t have to do error-prone transmutes yourself.

Source

pub fn get_target_data(&self) -> &TargetData

Source

pub fn get_function_value( &self, fn_name: &str, ) -> Result<FunctionValue<'ctx>, FunctionLookupError>

Source

pub unsafe fn run_function( &self, function: FunctionValue<'ctx>, args: &[&GenericValue<'ctx>], ) -> GenericValue<'ctx>

Source

pub unsafe fn run_function_as_main( &self, function: FunctionValue<'ctx>, args: &[&str], ) -> c_int

Source

pub fn free_fn_machine_code(&self, function: FunctionValue<'ctx>)

Source

pub fn run_static_constructors(&self)

Source

pub fn run_static_destructors(&self)

Trait Implementations§

Source§

impl Clone for ExecutionEngine<'_>

Source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'ctx> Debug for ExecutionEngine<'ctx>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for ExecutionEngine<'_>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl<'ctx> PartialEq for ExecutionEngine<'ctx>

Source§

fn eq(&self, other: &ExecutionEngine<'ctx>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'ctx> Eq for ExecutionEngine<'ctx>

Source§

impl<'ctx> StructuralPartialEq for ExecutionEngine<'ctx>

Auto Trait Implementations§

§

impl<'ctx> Freeze for ExecutionEngine<'ctx>

§

impl<'ctx> RefUnwindSafe for ExecutionEngine<'ctx>

§

impl<'ctx> !Send for ExecutionEngine<'ctx>

§

impl<'ctx> !Sync for ExecutionEngine<'ctx>

§

impl<'ctx> Unpin for ExecutionEngine<'ctx>

§

impl<'ctx> UnwindSafe for ExecutionEngine<'ctx>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.