Updated more tests to use unittest.

This commit is contained in:
Siu Kwan Lam 2012-07-20 21:46:23 -07:00
commit a9370d933d
5 changed files with 245 additions and 170 deletions

View file

@ -3,61 +3,68 @@
from llvm.core import Module,Type,Builder from llvm.core import Module,Type,Builder
from llvm.ee import ExecutionEngine from llvm.ee import ExecutionEngine
import llvm.core import llvm.core
import ctypes import ctypes
def test_jit_ctypes(): import logging
import unittest
# This example demonstrates calling an LLVM defined function using class TestCallJITCtypes(unittest.TestCase):
# ctypes. It illustrates the common C pattern of having an output def test_jit_ctypes(self):
# variable in the argument list to the function. The function also
# returns an error code upon exit.
# setup llvm types # This example demonstrates calling an LLVM defined function using
ty_errcode = Type.int() # ctypes. It illustrates the common C pattern of having an output
ty_float = Type.float() # variable in the argument list to the function. The function also
ty_ptr_float = Type.pointer(Type.float()) # returns an error code upon exit.
ty_func = Type.function(ty_errcode, [ty_float, ty_float, ty_ptr_float])
# setup ctypes types # setup llvm types
ct_errcode = ctypes.c_int ty_errcode = Type.int()
ct_float = ctypes.c_float ty_float = Type.float()
ct_ptr_float = ctypes.POINTER(ct_float) ty_ptr_float = Type.pointer(Type.float())
ct_argtypes = [ct_float, ct_float, ct_ptr_float] ty_func = Type.function(ty_errcode, [ty_float, ty_float, ty_ptr_float])
# generate the function using LLVM # setup ctypes types
my_module = Module.new('my_module') ct_errcode = ctypes.c_int
ct_float = ctypes.c_float
ct_ptr_float = ctypes.POINTER(ct_float)
ct_argtypes = [ct_float, ct_float, ct_ptr_float]
mult = my_module.add_function(ty_func, "mult") # generate the function using LLVM
mult.args[0].name = "a" my_module = Module.new('my_module')
mult.args[1].name = "b"
mult.args[2].name = "out"
mult.args[2].add_attribute(llvm.core.ATTR_NO_CAPTURE) # add nocapture to output arg
mult.does_not_throw = True # add nounwind attribute to function
bb = mult.append_basic_block("entry") mult = my_module.add_function(ty_func, "mult")
builder = Builder.new(bb) mult.args[0].name = "a"
tmp = builder.fmul( mult.args[0], mult.args[1] ) mult.args[1].name = "b"
builder.store( tmp, mult.args[2] ) mult.args[2].name = "out"
builder.ret(llvm.core.Constant.int(ty_errcode, 0)) # add nocapture to output arg
mult.args[2].add_attribute(llvm.core.ATTR_NO_CAPTURE)
mult.does_not_throw = True # add nounwind attribute to function
bb = mult.append_basic_block("entry")
builder = Builder.new(bb)
tmp = builder.fmul( mult.args[0], mult.args[1] )
builder.store( tmp, mult.args[2] )
builder.ret(llvm.core.Constant.int(ty_errcode, 0))
if 0:
# print the created module # print the created module
print(my_module) logging.debug(my_module)
# compile the function # compile the function
ee = ExecutionEngine.new(my_module) ee = ExecutionEngine.new(my_module)
# let ctypes know about the function # let ctypes know about the function
func_ptr_int = ee.get_pointer_to_function( mult ) func_ptr_int = ee.get_pointer_to_function( mult )
FUNC_TYPE = ctypes.CFUNCTYPE(ct_errcode, *ct_argtypes) FUNC_TYPE = ctypes.CFUNCTYPE(ct_errcode, *ct_argtypes)
py_mult = FUNC_TYPE(func_ptr_int) py_mult = FUNC_TYPE(func_ptr_int)
# now run the function, calling via ctypes # now run the function, calling via ctypes
output_value = ct_float(123456.0) output_value = ct_float(123456.0)
errcode = py_mult( 2.0, 3.0, ctypes.byref(output_value) ) errcode = py_mult( 2.0, 3.0, ctypes.byref(output_value) )
if errcode != 0:
raise RuntimeError('unexpected error') self.assertEqual(errcode, 0, msg='unexpected error')
assert output_value.value == 6.0
self.assertEqual(output_value.value, 6.0)
if __name__=='__main__': if __name__=='__main__':
test_jit_ctypes() unittest.main()

View file

@ -5,29 +5,44 @@ from llvm import *
from llvm.core import * from llvm.core import *
from llvm.ee import * # new import: ee = Execution Engine from llvm.ee import * # new import: ee = Execution Engine
# Create a module, as in the previous example. import logging
my_module = Module.new('my_module') import unittest
ty_int = Type.int() # by default 32 bits
ty_func = Type.function(ty_int, [ty_int, ty_int])
f_sum = my_module.add_function(ty_func, "sum")
f_sum.args[0].name = "a"
f_sum.args[1].name = "b"
bb = f_sum.append_basic_block("entry")
builder = Builder.new(bb)
tmp = builder.add(f_sum.args[0], f_sum.args[1], "tmp")
builder.ret(tmp)
# Create an execution engine object. This will create a JIT compiler
# on platforms that support it, or an interpreter otherwise.
ee = ExecutionEngine.new(my_module)
# The arguments needs to be passed as "GenericValue" objects. class TestExampleJIT(unittest.TestCase):
arg1 = GenericValue.int(ty_int, 100) def test_example_jit(self):
arg2 = GenericValue.int(ty_int, 42) # Create a module, as in the previous example.
my_module = Module.new('my_module')
ty_int = Type.int() # by default 32 bits
ty_func = Type.function(ty_int, [ty_int, ty_int])
f_sum = my_module.add_function(ty_func, "sum")
f_sum.args[0].name = "a"
f_sum.args[1].name = "b"
bb = f_sum.append_basic_block("entry")
builder = Builder.new(bb)
tmp = builder.add(f_sum.args[0], f_sum.args[1], "tmp")
builder.ret(tmp)
# Now let's compile and run! # Create an execution engine object. This will create a JIT compiler
retval = ee.run_function(f_sum, [arg1, arg2]) # on platforms that support it, or an interpreter otherwise.
ee = ExecutionEngine.new(my_module)
# The return value is also GenericValue. Let's print it. # The arguments needs to be passed as "GenericValue" objects.
print("returned", retval.as_int()) arg1_value = 100
arg2_value = 42
arg1 = GenericValue.int(ty_int, arg1_value)
arg2 = GenericValue.int(ty_int, arg2_value)
# Now let's compile and run!
retval = ee.run_function(f_sum, [arg1, arg2])
# The return value is also GenericValue. Let's print it.
logging.debug("returned %d", retval.as_int())
self.assertEqual(retval.as_int(), (arg1_value + arg2_value))
if __name__ == '__main__':
unittest.main()

View file

@ -4,42 +4,58 @@
from llvm import * from llvm import *
from llvm.core import * from llvm.core import *
# Create an (empty) module. import logging
my_module = Module.new('my_module') import unittest
# All the types involved here are "int"s. This type is represented
# by an object of the llvm.core.Type class:
ty_int = Type.int() # by default 32 bits
# We need to represent the class of functions that accept two integers class TestExample(unittest.TestCase):
# and return an integer. This is represented by an object of the def test_example(self):
# function type (llvm.core.FunctionType): # Create an (empty) module.
ty_func = Type.function(ty_int, [ty_int, ty_int]) my_module = Module.new('my_module')
# Now we need a function named 'sum' of this type. Functions are not # All the types involved here are "int"s. This type is represented
# free-standing (in llvm-py); it needs to be contained in a module. # by an object of the llvm.core.Type class:
f_sum = my_module.add_function(ty_func, "sum") ty_int = Type.int() # by default 32 bits
# Let's name the function arguments as 'a' and 'b'. # We need to represent the class of functions that accept two integers
f_sum.args[0].name = "a" # and return an integer. This is represented by an object of the
f_sum.args[1].name = "b" # function type (llvm.core.FunctionType):
ty_func = Type.function(ty_int, [ty_int, ty_int])
# Our function needs a "basic block" -- a set of instructions that # Now we need a function named 'sum' of this type. Functions are not
# end with a terminator (like return, branch etc.). By convention # free-standing (in llvm-py); it needs to be contained in a module.
# the first block is called "entry". f_sum = my_module.add_function(ty_func, "sum")
bb = f_sum.append_basic_block("entry")
# Let's add instructions into the block. For this, we need an self.assertEqual(str(f_sum).strip(), 'declare i32 @sum(i32, i32)')
# instruction builder:
builder = Builder.new(bb)
# OK, now for the instructions themselves. We'll create an add # Let's name the function arguments as 'a' and 'b'.
# instruction that returns the sum as a value, which we'll use f_sum.args[0].name = "a"
# a ret instruction to return. f_sum.args[1].name = "b"
tmp = builder.add(f_sum.args[0], f_sum.args[1], "tmp")
builder.ret(tmp)
# We've completed the definition now! Let's see the LLVM assembly # Our function needs a "basic block" -- a set of instructions that
# language representation of what we've created: # end with a terminator (like return, branch etc.). By convention
print(my_module) # the first block is called "entry".
bb = f_sum.append_basic_block("entry")
# Let's add instructions into the block. For this, we need an
# instruction builder:
builder = Builder.new(bb)
# OK, now for the instructions themselves. We'll create an add
# instruction that returns the sum as a value, which we'll use
# a ret instruction to return.
tmp = builder.add(f_sum.args[0], f_sum.args[1], "tmp")
self.assertEqual(str(tmp).strip(), '%tmp = add i32 %a, %b')
builder.ret(tmp)
# We've completed the definition now! Let's see the LLVM assembly
# language representation of what we've created:
logging.debug(my_module)
if __name__ == '__main__':
unittest.main()

View file

@ -5,75 +5,106 @@
from llvm.core import * from llvm.core import *
from llvm.ee import * from llvm.ee import *
# setup a function and a builder import logging
mod = Module.new('test') import unittest
functy = Type.function(Type.void(), []) import math
func = mod.add_function(functy, "showme")
block = func.append_basic_block("entry")
b = Builder.new(block)
# let's do bswap on a 32-bit integer using llvm.bswap class TestIntrinsic(unittest.TestCase):
val = Constant.int(Type.int(), 42) def test_bswap(self):
bswap = Function.intrinsic(mod, INTR_BSWAP, [Type.int()]) # setup a function and a builder
b.call(bswap, [val]) mod = Module.new('test')
print(mod) functy = Type.function(Type.int(), [])
func = mod.add_function(functy, "showme")
block = func.append_basic_block("entry")
b = Builder.new(block)
# the output is: # let's do bswap on a 32-bit integer using llvm.bswap
# val = Constant.int(Type.int(), 0x42)
# ; ModuleID = 'test' bswap = Function.intrinsic(mod, INTR_BSWAP, [Type.int()])
#
# define void @showme() {
# entry:
# call i32 @llvm.bswap.i32( i32 42 ) ; <i32>:0 [#uses=0]
# }
#
# declare i32 @llvm.bswap.i32(i32) nounwind readnone
#
# mysin(x) = sqrt(1.0 - pow(cos(x), 2)) bswap_res = b.call(bswap, [val])
b.ret(bswap_res)
float = Type.float() # see the generated IR
mysinty = Type.function( float, [float] ) logging.debug(mod)
mysin = mod.add_function(mysinty, "mysin")
block = mysin.append_basic_block("entry")
b = Builder.new(block)
sqrt = Function.intrinsic(mod, INTR_SQRT, [float]) # the output is:
pow = Function.intrinsic(mod, INTR_POWI, [float]) #
cos = Function.intrinsic(mod, INTR_COS, [float]) # ; ModuleID = 'test'
#
# define void @showme() {
# entry:
# %0 = call i32 @llvm.bswap.i32(i32 42)
# ret i32 %0
# }
mysin.args[0].name = "x" # let's run the function
x = mysin.args[0] ee = ExecutionEngine.new(mod)
one = Constant.real(float, "1") retval = ee.run_function(func, [])
cosx = b.call(cos, [x], "cosx") self.assertEqual(retval.as_int(), 0x42000000)
cos2 = b.call(pow, [cosx, Constant.int(Type.int(), 2)], "cos2")
onemc2 = b.sub(one, cos2, "onemc2")
sin = b.call(sqrt, [onemc2], "sin") def test_mysin(self):
b.ret(sin) # mysin(x) = sqrt(1.0 - pow(cos(x), 2))
print(mod) mod = Module.new('test')
float = Type.float()
mysinty = Type.function( float, [float] )
mysin = mod.add_function(mysinty, "mysin")
block = mysin.append_basic_block("entry")
b = Builder.new(block)
sqrt = Function.intrinsic(mod, INTR_SQRT, [float])
pow = Function.intrinsic(mod, INTR_POWI, [float])
cos = Function.intrinsic(mod, INTR_COS, [float])
mysin.args[0].name = "x"
x = mysin.args[0]
one = Constant.real(float, "1")
cosx = b.call(cos, [x], "cosx")
cos2 = b.call(pow, [cosx, Constant.int(Type.int(), 2)], "cos2")
onemc2 = b.fsub(one, cos2, "onemc2") # Should use fsub
sin = b.call(sqrt, [onemc2], "sin")
b.ret(sin)
logging.debug(mod)
#
# ; ModuleID = 'test'
#
# define void @showme() {
# entry:
# call i32 @llvm.bswap.i32( i32 42 ) ; <i32>:0 [#uses=0]
# }
#
# declare i32 @llvm.bswap.i32(i32) nounwind readnone
#
# define float @mysin(float %x) {
# entry:
# %cosx = call float @llvm.cos.f32( float %x ) ; <float> [#uses=1]
# %cos2 = call float @llvm.powi.f32( float %cosx, i32 2 ) ; <float> [#uses=1]
# %onemc2 = sub float 1.000000e+00, %cos2 ; <float> [#uses=1]
# %sin = call float @llvm.sqrt.f32( float %onemc2 ) ; <float> [#uses=1]
# ret float %sin
# }
#
# declare float @llvm.sqrt.f32(float) nounwind readnone
#
# declare float @llvm.powi.f32(float, i32) nounwind readnone
#
# declare float @llvm.cos.f32(float) nounwind readnone
#
# let's run the function
ee = ExecutionEngine.new(mod)
arg = GenericValue.real(Type.float(), 1.234)
retval = ee.run_function(mysin, [arg])
golden = math.sin(1.234)
answer = retval.as_real(Type.float())
self.assertLess(abs(answer-golden)/golden, 1e-5)
if __name__ == '__main__':
unittest.main()
#
# ; ModuleID = 'test'
#
# define void @showme() {
# entry:
# call i32 @llvm.bswap.i32( i32 42 ) ; <i32>:0 [#uses=0]
# }
#
# declare i32 @llvm.bswap.i32(i32) nounwind readnone
#
# define float @mysin(float %x) {
# entry:
# %cosx = call float @llvm.cos.f32( float %x ) ; <float> [#uses=1]
# %cos2 = call float @llvm.powi.f32( float %cosx, i32 2 ) ; <float> [#uses=1]
# %onemc2 = sub float 1.000000e+00, %cos2 ; <float> [#uses=1]
# %sin = call float @llvm.sqrt.f32( float %onemc2 ) ; <float> [#uses=1]
# ret float %sin
# }
#
# declare float @llvm.sqrt.f32(float) nounwind readnone
#
# declare float @llvm.powi.f32(float, i32) nounwind readnone
#
# declare float @llvm.cos.f32(float) nounwind readnone
#

View file

@ -1,21 +1,27 @@
#!/usr/bin/env python #!/usr/bin/env python
from llvm.core import * from llvm.core import *
import llvm._core
m = Module.new('a') import unittest
ti = Type.int()
tf = Type.function(ti, [ti, ti])
f = m.add_function(tf, "func1") class TestIssue10(unittest.TestCase):
def test_issue10(self):
m = Module.new('a')
ti = Type.int()
tf = Type.function(ti, [ti, ti])
bb = f.append_basic_block('entry') f = m.add_function(tf, "func1")
b = Builder.new(bb) bb = f.append_basic_block('entry')
# There are no instructions in bb. Positioning of the b = Builder.new(bb)
# builder at beginning (or end) should succeed (trivially).
b.position_at_end(bb) # There are no instructions in bb. Positioning of the
b.position_at_beginning(bb) # builder at beginning (or end) should succeed (trivially).
b.position_at_end(bb)
b.position_at_beginning(bb)
if __name__ == '__main__':
unittest.main()