Swap out old llvm code
This commit is contained in:
parent
da85049eb9
commit
450c29e052
21 changed files with 20 additions and 14200 deletions
2117
llvm/2.9_update.diff
2117
llvm/2.9_update.diff
File diff suppressed because it is too large
Load diff
154
llvm/__init__.py
154
llvm/__init__.py
|
|
@ -1,154 +0,0 @@
|
|||
"""
|
||||
Common classes related to LLVM.
|
||||
"""
|
||||
|
||||
from ._version import get_versions
|
||||
__version__ = get_versions()['version']
|
||||
del get_versions
|
||||
|
||||
|
||||
from weakref import WeakValueDictionary
|
||||
from . import _core
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# LLVM Version
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
version = _core.LLVMGetVersion()
|
||||
|
||||
def require_version_at_least(major, minor):
|
||||
'''Sentry to guard version requirement
|
||||
'''
|
||||
if version < (major, minor):
|
||||
raise Exception(major, minor)
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Exceptions
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
class LLVMException(Exception):
|
||||
"""Generic LLVM exception."""
|
||||
|
||||
def __init__(self, msg=""):
|
||||
Exception.__init__(self, msg)
|
||||
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Ownables
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
class Ownable(object):
|
||||
"""Objects that can be owned.
|
||||
|
||||
Modules and Module Providers can be owned, i.e., the responsibility of
|
||||
destruction of ownable objects can be handed over to other objects. The
|
||||
llvm.Ownable class represents objects that can be so owned. This class
|
||||
is NOT intended for public use.
|
||||
"""
|
||||
|
||||
def __init__(self, ptr, del_fn):
|
||||
self.ptr = ptr
|
||||
self.owner = None
|
||||
self.del_fn = del_fn
|
||||
|
||||
def _own(self, owner):
|
||||
if self.owner:
|
||||
raise LLVMException("object already owned")
|
||||
self.owner = owner
|
||||
|
||||
def _disown(self):
|
||||
if not self.owner:
|
||||
raise LLVMException("not owned")
|
||||
self.owner = None
|
||||
|
||||
def __del__(self):
|
||||
if not self.owner:
|
||||
self.del_fn(self.ptr)
|
||||
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Dummy owner, will not delete ownee. Be careful.
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
class DummyOwner(object):
|
||||
pass
|
||||
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# A metaclass to prevent aliasing. It stores a (weak) reference to objects
|
||||
# constructed based on a PyCObject. If an object is constructed based on a
|
||||
# PyCObject with the same underlying pointer as a previous object, a reference
|
||||
# to the previous object is returned rather than a new one.
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
class _ObjectCache(type):
|
||||
"""A metaclass to prevent aliasing.
|
||||
|
||||
Classes using 'ObjectCache' as a metaclass must have constructors
|
||||
that take a PyCObject as their first argument. When the class is
|
||||
called (to create a new instance of the class), the value of the
|
||||
pointer wrapped by the PyCObj is checked:
|
||||
|
||||
If no previous object has been created based on the same
|
||||
underlying pointer (note that different PyCObject objects can
|
||||
wrap the same pointer), the object will be initialized as
|
||||
usual and returned.
|
||||
|
||||
If a previous has been created based on the same pointer,
|
||||
then a reference to that object will be returned, and no
|
||||
object initialization is performed.
|
||||
"""
|
||||
|
||||
__instances = WeakValueDictionary()
|
||||
|
||||
def __call__(cls, ptr, *args, **kwargs):
|
||||
objid = _core.PyCObjectVoidPtrToPyLong(ptr)
|
||||
key = "%s:%d" % (cls.__name__, objid)
|
||||
obj = _ObjectCache.__instances.get(key)
|
||||
if obj is None:
|
||||
obj = super(_ObjectCache, cls).__call__(ptr, *args, **kwargs)
|
||||
_ObjectCache.__instances[key] = obj
|
||||
return obj
|
||||
|
||||
@staticmethod
|
||||
def forget(obj):
|
||||
objid = _core.PyCObjectVoidPtrToPyLong(obj.ptr)
|
||||
key = "%s:%d" % (type(obj).__name__, objid)
|
||||
if key in _ObjectCache.__instances:
|
||||
del _ObjectCache.__instances[key]
|
||||
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Cacheables
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
# version 2/3 compatibility help
|
||||
# version 2 metaclass
|
||||
# class Cacheable(object):
|
||||
# __metaclass__ = _ObjectCache # Doing nothing for version 3
|
||||
#
|
||||
# version 3 metaclass
|
||||
# class Cacheable(metaclass=_ObjectCache):
|
||||
#
|
||||
# Reference: http://mikewatkins.ca/2008/11/29/python-2-and-3-metaclasses/#using-the-metaclass-in-python-3-x
|
||||
ObjectCache = _ObjectCache('ObjectCache', (object, ), {})
|
||||
|
||||
class Cacheable(ObjectCache):
|
||||
"""Objects that can be cached.
|
||||
|
||||
Objects that wrap a PyCObject are cached to avoid "aliasing", i.e.,
|
||||
two Python objects each containing a PyCObject which internally points
|
||||
to the same C pointer."""
|
||||
|
||||
def forget(self):
|
||||
ObjectCache.forget(self)
|
||||
|
||||
|
||||
def test(verbosity=1):
|
||||
"""test(verbosity=1) -> TextTestResult
|
||||
|
||||
Run self-test, and return unittest.runner.TextTestResult object.
|
||||
"""
|
||||
from llvm.test_llvmpy import run
|
||||
|
||||
return run(verbosity=verbosity)
|
||||
2212
llvm/_core.cpp
2212
llvm/_core.cpp
File diff suppressed because it is too large
Load diff
|
|
@ -1,86 +0,0 @@
|
|||
#include <Python.h>
|
||||
#include <llvm/Support/Dwarf.h>
|
||||
|
||||
namespace llvmpy {
|
||||
namespace dwarf {
|
||||
|
||||
using namespace llvm::dwarf;
|
||||
|
||||
const char *constant_names[] = {
|
||||
"LLVMDebugVersion",
|
||||
|
||||
#define define(x) #x,
|
||||
#include "_dwarf.h"
|
||||
#undef define
|
||||
};
|
||||
|
||||
int constant_values[] = {
|
||||
llvm::LLVMDebugVersion,
|
||||
|
||||
#define define(x) x,
|
||||
#include "_dwarf.h"
|
||||
#undef define
|
||||
};
|
||||
|
||||
enum enum_values {
|
||||
__llvmpy_LLVMDebugVersion,
|
||||
|
||||
#define define(x) __llvmpy_##x,
|
||||
#include "_dwarf.h"
|
||||
#undef define
|
||||
|
||||
NVALUES /* Get the number of constants */
|
||||
};
|
||||
|
||||
} // End namespace dwarf
|
||||
|
||||
int
|
||||
set_dwarf_constants(PyObject *module)
|
||||
{
|
||||
int i;
|
||||
for (i = 0; i < dwarf::NVALUES; i++) {
|
||||
if (PyModule_AddIntConstant(module, dwarf::constant_names[i],
|
||||
dwarf::constant_values[i]) > 0)
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
} // End namespace llvmpy
|
||||
|
||||
#if (PY_MAJOR_VERSION >= 3)
|
||||
struct PyModuleDef module_def = {
|
||||
PyModuleDef_HEAD_INIT,
|
||||
"_dwarf",
|
||||
NULL,
|
||||
-1,
|
||||
NULL, /* m_methods */
|
||||
NULL, /* m_reload */
|
||||
NULL, /* m_traverse */
|
||||
NULL, /* m_clear */
|
||||
NULL, /* m_free */
|
||||
};
|
||||
|
||||
#define INITERROR return NULL
|
||||
PyObject *PyInit__dwarf(void)
|
||||
#else
|
||||
#define INITERROR return
|
||||
PyMODINIT_FUNC init_dwarf(void)
|
||||
#endif
|
||||
{
|
||||
#if PY_MAJOR_VERSION >= 3
|
||||
PyObject *module = PyModule_Create( &module_def );
|
||||
#else
|
||||
PyObject *module = Py_InitModule("_dwarf", NULL);
|
||||
#endif
|
||||
if (module == NULL)
|
||||
INITERROR;
|
||||
|
||||
if (llvmpy::set_dwarf_constants(module) < 0)
|
||||
INITERROR;
|
||||
|
||||
#if PY_MAJOR_VERSION >= 3
|
||||
return module;
|
||||
#endif
|
||||
}
|
||||
101
llvm/_dwarf.h
101
llvm/_dwarf.h
|
|
@ -1,101 +0,0 @@
|
|||
/* Dwarf constant wrapping. See include/llvm/Support/Dwarf.h */
|
||||
|
||||
define(DWARF_VERSION)
|
||||
|
||||
/* Dwarf tags */
|
||||
define(DW_TAG_array_type)
|
||||
define(DW_TAG_class_type)
|
||||
define(DW_TAG_entry_point)
|
||||
define(DW_TAG_enumeration_type)
|
||||
define(DW_TAG_formal_parameter)
|
||||
define(DW_TAG_imported_declaration)
|
||||
define(DW_TAG_label)
|
||||
define(DW_TAG_lexical_block)
|
||||
define(DW_TAG_member)
|
||||
define(DW_TAG_pointer_type)
|
||||
define(DW_TAG_reference_type)
|
||||
define(DW_TAG_compile_unit)
|
||||
define(DW_TAG_string_type)
|
||||
define(DW_TAG_structure_type)
|
||||
define(DW_TAG_subroutine_type)
|
||||
define(DW_TAG_typedef)
|
||||
define(DW_TAG_union_type)
|
||||
define(DW_TAG_unspecified_parameters)
|
||||
define(DW_TAG_variant)
|
||||
define(DW_TAG_common_block)
|
||||
define(DW_TAG_common_inclusion)
|
||||
define(DW_TAG_inheritance)
|
||||
define(DW_TAG_inlined_subroutine)
|
||||
define(DW_TAG_module)
|
||||
define(DW_TAG_ptr_to_member_type)
|
||||
define(DW_TAG_set_type)
|
||||
define(DW_TAG_subrange_type)
|
||||
define(DW_TAG_with_stmt)
|
||||
define(DW_TAG_access_declaration)
|
||||
define(DW_TAG_base_type)
|
||||
define(DW_TAG_catch_block)
|
||||
define(DW_TAG_const_type)
|
||||
define(DW_TAG_constant)
|
||||
define(DW_TAG_enumerator)
|
||||
define(DW_TAG_file_type)
|
||||
define(DW_TAG_friend)
|
||||
define(DW_TAG_namelist)
|
||||
define(DW_TAG_namelist_item)
|
||||
define(DW_TAG_packed_type)
|
||||
define(DW_TAG_subprogram)
|
||||
define(DW_TAG_template_type_parameter)
|
||||
define(DW_TAG_template_value_parameter)
|
||||
define(DW_TAG_thrown_type)
|
||||
define(DW_TAG_try_block)
|
||||
define(DW_TAG_variant_part)
|
||||
define(DW_TAG_variable)
|
||||
define(DW_TAG_volatile_type)
|
||||
define(DW_TAG_dwarf_procedure)
|
||||
define(DW_TAG_restrict_type)
|
||||
define(DW_TAG_interface_type)
|
||||
define(DW_TAG_namespace)
|
||||
define(DW_TAG_imported_module)
|
||||
define(DW_TAG_unspecified_type)
|
||||
define(DW_TAG_partial_unit)
|
||||
define(DW_TAG_imported_unit)
|
||||
define(DW_TAG_condition)
|
||||
define(DW_TAG_shared_type)
|
||||
define(DW_TAG_type_unit)
|
||||
define(DW_TAG_rvalue_reference_type)
|
||||
define(DW_TAG_template_alias)
|
||||
define(DW_TAG_MIPS_loop)
|
||||
define(DW_TAG_format_label)
|
||||
define(DW_TAG_function_template)
|
||||
define(DW_TAG_class_template)
|
||||
define(DW_TAG_GNU_template_template_param)
|
||||
define(DW_TAG_GNU_template_parameter_pack)
|
||||
define(DW_TAG_GNU_formal_parameter_pack)
|
||||
define(DW_TAG_lo_user)
|
||||
define(DW_TAG_APPLE_property)
|
||||
define(DW_TAG_hi_user)
|
||||
|
||||
/* Dwarf language constants */
|
||||
define(DW_LANG_C89)
|
||||
define(DW_LANG_C)
|
||||
define(DW_LANG_Ada83)
|
||||
define(DW_LANG_C_plus_plus)
|
||||
define(DW_LANG_Cobol74)
|
||||
define(DW_LANG_Cobol85)
|
||||
define(DW_LANG_Fortran77)
|
||||
define(DW_LANG_Fortran90)
|
||||
define(DW_LANG_Pascal83)
|
||||
define(DW_LANG_Modula2)
|
||||
define(DW_LANG_Java)
|
||||
define(DW_LANG_C99)
|
||||
define(DW_LANG_Ada95)
|
||||
define(DW_LANG_Fortran95)
|
||||
define(DW_LANG_PLI)
|
||||
define(DW_LANG_ObjC)
|
||||
define(DW_LANG_ObjC_plus_plus)
|
||||
define(DW_LANG_UPC)
|
||||
define(DW_LANG_D)
|
||||
define(DW_LANG_Python)
|
||||
define(DW_LANG_lo_user)
|
||||
define(DW_LANG_Mips_Assembler)
|
||||
define(DW_LANG_hi_user)
|
||||
|
||||
108
llvm/_util.py
108
llvm/_util.py
|
|
@ -1,108 +0,0 @@
|
|||
#
|
||||
# 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.
|
||||
#
|
||||
|
||||
"""Utility functions and classes.
|
||||
|
||||
Used only in other modules, not for public use."""
|
||||
|
||||
import llvm
|
||||
import llvm._core as _core # for PyCObjectVoidPtrToPyLong
|
||||
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# A set of helpers to check various things. Raises exceptions on
|
||||
# failures.
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
def check_gen(obj, typ):
|
||||
if not isinstance(obj, typ):
|
||||
typ_str = typ.__name__
|
||||
msg = "argument not an instance of llvm.core.%s" % typ_str
|
||||
raise TypeError(msg)
|
||||
|
||||
def check_is_unowned(ownable):
|
||||
if ownable.owner:
|
||||
raise llvm.LLVMException("object is already owned")
|
||||
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# A set of helpers to unpack a list of Python wrapper objects
|
||||
# into a list of PyCObject wrapped objects, checking types along
|
||||
# the way.
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
def unpack_gen(objlist, check_fn):
|
||||
for obj in objlist: check_fn(obj)
|
||||
return [ obj.ptr for obj in objlist ]
|
||||
|
||||
def unpack_gen_allow_none(objlist, check_fn):
|
||||
for obj in objlist:
|
||||
if obj is not None:
|
||||
check_fn(obj)
|
||||
return [ (obj.ptr if obj is not None else None) for obj in objlist ]
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Helper to wrap over iterables (LLVMFirstXXX, LLVMNextXXX). This used
|
||||
# to be a generator, but that loses subscriptability of the result, so
|
||||
# we now return a list.
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
def wrapiter(first, next, container, wrapper):
|
||||
ret = []
|
||||
ptr = first(container)
|
||||
while ptr:
|
||||
ret.append(wrapper(ptr))
|
||||
ptr = next(ptr)
|
||||
return ret
|
||||
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Py2/3 compatibility string check
|
||||
#===----------------------------------------------------------------------===
|
||||
def _isstring_py2(x):
|
||||
return isinstance(x, basestring)
|
||||
|
||||
def _isstring_py3(x):
|
||||
return isinstance(x, str)
|
||||
|
||||
def _isstring_choose():
|
||||
try:
|
||||
basestring
|
||||
return _isstring_py2
|
||||
except:
|
||||
return _isstring_py3
|
||||
|
||||
isstring = _isstring_choose()
|
||||
|
||||
try:
|
||||
unicode_type = unicode
|
||||
except NameError: # Py3
|
||||
unicode_type = str
|
||||
|
||||
193
llvm/_version.py
193
llvm/_version.py
|
|
@ -1,193 +0,0 @@
|
|||
|
||||
IN_LONG_VERSION_PY = True
|
||||
# This file helps to compute a version number in source trees obtained from
|
||||
# git-archive tarball (such as those provided by github's download-from-tag
|
||||
# feature). Distribution tarballs (build by setup.py sdist) and build
|
||||
# directories (produced by setup.py build) will contain a much shorter file
|
||||
# that just contains the computed version number.
|
||||
|
||||
# This file is released into the public domain. Generated by
|
||||
# versioneer-0.7+ (https://github.com/warner/python-versioneer)
|
||||
|
||||
# these strings will be replaced by git during git-archive
|
||||
git_refnames = "$Format:%d$"
|
||||
git_full = "$Format:%H$"
|
||||
GIT = "git"
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
def run_command(args, cwd=None, verbose=False):
|
||||
try:
|
||||
# remember shell=False, so use git.cmd on windows, not just git
|
||||
p = subprocess.Popen(args, stdout=subprocess.PIPE, cwd=cwd)
|
||||
except EnvironmentError:
|
||||
e = sys.exc_info()[1]
|
||||
if verbose:
|
||||
print("unable to run %s" % args[0])
|
||||
print(e)
|
||||
return None
|
||||
stdout = p.communicate()[0].strip()
|
||||
if sys.version >= '3':
|
||||
stdout = stdout.decode()
|
||||
if p.returncode != 0:
|
||||
if verbose:
|
||||
print("unable to run %s (error)" % args[0])
|
||||
return None
|
||||
return stdout
|
||||
|
||||
|
||||
import sys
|
||||
import re
|
||||
import os.path
|
||||
|
||||
def get_expanded_variables(versionfile_source):
|
||||
# the code embedded in _version.py can just fetch the value of these
|
||||
# variables. When used from setup.py, we don't want to import
|
||||
# _version.py, so we do it with a regexp instead. This function is not
|
||||
# used from _version.py.
|
||||
variables = {}
|
||||
try:
|
||||
for line in open(versionfile_source,"r").readlines():
|
||||
if line.strip().startswith("git_refnames ="):
|
||||
mo = re.search(r'=\s*"(.*)"', line)
|
||||
if mo:
|
||||
variables["refnames"] = mo.group(1)
|
||||
if line.strip().startswith("git_full ="):
|
||||
mo = re.search(r'=\s*"(.*)"', line)
|
||||
if mo:
|
||||
variables["full"] = mo.group(1)
|
||||
except EnvironmentError:
|
||||
pass
|
||||
return variables
|
||||
|
||||
def versions_from_expanded_variables(variables, tag_prefix, verbose=False):
|
||||
refnames = variables["refnames"].strip()
|
||||
if refnames.startswith("$Format"):
|
||||
if verbose:
|
||||
print("variables are unexpanded, not using")
|
||||
return {} # unexpanded, so not in an unpacked git-archive tarball
|
||||
refs = set([r.strip() for r in refnames.strip("()").split(",")])
|
||||
for ref in list(refs):
|
||||
if not re.search(r'\d', ref):
|
||||
if verbose:
|
||||
print("discarding '%s', no digits" % ref)
|
||||
refs.discard(ref)
|
||||
# Assume all version tags have a digit. git's %d expansion
|
||||
# behaves like git log --decorate=short and strips out the
|
||||
# refs/heads/ and refs/tags/ prefixes that would let us
|
||||
# distinguish between branches and tags. By ignoring refnames
|
||||
# without digits, we filter out many common branch names like
|
||||
# "release" and "stabilization", as well as "HEAD" and "master".
|
||||
if verbose:
|
||||
print("remaining refs: %s" % ",".join(sorted(refs)))
|
||||
for ref in sorted(refs):
|
||||
# sorting will prefer e.g. "2.0" over "2.0rc1"
|
||||
if ref.startswith(tag_prefix):
|
||||
r = ref[len(tag_prefix):]
|
||||
if verbose:
|
||||
print("picking %s" % r)
|
||||
return { "version": r,
|
||||
"full": variables["full"].strip() }
|
||||
# no suitable tags, so we use the full revision id
|
||||
if verbose:
|
||||
print("no suitable tags, using full revision id")
|
||||
return { "version": variables["full"].strip(),
|
||||
"full": variables["full"].strip() }
|
||||
|
||||
def versions_from_vcs(tag_prefix, versionfile_source, verbose=False):
|
||||
# this runs 'git' from the root of the source tree. That either means
|
||||
# someone ran a setup.py command (and this code is in versioneer.py, so
|
||||
# IN_LONG_VERSION_PY=False, thus the containing directory is the root of
|
||||
# the source tree), or someone ran a project-specific entry point (and
|
||||
# this code is in _version.py, so IN_LONG_VERSION_PY=True, thus the
|
||||
# containing directory is somewhere deeper in the source tree). This only
|
||||
# gets called if the git-archive 'subst' variables were *not* expanded,
|
||||
# and _version.py hasn't already been rewritten with a short version
|
||||
# string, meaning we're inside a checked out source tree.
|
||||
|
||||
try:
|
||||
here = os.path.abspath(__file__)
|
||||
except NameError:
|
||||
# some py2exe/bbfreeze/non-CPython implementations don't do __file__
|
||||
return {} # not always correct
|
||||
|
||||
# versionfile_source is the relative path from the top of the source tree
|
||||
# (where the .git directory might live) to this file. Invert this to find
|
||||
# the root from __file__.
|
||||
root = here
|
||||
if IN_LONG_VERSION_PY:
|
||||
for i in range(len(versionfile_source.split("/"))):
|
||||
root = os.path.dirname(root)
|
||||
else:
|
||||
root = os.path.dirname(here)
|
||||
if not os.path.exists(os.path.join(root, ".git")):
|
||||
if verbose:
|
||||
print("no .git in %s" % root)
|
||||
return {}
|
||||
|
||||
stdout = run_command([GIT, "describe", "--tags", "--dirty", "--always"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
if not stdout.startswith(tag_prefix):
|
||||
if verbose:
|
||||
print("tag '%s' doesn't start with prefix '%s'" % (stdout, tag_prefix))
|
||||
return {}
|
||||
tag = stdout[len(tag_prefix):]
|
||||
stdout = run_command([GIT, "rev-parse", "HEAD"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
full = stdout.strip()
|
||||
if tag.endswith("-dirty"):
|
||||
full += "-dirty"
|
||||
return {"version": tag, "full": full}
|
||||
|
||||
|
||||
def versions_from_parentdir(parentdir_prefix, versionfile_source, verbose=False):
|
||||
if IN_LONG_VERSION_PY:
|
||||
# We're running from _version.py. If it's from a source tree
|
||||
# (execute-in-place), we can work upwards to find the root of the
|
||||
# tree, and then check the parent directory for a version string. If
|
||||
# it's in an installed application, there's no hope.
|
||||
try:
|
||||
here = os.path.abspath(__file__)
|
||||
except NameError:
|
||||
# py2exe/bbfreeze/non-CPython don't have __file__
|
||||
return {} # without __file__, we have no hope
|
||||
# versionfile_source is the relative path from the top of the source
|
||||
# tree to _version.py. Invert this to find the root from __file__.
|
||||
root = here
|
||||
for i in range(len(versionfile_source.split("/"))):
|
||||
root = os.path.dirname(root)
|
||||
else:
|
||||
# we're running from versioneer.py, which means we're running from
|
||||
# the setup.py in a source tree. sys.argv[0] is setup.py in the root.
|
||||
here = os.path.abspath(sys.argv[0])
|
||||
root = os.path.dirname(here)
|
||||
|
||||
# Source tarballs conventionally unpack into a directory that includes
|
||||
# both the project name and a version string.
|
||||
dirname = os.path.basename(root)
|
||||
if not dirname.startswith(parentdir_prefix):
|
||||
if verbose:
|
||||
print("guessing rootdir is '%s', but '%s' doesn't start with prefix '%s'" %
|
||||
(root, dirname, parentdir_prefix))
|
||||
return None
|
||||
return {"version": dirname[len(parentdir_prefix):], "full": ""}
|
||||
|
||||
tag_prefix = ""
|
||||
parentdir_prefix = "llvmpy-"
|
||||
versionfile_source = "llvm/_version.py"
|
||||
|
||||
def get_versions(default={"version": "unknown", "full": ""}, verbose=False):
|
||||
variables = { "refnames": git_refnames, "full": git_full }
|
||||
ver = versions_from_expanded_variables(variables, tag_prefix, verbose)
|
||||
if not ver:
|
||||
ver = versions_from_vcs(tag_prefix, versionfile_source, verbose)
|
||||
if not ver:
|
||||
ver = versions_from_parentdir(parentdir_prefix, versionfile_source,
|
||||
verbose)
|
||||
if not ver:
|
||||
ver = default
|
||||
return ver
|
||||
|
|
@ -1,134 +0,0 @@
|
|||
#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 */
|
||||
2158
llvm/core.py
2158
llvm/core.py
File diff suppressed because it is too large
Load diff
|
|
@ -1,398 +0,0 @@
|
|||
"""
|
||||
Support for debug info metadata.
|
||||
"""
|
||||
|
||||
import functools
|
||||
|
||||
import llvm.core
|
||||
from llvm import _dwarf
|
||||
|
||||
#----------------------------------------------------------------------------
|
||||
# Some types and type checking functions
|
||||
#----------------------------------------------------------------------------
|
||||
|
||||
int32_t = llvm.core.Type.int(32)
|
||||
bool_t = llvm.core.Type.int(1)
|
||||
p_int32_t = llvm.core.Type.pointer(int32_t)
|
||||
null = llvm.core.Constant.null(p_int32_t)
|
||||
|
||||
i32 = functools.partial(llvm.core.Constant.int, int32_t)
|
||||
i1 = functools.partial(llvm.core.Constant.int, bool_t)
|
||||
|
||||
def is_md(value):
|
||||
return isinstance(value, (llvm.core.MetaData, llvm.core.NamedMetaData,
|
||||
llvm.core.Value))
|
||||
|
||||
def is_mdstr(value):
|
||||
return isinstance(value, (llvm.core.MetaDataString, llvm.core.Value))
|
||||
|
||||
#----------------------------------------------------------------------------
|
||||
# Callbacks for debug type descriptors
|
||||
#----------------------------------------------------------------------------
|
||||
|
||||
def get_i32(llvm_module, value):
|
||||
return i32(value)
|
||||
|
||||
def get_i1(llvm_module, value):
|
||||
return i1(value)
|
||||
|
||||
def get_md(llvm_module, value):
|
||||
if is_md(value):
|
||||
return value
|
||||
return value.get_metadata(llvm_module)
|
||||
|
||||
def get_mdstr(llvm_module, value):
|
||||
if is_mdstr(value):
|
||||
return value
|
||||
return llvm.core.MetaDataString.get(llvm_module, value)
|
||||
|
||||
def get_mdlist(llvm_module, value):
|
||||
if isinstance(value, list):
|
||||
value = MDList([value])
|
||||
return get_md(llvm_module, value)
|
||||
|
||||
def get_lfunc(llvm_module, lfunc):
|
||||
assert lfunc.module is llvm_module
|
||||
return lfunc
|
||||
|
||||
#----------------------------------------------------------------------------
|
||||
# Debug descriptors that generate LLVM Metadata
|
||||
#----------------------------------------------------------------------------
|
||||
|
||||
class desc(object):
|
||||
"""
|
||||
Descriptor of a debug field.
|
||||
|
||||
field_name:
|
||||
name of the field (keyword argument name)
|
||||
build_metadata:
|
||||
metadata callback :: (llvm_module, Python value) -> LLVM Value
|
||||
default:
|
||||
default value for this field
|
||||
"""
|
||||
|
||||
def __init__(self, field_name, build_metadata, default=None):
|
||||
self.field_name = field_name
|
||||
self.build_metadata = build_metadata
|
||||
self.default = default
|
||||
|
||||
|
||||
def build_operand_list(type_descriptors, idx2name, operands, kwargs):
|
||||
"""
|
||||
Build the list of operands from the positional and keyword arguments
|
||||
to a DebugInfoDescriptor.
|
||||
|
||||
E.g. FileDescriptor("foo.c", "/path/to/file", compile_unit=compile_unit)
|
||||
|
||||
idx2name: {0 : 'source_filename',
|
||||
1 : 'source_filedir',
|
||||
2 : 'compile_unit' }
|
||||
operands: ["foo.c", "/path/to/file"]
|
||||
kwargs: { 'compile_unit' : compile_unit }
|
||||
"""
|
||||
for i in range(len(operands), len(type_descriptors)):
|
||||
name = idx2name[i]
|
||||
if name in kwargs:
|
||||
op = kwargs[name]
|
||||
else:
|
||||
typedesc = type_descriptors[i]
|
||||
assert typedesc.default is not None, (
|
||||
"No value found for field %s" % typedesc.field_name)
|
||||
op = typedesc.default
|
||||
|
||||
operands.append(op)
|
||||
|
||||
return operands
|
||||
|
||||
|
||||
class DebugInfoDescriptor(object):
|
||||
"""
|
||||
Base class to describe a debug info descriptor.
|
||||
|
||||
See http://llvm.org/docs/SourceLevelDebugging.html
|
||||
"""
|
||||
|
||||
type_descriptors = None # [desc(...)]
|
||||
idx2name = None # { "field_idx" : field_name }
|
||||
name2idx = None # { "field_name" : field_idx }
|
||||
|
||||
# Whether the debug descriptor is allowed to be incomplete
|
||||
# The policy seems unclear ?
|
||||
accept_optional_data = False
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.class_init()
|
||||
self.metadata_cache = {}
|
||||
|
||||
operands = list(args)
|
||||
if kwargs or not self.accept_optional_data:
|
||||
operands = build_operand_list(self.type_descriptors,
|
||||
self.idx2name, operands, kwargs)
|
||||
|
||||
self.operands = operands
|
||||
self.operands_dict = dict(
|
||||
(typedesc.field_name, operand)
|
||||
for typedesc, operand in zip(self.type_descriptors, operands))
|
||||
|
||||
@classmethod
|
||||
def class_init(cls):
|
||||
if cls.idx2name is None and cls.type_descriptors is not None:
|
||||
cls.name2idx = {}
|
||||
cls.idx2name = {}
|
||||
|
||||
for i, typedesc in enumerate(cls.type_descriptors):
|
||||
cls.name2idx[typedesc.field_name] = i
|
||||
cls.idx2name[i] = typedesc.field_name
|
||||
|
||||
def add_metadata(self, metadata_name, metadata):
|
||||
"""
|
||||
Replace a metadata value in the operand list.
|
||||
"""
|
||||
idx = self.name2idx[metadata_name]
|
||||
self.operands[idx] = metadata
|
||||
|
||||
#------------------------------------------------------------------------
|
||||
# Define metadata in a module
|
||||
#------------------------------------------------------------------------
|
||||
|
||||
def get_metadata(self, llvm_module):
|
||||
"""
|
||||
Get an existing metadata node for the given LLVM module, or build
|
||||
one from this instance.
|
||||
"""
|
||||
if llvm_module in self.metadata_cache:
|
||||
node = self.metadata_cache[llvm_module]
|
||||
else:
|
||||
node = self.build_metadata(llvm_module)
|
||||
self.metadata_cache[llvm_module] = node
|
||||
|
||||
return node
|
||||
|
||||
def build_metadata(self, llvm_module):
|
||||
"Build a metadata node for the given LLVM module"
|
||||
mdops = []
|
||||
for type_desc, operand in zip(self.type_descriptors, self.operands):
|
||||
try:
|
||||
field_value = type_desc.build_metadata(llvm_module, operand)
|
||||
except Exception, e:
|
||||
if type_desc.build_metadata is get_md:
|
||||
raise
|
||||
|
||||
raise ValueError("Invalid value for field %r: %s" % (
|
||||
type_desc.field_name, e))
|
||||
|
||||
mdops.append(field_value)
|
||||
|
||||
return llvm.core.MetaData.get(llvm_module, mdops)
|
||||
|
||||
def define(self, llvm_module):
|
||||
"""
|
||||
Define this debug descriptor as named debug metadata for the module.
|
||||
"""
|
||||
md = self.get_metadata(llvm_module)
|
||||
llvm.core.MetaData.add_named_operand(llvm_module, "dbg", md)
|
||||
|
||||
#----------------------------------------------------------------------------
|
||||
# Convenience descriptors
|
||||
#----------------------------------------------------------------------------
|
||||
|
||||
class MDList(DebugInfoDescriptor):
|
||||
"""
|
||||
[MetaData]
|
||||
"""
|
||||
|
||||
def __init__(self, operands):
|
||||
self.type_descriptors = [desc("op", get_md)] * len(operands)
|
||||
super(MDList, self).__init__(*operands)
|
||||
|
||||
empty = MDList([])
|
||||
|
||||
#----------------------------------------------------------------------------
|
||||
# Dwarf Debug descriptors
|
||||
#----------------------------------------------------------------------------
|
||||
|
||||
class CompileUnitDescriptor(DebugInfoDescriptor):
|
||||
"""
|
||||
!0 = metadata !{
|
||||
i32, ;; Tag = 17 + LLVMDebugVersion (DW_TAG_compile_unit)
|
||||
i32, ;; Unused field.
|
||||
i32, ;; DWARF language identifier (ex. DW_LANG_C89)
|
||||
metadata, ;; Source file name
|
||||
metadata, ;; Source file directory (includes trailing slash)
|
||||
metadata ;; Producer (ex. "4.0.1 LLVM (LLVM research group)")
|
||||
i1, ;; True if this is a main compile unit.
|
||||
i1, ;; True if this is optimized.
|
||||
metadata, ;; Flags
|
||||
i32 ;; Runtime version
|
||||
metadata ;; List of enums types
|
||||
metadata ;; List of retained types
|
||||
metadata ;; List of subprograms
|
||||
metadata ;; List of global variables
|
||||
}
|
||||
"""
|
||||
|
||||
accept_optional_data = True
|
||||
|
||||
type_descriptors = [
|
||||
desc("tag", get_i32),
|
||||
desc("unused", get_i32),
|
||||
|
||||
# Positional argument list starts here:
|
||||
desc("langid", get_i32),
|
||||
desc("source_filename", get_mdstr),
|
||||
desc("source_filedir", get_mdstr),
|
||||
desc("producer", get_mdstr),
|
||||
desc("is_main", get_i1, default=False),
|
||||
desc("is_optimized", get_i1, default=False),
|
||||
desc("compile_flags", get_mdstr, default=""),
|
||||
desc("runtime_version", get_i32, default=0),
|
||||
desc("enum_types", get_mdlist, default=empty),
|
||||
desc("retained_types", get_mdlist, default=empty),
|
||||
desc("subprograms", get_mdlist, default=empty),
|
||||
desc("global_vars", get_mdlist, default=empty),
|
||||
]
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(CompileUnitDescriptor, self).__init__(
|
||||
_dwarf.DW_TAG_compile_unit + _dwarf.LLVMDebugVersion, # tag
|
||||
0, # unused
|
||||
*args, **kwargs)
|
||||
|
||||
def define(self, llvm_module):
|
||||
"""
|
||||
Define this debug descriptor as named debug metadata for the module.
|
||||
"""
|
||||
md = self.get_metadata(llvm_module)
|
||||
llvm.core.MetaData.add_named_operand(llvm_module, "llvm.dbg.cu", md)
|
||||
|
||||
|
||||
class FileDescriptor(DebugInfoDescriptor):
|
||||
"""
|
||||
!0 = metadata !{
|
||||
i32, ;; Tag = 41 + LLVMDebugVersion (DW_TAG_file_type)
|
||||
metadata, ;; Source file name
|
||||
metadata, ;; Source file directory (includes trailing slash)
|
||||
metadata ;; Unused
|
||||
}
|
||||
"""
|
||||
|
||||
type_descriptors = [
|
||||
desc("tag", get_i32),
|
||||
|
||||
# Positional argument list starts here:
|
||||
desc("source_filename", get_mdstr),
|
||||
desc("source_filedir", get_mdstr),
|
||||
desc("compile_unit", get_md, default=null),
|
||||
]
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(FileDescriptor, self).__init__(
|
||||
_dwarf.DW_TAG_file_type + _dwarf.LLVMDebugVersion, # Tag
|
||||
*args, **kwargs)
|
||||
|
||||
@classmethod
|
||||
def from_compileunit(cls, compile_unit_descriptor):
|
||||
return cls(compile_unit_descriptor.operands_dict["source_filename"],
|
||||
compile_unit_descriptor.operands_dict["source_filedir"],
|
||||
compile_unit_descriptor)
|
||||
|
||||
|
||||
class SubprogramDescriptor(DebugInfoDescriptor):
|
||||
"""
|
||||
!2 = metadata !{
|
||||
i32, ;; Tag = 46 + LLVMDebugVersion (DW_TAG_subprogram)
|
||||
i32, ;; Unused field.
|
||||
metadata, ;; Reference to context descriptor
|
||||
metadata, ;; Name
|
||||
metadata, ;; Display name (fully qualified C++ name)
|
||||
metadata, ;; MIPS linkage name (for C++)
|
||||
metadata, ;; Reference to file where defined
|
||||
i32, ;; Line number where defined
|
||||
metadata, ;; Reference to type descriptor
|
||||
i1, ;; True if the global is local to compile unit (static)
|
||||
i1, ;; True if the global is defined in the compile unit (not extern)
|
||||
i32, ;; Line number where the scope of the subprogram begins
|
||||
i32, ;; Virtuality, e.g. dwarf::DW_VIRTUALITY__virtual
|
||||
i32, ;; Index into a virtual function
|
||||
metadata, ;; indicates which base type contains the vtable pointer for the
|
||||
;; derived class
|
||||
i32, ;; Flags - Artifical, Private, Protected, Explicit, Prototyped.
|
||||
i1, ;; isOptimized
|
||||
Function * , ;; Pointer to LLVM function
|
||||
metadata, ;; Lists function template parameters
|
||||
metadata, ;; Function declaration descriptor
|
||||
metadata ;; List of function variables
|
||||
}
|
||||
"""
|
||||
|
||||
accept_optional_data = True
|
||||
|
||||
type_descriptors = [
|
||||
desc("tag", get_i32),
|
||||
desc("unused", get_i32),
|
||||
|
||||
# Positional argument list starts here:
|
||||
desc("file_desc", get_md),
|
||||
desc("name", get_mdstr),
|
||||
desc("display_name", get_mdstr),
|
||||
desc("mips_linkage_name", get_mdstr),
|
||||
desc("source_file_ref", get_md),
|
||||
desc("line_number", get_i32),
|
||||
desc("signature", get_md),
|
||||
desc("is_local", get_i1, default=False),
|
||||
desc("is_definition", get_i1, default=True),
|
||||
desc("virtual_attribute", get_i32, default=0),
|
||||
desc("virtual_index", get_i32, default=0),
|
||||
desc("virttab", get_i32, default=0),
|
||||
desc("flags", get_i32, default=0),
|
||||
desc("is_optimized", get_i1, default=False),
|
||||
desc("llvm_func", get_lfunc),
|
||||
# Template params
|
||||
# Func decl
|
||||
# Func vars
|
||||
]
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(SubprogramDescriptor, self).__init__(
|
||||
_dwarf.DW_TAG_subprogram + _dwarf.LLVMDebugVersion, # Tag
|
||||
0, # Unused
|
||||
*args, **kwargs)
|
||||
|
||||
class BlockDescriptor(DebugInfoDescriptor):
|
||||
"""
|
||||
!3 = metadata !{
|
||||
i32, ;; Tag = 11 + LLVMDebugVersion (DW_TAG_lexical_block)
|
||||
metadata,;; Reference to context descriptor
|
||||
i32, ;; Line number
|
||||
i32 ;; Column number
|
||||
}
|
||||
"""
|
||||
|
||||
type_descriptors = [
|
||||
desc("tag", get_i32),
|
||||
|
||||
# Positional argument list starts here:
|
||||
desc("context_descr", get_md), # FileDescr | BlockDescr |
|
||||
# SubprogDescr | ComputeUnit
|
||||
desc("line_number", get_i32),
|
||||
desc("col_number", get_i32),
|
||||
]
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(BlockDescriptor, self).__init__(
|
||||
_dwarf.DW_TAG_lexical_block + _dwarf.LLVMDebugVersion,
|
||||
*args, **kwargs)
|
||||
|
||||
class PositionInfoDescriptor(DebugInfoDescriptor):
|
||||
"""
|
||||
line number, column number, scope, and original scope
|
||||
"""
|
||||
|
||||
type_descriptors = [
|
||||
desc("line_number", get_i32),
|
||||
desc("col_number", get_i32),
|
||||
desc("context_descr", get_md), # Scope of instruction
|
||||
# (FileDescr etc)
|
||||
desc("original_context_descr", get_md, # The original scope if inlined
|
||||
default=null),
|
||||
]
|
||||
392
llvm/ee.py
392
llvm/ee.py
|
|
@ -1,392 +0,0 @@
|
|||
#
|
||||
# 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.
|
||||
#
|
||||
|
||||
"""Execution Engine and related classes.
|
||||
|
||||
"""
|
||||
|
||||
import llvm # top-level, for common stuff
|
||||
import llvm.core as core # module, function etc.
|
||||
import llvm._core as _core # C wrappers
|
||||
import llvm._util as _util # utility functions
|
||||
import logging
|
||||
import os
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# re-export TargetData for backward compatibility.
|
||||
from llvm.passes import TargetData
|
||||
|
||||
def _detect_avx_support():
|
||||
'''FIXME: This is a workaround for AVX support.
|
||||
'''
|
||||
disable_avx_detect = int(os.environ.get('LLVMPY_DISABLE_AVX_DETECT', 0))
|
||||
if disable_avx_detect:
|
||||
return False # enable AVX if user disable AVX detect
|
||||
force_disable_avx = int(os.environ.get('LLVMPY_FORCE_DISABLE_AVX', 0))
|
||||
if force_disable_avx:
|
||||
return True # force disable AVX
|
||||
# auto-detect avx
|
||||
try:
|
||||
for line in open('/proc/cpuinfo'):
|
||||
if line.lstrip().startswith('flags') and 'avx' in line.split():
|
||||
# enable AVX if flags contain AVX
|
||||
return False
|
||||
except IOError:
|
||||
pass # disable AVX if no /proc/cpuinfo is found
|
||||
return True # disable AVX if flags does not have AVX
|
||||
|
||||
FORCE_DISABLE_AVX = _detect_avx_support()
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Enumerations
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
BO_BIG_ENDIAN = 0
|
||||
BO_LITTLE_ENDIAN = 1
|
||||
|
||||
# CodeModel
|
||||
CM_DEFAULT = 0
|
||||
CM_JITDEFAULT = 1
|
||||
CM_SMALL = 2
|
||||
CM_KERNEL = 3
|
||||
CM_MEDIUM = 4
|
||||
CM_LARGE = 5
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Generic value
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
class GenericValue(object):
|
||||
|
||||
@staticmethod
|
||||
def int(ty, intval):
|
||||
core.check_is_type(ty)
|
||||
ptr = _core.LLVMCreateGenericValueOfInt(ty.ptr, intval, 0)
|
||||
return GenericValue(ptr)
|
||||
|
||||
@staticmethod
|
||||
def int_signed(ty, intval):
|
||||
core.check_is_type(ty)
|
||||
ptr = _core.LLVMCreateGenericValueOfInt(ty.ptr, intval, 1)
|
||||
return GenericValue(ptr)
|
||||
|
||||
@staticmethod
|
||||
def real(ty, floatval):
|
||||
core.check_is_type(ty) # only float or double
|
||||
ptr = _core.LLVMCreateGenericValueOfFloat(ty.ptr, floatval)
|
||||
return GenericValue(ptr)
|
||||
|
||||
@staticmethod
|
||||
def pointer(*args):
|
||||
'''
|
||||
One argument version takes (addr).
|
||||
Two argument version takes (ty, addr). [Deprecated]
|
||||
|
||||
`ty` is unused.
|
||||
`addr` is an integer representing an address.
|
||||
|
||||
TODO: remove two argument version.
|
||||
'''
|
||||
if len(args)==2:
|
||||
logger.warning("Deprecated: Two argument version of "
|
||||
"GenericValue.pointer() is deprecated.")
|
||||
addr = args[1]
|
||||
elif len(args)!=1:
|
||||
raise TypeError("pointer() takes 1 or 2 arguments.")
|
||||
else:
|
||||
addr = args[0]
|
||||
ptr = _core.LLVMCreateGenericValueOfPointer(addr)
|
||||
return GenericValue(ptr)
|
||||
|
||||
def __init__(self, ptr):
|
||||
self.ptr = ptr
|
||||
|
||||
def __del__(self):
|
||||
_core.LLVMDisposeGenericValue(self.ptr)
|
||||
|
||||
def as_int(self):
|
||||
return _core.LLVMGenericValueToInt(self.ptr, 0)
|
||||
|
||||
def as_int_signed(self):
|
||||
return _core.LLVMGenericValueToInt(self.ptr, 1)
|
||||
|
||||
def as_real(self, ty):
|
||||
core.check_is_type(ty) # only float or double
|
||||
return _core.LLVMGenericValueToFloat(ty.ptr, self.ptr)
|
||||
|
||||
def as_pointer(self):
|
||||
return _core.LLVMGenericValueToPointer(self.ptr)
|
||||
|
||||
|
||||
# helper functions for generic value objects
|
||||
def check_is_generic_value(obj): _util.check_gen(obj, GenericValue)
|
||||
def _unpack_generic_values(objlist):
|
||||
return _util.unpack_gen(objlist, check_is_generic_value)
|
||||
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Engine builder
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
class EngineBuilder(object):
|
||||
@staticmethod
|
||||
def new(module):
|
||||
core.check_is_module(module)
|
||||
_util.check_is_unowned(module)
|
||||
obj = _core.LLVMCreateEngineBuilder(module.ptr)
|
||||
return EngineBuilder(obj, module)
|
||||
|
||||
def __init__(self, ptr, module):
|
||||
self.ptr = ptr
|
||||
self._module = module
|
||||
self.__has_mattrs = False
|
||||
|
||||
def __del__(self):
|
||||
_core.LLVMDisposeEngineBuilder(self.ptr)
|
||||
|
||||
def force_jit(self):
|
||||
_core.LLVMEngineBuilderForceJIT(self.ptr)
|
||||
return self
|
||||
|
||||
def force_interpreter(self):
|
||||
_core.LLVMEngineBuilderForceInterpreter(self.ptr)
|
||||
return self
|
||||
|
||||
def opt(self, level):
|
||||
'''
|
||||
level valid [0, 1, 2, 3] -- [None, Less, Default, Aggressive]
|
||||
'''
|
||||
assert level in range(4)
|
||||
_core.LLVMEngineBuilderSetOptLevel(self.ptr, level)
|
||||
return self
|
||||
|
||||
def mattrs(self, string):
|
||||
'''set machine attributes as a comma/space separated string
|
||||
|
||||
e.g: +sse,-3dnow
|
||||
'''
|
||||
self.__has_mattrs = True
|
||||
if FORCE_DISABLE_AVX:
|
||||
if 'avx' not in map(lambda x: x.strip(), string.split(',')):
|
||||
# User did not override
|
||||
string += ',-avx'
|
||||
_core.LLVMEngineBuilderSetMAttrs(self.ptr, string.replace(',', ' '))
|
||||
return self
|
||||
|
||||
def create(self, tm=None):
|
||||
'''
|
||||
tm --- Optional. Provide a TargetMachine. Ownership is transfered
|
||||
to the returned execution engine.
|
||||
'''
|
||||
if not self.__has_mattrs and FORCE_DISABLE_AVX:
|
||||
self.mattrs('-avx')
|
||||
|
||||
if tm:
|
||||
_util.check_is_unowned(tm)
|
||||
ret = _core.LLVMEngineBuilderCreateTM(self.ptr, tm.ptr)
|
||||
else:
|
||||
ret = _core.LLVMEngineBuilderCreate(self.ptr)
|
||||
if isinstance(ret, str):
|
||||
raise llvm.LLVMException(ret)
|
||||
engine = ExecutionEngine(ret, self._module)
|
||||
if tm:
|
||||
tm._own(owner=llvm.DummyOwner)
|
||||
return engine
|
||||
|
||||
def select_target(self):
|
||||
'''get the corresponding target machine
|
||||
'''
|
||||
ptr = _core.LLVMTargetMachineFromEngineBuilder(self.ptr)
|
||||
return TargetMachine(ptr)
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Execution engine
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
class ExecutionEngine(object):
|
||||
|
||||
@staticmethod
|
||||
def new(module, force_interpreter=False):
|
||||
eb = EngineBuilder.new(module)
|
||||
if force_interpreter:
|
||||
eb.force_interpreter()
|
||||
return eb.create()
|
||||
|
||||
def __init__(self, ptr, module):
|
||||
self.ptr = ptr
|
||||
module._own(self)
|
||||
|
||||
def __del__(self):
|
||||
_core.LLVMDisposeExecutionEngine(self.ptr)
|
||||
|
||||
def disable_lazy_compilation(self, disabled=True):
|
||||
_core.LLVMExecutionEngineDisableLazyCompilation(self.ptr,
|
||||
int(bool(disabled)))
|
||||
|
||||
def run_function(self, fn, args):
|
||||
core.check_is_function(fn)
|
||||
ptrs = _unpack_generic_values(args)
|
||||
gvptr = _core.LLVMRunFunction2(self.ptr, fn.ptr, ptrs)
|
||||
return GenericValue(gvptr)
|
||||
|
||||
def get_pointer_to_function(self, fn):
|
||||
core.check_is_function(fn)
|
||||
return _core.LLVMGetPointerToFunction(self.ptr,fn.ptr)
|
||||
|
||||
def get_pointer_to_global(self, val):
|
||||
core.check_is_global_value(val)
|
||||
return _core.LLVMGetPointerToGlobal(self.ptr, val.ptr)
|
||||
|
||||
def add_global_mapping(self, gvar, addr):
|
||||
assert addr >= 0, "Address cannot not be negative"
|
||||
_core.LLVMAddGlobalMapping(self.ptr, gvar.ptr, addr)
|
||||
|
||||
def run_static_ctors(self):
|
||||
_core.LLVMRunStaticConstructors(self.ptr)
|
||||
|
||||
def run_static_dtors(self):
|
||||
_core.LLVMRunStaticDestructors(self.ptr)
|
||||
|
||||
def free_machine_code_for(self, fn):
|
||||
core.check_is_function(fn)
|
||||
_core.LLVMFreeMachineCodeForFunction(self.ptr, fn.ptr)
|
||||
|
||||
def add_module(self, module):
|
||||
core.check_is_module(module)
|
||||
_core.LLVMAddModule(self.ptr, module.ptr)
|
||||
module._own(self)
|
||||
|
||||
def remove_module(self, module):
|
||||
core.check_is_module(module)
|
||||
if module.owner != self:
|
||||
raise llvm.LLVMException("module is not owned by self")
|
||||
ret = _core.LLVMRemoveModule2(self.ptr, module.ptr)
|
||||
if isinstance(ret, str):
|
||||
raise llvm.LLVMException(ret)
|
||||
return core.Module(ret)
|
||||
|
||||
@property
|
||||
def target_data(self):
|
||||
td = TargetData(_core.LLVMGetExecutionEngineTargetData(self.ptr))
|
||||
td._own(self)
|
||||
return td
|
||||
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Target machine
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
def print_registered_targets():
|
||||
'''
|
||||
Note: print directly to stdout
|
||||
'''
|
||||
_core.LLVMPrintRegisteredTargetsForVersion()
|
||||
|
||||
def get_host_cpu_name():
|
||||
'''return the string name of the host CPU
|
||||
'''
|
||||
return _core.LLVMGetHostCPUName()
|
||||
|
||||
def get_default_triple():
|
||||
'''return the target triple of the host in str-rep
|
||||
'''
|
||||
return _core.LLVMDefaultTargetTriple()
|
||||
|
||||
|
||||
class TargetMachine(llvm.Ownable):
|
||||
|
||||
@staticmethod
|
||||
def new(triple='', cpu='', features='', opt=2, cm=CM_DEFAULT):
|
||||
if not triple and not cpu:
|
||||
triple = get_default_triple()
|
||||
cpu = get_host_cpu_name()
|
||||
ptr = _core.LLVMCreateTargetMachine(triple, cpu, features, opt, cm)
|
||||
return TargetMachine(ptr)
|
||||
|
||||
@staticmethod
|
||||
def lookup(arch, cpu='', features='', opt=2, cm=CM_DEFAULT):
|
||||
'''create a targetmachine given an architecture name
|
||||
|
||||
For a list of architectures,
|
||||
use: `llc -help`
|
||||
|
||||
For a list of available CPUs,
|
||||
use: `llvm-as < /dev/null | llc -march=xyz -mcpu=help`
|
||||
|
||||
For a list of available attributes (features),
|
||||
use: `llvm-as < /dev/null | llc -march=xyz -mattr=help`
|
||||
'''
|
||||
ptr = _core.LLVMTargetMachineLookup(arch, cpu, features, opt, cm)
|
||||
return TargetMachine(ptr)
|
||||
|
||||
def __init__(self, ptr):
|
||||
llvm.Ownable.__init__(self, ptr, _core.LLVMDisposeTargetMachine)
|
||||
|
||||
def emit_assembly(self, module):
|
||||
'''returns byte string of the module as assembly code of the target machine
|
||||
'''
|
||||
return _core.LLVMTargetMachineEmitFile(self.ptr, module.ptr, True)
|
||||
|
||||
def emit_object(self, module):
|
||||
'''returns byte string of the module as native code of the target machine
|
||||
'''
|
||||
return _core.LLVMTargetMachineEmitFile(self.ptr, module.ptr, False)
|
||||
|
||||
@property
|
||||
def target_data(self):
|
||||
'''get target data of this machine
|
||||
'''
|
||||
ptr = _core.LLVMTargetMachineGetTargetData(self.ptr)
|
||||
td = TargetData(ptr)
|
||||
td._own(self)
|
||||
return td
|
||||
|
||||
@property
|
||||
def target_name(self):
|
||||
return _core.LLVMTargetMachineGetTargetName(self.ptr)
|
||||
|
||||
@property
|
||||
def target_short_description(self):
|
||||
return _core.LLVMTargetMachineGetTargetShortDescription(self.ptr)
|
||||
|
||||
@property
|
||||
def triple(self):
|
||||
return _core.LLVMTargetMachineGetTriple(self.ptr)
|
||||
|
||||
@property
|
||||
def cpu(self):
|
||||
return _core.LLVMTargetMachineGetCPU(self.ptr)
|
||||
|
||||
@property
|
||||
def feature_string(self):
|
||||
return _core.LLVMTargetMachineGetFS(self.ptr)
|
||||
|
||||
1361
llvm/extra.cpp
1361
llvm/extra.cpp
File diff suppressed because it is too large
Load diff
676
llvm/extra.h
676
llvm/extra.h
|
|
@ -1,676 +0,0 @@
|
|||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* These are some "extra" functions not available in the standard LLVM-C
|
||||
* bindings, but are required / good-to-have inorder to implement the
|
||||
* Python bindings.
|
||||
*/
|
||||
|
||||
#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
|
||||
|
||||
|
||||
#if LLVM_VERSION_MAJOR >= 3 && LLVM_VERSION_MINOR >= 2
|
||||
/*
|
||||
* Wraps new TargetTransformInfo(
|
||||
* TargetMachine::getScalarTargetTransformInfo,
|
||||
* TargetMachine::getVectorTargetTransformInfo)
|
||||
*/
|
||||
LLVMPassRef LLVMCreateTargetTransformInfo(LLVMTargetMachineRef tmref);
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Wraps new TargetLibraryInfo
|
||||
*/
|
||||
LLVMPassRef LLVMCreateTargetLibraryInfo(const char * triple);
|
||||
|
||||
/*
|
||||
* Wraps llvm::getDefaultTargetTriple
|
||||
*/
|
||||
const char * LLVMDefaultTargetTriple();
|
||||
|
||||
/*
|
||||
* Wraps Pass::lookupPassInfo and PassInfo::createPass
|
||||
*/
|
||||
LLVMPassRef LLVMCreatePassByName(const char *name);
|
||||
|
||||
/*
|
||||
* Wraps operator delete (Pass*)
|
||||
*/
|
||||
void LLVMDisposePass(LLVMPassRef passref);
|
||||
|
||||
/*
|
||||
* Wraps Pass::getPassName
|
||||
*/
|
||||
const char * LLVMGetPassName(LLVMPassRef passref);
|
||||
|
||||
/*
|
||||
* Wraps PassManager::add
|
||||
*/
|
||||
void LLVMAddPass(LLVMPassManagerRef pmref, LLVMPassRef passref);
|
||||
|
||||
/*
|
||||
* Wraps Pass::dump
|
||||
*/
|
||||
void LLVMPassDump(LLVMPassRef passref);
|
||||
|
||||
/*
|
||||
* Wraps llvm:InlineAsm::get
|
||||
*/
|
||||
LLVMValueRef LLVMGetFunctionFromInlineAsm(LLVMTypeRef funcType,
|
||||
const char inlineAsm[],
|
||||
const char constrains[],
|
||||
bool hasSideEffect,
|
||||
bool isAlignStack,
|
||||
int asmDialect);
|
||||
|
||||
/*
|
||||
* Wraps llvm::CloneModule
|
||||
*/
|
||||
LLVMModuleRef LLVMCloneModule(LLVMModuleRef mod);
|
||||
|
||||
|
||||
/*
|
||||
* Wraps NamedMDNode::print()
|
||||
*/
|
||||
const char * LLVMDumpNamedMDToString(LLVMNamedMDRef nmd);
|
||||
|
||||
/*
|
||||
* Wraps NamedMDNode::getName()
|
||||
*/
|
||||
const char * LLVMNamedMetaDataGetName(LLVMNamedMDRef nmd);
|
||||
|
||||
/*
|
||||
* Wraps NamedMDNode::addOperand()
|
||||
*/
|
||||
void LLVMNamedMetaDataAddOperand(LLVMNamedMDRef nmd, LLVMValueRef md);
|
||||
|
||||
/*
|
||||
* Wraps NamedMDNode::eraseFromParent()
|
||||
*/
|
||||
void LLVMEraseNamedMetaData(LLVMNamedMDRef nmd);
|
||||
|
||||
/*
|
||||
* Wraps Module::getOrInsertNamedMetadata
|
||||
*/
|
||||
LLVMNamedMDRef LLVMModuleGetOrInsertNamedMetaData(LLVMModuleRef mod, const char *name);
|
||||
|
||||
/*
|
||||
* Wraps Module::getNamedMetadata
|
||||
*/
|
||||
LLVMNamedMDRef LLVMModuleGetNamedMetaData(LLVMModuleRef mod, const char *name);
|
||||
|
||||
/*
|
||||
* Wraps Instruction::setMetadata()
|
||||
*/
|
||||
void LLVMInstSetMetaData(LLVMValueRef instref, const char* mdkind,
|
||||
LLVMValueRef metaref);
|
||||
|
||||
/*
|
||||
* Wraps MDNode::get()
|
||||
*/
|
||||
LLVMValueRef LLVMMetaDataGet(LLVMModuleRef modref, LLVMValueRef * valrefs,
|
||||
unsigned valct);
|
||||
|
||||
/*
|
||||
* Wraps MDNode::getOperand()
|
||||
*/
|
||||
LLVMValueRef LLVMMetaDataGetOperand(LLVMValueRef mdref, unsigned index);
|
||||
|
||||
/*
|
||||
* Wraps MDNode::getNumOperands()
|
||||
*/
|
||||
unsigned LLVMMetaDataGetNumOperands(LLVMValueRef mdref);
|
||||
|
||||
/*
|
||||
* Wraps MDString::get()
|
||||
*/
|
||||
LLVMValueRef LLVMMetaDataStringGet(LLVMModuleRef modref, const char *s);
|
||||
|
||||
/*
|
||||
* Wraps ConstantExpr::getOpcodeName()
|
||||
*/
|
||||
const char *LLVMGetConstExprOpcodeName(LLVMValueRef inst);
|
||||
|
||||
/*
|
||||
* Wraps ConstantExpr::getOpcode()
|
||||
*/
|
||||
unsigned LLVMGetConstExprOpcode(LLVMValueRef inst);
|
||||
|
||||
/*
|
||||
* Wraps LoadInst::SetAlignment
|
||||
*/
|
||||
void LLVMLdSetAlignment(LLVMValueRef inst, unsigned align);
|
||||
|
||||
/*
|
||||
* Wraps StoreInst::SetAlignment
|
||||
*/
|
||||
void LLVMStSetAlignment(LLVMValueRef inst, unsigned align);
|
||||
|
||||
const char * LLVMGetHostCPUName();
|
||||
|
||||
int LLVMInitializeNativeTargetAsmPrinter();
|
||||
|
||||
|
||||
LLVMTargetMachineRef LLVMTargetMachineLookup(const char *arch, const char *cpu,
|
||||
const char *features, int opt,
|
||||
int codemodel, std::string &error);
|
||||
|
||||
LLVMTargetMachineRef LLVMCreateTargetMachine(const char *arch, const char *cpu,
|
||||
const char *features, int opt,
|
||||
int codemodel,
|
||||
std::string &error);
|
||||
|
||||
/*
|
||||
* Wraps EngineBuilder::selectTarget
|
||||
*/
|
||||
LLVMTargetMachineRef LLVMTargetMachineFromEngineBuilder(LLVMEngineBuilderRef eb);
|
||||
|
||||
/*
|
||||
* Wraps operator delete
|
||||
*/
|
||||
void LLVMDisposeTargetMachine(LLVMTargetMachineRef tm);
|
||||
|
||||
/*
|
||||
* Wraps TargetMachine::addPassesToEmitFile
|
||||
*/
|
||||
unsigned char* LLVMTargetMachineEmitFile(LLVMTargetMachineRef tmref,
|
||||
LLVMModuleRef modref,
|
||||
int assembly, size_t * lenp,
|
||||
std::string &error);
|
||||
|
||||
/*
|
||||
* Wraps TargetMachine::getTargetData
|
||||
*/
|
||||
LLVMTargetDataRef LLVMTargetMachineGetTargetData(LLVMTargetMachineRef tm);
|
||||
|
||||
/*
|
||||
* Wraps TargetMachine::getTarget().getName()
|
||||
*/
|
||||
const char* LLVMTargetMachineGetTargetName(LLVMTargetMachineRef tm);
|
||||
|
||||
/*
|
||||
* Wraps TargetMachine::getTarget().getShortDescription()
|
||||
*/
|
||||
const char* LLVMTargetMachineGetTargetShortDescription(LLVMTargetMachineRef tm);
|
||||
|
||||
/*
|
||||
* Wraps TargetMachine::getTargetTriple
|
||||
*/
|
||||
const char * LLVMTargetMachineGetTriple(LLVMTargetMachineRef tm);
|
||||
|
||||
/*
|
||||
* Wraps TargetMachine::getTargetCPU
|
||||
*/
|
||||
const char * LLVMTargetMachineGetCPU(LLVMTargetMachineRef tm);
|
||||
|
||||
/*
|
||||
* Wraps TargetMachine::getTargetFeatureString
|
||||
*/
|
||||
const char * LLVMTargetMachineGetFS(LLVMTargetMachineRef tm);
|
||||
|
||||
/*
|
||||
* Wraps TargetRegister::printRegisteredTargetsForVersion
|
||||
*/
|
||||
void LLVMPrintRegisteredTargetsForVersion();
|
||||
|
||||
/*
|
||||
* Wraps TargetMachine::addPassesToEmitFile
|
||||
*/
|
||||
unsigned char* LLVMGetNativeCodeFromModule(LLVMModuleRef module, int assembly,
|
||||
size_t * lenp, std::string &error);
|
||||
|
||||
/*
|
||||
* Wraps IRBuilder::CreateFence
|
||||
*/
|
||||
LLVMValueRef LLVMBuildFence(LLVMBuilderRef builder, const char* ordering,
|
||||
int crossthread);
|
||||
|
||||
/*
|
||||
* Wraps IRBuilder::CreateLoad, LoadInst::setAtomic
|
||||
*/
|
||||
LLVMValueRef LLVMBuildAtomicLoad(LLVMBuilderRef builder, LLVMValueRef ptr,
|
||||
unsigned align, const char* ordering,
|
||||
int crossthread);
|
||||
/*
|
||||
* Wraps IRBuilder::CreateStore, StoreInst::setAtomic
|
||||
*/
|
||||
LLVMValueRef LLVMBuildAtomicStore(LLVMBuilderRef builder,
|
||||
LLVMValueRef ptr, LLVMValueRef val,
|
||||
unsigned align, const char* ordering,
|
||||
int crossthread);
|
||||
|
||||
/*
|
||||
* Wraps IRBuilder::CreateAtomicRMW
|
||||
*/
|
||||
LLVMValueRef LLVMBuildAtomicRMW(LLVMBuilderRef builder, const char * op,
|
||||
LLVMValueRef ptr, LLVMValueRef val,
|
||||
const char* ordering, int crossthread);
|
||||
|
||||
/*
|
||||
* Wraps IRBuilder::CreateAtomicCmpXchg
|
||||
*/
|
||||
LLVMValueRef LLVMBuildAtomicCmpXchg(LLVMBuilderRef builder, LLVMValueRef ptr,
|
||||
LLVMValueRef cmp, LLVMValueRef val,
|
||||
const char* ordering, int crossthread);
|
||||
|
||||
/*
|
||||
* Wraps new EngineBuilder
|
||||
*/
|
||||
LLVMEngineBuilderRef LLVMCreateEngineBuilder(LLVMModuleRef mod);
|
||||
|
||||
/*
|
||||
* Wraps delete EngineBuilder
|
||||
*/
|
||||
void LLVMDisposeEngineBuilder(LLVMEngineBuilderRef eb);
|
||||
|
||||
|
||||
/*
|
||||
* Wraps EngineBuilder::setEngineKind(EngineKind::JIT)
|
||||
*/
|
||||
void LLVMEngineBuilderForceJIT(LLVMEngineBuilderRef eb);
|
||||
|
||||
/*
|
||||
* Wraps EngineBuilder::setEngineKind(EngineKind::Interpreter)
|
||||
*/
|
||||
void LLVMEngineBuilderForceInterpreter(LLVMEngineBuilderRef eb);
|
||||
|
||||
|
||||
/*
|
||||
* Wraps EngineBuilder::setOptLevel
|
||||
*/
|
||||
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
|
||||
*/
|
||||
LLVMExecutionEngineRef LLVMEngineBuilderCreate(LLVMEngineBuilderRef eb,
|
||||
std::string &error);
|
||||
|
||||
/*
|
||||
* Wraps EngineBuilder::create(TargetMachine*)
|
||||
*/
|
||||
LLVMExecutionEngineRef LLVMEngineBuilderCreateTM(LLVMEngineBuilderRef ebref,
|
||||
LLVMTargetMachineRef tmref,
|
||||
std::string & error);
|
||||
|
||||
|
||||
/*
|
||||
* Wraps PassManagerBuilder::OptLevel
|
||||
*/
|
||||
int LLVMPassManagerBuilderGetOptLevel(LLVMPassManagerBuilderRef pmb);
|
||||
|
||||
/*
|
||||
* Wraps PassManagerBuilder::SizeLevel
|
||||
*/
|
||||
int LLVMPassManagerBuilderGetSizeLevel(LLVMPassManagerBuilderRef pmb);
|
||||
|
||||
/*
|
||||
* Wraps PassManagerBuilder::Vectorize
|
||||
*/
|
||||
void LLVMPassManagerBuilderSetVectorize(LLVMPassManagerBuilderRef pmb, int flag);
|
||||
|
||||
/*
|
||||
* Wraps PassManagerBuilder::Vectorize
|
||||
*/
|
||||
int LLVMPassManagerBuilderGetVectorize(LLVMPassManagerBuilderRef pmb);
|
||||
|
||||
#if LLVM_VERSION_MAJOR >= 3 && LLVM_VERSION_MINOR >= 2
|
||||
/*
|
||||
* Wraps PassManagerBuilder::LoopVectorize
|
||||
*/
|
||||
void LLVMPassManagerBuilderSetLoopVectorize(LLVMPassManagerBuilderRef pmb,
|
||||
int flag);
|
||||
|
||||
/*
|
||||
* Wraps PassManagerBuilder::LoopVectorize
|
||||
*/
|
||||
int LLVMPassManagerBuilderGetLoopVectorize(LLVMPassManagerBuilderRef pmb);
|
||||
#endif // llvm-3.2
|
||||
|
||||
/*
|
||||
* Wraps PassManagerBuilder::DisableUnitAtATime
|
||||
*/
|
||||
int LLVMPassManagerBuilderGetDisableUnitAtATime(LLVMPassManagerBuilderRef pmb);
|
||||
|
||||
/*
|
||||
* Wraps PassManagerBuilder::DisableUnrollLoops
|
||||
*/
|
||||
int LLVMPassManagerBuilderGetDisableUnrollLoops(LLVMPassManagerBuilderRef pmb);
|
||||
|
||||
/*
|
||||
* Wraps PassManagerBuilder::DisableSimplifyLibCalls
|
||||
*/
|
||||
int LLVMPassManagerBuilderGetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef pmb);
|
||||
|
||||
/*
|
||||
* Wraps PassManager::add
|
||||
*/
|
||||
int LLVMAddPassByName(LLVMPassManagerRef pm, const char * name);
|
||||
|
||||
/*
|
||||
* Wraps initialize*
|
||||
*/
|
||||
void LLVMInitializePasses(void);
|
||||
|
||||
/*
|
||||
* Wraps PassRegistry::enumerateWith()
|
||||
* Returns a '\n' separated string of all passes available to `opt`.
|
||||
*/
|
||||
const char * LLVMDumpPasses(void);
|
||||
|
||||
/*
|
||||
* Wraps StructType::isLiteral()
|
||||
*/
|
||||
int LLVMIsLiteralStruct(LLVMTypeRef type);
|
||||
|
||||
/*
|
||||
* Wraps StructType::create()
|
||||
*/
|
||||
LLVMTypeRef LLVMStructTypeIdentified(const char * name);
|
||||
|
||||
/*
|
||||
* StructType::setBody()
|
||||
*/
|
||||
void LLVMSetStructBody(LLVMTypeRef type, LLVMTypeRef* elemtys, unsigned elemct, int is_packed);
|
||||
|
||||
/*
|
||||
* Wraps llvm::StructType::setName()
|
||||
*/
|
||||
void LLVMSetStructName(LLVMTypeRef type, const char * name);
|
||||
|
||||
|
||||
/*
|
||||
* Wraps llvm::Module::getModuleIdentifier()
|
||||
*/
|
||||
char *LLVMGetModuleIdentifier(LLVMModuleRef module);
|
||||
|
||||
/*
|
||||
* Wraps llvm::Module::setModuleIdentifier()
|
||||
*/
|
||||
void LLVMSetModuleIdentifier(LLVMModuleRef module, const char * name);
|
||||
|
||||
/* Notes:
|
||||
* - Some returned strings must be disposed of by LLVMDisposeMessage. These are
|
||||
* indicated in the comments. Where it is not indicated, DO NOT call dispose.
|
||||
*/
|
||||
|
||||
/* Wraps llvm::Module::print(). Dispose the returned string after use, via
|
||||
* LLVMDisposeMessage(). */
|
||||
char *LLVMDumpModuleToString(LLVMModuleRef module);
|
||||
|
||||
/* Wraps llvm::Module::addLibrary(name). */
|
||||
void LLVMModuleAddLibrary(LLVMModuleRef module, const char *name);
|
||||
|
||||
/* Wraps llvm::Type::print(). Dispose the returned string after use, via
|
||||
* LLVMDisposeMessage(). */
|
||||
char *LLVMDumpTypeToString(LLVMTypeRef type);
|
||||
|
||||
/* Wraps llvm::Value::print(). Dispose the returned string after use, via
|
||||
* LLVMDisposeMessage(). */
|
||||
char *LLVMDumpValueToString(LLVMValueRef Val);
|
||||
|
||||
/* Wraps llvm::IRBuilder::CreateRet(). */
|
||||
LLVMValueRef LLVMBuildRetMultiple(LLVMBuilderRef bulder, LLVMValueRef *values,
|
||||
unsigned n_values);
|
||||
|
||||
/* Wraps llvm::IRBuilder::CreateGetResult(). */
|
||||
LLVMValueRef LLVMBuildGetResult(LLVMBuilderRef builder, LLVMValueRef value,
|
||||
unsigned index, const char *name);
|
||||
|
||||
/* Wraps llvm::Value::getValueID(). */
|
||||
unsigned LLVMValueGetID(LLVMValueRef value);
|
||||
|
||||
/* Wraps llvm::Value::getNumUses(). */
|
||||
unsigned LLVMValueGetNumUses(LLVMValueRef value);
|
||||
|
||||
/* Wraps llvm::Value::use_{begin,end}. Allocates LLVMValueRef's as
|
||||
* required. Number of objects are returned as return value. If that is
|
||||
* greater than zero, the pointer given out must be freed by a
|
||||
* subsequent call to LLVMDisposeValueRefArray(). */
|
||||
unsigned LLVMValueGetUses(LLVMValueRef value, LLVMValueRef **refs);
|
||||
|
||||
/* See above. */
|
||||
void LLVMDisposeValueRefArray(LLVMValueRef *refs);
|
||||
|
||||
/* Wraps llvm:User::getNumOperands(). */
|
||||
unsigned LLVMUserGetNumOperands(LLVMValueRef user);
|
||||
|
||||
/* Wraps llvm:User::getOperand(). */
|
||||
LLVMValueRef LLVMUserGetOperand(LLVMValueRef user, unsigned idx);
|
||||
|
||||
/* Wraps llvm::ConstantExpr::getVICmp(). */
|
||||
LLVMValueRef LLVMConstVICmp(LLVMIntPredicate predicate, LLVMValueRef lhs,
|
||||
LLVMValueRef rhs);
|
||||
|
||||
/* Wraps llvm::ConstantExpr::getVFCmp(). */
|
||||
LLVMValueRef LLVMConstVFCmp(LLVMRealPredicate predicate, LLVMValueRef lhs,
|
||||
LLVMValueRef rhs);
|
||||
|
||||
/* Wraps llvm::IRBuilder::CreateVICmp(). */
|
||||
LLVMValueRef LLVMBuildVICmp(LLVMBuilderRef builder, LLVMIntPredicate predicate,
|
||||
LLVMValueRef lhs, LLVMValueRef rhs, const char *name);
|
||||
|
||||
/* Wraps llvm::IRBuilder::CreateVFCmp(). */
|
||||
LLVMValueRef LLVMBuildVFCmp(LLVMBuilderRef builder, LLVMRealPredicate predicate,
|
||||
LLVMValueRef lhs, LLVMValueRef rhs, const char *name);
|
||||
|
||||
/* Wraps llvm::Intrinsic::getDeclaration(). */
|
||||
LLVMValueRef LLVMGetIntrinsic(LLVMModuleRef builder, int id,
|
||||
LLVMTypeRef *types, unsigned n_types);
|
||||
|
||||
/* Wraps llvm::Function::doesNotThrow(). */
|
||||
unsigned LLVMGetDoesNotThrow(LLVMValueRef fn);
|
||||
|
||||
/* Wraps llvm::Function::setDoesNotThrow(). */
|
||||
void LLVMSetDoesNotThrow(LLVMValueRef fn, int DoesNotThrow);
|
||||
|
||||
/* Wraps llvm::Module::getPointerSize(). */
|
||||
unsigned LLVMModuleGetPointerSize(LLVMModuleRef module);
|
||||
|
||||
/* Wraps llvm::Module::getOrInsertFunction(). */
|
||||
LLVMValueRef LLVMModuleGetOrInsertFunction(LLVMModuleRef module,
|
||||
const char *name, LLVMTypeRef function_type);
|
||||
|
||||
/* Wraps llvm::GlobalVariable::hasInitializer(). */
|
||||
int LLVMHasInitializer(LLVMValueRef global_var);
|
||||
|
||||
/* The following functions wrap various llvm::Instruction::isXXX() functions.
|
||||
* All of them take an instruction and return 0 (isXXX returned false) or 1
|
||||
* (isXXX returned false). */
|
||||
unsigned LLVMInstIsTerminator (LLVMValueRef inst);
|
||||
unsigned LLVMInstIsBinaryOp (LLVMValueRef inst);
|
||||
unsigned LLVMInstIsShift (LLVMValueRef inst);
|
||||
unsigned LLVMInstIsCast (LLVMValueRef inst);
|
||||
unsigned LLVMInstIsLogicalShift (LLVMValueRef inst);
|
||||
unsigned LLVMInstIsArithmeticShift (LLVMValueRef inst);
|
||||
unsigned LLVMInstIsAssociative (LLVMValueRef inst);
|
||||
unsigned LLVMInstIsCommutative (LLVMValueRef inst);
|
||||
unsigned LLVMInstIsTrapping (LLVMValueRef inst);
|
||||
|
||||
/* As above, but these are wrap methods from subclasses of Instruction. */
|
||||
unsigned LLVMInstIsVolatile (LLVMValueRef inst);
|
||||
|
||||
/* Wraps llvm::Instruction::getOpcodeName(). */
|
||||
const char *LLVMInstGetOpcodeName(LLVMValueRef inst);
|
||||
|
||||
/* Wraps llvm::Instruction::getOpcode(). */
|
||||
unsigned LLVMInstGetOpcode(LLVMValueRef inst);
|
||||
|
||||
/* Wraps llvm::CmpInst::getPredicate(). */
|
||||
unsigned LLVMCmpInstGetPredicate(LLVMValueRef cmpinst);
|
||||
|
||||
/* Wraps llvm::CallSite::getCalledFunction.
|
||||
*/
|
||||
LLVMValueRef LLVMInstGetCalledFunction(LLVMValueRef inst);
|
||||
|
||||
/* Wraps llvm::CallSite::setCalledFunction.
|
||||
*/
|
||||
void LLVMInstSetCalledFunction(LLVMValueRef inst, LLVMValueRef fn);
|
||||
|
||||
/* Wraps llvm::ParseAssemblyString(). Returns a module reference or NULL (with
|
||||
* `out' pointing to an error message). Dispose error message after use, via
|
||||
* LLVMDisposeMessage(). */
|
||||
LLVMModuleRef LLVMGetModuleFromAssembly(const char *asmtxt, char **out);
|
||||
|
||||
/* Wraps llvm::ParseBitcodeFile(). Returns a module reference or NULL (with
|
||||
* `out' pointing to an error message). Dispose error message after use, via
|
||||
* LLVMDisposeMessage(). */
|
||||
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, int mode,
|
||||
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, size_t *len);
|
||||
|
||||
/* Wraps llvm::sys::DynamicLibrary::LoadLibraryPermanently(). Returns 0 on
|
||||
* failure (with errmsg filled in) and 1 on success. Dispose error message after
|
||||
* use, via LLVMDisposeMessage(). */
|
||||
unsigned LLVMLoadLibraryPermanently(const char* filename, char **errmsg);
|
||||
|
||||
/* Wraps llvm::ExecutionEngine::DisableLazyCompilation(bool)
|
||||
*/
|
||||
void LLVMExecutionEngineDisableLazyCompilation(LLVMExecutionEngineRef ee,
|
||||
int flag);
|
||||
|
||||
/* Wraps llvm::ExecutionEngine::getPointerToFunction(). Returns a pointer
|
||||
* to the JITted function. */
|
||||
void *LLVMGetPointerToFunction(LLVMExecutionEngineRef ee, LLVMValueRef fn);
|
||||
|
||||
/* Wraps llvm::InlineFunction(). Inlines a function. C is the call
|
||||
* instruction, created by LLVMBuildCall. Even if it fails, the Function
|
||||
* containing the call is still in a proper state (not changed).
|
||||
*/
|
||||
int LLVMInlineFunction(LLVMValueRef call);
|
||||
|
||||
/* Wraps llvm::getAlignmentFromAttrs from Attributes.h. Compliments the
|
||||
* already available LLVMSetParamAlignment(). */
|
||||
unsigned LLVMGetParamAlignment(LLVMValueRef arg);
|
||||
|
||||
/* Passes. Some passes are used directly from LLVM-C, rest are declared
|
||||
* here. */
|
||||
|
||||
/*
|
||||
#define declare_pass(P) \
|
||||
void LLVMAdd ## P ## Pass (LLVMPassManagerRef PM);
|
||||
|
||||
declare_pass( AAEval )
|
||||
declare_pass( AliasAnalysisCounter )
|
||||
declare_pass( AlwaysInliner )
|
||||
declare_pass( BasicAliasAnalysis )
|
||||
declare_pass( BlockPlacement )
|
||||
declare_pass( BreakCriticalEdges )
|
||||
declare_pass( CodeGenPrepare )
|
||||
declare_pass( DbgInfoPrinter )
|
||||
declare_pass( DeadCodeElimination )
|
||||
declare_pass( DeadInstElimination )
|
||||
declare_pass( DemoteRegisterToMemory )
|
||||
declare_pass( DomOnlyPrinter )
|
||||
declare_pass( DomOnlyViewer )
|
||||
declare_pass( DomPrinter )
|
||||
declare_pass( DomViewer )
|
||||
declare_pass( EdgeProfiler )
|
||||
//declare_pass( GEPSplitter )
|
||||
declare_pass( GlobalsModRef )
|
||||
declare_pass( InstCount )
|
||||
declare_pass( InstructionNamer )
|
||||
declare_pass( LazyValueInfo )
|
||||
declare_pass( LCSSA )
|
||||
//declare_pass( LiveValues )
|
||||
declare_pass( LoopDependenceAnalysis )
|
||||
declare_pass( LoopExtractor )
|
||||
declare_pass( LoopSimplify )
|
||||
declare_pass( LoopStrengthReduce )
|
||||
declare_pass( LowerInvoke )
|
||||
declare_pass( LowerSwitch )
|
||||
declare_pass( MergeFunctions )
|
||||
declare_pass( NoAA )
|
||||
declare_pass( NoProfileInfo )
|
||||
declare_pass( OptimalEdgeProfiler )
|
||||
declare_pass( PartialInlining )
|
||||
//declare_pass( PartialSpecialization )
|
||||
declare_pass( PostDomOnlyPrinter )
|
||||
declare_pass( PostDomOnlyViewer )
|
||||
declare_pass( PostDomPrinter )
|
||||
declare_pass( PostDomViewer )
|
||||
declare_pass( ProfileEstimator )
|
||||
declare_pass( ProfileLoader )
|
||||
declare_pass( ProfileVerifier )
|
||||
declare_pass( ScalarEvolutionAliasAnalysis )
|
||||
declare_pass( SimplifyHalfPowrLibCalls )
|
||||
declare_pass( SingleLoopExtractor )
|
||||
declare_pass( StripNonDebugSymbols )
|
||||
declare_pass( StructRetPromotion )
|
||||
declare_pass( TailDuplication )
|
||||
declare_pass( UnifyFunctionExitNodes )
|
||||
|
||||
declare_pass( Internalize2 )
|
||||
*/
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
|
||||
#endif /* LLVM_PY_EXTRA_H */
|
||||
|
||||
|
|
@ -1,31 +0,0 @@
|
|||
#ifndef LLVM_C_EXTRA_H_
|
||||
#define LLVM_C_EXTRA_H_
|
||||
|
||||
#include <llvm-c/Core.h>
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
// Resurrect from llvm-c/Core.h
|
||||
#define DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref) \
|
||||
inline ty *unwrap(ref P) { \
|
||||
return reinterpret_cast<ty*>(P); \
|
||||
} \
|
||||
\
|
||||
inline ref wrap(const ty *P) { \
|
||||
return reinterpret_cast<ref>(const_cast<ty*>(P)); \
|
||||
}
|
||||
|
||||
typedef struct LLVMOpaqueEngineBuilder *LLVMEngineBuilderRef;
|
||||
typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef;
|
||||
typedef struct LLVMOpaqueNamedMD *LLVMNamedMDRef;
|
||||
typedef struct LLVMOpaquePass *LLVMPassRef;
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif //LLVM_C_EXTRA_H_
|
||||
|
||||
417
llvm/passes.py
417
llvm/passes.py
|
|
@ -1,417 +0,0 @@
|
|||
#
|
||||
# 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.
|
||||
#
|
||||
|
||||
"""Pass managers and passes.
|
||||
|
||||
This module provides the LLVM pass managers and the passes themselves.
|
||||
All transformation passes listed at http://www.llvm.org/docs/Passes.html
|
||||
are available.
|
||||
"""
|
||||
|
||||
import llvm # top-level, for common stuff
|
||||
import llvm.core as core # module, function etc.
|
||||
import llvm._core as _core # C wrappers
|
||||
import llvm._util as _util # Utility functions
|
||||
|
||||
import warnings
|
||||
#===----------------------------------------------------------------------===
|
||||
# Pass manager builder
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
class PassManagerBuilder(object):
|
||||
@staticmethod
|
||||
def new():
|
||||
return PassManagerBuilder(_core.LLVMPassManagerBuilderCreate())
|
||||
|
||||
def __init__(self, ptr):
|
||||
self.ptr = ptr
|
||||
|
||||
def __del__(self):
|
||||
_core.LLVMPassManagerBuilderDispose(self.ptr)
|
||||
|
||||
def populate(self, pm):
|
||||
if isinstance(pm, FunctionPassManager):
|
||||
return _core.LLVMPassManagerBuilderPopulateFunctionPassManager(
|
||||
self.ptr, pm.ptr)
|
||||
else:
|
||||
return _core.LLVMPassManagerBuilderPopulateModulePassManager(
|
||||
self.ptr, pm.ptr)
|
||||
|
||||
|
||||
def _set_opt_level(self, optlevel):
|
||||
_core.LLVMPassManagerBuilderSetOptLevel(self.ptr, optlevel)
|
||||
|
||||
def _get_opt_level(self):
|
||||
return _core.LLVMPassManagerBuilderGetOptLevel(self.ptr)
|
||||
|
||||
opt_level = property(_get_opt_level, _set_opt_level)
|
||||
|
||||
def _set_size_level(self, sizelevel):
|
||||
_core.LLVMPassManagerBuilderSetSizeLevel(self.ptr, sizelevel)
|
||||
|
||||
def _get_size_level(self):
|
||||
return _core.LLVMPassManagerBuilderGetSizeLevel(self.ptr)
|
||||
|
||||
size_level = property(_get_size_level, _set_size_level)
|
||||
|
||||
def _set_vectorize(self, enable):
|
||||
_core.LLVMPassManagerBuilderSetVectorize(self.ptr, int(bool(enable)))
|
||||
|
||||
def _get_vectorize(self):
|
||||
return bool(_core.LLVMPassManagerBuilderGetVectorize(self.ptr))
|
||||
|
||||
vectorize = property(_get_vectorize, _set_vectorize)
|
||||
|
||||
def _set_loop_vectorize(self, enable):
|
||||
if llvm.version >= (3, 2):
|
||||
_core.LLVMPassManagerBuilderSetLoopVectorize(self.ptr,
|
||||
int(bool(enable)))
|
||||
elif enable:
|
||||
warnings.warn("Ignored. LLVM-3.1 & prior do not support loop vectorizer.")
|
||||
|
||||
def _get_loop_vectorize(self):
|
||||
try:
|
||||
return bool(_core.LLVMPassManagerBuilderGetLoopVectorize(self.ptr))
|
||||
except AttributeError:
|
||||
return False
|
||||
|
||||
loop_vectorize = property(_get_loop_vectorize, _set_loop_vectorize)
|
||||
|
||||
def _set_disable_unit_at_a_time(self, disable):
|
||||
return _core.LLVMPassManagerBuilderSetDisableUnitAtATime(
|
||||
self.ptr, disable)
|
||||
|
||||
def _get_disable_unit_at_a_time(self):
|
||||
return _core.LLVMPassManagerBuilderGetDisableUnitAtATime(
|
||||
self.ptr)
|
||||
|
||||
disable_unit_at_a_time = property(_get_disable_unit_at_a_time,
|
||||
_set_disable_unit_at_a_time)
|
||||
|
||||
def _set_disable_unroll_loops(self, disable):
|
||||
return _core.LLVMPassManagerBuilderGetDisableUnrollLoops(
|
||||
self.ptr, disable)
|
||||
|
||||
def _get_disable_unroll_loops(self):
|
||||
return _core.LLVMPassManagerBuilderGetDisableUnrollLoops(self.ptr)
|
||||
|
||||
disable_unroll_loops = property(_get_disable_unroll_loops,
|
||||
_set_disable_unroll_loops)
|
||||
|
||||
def _set_disable_simplify_lib_calls(self, disable):
|
||||
return _core.LLVMPassManagerBuilderGetDisableSimplifyLibCalls(
|
||||
self.ptr, disable)
|
||||
|
||||
def _get_disable_simplify_lib_calls(self):
|
||||
return _core.LLVMPassManagerBuilderGetDisableSimplifyLibCalls(self.ptr)
|
||||
|
||||
disable_simplify_lib_calls = property(_get_disable_simplify_lib_calls,
|
||||
_set_disable_simplify_lib_calls)
|
||||
|
||||
def use_inliner_with_threshold(self, threshold):
|
||||
_core.LLVMPassManagerBuilderUseInlinerWithThreshold(self.ptr, threshold)
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Pass manager
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
class PassManager(object):
|
||||
|
||||
@staticmethod
|
||||
def new():
|
||||
return PassManager(_core.LLVMCreatePassManager())
|
||||
|
||||
def __init__(self, ptr):
|
||||
self.ptr = ptr
|
||||
|
||||
def __del__(self):
|
||||
_core.LLVMDisposePassManager(self.ptr)
|
||||
|
||||
def add(self, pass_obj):
|
||||
'''Add a pass to the pass manager.
|
||||
|
||||
pass_obj --- Either a Pass instance, a string name of a pass
|
||||
'''
|
||||
if isinstance(pass_obj, Pass):
|
||||
_util.check_is_unowned(pass_obj)
|
||||
_core.LLVMAddPass(self.ptr, pass_obj.ptr)
|
||||
pass_obj._own(self) # PassManager owns the pass
|
||||
elif _util.isstring(pass_obj):
|
||||
self._add_pass(pass_obj)
|
||||
else:
|
||||
raise llvm.LLVMException("invalid pass_id (%s)" % pass_obj)
|
||||
|
||||
def _add_pass(self, pass_name):
|
||||
status = _core.LLVMAddPassByName(self.ptr, pass_name)
|
||||
if not status:
|
||||
assert pass_name not in PASSES, "Registered but not found?"
|
||||
raise llvm.LLVMException('Invalid pass name "%s"' % pass_name)
|
||||
|
||||
def run(self, module):
|
||||
core.check_is_module(module)
|
||||
return _core.LLVMRunPassManager(self.ptr, module.ptr)
|
||||
|
||||
class FunctionPassManager(PassManager):
|
||||
|
||||
@staticmethod
|
||||
def new(module):
|
||||
core.check_is_module(module)
|
||||
ptr = _core.LLVMCreateFunctionPassManagerForModule(module.ptr)
|
||||
return FunctionPassManager(ptr)
|
||||
|
||||
def __init__(self, ptr):
|
||||
PassManager.__init__(self, ptr)
|
||||
|
||||
def initialize(self):
|
||||
_core.LLVMInitializeFunctionPassManager(self.ptr)
|
||||
|
||||
def run(self, fn):
|
||||
core.check_is_function(fn)
|
||||
return _core.LLVMRunFunctionPassManager(self.ptr, fn.ptr)
|
||||
|
||||
def finalize(self):
|
||||
_core.LLVMFinalizeFunctionPassManager(self.ptr)
|
||||
|
||||
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Passes
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
class Pass(llvm.Ownable):
|
||||
'''Pass Inferface
|
||||
'''
|
||||
def __init__(self, ptr):
|
||||
llvm.Ownable.__init__(self, ptr, _core.LLVMDisposePass)
|
||||
self.__name = ''
|
||||
|
||||
@staticmethod
|
||||
def new(name):
|
||||
'''Create a new pass by name.
|
||||
|
||||
Note: Not all pass has a default constructor. LLVM will kill
|
||||
the process if an the pass requires arguments to construct.
|
||||
The error cannot be caught.
|
||||
'''
|
||||
ptr = _core.LLVMCreatePassByName(name)
|
||||
p = Pass(ptr)
|
||||
p.__name = name
|
||||
return p
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
'''The name used in PassRegistry.
|
||||
'''
|
||||
return self.__name
|
||||
|
||||
@property
|
||||
def description(self):
|
||||
return _core.LLVMGetPassName(self.ptr)
|
||||
|
||||
def dump(self):
|
||||
return _core.LLVMPassDump(self.ptr)
|
||||
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Target data
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
class TargetData(Pass):
|
||||
|
||||
@staticmethod
|
||||
def new(strrep):
|
||||
return TargetData(_core.LLVMCreateTargetData(strrep))
|
||||
|
||||
def clone(self):
|
||||
return TargetData.new(str(self))
|
||||
|
||||
def __str__(self):
|
||||
return _core.LLVMTargetDataAsString(self.ptr)
|
||||
|
||||
@property
|
||||
def byte_order(self):
|
||||
return _core.LLVMByteOrder(self.ptr)
|
||||
|
||||
@property
|
||||
def pointer_size(self):
|
||||
return _core.LLVMPointerSize(self.ptr)
|
||||
|
||||
@property
|
||||
def target_integer_type(self):
|
||||
ptr = _core.LLVMIntPtrType(self.ptr);
|
||||
return core.IntegerType(ptr, core.TYPE_INTEGER)
|
||||
|
||||
def size(self, ty):
|
||||
core.check_is_type(ty)
|
||||
return _core.LLVMSizeOfTypeInBits(self.ptr, ty.ptr)
|
||||
|
||||
def store_size(self, ty):
|
||||
core.check_is_type(ty)
|
||||
return _core.LLVMStoreSizeOfType(self.ptr, ty.ptr)
|
||||
|
||||
def abi_size(self, ty):
|
||||
core.check_is_type(ty)
|
||||
return _core.LLVMABISizeOfType(self.ptr, ty.ptr)
|
||||
|
||||
def abi_alignment(self, ty):
|
||||
core.check_is_type(ty)
|
||||
return _core.LLVMABIAlignmentOfType(self.ptr, ty.ptr)
|
||||
|
||||
def callframe_alignment(self, ty):
|
||||
core.check_is_type(ty)
|
||||
return _core.LLVMCallFrameAlignmentOfType(self.ptr, ty.ptr)
|
||||
|
||||
def preferred_alignment(self, ty_or_gv):
|
||||
if isinstance(ty_or_gv, core.Type):
|
||||
return _core.LLVMPreferredAlignmentOfType(self.ptr,
|
||||
ty_or_gv.ptr)
|
||||
elif isinstance(ty_or_gv, core.GlobalVariable):
|
||||
return _core.LLVMPreferredAlignmentOfGlobal(self.ptr,
|
||||
ty_or_gv.ptr)
|
||||
else:
|
||||
raise core.LLVMException("argument is neither a type nor a global variable")
|
||||
|
||||
def element_at_offset(self, ty, ofs):
|
||||
core.check_is_type_struct(ty)
|
||||
ofs = int(ofs) # ofs is unsigned long long
|
||||
return _core.LLVMElementAtOffset(self.ptr, ty.ptr, ofs)
|
||||
|
||||
def offset_of_element(self, ty, el):
|
||||
core.check_is_type_struct(ty)
|
||||
el = int(el) # el should be an int
|
||||
return _core.LLVMOffsetOfElement(self.ptr, ty.ptr, el)
|
||||
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Target Library Info
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
class TargetLibraryInfo(Pass):
|
||||
@staticmethod
|
||||
def new(triple):
|
||||
ptr = _core.LLVMCreateTargetLibraryInfo(triple)
|
||||
return TargetLibraryInfo(ptr)
|
||||
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Target Transform Info
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
class TargetTransformInfo(Pass):
|
||||
@staticmethod
|
||||
def new(targetmachine):
|
||||
llvm.require_version_at_least(3, 2)
|
||||
ptr = _core.LLVMCreateTargetTransformInfo(targetmachine.ptr)
|
||||
return TargetTransformInfo(ptr)
|
||||
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Helpers
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
def build_pass_managers(tm, opt=2, loop_vectorize=False, vectorize=False,
|
||||
inline_threshold=2000, pm=True, fpm=True, mod=None):
|
||||
'''
|
||||
tm --- The TargetMachine for which the passes are optimizing for.
|
||||
The TargetMachine must stay alive until the pass managers
|
||||
are removed.
|
||||
opt --- [0-3] Optimization level. Default to 2.
|
||||
loop_vectorize --- [boolean] Whether to use loop-vectorizer.
|
||||
vectorize --- [boolean] Whether to use basic-block vectorizer.
|
||||
inline_threshold --- [int] Threshold for the inliner.
|
||||
features --- [str] CPU feature string.
|
||||
pm --- [boolean] Whether to build a module-level pass-manager.
|
||||
fpm --- [boolean] Whether to build a function-level pass-manager.
|
||||
mod --- [Module] The module object for the FunctionPassManager.
|
||||
'''
|
||||
if pm:
|
||||
pm = PassManager.new()
|
||||
if fpm:
|
||||
if not mod:
|
||||
raise TypeError("Keyword 'mod' must be defined")
|
||||
fpm = FunctionPassManager.new(mod)
|
||||
|
||||
# Populate PassManagers with target specific passes
|
||||
pmb = PassManagerBuilder.new()
|
||||
pmb.opt_level = opt
|
||||
pmb.vectorize = vectorize
|
||||
pmb.loop_vectorize = loop_vectorize
|
||||
if inline_threshold:
|
||||
pmb.use_inliner_with_threshold(inline_threshold)
|
||||
if pm:
|
||||
pm.add(tm.target_data.clone())
|
||||
pm.add(TargetLibraryInfo.new(tm.triple))
|
||||
if llvm.version >= (3, 2):
|
||||
pm.add(TargetTransformInfo.new(tm))
|
||||
pmb.populate(pm)
|
||||
|
||||
if fpm:
|
||||
fpm.add(tm.target_data)
|
||||
fpm.add(TargetLibraryInfo.new(tm.triple))
|
||||
if llvm.version >= (3, 2):
|
||||
fpm.add(TargetTransformInfo.new(tm))
|
||||
pmb.populate(fpm)
|
||||
fpm.initialize()
|
||||
|
||||
from collections import namedtuple
|
||||
return namedtuple('passmanagers', ['pm', 'fpm'])(pm=pm, fpm=fpm)
|
||||
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# Misc.
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
# Intialize passes
|
||||
PASSES = None
|
||||
|
||||
def _dump_all_passes():
|
||||
passes_sep_by_line = _core.LLVMDumpPasses()
|
||||
strip = lambda S : S.strip()
|
||||
for line in passes_sep_by_line.splitlines():
|
||||
passarg, passname = map(strip, line.split('\t', 1))
|
||||
if passarg:
|
||||
yield passarg, passname
|
||||
|
||||
def _initialize_passes():
|
||||
global PASSES
|
||||
_core.LLVMInitializePasses()
|
||||
PASSES = dict(_dump_all_passes())
|
||||
|
||||
# build globals
|
||||
def transform(name):
|
||||
return "PASS_%s" % (name.upper().replace('-', '_'))
|
||||
|
||||
global_symbols = globals()
|
||||
for i in PASSES:
|
||||
assert i not in global_symbols
|
||||
global_symbols[transform(i)] = i
|
||||
|
||||
_initialize_passes()
|
||||
|
||||
|
|
@ -1,973 +0,0 @@
|
|||
--- .\setup-win32.py (original)
|
||||
+++ .\setup-win32.py (refactored)
|
||||
@@ -145,10 +145,10 @@
|
||||
|
||||
# get llvm config
|
||||
llvm_dir, llvm_build_dir, is_good = get_llvm_config()
|
||||
- print "Using llvm-dir=" + llvm_dir + " and llvm-build-dir=" + llvm_build_dir
|
||||
+ print("Using llvm-dir=" + llvm_dir + " and llvm-build-dir=" + llvm_build_dir)
|
||||
if not is_good:
|
||||
- print "Cannot find llvm-dir or llvm-build-dir"
|
||||
- print "Try again with --llvm-dir=/path/to/llvm-top-dir --llvm-build-dir=/path/to/llvm/cmake/dir."
|
||||
+ print("Cannot find llvm-dir or llvm-build-dir")
|
||||
+ print("Try again with --llvm-dir=/path/to/llvm-top-dir --llvm-build-dir=/path/to/llvm/cmake/dir.")
|
||||
return 1
|
||||
|
||||
# setup
|
||||
--- .\setup.py (original)
|
||||
+++ .\setup.py (refactored)
|
||||
@@ -120,10 +120,10 @@
|
||||
# get llvm config
|
||||
llvm_config, is_good = get_llvm_config()
|
||||
if is_good:
|
||||
- print "Using llvm-config=" + llvm_config
|
||||
+ 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."
|
||||
+ print("Cannot invoke llvm-config (tried '%s')." % llvm_config)
|
||||
+ print("Try again with --llvm-config=/path/to/llvm-config.")
|
||||
return 1
|
||||
|
||||
# setup
|
||||
--- .\llvm\__init__.py (original)
|
||||
+++ .\llvm\__init__.py (refactored)
|
||||
@@ -68,12 +68,12 @@
|
||||
|
||||
def _own(self, owner):
|
||||
if self.owner:
|
||||
- raise LLVMException, "object already owned"
|
||||
+ raise LLVMException("object already owned")
|
||||
self.owner = owner
|
||||
|
||||
def _disown(self):
|
||||
if not self.owner:
|
||||
- raise LLVMException, "not owned"
|
||||
+ raise LLVMException("not owned")
|
||||
self.owner = None
|
||||
|
||||
def __del__(self):
|
||||
@@ -135,15 +135,13 @@
|
||||
# Cacheables
|
||||
#===----------------------------------------------------------------------===
|
||||
|
||||
-class Cacheable(object):
|
||||
+class Cacheable(object, metaclass=_ObjectCache):
|
||||
"""Objects that can be cached.
|
||||
|
||||
Objects that wrap a PyCObject are cached to avoid "aliasing", i.e.,
|
||||
two Python objects each containing a PyCObject which internally points
|
||||
to the same C pointer."""
|
||||
|
||||
- __metaclass__ = _ObjectCache
|
||||
-
|
||||
def forget(self):
|
||||
_ObjectCache.forget(self)
|
||||
|
||||
--- .\llvm\_util.py (original)
|
||||
+++ .\llvm\_util.py (refactored)
|
||||
@@ -45,11 +45,11 @@
|
||||
if not isinstance(obj, typ):
|
||||
typ_str = typ.__name__
|
||||
msg = "argument not an instance of llvm.core.%s" % typ_str
|
||||
- raise TypeError, msg
|
||||
+ raise TypeError(msg)
|
||||
|
||||
def check_is_unowned(ownable):
|
||||
if ownable.owner:
|
||||
- raise llvm.LLVMException, "object is already owned"
|
||||
+ raise llvm.LLVMException("object is already owned")
|
||||
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
--- .\llvm\core.py (original)
|
||||
+++ .\llvm\core.py (refactored)
|
||||
@@ -297,7 +297,7 @@
|
||||
if isinstance(typ, PointerType) and \
|
||||
isinstance(typ.pointee, FunctionType):
|
||||
return
|
||||
- raise TypeError, "argument is neither a function nor a function pointer"
|
||||
+ raise TypeError("argument is neither a function nor a function pointer")
|
||||
|
||||
def _to_int(v):
|
||||
if v:
|
||||
@@ -341,9 +341,9 @@
|
||||
data = fileobj.read()
|
||||
ret = _core.LLVMGetModuleFromBitcode(data)
|
||||
if not ret:
|
||||
- raise llvm.LLVMException, "Unable to create module from bitcode"
|
||||
+ raise llvm.LLVMException("Unable to create module from bitcode")
|
||||
elif isinstance(ret, str):
|
||||
- raise llvm.LLVMException, ret
|
||||
+ raise llvm.LLVMException(ret)
|
||||
else:
|
||||
return Module(ret)
|
||||
|
||||
@@ -355,10 +355,9 @@
|
||||
data = fileobj.read()
|
||||
ret = _core.LLVMGetModuleFromAssembly(data)
|
||||
if not ret:
|
||||
- raise llvm.LLVMException, \
|
||||
- "Unable to create module from assembly"
|
||||
+ raise llvm.LLVMException("Unable to create module from assembly")
|
||||
elif isinstance(ret, str):
|
||||
- raise llvm.LLVMException, ret
|
||||
+ raise llvm.LLVMException(ret)
|
||||
else:
|
||||
return Module(ret)
|
||||
|
||||
@@ -437,7 +436,7 @@
|
||||
other.forget() # remove it from object cache
|
||||
ret = _core.LLVMLinkModules(self.ptr, other.ptr)
|
||||
if isinstance(ret, str):
|
||||
- raise llvm.LLVMException, ret
|
||||
+ raise llvm.LLVMException(ret)
|
||||
# Do not try to destroy the other module's llvm::Module*.
|
||||
other._own(llvm.DummyOwner())
|
||||
|
||||
@@ -506,7 +505,7 @@
|
||||
error."""
|
||||
ret = _core.LLVMVerifyModule(self.ptr)
|
||||
if ret != "":
|
||||
- raise llvm.LLVMException, ret
|
||||
+ raise llvm.LLVMException(ret)
|
||||
|
||||
def to_bitcode(self, fileobj):
|
||||
"""Write bitcode representation of module to given file-like
|
||||
@@ -514,7 +513,7 @@
|
||||
|
||||
data = _core.LLVMGetBitcodeFromModule(self.ptr)
|
||||
if not data:
|
||||
- raise llvm.LLVMException, "Unable to create bitcode"
|
||||
+ raise llvm.LLVMException("Unable to create bitcode")
|
||||
fileobj.write(data)
|
||||
|
||||
|
||||
@@ -1236,7 +1235,7 @@
|
||||
check_is_module(module)
|
||||
ptr = _core.LLVMGetNamedGlobal(module.ptr, name)
|
||||
if not ptr:
|
||||
- raise llvm.LLVMException, ("no global named `%s`" % name)
|
||||
+ raise llvm.LLVMException("no global named `%s`" % name)
|
||||
return _make_value(ptr)
|
||||
|
||||
def delete(self):
|
||||
@@ -1307,7 +1306,7 @@
|
||||
check_is_module(module)
|
||||
ptr = _core.LLVMGetNamedFunction(module.ptr, name)
|
||||
if not ptr:
|
||||
- raise llvm.LLVMException, ("no function named `%s`" % name)
|
||||
+ raise llvm.LLVMException("no function named `%s`" % name)
|
||||
return _make_value(ptr)
|
||||
|
||||
@staticmethod
|
||||
@@ -2006,7 +2005,7 @@
|
||||
|
||||
ret = _core.LLVMLoadLibraryPermanently(filename)
|
||||
if isinstance(ret, str):
|
||||
- raise llvm.LLVMException, ret
|
||||
+ raise llvm.LLVMException(ret)
|
||||
|
||||
def inline_function(call):
|
||||
check_is_value(call)
|
||||
--- .\llvm\ee.py (original)
|
||||
+++ .\llvm\ee.py (refactored)
|
||||
@@ -103,12 +103,11 @@
|
||||
return _core.LLVMPreferredAlignmentOfGlobal(self.ptr,
|
||||
ty_or_gv.ptr)
|
||||
else:
|
||||
- raise core.LLVMException, \
|
||||
- "argument is neither a type nor a global variable"
|
||||
+ raise core.LLVMException("argument is neither a type nor a global variable")
|
||||
|
||||
def element_at_offset(self, ty, ofs):
|
||||
core.check_is_type_struct(ty)
|
||||
- ofs = long(ofs) # ofs is unsigned long long
|
||||
+ ofs = int(ofs) # ofs is unsigned long long
|
||||
return _core.LLVMElementAtOffset(self.ptr, ty.ptr, ofs)
|
||||
|
||||
def offset_of_element(self, ty, el):
|
||||
@@ -185,7 +184,7 @@
|
||||
_util.check_is_unowned(module)
|
||||
ret = _core.LLVMCreateExecutionEngine(module.ptr, int(force_interpreter))
|
||||
if isinstance(ret, str):
|
||||
- raise llvm.LLVMException, ret
|
||||
+ raise llvm.LLVMException(ret)
|
||||
return ExecutionEngine(ret, module)
|
||||
|
||||
def __init__(self, ptr, module):
|
||||
@@ -223,10 +222,10 @@
|
||||
def remove_module(self, module):
|
||||
core.check_is_module(module)
|
||||
if module.owner != self:
|
||||
- raise llvm.LLVMException, "module is not owned by self"
|
||||
+ raise llvm.LLVMException("module is not owned by self")
|
||||
ret = _core.LLVMRemoveModule2(self.ptr, module.ptr)
|
||||
if isinstance(ret, str):
|
||||
- raise llvm.LLVMException, ret
|
||||
+ raise llvm.LLVMException(ret)
|
||||
return core.Module(ret)
|
||||
|
||||
@property
|
||||
--- .\llvm\passes.py (original)
|
||||
+++ .\llvm\passes.py (refactored)
|
||||
@@ -245,8 +245,7 @@
|
||||
elif tgt_data_or_pass_id in _pass_creator:
|
||||
self._add_pass(tgt_data_or_pass_id)
|
||||
else:
|
||||
- raise llvm.LLVMException, \
|
||||
- ("invalid pass_id (%s)" % str(tgt_data_or_pass_id))
|
||||
+ raise llvm.LLVMException("invalid pass_id (%s)" % str(tgt_data_or_pass_id))
|
||||
|
||||
def _add_target_data(self, tgt):
|
||||
_core.LLVMAddTargetData(tgt.ptr, self.ptr)
|
||||
--- .\test\JITTutorial1.py (original)
|
||||
+++ .\test\JITTutorial1.py (refactored)
|
||||
@@ -28,4 +28,4 @@
|
||||
|
||||
bldr.ret (tmp_2)
|
||||
|
||||
-print module
|
||||
+print(module)
|
||||
--- .\test\JITTutorial2.py (original)
|
||||
+++ .\test\JITTutorial2.py (refactored)
|
||||
@@ -47,4 +47,4 @@
|
||||
recur_2 = bldr.call (gcd, (x_sub_y, y,), "tmp")
|
||||
bldr.ret (recur_2)
|
||||
|
||||
-print module
|
||||
+print(module)
|
||||
--- .\test\asm.py (original)
|
||||
+++ .\test\asm.py (refactored)
|
||||
@@ -9,9 +9,9 @@
|
||||
|
||||
# write it's assembly representation to a file
|
||||
asm = str(m)
|
||||
-print >> file("/tmp/testasm.ll", "w"), asm
|
||||
+print(asm, file=file("/tmp/testasm.ll", "w"))
|
||||
|
||||
# read it back into a module
|
||||
m2 = Module.from_assembly(file("/tmp/testasm.ll"))
|
||||
-print m2
|
||||
+print(m2)
|
||||
|
||||
--- .\test\call-jit-ctypes.py (original)
|
||||
+++ .\test\call-jit-ctypes.py (refactored)
|
||||
@@ -42,7 +42,7 @@
|
||||
|
||||
if 0:
|
||||
# print the created module
|
||||
- print my_module
|
||||
+ print(my_module)
|
||||
|
||||
# compile the function
|
||||
ee = ExecutionEngine.new(my_module)
|
||||
--- .\test\example-jit.py (original)
|
||||
+++ .\test\example-jit.py (refactored)
|
||||
@@ -29,5 +29,5 @@
|
||||
retval = ee.run_function(f_sum, [arg1, arg2])
|
||||
|
||||
# The return value is also GenericValue. Let's print it.
|
||||
-print "returned", retval.as_int()
|
||||
+print("returned", retval.as_int())
|
||||
|
||||
--- .\test\example.py (original)
|
||||
+++ .\test\example.py (refactored)
|
||||
@@ -41,5 +41,5 @@
|
||||
|
||||
# We've completed the definition now! Let's see the LLVM assembly
|
||||
# language representation of what we've created:
|
||||
-print my_module
|
||||
+print(my_module)
|
||||
|
||||
--- .\test\intrinsic.py (original)
|
||||
+++ .\test\intrinsic.py (refactored)
|
||||
@@ -16,7 +16,7 @@
|
||||
val = Constant.int(Type.int(), 42)
|
||||
bswap = Function.intrinsic(mod, INTR_BSWAP, [Type.int()])
|
||||
b.call(bswap, [val])
|
||||
-print mod
|
||||
+print(mod)
|
||||
|
||||
# the output is:
|
||||
#
|
||||
@@ -50,7 +50,7 @@
|
||||
onemc2 = b.sub(one, cos2, "onemc2")
|
||||
sin = b.call(sqrt, [onemc2], "sin")
|
||||
b.ret(sin)
|
||||
-print mod
|
||||
+print(mod)
|
||||
|
||||
#
|
||||
# ; ModuleID = 'test'
|
||||
--- .\test\objcache.py (original)
|
||||
+++ .\test\objcache.py (refactored)
|
||||
@@ -4,17 +4,17 @@
|
||||
|
||||
def check(a, b):
|
||||
if a is b:
|
||||
- print "OK"
|
||||
+ print("OK")
|
||||
else:
|
||||
- print "FAIL"
|
||||
+ print("FAIL")
|
||||
|
||||
def check_isnot(a, b):
|
||||
if not (a is b):
|
||||
- print "OK"
|
||||
+ print("OK")
|
||||
else:
|
||||
- print "FAIL"
|
||||
+ print("FAIL")
|
||||
|
||||
-print "Testing module aliasing ..",
|
||||
+print("Testing module aliasing ..", end=' ')
|
||||
m1 = Module.new('a')
|
||||
t = Type.int()
|
||||
ft = Type.function(t, [t])
|
||||
@@ -22,75 +22,75 @@
|
||||
m2 = f1.module
|
||||
check(m1, m2)
|
||||
|
||||
-print "Testing global vairable aliasing 1 .. ",
|
||||
+print("Testing global vairable aliasing 1 .. ", end=' ')
|
||||
gv1 = GlobalVariable.new(m1, t, "gv")
|
||||
gv2 = GlobalVariable.get(m1, "gv")
|
||||
check(gv1, gv2)
|
||||
|
||||
-print "Testing global vairable aliasing 2 .. ",
|
||||
+print("Testing global vairable aliasing 2 .. ", end=' ')
|
||||
gv3 = m1.global_variables[0]
|
||||
check(gv1, gv3)
|
||||
|
||||
-print "Testing global vairable aliasing 3 .. ",
|
||||
+print("Testing global vairable aliasing 3 .. ", end=' ')
|
||||
gv2 = None
|
||||
gv3 = None
|
||||
gv1.delete()
|
||||
gv4 = GlobalVariable.new(m1, t, "gv")
|
||||
check_isnot(gv1, gv4)
|
||||
|
||||
-print "Testing function aliasing 1 ..",
|
||||
+print("Testing function aliasing 1 ..", end=' ')
|
||||
b1 = f1.append_basic_block('entry')
|
||||
f2 = b1.function
|
||||
check(f1, f2)
|
||||
|
||||
-print "Testing function aliasing 2 ..",
|
||||
+print("Testing function aliasing 2 ..", end=' ')
|
||||
f3 = m1.get_function_named("func")
|
||||
check(f1, f3)
|
||||
|
||||
-print "Testing function aliasing 3 ..",
|
||||
+print("Testing function aliasing 3 ..", end=' ')
|
||||
f4 = Function.get_or_insert(m1, ft, "func")
|
||||
check(f1, f4)
|
||||
|
||||
-print "Testing function aliasing 4 ..",
|
||||
+print("Testing function aliasing 4 ..", end=' ')
|
||||
f5 = Function.get(m1, "func")
|
||||
check(f1, f5)
|
||||
|
||||
-print "Testing function aliasing 5 ..",
|
||||
+print("Testing function aliasing 5 ..", end=' ')
|
||||
f6 = m1.get_or_insert_function(ft, "func")
|
||||
check(f1, f6)
|
||||
|
||||
-print "Testing function aliasing 6 ..",
|
||||
+print("Testing function aliasing 6 ..", end=' ')
|
||||
f7 = m1.functions[0]
|
||||
check(f1, f7)
|
||||
|
||||
-print "Testing argument aliasing .. ",
|
||||
+print("Testing argument aliasing .. ", end=' ')
|
||||
a1 = f1.args[0]
|
||||
a2 = f1.args[0]
|
||||
check(a1, a2)
|
||||
|
||||
-print "Testing basic block aliasing 1 .. ",
|
||||
+print("Testing basic block aliasing 1 .. ", end=' ')
|
||||
b2 = f1.basic_blocks[0]
|
||||
check(b1, b2)
|
||||
|
||||
-print "Testing basic block aliasing 2 .. ",
|
||||
+print("Testing basic block aliasing 2 .. ", end=' ')
|
||||
b3 = f1.get_entry_basic_block()
|
||||
check(b1, b3)
|
||||
|
||||
-print "Testing basic block aliasing 3 .. ",
|
||||
+print("Testing basic block aliasing 3 .. ", end=' ')
|
||||
b31 = f1.entry_basic_block
|
||||
check(b1, b31)
|
||||
|
||||
-print "Testing basic block aliasing 4 .. ",
|
||||
+print("Testing basic block aliasing 4 .. ", end=' ')
|
||||
bldr = Builder.new(b1)
|
||||
b4 = bldr.basic_block
|
||||
check(b1, b4)
|
||||
|
||||
-print "Testing basic block aliasing 5 .. ",
|
||||
+print("Testing basic block aliasing 5 .. ", end=' ')
|
||||
i1 = bldr.ret_void()
|
||||
b5 = i1.basic_block
|
||||
check(b1, b5)
|
||||
|
||||
-print "Testing instruction aliasing 1 .. ",
|
||||
+print("Testing instruction aliasing 1 .. ", end=' ')
|
||||
i2 = b5.instructions[0]
|
||||
check(i1, i2)
|
||||
|
||||
@@ -100,9 +100,9 @@
|
||||
v2 = phi.get_incoming_value(0)
|
||||
b6 = phi.get_incoming_block(0)
|
||||
|
||||
-print "Testing PHI / basic block aliasing 5 .. ",
|
||||
+print("Testing PHI / basic block aliasing 5 .. ", end=' ')
|
||||
check(b1, b6)
|
||||
|
||||
-print "Testing PHI / value aliasing .. ",
|
||||
+print("Testing PHI / value aliasing .. ", end=' ')
|
||||
check(f1.args[0], v2)
|
||||
|
||||
--- .\test\operands.py (original)
|
||||
+++ .\test\operands.py (refactored)
|
||||
@@ -28,9 +28,9 @@
|
||||
def __init__(self): pass
|
||||
def read(self): return test_module
|
||||
m = Module.from_assembly(strstream())
|
||||
-print "-"*60
|
||||
-print m
|
||||
-print "-"*60
|
||||
+print("-"*60)
|
||||
+print(m)
|
||||
+print("-"*60)
|
||||
|
||||
test_func = m.get_function_named("test_func")
|
||||
prod = m.get_function_named("prod")
|
||||
@@ -38,16 +38,16 @@
|
||||
#===----------------------------------------------------------------------===
|
||||
# test operands
|
||||
|
||||
-print
|
||||
+print()
|
||||
i1 = test_func.basic_blocks[0].instructions[0]
|
||||
i2 = test_func.basic_blocks[0].instructions[1]
|
||||
-print "Testing User.operand_count ..",
|
||||
+print("Testing User.operand_count ..", end=' ')
|
||||
if i1.operand_count == 3 and i2.operand_count == 2:
|
||||
- print "OK"
|
||||
+ print("OK")
|
||||
else:
|
||||
- print "FAIL"
|
||||
+ print("FAIL")
|
||||
|
||||
-print "Testing User.operands ..",
|
||||
+print("Testing User.operands ..", end=' ')
|
||||
c1 = i1.operands[0] is prod
|
||||
c2 = i1.operands[1] is test_func.args[0]
|
||||
c3 = i1.operands[2] is test_func.args[1]
|
||||
@@ -56,22 +56,22 @@
|
||||
c6 = len(i1.operands) == 3
|
||||
c7 = len(i2.operands) == 2
|
||||
if c1 and c2 and c3 and c5 and c6 and c7:
|
||||
- print "OK"
|
||||
+ print("OK")
|
||||
else:
|
||||
- print "FAIL"
|
||||
-print
|
||||
+ print("FAIL")
|
||||
+print()
|
||||
|
||||
#===----------------------------------------------------------------------===
|
||||
# show test_function
|
||||
|
||||
-print "Examining test_function `test_test_func':"
|
||||
+print("Examining test_function `test_test_func':")
|
||||
idx = 1
|
||||
for inst in test_func.basic_blocks[0].instructions:
|
||||
- print "Instruction #%d:" % (idx,)
|
||||
- print " operand_count =", inst.operand_count
|
||||
- print " operands:"
|
||||
+ print("Instruction #%d:" % (idx,))
|
||||
+ print(" operand_count =", inst.operand_count)
|
||||
+ print(" operands:")
|
||||
oidx = 1
|
||||
for op in inst.operands:
|
||||
- print " %d: %s" % (oidx, repr(op))
|
||||
+ print(" %d: %s" % (oidx, repr(op)))
|
||||
oidx += 1
|
||||
idx += 1
|
||||
--- .\test\passes.py (original)
|
||||
+++ .\test\passes.py (refactored)
|
||||
@@ -36,8 +36,8 @@
|
||||
}
|
||||
"""
|
||||
m = Module.from_assembly(strstream(asm))
|
||||
-print "-"*72
|
||||
-print m
|
||||
+print("-"*72)
|
||||
+print(m)
|
||||
|
||||
# Let's run a module-level inlining pass. First, create a pass manager.
|
||||
pm = PassManager.new()
|
||||
@@ -55,8 +55,8 @@
|
||||
del pm
|
||||
|
||||
# Print the result. Note the change in @test2.
|
||||
-print "-"*72
|
||||
-print m
|
||||
+print("-"*72)
|
||||
+print(m)
|
||||
|
||||
|
||||
# Let's run a DCE pass on the the function 'test1' now. First create a
|
||||
@@ -73,5 +73,5 @@
|
||||
fpm.run( m.get_function_named('test1') )
|
||||
|
||||
# Print the result. Note the change in @test1.
|
||||
-print "-"*72
|
||||
-print m
|
||||
+print("-"*72)
|
||||
+print(m)
|
||||
--- .\test\test.py (original)
|
||||
+++ .\test\test.py (refactored)
|
||||
@@ -69,7 +69,7 @@
|
||||
|
||||
# done
|
||||
if gc.garbage:
|
||||
- print "garbage = ", gc.garbage
|
||||
+ print("garbage = ", gc.garbage)
|
||||
|
||||
|
||||
main()
|
||||
--- .\test\testall.py (original)
|
||||
+++ .\test\testall.py (refactored)
|
||||
@@ -15,12 +15,12 @@
|
||||
|
||||
|
||||
def do_llvmexception():
|
||||
- print " Testing class LLVMException"
|
||||
+ print(" Testing class LLVMException")
|
||||
e = LLVMException()
|
||||
|
||||
|
||||
def do_ownable():
|
||||
- print " Testing class Ownable"
|
||||
+ print(" Testing class Ownable")
|
||||
o = Ownable(None, lambda x: None)
|
||||
try:
|
||||
o._own(None)
|
||||
@@ -30,7 +30,7 @@
|
||||
|
||||
|
||||
def do_misc():
|
||||
- print " Testing miscellaneous functions"
|
||||
+ print(" Testing miscellaneous functions")
|
||||
try:
|
||||
load_library_permanently("/usr/lib/libm.so")
|
||||
except LLVMException:
|
||||
@@ -42,14 +42,14 @@
|
||||
|
||||
|
||||
def do_llvm():
|
||||
- print " Testing module llvm"
|
||||
+ print(" Testing module llvm")
|
||||
do_llvmexception()
|
||||
do_ownable()
|
||||
do_misc()
|
||||
|
||||
|
||||
def do_module():
|
||||
- print " Testing class Module"
|
||||
+ print(" Testing class Module")
|
||||
m = Module.new('test')
|
||||
m.target = 'a'
|
||||
a = m.target
|
||||
@@ -101,7 +101,7 @@
|
||||
|
||||
|
||||
def do_type():
|
||||
- print " Testing class Type"
|
||||
+ print(" Testing class Type")
|
||||
for i in range(1,100):
|
||||
Type.int(i)
|
||||
Type.float()
|
||||
@@ -151,14 +151,14 @@
|
||||
|
||||
|
||||
def do_typehandle():
|
||||
- print " Testing class TypeHandle"
|
||||
+ print(" Testing class TypeHandle")
|
||||
th = TypeHandle.new(Type.opaque())
|
||||
ts = Type.struct([ Type.int(), Type.pointer(th.type) ])
|
||||
th.type.refine(ts)
|
||||
|
||||
|
||||
def do_value():
|
||||
- print " Testing class Value"
|
||||
+ print(" Testing class Value")
|
||||
k = Constant.int(ti, 42)
|
||||
k.name = 'a'
|
||||
s = k.name
|
||||
@@ -186,7 +186,7 @@
|
||||
|
||||
|
||||
def do_constant():
|
||||
- print " Testing class Constant"
|
||||
+ print(" Testing class Constant")
|
||||
Constant.null(ti)
|
||||
Constant.all_ones(ti)
|
||||
Constant.undef(ti)
|
||||
@@ -231,7 +231,7 @@
|
||||
|
||||
|
||||
def do_global_value():
|
||||
- print " Testing class GlobalValue"
|
||||
+ print(" Testing class GlobalValue")
|
||||
m = Module.new('a')
|
||||
gv = GlobalVariable.new(m, Type.int(), 'b')
|
||||
s = gv.is_declaration
|
||||
@@ -247,7 +247,7 @@
|
||||
|
||||
|
||||
def do_global_variable():
|
||||
- print " Testing class GlobalVariable"
|
||||
+ print(" Testing class GlobalVariable")
|
||||
m = Module.new('a')
|
||||
gv = GlobalVariable.new(m, Type.int(), 'b')
|
||||
gv = GlobalVariable.get(m, 'b')
|
||||
@@ -260,7 +260,7 @@
|
||||
|
||||
|
||||
def do_argument():
|
||||
- print " Testing class Argument"
|
||||
+ print(" Testing class Argument")
|
||||
m = Module.new('a')
|
||||
ft = Type.function(ti, [ti])
|
||||
f = Function.new(m, ft, 'func')
|
||||
@@ -272,7 +272,7 @@
|
||||
|
||||
|
||||
def do_function():
|
||||
- print " Testing class Function"
|
||||
+ print(" Testing class Function")
|
||||
ft = Type.function(ti, [ti]*20)
|
||||
zz = Function.new(Module.new('z'), ft, 'foobar')
|
||||
del zz
|
||||
@@ -307,7 +307,7 @@
|
||||
|
||||
|
||||
def do_instruction():
|
||||
- print " Testing class Instruction"
|
||||
+ print(" Testing class Instruction")
|
||||
m = Module.new('a')
|
||||
ft = Type.function(ti, [ti]*20)
|
||||
f = Function.new(m, ft, 'func')
|
||||
@@ -320,7 +320,7 @@
|
||||
|
||||
|
||||
def do_callorinvokeinstruction():
|
||||
- print " Testing class CallOrInvokeInstruction"
|
||||
+ print(" Testing class CallOrInvokeInstruction")
|
||||
m = Module.new('a')
|
||||
ft = Type.function(ti, [ti])
|
||||
f = Function.new(m, ft, 'func')
|
||||
@@ -337,7 +337,7 @@
|
||||
|
||||
|
||||
def do_phinode():
|
||||
- print " Testing class PhiNode"
|
||||
+ print(" Testing class PhiNode")
|
||||
m = Module.new('a')
|
||||
ft = Type.function(ti, [ti])
|
||||
f = Function.new(m, ft, 'func')
|
||||
@@ -354,7 +354,7 @@
|
||||
|
||||
|
||||
def do_switchinstruction():
|
||||
- print " Testing class SwitchInstruction"
|
||||
+ print(" Testing class SwitchInstruction")
|
||||
m = Module.new('a')
|
||||
ft = Type.function(ti, [ti])
|
||||
f = Function.new(m, ft, 'func')
|
||||
@@ -365,7 +365,7 @@
|
||||
|
||||
|
||||
def do_basicblock():
|
||||
- print " Testing class BasicBlock"
|
||||
+ print(" Testing class BasicBlock")
|
||||
m = Module.new('a')
|
||||
ft = Type.function(ti, [ti])
|
||||
f = Function.new(m, ft, 'func')
|
||||
@@ -395,7 +395,7 @@
|
||||
|
||||
|
||||
def do_builder():
|
||||
- print " Testing class Builder"
|
||||
+ print(" Testing class Builder")
|
||||
m = Module.new('a')
|
||||
ft = Type.function(ti, [ti])
|
||||
f = Function.new(m, ft, 'func')
|
||||
@@ -488,7 +488,7 @@
|
||||
|
||||
|
||||
def do_llvm_core():
|
||||
- print " Testing module llvm.core"
|
||||
+ print(" Testing module llvm.core")
|
||||
do_module()
|
||||
do_type()
|
||||
do_typehandle()
|
||||
@@ -508,7 +508,7 @@
|
||||
|
||||
|
||||
def do_targetdata():
|
||||
- print " Testing class TargetData"
|
||||
+ print(" Testing class TargetData")
|
||||
t = TargetData.new('')
|
||||
v = str(t)
|
||||
v = t.byte_order
|
||||
@@ -530,7 +530,7 @@
|
||||
|
||||
|
||||
def do_genericvalue():
|
||||
- print " Testing class GenericValue"
|
||||
+ print(" Testing class GenericValue")
|
||||
v = GenericValue.int(ti, 1)
|
||||
v = GenericValue.int_signed(ti, 1)
|
||||
v = GenericValue.real(Type.float(), 3.14)
|
||||
@@ -540,7 +540,7 @@
|
||||
|
||||
|
||||
def do_executionengine():
|
||||
- print " Testing class ExecutionEngine"
|
||||
+ print(" Testing class ExecutionEngine")
|
||||
m = Module.new('a')
|
||||
ee = ExecutionEngine.new(m, True)
|
||||
ft = Type.function(ti, [])
|
||||
@@ -567,14 +567,14 @@
|
||||
|
||||
|
||||
def do_llvm_ee():
|
||||
- print " Testing module llvm.ee"
|
||||
+ print(" Testing module llvm.ee")
|
||||
do_targetdata()
|
||||
do_genericvalue()
|
||||
do_executionengine()
|
||||
|
||||
|
||||
def do_passmanager():
|
||||
- print " Testing class PassManager"
|
||||
+ print(" Testing class PassManager")
|
||||
pm = PassManager.new()
|
||||
pm.add(TargetData.new(''))
|
||||
for i in [getattr(llvm.passes, x) for x in \
|
||||
@@ -586,7 +586,7 @@
|
||||
|
||||
|
||||
def do_functionpassmanager():
|
||||
- print " Testing class FunctionPassManager"
|
||||
+ print(" Testing class FunctionPassManager")
|
||||
m = Module.new('a')
|
||||
ft = Type.function(ti, [])
|
||||
f = m.add_function(ft, 'func')
|
||||
@@ -602,13 +602,13 @@
|
||||
|
||||
|
||||
def do_llvm_passes():
|
||||
- print " Testing module llvm.passes"
|
||||
+ print(" Testing module llvm.passes")
|
||||
do_passmanager()
|
||||
do_functionpassmanager()
|
||||
|
||||
|
||||
def main():
|
||||
- print "Testing package llvm"
|
||||
+ print("Testing package llvm")
|
||||
do_llvm()
|
||||
do_llvm_core()
|
||||
do_llvm_ee()
|
||||
--- .\test\testattrs.py (original)
|
||||
+++ .\test\testattrs.py (refactored)
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
from llvm.core import *
|
||||
-from cStringIO import StringIO
|
||||
+from io import StringIO
|
||||
|
||||
|
||||
def make_module():
|
||||
--- .\test\typehandle.py (original)
|
||||
+++ .\test\typehandle.py (refactored)
|
||||
@@ -16,4 +16,4 @@
|
||||
m.add_type_name("struct.node", th.type)
|
||||
|
||||
# show what we created
|
||||
-print m
|
||||
+print(m)
|
||||
--- .\test\uses.py (original)
|
||||
+++ .\test\uses.py (refactored)
|
||||
@@ -13,11 +13,11 @@
|
||||
tmp3 = bld.add(tmp1, f.args[2], "tmp3")
|
||||
bld.ret(tmp3)
|
||||
|
||||
-print "-"*60
|
||||
-print m
|
||||
-print "-"*60
|
||||
+print("-"*60)
|
||||
+print(m)
|
||||
+print("-"*60)
|
||||
|
||||
-print "Testing use count ..",
|
||||
+print("Testing use count ..", end=' ')
|
||||
c1 = f.args[0].use_count == 1
|
||||
c2 = f.args[1].use_count == 1
|
||||
c3 = f.args[2].use_count == 1
|
||||
@@ -25,11 +25,11 @@
|
||||
c5 = tmp2.use_count == 0
|
||||
c6 = tmp3.use_count == 1
|
||||
if c1 and c2 and c3 and c4 and c5 and c6:
|
||||
- print "OK"
|
||||
+ print("OK")
|
||||
else:
|
||||
- print "FAIL"
|
||||
+ print("FAIL")
|
||||
|
||||
-print "Testing uses ..",
|
||||
+print("Testing uses ..", end=' ')
|
||||
c1 = f.args[0].uses[0] is tmp1
|
||||
c2 = len(f.args[0].uses) == 1
|
||||
c3 = f.args[1].uses[0] is tmp2
|
||||
@@ -40,6 +40,6 @@
|
||||
c8 = len(tmp2.uses) == 0
|
||||
c9 = len(tmp3.uses) == 1
|
||||
if c1 and c2 and c3 and c4 and c5 and c6 and c7 and c8 and c9:
|
||||
- print "OK"
|
||||
+ print("OK")
|
||||
else:
|
||||
- print "FAIL"
|
||||
+ print("FAIL")
|
||||
--- .\tools\intrgen.py (original)
|
||||
+++ .\tools\intrgen.py (refactored)
|
||||
@@ -26,7 +26,7 @@
|
||||
idx = 1
|
||||
for i in intr:
|
||||
s = 'INTR_' + i.upper()
|
||||
- print '%s = %d' % (s.ljust(maxw), idx)
|
||||
+ print('%s = %d' % (s.ljust(maxw), idx))
|
||||
idx += 1
|
||||
|
||||
gen(sys.argv[1])
|
||||
--- .\tools\intrs_for_doc.py (original)
|
||||
+++ .\tools\intrs_for_doc.py (refactored)
|
||||
@@ -21,5 +21,5 @@
|
||||
outf = open(OUTF, 'wt')
|
||||
i = 0
|
||||
while i < len(intrs):
|
||||
- print >>outf, "`" + "`,`".join(intrs[i:min(i+NCOLS,len(intrs)+1)]) + "`"
|
||||
+ print("`" + "`,`".join(intrs[i:min(i+NCOLS,len(intrs)+1)]) + "`", file=outf)
|
||||
i += NCOLS
|
||||
--- .\www\makeweb.py (original)
|
||||
+++ .\www\makeweb.py (refactored)
|
||||
@@ -52,7 +52,7 @@
|
||||
|
||||
|
||||
def _rmtree_warn(fn, path, excinfo):
|
||||
- print "** WARNING **: error while doing %s on %s" % (fn, path)
|
||||
+ print("** WARNING **: error while doing %s on %s" % (fn, path))
|
||||
|
||||
|
||||
def _can_skip(opts, infile, outfile):
|
||||
@@ -67,14 +67,14 @@
|
||||
cmd = cmdfn(opts, infile, outfile_actual)
|
||||
if _can_skip(opts, infile, outfile_actual):
|
||||
if opts.verbose >= 2:
|
||||
- print "up to date %s -> %s" % (infile, outfile_actual)
|
||||
+ print("up to date %s -> %s" % (infile, outfile_actual))
|
||||
return
|
||||
if cmd:
|
||||
# do cmd
|
||||
if opts.verbose:
|
||||
- print "process %s -> %s" % (infile, outfile_actual)
|
||||
+ print("process %s -> %s" % (infile, outfile_actual))
|
||||
if opts.verbose >= 3:
|
||||
- print "command is [%s]" % cmd
|
||||
+ print("command is [%s]" % cmd)
|
||||
if not opts.dryrun:
|
||||
os.system(cmd)
|
||||
# else if cmd is None, do nothing
|
||||
@@ -83,7 +83,7 @@
|
||||
# nothing matched, default action is to copy
|
||||
if not _can_skip(opts, infile, outfile):
|
||||
if opts.verbose:
|
||||
- print "copying %s -> %s" % (infile, outfile)
|
||||
+ print("copying %s -> %s" % (infile, outfile))
|
||||
if not opts.dryrun:
|
||||
shutil.copy(infile, outfile)
|
||||
|
||||
@@ -95,14 +95,14 @@
|
||||
|
||||
# if it exists, it must be a dir!
|
||||
if odexists and not os.path.isdir(outdir):
|
||||
- print "** WARNING **: output dir '%s' exists but is " \
|
||||
- "not a dir, skipping" % outdir
|
||||
+ print("** WARNING **: output dir '%s' exists but is " \
|
||||
+ "not a dir, skipping" % outdir)
|
||||
return
|
||||
|
||||
# make outdir if not existing
|
||||
if not odexists:
|
||||
if opts.verbose:
|
||||
- print "creating %s" % outdir
|
||||
+ print("creating %s" % outdir)
|
||||
if not opts.dryrun:
|
||||
os.mkdir(outdir)
|
||||
|
||||
@@ -114,8 +114,8 @@
|
||||
# process files
|
||||
if os.path.isfile(inp):
|
||||
if os.path.exists(outp) and not os.path.isfile(outp):
|
||||
- print "** WARNING **: output '%s' corresponding to " \
|
||||
- "input '%s' is not a file, skipping" % (outp, inp)
|
||||
+ print("** WARNING **: output '%s' corresponding to " \
|
||||
+ "input '%s' is not a file, skipping" % (outp, inp))
|
||||
else:
|
||||
process_file(opts, inp, outp)
|
||||
|
||||
@@ -124,15 +124,15 @@
|
||||
# if dir is in skip list, silently ignore
|
||||
if elem in DIR_SKIP_TBL:
|
||||
if opts.verbose >= 3:
|
||||
- print "skipping %s" % inp
|
||||
+ print("skipping %s" % inp)
|
||||
continue
|
||||
# just recurse
|
||||
make(opts, inp, outp)
|
||||
|
||||
# neither a file nor a dir
|
||||
else:
|
||||
- print "** WARNING **: input '%s' is neither file nor " \
|
||||
- "dir, skipping" % inp
|
||||
+ print("** WARNING **: input '%s' is neither file nor " \
|
||||
+ "dir, skipping" % inp)
|
||||
|
||||
|
||||
def get_opts():
|
||||
@@ -173,14 +173,14 @@
|
||||
def main():
|
||||
opts, src, dest = get_opts()
|
||||
if opts.verbose >= 3:
|
||||
- print ("running with options:\nsrc = [%s]\ndest = [%s]\nverbose = [%d]\n" +\
|
||||
+ print(("running with options:\nsrc = [%s]\ndest = [%s]\nverbose = [%d]\n" +\
|
||||
"dry-run = [%d]\nclean-first = [%d]\nforce = [%d]") %\
|
||||
- (src, dest, opts.verbose, opts.dryrun, opts.clean, opts.force)
|
||||
+ (src, dest, opts.verbose, opts.dryrun, opts.clean, opts.force))
|
||||
if opts.dryrun and opts.verbose == 0:
|
||||
opts.verbose = 1
|
||||
if opts.clean:
|
||||
if opts.dryrun or opts.verbose:
|
||||
- print "removing tree %s" % dest
|
||||
+ print("removing tree %s" % dest)
|
||||
if not opts.dryrun:
|
||||
os.rmtree(dest, True, _rmtree_warn)
|
||||
make(opts, src, dest)
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
C:\Users\AndrewBC\src\llvm-py>python "C:\Program Files\Python27\Tools\Scripts\2to3.py" -w -f all -f idioms . > llvm/py3k_update.diff
|
||||
RefactoringTool: Skipping implicit fixer: buffer
|
||||
RefactoringTool: Skipping implicit fixer: set_literal
|
||||
RefactoringTool: Skipping implicit fixer: ws_comma
|
||||
RefactoringTool: Refactored .\setup-win32.py
|
||||
RefactoringTool: Refactored .\setup.py
|
||||
RefactoringTool: Refactored .\llvm\__init__.py
|
||||
RefactoringTool: Refactored .\llvm\_util.py
|
||||
RefactoringTool: Refactored .\llvm\core.py
|
||||
RefactoringTool: Refactored .\llvm\ee.py
|
||||
RefactoringTool: Refactored .\llvm\passes.py
|
||||
RefactoringTool: Refactored .\test\JITTutorial1.py
|
||||
RefactoringTool: Refactored .\test\JITTutorial2.py
|
||||
RefactoringTool: Refactored .\test\asm.py
|
||||
RefactoringTool: Refactored .\test\call-jit-ctypes.py
|
||||
RefactoringTool: Refactored .\test\example-jit.py
|
||||
RefactoringTool: Refactored .\test\example.py
|
||||
RefactoringTool: Refactored .\test\intrinsic.py
|
||||
RefactoringTool: Refactored .\test\objcache.py
|
||||
RefactoringTool: Refactored .\test\operands.py
|
||||
RefactoringTool: Refactored .\test\passes.py
|
||||
RefactoringTool: Refactored .\test\test.py
|
||||
RefactoringTool: Refactored .\test\testall.py
|
||||
RefactoringTool: Refactored .\test\testattrs.py
|
||||
RefactoringTool: Refactored .\test\typehandle.py
|
||||
RefactoringTool: Refactored .\test\uses.py
|
||||
RefactoringTool: Refactored .\tools\intrgen.py
|
||||
RefactoringTool: Refactored .\tools\intrs_for_doc.py
|
||||
RefactoringTool: Refactored .\www\makeweb.py
|
||||
RefactoringTool: Can't parse .\www\src\examples\JITTutorial1.py: ParseError: bad input: type=17, value=u'/', context=('', (1, 2))
|
||||
RefactoringTool: Can't parse .\www\src\examples\JITTutorial2.py: ParseError: bad input: type=17, value=u'/', context=('', (1, 2))
|
||||
RefactoringTool: Files that need to be modified:
|
||||
RefactoringTool: .\setup-win32.py
|
||||
RefactoringTool: .\setup.py
|
||||
RefactoringTool: .\llvm\__init__.py
|
||||
RefactoringTool: .\llvm\_util.py
|
||||
RefactoringTool: .\llvm\core.py
|
||||
RefactoringTool: .\llvm\ee.py
|
||||
RefactoringTool: .\llvm\passes.py
|
||||
RefactoringTool: .\test\JITTutorial1.py
|
||||
RefactoringTool: .\test\JITTutorial2.py
|
||||
RefactoringTool: .\test\asm.py
|
||||
RefactoringTool: .\test\call-jit-ctypes.py
|
||||
RefactoringTool: .\test\example-jit.py
|
||||
RefactoringTool: .\test\example.py
|
||||
RefactoringTool: .\test\intrinsic.py
|
||||
RefactoringTool: .\test\objcache.py
|
||||
RefactoringTool: .\test\operands.py
|
||||
RefactoringTool: .\test\passes.py
|
||||
RefactoringTool: .\test\test.py
|
||||
RefactoringTool: .\test\testall.py
|
||||
RefactoringTool: .\test\testattrs.py
|
||||
RefactoringTool: .\test\typehandle.py
|
||||
RefactoringTool: .\test\uses.py
|
||||
RefactoringTool: .\tools\intrgen.py
|
||||
RefactoringTool: .\tools\intrs_for_doc.py
|
||||
RefactoringTool: .\www\makeweb.py
|
||||
RefactoringTool: There were 2 errors:
|
||||
RefactoringTool: Can't parse .\www\src\examples\JITTutorial1.py: ParseError: bad input: type=17, value=u'/', context=('', (1, 2))
|
||||
RefactoringTool: Can't parse .\www\src\examples\JITTutorial2.py: ParseError: bad input: type=17, value=u'/', context=('', (1, 2))
|
||||
|
||||
C:\Users\AndrewBC\src\llvm-py>
|
||||
51
llvm/tbaa.py
51
llvm/tbaa.py
|
|
@ -1,51 +0,0 @@
|
|||
from llvm.core import *
|
||||
|
||||
class TBAABuilder(object):
|
||||
'''Simplify creation of TBAA metadata.
|
||||
|
||||
Each TBAABuidler object operates on a module.
|
||||
User can create multiple TBAABuilder on a module
|
||||
'''
|
||||
|
||||
def __init__(self, module, rootid):
|
||||
'''
|
||||
module --- the module to use.
|
||||
root --- string name to identify the TBAA root.
|
||||
'''
|
||||
self.__module = module
|
||||
self.__rootid = rootid
|
||||
self.__rootmd = self.__new_md(rootid)
|
||||
|
||||
@classmethod
|
||||
def new(cls, module, rootid):
|
||||
return cls(module, rootid)
|
||||
|
||||
def get_node(self, name, parent=None, const=False):
|
||||
'''Returns a MetaData object representing a TBAA node.
|
||||
|
||||
Use loadstore_instruction.set_metadata('tbaa', node) to
|
||||
bind a type to a memory.
|
||||
'''
|
||||
parent = parent or self.root
|
||||
const = Constant.int(Type.int(), int(bool(const)))
|
||||
return self.__new_md(name, parent, const)
|
||||
|
||||
@property
|
||||
def module(self):
|
||||
return self.__module
|
||||
|
||||
@property
|
||||
def root(self):
|
||||
return self.__rootmd
|
||||
|
||||
@property
|
||||
def root_name(self):
|
||||
return self.__rootid
|
||||
|
||||
def __new_md(self, *args):
|
||||
contents = list(args)
|
||||
for i, v in enumerate(contents):
|
||||
if isinstance(v, str):
|
||||
contents[i] = MetaDataString.get(self.module, v)
|
||||
return MetaData.get(self.module, contents)
|
||||
|
||||
1249
llvm/test_llvmpy.py
1249
llvm/test_llvmpy.py
File diff suppressed because it is too large
Load diff
|
|
@ -1,70 +0,0 @@
|
|||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
#include "wrap.h"
|
||||
|
||||
const char PYCAP_OBJECT_NAME[] = "llvm.wrap.h";
|
||||
|
||||
/*===----------------------------------------------------------------------===*/
|
||||
/* Type ctor/dtor */
|
||||
/*===----------------------------------------------------------------------===*/
|
||||
|
||||
|
||||
/*===----------------------------------------------------------------------===*/
|
||||
/* Helper functions */
|
||||
/*===----------------------------------------------------------------------===*/
|
||||
|
||||
void *get_object_arg(PyObject *args)
|
||||
{
|
||||
PyObject *o;
|
||||
|
||||
if (!PyArg_ParseTuple(args, "O", &o))
|
||||
throw py_exception();
|
||||
|
||||
return pycap_get<void*>(o);
|
||||
}
|
||||
|
||||
// must delete [] returned array
|
||||
void **make_array_from_list(PyObject *list, int n)
|
||||
{
|
||||
void **arr = new void*[n] ;
|
||||
|
||||
int i;
|
||||
for (i=0; i<n; i++) {
|
||||
PyObject *e = PyList_GetItem(list, i);
|
||||
if ( e == Py_None ) { // is None object?
|
||||
arr[i] = NULL;
|
||||
} else { // otherwise, it must be a PyCapsule
|
||||
arr[i] = pycap_get<void*>(e);
|
||||
}
|
||||
}
|
||||
|
||||
return arr;
|
||||
}
|
||||
1277
llvm/wrap.h
1277
llvm/wrap.h
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue