Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
numba
GitHub Repository: numba/llvmlite
Path: blob/main/examples/lljit.py
1154 views
1
# Tutorial example from
2
# https://llvmlite.readthedocs.io/en/latest/user-guide/binding/examples.html
3
# adapted to use LLJIT instead of MCJIT
4
#
5
# Additionally this example also demonstrates that typed pointers still work in
6
# LLVM 14 (and 15, if built against that).
7
8
from ctypes import CFUNCTYPE, POINTER, c_double
9
10
import llvmlite.binding as llvm
11
import numpy as np
12
13
llvm.initialize_native_target()
14
llvm.initialize_native_asmprinter() # yes, even this one
15
16
llvm_ir = """
17
; ModuleID = "examples/ir_fpadd.py"
18
target triple = "unknown-unknown-unknown"
19
target datalayout = ""
20
21
define double @"fpadd"(double %".1", double %".2", double* %"dummy")
22
{
23
entry:
24
%"res" = fadd double %".1", %".2"
25
%"val" = load double, double* %"dummy"
26
%"res2" = fadd double %"res", %"val"
27
ret double %"res2"
28
}
29
"""
30
31
lljit = llvm.create_lljit_compiler()
32
rt = llvm.JITLibraryBuilder().add_ir(llvm_ir).export_symbol('fpadd')\
33
.link(lljit, 'fpadd')
34
35
cfunc = CFUNCTYPE(c_double, c_double, c_double, POINTER(c_double))(rt['fpadd'])
36
37
# Create some floating point data and get a pointer to it that we can pass in
38
# to the jitted function
39
x = np.asarray([7.2])
40
data_ptr = x.ctypes.data_as(POINTER(c_double))
41
42
43
args = (1.0, 3.5, data_ptr)
44
res = cfunc(*args)
45
print(f"x[0] = {x[0]}")
46
print(f"fpadd({args[0]}, {args[1]}, &x[0]) = {res}")
47
48