numba-cuda 0.19.1__py3-none-any.whl → 0.20.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of numba-cuda might be problematic. Click here for more details.

Files changed (171) hide show
  1. numba_cuda/VERSION +1 -1
  2. numba_cuda/numba/cuda/__init__.py +1 -1
  3. numba_cuda/numba/cuda/_internal/cuda_bf16.py +12706 -1470
  4. numba_cuda/numba/cuda/_internal/cuda_fp16.py +2653 -8769
  5. numba_cuda/numba/cuda/api.py +6 -1
  6. numba_cuda/numba/cuda/bf16.py +285 -2
  7. numba_cuda/numba/cuda/cgutils.py +2 -2
  8. numba_cuda/numba/cuda/cloudpickle/__init__.py +21 -0
  9. numba_cuda/numba/cuda/cloudpickle/cloudpickle.py +1598 -0
  10. numba_cuda/numba/cuda/cloudpickle/cloudpickle_fast.py +17 -0
  11. numba_cuda/numba/cuda/codegen.py +1 -1
  12. numba_cuda/numba/cuda/compiler.py +373 -30
  13. numba_cuda/numba/cuda/core/analysis.py +319 -0
  14. numba_cuda/numba/cuda/core/annotations/__init__.py +0 -0
  15. numba_cuda/numba/cuda/core/annotations/type_annotations.py +304 -0
  16. numba_cuda/numba/cuda/core/base.py +1289 -0
  17. numba_cuda/numba/cuda/core/bytecode.py +727 -0
  18. numba_cuda/numba/cuda/core/caching.py +2 -2
  19. numba_cuda/numba/cuda/core/compiler.py +6 -14
  20. numba_cuda/numba/cuda/core/compiler_machinery.py +497 -0
  21. numba_cuda/numba/cuda/core/config.py +747 -0
  22. numba_cuda/numba/cuda/core/consts.py +124 -0
  23. numba_cuda/numba/cuda/core/cpu.py +370 -0
  24. numba_cuda/numba/cuda/core/environment.py +68 -0
  25. numba_cuda/numba/cuda/core/event.py +511 -0
  26. numba_cuda/numba/cuda/core/funcdesc.py +330 -0
  27. numba_cuda/numba/cuda/core/inline_closurecall.py +1889 -0
  28. numba_cuda/numba/cuda/core/interpreter.py +48 -26
  29. numba_cuda/numba/cuda/core/ir_utils.py +15 -26
  30. numba_cuda/numba/cuda/core/options.py +262 -0
  31. numba_cuda/numba/cuda/core/postproc.py +249 -0
  32. numba_cuda/numba/cuda/core/pythonapi.py +1868 -0
  33. numba_cuda/numba/cuda/core/rewrites/__init__.py +26 -0
  34. numba_cuda/numba/cuda/core/rewrites/ir_print.py +90 -0
  35. numba_cuda/numba/cuda/core/rewrites/registry.py +104 -0
  36. numba_cuda/numba/cuda/core/rewrites/static_binop.py +40 -0
  37. numba_cuda/numba/cuda/core/rewrites/static_getitem.py +187 -0
  38. numba_cuda/numba/cuda/core/rewrites/static_raise.py +98 -0
  39. numba_cuda/numba/cuda/core/ssa.py +496 -0
  40. numba_cuda/numba/cuda/core/targetconfig.py +329 -0
  41. numba_cuda/numba/cuda/core/tracing.py +231 -0
  42. numba_cuda/numba/cuda/core/transforms.py +952 -0
  43. numba_cuda/numba/cuda/core/typed_passes.py +738 -7
  44. numba_cuda/numba/cuda/core/typeinfer.py +1948 -0
  45. numba_cuda/numba/cuda/core/unsafe/__init__.py +0 -0
  46. numba_cuda/numba/cuda/core/unsafe/bytes.py +67 -0
  47. numba_cuda/numba/cuda/core/unsafe/eh.py +66 -0
  48. numba_cuda/numba/cuda/core/unsafe/refcount.py +98 -0
  49. numba_cuda/numba/cuda/core/untyped_passes.py +1983 -0
  50. numba_cuda/numba/cuda/cpython/cmathimpl.py +560 -0
  51. numba_cuda/numba/cuda/cpython/mathimpl.py +499 -0
  52. numba_cuda/numba/cuda/cpython/numbers.py +1474 -0
  53. numba_cuda/numba/cuda/cuda_paths.py +422 -246
  54. numba_cuda/numba/cuda/cudadecl.py +1 -1
  55. numba_cuda/numba/cuda/cudadrv/__init__.py +1 -1
  56. numba_cuda/numba/cuda/cudadrv/devicearray.py +2 -1
  57. numba_cuda/numba/cuda/cudadrv/driver.py +11 -140
  58. numba_cuda/numba/cuda/cudadrv/dummyarray.py +111 -24
  59. numba_cuda/numba/cuda/cudadrv/libs.py +5 -5
  60. numba_cuda/numba/cuda/cudadrv/mappings.py +1 -1
  61. numba_cuda/numba/cuda/cudadrv/nvrtc.py +19 -8
  62. numba_cuda/numba/cuda/cudadrv/nvvm.py +1 -4
  63. numba_cuda/numba/cuda/cudadrv/runtime.py +1 -1
  64. numba_cuda/numba/cuda/cudaimpl.py +5 -1
  65. numba_cuda/numba/cuda/debuginfo.py +85 -2
  66. numba_cuda/numba/cuda/decorators.py +3 -3
  67. numba_cuda/numba/cuda/descriptor.py +3 -4
  68. numba_cuda/numba/cuda/deviceufunc.py +66 -2
  69. numba_cuda/numba/cuda/dispatcher.py +18 -39
  70. numba_cuda/numba/cuda/flags.py +141 -1
  71. numba_cuda/numba/cuda/fp16.py +0 -2
  72. numba_cuda/numba/cuda/include/13/cuda_bf16.h +5118 -0
  73. numba_cuda/numba/cuda/include/13/cuda_bf16.hpp +3865 -0
  74. numba_cuda/numba/cuda/include/13/cuda_fp16.h +5363 -0
  75. numba_cuda/numba/cuda/include/13/cuda_fp16.hpp +3483 -0
  76. numba_cuda/numba/cuda/lowering.py +7 -144
  77. numba_cuda/numba/cuda/mathimpl.py +2 -1
  78. numba_cuda/numba/cuda/memory_management/nrt.py +43 -17
  79. numba_cuda/numba/cuda/misc/findlib.py +75 -0
  80. numba_cuda/numba/cuda/models.py +9 -1
  81. numba_cuda/numba/cuda/np/npdatetime_helpers.py +217 -0
  82. numba_cuda/numba/cuda/np/npyfuncs.py +1807 -0
  83. numba_cuda/numba/cuda/np/numpy_support.py +553 -0
  84. numba_cuda/numba/cuda/np/ufunc/ufuncbuilder.py +59 -0
  85. numba_cuda/numba/cuda/nvvmutils.py +1 -1
  86. numba_cuda/numba/cuda/printimpl.py +12 -1
  87. numba_cuda/numba/cuda/random.py +1 -1
  88. numba_cuda/numba/cuda/serialize.py +1 -1
  89. numba_cuda/numba/cuda/simulator/__init__.py +1 -1
  90. numba_cuda/numba/cuda/simulator/api.py +1 -1
  91. numba_cuda/numba/cuda/simulator/compiler.py +4 -0
  92. numba_cuda/numba/cuda/simulator/cudadrv/devicearray.py +1 -1
  93. numba_cuda/numba/cuda/simulator/kernelapi.py +1 -1
  94. numba_cuda/numba/cuda/simulator/memory_management/nrt.py +14 -2
  95. numba_cuda/numba/cuda/target.py +35 -17
  96. numba_cuda/numba/cuda/testing.py +4 -19
  97. numba_cuda/numba/cuda/tests/__init__.py +1 -1
  98. numba_cuda/numba/cuda/tests/cloudpickle_main_class.py +9 -0
  99. numba_cuda/numba/cuda/tests/core/test_serialize.py +4 -4
  100. numba_cuda/numba/cuda/tests/cudadrv/test_cuda_devicerecord.py +1 -1
  101. numba_cuda/numba/cuda/tests/cudadrv/test_cuda_libraries.py +1 -1
  102. numba_cuda/numba/cuda/tests/cudadrv/test_deallocations.py +1 -1
  103. numba_cuda/numba/cuda/tests/cudadrv/test_detect.py +6 -3
  104. numba_cuda/numba/cuda/tests/cudadrv/test_emm_plugins.py +1 -1
  105. numba_cuda/numba/cuda/tests/cudadrv/test_linker.py +18 -2
  106. numba_cuda/numba/cuda/tests/cudadrv/test_module_callbacks.py +2 -1
  107. numba_cuda/numba/cuda/tests/cudadrv/test_nvjitlink.py +1 -1
  108. numba_cuda/numba/cuda/tests/cudadrv/test_ptds.py +1 -1
  109. numba_cuda/numba/cuda/tests/cudapy/extensions_usecases.py +1 -1
  110. numba_cuda/numba/cuda/tests/cudapy/test_array.py +2 -1
  111. numba_cuda/numba/cuda/tests/cudapy/test_atomics.py +1 -1
  112. numba_cuda/numba/cuda/tests/cudapy/test_bfloat16.py +539 -2
  113. numba_cuda/numba/cuda/tests/cudapy/test_bfloat16_bindings.py +81 -1
  114. numba_cuda/numba/cuda/tests/cudapy/test_caching.py +1 -3
  115. numba_cuda/numba/cuda/tests/cudapy/test_complex.py +1 -1
  116. numba_cuda/numba/cuda/tests/cudapy/test_constmem.py +1 -1
  117. numba_cuda/numba/cuda/tests/cudapy/test_cooperative_groups.py +2 -3
  118. numba_cuda/numba/cuda/tests/cudapy/test_copy_propagate.py +130 -0
  119. numba_cuda/numba/cuda/tests/cudapy/test_datetime.py +1 -1
  120. numba_cuda/numba/cuda/tests/cudapy/test_debug.py +1 -1
  121. numba_cuda/numba/cuda/tests/cudapy/test_debuginfo.py +293 -4
  122. numba_cuda/numba/cuda/tests/cudapy/test_debuginfo_types.py +1 -1
  123. numba_cuda/numba/cuda/tests/cudapy/test_dispatcher.py +1 -1
  124. numba_cuda/numba/cuda/tests/cudapy/test_errors.py +1 -1
  125. numba_cuda/numba/cuda/tests/cudapy/test_exception.py +1 -1
  126. numba_cuda/numba/cuda/tests/cudapy/test_extending.py +2 -1
  127. numba_cuda/numba/cuda/tests/cudapy/test_inline.py +18 -8
  128. numba_cuda/numba/cuda/tests/cudapy/test_ir_utils.py +10 -37
  129. numba_cuda/numba/cuda/tests/cudapy/test_laplace.py +1 -1
  130. numba_cuda/numba/cuda/tests/cudapy/test_math.py +1 -1
  131. numba_cuda/numba/cuda/tests/cudapy/test_matmul.py +1 -1
  132. numba_cuda/numba/cuda/tests/cudapy/test_operator.py +1 -1
  133. numba_cuda/numba/cuda/tests/cudapy/test_print.py +20 -0
  134. numba_cuda/numba/cuda/tests/cudapy/test_record_dtype.py +1 -1
  135. numba_cuda/numba/cuda/tests/cudapy/test_reduction.py +1 -1
  136. numba_cuda/numba/cuda/tests/cudapy/test_serialize.py +1 -1
  137. numba_cuda/numba/cuda/tests/cudapy/test_sm.py +1 -1
  138. numba_cuda/numba/cuda/tests/cudapy/test_ssa.py +453 -0
  139. numba_cuda/numba/cuda/tests/cudapy/test_sync.py +1 -1
  140. numba_cuda/numba/cuda/tests/cudapy/test_typeinfer.py +538 -0
  141. numba_cuda/numba/cuda/tests/cudapy/test_ufuncs.py +263 -2
  142. numba_cuda/numba/cuda/tests/cudapy/test_userexc.py +1 -1
  143. numba_cuda/numba/cuda/tests/cudapy/test_vector_type.py +1 -1
  144. numba_cuda/numba/cuda/tests/cudapy/test_vectorize_decor.py +112 -6
  145. numba_cuda/numba/cuda/tests/cudapy/test_warning.py +1 -1
  146. numba_cuda/numba/cuda/tests/cudapy/test_warp_ops.py +1 -1
  147. numba_cuda/numba/cuda/tests/doc_examples/test_cg.py +0 -2
  148. numba_cuda/numba/cuda/tests/doc_examples/test_ffi.py +3 -2
  149. numba_cuda/numba/cuda/tests/doc_examples/test_laplace.py +0 -2
  150. numba_cuda/numba/cuda/tests/doc_examples/test_sessionize.py +0 -2
  151. numba_cuda/numba/cuda/tests/nocuda/test_import.py +3 -1
  152. numba_cuda/numba/cuda/tests/nocuda/test_library_lookup.py +24 -12
  153. numba_cuda/numba/cuda/tests/nrt/test_nrt.py +2 -1
  154. numba_cuda/numba/cuda/tests/support.py +55 -15
  155. numba_cuda/numba/cuda/tests/test_tracing.py +200 -0
  156. numba_cuda/numba/cuda/types.py +56 -0
  157. numba_cuda/numba/cuda/typing/__init__.py +9 -1
  158. numba_cuda/numba/cuda/typing/cffi_utils.py +55 -0
  159. numba_cuda/numba/cuda/typing/context.py +751 -0
  160. numba_cuda/numba/cuda/typing/enumdecl.py +74 -0
  161. numba_cuda/numba/cuda/typing/npydecl.py +658 -0
  162. numba_cuda/numba/cuda/typing/templates.py +7 -6
  163. numba_cuda/numba/cuda/ufuncs.py +3 -3
  164. numba_cuda/numba/cuda/utils.py +6 -112
  165. {numba_cuda-0.19.1.dist-info → numba_cuda-0.20.0.dist-info}/METADATA +2 -1
  166. {numba_cuda-0.19.1.dist-info → numba_cuda-0.20.0.dist-info}/RECORD +170 -115
  167. numba_cuda/numba/cuda/tests/cudadrv/test_mvc.py +0 -60
  168. {numba_cuda-0.19.1.dist-info → numba_cuda-0.20.0.dist-info}/WHEEL +0 -0
  169. {numba_cuda-0.19.1.dist-info → numba_cuda-0.20.0.dist-info}/licenses/LICENSE +0 -0
  170. {numba_cuda-0.19.1.dist-info → numba_cuda-0.20.0.dist-info}/licenses/LICENSE.numba +0 -0
  171. {numba_cuda-0.19.1.dist-info → numba_cuda-0.20.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1868 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: BSD-2-Clause
3
+
4
+ from collections import namedtuple
5
+ import contextlib
6
+ import hashlib
7
+ import sys
8
+
9
+ from llvmlite import ir
10
+ from llvmlite.ir import Constant
11
+
12
+ import ctypes
13
+ from numba import _helperlib
14
+ from numba.core import (
15
+ errors,
16
+ types,
17
+ config,
18
+ lowering,
19
+ cgutils,
20
+ imputils,
21
+ serialize,
22
+ )
23
+ from numba.core.utils import PYVERSION
24
+
25
+ PY_UNICODE_1BYTE_KIND = _helperlib.py_unicode_1byte_kind
26
+ PY_UNICODE_2BYTE_KIND = _helperlib.py_unicode_2byte_kind
27
+ PY_UNICODE_4BYTE_KIND = _helperlib.py_unicode_4byte_kind
28
+ if PYVERSION in ((3, 10), (3, 11)):
29
+ PY_UNICODE_WCHAR_KIND = _helperlib.py_unicode_wchar_kind
30
+
31
+
32
+ class _Registry(object):
33
+ def __init__(self):
34
+ self.functions = {}
35
+
36
+ def register(self, typeclass):
37
+ assert issubclass(typeclass, types.Type)
38
+
39
+ def decorator(func):
40
+ if typeclass in self.functions:
41
+ raise KeyError("duplicate registration for %s" % (typeclass,))
42
+ self.functions[typeclass] = func
43
+ return func
44
+
45
+ return decorator
46
+
47
+ def lookup(self, typeclass, default=None):
48
+ assert issubclass(typeclass, types.Type)
49
+ for cls in typeclass.__mro__:
50
+ func = self.functions.get(cls)
51
+ if func is not None:
52
+ return func
53
+ return default
54
+
55
+
56
+ # Registries of boxing / unboxing implementations
57
+ _boxers = _Registry()
58
+ _unboxers = _Registry()
59
+ _reflectors = _Registry()
60
+
61
+ box = _boxers.register
62
+ unbox = _unboxers.register
63
+ reflect = _reflectors.register
64
+
65
+
66
+ class _BoxContext(
67
+ namedtuple("_BoxContext", ("context", "builder", "pyapi", "env_manager"))
68
+ ):
69
+ """
70
+ The facilities required by boxing implementations.
71
+ """
72
+
73
+ __slots__ = ()
74
+
75
+ def box(self, typ, val):
76
+ return self.pyapi.from_native_value(typ, val, self.env_manager)
77
+
78
+
79
+ class _UnboxContext(
80
+ namedtuple("_UnboxContext", ("context", "builder", "pyapi"))
81
+ ):
82
+ """
83
+ The facilities required by unboxing implementations.
84
+ """
85
+
86
+ __slots__ = ()
87
+
88
+ def unbox(self, typ, obj):
89
+ return self.pyapi.to_native_value(typ, obj)
90
+
91
+
92
+ class _ReflectContext(
93
+ namedtuple(
94
+ "_ReflectContext",
95
+ ("context", "builder", "pyapi", "env_manager", "is_error"),
96
+ )
97
+ ):
98
+ """
99
+ The facilities required by reflection implementations.
100
+ """
101
+
102
+ __slots__ = ()
103
+
104
+ # XXX the error bit is currently unused by consumers (e.g. PyCallWrapper)
105
+ def set_error(self):
106
+ self.builder.store(self.is_error, cgutils.true_bit)
107
+
108
+ def box(self, typ, val):
109
+ return self.pyapi.from_native_value(typ, val, self.env_manager)
110
+
111
+ def reflect(self, typ, val):
112
+ return self.pyapi.reflect_native_value(typ, val, self.env_manager)
113
+
114
+
115
+ class NativeValue(object):
116
+ """
117
+ Encapsulate the result of converting a Python object to a native value,
118
+ recording whether the conversion was successful and how to cleanup.
119
+ """
120
+
121
+ def __init__(self, value, is_error=None, cleanup=None):
122
+ self.value = value
123
+ self.is_error = is_error if is_error is not None else cgutils.false_bit
124
+ self.cleanup = cleanup
125
+
126
+
127
+ class EnvironmentManager(object):
128
+ def __init__(self, pyapi, env, env_body, env_ptr):
129
+ assert isinstance(env, lowering.Environment)
130
+ self.pyapi = pyapi
131
+ self.env = env
132
+ self.env_body = env_body
133
+ self.env_ptr = env_ptr
134
+
135
+ def add_const(self, const):
136
+ """
137
+ Add a constant to the environment, return its index.
138
+ """
139
+ # All constants are frozen inside the environment
140
+ if isinstance(const, str):
141
+ const = sys.intern(const)
142
+ for index, val in enumerate(self.env.consts):
143
+ if val is const:
144
+ break
145
+ else:
146
+ index = len(self.env.consts)
147
+ self.env.consts.append(const)
148
+ return index
149
+
150
+ def read_const(self, index):
151
+ """
152
+ Look up constant number *index* inside the environment body.
153
+ A borrowed reference is returned.
154
+
155
+ The returned LLVM value may have NULL value at runtime which indicates
156
+ an error at runtime.
157
+ """
158
+ assert index < len(self.env.consts)
159
+
160
+ builder = self.pyapi.builder
161
+ consts = self.env_body.consts
162
+ ret = cgutils.alloca_once(builder, self.pyapi.pyobj, zfill=True)
163
+ with builder.if_else(cgutils.is_not_null(builder, consts)) as (
164
+ br_not_null,
165
+ br_null,
166
+ ):
167
+ with br_not_null:
168
+ getitem = self.pyapi.list_getitem(consts, index)
169
+ builder.store(getitem, ret)
170
+ with br_null:
171
+ # This can happen when the Environment is accidentally released
172
+ # and has subsequently been garbage collected.
173
+ self.pyapi.err_set_string(
174
+ "PyExc_RuntimeError",
175
+ "`env.consts` is NULL in `read_const`",
176
+ )
177
+ return builder.load(ret)
178
+
179
+
180
+ _IteratorLoop = namedtuple("_IteratorLoop", ("value", "do_break"))
181
+
182
+
183
+ class PythonAPI(object):
184
+ """
185
+ Code generation facilities to call into the CPython C API (and related
186
+ helpers).
187
+ """
188
+
189
+ def __init__(self, context, builder):
190
+ """
191
+ Note: Maybe called multiple times when lowering a function
192
+ """
193
+ self.context = context
194
+ self.builder = builder
195
+
196
+ self.module = builder.basic_block.function.module
197
+ # A unique mapping of serialized objects in this module
198
+ try:
199
+ self.module.__serialized
200
+ except AttributeError:
201
+ self.module.__serialized = {}
202
+
203
+ # Initialize types
204
+ self.pyobj = self.context.get_argument_type(types.pyobject)
205
+ self.pyobjptr = self.pyobj.as_pointer()
206
+ self.voidptr = ir.PointerType(ir.IntType(8))
207
+ self.long = ir.IntType(ctypes.sizeof(ctypes.c_long) * 8)
208
+ self.ulong = self.long
209
+ self.longlong = ir.IntType(ctypes.sizeof(ctypes.c_ulonglong) * 8)
210
+ self.ulonglong = self.longlong
211
+ self.double = ir.DoubleType()
212
+ if config.USE_LEGACY_TYPE_SYSTEM:
213
+ self.py_ssize_t = self.context.get_value_type(types.intp)
214
+ else:
215
+ self.py_ssize_t = self.context.get_value_type(types.c_intp)
216
+ self.cstring = ir.PointerType(ir.IntType(8))
217
+ self.gil_state = ir.IntType(_helperlib.py_gil_state_size * 8)
218
+ self.py_buffer_t = ir.ArrayType(
219
+ ir.IntType(8), _helperlib.py_buffer_size
220
+ )
221
+ self.py_hash_t = self.py_ssize_t
222
+ self.py_unicode_1byte_kind = _helperlib.py_unicode_1byte_kind
223
+ self.py_unicode_2byte_kind = _helperlib.py_unicode_2byte_kind
224
+ self.py_unicode_4byte_kind = _helperlib.py_unicode_4byte_kind
225
+
226
+ def get_env_manager(self, env, env_body, env_ptr):
227
+ return EnvironmentManager(self, env, env_body, env_ptr)
228
+
229
+ def emit_environment_sentry(
230
+ self, envptr, return_pyobject=False, debug_msg=""
231
+ ):
232
+ """Emits LLVM code to ensure the `envptr` is not NULL"""
233
+ is_null = cgutils.is_null(self.builder, envptr)
234
+ with cgutils.if_unlikely(self.builder, is_null):
235
+ if return_pyobject:
236
+ fnty = self.builder.function.type.pointee
237
+ assert fnty.return_type == self.pyobj
238
+ self.err_set_string(
239
+ "PyExc_RuntimeError",
240
+ f"missing Environment: {debug_msg}",
241
+ )
242
+ self.builder.ret(self.get_null_object())
243
+ else:
244
+ self.context.call_conv.return_user_exc(
245
+ self.builder,
246
+ RuntimeError,
247
+ (f"missing Environment: {debug_msg}",),
248
+ )
249
+
250
+ # ------ Python API -----
251
+
252
+ #
253
+ # Basic object API
254
+ #
255
+
256
+ def incref(self, obj):
257
+ fnty = ir.FunctionType(ir.VoidType(), [self.pyobj])
258
+ fn = self._get_function(fnty, name="Py_IncRef")
259
+ self.builder.call(fn, [obj])
260
+
261
+ def decref(self, obj):
262
+ fnty = ir.FunctionType(ir.VoidType(), [self.pyobj])
263
+ fn = self._get_function(fnty, name="Py_DecRef")
264
+ self.builder.call(fn, [obj])
265
+
266
+ def get_type(self, obj):
267
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj])
268
+ fn = self._get_function(fnty, name="numba_py_type")
269
+ return self.builder.call(fn, [obj])
270
+
271
+ #
272
+ # Argument unpacking
273
+ #
274
+
275
+ def parse_tuple_and_keywords(self, args, kws, fmt, keywords, *objs):
276
+ charptr = ir.PointerType(ir.IntType(8))
277
+ charptrary = ir.PointerType(charptr)
278
+ argtypes = [self.pyobj, self.pyobj, charptr, charptrary]
279
+ fnty = ir.FunctionType(ir.IntType(32), argtypes, var_arg=True)
280
+ fn = self._get_function(fnty, name="PyArg_ParseTupleAndKeywords")
281
+ return self.builder.call(fn, [args, kws, fmt, keywords] + list(objs))
282
+
283
+ def parse_tuple(self, args, fmt, *objs):
284
+ charptr = ir.PointerType(ir.IntType(8))
285
+ argtypes = [self.pyobj, charptr]
286
+ fnty = ir.FunctionType(ir.IntType(32), argtypes, var_arg=True)
287
+ fn = self._get_function(fnty, name="PyArg_ParseTuple")
288
+ return self.builder.call(fn, [args, fmt] + list(objs))
289
+
290
+ def unpack_tuple(self, args, name, n_min, n_max, *objs):
291
+ charptr = ir.PointerType(ir.IntType(8))
292
+ argtypes = [self.pyobj, charptr, self.py_ssize_t, self.py_ssize_t]
293
+ fnty = ir.FunctionType(ir.IntType(32), argtypes, var_arg=True)
294
+ fn = self._get_function(fnty, name="PyArg_UnpackTuple")
295
+ n_min = Constant(self.py_ssize_t, int(n_min))
296
+ n_max = Constant(self.py_ssize_t, int(n_max))
297
+ if isinstance(name, str):
298
+ name = self.context.insert_const_string(self.builder.module, name)
299
+ return self.builder.call(fn, [args, name, n_min, n_max] + list(objs))
300
+
301
+ #
302
+ # Exception and errors
303
+ #
304
+
305
+ def err_occurred(self):
306
+ fnty = ir.FunctionType(self.pyobj, ())
307
+ fn = self._get_function(fnty, name="PyErr_Occurred")
308
+ return self.builder.call(fn, ())
309
+
310
+ def err_clear(self):
311
+ fnty = ir.FunctionType(ir.VoidType(), ())
312
+ fn = self._get_function(fnty, name="PyErr_Clear")
313
+ return self.builder.call(fn, ())
314
+
315
+ def err_set_string(self, exctype, msg):
316
+ fnty = ir.FunctionType(ir.VoidType(), [self.pyobj, self.cstring])
317
+ fn = self._get_function(fnty, name="PyErr_SetString")
318
+ if isinstance(exctype, str):
319
+ exctype = self.get_c_object(exctype)
320
+ if isinstance(msg, str):
321
+ msg = self.context.insert_const_string(self.module, msg)
322
+ return self.builder.call(fn, (exctype, msg))
323
+
324
+ def err_format(self, exctype, msg, *format_args):
325
+ fnty = ir.FunctionType(
326
+ ir.VoidType(), [self.pyobj, self.cstring], var_arg=True
327
+ )
328
+ fn = self._get_function(fnty, name="PyErr_Format")
329
+ if isinstance(exctype, str):
330
+ exctype = self.get_c_object(exctype)
331
+ if isinstance(msg, str):
332
+ msg = self.context.insert_const_string(self.module, msg)
333
+ return self.builder.call(fn, (exctype, msg) + tuple(format_args))
334
+
335
+ def raise_object(self, exc=None):
336
+ """
337
+ Raise an arbitrary exception (type or value or (type, args)
338
+ or None - if reraising). A reference to the argument is consumed.
339
+ """
340
+ fnty = ir.FunctionType(ir.VoidType(), [self.pyobj])
341
+ fn = self._get_function(fnty, name="numba_do_raise")
342
+ if exc is None:
343
+ exc = self.make_none()
344
+ return self.builder.call(fn, (exc,))
345
+
346
+ def err_set_object(self, exctype, excval):
347
+ fnty = ir.FunctionType(ir.VoidType(), [self.pyobj, self.pyobj])
348
+ fn = self._get_function(fnty, name="PyErr_SetObject")
349
+ if isinstance(exctype, str):
350
+ exctype = self.get_c_object(exctype)
351
+ return self.builder.call(fn, (exctype, excval))
352
+
353
+ def err_set_none(self, exctype):
354
+ fnty = ir.FunctionType(ir.VoidType(), [self.pyobj])
355
+ fn = self._get_function(fnty, name="PyErr_SetNone")
356
+ if isinstance(exctype, str):
357
+ exctype = self.get_c_object(exctype)
358
+ return self.builder.call(fn, (exctype,))
359
+
360
+ def err_write_unraisable(self, obj):
361
+ fnty = ir.FunctionType(ir.VoidType(), [self.pyobj])
362
+ fn = self._get_function(fnty, name="PyErr_WriteUnraisable")
363
+ return self.builder.call(fn, (obj,))
364
+
365
+ def err_fetch(self, pty, pval, ptb):
366
+ fnty = ir.FunctionType(ir.VoidType(), [self.pyobjptr] * 3)
367
+ fn = self._get_function(fnty, name="PyErr_Fetch")
368
+ return self.builder.call(fn, (pty, pval, ptb))
369
+
370
+ def err_restore(self, ty, val, tb):
371
+ fnty = ir.FunctionType(ir.VoidType(), [self.pyobj] * 3)
372
+ fn = self._get_function(fnty, name="PyErr_Restore")
373
+ return self.builder.call(fn, (ty, val, tb))
374
+
375
+ @contextlib.contextmanager
376
+ def err_push(self, keep_new=False):
377
+ """
378
+ Temporarily push the current error indicator while the code
379
+ block is executed. If *keep_new* is True and the code block
380
+ raises a new error, the new error is kept, otherwise the old
381
+ error indicator is restored at the end of the block.
382
+ """
383
+ pty, pval, ptb = [
384
+ cgutils.alloca_once(self.builder, self.pyobj) for i in range(3)
385
+ ]
386
+ self.err_fetch(pty, pval, ptb)
387
+ yield
388
+ ty = self.builder.load(pty)
389
+ val = self.builder.load(pval)
390
+ tb = self.builder.load(ptb)
391
+ if keep_new:
392
+ new_error = cgutils.is_not_null(self.builder, self.err_occurred())
393
+ with self.builder.if_else(new_error, likely=False) as (
394
+ if_error,
395
+ if_ok,
396
+ ):
397
+ with if_error:
398
+ # Code block raised an error, keep it
399
+ self.decref(ty)
400
+ self.decref(val)
401
+ self.decref(tb)
402
+ with if_ok:
403
+ # Restore previous error
404
+ self.err_restore(ty, val, tb)
405
+ else:
406
+ self.err_restore(ty, val, tb)
407
+
408
+ def get_c_object(self, name):
409
+ """
410
+ Get a Python object through its C-accessible *name*
411
+ (e.g. "PyExc_ValueError"). The underlying variable must be
412
+ a `PyObject *`, and the value of that pointer is returned.
413
+ """
414
+ # A LLVM global variable is implicitly a pointer to the declared
415
+ # type, so fix up by using pyobj.pointee.
416
+ return self.context.get_c_value(
417
+ self.builder, self.pyobj.pointee, name, dllimport=True
418
+ )
419
+
420
+ def raise_missing_global_error(self, name):
421
+ msg = "global name '%s' is not defined" % name
422
+ cstr = self.context.insert_const_string(self.module, msg)
423
+ self.err_set_string("PyExc_NameError", cstr)
424
+
425
+ def raise_missing_name_error(self, name):
426
+ msg = "name '%s' is not defined" % name
427
+ cstr = self.context.insert_const_string(self.module, msg)
428
+ self.err_set_string("PyExc_NameError", cstr)
429
+
430
+ def fatal_error(self, msg):
431
+ fnty = ir.FunctionType(ir.VoidType(), [self.cstring])
432
+ fn = self._get_function(fnty, name="Py_FatalError")
433
+ fn.attributes.add("noreturn")
434
+ cstr = self.context.insert_const_string(self.module, msg)
435
+ self.builder.call(fn, (cstr,))
436
+
437
+ #
438
+ # Concrete dict API
439
+ #
440
+
441
+ def dict_getitem_string(self, dic, name):
442
+ """Lookup name inside dict
443
+
444
+ Returns a borrowed reference
445
+ """
446
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.cstring])
447
+ fn = self._get_function(fnty, name="PyDict_GetItemString")
448
+ cstr = self.context.insert_const_string(self.module, name)
449
+ return self.builder.call(fn, [dic, cstr])
450
+
451
+ def dict_getitem(self, dic, name):
452
+ """Lookup name inside dict
453
+
454
+ Returns a borrowed reference
455
+ """
456
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.pyobj])
457
+ fn = self._get_function(fnty, name="PyDict_GetItem")
458
+ return self.builder.call(fn, [dic, name])
459
+
460
+ def dict_new(self, presize=0):
461
+ if presize == 0:
462
+ fnty = ir.FunctionType(self.pyobj, ())
463
+ fn = self._get_function(fnty, name="PyDict_New")
464
+ return self.builder.call(fn, ())
465
+ else:
466
+ fnty = ir.FunctionType(self.pyobj, [self.py_ssize_t])
467
+ fn = self._get_function(fnty, name="_PyDict_NewPresized")
468
+ return self.builder.call(
469
+ fn, [Constant(self.py_ssize_t, int(presize))]
470
+ )
471
+
472
+ def dict_setitem(self, dictobj, nameobj, valobj):
473
+ fnty = ir.FunctionType(
474
+ ir.IntType(32), (self.pyobj, self.pyobj, self.pyobj)
475
+ )
476
+ fn = self._get_function(fnty, name="PyDict_SetItem")
477
+ return self.builder.call(fn, (dictobj, nameobj, valobj))
478
+
479
+ def dict_setitem_string(self, dictobj, name, valobj):
480
+ fnty = ir.FunctionType(
481
+ ir.IntType(32), (self.pyobj, self.cstring, self.pyobj)
482
+ )
483
+ fn = self._get_function(fnty, name="PyDict_SetItemString")
484
+ cstr = self.context.insert_const_string(self.module, name)
485
+ return self.builder.call(fn, (dictobj, cstr, valobj))
486
+
487
+ def dict_pack(self, keyvalues):
488
+ """
489
+ Args
490
+ -----
491
+ keyvalues: iterable of (str, llvm.Value of PyObject*)
492
+ """
493
+ dictobj = self.dict_new()
494
+ with self.if_object_ok(dictobj):
495
+ for k, v in keyvalues:
496
+ self.dict_setitem_string(dictobj, k, v)
497
+ return dictobj
498
+
499
+ #
500
+ # Concrete number APIs
501
+ #
502
+
503
+ def float_from_double(self, fval):
504
+ fnty = ir.FunctionType(self.pyobj, [self.double])
505
+ fn = self._get_function(fnty, name="PyFloat_FromDouble")
506
+ return self.builder.call(fn, [fval])
507
+
508
+ def number_as_ssize_t(self, numobj):
509
+ fnty = ir.FunctionType(self.py_ssize_t, [self.pyobj, self.pyobj])
510
+ fn = self._get_function(fnty, name="PyNumber_AsSsize_t")
511
+ # We don't want any clipping, so pass OverflowError as the 2nd arg
512
+ exc_class = self.get_c_object("PyExc_OverflowError")
513
+ return self.builder.call(fn, [numobj, exc_class])
514
+
515
+ def number_long(self, numobj):
516
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj])
517
+ fn = self._get_function(fnty, name="PyNumber_Long")
518
+ return self.builder.call(fn, [numobj])
519
+
520
+ def long_as_ulonglong(self, numobj):
521
+ fnty = ir.FunctionType(self.ulonglong, [self.pyobj])
522
+ fn = self._get_function(fnty, name="PyLong_AsUnsignedLongLong")
523
+ return self.builder.call(fn, [numobj])
524
+
525
+ def long_as_longlong(self, numobj):
526
+ fnty = ir.FunctionType(self.ulonglong, [self.pyobj])
527
+ fn = self._get_function(fnty, name="PyLong_AsLongLong")
528
+ return self.builder.call(fn, [numobj])
529
+
530
+ def long_as_voidptr(self, numobj):
531
+ """
532
+ Convert the given Python integer to a void*. This is recommended
533
+ over number_as_ssize_t as it isn't affected by signedness.
534
+ """
535
+ fnty = ir.FunctionType(self.voidptr, [self.pyobj])
536
+ fn = self._get_function(fnty, name="PyLong_AsVoidPtr")
537
+ return self.builder.call(fn, [numobj])
538
+
539
+ def _long_from_native_int(self, ival, func_name, native_int_type, signed):
540
+ fnty = ir.FunctionType(self.pyobj, [native_int_type])
541
+ fn = self._get_function(fnty, name=func_name)
542
+ resptr = cgutils.alloca_once(self.builder, self.pyobj)
543
+ fn = self._get_function(fnty, name=func_name)
544
+ self.builder.store(self.builder.call(fn, [ival]), resptr)
545
+
546
+ return self.builder.load(resptr)
547
+
548
+ def long_from_long(self, ival):
549
+ func_name = "PyLong_FromLong"
550
+ fnty = ir.FunctionType(self.pyobj, [self.long])
551
+ fn = self._get_function(fnty, name=func_name)
552
+ return self.builder.call(fn, [ival])
553
+
554
+ def long_from_ulong(self, ival):
555
+ return self._long_from_native_int(
556
+ ival, "PyLong_FromUnsignedLong", self.long, signed=False
557
+ )
558
+
559
+ def long_from_ssize_t(self, ival):
560
+ return self._long_from_native_int(
561
+ ival, "PyLong_FromSsize_t", self.py_ssize_t, signed=True
562
+ )
563
+
564
+ def long_from_longlong(self, ival):
565
+ return self._long_from_native_int(
566
+ ival, "PyLong_FromLongLong", self.longlong, signed=True
567
+ )
568
+
569
+ def long_from_ulonglong(self, ival):
570
+ return self._long_from_native_int(
571
+ ival, "PyLong_FromUnsignedLongLong", self.ulonglong, signed=False
572
+ )
573
+
574
+ def long_from_signed_int(self, ival):
575
+ """
576
+ Return a Python integer from any native integer value.
577
+ """
578
+ bits = ival.type.width
579
+ if bits <= self.long.width:
580
+ return self.long_from_long(self.builder.sext(ival, self.long))
581
+ elif bits <= self.longlong.width:
582
+ return self.long_from_longlong(
583
+ self.builder.sext(ival, self.longlong)
584
+ )
585
+ else:
586
+ raise OverflowError("integer too big (%d bits)" % (bits))
587
+
588
+ def long_from_unsigned_int(self, ival):
589
+ """
590
+ Same as long_from_signed_int, but for unsigned values.
591
+ """
592
+ bits = ival.type.width
593
+ if bits <= self.ulong.width:
594
+ return self.long_from_ulong(self.builder.zext(ival, self.ulong))
595
+ elif bits <= self.ulonglong.width:
596
+ return self.long_from_ulonglong(
597
+ self.builder.zext(ival, self.ulonglong)
598
+ )
599
+ else:
600
+ raise OverflowError("integer too big (%d bits)" % (bits))
601
+
602
+ def _get_number_operator(self, name):
603
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.pyobj])
604
+ fn = self._get_function(fnty, name="PyNumber_%s" % name)
605
+ return fn
606
+
607
+ def _call_number_operator(self, name, lhs, rhs, inplace=False):
608
+ if inplace:
609
+ name = "InPlace" + name
610
+ fn = self._get_number_operator(name)
611
+ return self.builder.call(fn, [lhs, rhs])
612
+
613
+ def number_add(self, lhs, rhs, inplace=False):
614
+ return self._call_number_operator("Add", lhs, rhs, inplace=inplace)
615
+
616
+ def number_subtract(self, lhs, rhs, inplace=False):
617
+ return self._call_number_operator("Subtract", lhs, rhs, inplace=inplace)
618
+
619
+ def number_multiply(self, lhs, rhs, inplace=False):
620
+ return self._call_number_operator("Multiply", lhs, rhs, inplace=inplace)
621
+
622
+ def number_truedivide(self, lhs, rhs, inplace=False):
623
+ return self._call_number_operator(
624
+ "TrueDivide", lhs, rhs, inplace=inplace
625
+ )
626
+
627
+ def number_floordivide(self, lhs, rhs, inplace=False):
628
+ return self._call_number_operator(
629
+ "FloorDivide", lhs, rhs, inplace=inplace
630
+ )
631
+
632
+ def number_remainder(self, lhs, rhs, inplace=False):
633
+ return self._call_number_operator(
634
+ "Remainder", lhs, rhs, inplace=inplace
635
+ )
636
+
637
+ def number_matrix_multiply(self, lhs, rhs, inplace=False):
638
+ return self._call_number_operator(
639
+ "MatrixMultiply", lhs, rhs, inplace=inplace
640
+ )
641
+
642
+ def number_lshift(self, lhs, rhs, inplace=False):
643
+ return self._call_number_operator("Lshift", lhs, rhs, inplace=inplace)
644
+
645
+ def number_rshift(self, lhs, rhs, inplace=False):
646
+ return self._call_number_operator("Rshift", lhs, rhs, inplace=inplace)
647
+
648
+ def number_and(self, lhs, rhs, inplace=False):
649
+ return self._call_number_operator("And", lhs, rhs, inplace=inplace)
650
+
651
+ def number_or(self, lhs, rhs, inplace=False):
652
+ return self._call_number_operator("Or", lhs, rhs, inplace=inplace)
653
+
654
+ def number_xor(self, lhs, rhs, inplace=False):
655
+ return self._call_number_operator("Xor", lhs, rhs, inplace=inplace)
656
+
657
+ def number_power(self, lhs, rhs, inplace=False):
658
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj] * 3)
659
+ fname = "PyNumber_InPlacePower" if inplace else "PyNumber_Power"
660
+ fn = self._get_function(fnty, fname)
661
+ return self.builder.call(fn, [lhs, rhs, self.borrow_none()])
662
+
663
+ def number_negative(self, obj):
664
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj])
665
+ fn = self._get_function(fnty, name="PyNumber_Negative")
666
+ return self.builder.call(fn, (obj,))
667
+
668
+ def number_positive(self, obj):
669
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj])
670
+ fn = self._get_function(fnty, name="PyNumber_Positive")
671
+ return self.builder.call(fn, (obj,))
672
+
673
+ def number_float(self, val):
674
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj])
675
+ fn = self._get_function(fnty, name="PyNumber_Float")
676
+ return self.builder.call(fn, [val])
677
+
678
+ def number_invert(self, obj):
679
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj])
680
+ fn = self._get_function(fnty, name="PyNumber_Invert")
681
+ return self.builder.call(fn, (obj,))
682
+
683
+ def float_as_double(self, fobj):
684
+ fnty = ir.FunctionType(self.double, [self.pyobj])
685
+ fn = self._get_function(fnty, name="PyFloat_AsDouble")
686
+ return self.builder.call(fn, [fobj])
687
+
688
+ def bool_from_bool(self, bval):
689
+ """
690
+ Get a Python bool from a LLVM boolean.
691
+ """
692
+ longval = self.builder.zext(bval, self.long)
693
+ return self.bool_from_long(longval)
694
+
695
+ def bool_from_long(self, ival):
696
+ fnty = ir.FunctionType(self.pyobj, [self.long])
697
+ fn = self._get_function(fnty, name="PyBool_FromLong")
698
+ return self.builder.call(fn, [ival])
699
+
700
+ def complex_from_doubles(self, realval, imagval):
701
+ fnty = ir.FunctionType(self.pyobj, [ir.DoubleType(), ir.DoubleType()])
702
+ fn = self._get_function(fnty, name="PyComplex_FromDoubles")
703
+ return self.builder.call(fn, [realval, imagval])
704
+
705
+ def complex_real_as_double(self, cobj):
706
+ fnty = ir.FunctionType(ir.DoubleType(), [self.pyobj])
707
+ fn = self._get_function(fnty, name="PyComplex_RealAsDouble")
708
+ return self.builder.call(fn, [cobj])
709
+
710
+ def complex_imag_as_double(self, cobj):
711
+ fnty = ir.FunctionType(ir.DoubleType(), [self.pyobj])
712
+ fn = self._get_function(fnty, name="PyComplex_ImagAsDouble")
713
+ return self.builder.call(fn, [cobj])
714
+
715
+ #
716
+ # Concrete slice API
717
+ #
718
+ def slice_as_ints(self, obj):
719
+ """
720
+ Read the members of a slice of integers.
721
+
722
+ Returns a (ok, start, stop, step) tuple where ok is a boolean and
723
+ the following members are pointer-sized ints.
724
+ """
725
+ pstart = cgutils.alloca_once(self.builder, self.py_ssize_t)
726
+ pstop = cgutils.alloca_once(self.builder, self.py_ssize_t)
727
+ pstep = cgutils.alloca_once(self.builder, self.py_ssize_t)
728
+ fnty = ir.FunctionType(
729
+ ir.IntType(32), [self.pyobj] + [self.py_ssize_t.as_pointer()] * 3
730
+ )
731
+ fn = self._get_function(fnty, name="numba_unpack_slice")
732
+ res = self.builder.call(fn, (obj, pstart, pstop, pstep))
733
+ start = self.builder.load(pstart)
734
+ stop = self.builder.load(pstop)
735
+ step = self.builder.load(pstep)
736
+ return cgutils.is_null(self.builder, res), start, stop, step
737
+
738
+ #
739
+ # List and sequence APIs
740
+ #
741
+
742
+ def sequence_getslice(self, obj, start, stop):
743
+ fnty = ir.FunctionType(
744
+ self.pyobj, [self.pyobj, self.py_ssize_t, self.py_ssize_t]
745
+ )
746
+ fn = self._get_function(fnty, name="PySequence_GetSlice")
747
+ return self.builder.call(fn, (obj, start, stop))
748
+
749
+ def sequence_tuple(self, obj):
750
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj])
751
+ fn = self._get_function(fnty, name="PySequence_Tuple")
752
+ return self.builder.call(fn, [obj])
753
+
754
+ def sequence_concat(self, obj1, obj2):
755
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.pyobj])
756
+ fn = self._get_function(fnty, name="PySequence_Concat")
757
+ return self.builder.call(fn, [obj1, obj2])
758
+
759
+ def list_new(self, szval):
760
+ fnty = ir.FunctionType(self.pyobj, [self.py_ssize_t])
761
+ fn = self._get_function(fnty, name="PyList_New")
762
+ return self.builder.call(fn, [szval])
763
+
764
+ def list_size(self, lst):
765
+ fnty = ir.FunctionType(self.py_ssize_t, [self.pyobj])
766
+ fn = self._get_function(fnty, name="PyList_Size")
767
+ return self.builder.call(fn, [lst])
768
+
769
+ def list_append(self, lst, val):
770
+ fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, self.pyobj])
771
+ fn = self._get_function(fnty, name="PyList_Append")
772
+ return self.builder.call(fn, [lst, val])
773
+
774
+ def list_setitem(self, lst, idx, val):
775
+ """
776
+ Warning: Steals reference to ``val``
777
+ """
778
+ fnty = ir.FunctionType(
779
+ ir.IntType(32), [self.pyobj, self.py_ssize_t, self.pyobj]
780
+ )
781
+ fn = self._get_function(fnty, name="PyList_SetItem")
782
+ return self.builder.call(fn, [lst, idx, val])
783
+
784
+ def list_getitem(self, lst, idx):
785
+ """
786
+ Returns a borrowed reference.
787
+ """
788
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.py_ssize_t])
789
+ fn = self._get_function(fnty, name="PyList_GetItem")
790
+ if isinstance(idx, int):
791
+ idx = self.context.get_constant(types.intp, idx)
792
+ return self.builder.call(fn, [lst, idx])
793
+
794
+ def list_setslice(self, lst, start, stop, obj):
795
+ if obj is None:
796
+ obj = self.get_null_object()
797
+ fnty = ir.FunctionType(
798
+ ir.IntType(32),
799
+ [self.pyobj, self.py_ssize_t, self.py_ssize_t, self.pyobj],
800
+ )
801
+ fn = self._get_function(fnty, name="PyList_SetSlice")
802
+ return self.builder.call(fn, (lst, start, stop, obj))
803
+
804
+ #
805
+ # Concrete tuple API
806
+ #
807
+
808
+ def tuple_getitem(self, tup, idx):
809
+ """
810
+ Borrow reference
811
+ """
812
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.py_ssize_t])
813
+ fn = self._get_function(fnty, name="PyTuple_GetItem")
814
+ idx = self.context.get_constant(types.intp, idx)
815
+ return self.builder.call(fn, [tup, idx])
816
+
817
+ def tuple_pack(self, items):
818
+ fnty = ir.FunctionType(self.pyobj, [self.py_ssize_t], var_arg=True)
819
+ fn = self._get_function(fnty, name="PyTuple_Pack")
820
+ n = self.context.get_constant(types.intp, len(items))
821
+ args = [n]
822
+ args.extend(items)
823
+ return self.builder.call(fn, args)
824
+
825
+ def tuple_size(self, tup):
826
+ fnty = ir.FunctionType(self.py_ssize_t, [self.pyobj])
827
+ fn = self._get_function(fnty, name="PyTuple_Size")
828
+ return self.builder.call(fn, [tup])
829
+
830
+ def tuple_new(self, count):
831
+ fnty = ir.FunctionType(self.pyobj, [self.py_ssize_t])
832
+ fn = self._get_function(fnty, name="PyTuple_New")
833
+ return self.builder.call(fn, [self.py_ssize_t(count)])
834
+
835
+ def tuple_setitem(self, tuple_val, index, item):
836
+ """
837
+ Steals a reference to `item`.
838
+ """
839
+ fnty = ir.FunctionType(
840
+ ir.IntType(32), [self.pyobj, self.py_ssize_t, self.pyobj]
841
+ )
842
+ setitem_fn = self._get_function(fnty, name="PyTuple_SetItem")
843
+ index = self.py_ssize_t(index)
844
+ self.builder.call(setitem_fn, [tuple_val, index, item])
845
+
846
+ #
847
+ # Concrete set API
848
+ #
849
+
850
+ def set_new(self, iterable=None):
851
+ if iterable is None:
852
+ iterable = self.get_null_object()
853
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj])
854
+ fn = self._get_function(fnty, name="PySet_New")
855
+ return self.builder.call(fn, [iterable])
856
+
857
+ def set_add(self, set, value):
858
+ fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, self.pyobj])
859
+ fn = self._get_function(fnty, name="PySet_Add")
860
+ return self.builder.call(fn, [set, value])
861
+
862
+ def set_clear(self, set):
863
+ fnty = ir.FunctionType(ir.IntType(32), [self.pyobj])
864
+ fn = self._get_function(fnty, name="PySet_Clear")
865
+ return self.builder.call(fn, [set])
866
+
867
+ def set_size(self, set):
868
+ fnty = ir.FunctionType(self.py_ssize_t, [self.pyobj])
869
+ fn = self._get_function(fnty, name="PySet_Size")
870
+ return self.builder.call(fn, [set])
871
+
872
+ def set_update(self, set, iterable):
873
+ fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, self.pyobj])
874
+ fn = self._get_function(fnty, name="_PySet_Update")
875
+ return self.builder.call(fn, [set, iterable])
876
+
877
+ def set_next_entry(self, set, posptr, keyptr, hashptr):
878
+ fnty = ir.FunctionType(
879
+ ir.IntType(32),
880
+ [
881
+ self.pyobj,
882
+ self.py_ssize_t.as_pointer(),
883
+ self.pyobj.as_pointer(),
884
+ self.py_hash_t.as_pointer(),
885
+ ],
886
+ )
887
+ fn = self._get_function(fnty, name="_PySet_NextEntry")
888
+ return self.builder.call(fn, (set, posptr, keyptr, hashptr))
889
+
890
+ @contextlib.contextmanager
891
+ def set_iterate(self, set):
892
+ builder = self.builder
893
+
894
+ hashptr = cgutils.alloca_once(builder, self.py_hash_t, name="hashptr")
895
+ keyptr = cgutils.alloca_once(builder, self.pyobj, name="keyptr")
896
+ posptr = cgutils.alloca_once_value(
897
+ builder, Constant(self.py_ssize_t, 0), name="posptr"
898
+ )
899
+
900
+ bb_body = builder.append_basic_block("bb_body")
901
+ bb_end = builder.append_basic_block("bb_end")
902
+
903
+ builder.branch(bb_body)
904
+
905
+ def do_break():
906
+ builder.branch(bb_end)
907
+
908
+ with builder.goto_block(bb_body):
909
+ r = self.set_next_entry(set, posptr, keyptr, hashptr)
910
+ finished = cgutils.is_null(builder, r)
911
+ with builder.if_then(finished, likely=False):
912
+ builder.branch(bb_end)
913
+ yield _IteratorLoop(builder.load(keyptr), do_break)
914
+ builder.branch(bb_body)
915
+
916
+ builder.position_at_end(bb_end)
917
+
918
+ #
919
+ # GIL APIs
920
+ #
921
+
922
+ def gil_ensure(self):
923
+ """
924
+ Ensure the GIL is acquired.
925
+ The returned value must be consumed by gil_release().
926
+ """
927
+ gilptrty = ir.PointerType(self.gil_state)
928
+ fnty = ir.FunctionType(ir.VoidType(), [gilptrty])
929
+ fn = self._get_function(fnty, "numba_gil_ensure")
930
+ gilptr = cgutils.alloca_once(self.builder, self.gil_state)
931
+ self.builder.call(fn, [gilptr])
932
+ return gilptr
933
+
934
+ def gil_release(self, gil):
935
+ """
936
+ Release the acquired GIL by gil_ensure().
937
+ Must be paired with a gil_ensure().
938
+ """
939
+ gilptrty = ir.PointerType(self.gil_state)
940
+ fnty = ir.FunctionType(ir.VoidType(), [gilptrty])
941
+ fn = self._get_function(fnty, "numba_gil_release")
942
+ return self.builder.call(fn, [gil])
943
+
944
+ def save_thread(self):
945
+ """
946
+ Release the GIL and return the former thread state
947
+ (an opaque non-NULL pointer).
948
+ """
949
+ fnty = ir.FunctionType(self.voidptr, [])
950
+ fn = self._get_function(fnty, name="PyEval_SaveThread")
951
+ return self.builder.call(fn, [])
952
+
953
+ def restore_thread(self, thread_state):
954
+ """
955
+ Restore the given thread state by reacquiring the GIL.
956
+ """
957
+ fnty = ir.FunctionType(ir.VoidType(), [self.voidptr])
958
+ fn = self._get_function(fnty, name="PyEval_RestoreThread")
959
+ self.builder.call(fn, [thread_state])
960
+
961
+ #
962
+ # Generic object private data (a way of associating an arbitrary void *
963
+ # pointer to an arbitrary Python object).
964
+ #
965
+
966
+ def object_get_private_data(self, obj):
967
+ fnty = ir.FunctionType(self.voidptr, [self.pyobj])
968
+ fn = self._get_function(fnty, name="numba_get_pyobject_private_data")
969
+ return self.builder.call(fn, (obj,))
970
+
971
+ def object_set_private_data(self, obj, ptr):
972
+ fnty = ir.FunctionType(ir.VoidType(), [self.pyobj, self.voidptr])
973
+ fn = self._get_function(fnty, name="numba_set_pyobject_private_data")
974
+ return self.builder.call(fn, (obj, ptr))
975
+
976
+ def object_reset_private_data(self, obj):
977
+ fnty = ir.FunctionType(ir.VoidType(), [self.pyobj])
978
+ fn = self._get_function(fnty, name="numba_reset_pyobject_private_data")
979
+ return self.builder.call(fn, (obj,))
980
+
981
+ #
982
+ # Other APIs (organize them better!)
983
+ #
984
+
985
+ def import_module(self, modname):
986
+ fnty = ir.FunctionType(self.pyobj, [self.cstring])
987
+ fn = self._get_function(fnty, name="PyImport_ImportModule")
988
+ return self.builder.call(fn, [modname])
989
+
990
+ def call_function_objargs(self, callee, objargs):
991
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj], var_arg=True)
992
+ fn = self._get_function(fnty, name="PyObject_CallFunctionObjArgs")
993
+ args = [callee] + list(objargs)
994
+ args.append(self.context.get_constant_null(types.pyobject))
995
+ return self.builder.call(fn, args)
996
+
997
+ def call_method(self, callee, method, objargs=()):
998
+ cname = self.context.insert_const_string(self.module, method)
999
+ fnty = ir.FunctionType(
1000
+ self.pyobj, [self.pyobj, self.cstring, self.cstring], var_arg=True
1001
+ )
1002
+ fn = self._get_function(fnty, name="PyObject_CallMethod")
1003
+ fmt = "O" * len(objargs)
1004
+ cfmt = self.context.insert_const_string(self.module, fmt)
1005
+ args = [callee, cname, cfmt]
1006
+ if objargs:
1007
+ args.extend(objargs)
1008
+ args.append(self.context.get_constant_null(types.pyobject))
1009
+ return self.builder.call(fn, args)
1010
+
1011
+ def call(self, callee, args=None, kws=None):
1012
+ if args_was_none := args is None:
1013
+ args = self.tuple_new(0)
1014
+ if kws is None:
1015
+ kws = self.get_null_object()
1016
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj] * 3)
1017
+ fn = self._get_function(fnty, name="PyObject_Call")
1018
+ result = self.builder.call(fn, (callee, args, kws))
1019
+ if args_was_none:
1020
+ self.decref(args)
1021
+ return result
1022
+
1023
+ def object_type(self, obj):
1024
+ """Emit a call to ``PyObject_Type(obj)`` to get the type of ``obj``."""
1025
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj])
1026
+ fn = self._get_function(fnty, name="PyObject_Type")
1027
+ return self.builder.call(fn, (obj,))
1028
+
1029
+ def object_istrue(self, obj):
1030
+ fnty = ir.FunctionType(ir.IntType(32), [self.pyobj])
1031
+ fn = self._get_function(fnty, name="PyObject_IsTrue")
1032
+ return self.builder.call(fn, [obj])
1033
+
1034
+ def object_not(self, obj):
1035
+ fnty = ir.FunctionType(ir.IntType(32), [self.pyobj])
1036
+ fn = self._get_function(fnty, name="PyObject_Not")
1037
+ return self.builder.call(fn, [obj])
1038
+
1039
+ def object_richcompare(self, lhs, rhs, opstr):
1040
+ """
1041
+ Refer to Python source Include/object.h for macros definition
1042
+ of the opid.
1043
+ """
1044
+ ops = ["<", "<=", "==", "!=", ">", ">="]
1045
+ if opstr in ops:
1046
+ opid = ops.index(opstr)
1047
+ fnty = ir.FunctionType(
1048
+ self.pyobj, [self.pyobj, self.pyobj, ir.IntType(32)]
1049
+ )
1050
+ fn = self._get_function(fnty, name="PyObject_RichCompare")
1051
+ lopid = self.context.get_constant(types.int32, opid)
1052
+ return self.builder.call(fn, (lhs, rhs, lopid))
1053
+ elif opstr == "is":
1054
+ bitflag = self.builder.icmp_unsigned("==", lhs, rhs)
1055
+ return self.bool_from_bool(bitflag)
1056
+ elif opstr == "is not":
1057
+ bitflag = self.builder.icmp_unsigned("!=", lhs, rhs)
1058
+ return self.bool_from_bool(bitflag)
1059
+ elif opstr in ("in", "not in"):
1060
+ fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, self.pyobj])
1061
+ fn = self._get_function(fnty, name="PySequence_Contains")
1062
+ status = self.builder.call(fn, (rhs, lhs))
1063
+ negone = self.context.get_constant(types.int32, -1)
1064
+ is_good = self.builder.icmp_unsigned("!=", status, negone)
1065
+ # Stack allocate output and initialize to Null
1066
+ outptr = cgutils.alloca_once_value(
1067
+ self.builder, Constant(self.pyobj, None)
1068
+ )
1069
+ # If PySequence_Contains returns non-error value
1070
+ with cgutils.if_likely(self.builder, is_good):
1071
+ if opstr == "not in":
1072
+ status = self.builder.not_(status)
1073
+ # Store the status as a boolean object
1074
+ truncated = self.builder.trunc(status, ir.IntType(1))
1075
+ self.builder.store(self.bool_from_bool(truncated), outptr)
1076
+
1077
+ return self.builder.load(outptr)
1078
+ else:
1079
+ raise NotImplementedError(
1080
+ "Unknown operator {op!r}".format(op=opstr)
1081
+ )
1082
+
1083
+ def iter_next(self, iterobj):
1084
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj])
1085
+ fn = self._get_function(fnty, name="PyIter_Next")
1086
+ return self.builder.call(fn, [iterobj])
1087
+
1088
+ def object_getiter(self, obj):
1089
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj])
1090
+ fn = self._get_function(fnty, name="PyObject_GetIter")
1091
+ return self.builder.call(fn, [obj])
1092
+
1093
+ def object_getattr_string(self, obj, attr):
1094
+ cstr = self.context.insert_const_string(self.module, attr)
1095
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.cstring])
1096
+ fn = self._get_function(fnty, name="PyObject_GetAttrString")
1097
+ return self.builder.call(fn, [obj, cstr])
1098
+
1099
+ def object_getattr(self, obj, attr):
1100
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.pyobj])
1101
+ fn = self._get_function(fnty, name="PyObject_GetAttr")
1102
+ return self.builder.call(fn, [obj, attr])
1103
+
1104
+ def object_setattr_string(self, obj, attr, val):
1105
+ cstr = self.context.insert_const_string(self.module, attr)
1106
+ fnty = ir.FunctionType(
1107
+ ir.IntType(32), [self.pyobj, self.cstring, self.pyobj]
1108
+ )
1109
+ fn = self._get_function(fnty, name="PyObject_SetAttrString")
1110
+ return self.builder.call(fn, [obj, cstr, val])
1111
+
1112
+ def object_setattr(self, obj, attr, val):
1113
+ fnty = ir.FunctionType(
1114
+ ir.IntType(32), [self.pyobj, self.pyobj, self.pyobj]
1115
+ )
1116
+ fn = self._get_function(fnty, name="PyObject_SetAttr")
1117
+ return self.builder.call(fn, [obj, attr, val])
1118
+
1119
+ def object_delattr_string(self, obj, attr):
1120
+ # PyObject_DelAttrString() is actually a C macro calling
1121
+ # PyObject_SetAttrString() with value == NULL.
1122
+ return self.object_setattr_string(obj, attr, self.get_null_object())
1123
+
1124
+ def object_delattr(self, obj, attr):
1125
+ # PyObject_DelAttr() is actually a C macro calling
1126
+ # PyObject_SetAttr() with value == NULL.
1127
+ return self.object_setattr(obj, attr, self.get_null_object())
1128
+
1129
+ def object_getitem(self, obj, key):
1130
+ """
1131
+ Return obj[key]
1132
+ """
1133
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.pyobj])
1134
+ fn = self._get_function(fnty, name="PyObject_GetItem")
1135
+ return self.builder.call(fn, (obj, key))
1136
+
1137
+ def object_setitem(self, obj, key, val):
1138
+ """
1139
+ obj[key] = val
1140
+ """
1141
+ fnty = ir.FunctionType(
1142
+ ir.IntType(32), [self.pyobj, self.pyobj, self.pyobj]
1143
+ )
1144
+ fn = self._get_function(fnty, name="PyObject_SetItem")
1145
+ return self.builder.call(fn, (obj, key, val))
1146
+
1147
+ def object_delitem(self, obj, key):
1148
+ """
1149
+ del obj[key]
1150
+ """
1151
+ fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, self.pyobj])
1152
+ fn = self._get_function(fnty, name="PyObject_DelItem")
1153
+ return self.builder.call(fn, (obj, key))
1154
+
1155
+ def string_as_string(self, strobj):
1156
+ fnty = ir.FunctionType(self.cstring, [self.pyobj])
1157
+ fname = "PyUnicode_AsUTF8"
1158
+ fn = self._get_function(fnty, name=fname)
1159
+ return self.builder.call(fn, [strobj])
1160
+
1161
+ def string_as_string_and_size(self, strobj):
1162
+ """
1163
+ Returns a tuple of ``(ok, buffer, length)``.
1164
+ The ``ok`` is i1 value that is set if ok.
1165
+ The ``buffer`` is a i8* of the output buffer.
1166
+ The ``length`` is a i32/i64 (py_ssize_t) of the length of the buffer.
1167
+ """
1168
+
1169
+ p_length = cgutils.alloca_once(self.builder, self.py_ssize_t)
1170
+ fnty = ir.FunctionType(
1171
+ self.cstring, [self.pyobj, self.py_ssize_t.as_pointer()]
1172
+ )
1173
+ fname = "PyUnicode_AsUTF8AndSize"
1174
+ fn = self._get_function(fnty, name=fname)
1175
+
1176
+ buffer = self.builder.call(fn, [strobj, p_length])
1177
+ ok = self.builder.icmp_unsigned(
1178
+ "!=", Constant(buffer.type, None), buffer
1179
+ )
1180
+ return (ok, buffer, self.builder.load(p_length))
1181
+
1182
+ def string_as_string_size_and_kind(self, strobj):
1183
+ """
1184
+ Returns a tuple of ``(ok, buffer, length, kind)``.
1185
+ The ``ok`` is i1 value that is set if ok.
1186
+ The ``buffer`` is a i8* of the output buffer.
1187
+ The ``length`` is a i32/i64 (py_ssize_t) of the length of the buffer.
1188
+ The ``kind`` is a i32 (int32) of the Unicode kind constant
1189
+ The ``hash`` is a long/uint64_t (py_hash_t) of the Unicode constant hash
1190
+ """
1191
+ p_length = cgutils.alloca_once(self.builder, self.py_ssize_t)
1192
+ p_kind = cgutils.alloca_once(self.builder, ir.IntType(32))
1193
+ p_ascii = cgutils.alloca_once(self.builder, ir.IntType(32))
1194
+ p_hash = cgutils.alloca_once(self.builder, self.py_hash_t)
1195
+ fnty = ir.FunctionType(
1196
+ self.cstring,
1197
+ [
1198
+ self.pyobj,
1199
+ self.py_ssize_t.as_pointer(),
1200
+ ir.IntType(32).as_pointer(),
1201
+ ir.IntType(32).as_pointer(),
1202
+ self.py_hash_t.as_pointer(),
1203
+ ],
1204
+ )
1205
+ fname = "numba_extract_unicode"
1206
+ fn = self._get_function(fnty, name=fname)
1207
+
1208
+ buffer = self.builder.call(
1209
+ fn, [strobj, p_length, p_kind, p_ascii, p_hash]
1210
+ )
1211
+ ok = self.builder.icmp_unsigned(
1212
+ "!=", Constant(buffer.type, None), buffer
1213
+ )
1214
+ return (
1215
+ ok,
1216
+ buffer,
1217
+ self.builder.load(p_length),
1218
+ self.builder.load(p_kind),
1219
+ self.builder.load(p_ascii),
1220
+ self.builder.load(p_hash),
1221
+ )
1222
+
1223
+ def string_from_string_and_size(self, string, size):
1224
+ fnty = ir.FunctionType(self.pyobj, [self.cstring, self.py_ssize_t])
1225
+ fname = "PyString_FromStringAndSize"
1226
+ fn = self._get_function(fnty, name=fname)
1227
+ return self.builder.call(fn, [string, size])
1228
+
1229
+ def string_from_string(self, string):
1230
+ fnty = ir.FunctionType(self.pyobj, [self.cstring])
1231
+ fname = "PyUnicode_FromString"
1232
+ fn = self._get_function(fnty, name=fname)
1233
+ return self.builder.call(fn, [string])
1234
+
1235
+ def string_from_kind_and_data(self, kind, string, size):
1236
+ fnty = ir.FunctionType(
1237
+ self.pyobj, [ir.IntType(32), self.cstring, self.py_ssize_t]
1238
+ )
1239
+ fname = "PyUnicode_FromKindAndData"
1240
+ fn = self._get_function(fnty, name=fname)
1241
+ return self.builder.call(fn, [kind, string, size])
1242
+
1243
+ def bytes_as_string(self, obj):
1244
+ fnty = ir.FunctionType(self.cstring, [self.pyobj])
1245
+ fname = "PyBytes_AsString"
1246
+ fn = self._get_function(fnty, name=fname)
1247
+ return self.builder.call(fn, [obj])
1248
+
1249
+ def bytes_as_string_and_size(self, obj, p_buffer, p_length):
1250
+ fnty = ir.FunctionType(
1251
+ ir.IntType(32),
1252
+ [
1253
+ self.pyobj,
1254
+ self.cstring.as_pointer(),
1255
+ self.py_ssize_t.as_pointer(),
1256
+ ],
1257
+ )
1258
+ fname = "PyBytes_AsStringAndSize"
1259
+ fn = self._get_function(fnty, name=fname)
1260
+ result = self.builder.call(fn, [obj, p_buffer, p_length])
1261
+ ok = self.builder.icmp_signed("!=", Constant(result.type, -1), result)
1262
+ return ok
1263
+
1264
+ def bytes_from_string_and_size(self, string, size):
1265
+ fnty = ir.FunctionType(self.pyobj, [self.cstring, self.py_ssize_t])
1266
+ fname = "PyBytes_FromStringAndSize"
1267
+ fn = self._get_function(fnty, name=fname)
1268
+ return self.builder.call(fn, [string, size])
1269
+
1270
+ def object_hash(self, obj):
1271
+ fnty = ir.FunctionType(
1272
+ self.py_hash_t,
1273
+ [
1274
+ self.pyobj,
1275
+ ],
1276
+ )
1277
+ fname = "PyObject_Hash"
1278
+ fn = self._get_function(fnty, name=fname)
1279
+ return self.builder.call(
1280
+ fn,
1281
+ [
1282
+ obj,
1283
+ ],
1284
+ )
1285
+
1286
+ def object_str(self, obj):
1287
+ fnty = ir.FunctionType(self.pyobj, [self.pyobj])
1288
+ fn = self._get_function(fnty, name="PyObject_Str")
1289
+ return self.builder.call(fn, [obj])
1290
+
1291
+ def make_none(self):
1292
+ obj = self.borrow_none()
1293
+ self.incref(obj)
1294
+ return obj
1295
+
1296
+ def borrow_none(self):
1297
+ return self.get_c_object("_Py_NoneStruct")
1298
+
1299
+ def sys_write_stdout(self, fmt, *args):
1300
+ fnty = ir.FunctionType(ir.VoidType(), [self.cstring], var_arg=True)
1301
+ fn = self._get_function(fnty, name="PySys_FormatStdout")
1302
+ return self.builder.call(fn, (fmt,) + args)
1303
+
1304
+ def object_dump(self, obj):
1305
+ """
1306
+ Dump a Python object on C stderr. For debugging purposes.
1307
+ """
1308
+ fnty = ir.FunctionType(ir.VoidType(), [self.pyobj])
1309
+ fn = self._get_function(fnty, name="_PyObject_Dump")
1310
+ return self.builder.call(fn, (obj,))
1311
+
1312
+ #
1313
+ # NRT (Numba runtime) APIs
1314
+ #
1315
+
1316
+ def nrt_adapt_ndarray_to_python(self, aryty, ary, dtypeptr):
1317
+ assert self.context.enable_nrt, "NRT required"
1318
+
1319
+ intty = ir.IntType(32)
1320
+ # Embed the Python type of the array (maybe subclass) in the LLVM IR.
1321
+ serial_aryty_pytype = self.unserialize(
1322
+ self.serialize_object(aryty.box_type)
1323
+ )
1324
+
1325
+ fnty = ir.FunctionType(
1326
+ self.pyobj, [self.voidptr, self.pyobj, intty, intty, self.pyobj]
1327
+ )
1328
+ fn = self._get_function(fnty, name="NRT_adapt_ndarray_to_python_acqref")
1329
+ fn.args[0].add_attribute("nocapture")
1330
+
1331
+ ndim = self.context.get_constant(types.int32, aryty.ndim)
1332
+ writable = self.context.get_constant(types.int32, int(aryty.mutable))
1333
+
1334
+ aryptr = cgutils.alloca_once_value(self.builder, ary)
1335
+ return self.builder.call(
1336
+ fn,
1337
+ [
1338
+ self.builder.bitcast(aryptr, self.voidptr),
1339
+ serial_aryty_pytype,
1340
+ ndim,
1341
+ writable,
1342
+ dtypeptr,
1343
+ ],
1344
+ )
1345
+
1346
+ def nrt_meminfo_new_from_pyobject(self, data, pyobj):
1347
+ """
1348
+ Allocate a new MemInfo with data payload borrowed from a python
1349
+ object.
1350
+ """
1351
+ mod = self.builder.module
1352
+ fnty = ir.FunctionType(
1353
+ cgutils.voidptr_t,
1354
+ [cgutils.voidptr_t, cgutils.voidptr_t],
1355
+ )
1356
+ fn = cgutils.get_or_insert_function(
1357
+ mod,
1358
+ fnty,
1359
+ "NRT_meminfo_new_from_pyobject",
1360
+ )
1361
+ fn.args[0].add_attribute("nocapture")
1362
+ fn.args[1].add_attribute("nocapture")
1363
+ fn.return_value.add_attribute("noalias")
1364
+ return self.builder.call(fn, [data, pyobj])
1365
+
1366
+ def nrt_meminfo_as_pyobject(self, miptr):
1367
+ mod = self.builder.module
1368
+ fnty = ir.FunctionType(self.pyobj, [cgutils.voidptr_t])
1369
+ fn = cgutils.get_or_insert_function(
1370
+ mod,
1371
+ fnty,
1372
+ "NRT_meminfo_as_pyobject",
1373
+ )
1374
+ fn.return_value.add_attribute("noalias")
1375
+ return self.builder.call(fn, [miptr])
1376
+
1377
+ def nrt_meminfo_from_pyobject(self, miobj):
1378
+ mod = self.builder.module
1379
+ fnty = ir.FunctionType(cgutils.voidptr_t, [self.pyobj])
1380
+ fn = cgutils.get_or_insert_function(
1381
+ mod,
1382
+ fnty,
1383
+ "NRT_meminfo_from_pyobject",
1384
+ )
1385
+ fn.return_value.add_attribute("noalias")
1386
+ return self.builder.call(fn, [miobj])
1387
+
1388
+ def nrt_adapt_ndarray_from_python(self, ary, ptr):
1389
+ assert self.context.enable_nrt
1390
+ fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, self.voidptr])
1391
+ fn = self._get_function(fnty, name="NRT_adapt_ndarray_from_python")
1392
+ fn.args[0].add_attribute("nocapture")
1393
+ fn.args[1].add_attribute("nocapture")
1394
+ return self.builder.call(fn, (ary, ptr))
1395
+
1396
+ def nrt_adapt_buffer_from_python(self, buf, ptr):
1397
+ assert self.context.enable_nrt
1398
+ fnty = ir.FunctionType(
1399
+ ir.VoidType(), [ir.PointerType(self.py_buffer_t), self.voidptr]
1400
+ )
1401
+ fn = self._get_function(fnty, name="NRT_adapt_buffer_from_python")
1402
+ fn.args[0].add_attribute("nocapture")
1403
+ fn.args[1].add_attribute("nocapture")
1404
+ return self.builder.call(fn, (buf, ptr))
1405
+
1406
+ # ------ utils -----
1407
+
1408
+ def _get_function(self, fnty, name):
1409
+ return cgutils.get_or_insert_function(self.module, fnty, name)
1410
+
1411
+ def alloca_obj(self):
1412
+ return self.builder.alloca(self.pyobj)
1413
+
1414
+ def alloca_buffer(self):
1415
+ """
1416
+ Return a pointer to a stack-allocated, zero-initialized Py_buffer.
1417
+ """
1418
+ # Treat the buffer as an opaque array of bytes
1419
+ ptr = cgutils.alloca_once_value(
1420
+ self.builder, Constant(self.py_buffer_t, None)
1421
+ )
1422
+ return ptr
1423
+
1424
+ @contextlib.contextmanager
1425
+ def if_object_ok(self, obj):
1426
+ with cgutils.if_likely(
1427
+ self.builder, cgutils.is_not_null(self.builder, obj)
1428
+ ):
1429
+ yield
1430
+
1431
+ def print_object(self, obj):
1432
+ strobj = self.object_str(obj)
1433
+ cstr = self.string_as_string(strobj)
1434
+ fmt = self.context.insert_const_string(self.module, "%s")
1435
+ self.sys_write_stdout(fmt, cstr)
1436
+ self.decref(strobj)
1437
+
1438
+ def print_string(self, text):
1439
+ fmt = self.context.insert_const_string(self.module, text)
1440
+ self.sys_write_stdout(fmt)
1441
+
1442
+ def get_null_object(self):
1443
+ return Constant(self.pyobj, None)
1444
+
1445
+ def return_none(self):
1446
+ none = self.make_none()
1447
+ self.builder.ret(none)
1448
+
1449
+ def list_pack(self, items):
1450
+ n = len(items)
1451
+ seq = self.list_new(self.context.get_constant(types.intp, n))
1452
+ with self.if_object_ok(seq):
1453
+ for i in range(n):
1454
+ idx = self.context.get_constant(types.intp, i)
1455
+ self.incref(items[i])
1456
+ self.list_setitem(seq, idx, items[i])
1457
+ return seq
1458
+
1459
+ def unserialize(self, structptr):
1460
+ """
1461
+ Unserialize some data. *structptr* should be a pointer to
1462
+ a {i8* data, i32 length, i8* hashbuf, i8* func_ptr, i32 alloc_flag}
1463
+ structure.
1464
+ """
1465
+ fnty = ir.FunctionType(
1466
+ self.pyobj, (self.voidptr, ir.IntType(32), self.voidptr)
1467
+ )
1468
+ fn = self._get_function(fnty, name="numba_unpickle")
1469
+ ptr = self.builder.extract_value(self.builder.load(structptr), 0)
1470
+ n = self.builder.extract_value(self.builder.load(structptr), 1)
1471
+ hashed = self.builder.extract_value(self.builder.load(structptr), 2)
1472
+ return self.builder.call(fn, (ptr, n, hashed))
1473
+
1474
+ def build_dynamic_excinfo_struct(self, struct_gv, exc_args):
1475
+ """
1476
+ Serialize some data at runtime. Returns a pointer to a python tuple
1477
+ (bytes_data, hash) where the first element is the serialized data as
1478
+ bytes and the second its hash.
1479
+ """
1480
+ fnty = ir.FunctionType(self.pyobj, (self.pyobj, self.pyobj))
1481
+ fn = self._get_function(fnty, name="numba_runtime_build_excinfo_struct")
1482
+ return self.builder.call(fn, (struct_gv, exc_args))
1483
+
1484
+ def serialize_uncached(self, obj):
1485
+ """
1486
+ Same as serialize_object(), but don't create a global variable,
1487
+ simply return a literal for structure:
1488
+ {i8* data, i32 length, i8* hashbuf, i8* func_ptr, i32 alloc_flag}
1489
+ """
1490
+ # First make the array constant
1491
+ data = serialize.dumps(obj)
1492
+ assert len(data) < 2**31
1493
+ name = ".const.pickledata.%s" % (
1494
+ id(obj) if config.DIFF_IR == 0 else "DIFF_IR"
1495
+ )
1496
+ bdata = cgutils.make_bytearray(data)
1497
+ # Make SHA1 hash on the pickled content
1498
+ # NOTE: update buffer size in numba_unpickle() when changing the
1499
+ # hash algorithm.
1500
+ hashed = cgutils.make_bytearray(hashlib.sha1(data).digest())
1501
+ arr = self.context.insert_unique_const(self.module, name, bdata)
1502
+ hasharr = self.context.insert_unique_const(
1503
+ self.module,
1504
+ f"{name}.sha1",
1505
+ hashed,
1506
+ )
1507
+ # Then populate the structure constant
1508
+ struct = Constant.literal_struct(
1509
+ [
1510
+ arr.bitcast(self.voidptr),
1511
+ Constant(ir.IntType(32), arr.type.pointee.count),
1512
+ hasharr.bitcast(self.voidptr),
1513
+ cgutils.get_null_value(self.voidptr),
1514
+ Constant(ir.IntType(32), 0),
1515
+ ]
1516
+ )
1517
+ return struct
1518
+
1519
+ def serialize_object(self, obj):
1520
+ """
1521
+ Serialize the given object in the bitcode, and return it
1522
+ as a pointer to a
1523
+ {i8* data, i32 length, i8* hashbuf, i8* fn_ptr, i32 alloc_flag},
1524
+ structure constant (suitable for passing to unserialize()).
1525
+ """
1526
+ try:
1527
+ gv = self.module.__serialized[obj]
1528
+ except KeyError:
1529
+ struct = self.serialize_uncached(obj)
1530
+ name = ".const.picklebuf.%s" % (
1531
+ id(obj) if config.DIFF_IR == 0 else "DIFF_IR"
1532
+ )
1533
+ gv = self.context.insert_unique_const(self.module, name, struct)
1534
+ # Make the id() (and hence the name) unique while populating the module.
1535
+ self.module.__serialized[obj] = gv
1536
+ return gv
1537
+
1538
+ def c_api_error(self):
1539
+ return cgutils.is_not_null(self.builder, self.err_occurred())
1540
+
1541
+ def to_native_value(self, typ, obj):
1542
+ """
1543
+ Unbox the Python object as the given Numba type.
1544
+ A NativeValue instance is returned.
1545
+ """
1546
+ from numba.core.boxing import unbox_unsupported
1547
+
1548
+ impl = _unboxers.lookup(typ.__class__, unbox_unsupported)
1549
+ c = _UnboxContext(self.context, self.builder, self)
1550
+ return impl(typ, obj, c)
1551
+
1552
+ def from_native_return(self, typ, val, env_manager):
1553
+ assert not isinstance(typ, types.Optional), (
1554
+ "callconv should have prevented the return of optional value"
1555
+ )
1556
+ out = self.from_native_value(typ, val, env_manager)
1557
+ return out
1558
+
1559
+ def from_native_value(self, typ, val, env_manager=None):
1560
+ """
1561
+ Box the native value of the given Numba type. A Python object
1562
+ pointer is returned (NULL if an error occurred).
1563
+ This method steals any native (NRT) reference embedded in *val*.
1564
+ """
1565
+ from numba.core.boxing import box_unsupported
1566
+
1567
+ impl = _boxers.lookup(typ.__class__, box_unsupported)
1568
+
1569
+ c = _BoxContext(self.context, self.builder, self, env_manager)
1570
+ return impl(typ, val, c)
1571
+
1572
+ def reflect_native_value(self, typ, val, env_manager=None):
1573
+ """
1574
+ Reflect the native value onto its Python original, if any.
1575
+ An error bit (as an LLVM value) is returned.
1576
+ """
1577
+ impl = _reflectors.lookup(typ.__class__)
1578
+ if impl is None:
1579
+ # Reflection isn't needed for most types
1580
+ return cgutils.false_bit
1581
+
1582
+ is_error = cgutils.alloca_once_value(self.builder, cgutils.false_bit)
1583
+ c = _ReflectContext(
1584
+ self.context, self.builder, self, env_manager, is_error
1585
+ )
1586
+ impl(typ, val, c)
1587
+ return self.builder.load(c.is_error)
1588
+
1589
+ def to_native_generator(self, obj, typ):
1590
+ """
1591
+ Extract the generator structure pointer from a generator *obj*
1592
+ (a _dynfunc.Generator instance).
1593
+ """
1594
+ gen_ptr_ty = ir.PointerType(self.context.get_data_type(typ))
1595
+ value = self.context.get_generator_state(self.builder, obj, gen_ptr_ty)
1596
+ return NativeValue(value)
1597
+
1598
+ def from_native_generator(self, val, typ, env=None):
1599
+ """
1600
+ Make a Numba generator (a _dynfunc.Generator instance) from a
1601
+ generator structure pointer *val*.
1602
+ *env* is an optional _dynfunc.Environment instance to be wrapped
1603
+ in the generator.
1604
+ """
1605
+ llty = self.context.get_data_type(typ)
1606
+ assert not llty.is_pointer
1607
+ gen_struct_size = self.context.get_abi_sizeof(llty)
1608
+
1609
+ gendesc = self.context.get_generator_desc(typ)
1610
+
1611
+ # This is the PyCFunctionWithKeywords generated by PyCallWrapper
1612
+ genfnty = ir.FunctionType(
1613
+ self.pyobj, [self.pyobj, self.pyobj, self.pyobj]
1614
+ )
1615
+ genfn = self._get_function(
1616
+ genfnty, name=gendesc.llvm_cpython_wrapper_name
1617
+ )
1618
+
1619
+ # This is the raw finalizer generated by _lower_generator_finalize_func()
1620
+ finalizerty = ir.FunctionType(ir.VoidType(), [self.voidptr])
1621
+ if typ.has_finalizer:
1622
+ finalizer = self._get_function(
1623
+ finalizerty, name=gendesc.llvm_finalizer_name
1624
+ )
1625
+ else:
1626
+ finalizer = Constant(ir.PointerType(finalizerty), None)
1627
+
1628
+ # PyObject *numba_make_generator(state_size, initial_state, nextfunc, finalizer, env)
1629
+ fnty = ir.FunctionType(
1630
+ self.pyobj,
1631
+ [
1632
+ self.py_ssize_t,
1633
+ self.voidptr,
1634
+ ir.PointerType(genfnty),
1635
+ ir.PointerType(finalizerty),
1636
+ self.voidptr,
1637
+ ],
1638
+ )
1639
+ fn = self._get_function(fnty, name="numba_make_generator")
1640
+
1641
+ state_size = Constant(self.py_ssize_t, gen_struct_size)
1642
+ initial_state = self.builder.bitcast(val, self.voidptr)
1643
+ if env is None:
1644
+ env = self.get_null_object()
1645
+ env = self.builder.bitcast(env, self.voidptr)
1646
+
1647
+ return self.builder.call(
1648
+ fn, (state_size, initial_state, genfn, finalizer, env)
1649
+ )
1650
+
1651
+ def numba_array_adaptor(self, ary, ptr):
1652
+ assert not self.context.enable_nrt
1653
+ fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, self.voidptr])
1654
+ fn = self._get_function(fnty, name="numba_adapt_ndarray")
1655
+ fn.args[0].add_attribute("nocapture")
1656
+ fn.args[1].add_attribute("nocapture")
1657
+ return self.builder.call(fn, (ary, ptr))
1658
+
1659
+ def numba_buffer_adaptor(self, buf, ptr):
1660
+ fnty = ir.FunctionType(
1661
+ ir.VoidType(), [ir.PointerType(self.py_buffer_t), self.voidptr]
1662
+ )
1663
+ fn = self._get_function(fnty, name="numba_adapt_buffer")
1664
+ fn.args[0].add_attribute("nocapture")
1665
+ fn.args[1].add_attribute("nocapture")
1666
+ return self.builder.call(fn, (buf, ptr))
1667
+
1668
+ def complex_adaptor(self, cobj, cmplx):
1669
+ fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, cmplx.type])
1670
+ fn = self._get_function(fnty, name="numba_complex_adaptor")
1671
+ return self.builder.call(fn, [cobj, cmplx])
1672
+
1673
+ def extract_record_data(self, obj, pbuf):
1674
+ fnty = ir.FunctionType(
1675
+ self.voidptr, [self.pyobj, ir.PointerType(self.py_buffer_t)]
1676
+ )
1677
+ fn = self._get_function(fnty, name="numba_extract_record_data")
1678
+ return self.builder.call(fn, [obj, pbuf])
1679
+
1680
+ def get_buffer(self, obj, pbuf):
1681
+ fnty = ir.FunctionType(
1682
+ ir.IntType(32), [self.pyobj, ir.PointerType(self.py_buffer_t)]
1683
+ )
1684
+ fn = self._get_function(fnty, name="numba_get_buffer")
1685
+ return self.builder.call(fn, [obj, pbuf])
1686
+
1687
+ def release_buffer(self, pbuf):
1688
+ fnty = ir.FunctionType(
1689
+ ir.VoidType(), [ir.PointerType(self.py_buffer_t)]
1690
+ )
1691
+ fn = self._get_function(fnty, name="numba_release_buffer")
1692
+ return self.builder.call(fn, [pbuf])
1693
+
1694
+ def extract_np_datetime(self, obj):
1695
+ fnty = ir.FunctionType(ir.IntType(64), [self.pyobj])
1696
+ fn = self._get_function(fnty, name="numba_extract_np_datetime")
1697
+ return self.builder.call(fn, [obj])
1698
+
1699
+ def extract_np_timedelta(self, obj):
1700
+ fnty = ir.FunctionType(ir.IntType(64), [self.pyobj])
1701
+ fn = self._get_function(fnty, name="numba_extract_np_timedelta")
1702
+ return self.builder.call(fn, [obj])
1703
+
1704
+ def create_np_datetime(self, val, unit_code):
1705
+ unit_code = Constant(ir.IntType(32), int(unit_code))
1706
+ fnty = ir.FunctionType(self.pyobj, [ir.IntType(64), ir.IntType(32)])
1707
+ fn = self._get_function(fnty, name="numba_create_np_datetime")
1708
+ return self.builder.call(fn, [val, unit_code])
1709
+
1710
+ def create_np_timedelta(self, val, unit_code):
1711
+ unit_code = Constant(ir.IntType(32), int(unit_code))
1712
+ fnty = ir.FunctionType(self.pyobj, [ir.IntType(64), ir.IntType(32)])
1713
+ fn = self._get_function(fnty, name="numba_create_np_timedelta")
1714
+ return self.builder.call(fn, [val, unit_code])
1715
+
1716
+ def recreate_record(self, pdata, size, dtype, env_manager):
1717
+ fnty = ir.FunctionType(
1718
+ self.pyobj,
1719
+ [ir.PointerType(ir.IntType(8)), ir.IntType(32), self.pyobj],
1720
+ )
1721
+ fn = self._get_function(fnty, name="numba_recreate_record")
1722
+ dtypeaddr = env_manager.read_const(env_manager.add_const(dtype))
1723
+ return self.builder.call(fn, [pdata, size, dtypeaddr])
1724
+
1725
+ def string_from_constant_string(self, string):
1726
+ cstr = self.context.insert_const_string(self.module, string)
1727
+ sz = self.context.get_constant(types.intp, len(string))
1728
+ return self.string_from_string_and_size(cstr, sz)
1729
+
1730
+ def call_jit_code(self, func, sig, args):
1731
+ """Calls into Numba jitted code and propagate error using the Python
1732
+ calling convention.
1733
+
1734
+ Parameters
1735
+ ----------
1736
+ func : function
1737
+ The Python function to be compiled. This function is compiled
1738
+ in nopython-mode.
1739
+ sig : numba.typing.Signature
1740
+ The function signature for *func*.
1741
+ args : Sequence[llvmlite.binding.Value]
1742
+ LLVM values to use as arguments.
1743
+
1744
+ Returns
1745
+ -------
1746
+ (is_error, res) : 2-tuple of llvmlite.binding.Value.
1747
+ is_error : true iff *func* raised an exception.
1748
+ res : Returned value from *func* iff *is_error* is false.
1749
+
1750
+ If *is_error* is true, this method will adapt the nopython exception
1751
+ into a Python exception. Caller should return NULL to Python to
1752
+ indicate an error.
1753
+ """
1754
+ # Compile *func*
1755
+ builder = self.builder
1756
+ cres = self.context.compile_subroutine(builder, func, sig)
1757
+ got_retty = cres.signature.return_type
1758
+ retty = sig.return_type
1759
+ if got_retty != retty:
1760
+ # This error indicates an error in *func* or the caller of this
1761
+ # method.
1762
+ raise errors.LoweringError(
1763
+ f"mismatching signature {got_retty} != {retty}.\n"
1764
+ )
1765
+ # Call into *func*
1766
+ status, res = self.context.call_internal_no_propagate(
1767
+ builder,
1768
+ cres.fndesc,
1769
+ sig,
1770
+ args,
1771
+ )
1772
+ # Post-call handling for *func*
1773
+ is_error_ptr = cgutils.alloca_once(builder, cgutils.bool_t, zfill=True)
1774
+ res_type = self.context.get_value_type(sig.return_type)
1775
+ res_ptr = cgutils.alloca_once(builder, res_type, zfill=True)
1776
+
1777
+ # Handle error and adapt the nopython exception into cpython exception
1778
+ with builder.if_else(status.is_error) as (has_err, no_err):
1779
+ with has_err:
1780
+ builder.store(status.is_error, is_error_ptr)
1781
+ # Set error state in the Python interpreter
1782
+ self.context.call_conv.raise_error(builder, self, status)
1783
+ with no_err:
1784
+ # Handle returned value
1785
+ res = imputils.fix_returning_optional(
1786
+ self.context,
1787
+ builder,
1788
+ sig,
1789
+ status,
1790
+ res,
1791
+ )
1792
+ builder.store(res, res_ptr)
1793
+
1794
+ is_error = builder.load(is_error_ptr)
1795
+ res = builder.load(res_ptr)
1796
+ return is_error, res
1797
+
1798
+
1799
+ class ObjModeUtils:
1800
+ """Internal utils for calling objmode dispatcher from within NPM code."""
1801
+
1802
+ def __init__(self, pyapi):
1803
+ self.pyapi = pyapi
1804
+
1805
+ def load_dispatcher(self, fnty, argtypes):
1806
+ builder = self.pyapi.builder
1807
+ tyctx = self.pyapi.context
1808
+ m = builder.module
1809
+
1810
+ # Add a global variable to cache the objmode dispatcher
1811
+ gv = ir.GlobalVariable(
1812
+ m,
1813
+ self.pyapi.pyobj,
1814
+ name=m.get_unique_name("cached_objmode_dispatcher"),
1815
+ )
1816
+ gv.initializer = gv.type.pointee(None)
1817
+ gv.linkage = "internal"
1818
+
1819
+ # Make a basic-block to common exit
1820
+ bb_end = builder.append_basic_block("bb_end")
1821
+
1822
+ if serialize.is_serialiable(fnty.dispatcher):
1823
+ serialized_dispatcher = self.pyapi.serialize_object(
1824
+ (fnty.dispatcher, tuple(argtypes)),
1825
+ )
1826
+ compile_args = self.pyapi.unserialize(serialized_dispatcher)
1827
+ # unserialize (unpickling) can fail
1828
+ failed_unser = cgutils.is_null(builder, compile_args)
1829
+ with builder.if_then(failed_unser):
1830
+ # early exit. `gv` is still null.
1831
+ builder.branch(bb_end)
1832
+
1833
+ cached = builder.load(gv)
1834
+ with builder.if_then(cgutils.is_null(builder, cached)):
1835
+ if serialize.is_serialiable(fnty.dispatcher):
1836
+ cls = type(self)
1837
+ compiler = self.pyapi.unserialize(
1838
+ self.pyapi.serialize_object(cls._call_objmode_dispatcher)
1839
+ )
1840
+ callee = self.pyapi.call_function_objargs(
1841
+ compiler,
1842
+ [compile_args],
1843
+ )
1844
+ # Clean up
1845
+ self.pyapi.decref(compiler)
1846
+ self.pyapi.decref(compile_args)
1847
+ else:
1848
+ entry_pt = fnty.dispatcher.compile(tuple(argtypes))
1849
+ callee = tyctx.add_dynamic_addr(
1850
+ builder,
1851
+ id(entry_pt),
1852
+ info="with_objectmode",
1853
+ )
1854
+ # Incref the dispatcher and cache it
1855
+ self.pyapi.incref(callee)
1856
+ builder.store(callee, gv)
1857
+ # Jump to the exit block
1858
+ builder.branch(bb_end)
1859
+ # Define the exit block
1860
+ builder.position_at_end(bb_end)
1861
+ callee = builder.load(gv)
1862
+ return callee
1863
+
1864
+ @staticmethod
1865
+ def _call_objmode_dispatcher(compile_args):
1866
+ dispatcher, argtypes = compile_args
1867
+ entrypt = dispatcher.compile(argtypes)
1868
+ return entrypt