ZTWHHH commited on
Commit
32e58cc
·
verified ·
1 Parent(s): f808588

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/INSTALLER +1 -0
  2. vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/LICENSE +20 -0
  3. vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/METADATA +68 -0
  4. vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/RECORD +15 -0
  5. vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/REQUESTED +0 -0
  6. vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/WHEEL +5 -0
  7. vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/top_level.txt +1 -0
  8. vllm/lib/python3.10/site-packages/llvmlite/__init__.py +3 -0
  9. vllm/lib/python3.10/site-packages/llvmlite/_version.py +11 -0
  10. vllm/lib/python3.10/site-packages/llvmlite/binding/__init__.py +18 -0
  11. vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/__init__.cpython-310.pyc +0 -0
  12. vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/analysis.cpython-310.pyc +0 -0
  13. vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/common.cpython-310.pyc +0 -0
  14. vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/context.cpython-310.pyc +0 -0
  15. vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/dylib.cpython-310.pyc +0 -0
  16. vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/executionengine.cpython-310.pyc +0 -0
  17. vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/ffi.cpython-310.pyc +0 -0
  18. vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/initfini.cpython-310.pyc +0 -0
  19. vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/linker.cpython-310.pyc +0 -0
  20. vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/module.cpython-310.pyc +0 -0
  21. vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/object_file.cpython-310.pyc +0 -0
  22. vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/options.cpython-310.pyc +0 -0
  23. vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/orcjit.cpython-310.pyc +0 -0
  24. vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/passmanagers.cpython-310.pyc +0 -0
  25. vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/targets.cpython-310.pyc +0 -0
  26. vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/transforms.cpython-310.pyc +0 -0
  27. vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/typeref.cpython-310.pyc +0 -0
  28. vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/value.cpython-310.pyc +0 -0
  29. vllm/lib/python3.10/site-packages/llvmlite/binding/analysis.py +69 -0
  30. vllm/lib/python3.10/site-packages/llvmlite/binding/common.py +34 -0
  31. vllm/lib/python3.10/site-packages/llvmlite/binding/context.py +29 -0
  32. vllm/lib/python3.10/site-packages/llvmlite/binding/dylib.py +45 -0
  33. vllm/lib/python3.10/site-packages/llvmlite/binding/executionengine.py +330 -0
  34. vllm/lib/python3.10/site-packages/llvmlite/binding/ffi.py +390 -0
  35. vllm/lib/python3.10/site-packages/llvmlite/binding/initfini.py +73 -0
  36. vllm/lib/python3.10/site-packages/llvmlite/binding/linker.py +20 -0
  37. vllm/lib/python3.10/site-packages/llvmlite/binding/module.py +349 -0
  38. vllm/lib/python3.10/site-packages/llvmlite/binding/object_file.py +82 -0
  39. vllm/lib/python3.10/site-packages/llvmlite/binding/options.py +17 -0
  40. vllm/lib/python3.10/site-packages/llvmlite/binding/orcjit.py +342 -0
  41. vllm/lib/python3.10/site-packages/llvmlite/binding/passmanagers.py +939 -0
  42. vllm/lib/python3.10/site-packages/llvmlite/binding/targets.py +450 -0
  43. vllm/lib/python3.10/site-packages/llvmlite/binding/transforms.py +151 -0
  44. vllm/lib/python3.10/site-packages/llvmlite/binding/typeref.py +198 -0
  45. vllm/lib/python3.10/site-packages/llvmlite/binding/value.py +618 -0
  46. vllm/lib/python3.10/site-packages/llvmlite/tests/__init__.py +57 -0
  47. vllm/lib/python3.10/site-packages/llvmlite/tests/__main__.py +3 -0
  48. vllm/lib/python3.10/site-packages/llvmlite/tests/customize.py +407 -0
  49. vllm/lib/python3.10/site-packages/llvmlite/tests/test_valuerepr.py +60 -0
  50. vllm/lib/python3.10/site-packages/llvmlite/utils.py +29 -0
vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/LICENSE ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ This package contains a modified version of ca-bundle.crt:
2
+
3
+ ca-bundle.crt -- Bundle of CA Root Certificates
4
+
5
+ This is a bundle of X.509 certificates of public Certificate Authorities
6
+ (CA). These were automatically extracted from Mozilla's root certificates
7
+ file (certdata.txt). This file can be found in the mozilla source tree:
8
+ https://hg.mozilla.org/mozilla-central/file/tip/security/nss/lib/ckfw/builtins/certdata.txt
9
+ It contains the certificates in PEM format and therefore
10
+ can be directly used with curl / libcurl / php_curl, or with
11
+ an Apache+mod_ssl webserver for SSL client authentication.
12
+ Just configure this file as the SSLCACertificateFile.#
13
+
14
+ ***** BEGIN LICENSE BLOCK *****
15
+ This Source Code Form is subject to the terms of the Mozilla Public License,
16
+ v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain
17
+ one at http://mozilla.org/MPL/2.0/.
18
+
19
+ ***** END LICENSE BLOCK *****
20
+ @(#) $RCSfile: certdata.txt,v $ $Revision: 1.80 $ $Date: 2011/11/03 15:11:58 $
vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/METADATA ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: certifi
3
+ Version: 2024.12.14
4
+ Summary: Python package for providing Mozilla's CA Bundle.
5
+ Home-page: https://github.com/certifi/python-certifi
6
+ Author: Kenneth Reitz
7
+ Author-email: me@kennethreitz.com
8
+ License: MPL-2.0
9
+ Project-URL: Source, https://github.com/certifi/python-certifi
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
13
+ Classifier: Natural Language :: English
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.6
18
+ Classifier: Programming Language :: Python :: 3.7
19
+ Classifier: Programming Language :: Python :: 3.8
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Requires-Python: >=3.6
26
+ License-File: LICENSE
27
+
28
+ Certifi: Python SSL Certificates
29
+ ================================
30
+
31
+ Certifi provides Mozilla's carefully curated collection of Root Certificates for
32
+ validating the trustworthiness of SSL certificates while verifying the identity
33
+ of TLS hosts. It has been extracted from the `Requests`_ project.
34
+
35
+ Installation
36
+ ------------
37
+
38
+ ``certifi`` is available on PyPI. Simply install it with ``pip``::
39
+
40
+ $ pip install certifi
41
+
42
+ Usage
43
+ -----
44
+
45
+ To reference the installed certificate authority (CA) bundle, you can use the
46
+ built-in function::
47
+
48
+ >>> import certifi
49
+
50
+ >>> certifi.where()
51
+ '/usr/local/lib/python3.7/site-packages/certifi/cacert.pem'
52
+
53
+ Or from the command line::
54
+
55
+ $ python -m certifi
56
+ /usr/local/lib/python3.7/site-packages/certifi/cacert.pem
57
+
58
+ Enjoy!
59
+
60
+ .. _`Requests`: https://requests.readthedocs.io/en/master/
61
+
62
+ Addition/Removal of Certificates
63
+ --------------------------------
64
+
65
+ Certifi does not support any addition/removal or other modification of the
66
+ CA trust store content. This project is intended to provide a reliable and
67
+ highly portable root of trust to python deployments. Look to upstream projects
68
+ for methods to use alternate trust.
vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/RECORD ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ certifi-2024.12.14.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ certifi-2024.12.14.dist-info/LICENSE,sha256=6TcW2mucDVpKHfYP5pWzcPBpVgPSH2-D8FPkLPwQyvc,989
3
+ certifi-2024.12.14.dist-info/METADATA,sha256=z71eRGTFszr4qsHenZ_vG2Fd5bV9PBWmJgShthc8IkY,2274
4
+ certifi-2024.12.14.dist-info/RECORD,,
5
+ certifi-2024.12.14.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ certifi-2024.12.14.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
7
+ certifi-2024.12.14.dist-info/top_level.txt,sha256=KMu4vUCfsjLrkPbSNdgdekS-pVJzBAJFO__nI8NF6-U,8
8
+ certifi/__init__.py,sha256=LqjNcwt1sYSS3uhPXrf6jJzVCuHtNVpuirg5rb7mVm8,94
9
+ certifi/__main__.py,sha256=xBBoj905TUWBLRGANOcf7oi6e-3dMP4cEoG9OyMs11g,243
10
+ certifi/__pycache__/__init__.cpython-310.pyc,,
11
+ certifi/__pycache__/__main__.cpython-310.pyc,,
12
+ certifi/__pycache__/core.cpython-310.pyc,,
13
+ certifi/cacert.pem,sha256=gHiXJU84Oif0XkT0llbzeKurIUHt5DpK08JCCll90j8,294769
14
+ certifi/core.py,sha256=qRDDFyXVJwTB_EmoGppaXU_R9qCZvhl-EzxPMuV3nTA,4426
15
+ certifi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/REQUESTED ADDED
File without changes
vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.6.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ certifi
vllm/lib/python3.10/site-packages/llvmlite/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from ._version import get_versions
2
+ __version__ = get_versions()['version']
3
+ del get_versions
vllm/lib/python3.10/site-packages/llvmlite/_version.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # This file was generated by 'versioneer.py' (0.14) from
3
+ # revision-control system data, or from the parent directory name of an
4
+ # unpacked source archive. Distribution tarballs contain a pre-generated copy
5
+ # of this file.
6
+
7
+ version_version = '0.43.0'
8
+ version_full = '6c786059354260a0ae93f9d0144d4016ab3d63b4'
9
+ def get_versions(default={}, verbose=False):
10
+ return {'version': version_version, 'full': version_full}
11
+
vllm/lib/python3.10/site-packages/llvmlite/binding/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Things that rely on the LLVM library
3
+ """
4
+ from .dylib import *
5
+ from .executionengine import *
6
+ from .initfini import *
7
+ from .linker import *
8
+ from .module import *
9
+ from .options import *
10
+ from .passmanagers import *
11
+ from .targets import *
12
+ from .transforms import *
13
+ from .value import *
14
+ from .typeref import *
15
+ from .analysis import *
16
+ from .object_file import *
17
+ from .context import *
18
+ from .orcjit import *
vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (526 Bytes). View file
 
vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/analysis.cpython-310.pyc ADDED
Binary file (2.28 kB). View file
 
vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/common.cpython-310.pyc ADDED
Binary file (1.1 kB). View file
 
vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/context.cpython-310.pyc ADDED
Binary file (1.41 kB). View file
 
vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/dylib.cpython-310.pyc ADDED
Binary file (1.41 kB). View file
 
vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/executionengine.cpython-310.pyc ADDED
Binary file (9.63 kB). View file
 
vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/ffi.cpython-310.pyc ADDED
Binary file (13.7 kB). View file
 
vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/initfini.cpython-310.pyc ADDED
Binary file (2.24 kB). View file
 
vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/linker.cpython-310.pyc ADDED
Binary file (658 Bytes). View file
 
vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/module.cpython-310.pyc ADDED
Binary file (10.5 kB). View file
 
vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/object_file.cpython-310.pyc ADDED
Binary file (3.24 kB). View file
 
vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/options.cpython-310.pyc ADDED
Binary file (701 Bytes). View file
 
vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/orcjit.cpython-310.pyc ADDED
Binary file (12 kB). View file
 
vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/passmanagers.cpython-310.pyc ADDED
Binary file (34.5 kB). View file
 
vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/targets.cpython-310.pyc ADDED
Binary file (13 kB). View file
 
vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/transforms.cpython-310.pyc ADDED
Binary file (4.91 kB). View file
 
vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/typeref.cpython-310.pyc ADDED
Binary file (6.12 kB). View file
 
vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/value.cpython-310.pyc ADDED
Binary file (17.3 kB). View file
 
vllm/lib/python3.10/site-packages/llvmlite/binding/analysis.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A collection of analysis utilities
3
+ """
4
+
5
+ from ctypes import POINTER, c_char_p, c_int
6
+
7
+ from llvmlite.binding import ffi
8
+ from llvmlite.binding.module import parse_assembly
9
+
10
+
11
+ def get_function_cfg(func, show_inst=True):
12
+ """Return a string of the control-flow graph of the function in DOT
13
+ format. If the input `func` is not a materialized function, the module
14
+ containing the function is parsed to create an actual LLVM module.
15
+ The `show_inst` flag controls whether the instructions of each block
16
+ are printed.
17
+ """
18
+ assert func is not None
19
+ from llvmlite import ir
20
+ if isinstance(func, ir.Function):
21
+ mod = parse_assembly(str(func.module))
22
+ func = mod.get_function(func.name)
23
+
24
+ # Assume func is a materialized function
25
+ with ffi.OutputString() as dotstr:
26
+ ffi.lib.LLVMPY_WriteCFG(func, dotstr, show_inst)
27
+ return str(dotstr)
28
+
29
+
30
+ def view_dot_graph(graph, filename=None, view=False):
31
+ """
32
+ View the given DOT source. If view is True, the image is rendered
33
+ and viewed by the default application in the system. The file path of
34
+ the output is returned. If view is False, a graphviz.Source object is
35
+ returned. If view is False and the environment is in a IPython session,
36
+ an IPython image object is returned and can be displayed inline in the
37
+ notebook.
38
+
39
+ This function requires the graphviz package.
40
+
41
+ Args
42
+ ----
43
+ - graph [str]: a DOT source code
44
+ - filename [str]: optional. if given and view is True, this specifies
45
+ the file path for the rendered output to write to.
46
+ - view [bool]: if True, opens the rendered output file.
47
+
48
+ """
49
+ # Optionally depends on graphviz package
50
+ import graphviz as gv
51
+
52
+ src = gv.Source(graph)
53
+ if view:
54
+ # Returns the output file path
55
+ return src.render(filename, view=view)
56
+ else:
57
+ # Attempts to show the graph in IPython notebook
58
+ try:
59
+ __IPYTHON__
60
+ except NameError:
61
+ return src
62
+ else:
63
+ import IPython.display as display
64
+ format = 'svg'
65
+ return display.SVG(data=src.pipe(format))
66
+
67
+
68
+ # Ctypes binding
69
+ ffi.lib.LLVMPY_WriteCFG.argtypes = [ffi.LLVMValueRef, POINTER(c_char_p), c_int]
vllm/lib/python3.10/site-packages/llvmlite/binding/common.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import atexit
2
+
3
+
4
+ def _encode_string(s):
5
+ encoded = s.encode('utf-8')
6
+ return encoded
7
+
8
+
9
+ def _decode_string(b):
10
+ return b.decode('utf-8')
11
+
12
+
13
+ _encode_string.__doc__ = """Encode a string for use by LLVM."""
14
+ _decode_string.__doc__ = """Decode a LLVM character (byte)string."""
15
+
16
+
17
+ _shutting_down = [False]
18
+
19
+
20
+ def _at_shutdown():
21
+ _shutting_down[0] = True
22
+
23
+
24
+ atexit.register(_at_shutdown)
25
+
26
+
27
+ def _is_shutting_down(_shutting_down=_shutting_down):
28
+ """
29
+ Whether the interpreter is currently shutting down.
30
+ For use in finalizers, __del__ methods, and similar; it is advised
31
+ to early bind this function rather than look it up when calling it,
32
+ since at shutdown module globals may be cleared.
33
+ """
34
+ return _shutting_down[0]
vllm/lib/python3.10/site-packages/llvmlite/binding/context.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from llvmlite.binding import ffi
2
+
3
+
4
+ def create_context():
5
+ return ContextRef(ffi.lib.LLVMPY_ContextCreate())
6
+
7
+
8
+ def get_global_context():
9
+ return GlobalContextRef(ffi.lib.LLVMPY_GetGlobalContext())
10
+
11
+
12
+ class ContextRef(ffi.ObjectRef):
13
+ def __init__(self, context_ptr):
14
+ super(ContextRef, self).__init__(context_ptr)
15
+
16
+ def _dispose(self):
17
+ ffi.lib.LLVMPY_ContextDispose(self)
18
+
19
+
20
+ class GlobalContextRef(ContextRef):
21
+ def _dispose(self):
22
+ pass
23
+
24
+
25
+ ffi.lib.LLVMPY_GetGlobalContext.restype = ffi.LLVMContextRef
26
+
27
+ ffi.lib.LLVMPY_ContextCreate.restype = ffi.LLVMContextRef
28
+
29
+ ffi.lib.LLVMPY_ContextDispose.argtypes = [ffi.LLVMContextRef]
vllm/lib/python3.10/site-packages/llvmlite/binding/dylib.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ctypes import c_void_p, c_char_p, c_bool, POINTER
2
+
3
+ from llvmlite.binding import ffi
4
+ from llvmlite.binding.common import _encode_string
5
+
6
+
7
+ def address_of_symbol(name):
8
+ """
9
+ Get the in-process address of symbol named *name*.
10
+ An integer is returned, or None if the symbol isn't found.
11
+ """
12
+ return ffi.lib.LLVMPY_SearchAddressOfSymbol(_encode_string(name))
13
+
14
+
15
+ def add_symbol(name, address):
16
+ """
17
+ Register the *address* of global symbol *name*. This will make
18
+ it usable (e.g. callable) from LLVM-compiled functions.
19
+ """
20
+ ffi.lib.LLVMPY_AddSymbol(_encode_string(name), c_void_p(address))
21
+
22
+
23
+ def load_library_permanently(filename):
24
+ """
25
+ Load an external library
26
+ """
27
+ with ffi.OutputString() as outerr:
28
+ if ffi.lib.LLVMPY_LoadLibraryPermanently(
29
+ _encode_string(filename), outerr):
30
+ raise RuntimeError(str(outerr))
31
+
32
+ # ============================================================================
33
+ # FFI
34
+
35
+
36
+ ffi.lib.LLVMPY_AddSymbol.argtypes = [
37
+ c_char_p,
38
+ c_void_p,
39
+ ]
40
+
41
+ ffi.lib.LLVMPY_SearchAddressOfSymbol.argtypes = [c_char_p]
42
+ ffi.lib.LLVMPY_SearchAddressOfSymbol.restype = c_void_p
43
+
44
+ ffi.lib.LLVMPY_LoadLibraryPermanently.argtypes = [c_char_p, POINTER(c_char_p)]
45
+ ffi.lib.LLVMPY_LoadLibraryPermanently.restype = c_bool
vllm/lib/python3.10/site-packages/llvmlite/binding/executionengine.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import platform
2
+ from ctypes import (POINTER, c_char_p, c_bool, c_void_p,
3
+ c_int, c_uint64, c_size_t, CFUNCTYPE, string_at, cast,
4
+ py_object, Structure)
5
+
6
+ from llvmlite.binding import ffi, targets, object_file
7
+
8
+
9
+ # Just check these weren't optimized out of the DLL.
10
+ ffi.lib.LLVMPY_LinkInMCJIT
11
+
12
+
13
+ def create_mcjit_compiler(module, target_machine, use_lmm=None):
14
+ """
15
+ Create a MCJIT ExecutionEngine from the given *module* and
16
+ *target_machine*.
17
+
18
+ *lmm* controls whether the llvmlite memory manager is used. If not supplied,
19
+ the default choice for the platform will be used (``True`` on 64-bit ARM
20
+ systems, ``False`` otherwise).
21
+ """
22
+ if use_lmm is None:
23
+ use_lmm = platform.machine() in ('arm64', 'aarch64')
24
+
25
+ with ffi.OutputString() as outerr:
26
+ engine = ffi.lib.LLVMPY_CreateMCJITCompiler(
27
+ module, target_machine, use_lmm, outerr)
28
+ if not engine:
29
+ raise RuntimeError(str(outerr))
30
+
31
+ target_machine._owned = True
32
+ return ExecutionEngine(engine, module=module)
33
+
34
+
35
+ def check_jit_execution():
36
+ """
37
+ Check the system allows execution of in-memory JITted functions.
38
+ An exception is raised otherwise.
39
+ """
40
+ errno = ffi.lib.LLVMPY_TryAllocateExecutableMemory()
41
+ if errno != 0:
42
+ raise OSError(errno,
43
+ "cannot allocate executable memory. "
44
+ "This may be due to security restrictions on your "
45
+ "system, such as SELinux or similar mechanisms."
46
+ )
47
+
48
+
49
+ class ExecutionEngine(ffi.ObjectRef):
50
+ """An ExecutionEngine owns all Modules associated with it.
51
+ Deleting the engine will remove all associated modules.
52
+ It is an error to delete the associated modules.
53
+ """
54
+ _object_cache = None
55
+
56
+ def __init__(self, ptr, module):
57
+ """
58
+ Module ownership is transferred to the EE
59
+ """
60
+ self._modules = set([module])
61
+ self._td = None
62
+ module._owned = True
63
+ ffi.ObjectRef.__init__(self, ptr)
64
+
65
+ def get_function_address(self, name):
66
+ """
67
+ Return the address of the function named *name* as an integer.
68
+
69
+ It's a fatal error in LLVM if the symbol of *name* doesn't exist.
70
+ """
71
+ return ffi.lib.LLVMPY_GetFunctionAddress(self, name.encode("ascii"))
72
+
73
+ def get_global_value_address(self, name):
74
+ """
75
+ Return the address of the global value named *name* as an integer.
76
+
77
+ It's a fatal error in LLVM if the symbol of *name* doesn't exist.
78
+ """
79
+ return ffi.lib.LLVMPY_GetGlobalValueAddress(self, name.encode("ascii"))
80
+
81
+ def add_global_mapping(self, gv, addr):
82
+ ffi.lib.LLVMPY_AddGlobalMapping(self, gv, addr)
83
+
84
+ def add_module(self, module):
85
+ """
86
+ Ownership of module is transferred to the execution engine
87
+ """
88
+ if module in self._modules:
89
+ raise KeyError("module already added to this engine")
90
+ ffi.lib.LLVMPY_AddModule(self, module)
91
+ module._owned = True
92
+ self._modules.add(module)
93
+
94
+ def finalize_object(self):
95
+ """
96
+ Make sure all modules owned by the execution engine are fully processed
97
+ and "usable" for execution.
98
+ """
99
+ ffi.lib.LLVMPY_FinalizeObject(self)
100
+
101
+ def run_static_constructors(self):
102
+ """
103
+ Run static constructors which initialize module-level static objects.
104
+ """
105
+ ffi.lib.LLVMPY_RunStaticConstructors(self)
106
+
107
+ def run_static_destructors(self):
108
+ """
109
+ Run static destructors which perform module-level cleanup of static
110
+ resources.
111
+ """
112
+ ffi.lib.LLVMPY_RunStaticDestructors(self)
113
+
114
+ def remove_module(self, module):
115
+ """
116
+ Ownership of module is returned
117
+ """
118
+ with ffi.OutputString() as outerr:
119
+ if ffi.lib.LLVMPY_RemoveModule(self, module, outerr):
120
+ raise RuntimeError(str(outerr))
121
+ self._modules.remove(module)
122
+ module._owned = False
123
+
124
+ @property
125
+ def target_data(self):
126
+ """
127
+ The TargetData for this execution engine.
128
+ """
129
+ if self._td is not None:
130
+ return self._td
131
+ ptr = ffi.lib.LLVMPY_GetExecutionEngineTargetData(self)
132
+ self._td = targets.TargetData(ptr)
133
+ self._td._owned = True
134
+ return self._td
135
+
136
+ def enable_jit_events(self):
137
+ """
138
+ Enable JIT events for profiling of generated code.
139
+ Return value indicates whether connection to profiling tool
140
+ was successful.
141
+ """
142
+ ret = ffi.lib.LLVMPY_EnableJITEvents(self)
143
+ return ret
144
+
145
+ def _find_module_ptr(self, module_ptr):
146
+ """
147
+ Find the ModuleRef corresponding to the given pointer.
148
+ """
149
+ ptr = cast(module_ptr, c_void_p).value
150
+ for module in self._modules:
151
+ if cast(module._ptr, c_void_p).value == ptr:
152
+ return module
153
+ return None
154
+
155
+ def add_object_file(self, obj_file):
156
+ """
157
+ Add object file to the jit. object_file can be instance of
158
+ :class:ObjectFile or a string representing file system path
159
+ """
160
+ if isinstance(obj_file, str):
161
+ obj_file = object_file.ObjectFileRef.from_path(obj_file)
162
+
163
+ ffi.lib.LLVMPY_MCJITAddObjectFile(self, obj_file)
164
+
165
+ def set_object_cache(self, notify_func=None, getbuffer_func=None):
166
+ """
167
+ Set the object cache "notifyObjectCompiled" and "getBuffer"
168
+ callbacks to the given Python functions.
169
+ """
170
+ self._object_cache_notify = notify_func
171
+ self._object_cache_getbuffer = getbuffer_func
172
+ # Lifetime of the object cache is managed by us.
173
+ self._object_cache = _ObjectCacheRef(self)
174
+ # Note this doesn't keep a reference to self, to avoid reference
175
+ # cycles.
176
+ ffi.lib.LLVMPY_SetObjectCache(self, self._object_cache)
177
+
178
+ def _raw_object_cache_notify(self, data):
179
+ """
180
+ Low-level notify hook.
181
+ """
182
+ if self._object_cache_notify is None:
183
+ return
184
+ module_ptr = data.contents.module_ptr
185
+ buf_ptr = data.contents.buf_ptr
186
+ buf_len = data.contents.buf_len
187
+ buf = string_at(buf_ptr, buf_len)
188
+ module = self._find_module_ptr(module_ptr)
189
+ if module is None:
190
+ # The LLVM EE should only give notifications for modules
191
+ # known by us.
192
+ raise RuntimeError("object compilation notification "
193
+ "for unknown module %s" % (module_ptr,))
194
+ self._object_cache_notify(module, buf)
195
+
196
+ def _raw_object_cache_getbuffer(self, data):
197
+ """
198
+ Low-level getbuffer hook.
199
+ """
200
+ if self._object_cache_getbuffer is None:
201
+ return
202
+ module_ptr = data.contents.module_ptr
203
+ module = self._find_module_ptr(module_ptr)
204
+ if module is None:
205
+ # The LLVM EE should only give notifications for modules
206
+ # known by us.
207
+ raise RuntimeError("object compilation notification "
208
+ "for unknown module %s" % (module_ptr,))
209
+
210
+ buf = self._object_cache_getbuffer(module)
211
+ if buf is not None:
212
+ # Create a copy, which will be freed by the caller
213
+ data[0].buf_ptr = ffi.lib.LLVMPY_CreateByteString(buf, len(buf))
214
+ data[0].buf_len = len(buf)
215
+
216
+ def _dispose(self):
217
+ # The modules will be cleaned up by the EE
218
+ for mod in self._modules:
219
+ mod.detach()
220
+ if self._td is not None:
221
+ self._td.detach()
222
+ self._modules.clear()
223
+ self._object_cache = None
224
+ self._capi.LLVMPY_DisposeExecutionEngine(self)
225
+
226
+
227
+ class _ObjectCacheRef(ffi.ObjectRef):
228
+ """
229
+ Internal: an ObjectCache instance for use within an ExecutionEngine.
230
+ """
231
+
232
+ def __init__(self, obj):
233
+ ptr = ffi.lib.LLVMPY_CreateObjectCache(_notify_c_hook,
234
+ _getbuffer_c_hook,
235
+ obj)
236
+ ffi.ObjectRef.__init__(self, ptr)
237
+
238
+ def _dispose(self):
239
+ self._capi.LLVMPY_DisposeObjectCache(self)
240
+
241
+
242
+ # ============================================================================
243
+ # FFI
244
+
245
+
246
+ ffi.lib.LLVMPY_CreateMCJITCompiler.argtypes = [
247
+ ffi.LLVMModuleRef,
248
+ ffi.LLVMTargetMachineRef,
249
+ c_bool,
250
+ POINTER(c_char_p),
251
+ ]
252
+ ffi.lib.LLVMPY_CreateMCJITCompiler.restype = ffi.LLVMExecutionEngineRef
253
+
254
+ ffi.lib.LLVMPY_RemoveModule.argtypes = [
255
+ ffi.LLVMExecutionEngineRef,
256
+ ffi.LLVMModuleRef,
257
+ POINTER(c_char_p),
258
+ ]
259
+ ffi.lib.LLVMPY_RemoveModule.restype = c_bool
260
+
261
+ ffi.lib.LLVMPY_AddModule.argtypes = [
262
+ ffi.LLVMExecutionEngineRef,
263
+ ffi.LLVMModuleRef
264
+ ]
265
+
266
+ ffi.lib.LLVMPY_AddGlobalMapping.argtypes = [ffi.LLVMExecutionEngineRef,
267
+ ffi.LLVMValueRef,
268
+ c_void_p]
269
+
270
+ ffi.lib.LLVMPY_FinalizeObject.argtypes = [ffi.LLVMExecutionEngineRef]
271
+
272
+ ffi.lib.LLVMPY_GetExecutionEngineTargetData.argtypes = [
273
+ ffi.LLVMExecutionEngineRef
274
+ ]
275
+ ffi.lib.LLVMPY_GetExecutionEngineTargetData.restype = ffi.LLVMTargetDataRef
276
+
277
+ ffi.lib.LLVMPY_TryAllocateExecutableMemory.argtypes = []
278
+ ffi.lib.LLVMPY_TryAllocateExecutableMemory.restype = c_int
279
+
280
+ ffi.lib.LLVMPY_GetFunctionAddress.argtypes = [
281
+ ffi.LLVMExecutionEngineRef,
282
+ c_char_p
283
+ ]
284
+ ffi.lib.LLVMPY_GetFunctionAddress.restype = c_uint64
285
+
286
+ ffi.lib.LLVMPY_GetGlobalValueAddress.argtypes = [
287
+ ffi.LLVMExecutionEngineRef,
288
+ c_char_p
289
+ ]
290
+ ffi.lib.LLVMPY_GetGlobalValueAddress.restype = c_uint64
291
+
292
+ ffi.lib.LLVMPY_MCJITAddObjectFile.argtypes = [
293
+ ffi.LLVMExecutionEngineRef,
294
+ ffi.LLVMObjectFileRef
295
+ ]
296
+
297
+
298
+ class _ObjectCacheData(Structure):
299
+ _fields_ = [
300
+ ('module_ptr', ffi.LLVMModuleRef),
301
+ ('buf_ptr', c_void_p),
302
+ ('buf_len', c_size_t),
303
+ ]
304
+
305
+
306
+ _ObjectCacheNotifyFunc = CFUNCTYPE(None, py_object,
307
+ POINTER(_ObjectCacheData))
308
+ _ObjectCacheGetBufferFunc = CFUNCTYPE(None, py_object,
309
+ POINTER(_ObjectCacheData))
310
+
311
+ # XXX The ctypes function wrappers are created at the top-level, otherwise
312
+ # there are issues when creating CFUNCTYPEs in child processes on CentOS 5
313
+ # 32 bits.
314
+ _notify_c_hook = _ObjectCacheNotifyFunc(
315
+ ExecutionEngine._raw_object_cache_notify)
316
+ _getbuffer_c_hook = _ObjectCacheGetBufferFunc(
317
+ ExecutionEngine._raw_object_cache_getbuffer)
318
+
319
+ ffi.lib.LLVMPY_CreateObjectCache.argtypes = [_ObjectCacheNotifyFunc,
320
+ _ObjectCacheGetBufferFunc,
321
+ py_object]
322
+ ffi.lib.LLVMPY_CreateObjectCache.restype = ffi.LLVMObjectCacheRef
323
+
324
+ ffi.lib.LLVMPY_DisposeObjectCache.argtypes = [ffi.LLVMObjectCacheRef]
325
+
326
+ ffi.lib.LLVMPY_SetObjectCache.argtypes = [ffi.LLVMExecutionEngineRef,
327
+ ffi.LLVMObjectCacheRef]
328
+
329
+ ffi.lib.LLVMPY_CreateByteString.restype = c_void_p
330
+ ffi.lib.LLVMPY_CreateByteString.argtypes = [c_void_p, c_size_t]
vllm/lib/python3.10/site-packages/llvmlite/binding/ffi.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import ctypes
3
+ import threading
4
+ import importlib.resources as _impres
5
+
6
+ from llvmlite.binding.common import _decode_string, _is_shutting_down
7
+ from llvmlite.utils import get_library_name
8
+
9
+
10
+ def _make_opaque_ref(name):
11
+ newcls = type(name, (ctypes.Structure,), {})
12
+ return ctypes.POINTER(newcls)
13
+
14
+
15
+ LLVMContextRef = _make_opaque_ref("LLVMContext")
16
+ LLVMModuleRef = _make_opaque_ref("LLVMModule")
17
+ LLVMValueRef = _make_opaque_ref("LLVMValue")
18
+ LLVMTypeRef = _make_opaque_ref("LLVMType")
19
+ LLVMExecutionEngineRef = _make_opaque_ref("LLVMExecutionEngine")
20
+ LLVMPassManagerBuilderRef = _make_opaque_ref("LLVMPassManagerBuilder")
21
+ LLVMPassManagerRef = _make_opaque_ref("LLVMPassManager")
22
+ LLVMTargetDataRef = _make_opaque_ref("LLVMTargetData")
23
+ LLVMTargetLibraryInfoRef = _make_opaque_ref("LLVMTargetLibraryInfo")
24
+ LLVMTargetRef = _make_opaque_ref("LLVMTarget")
25
+ LLVMTargetMachineRef = _make_opaque_ref("LLVMTargetMachine")
26
+ LLVMMemoryBufferRef = _make_opaque_ref("LLVMMemoryBuffer")
27
+ LLVMAttributeListIterator = _make_opaque_ref("LLVMAttributeListIterator")
28
+ LLVMElementIterator = _make_opaque_ref("LLVMElementIterator")
29
+ LLVMAttributeSetIterator = _make_opaque_ref("LLVMAttributeSetIterator")
30
+ LLVMGlobalsIterator = _make_opaque_ref("LLVMGlobalsIterator")
31
+ LLVMFunctionsIterator = _make_opaque_ref("LLVMFunctionsIterator")
32
+ LLVMBlocksIterator = _make_opaque_ref("LLVMBlocksIterator")
33
+ LLVMArgumentsIterator = _make_opaque_ref("LLVMArgumentsIterator")
34
+ LLVMInstructionsIterator = _make_opaque_ref("LLVMInstructionsIterator")
35
+ LLVMOperandsIterator = _make_opaque_ref("LLVMOperandsIterator")
36
+ LLVMIncomingBlocksIterator = _make_opaque_ref("LLVMIncomingBlocksIterator")
37
+ LLVMTypesIterator = _make_opaque_ref("LLVMTypesIterator")
38
+ LLVMObjectCacheRef = _make_opaque_ref("LLVMObjectCache")
39
+ LLVMObjectFileRef = _make_opaque_ref("LLVMObjectFile")
40
+ LLVMSectionIteratorRef = _make_opaque_ref("LLVMSectionIterator")
41
+ LLVMOrcLLJITRef = _make_opaque_ref("LLVMOrcLLJITRef")
42
+ LLVMOrcDylibTrackerRef = _make_opaque_ref("LLVMOrcDylibTrackerRef")
43
+
44
+
45
+ class _LLVMLock:
46
+ """A Lock to guarantee thread-safety for the LLVM C-API.
47
+
48
+ This class implements __enter__ and __exit__ for acquiring and releasing
49
+ the lock as a context manager.
50
+
51
+ Also, callbacks can be attached so that every time the lock is acquired
52
+ and released the corresponding callbacks will be invoked.
53
+ """
54
+ def __init__(self):
55
+ # The reentrant lock is needed for callbacks that re-enter
56
+ # the Python interpreter.
57
+ self._lock = threading.RLock()
58
+ self._cblist = []
59
+
60
+ def register(self, acq_fn, rel_fn):
61
+ """Register callbacks that are invoked immediately after the lock is
62
+ acquired (``acq_fn()``) and immediately before the lock is released
63
+ (``rel_fn()``).
64
+ """
65
+ self._cblist.append((acq_fn, rel_fn))
66
+
67
+ def unregister(self, acq_fn, rel_fn):
68
+ """Remove the registered callbacks.
69
+ """
70
+ self._cblist.remove((acq_fn, rel_fn))
71
+
72
+ def __enter__(self):
73
+ self._lock.acquire()
74
+ # Invoke all callbacks
75
+ for acq_fn, rel_fn in self._cblist:
76
+ acq_fn()
77
+
78
+ def __exit__(self, *exc_details):
79
+ # Invoke all callbacks
80
+ for acq_fn, rel_fn in self._cblist:
81
+ rel_fn()
82
+ self._lock.release()
83
+
84
+
85
+ class _suppress_cleanup_errors:
86
+ def __init__(self, context):
87
+ self._context = context
88
+
89
+ def __enter__(self):
90
+ return self._context.__enter__()
91
+
92
+ def __exit__(self, exc_type, exc_value, traceback):
93
+ try:
94
+ return self._context.__exit__(exc_type, exc_value, traceback)
95
+ except PermissionError:
96
+ pass # Resource dylibs can't be deleted on Windows.
97
+
98
+
99
+ class _lib_wrapper(object):
100
+ """Wrap libllvmlite with a lock such that only one thread may access it at
101
+ a time.
102
+
103
+ This class duck-types a CDLL.
104
+ """
105
+ __slots__ = ['_lib_handle', '_fntab', '_lock']
106
+
107
+ def __init__(self):
108
+ self._lib_handle = None
109
+ self._fntab = {}
110
+ self._lock = _LLVMLock()
111
+
112
+ def _load_lib(self):
113
+ try:
114
+ with _suppress_cleanup_errors(_importlib_resources_path(
115
+ __name__.rpartition(".")[0],
116
+ get_library_name())) as lib_path:
117
+ self._lib_handle = ctypes.CDLL(str(lib_path))
118
+ # Check that we can look up expected symbols.
119
+ _ = self._lib_handle.LLVMPY_GetVersionInfo()
120
+ except (OSError, AttributeError) as e:
121
+ # OSError may be raised if the file cannot be opened, or is not
122
+ # a shared library.
123
+ # AttributeError is raised if LLVMPY_GetVersionInfo does not
124
+ # exist.
125
+ raise OSError("Could not find/load shared object file") from e
126
+
127
+ @property
128
+ def _lib(self):
129
+ # Not threadsafe.
130
+ if not self._lib_handle:
131
+ self._load_lib()
132
+ return self._lib_handle
133
+
134
+ def __getattr__(self, name):
135
+ try:
136
+ return self._fntab[name]
137
+ except KeyError:
138
+ # Lazily wraps new functions as they are requested
139
+ cfn = getattr(self._lib, name)
140
+ wrapped = _lib_fn_wrapper(self._lock, cfn)
141
+ self._fntab[name] = wrapped
142
+ return wrapped
143
+
144
+ @property
145
+ def _name(self):
146
+ """The name of the library passed in the CDLL constructor.
147
+
148
+ For duck-typing a ctypes.CDLL
149
+ """
150
+ return self._lib._name
151
+
152
+ @property
153
+ def _handle(self):
154
+ """The system handle used to access the library.
155
+
156
+ For duck-typing a ctypes.CDLL
157
+ """
158
+ return self._lib._handle
159
+
160
+
161
+ class _lib_fn_wrapper(object):
162
+ """Wraps and duck-types a ctypes.CFUNCTYPE to provide
163
+ automatic locking when the wrapped function is called.
164
+
165
+ TODO: we can add methods to mark the function as threadsafe
166
+ and remove the locking-step on call when marked.
167
+ """
168
+ __slots__ = ['_lock', '_cfn']
169
+
170
+ def __init__(self, lock, cfn):
171
+ self._lock = lock
172
+ self._cfn = cfn
173
+
174
+ @property
175
+ def argtypes(self):
176
+ return self._cfn.argtypes
177
+
178
+ @argtypes.setter
179
+ def argtypes(self, argtypes):
180
+ self._cfn.argtypes = argtypes
181
+
182
+ @property
183
+ def restype(self):
184
+ return self._cfn.restype
185
+
186
+ @restype.setter
187
+ def restype(self, restype):
188
+ self._cfn.restype = restype
189
+
190
+ def __call__(self, *args, **kwargs):
191
+ with self._lock:
192
+ return self._cfn(*args, **kwargs)
193
+
194
+
195
+ def _importlib_resources_path_repl(package, resource):
196
+ """Replacement implementation of `import.resources.path` to avoid
197
+ deprecation warning following code at importlib_resources/_legacy.py
198
+ as suggested by https://importlib-resources.readthedocs.io/en/latest/using.html#migrating-from-legacy
199
+
200
+ Notes on differences from importlib.resources implementation:
201
+
202
+ The `_common.normalize_path(resource)` call is skipped because it is an
203
+ internal API and it is unnecessary for the use here. What it does is
204
+ ensuring `resource` is a str and that it does not contain path separators.
205
+ """ # noqa E501
206
+ return _impres.as_file(_impres.files(package) / resource)
207
+
208
+
209
+ _importlib_resources_path = (_importlib_resources_path_repl
210
+ if sys.version_info[:2] >= (3, 9)
211
+ else _impres.path)
212
+
213
+
214
+ lib = _lib_wrapper()
215
+
216
+
217
+ def register_lock_callback(acq_fn, rel_fn):
218
+ """Register callback functions for lock acquire and release.
219
+ *acq_fn* and *rel_fn* are callables that take no arguments.
220
+ """
221
+ lib._lock.register(acq_fn, rel_fn)
222
+
223
+
224
+ def unregister_lock_callback(acq_fn, rel_fn):
225
+ """Remove the registered callback functions for lock acquire and release.
226
+ The arguments are the same as used in `register_lock_callback()`.
227
+ """
228
+ lib._lock.unregister(acq_fn, rel_fn)
229
+
230
+
231
+ class _DeadPointer(object):
232
+ """
233
+ Dummy class to make error messages more helpful.
234
+ """
235
+
236
+
237
+ class OutputString(object):
238
+ """
239
+ Object for managing the char* output of LLVM APIs.
240
+ """
241
+ _as_parameter_ = _DeadPointer()
242
+
243
+ @classmethod
244
+ def from_return(cls, ptr):
245
+ """Constructing from a pointer returned from the C-API.
246
+ The pointer must be allocated with LLVMPY_CreateString.
247
+
248
+ Note
249
+ ----
250
+ Because ctypes auto-converts *restype* of *c_char_p* into a python
251
+ string, we must use *c_void_p* to obtain the raw pointer.
252
+ """
253
+ return cls(init=ctypes.cast(ptr, ctypes.c_char_p))
254
+
255
+ def __init__(self, owned=True, init=None):
256
+ self._ptr = init if init is not None else ctypes.c_char_p(None)
257
+ self._as_parameter_ = ctypes.byref(self._ptr)
258
+ self._owned = owned
259
+
260
+ def close(self):
261
+ if self._ptr is not None:
262
+ if self._owned:
263
+ lib.LLVMPY_DisposeString(self._ptr)
264
+ self._ptr = None
265
+ del self._as_parameter_
266
+
267
+ def __enter__(self):
268
+ return self
269
+
270
+ def __exit__(self, exc_type, exc_val, exc_tb):
271
+ self.close()
272
+
273
+ def __del__(self, _is_shutting_down=_is_shutting_down):
274
+ # Avoid errors trying to rely on globals and modules at interpreter
275
+ # shutdown.
276
+ if not _is_shutting_down():
277
+ if self.close is not None:
278
+ self.close()
279
+
280
+ def __str__(self):
281
+ if self._ptr is None:
282
+ return "<dead OutputString>"
283
+ s = self._ptr.value
284
+ assert s is not None
285
+ return _decode_string(s)
286
+
287
+ def __bool__(self):
288
+ return bool(self._ptr)
289
+
290
+ __nonzero__ = __bool__
291
+
292
+ @property
293
+ def bytes(self):
294
+ """Get the raw bytes of content of the char pointer.
295
+ """
296
+ return self._ptr.value
297
+
298
+
299
+ def ret_string(ptr):
300
+ """To wrap string return-value from C-API.
301
+ """
302
+ if ptr is not None:
303
+ return str(OutputString.from_return(ptr))
304
+
305
+
306
+ def ret_bytes(ptr):
307
+ """To wrap bytes return-value from C-API.
308
+ """
309
+ if ptr is not None:
310
+ return OutputString.from_return(ptr).bytes
311
+
312
+
313
+ class ObjectRef(object):
314
+ """
315
+ A wrapper around a ctypes pointer to a LLVM object ("resource").
316
+ """
317
+ _closed = False
318
+ _as_parameter_ = _DeadPointer()
319
+ # Whether this object pointer is owned by another one.
320
+ _owned = False
321
+
322
+ def __init__(self, ptr):
323
+ if ptr is None:
324
+ raise ValueError("NULL pointer")
325
+ self._ptr = ptr
326
+ self._as_parameter_ = ptr
327
+ self._capi = lib
328
+
329
+ def close(self):
330
+ """
331
+ Close this object and do any required clean-up actions.
332
+ """
333
+ try:
334
+ if not self._closed and not self._owned:
335
+ self._dispose()
336
+ finally:
337
+ self.detach()
338
+
339
+ def detach(self):
340
+ """
341
+ Detach the underlying LLVM resource without disposing of it.
342
+ """
343
+ if not self._closed:
344
+ del self._as_parameter_
345
+ self._closed = True
346
+ self._ptr = None
347
+
348
+ def _dispose(self):
349
+ """
350
+ Dispose of the underlying LLVM resource. Should be overriden
351
+ by subclasses. Automatically called by close(), __del__() and
352
+ __exit__() (unless the resource has been detached).
353
+ """
354
+
355
+ @property
356
+ def closed(self):
357
+ """
358
+ Whether this object has been closed. A closed object can't
359
+ be used anymore.
360
+ """
361
+ return self._closed
362
+
363
+ def __enter__(self):
364
+ assert hasattr(self, "close")
365
+ if self._closed:
366
+ raise RuntimeError("%s instance already closed" % (self.__class__,))
367
+ return self
368
+
369
+ def __exit__(self, exc_type, exc_val, exc_tb):
370
+ self.close()
371
+
372
+ def __del__(self, _is_shutting_down=_is_shutting_down):
373
+ if not _is_shutting_down():
374
+ if self.close is not None:
375
+ self.close()
376
+
377
+ def __bool__(self):
378
+ return bool(self._ptr)
379
+
380
+ def __eq__(self, other):
381
+ if not hasattr(other, "_ptr"):
382
+ return False
383
+ return ctypes.addressof(self._ptr[0]) == \
384
+ ctypes.addressof(other._ptr[0])
385
+
386
+ __nonzero__ = __bool__
387
+
388
+ # XXX useful?
389
+ def __hash__(self):
390
+ return hash(ctypes.cast(self._ptr, ctypes.c_void_p).value)
vllm/lib/python3.10/site-packages/llvmlite/binding/initfini.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ctypes import c_uint
2
+
3
+ from llvmlite.binding import ffi
4
+
5
+
6
+ def initialize():
7
+ """
8
+ Initialize the LLVM core.
9
+ """
10
+ ffi.lib.LLVMPY_InitializeCore()
11
+
12
+
13
+ def initialize_all_targets():
14
+ """
15
+ Initialize all targets. Necessary before targets can be looked up
16
+ via the :class:`Target` class.
17
+ """
18
+ ffi.lib.LLVMPY_InitializeAllTargetInfos()
19
+ ffi.lib.LLVMPY_InitializeAllTargets()
20
+ ffi.lib.LLVMPY_InitializeAllTargetMCs()
21
+
22
+
23
+ def initialize_all_asmprinters():
24
+ """
25
+ Initialize all code generators. Necessary before generating
26
+ any assembly or machine code via the :meth:`TargetMachine.emit_object`
27
+ and :meth:`TargetMachine.emit_assembly` methods.
28
+ """
29
+ ffi.lib.LLVMPY_InitializeAllAsmPrinters()
30
+
31
+
32
+ def initialize_native_target():
33
+ """
34
+ Initialize the native (host) target. Necessary before doing any
35
+ code generation.
36
+ """
37
+ ffi.lib.LLVMPY_InitializeNativeTarget()
38
+
39
+
40
+ def initialize_native_asmprinter():
41
+ """
42
+ Initialize the native ASM printer.
43
+ """
44
+ ffi.lib.LLVMPY_InitializeNativeAsmPrinter()
45
+
46
+
47
+ def initialize_native_asmparser():
48
+ """
49
+ Initialize the native ASM parser.
50
+ """
51
+ ffi.lib.LLVMPY_InitializeNativeAsmParser()
52
+
53
+
54
+ def shutdown():
55
+ ffi.lib.LLVMPY_Shutdown()
56
+
57
+
58
+ # =============================================================================
59
+ # Set function FFI
60
+
61
+ ffi.lib.LLVMPY_GetVersionInfo.restype = c_uint
62
+
63
+
64
+ def _version_info():
65
+ v = []
66
+ x = ffi.lib.LLVMPY_GetVersionInfo()
67
+ while x:
68
+ v.append(x & 0xff)
69
+ x >>= 8
70
+ return tuple(reversed(v))
71
+
72
+
73
+ llvm_version_info = _version_info()
vllm/lib/python3.10/site-packages/llvmlite/binding/linker.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ctypes import c_int, c_char_p, POINTER
2
+ from llvmlite.binding import ffi
3
+
4
+
5
+ def link_modules(dst, src):
6
+ with ffi.OutputString() as outerr:
7
+ err = ffi.lib.LLVMPY_LinkModules(dst, src, outerr)
8
+ # The underlying module was destroyed
9
+ src.detach()
10
+ if err:
11
+ raise RuntimeError(str(outerr))
12
+
13
+
14
+ ffi.lib.LLVMPY_LinkModules.argtypes = [
15
+ ffi.LLVMModuleRef,
16
+ ffi.LLVMModuleRef,
17
+ POINTER(c_char_p),
18
+ ]
19
+
20
+ ffi.lib.LLVMPY_LinkModules.restype = c_int
vllm/lib/python3.10/site-packages/llvmlite/binding/module.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ctypes import (c_char_p, byref, POINTER, c_bool, create_string_buffer,
2
+ c_size_t, string_at)
3
+
4
+ from llvmlite.binding import ffi
5
+ from llvmlite.binding.linker import link_modules
6
+ from llvmlite.binding.common import _decode_string, _encode_string
7
+ from llvmlite.binding.value import ValueRef, TypeRef
8
+ from llvmlite.binding.context import get_global_context
9
+
10
+
11
+ def parse_assembly(llvmir, context=None):
12
+ """
13
+ Create Module from a LLVM IR string
14
+ """
15
+ if context is None:
16
+ context = get_global_context()
17
+ llvmir = _encode_string(llvmir)
18
+ strbuf = c_char_p(llvmir)
19
+ with ffi.OutputString() as errmsg:
20
+ mod = ModuleRef(
21
+ ffi.lib.LLVMPY_ParseAssembly(context, strbuf, errmsg),
22
+ context)
23
+ if errmsg:
24
+ mod.close()
25
+ raise RuntimeError("LLVM IR parsing error\n{0}".format(errmsg))
26
+ return mod
27
+
28
+
29
+ def parse_bitcode(bitcode, context=None):
30
+ """
31
+ Create Module from a LLVM *bitcode* (a bytes object).
32
+ """
33
+ if context is None:
34
+ context = get_global_context()
35
+ buf = c_char_p(bitcode)
36
+ bufsize = len(bitcode)
37
+ with ffi.OutputString() as errmsg:
38
+ mod = ModuleRef(ffi.lib.LLVMPY_ParseBitcode(
39
+ context, buf, bufsize, errmsg), context)
40
+ if errmsg:
41
+ mod.close()
42
+ raise RuntimeError(
43
+ "LLVM bitcode parsing error\n{0}".format(errmsg))
44
+ return mod
45
+
46
+
47
+ class ModuleRef(ffi.ObjectRef):
48
+ """
49
+ A reference to a LLVM module.
50
+ """
51
+
52
+ def __init__(self, module_ptr, context):
53
+ super(ModuleRef, self).__init__(module_ptr)
54
+ self._context = context
55
+
56
+ def __str__(self):
57
+ with ffi.OutputString() as outstr:
58
+ ffi.lib.LLVMPY_PrintModuleToString(self, outstr)
59
+ return str(outstr)
60
+
61
+ def as_bitcode(self):
62
+ """
63
+ Return the module's LLVM bitcode, as a bytes object.
64
+ """
65
+ ptr = c_char_p(None)
66
+ size = c_size_t(-1)
67
+ ffi.lib.LLVMPY_WriteBitcodeToString(self, byref(ptr), byref(size))
68
+ if not ptr:
69
+ raise MemoryError
70
+ try:
71
+ assert size.value >= 0
72
+ return string_at(ptr, size.value)
73
+ finally:
74
+ ffi.lib.LLVMPY_DisposeString(ptr)
75
+
76
+ def _dispose(self):
77
+ self._capi.LLVMPY_DisposeModule(self)
78
+
79
+ def get_function(self, name):
80
+ """
81
+ Get a ValueRef pointing to the function named *name*.
82
+ NameError is raised if the symbol isn't found.
83
+ """
84
+ p = ffi.lib.LLVMPY_GetNamedFunction(self, _encode_string(name))
85
+ if not p:
86
+ raise NameError(name)
87
+ return ValueRef(p, 'function', dict(module=self))
88
+
89
+ def get_global_variable(self, name):
90
+ """
91
+ Get a ValueRef pointing to the global variable named *name*.
92
+ NameError is raised if the symbol isn't found.
93
+ """
94
+ p = ffi.lib.LLVMPY_GetNamedGlobalVariable(self, _encode_string(name))
95
+ if not p:
96
+ raise NameError(name)
97
+ return ValueRef(p, 'global', dict(module=self))
98
+
99
+ def get_struct_type(self, name):
100
+ """
101
+ Get a TypeRef pointing to a structure type named *name*.
102
+ NameError is raised if the struct type isn't found.
103
+ """
104
+ p = ffi.lib.LLVMPY_GetNamedStructType(self, _encode_string(name))
105
+ if not p:
106
+ raise NameError(name)
107
+ return TypeRef(p)
108
+
109
+ def verify(self):
110
+ """
111
+ Verify the module IR's correctness. RuntimeError is raised on error.
112
+ """
113
+ with ffi.OutputString() as outmsg:
114
+ if ffi.lib.LLVMPY_VerifyModule(self, outmsg):
115
+ raise RuntimeError(str(outmsg))
116
+
117
+ @property
118
+ def name(self):
119
+ """
120
+ The module's identifier.
121
+ """
122
+ return _decode_string(ffi.lib.LLVMPY_GetModuleName(self))
123
+
124
+ @name.setter
125
+ def name(self, value):
126
+ ffi.lib.LLVMPY_SetModuleName(self, _encode_string(value))
127
+
128
+ @property
129
+ def source_file(self):
130
+ """
131
+ The module's original source file name
132
+ """
133
+ return _decode_string(ffi.lib.LLVMPY_GetModuleSourceFileName(self))
134
+
135
+ @property
136
+ def data_layout(self):
137
+ """
138
+ This module's data layout specification, as a string.
139
+ """
140
+ # LLVMGetDataLayout() points inside a std::string managed by LLVM.
141
+ with ffi.OutputString(owned=False) as outmsg:
142
+ ffi.lib.LLVMPY_GetDataLayout(self, outmsg)
143
+ return str(outmsg)
144
+
145
+ @data_layout.setter
146
+ def data_layout(self, strrep):
147
+ ffi.lib.LLVMPY_SetDataLayout(self,
148
+ create_string_buffer(
149
+ strrep.encode('utf8')))
150
+
151
+ @property
152
+ def triple(self):
153
+ """
154
+ This module's target "triple" specification, as a string.
155
+ """
156
+ # LLVMGetTarget() points inside a std::string managed by LLVM.
157
+ with ffi.OutputString(owned=False) as outmsg:
158
+ ffi.lib.LLVMPY_GetTarget(self, outmsg)
159
+ return str(outmsg)
160
+
161
+ @triple.setter
162
+ def triple(self, strrep):
163
+ ffi.lib.LLVMPY_SetTarget(self,
164
+ create_string_buffer(
165
+ strrep.encode('utf8')))
166
+
167
+ def link_in(self, other, preserve=False):
168
+ """
169
+ Link the *other* module into this one. The *other* module will
170
+ be destroyed unless *preserve* is true.
171
+ """
172
+ if preserve:
173
+ other = other.clone()
174
+ link_modules(self, other)
175
+
176
+ @property
177
+ def global_variables(self):
178
+ """
179
+ Return an iterator over this module's global variables.
180
+ The iterator will yield a ValueRef for each global variable.
181
+
182
+ Note that global variables don't include functions
183
+ (a function is a "global value" but not a "global variable" in
184
+ LLVM parlance)
185
+ """
186
+ it = ffi.lib.LLVMPY_ModuleGlobalsIter(self)
187
+ return _GlobalsIterator(it, dict(module=self))
188
+
189
+ @property
190
+ def functions(self):
191
+ """
192
+ Return an iterator over this module's functions.
193
+ The iterator will yield a ValueRef for each function.
194
+ """
195
+ it = ffi.lib.LLVMPY_ModuleFunctionsIter(self)
196
+ return _FunctionsIterator(it, dict(module=self))
197
+
198
+ @property
199
+ def struct_types(self):
200
+ """
201
+ Return an iterator over the struct types defined in
202
+ the module. The iterator will yield a TypeRef.
203
+ """
204
+ it = ffi.lib.LLVMPY_ModuleTypesIter(self)
205
+ return _TypesIterator(it, dict(module=self))
206
+
207
+ def clone(self):
208
+ return ModuleRef(ffi.lib.LLVMPY_CloneModule(self), self._context)
209
+
210
+
211
+ class _Iterator(ffi.ObjectRef):
212
+
213
+ kind = None
214
+
215
+ def __init__(self, ptr, parents):
216
+ ffi.ObjectRef.__init__(self, ptr)
217
+ self._parents = parents
218
+ assert self.kind is not None
219
+
220
+ def __next__(self):
221
+ vp = self._next()
222
+ if vp:
223
+ return ValueRef(vp, self.kind, self._parents)
224
+ else:
225
+ raise StopIteration
226
+
227
+ next = __next__
228
+
229
+ def __iter__(self):
230
+ return self
231
+
232
+
233
+ class _GlobalsIterator(_Iterator):
234
+
235
+ kind = 'global'
236
+
237
+ def _dispose(self):
238
+ self._capi.LLVMPY_DisposeGlobalsIter(self)
239
+
240
+ def _next(self):
241
+ return ffi.lib.LLVMPY_GlobalsIterNext(self)
242
+
243
+
244
+ class _FunctionsIterator(_Iterator):
245
+
246
+ kind = 'function'
247
+
248
+ def _dispose(self):
249
+ self._capi.LLVMPY_DisposeFunctionsIter(self)
250
+
251
+ def _next(self):
252
+ return ffi.lib.LLVMPY_FunctionsIterNext(self)
253
+
254
+
255
+ class _TypesIterator(_Iterator):
256
+
257
+ kind = 'type'
258
+
259
+ def _dispose(self):
260
+ self._capi.LLVMPY_DisposeTypesIter(self)
261
+
262
+ def __next__(self):
263
+ vp = self._next()
264
+ if vp:
265
+ return TypeRef(vp)
266
+ else:
267
+ raise StopIteration
268
+
269
+ def _next(self):
270
+ return ffi.lib.LLVMPY_TypesIterNext(self)
271
+
272
+ next = __next__
273
+
274
+
275
+ # =============================================================================
276
+ # Set function FFI
277
+
278
+ ffi.lib.LLVMPY_ParseAssembly.argtypes = [ffi.LLVMContextRef,
279
+ c_char_p,
280
+ POINTER(c_char_p)]
281
+ ffi.lib.LLVMPY_ParseAssembly.restype = ffi.LLVMModuleRef
282
+
283
+ ffi.lib.LLVMPY_ParseBitcode.argtypes = [ffi.LLVMContextRef,
284
+ c_char_p, c_size_t,
285
+ POINTER(c_char_p)]
286
+ ffi.lib.LLVMPY_ParseBitcode.restype = ffi.LLVMModuleRef
287
+
288
+ ffi.lib.LLVMPY_DisposeModule.argtypes = [ffi.LLVMModuleRef]
289
+
290
+ ffi.lib.LLVMPY_PrintModuleToString.argtypes = [ffi.LLVMModuleRef,
291
+ POINTER(c_char_p)]
292
+ ffi.lib.LLVMPY_WriteBitcodeToString.argtypes = [ffi.LLVMModuleRef,
293
+ POINTER(c_char_p),
294
+ POINTER(c_size_t)]
295
+
296
+ ffi.lib.LLVMPY_GetNamedFunction.argtypes = [ffi.LLVMModuleRef,
297
+ c_char_p]
298
+ ffi.lib.LLVMPY_GetNamedFunction.restype = ffi.LLVMValueRef
299
+
300
+ ffi.lib.LLVMPY_VerifyModule.argtypes = [ffi.LLVMModuleRef,
301
+ POINTER(c_char_p)]
302
+ ffi.lib.LLVMPY_VerifyModule.restype = c_bool
303
+
304
+ ffi.lib.LLVMPY_GetDataLayout.argtypes = [ffi.LLVMModuleRef, POINTER(c_char_p)]
305
+ ffi.lib.LLVMPY_SetDataLayout.argtypes = [ffi.LLVMModuleRef, c_char_p]
306
+
307
+ ffi.lib.LLVMPY_GetTarget.argtypes = [ffi.LLVMModuleRef, POINTER(c_char_p)]
308
+ ffi.lib.LLVMPY_SetTarget.argtypes = [ffi.LLVMModuleRef, c_char_p]
309
+
310
+ ffi.lib.LLVMPY_GetNamedGlobalVariable.argtypes = [ffi.LLVMModuleRef, c_char_p]
311
+ ffi.lib.LLVMPY_GetNamedGlobalVariable.restype = ffi.LLVMValueRef
312
+
313
+ ffi.lib.LLVMPY_GetNamedStructType.argtypes = [ffi.LLVMModuleRef, c_char_p]
314
+ ffi.lib.LLVMPY_GetNamedStructType.restype = ffi.LLVMTypeRef
315
+
316
+ ffi.lib.LLVMPY_ModuleGlobalsIter.argtypes = [ffi.LLVMModuleRef]
317
+ ffi.lib.LLVMPY_ModuleGlobalsIter.restype = ffi.LLVMGlobalsIterator
318
+
319
+ ffi.lib.LLVMPY_DisposeGlobalsIter.argtypes = [ffi.LLVMGlobalsIterator]
320
+
321
+ ffi.lib.LLVMPY_GlobalsIterNext.argtypes = [ffi.LLVMGlobalsIterator]
322
+ ffi.lib.LLVMPY_GlobalsIterNext.restype = ffi.LLVMValueRef
323
+
324
+ ffi.lib.LLVMPY_ModuleFunctionsIter.argtypes = [ffi.LLVMModuleRef]
325
+ ffi.lib.LLVMPY_ModuleFunctionsIter.restype = ffi.LLVMFunctionsIterator
326
+
327
+ ffi.lib.LLVMPY_ModuleTypesIter.argtypes = [ffi.LLVMModuleRef]
328
+ ffi.lib.LLVMPY_ModuleTypesIter.restype = ffi.LLVMTypesIterator
329
+
330
+ ffi.lib.LLVMPY_DisposeFunctionsIter.argtypes = [ffi.LLVMFunctionsIterator]
331
+
332
+ ffi.lib.LLVMPY_DisposeTypesIter.argtypes = [ffi.LLVMTypesIterator]
333
+
334
+ ffi.lib.LLVMPY_FunctionsIterNext.argtypes = [ffi.LLVMFunctionsIterator]
335
+ ffi.lib.LLVMPY_FunctionsIterNext.restype = ffi.LLVMValueRef
336
+
337
+ ffi.lib.LLVMPY_TypesIterNext.argtypes = [ffi.LLVMTypesIterator]
338
+ ffi.lib.LLVMPY_TypesIterNext.restype = ffi.LLVMTypeRef
339
+
340
+ ffi.lib.LLVMPY_CloneModule.argtypes = [ffi.LLVMModuleRef]
341
+ ffi.lib.LLVMPY_CloneModule.restype = ffi.LLVMModuleRef
342
+
343
+ ffi.lib.LLVMPY_GetModuleName.argtypes = [ffi.LLVMModuleRef]
344
+ ffi.lib.LLVMPY_GetModuleName.restype = c_char_p
345
+
346
+ ffi.lib.LLVMPY_SetModuleName.argtypes = [ffi.LLVMModuleRef, c_char_p]
347
+
348
+ ffi.lib.LLVMPY_GetModuleSourceFileName.argtypes = [ffi.LLVMModuleRef]
349
+ ffi.lib.LLVMPY_GetModuleSourceFileName.restype = c_char_p
vllm/lib/python3.10/site-packages/llvmlite/binding/object_file.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from llvmlite.binding import ffi
2
+ from ctypes import (c_bool, c_char_p, c_char, c_size_t, string_at, c_uint64,
3
+ POINTER)
4
+
5
+
6
+ class SectionIteratorRef(ffi.ObjectRef):
7
+ def name(self):
8
+ return ffi.lib.LLVMPY_GetSectionName(self)
9
+
10
+ def is_text(self):
11
+ return ffi.lib.LLVMPY_IsSectionText(self)
12
+
13
+ def size(self):
14
+ return ffi.lib.LLVMPY_GetSectionSize(self)
15
+
16
+ def address(self):
17
+ return ffi.lib.LLVMPY_GetSectionAddress(self)
18
+
19
+ def data(self):
20
+ return string_at(ffi.lib.LLVMPY_GetSectionContents(self), self.size())
21
+
22
+ def is_end(self, object_file):
23
+ return ffi.lib.LLVMPY_IsSectionIteratorAtEnd(object_file, self)
24
+
25
+ def next(self):
26
+ ffi.lib.LLVMPY_MoveToNextSection(self)
27
+
28
+ def _dispose(self):
29
+ ffi.lib.LLVMPY_DisposeSectionIterator(self)
30
+
31
+
32
+ class ObjectFileRef(ffi.ObjectRef):
33
+ @classmethod
34
+ def from_data(cls, data):
35
+ return cls(ffi.lib.LLVMPY_CreateObjectFile(data, len(data)))
36
+
37
+ @classmethod
38
+ def from_path(cls, path):
39
+ with open(path, 'rb') as f:
40
+ data = f.read()
41
+ return cls(ffi.lib.LLVMPY_CreateObjectFile(data, len(data)))
42
+
43
+ def sections(self):
44
+ it = SectionIteratorRef(ffi.lib.LLVMPY_GetSections(self))
45
+ while not it.is_end(self):
46
+ yield it
47
+ it.next()
48
+
49
+ def _dispose(self):
50
+ ffi.lib.LLVMPY_DisposeObjectFile(self)
51
+
52
+
53
+ ffi.lib.LLVMPY_CreateObjectFile.argtypes = [c_char_p, c_size_t]
54
+ ffi.lib.LLVMPY_CreateObjectFile.restype = ffi.LLVMObjectFileRef
55
+
56
+ ffi.lib.LLVMPY_DisposeObjectFile.argtypes = [ffi.LLVMObjectFileRef]
57
+
58
+ ffi.lib.LLVMPY_GetSections.argtypes = [ffi.LLVMObjectFileRef]
59
+ ffi.lib.LLVMPY_GetSections.restype = ffi.LLVMSectionIteratorRef
60
+
61
+ ffi.lib.LLVMPY_DisposeSectionIterator.argtypes = [ffi.LLVMSectionIteratorRef]
62
+
63
+ ffi.lib.LLVMPY_MoveToNextSection.argtypes = [ffi.LLVMSectionIteratorRef]
64
+
65
+ ffi.lib.LLVMPY_IsSectionIteratorAtEnd.argtypes = [
66
+ ffi.LLVMObjectFileRef, ffi.LLVMSectionIteratorRef]
67
+ ffi.lib.LLVMPY_IsSectionIteratorAtEnd.restype = c_bool
68
+
69
+ ffi.lib.LLVMPY_GetSectionName.argtypes = [ffi.LLVMSectionIteratorRef]
70
+ ffi.lib.LLVMPY_GetSectionName.restype = c_char_p
71
+
72
+ ffi.lib.LLVMPY_GetSectionSize.argtypes = [ffi.LLVMSectionIteratorRef]
73
+ ffi.lib.LLVMPY_GetSectionSize.restype = c_uint64
74
+
75
+ ffi.lib.LLVMPY_GetSectionAddress.argtypes = [ffi.LLVMSectionIteratorRef]
76
+ ffi.lib.LLVMPY_GetSectionAddress.restype = c_uint64
77
+
78
+ ffi.lib.LLVMPY_GetSectionContents.argtypes = [ffi.LLVMSectionIteratorRef]
79
+ ffi.lib.LLVMPY_GetSectionContents.restype = POINTER(c_char)
80
+
81
+ ffi.lib.LLVMPY_IsSectionText.argtypes = [ffi.LLVMSectionIteratorRef]
82
+ ffi.lib.LLVMPY_IsSectionText.restype = c_bool
vllm/lib/python3.10/site-packages/llvmlite/binding/options.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from llvmlite.binding import ffi
2
+ from llvmlite.binding.common import _encode_string
3
+ from ctypes import c_char_p
4
+
5
+
6
+ def set_option(name, option):
7
+ """
8
+ Set the given LLVM "command-line" option.
9
+
10
+ For example set_option("test", "-debug-pass=Structure") would display
11
+ all optimization passes when generating code.
12
+ """
13
+ ffi.lib.LLVMPY_SetCommandLine(_encode_string(name),
14
+ _encode_string(option))
15
+
16
+
17
+ ffi.lib.LLVMPY_SetCommandLine.argtypes = [c_char_p, c_char_p]
vllm/lib/python3.10/site-packages/llvmlite/binding/orcjit.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ctypes
2
+ from ctypes import POINTER, c_bool, c_char_p, c_uint8, c_uint64, c_size_t
3
+
4
+ from llvmlite.binding import ffi, targets
5
+
6
+
7
+ class _LinkElement(ctypes.Structure):
8
+ _fields_ = [("element_kind", c_uint8),
9
+ ("value", c_char_p),
10
+ ("value_len", c_size_t)]
11
+
12
+
13
+ class _SymbolAddress(ctypes.Structure):
14
+ _fields_ = [("name", c_char_p), ("address", c_uint64)]
15
+
16
+
17
+ class JITLibraryBuilder:
18
+ """
19
+ Create a library for linking by OrcJIT
20
+
21
+ OrcJIT operates like a linker: a number of compilation units and
22
+ dependencies are collected together and linked into a single dynamic library
23
+ that can export functions to other libraries or to be consumed directly as
24
+ entry points into JITted code. The native OrcJIT has a lot of memory
25
+ management complications so this API is designed to work well with Python's
26
+ garbage collection.
27
+
28
+ The creation of a new library is a bit like a linker command line where
29
+ compilation units, mostly as LLVM IR, and previously constructed libraries
30
+ are linked together, then loaded into memory, and the addresses of exported
31
+ symbols are extracted. Any static initializers are run and the exported
32
+ addresses and a resource tracker is produced. As long as the resource
33
+ tracker is referenced somewhere in Python, the exported addresses will be
34
+ valid. Once the resource tracker is garbage collected, the static
35
+ destructors will run and library will be unloaded from memory.
36
+ """
37
+ def __init__(self):
38
+ self.__entries = []
39
+ self.__exports = set()
40
+ self.__imports = {}
41
+
42
+ def add_ir(self, llvmir):
43
+ """
44
+ Adds a compilation unit to the library using LLVM IR as the input
45
+ format.
46
+
47
+ This takes a string or an object that can be converted to a string,
48
+ including IRBuilder, that contains LLVM IR.
49
+ """
50
+ self.__entries.append((0, str(llvmir).encode('utf-8')))
51
+ return self
52
+
53
+ def add_native_assembly(self, asm):
54
+ """
55
+ Adds a compilation unit to the library using native assembly as the
56
+ input format.
57
+
58
+ This takes a string or an object that can be converted to a string that
59
+ contains native assembly, which will be
60
+ parsed by LLVM.
61
+ """
62
+ self.__entries.append((1, str(asm).encode('utf-8')))
63
+ return self
64
+
65
+ def add_object_img(self, data):
66
+ """
67
+ Adds a compilation unit to the library using pre-compiled object code.
68
+
69
+ This takes the bytes of the contents of an object artifact which will be
70
+ loaded by LLVM.
71
+ """
72
+ self.__entries.append((2, bytes(data)))
73
+ return self
74
+
75
+ def add_object_file(self, file_path):
76
+ """
77
+ Adds a compilation unit to the library using pre-compiled object file.
78
+
79
+ This takes a string or path-like object that references an object file
80
+ which will be loaded by LLVM.
81
+ """
82
+ with open(file_path, "rb") as f:
83
+ self.__entries.append((2, f.read()))
84
+ return self
85
+
86
+ def add_jit_library(self, name):
87
+ """
88
+ Adds an existing JIT library as prerequisite.
89
+
90
+ The name of the library must match the one provided in a previous link
91
+ command.
92
+ """
93
+ self.__entries.append((3, str(name).encode('utf-8')))
94
+ return self
95
+
96
+ def add_current_process(self):
97
+ """
98
+ Allows the JITted library to access symbols in the current binary.
99
+
100
+ That is, it allows exporting the current binary's symbols, including
101
+ loaded libraries, as imports to the JITted
102
+ library.
103
+ """
104
+ self.__entries.append((3, b''))
105
+ return self
106
+
107
+ def import_symbol(self, name, address):
108
+ """
109
+ Register the *address* of global symbol *name*. This will make
110
+ it usable (e.g. callable) from LLVM-compiled functions.
111
+ """
112
+ self.__imports[str(name)] = c_uint64(address)
113
+ return self
114
+
115
+ def export_symbol(self, name):
116
+ """
117
+ During linking, extract the address of a symbol that was defined in one
118
+ of the compilation units.
119
+
120
+ This allows getting symbols, functions or global variables, out of the
121
+ JIT linked library. The addresses will be
122
+ available when the link method is called.
123
+ """
124
+ self.__exports.add(str(name))
125
+ return self
126
+
127
+ def link(self, lljit, library_name):
128
+ """
129
+ Link all the current compilation units into a JITted library and extract
130
+ the address of exported symbols.
131
+
132
+ An instance of the OrcJIT instance must be provided and this will be the
133
+ scope that is used to find other JITted libraries that are dependencies
134
+ and also be the place where this library will be defined.
135
+
136
+ After linking, the method will return a resource tracker that keeps the
137
+ library alive. This tracker also knows the addresses of any exported
138
+ symbols that were requested.
139
+
140
+ The addresses will be valid as long as the resource tracker is
141
+ referenced.
142
+
143
+ When the resource tracker is destroyed, the library will be cleaned up,
144
+ however, the name of the library cannot be reused.
145
+ """
146
+ assert not lljit.closed, "Cannot add to closed JIT"
147
+ encoded_library_name = str(library_name).encode('utf-8')
148
+ assert len(encoded_library_name) > 0, "Library cannot be empty"
149
+ elements = (_LinkElement * len(self.__entries))()
150
+ for idx, (kind, value) in enumerate(self.__entries):
151
+ elements[idx].element_kind = c_uint8(kind)
152
+ elements[idx].value = c_char_p(value)
153
+ elements[idx].value_len = c_size_t(len(value))
154
+ exports = (_SymbolAddress * len(self.__exports))()
155
+ for idx, name in enumerate(self.__exports):
156
+ exports[idx].name = name.encode('utf-8')
157
+
158
+ imports = (_SymbolAddress * len(self.__imports))()
159
+ for idx, (name, addr) in enumerate(self.__imports.items()):
160
+ imports[idx].name = name.encode('utf-8')
161
+ imports[idx].address = addr
162
+
163
+ with ffi.OutputString() as outerr:
164
+ tracker = lljit._capi.LLVMPY_LLJIT_Link(
165
+ lljit._ptr,
166
+ encoded_library_name,
167
+ elements,
168
+ len(self.__entries),
169
+ imports,
170
+ len(self.__imports),
171
+ exports,
172
+ len(self.__exports),
173
+ outerr)
174
+ if not tracker:
175
+ raise RuntimeError(str(outerr))
176
+ return ResourceTracker(tracker,
177
+ library_name,
178
+ {name: exports[idx].address
179
+ for idx, name in enumerate(self.__exports)})
180
+
181
+
182
+ class ResourceTracker(ffi.ObjectRef):
183
+ """
184
+ A resource tracker is created for each loaded JIT library and keeps the
185
+ module alive.
186
+
187
+ OrcJIT supports unloading libraries that are no longer used. This resource
188
+ tracker should be stored in any object that reference functions or constants
189
+ for a JITted library. When all references to the resource tracker are
190
+ dropped, this will trigger LLVM to unload the library and destroy any
191
+ functions.
192
+
193
+ Failure to keep resource trackers while calling a function or accessing a
194
+ symbol can result in crashes or memory corruption.
195
+
196
+ LLVM internally tracks references between different libraries, so only
197
+ "leaf" libraries need to be tracked.
198
+ """
199
+ def __init__(self, ptr, name, addresses):
200
+ self.__addresses = addresses
201
+ self.__name = name
202
+ ffi.ObjectRef.__init__(self, ptr)
203
+
204
+ def __getitem__(self, item):
205
+ """
206
+ Get the address of an exported symbol as an integer
207
+ """
208
+ return self.__addresses[item]
209
+
210
+ @property
211
+ def name(self):
212
+ return self.__name
213
+
214
+ def _dispose(self):
215
+ with ffi.OutputString() as outerr:
216
+ if self._capi.LLVMPY_LLJIT_Dylib_Tracker_Dispose(self, outerr):
217
+ raise RuntimeError(str(outerr))
218
+
219
+
220
+ class LLJIT(ffi.ObjectRef):
221
+ """
222
+ A OrcJIT-based LLVM JIT engine that can compile and run LLVM IR as a
223
+ collection of JITted dynamic libraries
224
+
225
+ The C++ OrcJIT API has a lot of memory ownership patterns that do not work
226
+ with Python. This API attempts to provide ones that are safe at the expense
227
+ of some features. Each LLJIT instance is a collection of JIT-compiled
228
+ libraries. In the C++ API, there is a "main" library; this API does not
229
+ provide access to the main library. Use the JITLibraryBuilder to create a
230
+ new named library instead.
231
+ """
232
+ def __init__(self, ptr):
233
+ self._td = None
234
+ ffi.ObjectRef.__init__(self, ptr)
235
+
236
+ def lookup(self, dylib, fn):
237
+ """
238
+ Find a function in this dynamic library and construct a new tracking
239
+ object for it
240
+
241
+ If the library or function do not exist, an exception will occur.
242
+
243
+ Parameters
244
+ ----------
245
+ dylib : str or None
246
+ the name of the library containing the symbol
247
+ fn : str
248
+ the name of the function to get
249
+ """
250
+ assert not self.closed, "Cannot lookup in closed JIT"
251
+ address = ctypes.c_uint64()
252
+ with ffi.OutputString() as outerr:
253
+ tracker = ffi.lib.LLVMPY_LLJITLookup(self,
254
+ dylib.encode("utf-8"),
255
+ fn.encode("utf-8"),
256
+ ctypes.byref(address),
257
+ outerr)
258
+ if not tracker:
259
+ raise RuntimeError(str(outerr))
260
+
261
+ return ResourceTracker(tracker, dylib, {fn: address.value})
262
+
263
+ @property
264
+ def target_data(self):
265
+ """
266
+ The TargetData for this LLJIT instance.
267
+ """
268
+ if self._td is not None:
269
+ return self._td
270
+ ptr = ffi.lib.LLVMPY_LLJITGetDataLayout(self)
271
+ self._td = targets.TargetData(ptr)
272
+ self._td._owned = True
273
+ return self._td
274
+
275
+ def _dispose(self):
276
+ if self._td is not None:
277
+ self._td.detach()
278
+ self._capi.LLVMPY_LLJITDispose(self)
279
+
280
+
281
+ def create_lljit_compiler(target_machine=None, *,
282
+ use_jit_link=False,
283
+ suppress_errors=False):
284
+ """
285
+ Create an LLJIT instance
286
+ """
287
+ with ffi.OutputString() as outerr:
288
+ lljit = ffi.lib.LLVMPY_CreateLLJITCompiler(target_machine,
289
+ suppress_errors,
290
+ use_jit_link,
291
+ outerr)
292
+ if not lljit:
293
+ raise RuntimeError(str(outerr))
294
+
295
+ return LLJIT(lljit)
296
+
297
+
298
+ ffi.lib.LLVMPY_LLJITLookup.argtypes = [
299
+ ffi.LLVMOrcLLJITRef,
300
+ c_char_p,
301
+ c_char_p,
302
+ POINTER(c_uint64),
303
+ POINTER(c_char_p),
304
+ ]
305
+ ffi.lib.LLVMPY_LLJITLookup.restype = ffi.LLVMOrcDylibTrackerRef
306
+
307
+ ffi.lib.LLVMPY_LLJITGetDataLayout.argtypes = [
308
+ ffi.LLVMOrcLLJITRef,
309
+ ]
310
+ ffi.lib.LLVMPY_LLJITGetDataLayout.restype = ffi.LLVMTargetDataRef
311
+
312
+ ffi.lib.LLVMPY_CreateLLJITCompiler.argtypes = [
313
+ ffi.LLVMTargetMachineRef,
314
+ c_bool,
315
+ c_bool,
316
+ POINTER(c_char_p),
317
+ ]
318
+ ffi.lib.LLVMPY_CreateLLJITCompiler.restype = ffi.LLVMOrcLLJITRef
319
+
320
+ ffi.lib.LLVMPY_LLJITDispose.argtypes = [
321
+ ffi.LLVMOrcLLJITRef,
322
+ ]
323
+
324
+
325
+ ffi.lib.LLVMPY_LLJIT_Link.argtypes = [
326
+ ffi.LLVMOrcLLJITRef,
327
+ c_char_p,
328
+ POINTER(_LinkElement),
329
+ c_size_t,
330
+ POINTER(_SymbolAddress),
331
+ c_size_t,
332
+ POINTER(_SymbolAddress),
333
+ c_size_t,
334
+ POINTER(c_char_p)
335
+ ]
336
+ ffi.lib.LLVMPY_LLJIT_Link.restype = ffi.LLVMOrcDylibTrackerRef
337
+
338
+ ffi.lib.LLVMPY_LLJIT_Dylib_Tracker_Dispose.argtypes = [
339
+ ffi.LLVMOrcDylibTrackerRef,
340
+ POINTER(c_char_p)
341
+ ]
342
+ ffi.lib.LLVMPY_LLJIT_Dylib_Tracker_Dispose.restype = c_bool
vllm/lib/python3.10/site-packages/llvmlite/binding/passmanagers.py ADDED
@@ -0,0 +1,939 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ctypes import (c_bool, c_char_p, c_int, c_size_t, c_uint, Structure, byref,
2
+ POINTER)
3
+ from collections import namedtuple
4
+ from enum import IntFlag
5
+ from llvmlite.binding import ffi
6
+ from llvmlite.binding.initfini import llvm_version_info
7
+ import os
8
+ from tempfile import mkstemp
9
+ from llvmlite.binding.common import _encode_string
10
+
11
+ _prunestats = namedtuple('PruneStats',
12
+ ('basicblock diamond fanout fanout_raise'))
13
+
14
+ llvm_version_major = llvm_version_info[0]
15
+
16
+
17
+ class PruneStats(_prunestats):
18
+ """ Holds statistics from reference count pruning.
19
+ """
20
+
21
+ def __add__(self, other):
22
+ if not isinstance(other, PruneStats):
23
+ msg = 'PruneStats can only be added to another PruneStats, got {}.'
24
+ raise TypeError(msg.format(type(other)))
25
+ return PruneStats(self.basicblock + other.basicblock,
26
+ self.diamond + other.diamond,
27
+ self.fanout + other.fanout,
28
+ self.fanout_raise + other.fanout_raise)
29
+
30
+ def __sub__(self, other):
31
+ if not isinstance(other, PruneStats):
32
+ msg = ('PruneStats can only be subtracted from another PruneStats, '
33
+ 'got {}.')
34
+ raise TypeError(msg.format(type(other)))
35
+ return PruneStats(self.basicblock - other.basicblock,
36
+ self.diamond - other.diamond,
37
+ self.fanout - other.fanout,
38
+ self.fanout_raise - other.fanout_raise)
39
+
40
+
41
+ class _c_PruneStats(Structure):
42
+ _fields_ = [
43
+ ('basicblock', c_size_t),
44
+ ('diamond', c_size_t),
45
+ ('fanout', c_size_t),
46
+ ('fanout_raise', c_size_t)]
47
+
48
+
49
+ def dump_refprune_stats(printout=False):
50
+ """ Returns a namedtuple containing the current values for the refop pruning
51
+ statistics. If kwarg `printout` is True the stats are printed to stderr,
52
+ default is False.
53
+ """
54
+
55
+ stats = _c_PruneStats(0, 0, 0, 0)
56
+ do_print = c_bool(printout)
57
+
58
+ ffi.lib.LLVMPY_DumpRefPruneStats(byref(stats), do_print)
59
+ return PruneStats(stats.basicblock, stats.diamond, stats.fanout,
60
+ stats.fanout_raise)
61
+
62
+
63
+ def set_time_passes(enable):
64
+ """Enable or disable the pass timers.
65
+
66
+ Parameters
67
+ ----------
68
+ enable : bool
69
+ Set to True to enable the pass timers.
70
+ Set to False to disable the pass timers.
71
+ """
72
+ ffi.lib.LLVMPY_SetTimePasses(c_bool(enable))
73
+
74
+
75
+ def report_and_reset_timings():
76
+ """Returns the pass timings report and resets the LLVM internal timers.
77
+
78
+ Pass timers are enabled by ``set_time_passes()``. If the timers are not
79
+ enabled, this function will return an empty string.
80
+
81
+ Returns
82
+ -------
83
+ res : str
84
+ LLVM generated timing report.
85
+ """
86
+ with ffi.OutputString() as buf:
87
+ ffi.lib.LLVMPY_ReportAndResetTimings(buf)
88
+ return str(buf)
89
+
90
+
91
+ def create_module_pass_manager():
92
+ return ModulePassManager()
93
+
94
+
95
+ def create_function_pass_manager(module):
96
+ return FunctionPassManager(module)
97
+
98
+
99
+ class RefPruneSubpasses(IntFlag):
100
+ PER_BB = 0b0001 # noqa: E221
101
+ DIAMOND = 0b0010 # noqa: E221
102
+ FANOUT = 0b0100 # noqa: E221
103
+ FANOUT_RAISE = 0b1000
104
+ ALL = PER_BB | DIAMOND | FANOUT | FANOUT_RAISE
105
+
106
+
107
+ class PassManager(ffi.ObjectRef):
108
+ """PassManager
109
+ """
110
+
111
+ def _dispose(self):
112
+ self._capi.LLVMPY_DisposePassManager(self)
113
+
114
+ def add_aa_eval_pass(self):
115
+ """
116
+ See https://llvm.org/docs/Passes.html#aa-eval-exhaustive-alias-analysis-precision-evaluator
117
+
118
+ LLVM 14: `llvm::createAAEvalPass`
119
+ """ # noqa E501
120
+ ffi.lib.LLVMPY_AddAAEvalPass(self)
121
+
122
+ def add_basic_aa_pass(self):
123
+ """
124
+ See https://llvm.org/docs/Passes.html#basic-aa-basic-alias-analysis-stateless-aa-impl
125
+
126
+ LLVM 14: `llvm::createBasicAAWrapperPass`
127
+ """ # noqa E501
128
+ ffi.lib.LLVMPY_AddBasicAAWrapperPass(self)
129
+
130
+ def add_constant_merge_pass(self):
131
+ """
132
+ See http://llvm.org/docs/Passes.html#constmerge-merge-duplicate-global-constants
133
+
134
+ LLVM 14: `LLVMAddConstantMergePass`
135
+ """ # noqa E501
136
+ ffi.lib.LLVMPY_AddConstantMergePass(self)
137
+
138
+ def add_dead_arg_elimination_pass(self):
139
+ """
140
+ See http://llvm.org/docs/Passes.html#deadargelim-dead-argument-elimination
141
+
142
+ LLVM 14: `LLVMAddDeadArgEliminationPass`
143
+ """ # noqa E501
144
+ ffi.lib.LLVMPY_AddDeadArgEliminationPass(self)
145
+
146
+ def add_dependence_analysis_pass(self):
147
+ """
148
+ See https://llvm.org/docs/Passes.html#da-dependence-analysis
149
+
150
+ LLVM 14: `llvm::createDependenceAnalysisWrapperPass`
151
+ """ # noqa E501
152
+ ffi.lib.LLVMPY_AddDependenceAnalysisPass(self)
153
+
154
+ def add_dot_call_graph_pass(self):
155
+ """
156
+ See https://llvm.org/docs/Passes.html#dot-callgraph-print-call-graph-to-dot-file
157
+
158
+ LLVM 14: `llvm::createCallGraphDOTPrinterPass`
159
+ """ # noqa E501
160
+ ffi.lib.LLVMPY_AddCallGraphDOTPrinterPass(self)
161
+
162
+ def add_dot_cfg_printer_pass(self):
163
+ """
164
+ See https://llvm.org/docs/Passes.html#dot-cfg-print-cfg-of-function-to-dot-file
165
+
166
+ LLVM 14: `llvm::createCFGPrinterLegacyPassPass`
167
+ """ # noqa E501
168
+ ffi.lib.LLVMPY_AddCFGPrinterPass(self)
169
+
170
+ def add_dot_dom_printer_pass(self, show_body=False):
171
+ """
172
+ See https://llvm.org/docs/Passes.html#dot-dom-print-dominance-tree-of-function-to-dot-file
173
+
174
+ LLVM 14: `llvm::createDomPrinterPass` and `llvm::createDomOnlyPrinterPass`
175
+ """ # noqa E501
176
+ ffi.lib.LLVMPY_AddDotDomPrinterPass(self, show_body)
177
+
178
+ def add_dot_postdom_printer_pass(self, show_body=False):
179
+ """
180
+ See https://llvm.org/docs/Passes.html#dot-postdom-print-postdominance-tree-of-function-to-dot-file
181
+
182
+ LLVM 14: `llvm::createPostDomPrinterPass` and `llvm::createPostDomOnlyPrinterPass`
183
+ """ # noqa E501
184
+ ffi.lib.LLVMPY_AddDotPostDomPrinterPass(self, show_body)
185
+
186
+ def add_globals_mod_ref_aa_pass(self):
187
+ """
188
+ See https://llvm.org/docs/Passes.html#globalsmodref-aa-simple-mod-ref-analysis-for-globals
189
+
190
+ LLVM 14: `llvm::createGlobalsAAWrapperPass`
191
+ """ # noqa E501
192
+ ffi.lib.LLVMPY_AddGlobalsModRefAAPass(self)
193
+
194
+ def add_iv_users_pass(self):
195
+ """
196
+ See https://llvm.org/docs/Passes.html#iv-users-induction-variable-users
197
+
198
+ LLVM 14: `llvm::createIVUsersPass`
199
+ """ # noqa E501
200
+ ffi.lib.LLVMPY_AddIVUsersPass(self)
201
+
202
+ def add_lint_pass(self):
203
+ """
204
+ See https://llvm.org/docs/Passes.html#lint-statically-lint-checks-llvm-ir
205
+
206
+ LLVM 14: `llvm::createLintLegacyPassPass`
207
+ """ # noqa E501
208
+ ffi.lib.LLVMPY_AddLintPass(self)
209
+
210
+ def add_lazy_value_info_pass(self):
211
+ """
212
+ See https://llvm.org/docs/Passes.html#lazy-value-info-lazy-value-information-analysis
213
+
214
+ LLVM 14: `llvm::createLazyValueInfoPass`
215
+ """ # noqa E501
216
+ ffi.lib.LLVMPY_AddLazyValueInfoPass(self)
217
+
218
+ def add_module_debug_info_pass(self):
219
+ """
220
+ See https://llvm.org/docs/Passes.html#module-debuginfo-decodes-module-level-debug-info
221
+
222
+ LLVM 14: `llvm::createModuleDebugInfoPrinterPass`
223
+ """ # noqa E501
224
+ ffi.lib.LLVMPY_AddModuleDebugInfoPrinterPass(self)
225
+
226
+ def add_region_info_pass(self):
227
+ """
228
+ See https://llvm.org/docs/Passes.html#regions-detect-single-entry-single-exit-regions
229
+
230
+ LLVM 14: `llvm::createRegionInfoPass`
231
+ """ # noqa E501
232
+ ffi.lib.LLVMPY_AddRegionInfoPass(self)
233
+
234
+ def add_scalar_evolution_aa_pass(self):
235
+ """
236
+ See https://llvm.org/docs/Passes.html#scev-aa-scalarevolution-based-alias-analysis
237
+
238
+ LLVM 14: `llvm::createSCEVAAWrapperPass`
239
+ """ # noqa E501
240
+ ffi.lib.LLVMPY_AddScalarEvolutionAAPass(self)
241
+
242
+ def add_aggressive_dead_code_elimination_pass(self):
243
+ """
244
+ See https://llvm.org/docs/Passes.html#adce-aggressive-dead-code-elimination
245
+
246
+ LLVM 14: `llvm::createAggressiveDCEPass`
247
+ """ # noqa E501
248
+ ffi.lib.LLVMPY_AddAggressiveDCEPass(self)
249
+
250
+ def add_always_inliner_pass(self, insert_lifetime=True):
251
+ """
252
+ See https://llvm.org/docs/Passes.html#always-inline-inliner-for-always-inline-functions
253
+
254
+ LLVM 14: `llvm::createAlwaysInlinerLegacyPass`
255
+ """ # noqa E501
256
+ ffi.lib.LLVMPY_AddAlwaysInlinerPass(self, insert_lifetime)
257
+
258
+ def add_arg_promotion_pass(self, max_elements=3):
259
+ """
260
+ See https://llvm.org/docs/Passes.html#argpromotion-promote-by-reference-arguments-to-scalars
261
+
262
+ LLVM 14: `llvm::createArgumentPromotionPass`
263
+ """ # noqa E501
264
+ if llvm_version_major > 14:
265
+ raise RuntimeError('ArgumentPromotionPass unavailable in LLVM > 14')
266
+ ffi.lib.LLVMPY_AddArgPromotionPass(self, max_elements)
267
+
268
+ def add_break_critical_edges_pass(self):
269
+ """
270
+ See https://llvm.org/docs/Passes.html#break-crit-edges-break-critical-edges-in-cfg
271
+
272
+ LLVM 14: `llvm::createBreakCriticalEdgesPass`
273
+ """ # noqa E501
274
+ ffi.lib.LLVMPY_AddBreakCriticalEdgesPass(self)
275
+
276
+ def add_dead_store_elimination_pass(self):
277
+ """
278
+ See https://llvm.org/docs/Passes.html#dse-dead-store-elimination
279
+
280
+ LLVM 14: `llvm::createDeadStoreEliminationPass`
281
+ """ # noqa E501
282
+ ffi.lib.LLVMPY_AddDeadStoreEliminationPass(self)
283
+
284
+ def add_reverse_post_order_function_attrs_pass(self):
285
+ """
286
+ See https://llvm.org/docs/Passes.html#function-attrs-deduce-function-attributes
287
+
288
+ LLVM 14: `llvm::createReversePostOrderFunctionAttrsPass`
289
+ """ # noqa E501
290
+ ffi.lib.LLVMPY_AddReversePostOrderFunctionAttrsPass(self)
291
+
292
+ def add_function_attrs_pass(self):
293
+ """
294
+ See http://llvm.org/docs/Passes.html#functionattrs-deduce-function-attributes
295
+
296
+ LLVM 14: `LLVMAddFunctionAttrsPass`
297
+ """ # noqa E501
298
+ ffi.lib.LLVMPY_AddFunctionAttrsPass(self)
299
+
300
+ def add_function_inlining_pass(self, threshold):
301
+ """
302
+ See http://llvm.org/docs/Passes.html#inline-function-integration-inlining
303
+
304
+ LLVM 14: `createFunctionInliningPass`
305
+ """ # noqa E501
306
+ ffi.lib.LLVMPY_AddFunctionInliningPass(self, threshold)
307
+
308
+ def add_global_dce_pass(self):
309
+ """
310
+ See http://llvm.org/docs/Passes.html#globaldce-dead-global-elimination
311
+
312
+ LLVM 14: `LLVMAddGlobalDCEPass`
313
+ """ # noqa E501
314
+ ffi.lib.LLVMPY_AddGlobalDCEPass(self)
315
+
316
+ def add_global_optimizer_pass(self):
317
+ """
318
+ See http://llvm.org/docs/Passes.html#globalopt-global-variable-optimizer
319
+
320
+ LLVM 14: `LLVMAddGlobalOptimizerPass`
321
+ """ # noqa E501
322
+ ffi.lib.LLVMPY_AddGlobalOptimizerPass(self)
323
+
324
+ def add_ipsccp_pass(self):
325
+ """
326
+ See http://llvm.org/docs/Passes.html#ipsccp-interprocedural-sparse-conditional-constant-propagation
327
+
328
+ LLVM 14: `LLVMAddIPSCCPPass`
329
+ """ # noqa E501
330
+ ffi.lib.LLVMPY_AddIPSCCPPass(self)
331
+
332
+ def add_dead_code_elimination_pass(self):
333
+ """
334
+ See http://llvm.org/docs/Passes.html#dce-dead-code-elimination
335
+ LLVM 14: `llvm::createDeadCodeEliminationPass`
336
+ """
337
+ ffi.lib.LLVMPY_AddDeadCodeEliminationPass(self)
338
+
339
+ def add_aggressive_instruction_combining_pass(self):
340
+ """
341
+ See https://llvm.org/docs/Passes.html#aggressive-instcombine-combine-expression-patterns
342
+
343
+ LLVM 14: `llvm::createAggressiveInstCombinerPass`
344
+ """ # noqa E501
345
+ ffi.lib.LLVMPY_AddAggressiveInstructionCombiningPass(self)
346
+
347
+ def add_internalize_pass(self):
348
+ """
349
+ See https://llvm.org/docs/Passes.html#internalize-internalize-global-symbols
350
+
351
+ LLVM 14: `llvm::createInternalizePass`
352
+ """ # noqa E501
353
+ ffi.lib.LLVMPY_AddInternalizePass(self)
354
+
355
+ def add_cfg_simplification_pass(self):
356
+ """
357
+ See http://llvm.org/docs/Passes.html#simplifycfg-simplify-the-cfg
358
+
359
+ LLVM 14: `LLVMAddCFGSimplificationPass`
360
+ """
361
+ ffi.lib.LLVMPY_AddCFGSimplificationPass(self)
362
+
363
+ def add_jump_threading_pass(self, threshold=-1):
364
+ """
365
+ See https://llvm.org/docs/Passes.html#jump-threading-jump-threading
366
+
367
+ LLVM 14: `llvm::createJumpThreadingPass`
368
+ """ # noqa E501
369
+ ffi.lib.LLVMPY_AddJumpThreadingPass(self, threshold)
370
+
371
+ def add_lcssa_pass(self):
372
+ """
373
+ See https://llvm.org/docs/Passes.html#lcssa-loop-closed-ssa-form-pass
374
+
375
+ LLVM 14: `llvm::createLCSSAPass`
376
+ """ # noqa E501
377
+ ffi.lib.LLVMPY_AddLCSSAPass(self)
378
+
379
+ def add_gvn_pass(self):
380
+ """
381
+ See http://llvm.org/docs/Passes.html#gvn-global-value-numbering
382
+
383
+ LLVM 14: `LLVMAddGVNPass`
384
+ """
385
+ ffi.lib.LLVMPY_AddGVNPass(self)
386
+
387
+ def add_instruction_combining_pass(self):
388
+ """
389
+ See http://llvm.org/docs/Passes.html#passes-instcombine
390
+
391
+ LLVM 14: `LLVMAddInstructionCombiningPass`
392
+ """
393
+ ffi.lib.LLVMPY_AddInstructionCombiningPass(self)
394
+
395
+ def add_licm_pass(self):
396
+ """
397
+ See http://llvm.org/docs/Passes.html#licm-loop-invariant-code-motion
398
+
399
+ LLVM 14: `LLVMAddLICMPass`
400
+ """ # noqa E501
401
+ ffi.lib.LLVMPY_AddLICMPass(self)
402
+
403
+ def add_loop_deletion_pass(self):
404
+ """
405
+ See https://llvm.org/docs/Passes.html#loop-deletion-delete-dead-loops
406
+
407
+ LLVM 14: `llvm::createLoopDeletionPass`
408
+ """ # noqa E501
409
+ ffi.lib.LLVMPY_AddLoopDeletionPass(self)
410
+
411
+ def add_loop_extractor_pass(self):
412
+ """
413
+ See https://llvm.org/docs/Passes.html#loop-extract-extract-loops-into-new-functions
414
+
415
+ LLVM 14: `llvm::createLoopExtractorPass`
416
+ """ # noqa E501
417
+ ffi.lib.LLVMPY_AddLoopExtractorPass(self)
418
+
419
+ def add_single_loop_extractor_pass(self):
420
+ """
421
+ See https://llvm.org/docs/Passes.html#loop-extract-single-extract-at-most-one-loop-into-a-new-function
422
+
423
+ LLVM 14: `llvm::createSingleLoopExtractorPass`
424
+ """ # noqa E501
425
+ ffi.lib.LLVMPY_AddSingleLoopExtractorPass(self)
426
+
427
+ def add_sccp_pass(self):
428
+ """
429
+ See http://llvm.org/docs/Passes.html#sccp-sparse-conditional-constant-propagation
430
+
431
+ LLVM 14: `LLVMAddSCCPPass`
432
+ """ # noqa E501
433
+ ffi.lib.LLVMPY_AddSCCPPass(self)
434
+
435
+ def add_loop_strength_reduce_pass(self):
436
+ """
437
+ See https://llvm.org/docs/Passes.html#loop-reduce-loop-strength-reduction
438
+
439
+ LLVM 14: `llvm::createLoopStrengthReducePass`
440
+ """ # noqa E501
441
+ ffi.lib.LLVMPY_AddLoopStrengthReducePass(self)
442
+
443
+ def add_loop_simplification_pass(self):
444
+ """
445
+ See https://llvm.org/docs/Passes.html#loop-simplify-canonicalize-natural-loops
446
+
447
+ LLVM 14: `llvm::createLoopSimplifyPass`
448
+ """ # noqa E501
449
+ ffi.lib.LLVMPY_AddLoopSimplificationPass(self)
450
+
451
+ def add_loop_unroll_pass(self):
452
+ """
453
+ See https://llvm.org/docs/Passes.html#loop-unroll-unroll-loops
454
+
455
+ LLVM 14: `LLVMAddLoopUnrollPass`
456
+ """ # noqa E501
457
+ ffi.lib.LLVMPY_AddLoopUnrollPass(self)
458
+
459
+ def add_loop_unroll_and_jam_pass(self):
460
+ """
461
+ See https://llvm.org/docs/Passes.html#loop-unroll-and-jam-unroll-and-jam-loops
462
+
463
+ LLVM 14: `LLVMAddLoopUnrollAndJamPass`
464
+ """ # noqa E501
465
+ ffi.lib.LLVMPY_AddLoopUnrollAndJamPass(self)
466
+
467
+ def add_loop_unswitch_pass(self,
468
+ optimize_for_size=False,
469
+ has_branch_divergence=False):
470
+ """
471
+ See https://llvm.org/docs/Passes.html#loop-unswitch-unswitch-loops
472
+
473
+ LLVM 14: `llvm::createLoopUnswitchPass`
474
+ LLVM 15: `llvm::createSimpleLoopUnswitchLegacyPass`
475
+ """ # noqa E501
476
+ ffi.lib.LLVMPY_AddLoopUnswitchPass(self, optimize_for_size,
477
+ has_branch_divergence)
478
+
479
+ def add_lower_atomic_pass(self):
480
+ """
481
+ See https://llvm.org/docs/Passes.html#loweratomic-lower-atomic-intrinsics-to-non-atomic-form
482
+
483
+ LLVM 14: `llvm::createLowerAtomicPass`
484
+ """ # noqa E501
485
+ ffi.lib.LLVMPY_AddLowerAtomicPass(self)
486
+
487
+ def add_lower_invoke_pass(self):
488
+ """
489
+ See https://llvm.org/docs/Passes.html#lowerinvoke-lower-invokes-to-calls-for-unwindless-code-generators
490
+
491
+ LLVM 14: `llvm::createLowerInvokePass`
492
+ """ # noqa E501
493
+ ffi.lib.LLVMPY_AddLowerInvokePass(self)
494
+
495
+ def add_lower_switch_pass(self):
496
+ """
497
+ See https://llvm.org/docs/Passes.html#lowerswitch-lower-switchinsts-to-branches
498
+
499
+ LLVM 14: `llvm::createLowerSwitchPass`
500
+ """ # noqa E501
501
+ ffi.lib.LLVMPY_AddLowerSwitchPass(self)
502
+
503
+ def add_memcpy_optimization_pass(self):
504
+ """
505
+ See https://llvm.org/docs/Passes.html#memcpyopt-memcpy-optimization
506
+
507
+ LLVM 14: `llvm::createMemCpyOptPass`
508
+ """ # noqa E501
509
+ ffi.lib.LLVMPY_AddMemCpyOptimizationPass(self)
510
+
511
+ def add_merge_functions_pass(self):
512
+ """
513
+ See https://llvm.org/docs/Passes.html#mergefunc-merge-functions
514
+
515
+ LLVM 14: `llvm::createMergeFunctionsPass`
516
+ """ # noqa E501
517
+ ffi.lib.LLVMPY_AddMergeFunctionsPass(self)
518
+
519
+ def add_merge_returns_pass(self):
520
+ """
521
+ See https://llvm.org/docs/Passes.html#mergereturn-unify-function-exit-nodes
522
+
523
+ LLVM 14: `llvm::createUnifyFunctionExitNodesPass`
524
+ """ # noqa E501
525
+ ffi.lib.LLVMPY_AddMergeReturnsPass(self)
526
+
527
+ def add_partial_inlining_pass(self):
528
+ """
529
+ See https://llvm.org/docs/Passes.html#partial-inliner-partial-inliner
530
+
531
+ LLVM 14: `llvm::createPartialInliningPass`
532
+ """ # noqa E501
533
+ ffi.lib.LLVMPY_AddPartialInliningPass(self)
534
+
535
+ def add_prune_exception_handling_pass(self):
536
+ """
537
+ See https://llvm.org/docs/Passes.html#prune-eh-remove-unused-exception-handling-info
538
+
539
+ LLVM 14: `llvm::createPruneEHPass`
540
+ """ # noqa E501
541
+ ffi.lib.LLVMPY_AddPruneExceptionHandlingPass(self)
542
+
543
+ def add_reassociate_expressions_pass(self):
544
+ """
545
+ See https://llvm.org/docs/Passes.html#reassociate-reassociate-expressions
546
+
547
+ LLVM 14: `llvm::createReassociatePass`
548
+ """ # noqa E501
549
+ ffi.lib.LLVMPY_AddReassociatePass(self)
550
+
551
+ def add_demote_register_to_memory_pass(self):
552
+ """
553
+ See https://llvm.org/docs/Passes.html#rel-lookup-table-converter-relative-lookup-table-converter
554
+
555
+ LLVM 14: `llvm::createDemoteRegisterToMemoryPass`
556
+ """ # noqa E501
557
+ ffi.lib.LLVMPY_AddDemoteRegisterToMemoryPass(self)
558
+
559
+ def add_sroa_pass(self):
560
+ """
561
+ See http://llvm.org/docs/Passes.html#scalarrepl-scalar-replacement-of-aggregates-dt
562
+ Note that this pass corresponds to the ``opt -sroa`` command-line option,
563
+ despite the link above.
564
+
565
+ LLVM 14: `llvm::createSROAPass`
566
+ """ # noqa E501
567
+ ffi.lib.LLVMPY_AddSROAPass(self)
568
+
569
+ def add_sink_pass(self):
570
+ """
571
+ See https://llvm.org/docs/Passes.html#sink-code-sinking
572
+
573
+ LLVM 14: `llvm::createSinkingPass`
574
+ """ # noqa E501
575
+ ffi.lib.LLVMPY_AddSinkPass(self)
576
+
577
+ def add_strip_symbols_pass(self, only_debug=False):
578
+ """
579
+ See https://llvm.org/docs/Passes.html#strip-strip-all-symbols-from-a-module
580
+
581
+ LLVM 14: `llvm::createStripSymbolsPass`
582
+ """ # noqa E501
583
+ ffi.lib.LLVMPY_AddStripSymbolsPass(self, only_debug)
584
+
585
+ def add_strip_dead_debug_info_pass(self):
586
+ """
587
+ See https://llvm.org/docs/Passes.html#strip-dead-debug-info-strip-debug-info-for-unused-symbols
588
+
589
+ LLVM 14: `llvm::createStripDeadDebugInfoPass`
590
+ """ # noqa E501
591
+ ffi.lib.LLVMPY_AddStripDeadDebugInfoPass(self)
592
+
593
+ def add_strip_dead_prototypes_pass(self):
594
+ """
595
+ See https://llvm.org/docs/Passes.html#strip-dead-prototypes-strip-unused-function-prototypes
596
+
597
+ LLVM 14: `llvm::createStripDeadPrototypesPass`
598
+ """ # noqa E501
599
+ ffi.lib.LLVMPY_AddStripDeadPrototypesPass(self)
600
+
601
+ def add_strip_debug_declare_pass(self):
602
+ """
603
+ See https://llvm.org/docs/Passes.html#strip-debug-declare-strip-all-llvm-dbg-declare-intrinsics
604
+
605
+ LLVM 14: `llvm::createStripDebugDeclarePass`
606
+ """ # noqa E501
607
+ ffi.lib.LLVMPY_AddStripDebugDeclarePrototypesPass(self)
608
+
609
+ def add_strip_nondebug_symbols_pass(self):
610
+ """
611
+ See https://llvm.org/docs/Passes.html#strip-nondebug-strip-all-symbols-except-dbg-symbols-from-a-module
612
+
613
+ LLVM 14: `llvm::createStripNonDebugSymbolsPass`
614
+ """ # noqa E501
615
+ ffi.lib.LLVMPY_AddStripNondebugSymbolsPass(self)
616
+
617
+ def add_tail_call_elimination_pass(self):
618
+ """
619
+ See https://llvm.org/docs/Passes.html#tailcallelim-tail-call-elimination
620
+
621
+ LLVM 14: `llvm::createTailCallEliminationPass`
622
+ """ # noqa E501
623
+ ffi.lib.LLVMPY_AddTailCallEliminationPass(self)
624
+
625
+ def add_type_based_alias_analysis_pass(self):
626
+ """
627
+ LLVM 14: `LLVMAddTypeBasedAliasAnalysisPass`
628
+ """ # noqa E501
629
+ ffi.lib.LLVMPY_AddTypeBasedAliasAnalysisPass(self)
630
+
631
+ def add_basic_alias_analysis_pass(self):
632
+ """
633
+ See http://llvm.org/docs/AliasAnalysis.html#the-basicaa-pass
634
+
635
+ LLVM 14: `LLVMAddBasicAliasAnalysisPass`
636
+ """
637
+ ffi.lib.LLVMPY_AddBasicAliasAnalysisPass(self)
638
+
639
+ def add_loop_rotate_pass(self):
640
+ """http://llvm.org/docs/Passes.html#loop-rotate-rotate-loops."""
641
+ ffi.lib.LLVMPY_LLVMAddLoopRotatePass(self)
642
+
643
+ def add_target_library_info(self, triple):
644
+ ffi.lib.LLVMPY_AddTargetLibraryInfoPass(self, _encode_string(triple))
645
+
646
+ def add_instruction_namer_pass(self):
647
+ """
648
+ See https://llvm.org/docs/Passes.html#instnamer-assign-names-to-anonymous-instructions.
649
+
650
+ LLVM 14: `llvm::createInstructionNamerPass`
651
+ """ # noqa E501
652
+ ffi.lib.LLVMPY_AddInstructionNamerPass(self)
653
+
654
+ # Non-standard LLVM passes
655
+
656
+ def add_refprune_pass(self, subpasses_flags=RefPruneSubpasses.ALL,
657
+ subgraph_limit=1000):
658
+ """Add Numba specific Reference count pruning pass.
659
+
660
+ Parameters
661
+ ----------
662
+ subpasses_flags : RefPruneSubpasses
663
+ A bitmask to control the subpasses to be enabled.
664
+ subgraph_limit : int
665
+ Limit the fanout pruners to working on a subgraph no bigger than
666
+ this number of basic-blocks to avoid spending too much time in very
667
+ large graphs. Default is 1000. Subject to change in future
668
+ versions.
669
+ """
670
+ iflags = RefPruneSubpasses(subpasses_flags)
671
+ ffi.lib.LLVMPY_AddRefPrunePass(self, iflags, subgraph_limit)
672
+
673
+
674
+ class ModulePassManager(PassManager):
675
+
676
+ def __init__(self, ptr=None):
677
+ if ptr is None:
678
+ ptr = ffi.lib.LLVMPY_CreatePassManager()
679
+ PassManager.__init__(self, ptr)
680
+
681
+ def run(self, module, remarks_file=None, remarks_format='yaml',
682
+ remarks_filter=''):
683
+ """
684
+ Run optimization passes on the given module.
685
+
686
+ Parameters
687
+ ----------
688
+ module : llvmlite.binding.ModuleRef
689
+ The module to be optimized inplace
690
+ remarks_file : str; optional
691
+ If not `None`, it is the file to store the optimization remarks.
692
+ remarks_format : str; optional
693
+ The format to write; YAML is default
694
+ remarks_filter : str; optional
695
+ The filter that should be applied to the remarks output.
696
+ """
697
+ if remarks_file is None:
698
+ return ffi.lib.LLVMPY_RunPassManager(self, module)
699
+ else:
700
+ r = ffi.lib.LLVMPY_RunPassManagerWithRemarks(
701
+ self, module, _encode_string(remarks_format),
702
+ _encode_string(remarks_filter),
703
+ _encode_string(remarks_file))
704
+ if r == -1:
705
+ raise IOError("Failed to initialize remarks file.")
706
+ return r > 0
707
+
708
+ def run_with_remarks(self, module, remarks_format='yaml',
709
+ remarks_filter=''):
710
+ """
711
+ Run optimization passes on the given module and returns the result and
712
+ the remarks data.
713
+
714
+ Parameters
715
+ ----------
716
+ module : llvmlite.binding.ModuleRef
717
+ The module to be optimized
718
+ remarks_format : str
719
+ The remarks output; YAML is the default
720
+ remarks_filter : str; optional
721
+ The filter that should be applied to the remarks output.
722
+ """
723
+ remarkdesc, remarkfile = mkstemp()
724
+ try:
725
+ with os.fdopen(remarkdesc, 'r'):
726
+ pass
727
+ r = self.run(module, remarkfile, remarks_format, remarks_filter)
728
+ if r == -1:
729
+ raise IOError("Failed to initialize remarks file.")
730
+ with open(remarkfile) as f:
731
+ return bool(r), f.read()
732
+ finally:
733
+ os.unlink(remarkfile)
734
+
735
+
736
+ class FunctionPassManager(PassManager):
737
+
738
+ def __init__(self, module):
739
+ ptr = ffi.lib.LLVMPY_CreateFunctionPassManager(module)
740
+ self._module = module
741
+ module._owned = True
742
+ PassManager.__init__(self, ptr)
743
+
744
+ def initialize(self):
745
+ """
746
+ Initialize the FunctionPassManager. Returns True if it produced
747
+ any changes (?).
748
+ """
749
+ return ffi.lib.LLVMPY_InitializeFunctionPassManager(self)
750
+
751
+ def finalize(self):
752
+ """
753
+ Finalize the FunctionPassManager. Returns True if it produced
754
+ any changes (?).
755
+ """
756
+ return ffi.lib.LLVMPY_FinalizeFunctionPassManager(self)
757
+
758
+ def run(self, function, remarks_file=None, remarks_format='yaml',
759
+ remarks_filter=''):
760
+ """
761
+ Run optimization passes on the given function.
762
+
763
+ Parameters
764
+ ----------
765
+ function : llvmlite.binding.FunctionRef
766
+ The function to be optimized inplace
767
+ remarks_file : str; optional
768
+ If not `None`, it is the file to store the optimization remarks.
769
+ remarks_format : str; optional
770
+ The format of the remarks file; the default is YAML
771
+ remarks_filter : str; optional
772
+ The filter that should be applied to the remarks output.
773
+ """
774
+ if remarks_file is None:
775
+ return ffi.lib.LLVMPY_RunFunctionPassManager(self, function)
776
+ else:
777
+ r = ffi.lib.LLVMPY_RunFunctionPassManagerWithRemarks(
778
+ self, function, _encode_string(remarks_format),
779
+ _encode_string(remarks_filter),
780
+ _encode_string(remarks_file))
781
+ if r == -1:
782
+ raise IOError("Failed to initialize remarks file.")
783
+ return bool(r)
784
+
785
+ def run_with_remarks(self, function, remarks_format='yaml',
786
+ remarks_filter=''):
787
+ """
788
+ Run optimization passes on the given function and returns the result
789
+ and the remarks data.
790
+
791
+ Parameters
792
+ ----------
793
+ function : llvmlite.binding.FunctionRef
794
+ The function to be optimized inplace
795
+ remarks_format : str; optional
796
+ The format of the remarks file; the default is YAML
797
+ remarks_filter : str; optional
798
+ The filter that should be applied to the remarks output.
799
+ """
800
+ # LLVM is going to need to close this file and then reopen it, so we
801
+ # can't use an unlinked temporary file.
802
+ remarkdesc, remarkfile = mkstemp()
803
+ try:
804
+ # We get an open handle, but we need LLVM to write first, so close
805
+ # it.
806
+ with os.fdopen(remarkdesc, 'r'):
807
+ pass
808
+ r = self.run(function, remarkfile, remarks_format, remarks_filter)
809
+ if r == -1:
810
+ raise IOError("Failed to initialize remarks file.")
811
+ with open(remarkfile) as f:
812
+ return bool(r), f.read()
813
+ finally:
814
+ os.unlink(remarkfile)
815
+
816
+
817
+ # ============================================================================
818
+ # FFI
819
+
820
+ ffi.lib.LLVMPY_CreatePassManager.restype = ffi.LLVMPassManagerRef
821
+
822
+ ffi.lib.LLVMPY_CreateFunctionPassManager.argtypes = [ffi.LLVMModuleRef]
823
+ ffi.lib.LLVMPY_CreateFunctionPassManager.restype = ffi.LLVMPassManagerRef
824
+
825
+ ffi.lib.LLVMPY_DisposePassManager.argtypes = [ffi.LLVMPassManagerRef]
826
+
827
+ ffi.lib.LLVMPY_RunPassManager.argtypes = [ffi.LLVMPassManagerRef,
828
+ ffi.LLVMModuleRef]
829
+ ffi.lib.LLVMPY_RunPassManager.restype = c_bool
830
+
831
+ ffi.lib.LLVMPY_RunPassManagerWithRemarks.argtypes = [ffi.LLVMPassManagerRef,
832
+ ffi.LLVMModuleRef,
833
+ c_char_p,
834
+ c_char_p,
835
+ c_char_p]
836
+ ffi.lib.LLVMPY_RunPassManagerWithRemarks.restype = c_int
837
+
838
+ ffi.lib.LLVMPY_InitializeFunctionPassManager.argtypes = [ffi.LLVMPassManagerRef]
839
+ ffi.lib.LLVMPY_InitializeFunctionPassManager.restype = c_bool
840
+
841
+ ffi.lib.LLVMPY_FinalizeFunctionPassManager.argtypes = [ffi.LLVMPassManagerRef]
842
+ ffi.lib.LLVMPY_FinalizeFunctionPassManager.restype = c_bool
843
+
844
+ ffi.lib.LLVMPY_RunFunctionPassManager.argtypes = [ffi.LLVMPassManagerRef,
845
+ ffi.LLVMValueRef]
846
+ ffi.lib.LLVMPY_RunFunctionPassManager.restype = c_bool
847
+
848
+ ffi.lib.LLVMPY_RunFunctionPassManagerWithRemarks.argtypes = [
849
+ ffi.LLVMPassManagerRef, ffi.LLVMValueRef, c_char_p, c_char_p, c_char_p
850
+ ]
851
+ ffi.lib.LLVMPY_RunFunctionPassManagerWithRemarks.restype = c_int
852
+
853
+ ffi.lib.LLVMPY_AddAAEvalPass.argtypes = [ffi.LLVMPassManagerRef]
854
+ ffi.lib.LLVMPY_AddBasicAAWrapperPass.argtypes = [ffi.LLVMPassManagerRef]
855
+ ffi.lib.LLVMPY_AddConstantMergePass.argtypes = [ffi.LLVMPassManagerRef]
856
+ ffi.lib.LLVMPY_AddDeadArgEliminationPass.argtypes = [ffi.LLVMPassManagerRef]
857
+ ffi.lib.LLVMPY_AddDependenceAnalysisPass.argtypes = [ffi.LLVMPassManagerRef]
858
+ ffi.lib.LLVMPY_AddCallGraphDOTPrinterPass.argtypes = [ffi.LLVMPassManagerRef]
859
+ ffi.lib.LLVMPY_AddCFGPrinterPass.argtypes = [ffi.LLVMPassManagerRef]
860
+ ffi.lib.LLVMPY_AddDotDomPrinterPass.argtypes = [ffi.LLVMPassManagerRef, c_bool]
861
+ ffi.lib.LLVMPY_AddDotPostDomPrinterPass.argtypes = [
862
+ ffi.LLVMPassManagerRef,
863
+ c_bool]
864
+ ffi.lib.LLVMPY_AddGlobalsModRefAAPass.argtypes = [ffi.LLVMPassManagerRef]
865
+ ffi.lib.LLVMPY_AddInstructionCountPass.argtypes = [ffi.LLVMPassManagerRef]
866
+ ffi.lib.LLVMPY_AddIVUsersPass.argtypes = [ffi.LLVMPassManagerRef]
867
+ ffi.lib.LLVMPY_AddLazyValueInfoPass.argtypes = [ffi.LLVMPassManagerRef]
868
+ ffi.lib.LLVMPY_AddLintPass.argtypes = [ffi.LLVMPassManagerRef]
869
+ ffi.lib.LLVMPY_AddModuleDebugInfoPrinterPass.argtypes = [ffi.LLVMPassManagerRef]
870
+ ffi.lib.LLVMPY_AddRegionInfoPass.argtypes = [ffi.LLVMPassManagerRef]
871
+ ffi.lib.LLVMPY_AddScalarEvolutionAAPass.argtypes = [ffi.LLVMPassManagerRef]
872
+ ffi.lib.LLVMPY_AddAggressiveDCEPass.argtypes = [ffi.LLVMPassManagerRef]
873
+ ffi.lib.LLVMPY_AddAlwaysInlinerPass.argtypes = [ffi.LLVMPassManagerRef, c_bool]
874
+
875
+ if llvm_version_major < 15:
876
+ ffi.lib.LLVMPY_AddArgPromotionPass.argtypes = [
877
+ ffi.LLVMPassManagerRef, c_uint]
878
+
879
+ ffi.lib.LLVMPY_AddBreakCriticalEdgesPass.argtypes = [ffi.LLVMPassManagerRef]
880
+ ffi.lib.LLVMPY_AddDeadStoreEliminationPass.argtypes = [
881
+ ffi.LLVMPassManagerRef]
882
+ ffi.lib.LLVMPY_AddReversePostOrderFunctionAttrsPass.argtypes = [
883
+ ffi.LLVMPassManagerRef]
884
+ ffi.lib.LLVMPY_AddAggressiveInstructionCombiningPass.argtypes = [
885
+ ffi.LLVMPassManagerRef]
886
+ ffi.lib.LLVMPY_AddInternalizePass.argtypes = [ffi.LLVMPassManagerRef]
887
+ ffi.lib.LLVMPY_AddLCSSAPass.argtypes = [ffi.LLVMPassManagerRef]
888
+ ffi.lib.LLVMPY_AddLoopDeletionPass.argtypes = [ffi.LLVMPassManagerRef]
889
+ ffi.lib.LLVMPY_AddLoopExtractorPass.argtypes = [ffi.LLVMPassManagerRef]
890
+ ffi.lib.LLVMPY_AddSingleLoopExtractorPass.argtypes = [ffi.LLVMPassManagerRef]
891
+ ffi.lib.LLVMPY_AddLoopStrengthReducePass.argtypes = [ffi.LLVMPassManagerRef]
892
+ ffi.lib.LLVMPY_AddLoopSimplificationPass.argtypes = [ffi.LLVMPassManagerRef]
893
+ ffi.lib.LLVMPY_AddLoopUnrollPass.argtypes = [ffi.LLVMPassManagerRef]
894
+ ffi.lib.LLVMPY_AddLoopUnrollAndJamPass.argtypes = [ffi.LLVMPassManagerRef]
895
+ ffi.lib.LLVMPY_AddLoopUnswitchPass.argtypes = [ffi.LLVMPassManagerRef, c_bool,
896
+ c_bool]
897
+ ffi.lib.LLVMPY_AddLowerAtomicPass.argtypes = [ffi.LLVMPassManagerRef]
898
+ ffi.lib.LLVMPY_AddLowerInvokePass.argtypes = [ffi.LLVMPassManagerRef]
899
+ ffi.lib.LLVMPY_AddLowerSwitchPass.argtypes = [ffi.LLVMPassManagerRef]
900
+ ffi.lib.LLVMPY_AddMemCpyOptimizationPass.argtypes = [ffi.LLVMPassManagerRef]
901
+ ffi.lib.LLVMPY_AddMergeFunctionsPass.argtypes = [ffi.LLVMPassManagerRef]
902
+ ffi.lib.LLVMPY_AddMergeReturnsPass.argtypes = [ffi.LLVMPassManagerRef]
903
+ ffi.lib.LLVMPY_AddPartialInliningPass.argtypes = [ffi.LLVMPassManagerRef]
904
+ ffi.lib.LLVMPY_AddPruneExceptionHandlingPass.argtypes = [ffi.LLVMPassManagerRef]
905
+ ffi.lib.LLVMPY_AddReassociatePass.argtypes = [ffi.LLVMPassManagerRef]
906
+ ffi.lib.LLVMPY_AddDemoteRegisterToMemoryPass.argtypes = [ffi.LLVMPassManagerRef]
907
+ ffi.lib.LLVMPY_AddSinkPass.argtypes = [ffi.LLVMPassManagerRef]
908
+ ffi.lib.LLVMPY_AddStripSymbolsPass.argtypes = [ffi.LLVMPassManagerRef, c_bool]
909
+ ffi.lib.LLVMPY_AddStripDeadDebugInfoPass.argtypes = [ffi.LLVMPassManagerRef]
910
+ ffi.lib.LLVMPY_AddStripDeadPrototypesPass.argtypes = [ffi.LLVMPassManagerRef]
911
+ ffi.lib.LLVMPY_AddStripDebugDeclarePrototypesPass.argtypes = [
912
+ ffi.LLVMPassManagerRef]
913
+ ffi.lib.LLVMPY_AddStripNondebugSymbolsPass.argtypes = [ffi.LLVMPassManagerRef]
914
+ ffi.lib.LLVMPY_AddTailCallEliminationPass.argtypes = [ffi.LLVMPassManagerRef]
915
+ ffi.lib.LLVMPY_AddJumpThreadingPass.argtypes = [ffi.LLVMPassManagerRef, c_int]
916
+ ffi.lib.LLVMPY_AddFunctionAttrsPass.argtypes = [ffi.LLVMPassManagerRef]
917
+ ffi.lib.LLVMPY_AddFunctionInliningPass.argtypes = [
918
+ ffi.LLVMPassManagerRef, c_int]
919
+ ffi.lib.LLVMPY_AddGlobalDCEPass.argtypes = [ffi.LLVMPassManagerRef]
920
+ ffi.lib.LLVMPY_AddGlobalOptimizerPass.argtypes = [ffi.LLVMPassManagerRef]
921
+ ffi.lib.LLVMPY_AddIPSCCPPass.argtypes = [ffi.LLVMPassManagerRef]
922
+
923
+ ffi.lib.LLVMPY_AddDeadCodeEliminationPass.argtypes = [ffi.LLVMPassManagerRef]
924
+ ffi.lib.LLVMPY_AddCFGSimplificationPass.argtypes = [ffi.LLVMPassManagerRef]
925
+ ffi.lib.LLVMPY_AddGVNPass.argtypes = [ffi.LLVMPassManagerRef]
926
+ ffi.lib.LLVMPY_AddInstructionCombiningPass.argtypes = [ffi.LLVMPassManagerRef]
927
+ ffi.lib.LLVMPY_AddLICMPass.argtypes = [ffi.LLVMPassManagerRef]
928
+ ffi.lib.LLVMPY_AddSCCPPass.argtypes = [ffi.LLVMPassManagerRef]
929
+ ffi.lib.LLVMPY_AddSROAPass.argtypes = [ffi.LLVMPassManagerRef]
930
+ ffi.lib.LLVMPY_AddTypeBasedAliasAnalysisPass.argtypes = [ffi.LLVMPassManagerRef]
931
+ ffi.lib.LLVMPY_AddBasicAliasAnalysisPass.argtypes = [ffi.LLVMPassManagerRef]
932
+ ffi.lib.LLVMPY_AddTargetLibraryInfoPass.argtypes = [ffi.LLVMPassManagerRef,
933
+ c_char_p]
934
+ ffi.lib.LLVMPY_AddInstructionNamerPass.argtypes = [ffi.LLVMPassManagerRef]
935
+
936
+ ffi.lib.LLVMPY_AddRefPrunePass.argtypes = [ffi.LLVMPassManagerRef, c_int,
937
+ c_size_t]
938
+
939
+ ffi.lib.LLVMPY_DumpRefPruneStats.argtypes = [POINTER(_c_PruneStats), c_bool]
vllm/lib/python3.10/site-packages/llvmlite/binding/targets.py ADDED
@@ -0,0 +1,450 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from ctypes import (POINTER, c_char_p, c_longlong, c_int, c_size_t,
3
+ c_void_p, string_at)
4
+
5
+ from llvmlite.binding import ffi
6
+ from llvmlite.binding.common import _decode_string, _encode_string
7
+
8
+
9
+ def get_process_triple():
10
+ """
11
+ Return a target triple suitable for generating code for the current process.
12
+ An example when the default triple from ``get_default_triple()`` is not be
13
+ suitable is when LLVM is compiled for 32-bit but the process is executing
14
+ in 64-bit mode.
15
+ """
16
+ with ffi.OutputString() as out:
17
+ ffi.lib.LLVMPY_GetProcessTriple(out)
18
+ return str(out)
19
+
20
+
21
+ class FeatureMap(dict):
22
+ """
23
+ Maps feature name to a boolean indicating the availability of the feature.
24
+ Extends ``dict`` to add `.flatten()` method.
25
+ """
26
+
27
+ def flatten(self, sort=True):
28
+ """
29
+ Args
30
+ ----
31
+ sort: bool
32
+ Optional. If True, the features are sorted by name; otherwise,
33
+ the ordering is unstable between python session due to hash
34
+ randomization. Defaults to True.
35
+
36
+ Returns a string suitable for use as the ``features`` argument to
37
+ ``Target.create_target_machine()``.
38
+
39
+ """
40
+ iterator = sorted(self.items()) if sort else iter(self.items())
41
+ flag_map = {True: '+', False: '-'}
42
+ return ','.join('{0}{1}'.format(flag_map[v], k)
43
+ for k, v in iterator)
44
+
45
+
46
+ def get_host_cpu_features():
47
+ """
48
+ Returns a dictionary-like object indicating the CPU features for current
49
+ architecture and whether they are enabled for this CPU. The key-value pairs
50
+ are the feature name as string and a boolean indicating whether the feature
51
+ is available. The returned value is an instance of ``FeatureMap`` class,
52
+ which adds a new method ``.flatten()`` for returning a string suitable for
53
+ use as the "features" argument to ``Target.create_target_machine()``.
54
+
55
+ If LLVM has not implemented this feature or it fails to get the information,
56
+ this function will raise a RuntimeError exception.
57
+ """
58
+ with ffi.OutputString() as out:
59
+ outdict = FeatureMap()
60
+ if not ffi.lib.LLVMPY_GetHostCPUFeatures(out):
61
+ return outdict
62
+ flag_map = {'+': True, '-': False}
63
+ content = str(out)
64
+ if content: # protect against empty string
65
+ for feat in content.split(','):
66
+ if feat: # protect against empty feature
67
+ outdict[feat[1:]] = flag_map[feat[0]]
68
+ return outdict
69
+
70
+
71
+ def get_default_triple():
72
+ """
73
+ Return the default target triple LLVM is configured to produce code for.
74
+ """
75
+ with ffi.OutputString() as out:
76
+ ffi.lib.LLVMPY_GetDefaultTargetTriple(out)
77
+ return str(out)
78
+
79
+
80
+ def get_host_cpu_name():
81
+ """
82
+ Get the name of the host's CPU, suitable for using with
83
+ :meth:`Target.create_target_machine()`.
84
+ """
85
+ with ffi.OutputString() as out:
86
+ ffi.lib.LLVMPY_GetHostCPUName(out)
87
+ return str(out)
88
+
89
+
90
+ _object_formats = {
91
+ 1: "COFF",
92
+ 2: "ELF",
93
+ 3: "MachO",
94
+ }
95
+
96
+
97
+ def get_object_format(triple=None):
98
+ """
99
+ Get the object format for the given *triple* string (or the default
100
+ triple if omitted).
101
+ A string is returned
102
+ """
103
+ if triple is None:
104
+ triple = get_default_triple()
105
+ res = ffi.lib.LLVMPY_GetTripleObjectFormat(_encode_string(triple))
106
+ return _object_formats[res]
107
+
108
+
109
+ def create_target_data(layout):
110
+ """
111
+ Create a TargetData instance for the given *layout* string.
112
+ """
113
+ return TargetData(ffi.lib.LLVMPY_CreateTargetData(_encode_string(layout)))
114
+
115
+
116
+ class TargetData(ffi.ObjectRef):
117
+ """
118
+ A TargetData provides structured access to a data layout.
119
+ Use :func:`create_target_data` to create instances.
120
+ """
121
+
122
+ def __str__(self):
123
+ if self._closed:
124
+ return "<dead TargetData>"
125
+ with ffi.OutputString() as out:
126
+ ffi.lib.LLVMPY_CopyStringRepOfTargetData(self, out)
127
+ return str(out)
128
+
129
+ def _dispose(self):
130
+ self._capi.LLVMPY_DisposeTargetData(self)
131
+
132
+ def get_abi_size(self, ty):
133
+ """
134
+ Get ABI size of LLVM type *ty*.
135
+ """
136
+ return ffi.lib.LLVMPY_ABISizeOfType(self, ty)
137
+
138
+ def get_element_offset(self, ty, position):
139
+ """
140
+ Get byte offset of type's ty element at the given position
141
+ """
142
+
143
+ offset = ffi.lib.LLVMPY_OffsetOfElement(self, ty, position)
144
+ if offset == -1:
145
+ raise ValueError("Could not determined offset of {}th "
146
+ "element of the type '{}'. Is it a struct"
147
+ "type?".format(position, str(ty)))
148
+ return offset
149
+
150
+ def get_pointee_abi_size(self, ty):
151
+ """
152
+ Get ABI size of pointee type of LLVM pointer type *ty*.
153
+ """
154
+ size = ffi.lib.LLVMPY_ABISizeOfElementType(self, ty)
155
+ if size == -1:
156
+ raise RuntimeError("Not a pointer type: %s" % (ty,))
157
+ return size
158
+
159
+ def get_pointee_abi_alignment(self, ty):
160
+ """
161
+ Get minimum ABI alignment of pointee type of LLVM pointer type *ty*.
162
+ """
163
+ size = ffi.lib.LLVMPY_ABIAlignmentOfElementType(self, ty)
164
+ if size == -1:
165
+ raise RuntimeError("Not a pointer type: %s" % (ty,))
166
+ return size
167
+
168
+
169
+ RELOC = frozenset(['default', 'static', 'pic', 'dynamicnopic'])
170
+ CODEMODEL = frozenset(['default', 'jitdefault', 'small', 'kernel', 'medium',
171
+ 'large'])
172
+
173
+
174
+ class Target(ffi.ObjectRef):
175
+ _triple = ''
176
+
177
+ # No _dispose() method since LLVMGetTargetFromTriple() returns a
178
+ # persistent object.
179
+
180
+ @classmethod
181
+ def from_default_triple(cls):
182
+ """
183
+ Create a Target instance for the default triple.
184
+ """
185
+ triple = get_default_triple()
186
+ return cls.from_triple(triple)
187
+
188
+ @classmethod
189
+ def from_triple(cls, triple):
190
+ """
191
+ Create a Target instance for the given triple (a string).
192
+ """
193
+ with ffi.OutputString() as outerr:
194
+ target = ffi.lib.LLVMPY_GetTargetFromTriple(triple.encode('utf8'),
195
+ outerr)
196
+ if not target:
197
+ raise RuntimeError(str(outerr))
198
+ target = cls(target)
199
+ target._triple = triple
200
+ return target
201
+
202
+ @property
203
+ def name(self):
204
+ s = ffi.lib.LLVMPY_GetTargetName(self)
205
+ return _decode_string(s)
206
+
207
+ @property
208
+ def description(self):
209
+ s = ffi.lib.LLVMPY_GetTargetDescription(self)
210
+ return _decode_string(s)
211
+
212
+ @property
213
+ def triple(self):
214
+ return self._triple
215
+
216
+ def __str__(self):
217
+ return "<Target {0} ({1})>".format(self.name, self.description)
218
+
219
+ def create_target_machine(self, cpu='', features='',
220
+ opt=2, reloc='default', codemodel='jitdefault',
221
+ printmc=False, jit=False, abiname=''):
222
+ """
223
+ Create a new TargetMachine for this target and the given options.
224
+
225
+ Specifying codemodel='default' will result in the use of the "small"
226
+ code model. Specifying codemodel='jitdefault' will result in the code
227
+ model being picked based on platform bitness (32="small", 64="large").
228
+
229
+ The `printmc` option corresponds to llvm's `-print-machineinstrs`.
230
+
231
+ The `jit` option should be set when the target-machine is to be used
232
+ in a JIT engine.
233
+
234
+ The `abiname` option specifies the ABI. RISC-V targets with hard-float
235
+ needs to pass the ABI name to LLVM.
236
+ """
237
+ assert 0 <= opt <= 3
238
+ assert reloc in RELOC
239
+ assert codemodel in CODEMODEL
240
+ triple = self._triple
241
+ # MCJIT under Windows only supports ELF objects, see
242
+ # http://lists.llvm.org/pipermail/llvm-dev/2013-December/068341.html
243
+ # Note we still want to produce regular COFF files in AOT mode.
244
+ if os.name == 'nt' and codemodel == 'jitdefault':
245
+ triple += '-elf'
246
+ tm = ffi.lib.LLVMPY_CreateTargetMachine(self,
247
+ _encode_string(triple),
248
+ _encode_string(cpu),
249
+ _encode_string(features),
250
+ opt,
251
+ _encode_string(reloc),
252
+ _encode_string(codemodel),
253
+ int(printmc),
254
+ int(jit),
255
+ _encode_string(abiname),
256
+ )
257
+ if tm:
258
+ return TargetMachine(tm)
259
+ else:
260
+ raise RuntimeError("Cannot create target machine")
261
+
262
+
263
+ class TargetMachine(ffi.ObjectRef):
264
+
265
+ def _dispose(self):
266
+ self._capi.LLVMPY_DisposeTargetMachine(self)
267
+
268
+ def add_analysis_passes(self, pm):
269
+ """
270
+ Register analysis passes for this target machine with a pass manager.
271
+ """
272
+ ffi.lib.LLVMPY_AddAnalysisPasses(self, pm)
273
+
274
+ def set_asm_verbosity(self, verbose):
275
+ """
276
+ Set whether this target machine will emit assembly with human-readable
277
+ comments describing control flow, debug information, and so on.
278
+ """
279
+ ffi.lib.LLVMPY_SetTargetMachineAsmVerbosity(self, verbose)
280
+
281
+ def emit_object(self, module):
282
+ """
283
+ Represent the module as a code object, suitable for use with
284
+ the platform's linker. Returns a byte string.
285
+ """
286
+ return self._emit_to_memory(module, use_object=True)
287
+
288
+ def emit_assembly(self, module):
289
+ """
290
+ Return the raw assembler of the module, as a string.
291
+
292
+ llvm.initialize_native_asmprinter() must have been called first.
293
+ """
294
+ return _decode_string(self._emit_to_memory(module, use_object=False))
295
+
296
+ def _emit_to_memory(self, module, use_object=False):
297
+ """Returns bytes of object code of the module.
298
+
299
+ Args
300
+ ----
301
+ use_object : bool
302
+ Emit object code or (if False) emit assembly code.
303
+ """
304
+ with ffi.OutputString() as outerr:
305
+ mb = ffi.lib.LLVMPY_TargetMachineEmitToMemory(self, module,
306
+ int(use_object),
307
+ outerr)
308
+ if not mb:
309
+ raise RuntimeError(str(outerr))
310
+
311
+ bufptr = ffi.lib.LLVMPY_GetBufferStart(mb)
312
+ bufsz = ffi.lib.LLVMPY_GetBufferSize(mb)
313
+ try:
314
+ return string_at(bufptr, bufsz)
315
+ finally:
316
+ ffi.lib.LLVMPY_DisposeMemoryBuffer(mb)
317
+
318
+ @property
319
+ def target_data(self):
320
+ return TargetData(ffi.lib.LLVMPY_CreateTargetMachineData(self))
321
+
322
+ @property
323
+ def triple(self):
324
+ with ffi.OutputString() as out:
325
+ ffi.lib.LLVMPY_GetTargetMachineTriple(self, out)
326
+ return str(out)
327
+
328
+
329
+ def has_svml():
330
+ """
331
+ Returns True if SVML was enabled at FFI support compile time.
332
+ """
333
+ if ffi.lib.LLVMPY_HasSVMLSupport() == 0:
334
+ return False
335
+ else:
336
+ return True
337
+
338
+
339
+ # ============================================================================
340
+ # FFI
341
+
342
+ ffi.lib.LLVMPY_GetProcessTriple.argtypes = [POINTER(c_char_p)]
343
+
344
+ ffi.lib.LLVMPY_GetHostCPUFeatures.argtypes = [POINTER(c_char_p)]
345
+ ffi.lib.LLVMPY_GetHostCPUFeatures.restype = c_int
346
+
347
+ ffi.lib.LLVMPY_GetDefaultTargetTriple.argtypes = [POINTER(c_char_p)]
348
+
349
+ ffi.lib.LLVMPY_GetHostCPUName.argtypes = [POINTER(c_char_p)]
350
+
351
+ ffi.lib.LLVMPY_GetTripleObjectFormat.argtypes = [c_char_p]
352
+ ffi.lib.LLVMPY_GetTripleObjectFormat.restype = c_int
353
+
354
+ ffi.lib.LLVMPY_CreateTargetData.argtypes = [c_char_p]
355
+ ffi.lib.LLVMPY_CreateTargetData.restype = ffi.LLVMTargetDataRef
356
+
357
+ ffi.lib.LLVMPY_CopyStringRepOfTargetData.argtypes = [
358
+ ffi.LLVMTargetDataRef,
359
+ POINTER(c_char_p),
360
+ ]
361
+
362
+ ffi.lib.LLVMPY_DisposeTargetData.argtypes = [
363
+ ffi.LLVMTargetDataRef,
364
+ ]
365
+
366
+ ffi.lib.LLVMPY_ABISizeOfType.argtypes = [ffi.LLVMTargetDataRef,
367
+ ffi.LLVMTypeRef]
368
+ ffi.lib.LLVMPY_ABISizeOfType.restype = c_longlong
369
+
370
+ ffi.lib.LLVMPY_OffsetOfElement.argtypes = [ffi.LLVMTargetDataRef,
371
+ ffi.LLVMTypeRef,
372
+ c_int]
373
+ ffi.lib.LLVMPY_OffsetOfElement.restype = c_longlong
374
+
375
+ ffi.lib.LLVMPY_ABISizeOfElementType.argtypes = [ffi.LLVMTargetDataRef,
376
+ ffi.LLVMTypeRef]
377
+ ffi.lib.LLVMPY_ABISizeOfElementType.restype = c_longlong
378
+
379
+ ffi.lib.LLVMPY_ABIAlignmentOfElementType.argtypes = [ffi.LLVMTargetDataRef,
380
+ ffi.LLVMTypeRef]
381
+ ffi.lib.LLVMPY_ABIAlignmentOfElementType.restype = c_longlong
382
+
383
+ ffi.lib.LLVMPY_GetTargetFromTriple.argtypes = [c_char_p, POINTER(c_char_p)]
384
+ ffi.lib.LLVMPY_GetTargetFromTriple.restype = ffi.LLVMTargetRef
385
+
386
+ ffi.lib.LLVMPY_GetTargetName.argtypes = [ffi.LLVMTargetRef]
387
+ ffi.lib.LLVMPY_GetTargetName.restype = c_char_p
388
+
389
+ ffi.lib.LLVMPY_GetTargetDescription.argtypes = [ffi.LLVMTargetRef]
390
+ ffi.lib.LLVMPY_GetTargetDescription.restype = c_char_p
391
+
392
+ ffi.lib.LLVMPY_CreateTargetMachine.argtypes = [
393
+ ffi.LLVMTargetRef,
394
+ # Triple
395
+ c_char_p,
396
+ # CPU
397
+ c_char_p,
398
+ # Features
399
+ c_char_p,
400
+ # OptLevel
401
+ c_int,
402
+ # Reloc
403
+ c_char_p,
404
+ # CodeModel
405
+ c_char_p,
406
+ # PrintMC
407
+ c_int,
408
+ # JIT
409
+ c_int,
410
+ # ABIName
411
+ c_char_p,
412
+ ]
413
+ ffi.lib.LLVMPY_CreateTargetMachine.restype = ffi.LLVMTargetMachineRef
414
+
415
+ ffi.lib.LLVMPY_DisposeTargetMachine.argtypes = [ffi.LLVMTargetMachineRef]
416
+
417
+ ffi.lib.LLVMPY_GetTargetMachineTriple.argtypes = [ffi.LLVMTargetMachineRef,
418
+ POINTER(c_char_p)]
419
+
420
+ ffi.lib.LLVMPY_SetTargetMachineAsmVerbosity.argtypes = [
421
+ ffi.LLVMTargetMachineRef, c_int]
422
+
423
+ ffi.lib.LLVMPY_AddAnalysisPasses.argtypes = [
424
+ ffi.LLVMTargetMachineRef,
425
+ ffi.LLVMPassManagerRef,
426
+ ]
427
+
428
+ ffi.lib.LLVMPY_TargetMachineEmitToMemory.argtypes = [
429
+ ffi.LLVMTargetMachineRef,
430
+ ffi.LLVMModuleRef,
431
+ c_int,
432
+ POINTER(c_char_p),
433
+ ]
434
+ ffi.lib.LLVMPY_TargetMachineEmitToMemory.restype = ffi.LLVMMemoryBufferRef
435
+
436
+ ffi.lib.LLVMPY_GetBufferStart.argtypes = [ffi.LLVMMemoryBufferRef]
437
+ ffi.lib.LLVMPY_GetBufferStart.restype = c_void_p
438
+
439
+ ffi.lib.LLVMPY_GetBufferSize.argtypes = [ffi.LLVMMemoryBufferRef]
440
+ ffi.lib.LLVMPY_GetBufferSize.restype = c_size_t
441
+
442
+ ffi.lib.LLVMPY_DisposeMemoryBuffer.argtypes = [ffi.LLVMMemoryBufferRef]
443
+
444
+ ffi.lib.LLVMPY_CreateTargetMachineData.argtypes = [
445
+ ffi.LLVMTargetMachineRef,
446
+ ]
447
+ ffi.lib.LLVMPY_CreateTargetMachineData.restype = ffi.LLVMTargetDataRef
448
+
449
+ ffi.lib.LLVMPY_HasSVMLSupport.argtypes = []
450
+ ffi.lib.LLVMPY_HasSVMLSupport.restype = c_int
vllm/lib/python3.10/site-packages/llvmlite/binding/transforms.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ctypes import c_uint, c_bool
2
+ from llvmlite.binding import ffi
3
+ from llvmlite.binding import passmanagers
4
+
5
+
6
+ def create_pass_manager_builder():
7
+ return PassManagerBuilder()
8
+
9
+
10
+ class PassManagerBuilder(ffi.ObjectRef):
11
+ __slots__ = ()
12
+
13
+ def __init__(self, ptr=None):
14
+ if ptr is None:
15
+ ptr = ffi.lib.LLVMPY_PassManagerBuilderCreate()
16
+ ffi.ObjectRef.__init__(self, ptr)
17
+
18
+ @property
19
+ def opt_level(self):
20
+ """
21
+ The general optimization level as an integer between 0 and 3.
22
+ """
23
+ return ffi.lib.LLVMPY_PassManagerBuilderGetOptLevel(self)
24
+
25
+ @opt_level.setter
26
+ def opt_level(self, level):
27
+ ffi.lib.LLVMPY_PassManagerBuilderSetOptLevel(self, level)
28
+
29
+ @property
30
+ def size_level(self):
31
+ """
32
+ Whether and how much to optimize for size. An integer between 0 and 2.
33
+ """
34
+ return ffi.lib.LLVMPY_PassManagerBuilderGetSizeLevel(self)
35
+
36
+ @size_level.setter
37
+ def size_level(self, size):
38
+ ffi.lib.LLVMPY_PassManagerBuilderSetSizeLevel(self, size)
39
+
40
+ @property
41
+ def inlining_threshold(self):
42
+ """
43
+ The integer threshold for inlining a function into another. The higher,
44
+ the more likely inlining a function is. This attribute is write-only.
45
+ """
46
+ raise NotImplementedError("inlining_threshold is write-only")
47
+
48
+ @inlining_threshold.setter
49
+ def inlining_threshold(self, threshold):
50
+ ffi.lib.LLVMPY_PassManagerBuilderUseInlinerWithThreshold(
51
+ self, threshold)
52
+
53
+ @property
54
+ def disable_unroll_loops(self):
55
+ """
56
+ If true, disable loop unrolling.
57
+ """
58
+ return ffi.lib.LLVMPY_PassManagerBuilderGetDisableUnrollLoops(self)
59
+
60
+ @disable_unroll_loops.setter
61
+ def disable_unroll_loops(self, disable=True):
62
+ ffi.lib.LLVMPY_PassManagerBuilderSetDisableUnrollLoops(self, disable)
63
+
64
+ @property
65
+ def loop_vectorize(self):
66
+ """
67
+ If true, allow vectorizing loops.
68
+ """
69
+ return ffi.lib.LLVMPY_PassManagerBuilderGetLoopVectorize(self)
70
+
71
+ @loop_vectorize.setter
72
+ def loop_vectorize(self, enable=True):
73
+ return ffi.lib.LLVMPY_PassManagerBuilderSetLoopVectorize(self, enable)
74
+
75
+ @property
76
+ def slp_vectorize(self):
77
+ """
78
+ If true, enable the "SLP vectorizer", which uses a different algorithm
79
+ from the loop vectorizer. Both may be enabled at the same time.
80
+ """
81
+ return ffi.lib.LLVMPY_PassManagerBuilderGetSLPVectorize(self)
82
+
83
+ @slp_vectorize.setter
84
+ def slp_vectorize(self, enable=True):
85
+ return ffi.lib.LLVMPY_PassManagerBuilderSetSLPVectorize(self, enable)
86
+
87
+ def _populate_module_pm(self, pm):
88
+ ffi.lib.LLVMPY_PassManagerBuilderPopulateModulePassManager(self, pm)
89
+
90
+ def _populate_function_pm(self, pm):
91
+ ffi.lib.LLVMPY_PassManagerBuilderPopulateFunctionPassManager(self, pm)
92
+
93
+ def populate(self, pm):
94
+ if isinstance(pm, passmanagers.ModulePassManager):
95
+ self._populate_module_pm(pm)
96
+ elif isinstance(pm, passmanagers.FunctionPassManager):
97
+ self._populate_function_pm(pm)
98
+ else:
99
+ raise TypeError(pm)
100
+
101
+ def _dispose(self):
102
+ self._capi.LLVMPY_PassManagerBuilderDispose(self)
103
+
104
+
105
+ # ============================================================================
106
+ # FFI
107
+
108
+ ffi.lib.LLVMPY_PassManagerBuilderCreate.restype = ffi.LLVMPassManagerBuilderRef
109
+
110
+ ffi.lib.LLVMPY_PassManagerBuilderDispose.argtypes = [
111
+ ffi.LLVMPassManagerBuilderRef,
112
+ ]
113
+
114
+ ffi.lib.LLVMPY_PassManagerBuilderPopulateModulePassManager.argtypes = [
115
+ ffi.LLVMPassManagerBuilderRef,
116
+ ffi.LLVMPassManagerRef,
117
+ ]
118
+
119
+ ffi.lib.LLVMPY_PassManagerBuilderPopulateFunctionPassManager.argtypes = [
120
+ ffi.LLVMPassManagerBuilderRef,
121
+ ffi.LLVMPassManagerRef,
122
+ ]
123
+
124
+ # Unsigned int PassManagerBuilder properties
125
+
126
+ for _func in (ffi.lib.LLVMPY_PassManagerBuilderSetOptLevel,
127
+ ffi.lib.LLVMPY_PassManagerBuilderSetSizeLevel,
128
+ ffi.lib.LLVMPY_PassManagerBuilderUseInlinerWithThreshold,
129
+ ):
130
+ _func.argtypes = [ffi.LLVMPassManagerBuilderRef, c_uint]
131
+
132
+ for _func in (ffi.lib.LLVMPY_PassManagerBuilderGetOptLevel,
133
+ ffi.lib.LLVMPY_PassManagerBuilderGetSizeLevel,
134
+ ):
135
+ _func.argtypes = [ffi.LLVMPassManagerBuilderRef]
136
+ _func.restype = c_uint
137
+
138
+ # Boolean PassManagerBuilder properties
139
+
140
+ for _func in (ffi.lib.LLVMPY_PassManagerBuilderSetDisableUnrollLoops,
141
+ ffi.lib.LLVMPY_PassManagerBuilderSetLoopVectorize,
142
+ ffi.lib.LLVMPY_PassManagerBuilderSetSLPVectorize,
143
+ ):
144
+ _func.argtypes = [ffi.LLVMPassManagerBuilderRef, c_bool]
145
+
146
+ for _func in (ffi.lib.LLVMPY_PassManagerBuilderGetDisableUnrollLoops,
147
+ ffi.lib.LLVMPY_PassManagerBuilderGetLoopVectorize,
148
+ ffi.lib.LLVMPY_PassManagerBuilderGetSLPVectorize,
149
+ ):
150
+ _func.argtypes = [ffi.LLVMPassManagerBuilderRef]
151
+ _func.restype = c_bool
vllm/lib/python3.10/site-packages/llvmlite/binding/typeref.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ctypes import c_int, c_bool, c_void_p, c_uint64
2
+ import enum
3
+
4
+ from llvmlite.binding import ffi
5
+
6
+
7
+ class TypeKind(enum.IntEnum):
8
+ # The LLVMTypeKind enum from llvm-c/Core.h
9
+
10
+ void = 0
11
+ half = 1
12
+ float = 2
13
+ double = 3
14
+ x86_fp80 = 4
15
+ fp128 = 5
16
+ ppc_fp128 = 6
17
+ label = 7
18
+ integer = 8
19
+ function = 9
20
+ struct = 10
21
+ array = 11
22
+ pointer = 12
23
+ vector = 13
24
+ metadata = 14
25
+ x86_mmx = 15
26
+ token = 16
27
+ scalable_vector = 17
28
+ bfloat = 18
29
+ x86_amx = 19
30
+
31
+
32
+ class TypeRef(ffi.ObjectRef):
33
+ """A weak reference to a LLVM type
34
+ """
35
+ @property
36
+ def name(self):
37
+ """
38
+ Get type name
39
+ """
40
+ return ffi.ret_string(ffi.lib.LLVMPY_GetTypeName(self))
41
+
42
+ @property
43
+ def is_struct(self):
44
+ """
45
+ Returns true if the type is a struct type.
46
+ """
47
+ return ffi.lib.LLVMPY_TypeIsStruct(self)
48
+
49
+ @property
50
+ def is_pointer(self):
51
+ """
52
+ Returns true if the type is a pointer type.
53
+ """
54
+ return ffi.lib.LLVMPY_TypeIsPointer(self)
55
+
56
+ @property
57
+ def is_array(self):
58
+ """
59
+ Returns true if the type is an array type.
60
+ """
61
+ return ffi.lib.LLVMPY_TypeIsArray(self)
62
+
63
+ @property
64
+ def is_vector(self):
65
+ """
66
+ Returns true if the type is a vector type.
67
+ """
68
+ return ffi.lib.LLVMPY_TypeIsVector(self)
69
+
70
+ @property
71
+ def is_function_vararg(self):
72
+ """
73
+ Returns true if a function type accepts a variable number of arguments.
74
+ When the type is not a function, raises exception.
75
+ """
76
+ if self.type_kind != TypeKind.function:
77
+ raise ValueError("Type {} is not a function".format(self))
78
+ return ffi.lib.LLVMPY_IsFunctionVararg(self)
79
+
80
+ @property
81
+ def elements(self):
82
+ """
83
+ Returns iterator over enclosing types
84
+ """
85
+ return _TypeListIterator(ffi.lib.LLVMPY_ElementIter(self))
86
+
87
+ @property
88
+ def element_type(self):
89
+ """
90
+ Returns the pointed-to type. When the type is not a pointer,
91
+ raises exception.
92
+ """
93
+ if not self.is_pointer:
94
+ raise ValueError("Type {} is not a pointer".format(self))
95
+ return TypeRef(ffi.lib.LLVMPY_GetElementType(self))
96
+
97
+ @property
98
+ def element_count(self):
99
+ """
100
+ Returns the number of elements in an array or a vector. For scalable
101
+ vectors, returns minimum number of elements. When the type is neither
102
+ an array nor a vector, raises exception.
103
+ """
104
+ if not self.is_array and not self.is_vector:
105
+ raise ValueError("Type {} is not an array nor vector".format(self))
106
+ return ffi.lib.LLVMPY_GetTypeElementCount(self)
107
+
108
+ @property
109
+ def type_width(self):
110
+ """
111
+ Return the basic size of this type if it is a primitive type. These are
112
+ fixed by LLVM and are not target-dependent.
113
+ This will return zero if the type does not have a size or is not a
114
+ primitive type.
115
+
116
+ If this is a scalable vector type, the scalable property will be set and
117
+ the runtime size will be a positive integer multiple of the base size.
118
+
119
+ Note that this may not reflect the size of memory allocated for an
120
+ instance of the type or the number of bytes that are written when an
121
+ instance of the type is stored to memory.
122
+ """
123
+ return ffi.lib.LLVMPY_GetTypeBitWidth(self)
124
+
125
+ @property
126
+ def type_kind(self):
127
+ """
128
+ Returns the LLVMTypeKind enumeration of this type.
129
+ """
130
+ return TypeKind(ffi.lib.LLVMPY_GetTypeKind(self))
131
+
132
+ def __str__(self):
133
+ return ffi.ret_string(ffi.lib.LLVMPY_PrintType(self))
134
+
135
+
136
+ class _TypeIterator(ffi.ObjectRef):
137
+
138
+ def __next__(self):
139
+ vp = self._next()
140
+ if vp:
141
+ return TypeRef(vp)
142
+ else:
143
+ raise StopIteration
144
+
145
+ next = __next__
146
+
147
+ def __iter__(self):
148
+ return self
149
+
150
+
151
+ class _TypeListIterator(_TypeIterator):
152
+
153
+ def _dispose(self):
154
+ self._capi.LLVMPY_DisposeElementIter(self)
155
+
156
+ def _next(self):
157
+ return ffi.lib.LLVMPY_ElementIterNext(self)
158
+
159
+
160
+ # FFI
161
+
162
+ ffi.lib.LLVMPY_PrintType.argtypes = [ffi.LLVMTypeRef]
163
+ ffi.lib.LLVMPY_PrintType.restype = c_void_p
164
+
165
+ ffi.lib.LLVMPY_GetElementType.argtypes = [ffi.LLVMTypeRef]
166
+ ffi.lib.LLVMPY_GetElementType.restype = ffi.LLVMTypeRef
167
+
168
+ ffi.lib.LLVMPY_TypeIsPointer.argtypes = [ffi.LLVMTypeRef]
169
+ ffi.lib.LLVMPY_TypeIsPointer.restype = c_bool
170
+
171
+ ffi.lib.LLVMPY_TypeIsArray.argtypes = [ffi.LLVMTypeRef]
172
+ ffi.lib.LLVMPY_TypeIsArray.restype = c_bool
173
+
174
+ ffi.lib.LLVMPY_TypeIsVector.argtypes = [ffi.LLVMTypeRef]
175
+ ffi.lib.LLVMPY_TypeIsVector.restype = c_bool
176
+
177
+ ffi.lib.LLVMPY_TypeIsStruct.argtypes = [ffi.LLVMTypeRef]
178
+ ffi.lib.LLVMPY_TypeIsStruct.restype = c_bool
179
+
180
+ ffi.lib.LLVMPY_IsFunctionVararg.argtypes = [ffi.LLVMTypeRef]
181
+ ffi.lib.LLVMPY_IsFunctionVararg.restype = c_bool
182
+
183
+ ffi.lib.LLVMPY_GetTypeKind.argtypes = [ffi.LLVMTypeRef]
184
+ ffi.lib.LLVMPY_GetTypeKind.restype = c_int
185
+
186
+ ffi.lib.LLVMPY_GetTypeElementCount.argtypes = [ffi.LLVMTypeRef]
187
+ ffi.lib.LLVMPY_GetTypeElementCount.restype = c_int
188
+
189
+ ffi.lib.LLVMPY_GetTypeBitWidth.argtypes = [ffi.LLVMTypeRef]
190
+ ffi.lib.LLVMPY_GetTypeBitWidth.restype = c_uint64
191
+
192
+ ffi.lib.LLVMPY_ElementIter.argtypes = [ffi.LLVMTypeRef]
193
+ ffi.lib.LLVMPY_ElementIter.restype = ffi.LLVMElementIterator
194
+
195
+ ffi.lib.LLVMPY_ElementIterNext.argtypes = [ffi.LLVMElementIterator]
196
+ ffi.lib.LLVMPY_ElementIterNext.restype = ffi.LLVMTypeRef
197
+
198
+ ffi.lib.LLVMPY_DisposeElementIter.argtypes = [ffi.LLVMElementIterator]
vllm/lib/python3.10/site-packages/llvmlite/binding/value.py ADDED
@@ -0,0 +1,618 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ctypes import (POINTER, byref, cast, c_char_p, c_double, c_int, c_size_t,
2
+ c_uint, c_uint64, c_bool, c_void_p)
3
+ import enum
4
+
5
+ from llvmlite.binding import ffi
6
+ from llvmlite.binding.common import _decode_string, _encode_string
7
+ from llvmlite.binding.typeref import TypeRef
8
+
9
+
10
+ class Linkage(enum.IntEnum):
11
+ # The LLVMLinkage enum from llvm-c/Core.h
12
+
13
+ external = 0
14
+ available_externally = 1
15
+ linkonce_any = 2
16
+ linkonce_odr = 3
17
+ linkonce_odr_autohide = 4
18
+ weak_any = 5
19
+ weak_odr = 6
20
+ appending = 7
21
+ internal = 8
22
+ private = 9
23
+ dllimport = 10
24
+ dllexport = 11
25
+ external_weak = 12
26
+ ghost = 13
27
+ common = 14
28
+ linker_private = 15
29
+ linker_private_weak = 16
30
+
31
+
32
+ class Visibility(enum.IntEnum):
33
+ # The LLVMVisibility enum from llvm-c/Core.h
34
+
35
+ default = 0
36
+ hidden = 1
37
+ protected = 2
38
+
39
+
40
+ class StorageClass(enum.IntEnum):
41
+ # The LLVMDLLStorageClass enum from llvm-c/Core.h
42
+
43
+ default = 0
44
+ dllimport = 1
45
+ dllexport = 2
46
+
47
+
48
+ class ValueKind(enum.IntEnum):
49
+ # The LLVMValueKind enum from llvm-c/Core.h
50
+
51
+ argument = 0
52
+ basic_block = 1
53
+ memory_use = 2
54
+ memory_def = 3
55
+ memory_phi = 4
56
+
57
+ function = 5
58
+ global_alias = 6
59
+ global_ifunc = 7
60
+ global_variable = 8
61
+ block_address = 9
62
+ constant_expr = 10
63
+ constant_array = 11
64
+ constant_struct = 12
65
+ constant_vector = 13
66
+
67
+ undef_value = 14
68
+ constant_aggregate_zero = 15
69
+ constant_data_array = 16
70
+ constant_data_vector = 17
71
+ constant_int = 18
72
+ constant_fp = 19
73
+ constant_pointer_null = 20
74
+ constant_token_none = 21
75
+
76
+ metadata_as_value = 22
77
+ inline_asm = 23
78
+
79
+ instruction = 24
80
+ poison_value = 25
81
+
82
+
83
+ class ValueRef(ffi.ObjectRef):
84
+ """A weak reference to a LLVM value.
85
+ """
86
+
87
+ def __init__(self, ptr, kind, parents):
88
+ self._kind = kind
89
+ self._parents = parents
90
+ ffi.ObjectRef.__init__(self, ptr)
91
+
92
+ def __str__(self):
93
+ with ffi.OutputString() as outstr:
94
+ ffi.lib.LLVMPY_PrintValueToString(self, outstr)
95
+ return str(outstr)
96
+
97
+ @property
98
+ def module(self):
99
+ """
100
+ The module this function or global variable value was obtained from.
101
+ """
102
+ return self._parents.get('module')
103
+
104
+ @property
105
+ def function(self):
106
+ """
107
+ The function this argument or basic block value was obtained from.
108
+ """
109
+ return self._parents.get('function')
110
+
111
+ @property
112
+ def block(self):
113
+ """
114
+ The block this instruction value was obtained from.
115
+ """
116
+ return self._parents.get('block')
117
+
118
+ @property
119
+ def instruction(self):
120
+ """
121
+ The instruction this operand value was obtained from.
122
+ """
123
+ return self._parents.get('instruction')
124
+
125
+ @property
126
+ def is_global(self):
127
+ return self._kind == 'global'
128
+
129
+ @property
130
+ def is_function(self):
131
+ return self._kind == 'function'
132
+
133
+ @property
134
+ def is_block(self):
135
+ return self._kind == 'block'
136
+
137
+ @property
138
+ def is_argument(self):
139
+ return self._kind == 'argument'
140
+
141
+ @property
142
+ def is_instruction(self):
143
+ return self._kind == 'instruction'
144
+
145
+ @property
146
+ def is_operand(self):
147
+ return self._kind == 'operand'
148
+
149
+ @property
150
+ def is_constant(self):
151
+ return bool(ffi.lib.LLVMPY_IsConstant(self))
152
+
153
+ @property
154
+ def value_kind(self):
155
+ return ValueKind(ffi.lib.LLVMPY_GetValueKind(self))
156
+
157
+ @property
158
+ def name(self):
159
+ return _decode_string(ffi.lib.LLVMPY_GetValueName(self))
160
+
161
+ @name.setter
162
+ def name(self, val):
163
+ ffi.lib.LLVMPY_SetValueName(self, _encode_string(val))
164
+
165
+ @property
166
+ def linkage(self):
167
+ return Linkage(ffi.lib.LLVMPY_GetLinkage(self))
168
+
169
+ @linkage.setter
170
+ def linkage(self, value):
171
+ if not isinstance(value, Linkage):
172
+ value = Linkage[value]
173
+ ffi.lib.LLVMPY_SetLinkage(self, value)
174
+
175
+ @property
176
+ def visibility(self):
177
+ return Visibility(ffi.lib.LLVMPY_GetVisibility(self))
178
+
179
+ @visibility.setter
180
+ def visibility(self, value):
181
+ if not isinstance(value, Visibility):
182
+ value = Visibility[value]
183
+ ffi.lib.LLVMPY_SetVisibility(self, value)
184
+
185
+ @property
186
+ def storage_class(self):
187
+ return StorageClass(ffi.lib.LLVMPY_GetDLLStorageClass(self))
188
+
189
+ @storage_class.setter
190
+ def storage_class(self, value):
191
+ if not isinstance(value, StorageClass):
192
+ value = StorageClass[value]
193
+ ffi.lib.LLVMPY_SetDLLStorageClass(self, value)
194
+
195
+ def add_function_attribute(self, attr):
196
+ """Only works on function value
197
+
198
+ Parameters
199
+ -----------
200
+ attr : str
201
+ attribute name
202
+ """
203
+ if not self.is_function:
204
+ raise ValueError('expected function value, got %s' % (self._kind,))
205
+ attrname = str(attr)
206
+ attrval = ffi.lib.LLVMPY_GetEnumAttributeKindForName(
207
+ _encode_string(attrname), len(attrname))
208
+ if attrval == 0:
209
+ raise ValueError('no such attribute {!r}'.format(attrname))
210
+ ffi.lib.LLVMPY_AddFunctionAttr(self, attrval)
211
+
212
+ @property
213
+ def type(self):
214
+ """
215
+ This value's LLVM type.
216
+ """
217
+ # XXX what does this return?
218
+ return TypeRef(ffi.lib.LLVMPY_TypeOf(self))
219
+
220
+ @property
221
+ def is_declaration(self):
222
+ """
223
+ Whether this value (presumably global) is defined in the current
224
+ module.
225
+ """
226
+ if not (self.is_global or self.is_function):
227
+ raise ValueError('expected global or function value, got %s'
228
+ % (self._kind,))
229
+ return ffi.lib.LLVMPY_IsDeclaration(self)
230
+
231
+ @property
232
+ def attributes(self):
233
+ """
234
+ Return an iterator over this value's attributes.
235
+ The iterator will yield a string for each attribute.
236
+ """
237
+ itr = iter(())
238
+ if self.is_function:
239
+ it = ffi.lib.LLVMPY_FunctionAttributesIter(self)
240
+ itr = _AttributeListIterator(it)
241
+ elif self.is_instruction:
242
+ if self.opcode == 'call':
243
+ it = ffi.lib.LLVMPY_CallInstAttributesIter(self)
244
+ itr = _AttributeListIterator(it)
245
+ elif self.opcode == 'invoke':
246
+ it = ffi.lib.LLVMPY_InvokeInstAttributesIter(self)
247
+ itr = _AttributeListIterator(it)
248
+ elif self.is_global:
249
+ it = ffi.lib.LLVMPY_GlobalAttributesIter(self)
250
+ itr = _AttributeSetIterator(it)
251
+ elif self.is_argument:
252
+ it = ffi.lib.LLVMPY_ArgumentAttributesIter(self)
253
+ itr = _AttributeSetIterator(it)
254
+ return itr
255
+
256
+ @property
257
+ def blocks(self):
258
+ """
259
+ Return an iterator over this function's blocks.
260
+ The iterator will yield a ValueRef for each block.
261
+ """
262
+ if not self.is_function:
263
+ raise ValueError('expected function value, got %s' % (self._kind,))
264
+ it = ffi.lib.LLVMPY_FunctionBlocksIter(self)
265
+ parents = self._parents.copy()
266
+ parents.update(function=self)
267
+ return _BlocksIterator(it, parents)
268
+
269
+ @property
270
+ def arguments(self):
271
+ """
272
+ Return an iterator over this function's arguments.
273
+ The iterator will yield a ValueRef for each argument.
274
+ """
275
+ if not self.is_function:
276
+ raise ValueError('expected function value, got %s' % (self._kind,))
277
+ it = ffi.lib.LLVMPY_FunctionArgumentsIter(self)
278
+ parents = self._parents.copy()
279
+ parents.update(function=self)
280
+ return _ArgumentsIterator(it, parents)
281
+
282
+ @property
283
+ def instructions(self):
284
+ """
285
+ Return an iterator over this block's instructions.
286
+ The iterator will yield a ValueRef for each instruction.
287
+ """
288
+ if not self.is_block:
289
+ raise ValueError('expected block value, got %s' % (self._kind,))
290
+ it = ffi.lib.LLVMPY_BlockInstructionsIter(self)
291
+ parents = self._parents.copy()
292
+ parents.update(block=self)
293
+ return _InstructionsIterator(it, parents)
294
+
295
+ @property
296
+ def operands(self):
297
+ """
298
+ Return an iterator over this instruction's operands.
299
+ The iterator will yield a ValueRef for each operand.
300
+ """
301
+ if not self.is_instruction:
302
+ raise ValueError('expected instruction value, got %s'
303
+ % (self._kind,))
304
+ it = ffi.lib.LLVMPY_InstructionOperandsIter(self)
305
+ parents = self._parents.copy()
306
+ parents.update(instruction=self)
307
+ return _OperandsIterator(it, parents)
308
+
309
+ @property
310
+ def opcode(self):
311
+ if not self.is_instruction:
312
+ raise ValueError('expected instruction value, got %s'
313
+ % (self._kind,))
314
+ return ffi.ret_string(ffi.lib.LLVMPY_GetOpcodeName(self))
315
+
316
+ @property
317
+ def incoming_blocks(self):
318
+ """
319
+ Return an iterator over this phi instruction's incoming blocks.
320
+ The iterator will yield a ValueRef for each block.
321
+ """
322
+ if not self.is_instruction or self.opcode != 'phi':
323
+ raise ValueError('expected phi instruction value, got %s'
324
+ % (self._kind,))
325
+ it = ffi.lib.LLVMPY_PhiIncomingBlocksIter(self)
326
+ parents = self._parents.copy()
327
+ parents.update(instruction=self)
328
+ return _IncomingBlocksIterator(it, parents)
329
+
330
+ def get_constant_value(self, signed_int=False, round_fp=False):
331
+ """
332
+ Return the constant value, either as a literal (when supported)
333
+ or as a string.
334
+
335
+ Parameters
336
+ -----------
337
+ signed_int : bool
338
+ if True and the constant is an integer, returns a signed version
339
+ round_fp : bool
340
+ if True and the constant is a floating point value, rounds the
341
+ result upon accuracy loss (e.g., when querying an fp128 value).
342
+ By default, raises an exception on accuracy loss
343
+ """
344
+ if not self.is_constant:
345
+ raise ValueError('expected constant value, got %s'
346
+ % (self._kind,))
347
+
348
+ if self.value_kind == ValueKind.constant_int:
349
+ # Python integers are also arbitrary-precision
350
+ little_endian = c_bool(False)
351
+ words = ffi.lib.LLVMPY_GetConstantIntNumWords(self)
352
+ ptr = ffi.lib.LLVMPY_GetConstantIntRawValue(
353
+ self, byref(little_endian))
354
+ asbytes = bytes(cast(ptr, POINTER(c_uint64 * words)).contents)
355
+ return int.from_bytes(
356
+ asbytes,
357
+ ('little' if little_endian.value else 'big'),
358
+ signed=signed_int,
359
+ )
360
+ elif self.value_kind == ValueKind.constant_fp:
361
+ # Convert floating-point values to double-precision (Python float)
362
+ accuracy_loss = c_bool(False)
363
+ value = ffi.lib.LLVMPY_GetConstantFPValue(self,
364
+ byref(accuracy_loss))
365
+ if accuracy_loss.value and not round_fp:
366
+ raise ValueError(
367
+ 'Accuracy loss encountered in conversion of constant '
368
+ f'value {str(self)}')
369
+
370
+ return value
371
+
372
+ # Otherwise, return the IR string
373
+ return str(self)
374
+
375
+
376
+ class _ValueIterator(ffi.ObjectRef):
377
+
378
+ kind = None # derived classes must specify the Value kind value
379
+ # as class attribute
380
+
381
+ def __init__(self, ptr, parents):
382
+ ffi.ObjectRef.__init__(self, ptr)
383
+ # Keep parent objects (module, function, etc) alive
384
+ self._parents = parents
385
+ if self.kind is None:
386
+ raise NotImplementedError('%s must specify kind attribute'
387
+ % (type(self).__name__,))
388
+
389
+ def __next__(self):
390
+ vp = self._next()
391
+ if vp:
392
+ return ValueRef(vp, self.kind, self._parents)
393
+ else:
394
+ raise StopIteration
395
+
396
+ next = __next__
397
+
398
+ def __iter__(self):
399
+ return self
400
+
401
+
402
+ class _AttributeIterator(ffi.ObjectRef):
403
+
404
+ def __next__(self):
405
+ vp = self._next()
406
+ if vp:
407
+ return vp
408
+ else:
409
+ raise StopIteration
410
+
411
+ next = __next__
412
+
413
+ def __iter__(self):
414
+ return self
415
+
416
+
417
+ class _AttributeListIterator(_AttributeIterator):
418
+
419
+ def _dispose(self):
420
+ self._capi.LLVMPY_DisposeAttributeListIter(self)
421
+
422
+ def _next(self):
423
+ return ffi.ret_bytes(ffi.lib.LLVMPY_AttributeListIterNext(self))
424
+
425
+
426
+ class _AttributeSetIterator(_AttributeIterator):
427
+
428
+ def _dispose(self):
429
+ self._capi.LLVMPY_DisposeAttributeSetIter(self)
430
+
431
+ def _next(self):
432
+ return ffi.ret_bytes(ffi.lib.LLVMPY_AttributeSetIterNext(self))
433
+
434
+
435
+ class _BlocksIterator(_ValueIterator):
436
+
437
+ kind = 'block'
438
+
439
+ def _dispose(self):
440
+ self._capi.LLVMPY_DisposeBlocksIter(self)
441
+
442
+ def _next(self):
443
+ return ffi.lib.LLVMPY_BlocksIterNext(self)
444
+
445
+
446
+ class _ArgumentsIterator(_ValueIterator):
447
+
448
+ kind = 'argument'
449
+
450
+ def _dispose(self):
451
+ self._capi.LLVMPY_DisposeArgumentsIter(self)
452
+
453
+ def _next(self):
454
+ return ffi.lib.LLVMPY_ArgumentsIterNext(self)
455
+
456
+
457
+ class _InstructionsIterator(_ValueIterator):
458
+
459
+ kind = 'instruction'
460
+
461
+ def _dispose(self):
462
+ self._capi.LLVMPY_DisposeInstructionsIter(self)
463
+
464
+ def _next(self):
465
+ return ffi.lib.LLVMPY_InstructionsIterNext(self)
466
+
467
+
468
+ class _OperandsIterator(_ValueIterator):
469
+
470
+ kind = 'operand'
471
+
472
+ def _dispose(self):
473
+ self._capi.LLVMPY_DisposeOperandsIter(self)
474
+
475
+ def _next(self):
476
+ return ffi.lib.LLVMPY_OperandsIterNext(self)
477
+
478
+
479
+ class _IncomingBlocksIterator(_ValueIterator):
480
+
481
+ kind = 'block'
482
+
483
+ def _dispose(self):
484
+ self._capi.LLVMPY_DisposeIncomingBlocksIter(self)
485
+
486
+ def _next(self):
487
+ return ffi.lib.LLVMPY_IncomingBlocksIterNext(self)
488
+
489
+
490
+ # FFI
491
+
492
+ ffi.lib.LLVMPY_PrintValueToString.argtypes = [
493
+ ffi.LLVMValueRef,
494
+ POINTER(c_char_p)
495
+ ]
496
+
497
+ ffi.lib.LLVMPY_GetGlobalParent.argtypes = [ffi.LLVMValueRef]
498
+ ffi.lib.LLVMPY_GetGlobalParent.restype = ffi.LLVMModuleRef
499
+
500
+ ffi.lib.LLVMPY_GetValueName.argtypes = [ffi.LLVMValueRef]
501
+ ffi.lib.LLVMPY_GetValueName.restype = c_char_p
502
+
503
+ ffi.lib.LLVMPY_SetValueName.argtypes = [ffi.LLVMValueRef, c_char_p]
504
+
505
+ ffi.lib.LLVMPY_TypeOf.argtypes = [ffi.LLVMValueRef]
506
+ ffi.lib.LLVMPY_TypeOf.restype = ffi.LLVMTypeRef
507
+
508
+ ffi.lib.LLVMPY_GetTypeName.argtypes = [ffi.LLVMTypeRef]
509
+ ffi.lib.LLVMPY_GetTypeName.restype = c_void_p
510
+
511
+ ffi.lib.LLVMPY_GetLinkage.argtypes = [ffi.LLVMValueRef]
512
+ ffi.lib.LLVMPY_GetLinkage.restype = c_int
513
+
514
+ ffi.lib.LLVMPY_SetLinkage.argtypes = [ffi.LLVMValueRef, c_int]
515
+
516
+ ffi.lib.LLVMPY_GetVisibility.argtypes = [ffi.LLVMValueRef]
517
+ ffi.lib.LLVMPY_GetVisibility.restype = c_int
518
+
519
+ ffi.lib.LLVMPY_SetVisibility.argtypes = [ffi.LLVMValueRef, c_int]
520
+
521
+ ffi.lib.LLVMPY_GetDLLStorageClass.argtypes = [ffi.LLVMValueRef]
522
+ ffi.lib.LLVMPY_GetDLLStorageClass.restype = c_int
523
+
524
+ ffi.lib.LLVMPY_SetDLLStorageClass.argtypes = [ffi.LLVMValueRef, c_int]
525
+
526
+ ffi.lib.LLVMPY_GetEnumAttributeKindForName.argtypes = [c_char_p, c_size_t]
527
+ ffi.lib.LLVMPY_GetEnumAttributeKindForName.restype = c_uint
528
+
529
+ ffi.lib.LLVMPY_AddFunctionAttr.argtypes = [ffi.LLVMValueRef, c_uint]
530
+
531
+ ffi.lib.LLVMPY_IsDeclaration.argtypes = [ffi.LLVMValueRef]
532
+ ffi.lib.LLVMPY_IsDeclaration.restype = c_int
533
+
534
+ ffi.lib.LLVMPY_FunctionAttributesIter.argtypes = [ffi.LLVMValueRef]
535
+ ffi.lib.LLVMPY_FunctionAttributesIter.restype = ffi.LLVMAttributeListIterator
536
+
537
+ ffi.lib.LLVMPY_CallInstAttributesIter.argtypes = [ffi.LLVMValueRef]
538
+ ffi.lib.LLVMPY_CallInstAttributesIter.restype = ffi.LLVMAttributeListIterator
539
+
540
+ ffi.lib.LLVMPY_InvokeInstAttributesIter.argtypes = [ffi.LLVMValueRef]
541
+ ffi.lib.LLVMPY_InvokeInstAttributesIter.restype = ffi.LLVMAttributeListIterator
542
+
543
+ ffi.lib.LLVMPY_GlobalAttributesIter.argtypes = [ffi.LLVMValueRef]
544
+ ffi.lib.LLVMPY_GlobalAttributesIter.restype = ffi.LLVMAttributeSetIterator
545
+
546
+ ffi.lib.LLVMPY_ArgumentAttributesIter.argtypes = [ffi.LLVMValueRef]
547
+ ffi.lib.LLVMPY_ArgumentAttributesIter.restype = ffi.LLVMAttributeSetIterator
548
+
549
+ ffi.lib.LLVMPY_FunctionBlocksIter.argtypes = [ffi.LLVMValueRef]
550
+ ffi.lib.LLVMPY_FunctionBlocksIter.restype = ffi.LLVMBlocksIterator
551
+
552
+ ffi.lib.LLVMPY_FunctionArgumentsIter.argtypes = [ffi.LLVMValueRef]
553
+ ffi.lib.LLVMPY_FunctionArgumentsIter.restype = ffi.LLVMArgumentsIterator
554
+
555
+ ffi.lib.LLVMPY_BlockInstructionsIter.argtypes = [ffi.LLVMValueRef]
556
+ ffi.lib.LLVMPY_BlockInstructionsIter.restype = ffi.LLVMInstructionsIterator
557
+
558
+ ffi.lib.LLVMPY_InstructionOperandsIter.argtypes = [ffi.LLVMValueRef]
559
+ ffi.lib.LLVMPY_InstructionOperandsIter.restype = ffi.LLVMOperandsIterator
560
+
561
+ ffi.lib.LLVMPY_PhiIncomingBlocksIter.argtypes = [ffi.LLVMValueRef]
562
+ ffi.lib.LLVMPY_PhiIncomingBlocksIter.restype = ffi.LLVMIncomingBlocksIterator
563
+
564
+ ffi.lib.LLVMPY_DisposeAttributeListIter.argtypes = [
565
+ ffi.LLVMAttributeListIterator]
566
+
567
+ ffi.lib.LLVMPY_DisposeAttributeSetIter.argtypes = [ffi.LLVMAttributeSetIterator]
568
+
569
+ ffi.lib.LLVMPY_DisposeBlocksIter.argtypes = [ffi.LLVMBlocksIterator]
570
+
571
+ ffi.lib.LLVMPY_DisposeInstructionsIter.argtypes = [ffi.LLVMInstructionsIterator]
572
+
573
+ ffi.lib.LLVMPY_DisposeOperandsIter.argtypes = [ffi.LLVMOperandsIterator]
574
+
575
+ ffi.lib.LLVMPY_DisposeIncomingBlocksIter.argtypes = [
576
+ ffi.LLVMIncomingBlocksIterator]
577
+
578
+ ffi.lib.LLVMPY_AttributeListIterNext.argtypes = [ffi.LLVMAttributeListIterator]
579
+ ffi.lib.LLVMPY_AttributeListIterNext.restype = c_void_p
580
+
581
+ ffi.lib.LLVMPY_AttributeSetIterNext.argtypes = [ffi.LLVMAttributeSetIterator]
582
+ ffi.lib.LLVMPY_AttributeSetIterNext.restype = c_void_p
583
+
584
+ ffi.lib.LLVMPY_BlocksIterNext.argtypes = [ffi.LLVMBlocksIterator]
585
+ ffi.lib.LLVMPY_BlocksIterNext.restype = ffi.LLVMValueRef
586
+
587
+ ffi.lib.LLVMPY_ArgumentsIterNext.argtypes = [ffi.LLVMArgumentsIterator]
588
+ ffi.lib.LLVMPY_ArgumentsIterNext.restype = ffi.LLVMValueRef
589
+
590
+ ffi.lib.LLVMPY_InstructionsIterNext.argtypes = [ffi.LLVMInstructionsIterator]
591
+ ffi.lib.LLVMPY_InstructionsIterNext.restype = ffi.LLVMValueRef
592
+
593
+ ffi.lib.LLVMPY_OperandsIterNext.argtypes = [ffi.LLVMOperandsIterator]
594
+ ffi.lib.LLVMPY_OperandsIterNext.restype = ffi.LLVMValueRef
595
+
596
+ ffi.lib.LLVMPY_IncomingBlocksIterNext.argtypes = [
597
+ ffi.LLVMIncomingBlocksIterator]
598
+ ffi.lib.LLVMPY_IncomingBlocksIterNext.restype = ffi.LLVMValueRef
599
+
600
+ ffi.lib.LLVMPY_GetOpcodeName.argtypes = [ffi.LLVMValueRef]
601
+ ffi.lib.LLVMPY_GetOpcodeName.restype = c_void_p
602
+
603
+ ffi.lib.LLVMPY_IsConstant.argtypes = [ffi.LLVMValueRef]
604
+ ffi.lib.LLVMPY_IsConstant.restype = c_bool
605
+
606
+ ffi.lib.LLVMPY_GetValueKind.argtypes = [ffi.LLVMValueRef]
607
+ ffi.lib.LLVMPY_GetValueKind.restype = c_int
608
+
609
+ ffi.lib.LLVMPY_GetConstantIntRawValue.argtypes = [ffi.LLVMValueRef,
610
+ POINTER(c_bool)]
611
+ ffi.lib.LLVMPY_GetConstantIntRawValue.restype = POINTER(c_uint64)
612
+
613
+ ffi.lib.LLVMPY_GetConstantIntNumWords.argtypes = [ffi.LLVMValueRef]
614
+ ffi.lib.LLVMPY_GetConstantIntNumWords.restype = c_uint
615
+
616
+ ffi.lib.LLVMPY_GetConstantFPValue.argtypes = [ffi.LLVMValueRef,
617
+ POINTER(c_bool)]
618
+ ffi.lib.LLVMPY_GetConstantFPValue.restype = c_double
vllm/lib/python3.10/site-packages/llvmlite/tests/__init__.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import unittest
4
+ from unittest import TestCase
5
+
6
+ import faulthandler
7
+
8
+
9
+ try:
10
+ # May fail in IPython Notebook with UnsupportedOperation
11
+ faulthandler.enable()
12
+ except BaseException as e:
13
+ msg = "Failed to enable faulthandler due to:\n{err}"
14
+ warnings.warn(msg.format(err=e))
15
+
16
+
17
+ # Try to inject Numba's unittest customizations.
18
+ from llvmlite.tests import customize
19
+
20
+
21
+ def discover_tests(startdir):
22
+ """Discover test under a directory
23
+ """
24
+ # Avoid importing unittest
25
+ loader = unittest.TestLoader()
26
+ suite = loader.discover(startdir)
27
+ return suite
28
+
29
+
30
+ def run_tests(suite=None, xmloutput=None, verbosity=1):
31
+ """
32
+ args
33
+ ----
34
+ - suite [TestSuite]
35
+ A suite of all tests to run
36
+ - xmloutput [str or None]
37
+ Path of XML output directory (optional)
38
+ - verbosity [int]
39
+ Verbosity level of tests output
40
+
41
+ Returns the TestResult object after running the test *suite*.
42
+ """
43
+ if suite is None:
44
+ suite = discover_tests("llvmlite.tests")
45
+ if xmloutput is not None:
46
+ import xmlrunner
47
+ runner = xmlrunner.XMLTestRunner(output=xmloutput)
48
+ else:
49
+ runner = None
50
+ prog = unittest.main(suite=suite, testRunner=runner, exit=False,
51
+ verbosity=verbosity)
52
+ return prog.result
53
+
54
+
55
+ def main():
56
+ res = run_tests()
57
+ sys.exit(0 if res.wasSuccessful() else 1)
vllm/lib/python3.10/site-packages/llvmlite/tests/__main__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from llvmlite.tests import main
2
+
3
+ main()
vllm/lib/python3.10/site-packages/llvmlite/tests/customize.py ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # XXX Ripped off from numba.tests; we should factor it out somewhere?
2
+
3
+ import collections
4
+ import contextlib
5
+ import cProfile
6
+ from io import StringIO
7
+ import gc
8
+ import os
9
+ import multiprocessing
10
+ import sys
11
+ import time
12
+ import unittest
13
+ import warnings
14
+ from unittest import result, runner, signals
15
+
16
+
17
+ # "unittest.main" is really the TestProgram class!
18
+ # (defined in a module named itself "unittest.main"...)
19
+
20
+ class NumbaTestProgram(unittest.main):
21
+ """
22
+ A TestProgram subclass adding the following options:
23
+ * a -R option to enable reference leak detection
24
+ * a --profile option to enable profiling of the test run
25
+
26
+ Currently the options are only added in 3.4+.
27
+ """
28
+
29
+ refleak = False
30
+ profile = False
31
+ multiprocess = False
32
+
33
+ def __init__(self, *args, **kwargs):
34
+ self.discovered_suite = kwargs.pop('suite', None)
35
+ # HACK to force unittest not to change warning display options
36
+ # (so that NumbaWarnings don't appear all over the place)
37
+ sys.warnoptions.append(':x')
38
+ super(NumbaTestProgram, self).__init__(*args, **kwargs)
39
+
40
+ def createTests(self):
41
+ if self.discovered_suite is not None:
42
+ self.test = self.discovered_suite
43
+ else:
44
+ super(NumbaTestProgram, self).createTests()
45
+
46
+ def _getParentArgParser(self):
47
+ # NOTE: this hook only exists on Python 3.4+. The options won't be
48
+ # added in earlier versions (which use optparse - 3.3 - or getopt()
49
+ # - 2.x).
50
+ parser = super(NumbaTestProgram, self)._getParentArgParser()
51
+ if self.testRunner is None:
52
+ parser.add_argument('-R', '--refleak', dest='refleak',
53
+ action='store_true',
54
+ help='Detect reference / memory leaks')
55
+ parser.add_argument('-m', '--multiprocess', dest='multiprocess',
56
+ action='store_true',
57
+ help='Parallelize tests')
58
+ parser.add_argument('--profile', dest='profile',
59
+ action='store_true',
60
+ help='Profile the test run')
61
+ return parser
62
+
63
+ def parseArgs(self, argv):
64
+ if sys.version_info < (3, 4):
65
+ # We want these options to work on all versions, emulate them.
66
+ if '-R' in argv:
67
+ argv.remove('-R')
68
+ self.refleak = True
69
+ if '-m' in argv:
70
+ argv.remove('-m')
71
+ self.multiprocess = True
72
+ super(NumbaTestProgram, self).parseArgs(argv)
73
+ if self.verbosity <= 0:
74
+ # We aren't interested in informational messages / warnings when
75
+ # running with '-q'.
76
+ self.buffer = True
77
+
78
+ def runTests(self):
79
+ if self.refleak:
80
+ self.testRunner = RefleakTestRunner
81
+
82
+ if not hasattr(sys, "gettotalrefcount"):
83
+ warnings.warn("detecting reference leaks requires a debug "
84
+ "build of Python, only memory leaks will be "
85
+ "detected")
86
+
87
+ elif self.testRunner is None:
88
+ self.testRunner = unittest.TextTestRunner
89
+
90
+ if self.multiprocess:
91
+ self.testRunner = ParallelTestRunner(self.testRunner,
92
+ verbosity=self.verbosity,
93
+ failfast=self.failfast,
94
+ buffer=self.buffer)
95
+
96
+ def run_tests_real():
97
+ super(NumbaTestProgram, self).runTests()
98
+
99
+ if self.profile:
100
+ filename = os.path.splitext(
101
+ os.path.basename(sys.modules['__main__'].__file__)
102
+ )[0] + '.prof'
103
+ p = cProfile.Profile(timer=time.perf_counter) # 3.3+
104
+ p.enable()
105
+ try:
106
+ p.runcall(run_tests_real)
107
+ finally:
108
+ p.disable()
109
+ print("Writing test profile data into %r" % (filename,))
110
+ p.dump_stats(filename)
111
+ else:
112
+ run_tests_real()
113
+
114
+
115
+ # Monkey-patch unittest so that individual test modules get our custom
116
+ # options for free.
117
+ unittest.main = NumbaTestProgram
118
+
119
+
120
+ # The reference leak detection code is liberally taken and adapted from
121
+ # Python's own Lib/test/regrtest.py.
122
+
123
+ def _refleak_cleanup():
124
+ # Collect cyclic trash and read memory statistics immediately after.
125
+ try:
126
+ func1 = sys.getallocatedblocks
127
+ except AttributeError:
128
+ def func1():
129
+ return 42
130
+ try:
131
+ func2 = sys.gettotalrefcount
132
+ except AttributeError:
133
+ def func2():
134
+ return 42
135
+
136
+ # Flush standard output, so that buffered data is sent to the OS and
137
+ # associated Python objects are reclaimed.
138
+ for stream in (sys.stdout, sys.stderr, sys.__stdout__, sys.__stderr__):
139
+ if stream is not None:
140
+ stream.flush()
141
+
142
+ sys._clear_type_cache()
143
+ # This also clears the various internal CPython freelists.
144
+ gc.collect()
145
+ return func1(), func2()
146
+
147
+
148
+ class ReferenceLeakError(RuntimeError):
149
+ pass
150
+
151
+
152
+ class IntPool(collections.defaultdict):
153
+
154
+ def __missing__(self, key):
155
+ return key
156
+
157
+
158
+ class RefleakTestResult(runner.TextTestResult):
159
+
160
+ warmup = 3
161
+ repetitions = 6
162
+
163
+ def _huntLeaks(self, test):
164
+ self.stream.flush()
165
+
166
+ repcount = self.repetitions
167
+ nwarmup = self.warmup
168
+ rc_deltas = [0] * (repcount - nwarmup)
169
+ alloc_deltas = [0] * (repcount - nwarmup)
170
+ # Preallocate ints likely to be stored in rc_deltas and alloc_deltas,
171
+ # to make sys.getallocatedblocks() less flaky.
172
+ _int_pool = IntPool()
173
+ for i in range(-200, 200):
174
+ _int_pool[i]
175
+
176
+ alloc_before = rc_before = 0
177
+ for i in range(repcount):
178
+ # Use a pristine, silent result object to avoid recursion
179
+ res = result.TestResult()
180
+ test.run(res)
181
+ # Poorly-written tests may fail when run several times.
182
+ # In this case, abort the refleak run and report the failure.
183
+ if not res.wasSuccessful():
184
+ self.failures.extend(res.failures)
185
+ self.errors.extend(res.errors)
186
+ raise AssertionError
187
+ del res
188
+ alloc_after, rc_after = _refleak_cleanup()
189
+ if i >= nwarmup:
190
+ rc_deltas[i - nwarmup] = _int_pool[rc_after - rc_before]
191
+ alloc_deltas[i -
192
+ nwarmup] = _int_pool[alloc_after -
193
+ alloc_before]
194
+ alloc_before, rc_before = alloc_after, rc_after
195
+ return rc_deltas, alloc_deltas
196
+
197
+ def addSuccess(self, test):
198
+ try:
199
+ rc_deltas, alloc_deltas = self._huntLeaks(test)
200
+ except AssertionError:
201
+ # Test failed when repeated
202
+ assert not self.wasSuccessful()
203
+ return
204
+
205
+ # These checkers return False on success, True on failure
206
+ def check_rc_deltas(deltas):
207
+ return any(deltas)
208
+
209
+ def check_alloc_deltas(deltas):
210
+ # At least 1/3rd of 0s
211
+ if 3 * deltas.count(0) < len(deltas):
212
+ return True
213
+ # Nothing else than 1s, 0s and -1s
214
+ if not set(deltas) <= set((1, 0, -1)):
215
+ return True
216
+ return False
217
+
218
+ failed = False
219
+
220
+ for deltas, item_name, checker in [
221
+ (rc_deltas, 'references', check_rc_deltas),
222
+ (alloc_deltas, 'memory blocks', check_alloc_deltas)]:
223
+ if checker(deltas):
224
+ msg = '%s leaked %s %s, sum=%s' % (
225
+ test, deltas, item_name, sum(deltas))
226
+ failed = True
227
+ try:
228
+ raise ReferenceLeakError(msg)
229
+ except Exception:
230
+ exc_info = sys.exc_info()
231
+ if self.showAll:
232
+ self.stream.write("%s = %r " % (item_name, deltas))
233
+ self.addFailure(test, exc_info)
234
+
235
+ if not failed:
236
+ super(RefleakTestResult, self).addSuccess(test)
237
+
238
+
239
+ class RefleakTestRunner(runner.TextTestRunner):
240
+ resultclass = RefleakTestResult
241
+
242
+
243
+ def _flatten_suite(test):
244
+ """Expand suite into list of tests
245
+ """
246
+ if isinstance(test, unittest.TestSuite):
247
+ tests = []
248
+ for x in test:
249
+ tests.extend(_flatten_suite(x))
250
+ return tests
251
+ else:
252
+ return [test]
253
+
254
+
255
+ class ParallelTestResult(runner.TextTestResult):
256
+ """
257
+ A TestResult able to inject results from other results.
258
+ """
259
+
260
+ def add_results(self, result):
261
+ """
262
+ Add the results from the other *result* to this result.
263
+ """
264
+ self.stream.write(result.stream.getvalue())
265
+ self.stream.flush()
266
+ self.testsRun += result.testsRun
267
+ self.failures.extend(result.failures)
268
+ self.errors.extend(result.errors)
269
+ self.skipped.extend(result.skipped)
270
+ self.expectedFailures.extend(result.expectedFailures)
271
+ self.unexpectedSuccesses.extend(result.unexpectedSuccesses)
272
+
273
+
274
+ class _MinimalResult(object):
275
+ """
276
+ A minimal, picklable TestResult-alike object.
277
+ """
278
+
279
+ __slots__ = (
280
+ 'failures', 'errors', 'skipped', 'expectedFailures',
281
+ 'unexpectedSuccesses', 'stream', 'shouldStop', 'testsRun')
282
+
283
+ def fixup_case(self, case):
284
+ """
285
+ Remove any unpicklable attributes from TestCase instance *case*.
286
+ """
287
+ # Python 3.3 doesn't reset this one.
288
+ case._outcomeForDoCleanups = None
289
+
290
+ def __init__(self, original_result):
291
+ for attr in self.__slots__:
292
+ setattr(self, attr, getattr(original_result, attr))
293
+ for case, _ in self.expectedFailures:
294
+ self.fixup_case(case)
295
+ for case, _ in self.errors:
296
+ self.fixup_case(case)
297
+ for case, _ in self.failures:
298
+ self.fixup_case(case)
299
+
300
+
301
+ class _FakeStringIO(object):
302
+ """
303
+ A trivial picklable StringIO-alike for Python 2.
304
+ """
305
+
306
+ def __init__(self, value):
307
+ self._value = value
308
+
309
+ def getvalue(self):
310
+ return self._value
311
+
312
+
313
+ class _MinimalRunner(object):
314
+ """
315
+ A minimal picklable object able to instantiate a runner in a
316
+ child process and run a test case with it.
317
+ """
318
+
319
+ def __init__(self, runner_cls, runner_args):
320
+ self.runner_cls = runner_cls
321
+ self.runner_args = runner_args
322
+
323
+ # Python 2 doesn't know how to pickle instance methods, so we use __call__
324
+ # instead.
325
+
326
+ def __call__(self, test):
327
+ # Executed in child process
328
+ kwargs = self.runner_args
329
+ # Force recording of output in a buffer (it will be printed out
330
+ # by the parent).
331
+ kwargs['stream'] = StringIO()
332
+ runner = self.runner_cls(**kwargs)
333
+ result = runner._makeResult()
334
+ # Avoid child tracebacks when Ctrl-C is pressed.
335
+ signals.installHandler()
336
+ signals.registerResult(result)
337
+ result.failfast = runner.failfast
338
+ result.buffer = runner.buffer
339
+ with self.cleanup_object(test):
340
+ test(result)
341
+ # HACK as cStringIO.StringIO isn't picklable in 2.x
342
+ result.stream = _FakeStringIO(result.stream.getvalue())
343
+ return _MinimalResult(result)
344
+
345
+ @contextlib.contextmanager
346
+ def cleanup_object(self, test):
347
+ """
348
+ A context manager which cleans up unwanted attributes on a test case
349
+ (or any other object).
350
+ """
351
+ vanilla_attrs = set(test.__dict__)
352
+ try:
353
+ yield test
354
+ finally:
355
+ spurious_attrs = set(test.__dict__) - vanilla_attrs
356
+ for name in spurious_attrs:
357
+ del test.__dict__[name]
358
+
359
+
360
+ class ParallelTestRunner(runner.TextTestRunner):
361
+ """
362
+ A test runner which delegates the actual running to a pool of child
363
+ processes.
364
+ """
365
+
366
+ resultclass = ParallelTestResult
367
+
368
+ def __init__(self, runner_cls, **kwargs):
369
+ runner.TextTestRunner.__init__(self, **kwargs)
370
+ self.runner_cls = runner_cls
371
+ self.runner_args = kwargs
372
+
373
+ def _run_inner(self, result):
374
+ # We hijack TextTestRunner.run()'s inner logic by passing this
375
+ # method as if it were a test case.
376
+ child_runner = _MinimalRunner(self.runner_cls, self.runner_args)
377
+ pool = multiprocessing.Pool()
378
+ imap = pool.imap_unordered
379
+ try:
380
+ for child_result in imap(child_runner, self._test_list):
381
+ result.add_results(child_result)
382
+ if child_result.shouldStop:
383
+ break
384
+ return result
385
+ finally:
386
+ # Kill the still active workers
387
+ pool.terminate()
388
+ pool.join()
389
+
390
+ def run(self, test):
391
+ self._test_list = _flatten_suite(test)
392
+ # This will call self._run_inner() on the created result object,
393
+ # and print out the detailed test results at the end.
394
+ return super(ParallelTestRunner, self).run(self._run_inner)
395
+
396
+
397
+ try:
398
+ import faulthandler
399
+ except ImportError:
400
+ pass
401
+ else:
402
+ try:
403
+ # May fail in IPython Notebook with UnsupportedOperation
404
+ faulthandler.enable()
405
+ except BaseException as e:
406
+ msg = "Failed to enable faulthandler due to:\n{err}"
407
+ warnings.warn(msg.format(err=e))
vllm/lib/python3.10/site-packages/llvmlite/tests/test_valuerepr.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import sys
3
+ import unittest
4
+
5
+ from llvmlite.ir import (
6
+ Constant, FloatType, DoubleType, LiteralStructType, IntType,
7
+ ArrayType, HalfType)
8
+ from llvmlite.tests import TestCase
9
+
10
+
11
+ int8 = IntType(8)
12
+ int16 = IntType(16)
13
+
14
+
15
+ PY36_OR_LATER = sys.version_info[:2] >= (3, 6)
16
+
17
+
18
+ class TestValueRepr(TestCase):
19
+
20
+ def test_double_repr(self):
21
+ def check_repr(val, expected):
22
+ c = Constant(DoubleType(), val)
23
+ self.assertEqual(str(c), expected)
24
+ check_repr(math.pi, "double 0x400921fb54442d18")
25
+ check_repr(float('inf'), "double 0x7ff0000000000000")
26
+ check_repr(float('-inf'), "double 0xfff0000000000000")
27
+
28
+ def test_float_repr(self):
29
+ def check_repr(val, expected):
30
+ c = Constant(FloatType(), val)
31
+ self.assertEqual(str(c), expected)
32
+ check_repr(math.pi, "float 0x400921fb60000000")
33
+ check_repr(float('inf'), "float 0x7ff0000000000000")
34
+ check_repr(float('-inf'), "float 0xfff0000000000000")
35
+
36
+ @unittest.skipUnless(PY36_OR_LATER, 'py36+ only')
37
+ def test_half_repr(self):
38
+ def check_repr(val, expected):
39
+ c = Constant(HalfType(), val)
40
+ self.assertEqual(str(c), expected)
41
+ check_repr(math.pi, "half 0x4009200000000000")
42
+ check_repr(float('inf'), "half 0x7ff0000000000000")
43
+ check_repr(float('-inf'), "half 0xfff0000000000000")
44
+
45
+ def test_struct_repr(self):
46
+ tp = LiteralStructType([int8, int16])
47
+ c = Constant(tp, (Constant(int8, 100), Constant(int16, 1000)))
48
+ self.assertEqual(str(c), "{i8, i16} {i8 100, i16 1000}")
49
+
50
+ def test_array_repr(self):
51
+ tp = ArrayType(int8, 3)
52
+ values = [Constant(int8, x) for x in (5, 10, -15)]
53
+ c = Constant(tp, values)
54
+ self.assertEqual(str(c), "[3 x i8] [i8 5, i8 10, i8 -15]")
55
+ c = Constant(tp, bytearray(b"\x01\x02\x03"))
56
+ self.assertEqual(str(c), '[3 x i8] c"\\01\\02\\03"')
57
+
58
+
59
+ if __name__ == "__main__":
60
+ unittest.main()
vllm/lib/python3.10/site-packages/llvmlite/utils.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+
5
+ # This module must be importable without loading the binding, to avoid
6
+ # bootstrapping issues in setup.py.
7
+
8
+ def get_library_name():
9
+ """
10
+ Return the name of the llvmlite shared library file.
11
+ """
12
+ if os.name == 'posix':
13
+ if sys.platform == 'darwin':
14
+ return 'libllvmlite.dylib'
15
+ else:
16
+ return 'libllvmlite.so'
17
+ else:
18
+ assert os.name == 'nt'
19
+ return 'llvmlite.dll'
20
+
21
+
22
+ def get_library_files():
23
+ """
24
+ Return the names of shared library files needed for this platform.
25
+ """
26
+ files = [get_library_name()]
27
+ if os.name == 'nt':
28
+ files.extend(['msvcr120.dll', 'msvcp120.dll'])
29
+ return files