Merge branch 'master' of github.com:llvmpy/llvmpy

This commit is contained in:
Maggie Mari 2012-08-19 12:15:53 -05:00
commit 96406b2737
32 changed files with 386 additions and 2107 deletions

1
.gitignore vendored
View file

@ -2,3 +2,4 @@
build
_build
*.pyc
/llvm/_intrinsic_ids.py

View file

@ -43,6 +43,11 @@
#include "llvm-c/ExecutionEngine.h"
#include "llvm-c/Target.h"
#include "llvm-c/Transforms/IPO.h"
#if LLVM_VERSION_MAJOR >= 3 && LLVM_VERSION_MINOR >= 2
#include "llvm-c/Linker.h"
#else
typedef unsigned int LLVMLinkerMode;
#endif
/* libc includes */
#include <stdarg.h> /* for malloc(), free() */
@ -225,7 +230,7 @@ _wLLVMLinkModules(PyObject *self, PyObject *args)
dest = (LLVMModuleRef) PyCapsule_GetPointer(dest_obj, NULL);
src = (LLVMModuleRef) PyCapsule_GetPointer(src_obj, NULL);
if (!LLVMLinkModules(dest, src, mode, &errmsg)) {
if (!LLVMLinkModules(dest, src, (LLVMLinkerMode)mode, &errmsg)) {
if (errmsg) {
ret = PyUnicode_FromString(errmsg);
LLVMDisposeMessage(errmsg);
@ -897,11 +902,17 @@ _wrap_none2none(LLVMInitializePasses)
_wrap_none2obj(LLVMInitializeNativeTarget, int)
_wrap_none2obj(LLVMInitializeNativeTargetAsmPrinter, int)
#if LLVM_HAS_NVPTX
_wrap_none2none(LLVMInitializeNVPTXTarget)
_wrap_none2none(LLVMInitializeNVPTXTargetInfo)
_wrap_none2none( LLVMInitializeNVPTXTargetMC )
_wrap_none2none(LLVMInitializeNVPTXAsmPrinter)
#else
_wrap_none2none(LLVMInitializePTXTarget)
_wrap_none2none(LLVMInitializePTXTargetInfo)
_wrap_none2none( LLVMInitializePTXTargetMC )
_wrap_none2none(LLVMInitializePTXAsmPrinter)
#endif
/*===----------------------------------------------------------------------===*/
/* Passes */
@ -1002,6 +1013,8 @@ _wrap_pass( Internalize2 )
/* Target Machine */
/*===----------------------------------------------------------------------===*/
_wrap_none2str(LLVMGetHostCPUName);
_wrap_obj2obj(LLVMTargetMachineFromEngineBuilder, LLVMEngineBuilderRef,
LLVMTargetMachineRef)
_wrap_obj2none(LLVMDisposeTargetMachine, LLVMTargetMachineRef)
@ -1122,6 +1135,8 @@ _wrap_obj2none(LLVMDisposeEngineBuilder, LLVMEngineBuilderRef)
_wrap_obj2none(LLVMEngineBuilderForceJIT, LLVMEngineBuilderRef)
_wrap_obj2none(LLVMEngineBuilderForceInterpreter, LLVMEngineBuilderRef)
_wrap_objint2none(LLVMEngineBuilderSetOptLevel, LLVMEngineBuilderRef)
_wrap_objstr2none(LLVMEngineBuilderSetMCPU, LLVMEngineBuilderRef)
_wrap_objstr2none(LLVMEngineBuilderSetMAttrs, LLVMEngineBuilderRef)
static PyObject *
_wLLVMEngineBuilderCreate(PyObject *self, PyObject *args)
@ -1822,11 +1837,17 @@ static PyMethodDef core_methods[] = {
_method( LLVMInitializeNativeTarget )
_method( LLVMInitializeNativeTargetAsmPrinter )
#if LLVM_HAS_NVPTX
_method( LLVMInitializeNVPTXTarget )
_method( LLVMInitializeNVPTXTargetInfo )
_method( LLVMInitializeNVPTXTargetMC )
_method( LLVMInitializeNVPTXAsmPrinter )
#else
_method( LLVMInitializePTXTarget )
_method( LLVMInitializePTXTargetInfo )
_method( LLVMInitializePTXTargetMC )
_method( LLVMInitializePTXAsmPrinter )
#endif
/* Passes */
/*
@ -1927,7 +1948,9 @@ static PyMethodDef core_methods[] = {
_method( LLVMTargetMachineGetTriple )
_method( LLVMTargetMachineGetCPU )
_method( LLVMTargetMachineGetFS )
_method( LLVMPrintRegisteredTargetsForVersion )
_method( LLVMGetHostCPUName )
/* Target Data */
_method( LLVMCreateTargetData )
@ -1954,6 +1977,8 @@ static PyMethodDef core_methods[] = {
_method( LLVMEngineBuilderForceJIT )
_method( LLVMEngineBuilderForceInterpreter )
_method( LLVMEngineBuilderSetOptLevel )
_method( LLVMEngineBuilderSetMCPU )
_method( LLVMEngineBuilderSetMAttrs )
_method( LLVMEngineBuilderCreate )
/* Execution Engine */

File diff suppressed because it is too large Load diff

134
llvm/capsulethunk.h Normal file
View file

@ -0,0 +1,134 @@
#ifndef __CAPSULETHUNK_H
#define __CAPSULETHUNK_H
#if ( (PY_VERSION_HEX < 0x02070000) \
|| ((PY_VERSION_HEX >= 0x03000000) \
&& (PY_VERSION_HEX < 0x03010000)) )
#define __PyCapsule_GetField(capsule, field, default_value) \
( PyCapsule_CheckExact(capsule) \
? (((PyCObject *)capsule)->field) \
: (default_value) \
) \
#define __PyCapsule_SetField(capsule, field, value) \
( PyCapsule_CheckExact(capsule) \
? (((PyCObject *)capsule)->field = value), 1 \
: 0 \
) \
#define PyCapsule_Type PyCObject_Type
#define PyCapsule_CheckExact(capsule) (PyCObject_Check(capsule))
#define PyCapsule_IsValid(capsule, name) (PyCObject_Check(capsule))
#define PyCapsule_New(pointer, name, destructor) \
(PyCObject_FromVoidPtr(pointer, destructor))
#define PyCapsule_GetPointer(capsule, name) \
(PyCObject_AsVoidPtr(capsule))
/* Don't call PyCObject_SetPointer here, it fails if there's a destructor */
#define PyCapsule_SetPointer(capsule, pointer) \
__PyCapsule_SetField(capsule, cobject, pointer)
#define PyCapsule_GetDestructor(capsule) \
__PyCapsule_GetField(capsule, destructor)
#define PyCapsule_SetDestructor(capsule, dtor) \
__PyCapsule_SetField(capsule, destructor, dtor)
/*
* Sorry, there's simply no place
* to store a Capsule "name" in a CObject.
*/
#define PyCapsule_GetName(capsule) NULL
static int
PyCapsule_SetName(PyObject *capsule, const char *unused)
{
unused = unused;
PyErr_SetString(PyExc_NotImplementedError,
"can't use PyCapsule_SetName with CObjects");
return 1;
}
#define PyCapsule_GetContext(capsule) \
__PyCapsule_GetField(capsule, descr)
#define PyCapsule_SetContext(capsule, context) \
__PyCapsule_SetField(capsule, descr, context)
static void *
PyCapsule_Import(const char *name, int no_block)
{
PyObject *object = NULL;
void *return_value = NULL;
char *trace;
size_t name_length = (strlen(name) + 1) * sizeof(char);
char *name_dup = (char *)PyMem_MALLOC(name_length);
if (!name_dup) {
return NULL;
}
memcpy(name_dup, name, name_length);
trace = name_dup;
while (trace) {
char *dot = strchr(trace, '.');
if (dot) {
*dot++ = '\0';
}
if (object == NULL) {
if (no_block) {
object = PyImport_ImportModuleNoBlock(trace);
} else {
object = PyImport_ImportModule(trace);
if (!object) {
PyErr_Format(PyExc_ImportError,
"PyCapsule_Import could not "
"import module \"%s\"", trace);
}
}
} else {
PyObject *object2 = PyObject_GetAttrString(object, trace);
Py_DECREF(object);
object = object2;
}
if (!object) {
goto EXIT;
}
trace = dot;
}
if (PyCObject_Check(object)) {
PyCObject *cobject = (PyCObject *)object;
return_value = cobject->cobject;
} else {
PyErr_Format(PyExc_AttributeError,
"PyCapsule_Import \"%s\" is not valid",
name);
}
EXIT:
Py_XDECREF(object);
if (name_dup) {
PyMem_FREE(name_dup);
}
return return_value;
}
#endif /* #if PY_VERSION_HEX < 0x02070000 */
#endif /* __CAPSULETHUNK_H */

View file

@ -2155,8 +2155,19 @@ if _core.LLVMInitializeNativeTargetAsmPrinter():
# should user trigger the initialization?
raise llvm.LLVMException("No native asm printer!?")
if True: # use PTX
_core.LLVMInitializePTXTarget()
_core.LLVMInitializePTXTargetInfo()
_core.LLVMInitializePTXTargetMC()
_core.LLVMInitializePTXAsmPrinter()
HAS_PTX = HAS_NVPTX = False
if True: # use PTX?
try:
_core.LLVMInitializePTXTarget()
_core.LLVMInitializePTXTargetInfo()
_core.LLVMInitializePTXTargetMC()
_core.LLVMInitializePTXAsmPrinter()
HAS_PTX = True
except AttributeError:
_core.LLVMInitializeNVPTXTarget()
_core.LLVMInitializeNVPTXTargetInfo()
_core.LLVMInitializeNVPTXTargetMC()
_core.LLVMInitializeNVPTXAsmPrinter()
HAS_NVPTX = True

View file

@ -225,6 +225,14 @@ class EngineBuilder(object):
_core.LLVMEngineBuilderSetOptLevel(self.ptr, level)
return self
def mattrs(self, string):
'''set machine attributes as a comma/space separated string
e.g: +sse,-3dnow
'''
_core.LLVMEngineBuilderSetMAttrs(self.ptr, string.replace(',', ' '))
return self
def create(self):
ret = _core.LLVMEngineBuilderCreate(self.ptr)
if isinstance(ret, str):
@ -310,6 +318,11 @@ def print_registered_targets():
'''
_core.LLVMPrintRegisteredTargetsForVersion()
def get_host_cpu_name():
'''return the string name of the host CPU
'''
return _core.LLVMGetHostCPUName()
class TargetMachine(object):
@staticmethod

View file

@ -56,6 +56,7 @@
#include "llvm/Target/TargetData.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/Host.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Analysis/Verifier.h"
@ -126,6 +127,19 @@ const CodeGenOpt::Level OptLevelMap[] = {
} // end anony namespace
const char * LLVMGetHostCPUName()
{
return strdup(llvm::sys::getHostCPUName().c_str());
}
const char * LLVMGetHostCPUFeatures()
{
// placeholder
// TODO not implemented even in LLVM3.2svn
// llvm::sys::getHostCPUFeatures
return NULL;
}
int LLVMInitializeNativeTargetAsmPrinter()
{
return llvm::InitializeNativeTargetAsmPrinter();
@ -442,8 +456,7 @@ LLVMValueRef LLVMBuildAtomicCmpXchg(LLVMBuilderRef builder, LLVMValueRef ptr,
LLVMEngineBuilderRef LLVMCreateEngineBuilder(LLVMModuleRef mod)
{
using namespace llvm;
return wrap(new EngineBuilder(unwrap(mod)));
return llvm::wrap(new EngineBuilder(unwrap(mod)));
}
void LLVMDisposeEngineBuilder(LLVMEngineBuilderRef eb)
@ -468,6 +481,21 @@ void LLVMEngineBuilderSetOptLevel(LLVMEngineBuilderRef eb, int level)
unwrap(eb)->setOptLevel(OptLevelMap[level]);
}
void LLVMEngineBuilderSetMCPU(LLVMEngineBuilderRef eb, const char * mcpu)
{ // TODO add test when llvm3.2 releases
unwrap(eb)->setMCPU(mcpu); // does not work in llvm3.1
}
void LLVMEngineBuilderSetMAttrs(LLVMEngineBuilderRef eb, const char * mattrs)
{ // TODO add test when llvm3.2 releases
std::vector<std::string> tokenized;
std::istringstream iss(mattrs);
std::string buf;
while ( iss >> buf ){
tokenized.push_back(buf);
}
unwrap(eb)->setMAttrs(tokenized); // does not work in llvm3.1
}
LLVMExecutionEngineRef LLVMEngineBuilderCreate(LLVMEngineBuilderRef eb, std::string & error)
{
@ -893,6 +921,7 @@ LLVMModuleRef LLVMGetModuleFromBitcode(const char *bitcode, unsigned bclen,
return wrap(modulep);
}
#if LLVM_VERSION_MAJOR <= 3 && LLVM_VERSION_MINOR < 2
unsigned LLVMLinkModules(LLVMModuleRef dest, LLVMModuleRef src, unsigned int mode,
char **out)
{
@ -909,6 +938,7 @@ unsigned LLVMLinkModules(LLVMModuleRef dest, LLVMModuleRef src, unsigned int mod
return 1;
}
#endif
unsigned char *LLVMGetBitcodeFromModule(LLVMModuleRef module, unsigned *lenp)
{

View file

@ -37,14 +37,26 @@
#ifndef LLVM_PY_EXTRA_H
#define LLVM_PY_EXTRA_H
// select PTX or NVPTX
#if LLVM_VERSION_MAJOR >= 3 && LLVM_VERSION_MINOR >= 2
#define LLVM_HAS_NVPTX 1
#else
#define LLVM_HAS_NVPTX 0
#endif
#include "llvm-c/Transforms/PassManagerBuilder.h"
#include "llvm_c_extra.h"
#ifdef __cplusplus
extern "C" {
#endif
const char * LLVMGetHostCPUName();
int LLVMInitializeNativeTargetAsmPrinter();
@ -172,6 +184,16 @@ void LLVMEngineBuilderForceInterpreter(LLVMEngineBuilderRef eb);
*/
void LLVMEngineBuilderSetOptLevel(LLVMEngineBuilderRef eb, int level);
/*
* Wraps EngineBuilder::setMCPU
*/
void LLVMEngineBuilderSetMCPU(LLVMEngineBuilderRef eb, const char * mcpu);
/*
* Wraps EngineBuilder::setMAttrs
*/
void LLVMEngineBuilderSetMAttrs(LLVMEngineBuilderRef eb, const char * mattrs);
/*
* Wraps EngineBuilder::setErrorStr and EngineBuilder::create
*/
@ -381,12 +403,13 @@ LLVMModuleRef LLVMGetModuleFromAssembly(const char *asmtxt, char **out);
LLVMModuleRef LLVMGetModuleFromBitcode(const char *bc, unsigned bclen,
char **out);
#if LLVM_VERSION_MAJOR <= 3 && LLVM_VERSION_MINOR < 2
/* Wraps llvm::Linker::LinkModules(). Returns 0 on failure (with errmsg
* filled in) and 1 on success. Dispose error message after use with
* LLVMDisposeMessage(). */
unsigned LLVMLinkModules(LLVMModuleRef dest, LLVMModuleRef src,
unsigned int, char **errmsg);
#endif
/* Returns pointer to a heap-allocated block of `*len' bytes containing bit code
* for the given module. NULL on error. */
unsigned char *LLVMGetBitcodeFromModule(LLVMModuleRef module, unsigned *len);

View file

@ -43,7 +43,7 @@
//// For pre-2.7 compatbility, use the following include, which provides
//// alias for PyCapsule.
//// See http://docs.python.org/py3k/howto/cporting.html
// #include <capsulethunk.h> // pre-2.7 compatibility for PyCapsule
#include "capsulethunk.h" // pre-2.7 compatibility for PyCapsule
/* llvm includes */

203
setup.py Executable file → Normal file
View file

@ -1,145 +1,114 @@
#!/usr/bin/env python
#
# Copyright (c) 2008-10, Mahadevan R All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of this software, nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import sys, os
import sys
import os
import re
from distutils.core import setup, Extension
LLVM_PY_VERSION = '0.8.2'
llvm_config = os.environ.get('LLVM_CONFIG_PATH', 'llvm-config')
# set LLVMPY_DYNLINK=1, if you want to link _core.so dynamically to libLLVM.so
dynlink = int(os.environ.get('LLVMPY_DYNLINK', 0))
def _run(cmd):
def run_llvm_config(args):
cmd = llvm_config + ' ' + ' '.join(args)
return os.popen(cmd).read().rstrip()
if run_llvm_config(['--version']) == '':
print("Cannot invoke llvm-config.")
print("Try setting LLVM_CONFIG_PATH=/path/to/llvm-config")
sys.exit(1)
def get_libs_and_objs(llvm_config, components):
parts = _run(llvm_config + ' --libs ' + ' '.join(components)).split()
def get_libs_and_objs(components):
parts = run_llvm_config(['--libs'] + components).split()
libs = []
objs = []
for part in parts:
if part.startswith('-l'):
libs.append(part[2:])
elif part.endswith('.o'):
# objs.append(part[:-2])
objs.append(part) # eh, looks like we need the .o after all
return (libs, objs)
objs.append(part)
return libs, objs
def get_llvm_config():
# get from command-line, or use default
lc = 'llvm-config'
i = 0
while i < len(sys.argv):
arg = sys.argv[i]
if arg.startswith('--llvm-config='):
del sys.argv[i]
lc = arg.split('=')[1]
else:
i += 1
# see if it works
version = _run(lc + ' --version')
if version == '':
return (lc, False) # didn't work
return (lc, True)
def get_llvm_version():
# get version number; treat it as fixed point
pat = re.compile(r'(\d+)\.(\d+)')
m = pat.search(run_llvm_config([' --version']))
if m is None:
sys.exit('could not determine llvm version')
return tuple(map(int, m.groups()))
def call_setup(llvm_config):
def auto_intrinsic_gen(incdir):
# let's do auto intrinsic generation
print("Generate intrinsic IDs")
from tools import intrgen
path = "%s/llvm/Intrinsics.gen" % incdir
with open('llvm/_intrinsic_ids.py', 'w') as fout:
intrgen.gen(path, fout)
incdir = _run(llvm_config + ' --includedir')
libdir = _run(llvm_config + ' --libdir')
ldflags = _run(llvm_config + ' --ldflags')
ptx_components = ['ptx', 'ptxasmprinter', 'ptxcodegen', 'ptxdesc', 'ptxinfo']
incdir = run_llvm_config(['--includedir'])
libdir = run_llvm_config(['--libdir'])
libs_core, objs_core = get_libs_and_objs(llvm_config,
llvm_version = get_llvm_version()
print('LLVM version = %d.%d' % llvm_version)
auto_intrinsic_gen(incdir)
if dynlink:
libs_core = ['LLVM-%d.%d' % llvm_version]
objs_core = []
else:
if llvm_version <= (3, 1): # select between PTX & NVPTX
print('Using PTX')
ptx_components = ['ptx',
'ptxasmprinter',
'ptxcodegen',
'ptxdesc',
'ptxinfo']
else:
print('Using NVPTX')
ptx_components = ['nvptx',
'nvptxasmprinter',
'nvptxcodegen',
'nvptxdesc',
'nvptxinfo']
libs_core, objs_core = get_libs_and_objs(
['core', 'analysis', 'scalaropts', 'executionengine',
'jit', 'native', 'interpreter', 'bitreader', 'bitwriter',
'instrumentation', 'ipa', 'ipo', 'transformutils',
'asmparser', 'linker', 'support', 'vectorize']
+ ptx_components)
+ ptx_components)
std_libs = [ 'pthread', 'm', 'stdc++' ]
extra_link_args = ["-fPIC"]
if not ("openbsd" in sys.platform or "freebsd" in sys.platform):
std_libs.append("dl")
if "darwin" in sys.platform:
std_libs.append("ffi")
extra_link_args += ['-framework', 'Python']
std_libs = ['pthread', 'm', 'stdc++', 'dl']
extra_link_args = ["-fPIC"]
if sys.platform == 'darwin':
std_libs.append("ffi")
ext_core = Extension(
name='llvm._core',
sources=['llvm/_core.cpp', 'llvm/wrap.cpp', 'llvm/extra.cpp'],
define_macros = [('__STDC_CONSTANT_MACROS', None),
('__STDC_LIMIT_MACROS', None),
('_GNU_SOURCE', None)],
include_dirs = ['/usr/include', incdir],
library_dirs = [libdir],
libraries = std_libs + libs_core,
extra_objects = objs_core,
extra_link_args = extra_link_args,
)
ext_core = Extension(
'llvm._core',
['llvm/_core.cpp', 'llvm/wrap.cpp', 'llvm/extra.cpp'],
define_macros = [
('__STDC_CONSTANT_MACROS', None),
('__STDC_LIMIT_MACROS', None),
('_GNU_SOURCE', None)],
include_dirs = ['/usr/include', incdir],
library_dirs = [libdir],
libraries = std_libs + libs_core,
extra_objects = objs_core,
extra_link_args = extra_link_args)
setup(
name='llvm-py',
version=LLVM_PY_VERSION,
description='Python Bindings for LLVM',
author='Mahadevan R',
author_email='mdevan@mdevan.org',
url='http://www.mdevan.org/llvm-py/',
packages=['llvm'],
py_modules = [ 'llvm.core' ],
ext_modules = [ ext_core ],)
def main():
# get llvm config
llvm_config, is_good = get_llvm_config()
if is_good:
print("Using llvm-config=" + llvm_config)
else:
print("Cannot invoke llvm-config (tried '%s')." % llvm_config)
print("Try again with --llvm-config=/path/to/llvm-config.")
return 1
# setup
call_setup(llvm_config)
# done
return 0
ev = main()
sys.exit(ev)
setup(
name = 'llvm-py',
version = LLVM_PY_VERSION,
description = 'Python bindings for LLVM',
author = 'Mahadevan R',
author_email = 'mdevan@mdevan.org',
url = 'http://www.llvmpy.org/',
packages = ['llvm'],
py_modules = ['llvm.core'],
ext_modules = [ ext_core ],
)

0
test/JITTutorial1.py Executable file → Normal file
View file

0
test/JITTutorial2.py Executable file → Normal file
View file

0
test/asm.py Executable file → Normal file
View file

View file

@ -88,21 +88,19 @@ class TestAtomic(unittest.TestCase):
for ordering in test_these_orderings:
loaded = bldr.atomic_load(ptr, ordering)
self.assertIn('load atomic', str(loaded))
self.assert_('load atomic' in str(loaded))
self.assertEqual(ordering,
str(loaded).strip().split(' ')[-3].rstrip(','))
self.assertIn('align 1', str(loaded))
self.assert_('align 1' in str(loaded))
stored = bldr.atomic_store(loaded, ptr, ordering)
self.assertIn('store atomic', str(stored))
self.assert_('store atomic' in str(stored))
self.assertEqual(ordering,
str(stored).strip().split(' ')[-3].rstrip(','))
self.assertIn('align 1', str(stored))
self.assert_('align 1' in str(stored))
fenced = bldr.fence(ordering)
self.assertEqual(['fence', ordering], str(fenced).strip().split(' '))
if __name__ == '__main__':
unittest.main()

0
test/call-jit-ctypes.py Executable file → Normal file
View file

8
test/constants.py Executable file → Normal file
View file

@ -1,14 +1,14 @@
#! /usr/bin/env python
'''
Test and stress Constants.
'''
import unittest
import logging
from llvm.core import *
from llvm.ee import *
from ctypes import *
import unittest, logging
# logging.basicConfig(level=logging.DEBUG)
@ -135,7 +135,7 @@ class TestConstants(unittest.TestCase):
if golden == 0:
self.assertEqual(result, golden)
else:
self.assertLess(abs(result-golden)/golden, 1e-7)
self.assert_(abs(result-golden)/golden < 1e-7)
def test_const_double(self):
from random import random
@ -250,7 +250,7 @@ class TestConstants(unittest.TestCase):
if golden[1] == 0:
self.assertEqual(result[1], golden[1])
else:
self.assertLess(abs(result[1]-golden[1])/golden[1], 1e-7)
self.assert_(abs(result[1]-golden[1])/golden[1] < 1e-7)
self.assertEqual(result[2], golden[2])
def test_const_vector(self):

0
test/example-jit.py Executable file → Normal file
View file

0
test/example.py Executable file → Normal file
View file

2
test/intrinsic.py Executable file → Normal file
View file

@ -102,7 +102,7 @@ class TestIntrinsic(unittest.TestCase):
golden = math.sin(1.234)
answer = retval.as_real(Type.float())
self.assertLess(abs(answer-golden)/golden, 1e-5)
self.assertTrue(abs(answer-golden)/golden < 1e-5)
if __name__ == '__main__':

0
test/issue10.py Executable file → Normal file
View file

0
test/native.py Executable file → Normal file
View file

12
test/objcache.py Executable file → Normal file
View file

@ -2,9 +2,17 @@
from llvm.core import *
import logging, unittest
import logging, sys, unittest
class TestObjCache(unittest.TestCase):
if sys.version_info[:2] < (2, 7):
def assertIs(self, expr1, expr2, msg=None):
if expr1 is not expr2:
standardMsg = '%s is not %s' % (safe_repr(expr1),
safe_repr(expr2))
self.fail(self._formatMessage(msg, standardMsg))
def test_objcache(self):
logging.debug("Testing module aliasing ..")
m1 = Module.new('a')
@ -31,7 +39,7 @@ class TestObjCache(unittest.TestCase):
gv1.delete()
gv4 = GlobalVariable.new(m1, t, "gv")
self.assertIsNot(gv1, gv4)
self.assert_(gv1 is not gv4)
logging.debug("Testing function aliasing 1 ..")
b1 = f1.append_basic_block('entry')

3
test/opaque.py Executable file → Normal file
View file

@ -6,10 +6,11 @@ from llvm import LLVMException
import logging, unittest
class TestOpaque(unittest.TestCase):
def test_opaque(self):
# Create an opaque type
ts = Type.opaque('mystruct')
self.assertIn('type opaque', str(ts))
self.assertTrue('type opaque' in str(ts))
self.assertTrue(ts.is_opaque)
self.assertTrue(ts.is_identified)
self.assertFalse(ts.is_literal)

21
test/operands.py Executable file → Normal file
View file

@ -1,6 +1,9 @@
#!/usr/bin/env python
# Tests accessing of instruction operands.
import sys
import logging
import unittest
from llvm.core import *
try:
@ -8,8 +11,6 @@ try:
except ImportError:
from io import StringIO
import logging, unittest
m = None
#===----------------------------------------------------------------------===
@ -32,6 +33,7 @@ entry:
"""
class TestOperands(unittest.TestCase):
def test_operands(self):
m = Module.from_assembly(StringIO(test_module))
logging.debug("-"*60)
@ -41,7 +43,7 @@ class TestOperands(unittest.TestCase):
test_func = m.get_function_named("test_func")
prod = m.get_function_named("prod")
#===----------------------------------------------------------------------===
#===-----------------------------------------------------------===
# test operands
@ -54,15 +56,15 @@ class TestOperands(unittest.TestCase):
logging.debug("Testing User.operands ..")
self.assertIs(i1.operands[-1], prod)
self.assertIs(i1.operands[0], test_func.args[0])
self.assertIs(i1.operands[1], test_func.args[1])
self.assertIs(i2.operands[0], i1)
self.assertIs(i2.operands[1], test_func.args[2])
self.assert_(i1.operands[-1] is prod)
self.assert_(i1.operands[0] is test_func.args[0])
self.assert_(i1.operands[1] is test_func.args[1])
self.assert_(i2.operands[0] is i1)
self.assert_(i2.operands[1] is test_func.args[2])
self.assertEqual(len(i1.operands), 3)
self.assertEqual(len(i2.operands), 2)
#===----------------------------------------------------------------------===
#===-----------------------------------------------------------===
# show test_function
logging.debug("Examining test_function `test_test_func':")
@ -80,4 +82,3 @@ class TestOperands(unittest.TestCase):
if __name__ == '__main__':
unittest.main()

0
test/passes.py Executable file → Normal file
View file

View file

@ -1,5 +1,5 @@
from llvm.core import *
from llvm.ee import TargetMachine, EngineBuilder, print_registered_targets
from llvm.ee import *
import unittest
class TestTargetMachines(unittest.TestCase):
@ -17,19 +17,25 @@ class TestTargetMachines(unittest.TestCase):
self.assertTrue(tm.target_short_description)
self.assertTrue(tm.triple)
self.assertIn('foo', tm.emit_assembly(m).decode('utf-8'))
self.assertTrue(get_host_cpu_name())
def test_ptx(self):
if HAS_PTX:
arch = 'ptx64'
elif HAS_NVPTX:
arch = 'nvptx64'
else:
return # skip this test
m, func = self._build_module()
func.calling_convention = CC_PTX_KERNEL # set calling conv
ptxtm = TargetMachine.lookup(arch='ptx64', cpu='compute_20',
features='-double')
ptxtm = TargetMachine.lookup(arch=arch, cpu='compute_20')
self.assertTrue(ptxtm.triple)
self.assertTrue(ptxtm.cpu)
self.assertTrue(ptxtm.feature_string)
ptxasm = ptxtm.emit_assembly(m).decode('utf-8')
self.assertIn('foo', ptxasm)
self.assertIn('map_f64_to_f32', ptxasm)
self.assertIn('compute_10', ptxasm)
if HAS_NVPTX:
self.assertIn('.address_size 64', ptxasm)
self.assertIn('compute_20', ptxasm)
def _build_module(self):
m = Module.new('TestTargetMachines')

0
test/test.py Executable file → Normal file
View file

0
test/testall.py Executable file → Normal file
View file

0
test/testattrs.py Executable file → Normal file
View file

6
test/uses.py Executable file → Normal file
View file

@ -30,11 +30,11 @@ class TestUses(unittest.TestCase):
self.assertEqual(tmp3.use_count, 1)
logging.debug("Testing uses ..")
self.assertIs(f.args[0].uses[0], tmp1)
self.assert_(f.args[0].uses[0] is tmp1)
self.assertEqual(len(f.args[0].uses), 1)
self.assertIs(f.args[1].uses[0], tmp2)
self.assert_(f.args[1].uses[0] is tmp2)
self.assertEqual(len(f.args[1].uses), 1)
self.assertIs(f.args[2].uses[0], tmp3)
self.assert_(f.args[2].uses[0] is tmp3)
self.assertEqual(len(f.args[2].uses), 1)
self.assertEqual(len(tmp1.uses), 2)
self.assertEqual(len(tmp2.uses), 0)

0
tools/__init__.py Normal file
View file

View file

@ -6,7 +6,7 @@
import sys
def gen(f):
def gen(f, out=sys.stdout):
intr = []
maxw = 0
flag = False
@ -26,7 +26,8 @@ def gen(f):
idx = 1
for i in intr:
s = 'INTR_' + i.upper()
print('%s = %d' % (s.ljust(maxw), idx))
out.write('%s = %d\n' % (s.ljust(maxw), idx))
idx += 1
gen(sys.argv[1])
if __name__ == '__main__':
gen(sys.argv[1])