llvmlite

0.46.0 · active · verified Sat Mar 28

llvmlite is a lightweight Python binding to LLVM, primarily used for just-in-time (JIT) compilation. It allows Python code to construct LLVM Intermediate Representation (IR) in pure Python, which is then passed to LLVM for compilation and optimization. Maintained by the Numba team, it releases several times a year, often in conjunction with Numba updates and LLVM version bumps. The current stable version is 0.46.0.

Warnings

Install

Imports

Quickstart

This example demonstrates how to define a simple floating-point addition function using `llvmlite.ir`, compile it using `llvmlite.binding`, and execute it via `ctypes`. It covers IR construction, module parsing, execution engine setup, and function invocation.

from ctypes import CFUNCTYPE, c_double
from llvmlite import ir
import llvmlite.binding as llvm

# All these initializations are required for JIT compilation
llvm.initialize_native_target()
llvm.initialize_native_asmprinter()

# Define the LLVM IR for a simple function (double fpadd(double a, double b) { return a + b; })
double = ir.DoubleType()
fnty = ir.FunctionType(double, (double, double))

module = ir.Module(name=__file__)
func = ir.Function(module, fnty, name="fpadd")

block = func.append_basic_block(name="entry")
builder = ir.IRBuilder(block)
a, b = func.args
result = builder.fadd(a, b, name="res")
builder.ret(result)

# Convert textual LLVM IR into in-memory representation
llvm_module = llvm.parse_assembly(str(module))
llvm_module.verify()

# Create an ExecutionEngine suitable for JIT code generation
target = llvm.Target.from_default_triple()
target_machine = target.create_target_machine()
engine = llvm.create_mcjit_compiler(llvm_module, target_machine)

# Finalize the engine to make the function available
engine.finalize_object()
engine.run_static_constructors()

# Look up the function pointer and cast it to a C function
func_ptr = engine.get_function_address("fpadd")
cfunc = CFUNCTYPE(c_double, c_double, c_double)(func_ptr)

# Run the function
res = cfunc(1.0, 2.5)
print(f"Result of fpadd(1.0, 2.5): {res}") # Expected: 3.5

view raw JSON →