gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _fail(self, val):
    raise ConstantInferenceError("constant inference not possible for %s" % (val,))


# Traceback (ConstantInferenceError)
---------------------------------------------------------------------------
ConstantInferenceError                    Traceback (most recent call last)
<ipython-input-29-41c708083646> in <module>
5     return a*b
6
----> 7 problem(1,2)

~/.virtualenvs/dl4cv/lib/python3.7/site-packages/numba/dispatcher.py in _compile_for_args(self, *args, **kws)
358             # this is from trying to infer something as constant when it isn't
359             # or isn't supported as a constant
--> 360             error_rewrite(e, 'constant_inference')
361         except Exception as e:
362             if config.SHOW_HELP:

~/.virtualenvs/dl4cv/lib/python3.7/site-packages/numba/dispatcher.py in error_rewrite(e, issue_type)
313                 raise e
314             else:
--> 315                 reraise(type(e), e, None)
316
317         argtypes = []

~/.virtualenvs/dl4cv/lib/python3.7/site-packages/numba/six.py in reraise(tp, value, tb)
656             value = tp()
657         if value.__traceback__ is not tb:
--> 658             raise value.with_traceback(tb)
659         raise value
660

ConstantInferenceError: Failed in nopython mode pipeline (step: nopython rewrites)
Cannot make a constant from: Cannot make a constant from: Cannot make a constant from: constant inference not possible for arg(0, name=a)
Numba could not make a constant out of something that it decided should be
a constant. This could well be a current limitation in Numba's internals,
please either raise a bug report along with a minimal reproducer at:
https://github.com/numba/numba/issues/new

# Fixed code
def _fail(self, val):
    # The location here is set to None because `val` is the ir.Var name
    # and not the actual offending use of the var. When this is raised it is
    # caught in the flow control of `infer_constant` and the class and args
    # (the message) are captured and then raised again but with the location
    # set to the expression that caused the constant inference error.
    raise ConstantInferenceError(
        "Constant inference not possible for: %s" % (val,), loc=None
    )
# Buggy code
def _infer_expr(self, expr):
    # Infer an expression: handle supported cases
    if expr.op == "call":
        func = self.infer_constant(expr.func.name)
        return self._infer_call(func, expr)
    elif expr.op == "getattr":
        value = self.infer_constant(expr.value.name)
        return self._infer_getattr(value, expr)
    elif expr.op == "build_list":
        return [self.infer_constant(i.name) for i in expr.items]
    elif expr.op == "build_tuple":
        return tuple(self.infer_constant(i.name) for i in expr.items)
    self._fail(expr)


# Traceback (ConstantInferenceError)
---------------------------------------------------------------------------
ConstantInferenceError                    Traceback (most recent call last)
<ipython-input-29-41c708083646> in <module>
5     return a*b
6
----> 7 problem(1,2)

~/.virtualenvs/dl4cv/lib/python3.7/site-packages/numba/dispatcher.py in _compile_for_args(self, *args, **kws)
358             # this is from trying to infer something as constant when it isn't
359             # or isn't supported as a constant
--> 360             error_rewrite(e, 'constant_inference')
361         except Exception as e:
362             if config.SHOW_HELP:

~/.virtualenvs/dl4cv/lib/python3.7/site-packages/numba/dispatcher.py in error_rewrite(e, issue_type)
313                 raise e
314             else:
--> 315                 reraise(type(e), e, None)
316
317         argtypes = []

~/.virtualenvs/dl4cv/lib/python3.7/site-packages/numba/six.py in reraise(tp, value, tb)
656             value = tp()
657         if value.__traceback__ is not tb:
--> 658             raise value.with_traceback(tb)
659         raise value
660

ConstantInferenceError: Failed in nopython mode pipeline (step: nopython rewrites)
Cannot make a constant from: Cannot make a constant from: Cannot make a constant from: constant inference not possible for arg(0, name=a)
Numba could not make a constant out of something that it decided should be
a constant. This could well be a current limitation in Numba's internals,
please either raise a bug report along with a minimal reproducer at:
https://github.com/numba/numba/issues/new

# Fixed code
def _infer_expr(self, expr):
    # Infer an expression: handle supported cases
    if expr.op == "call":
        func = self.infer_constant(expr.func.name, loc=expr.loc)
        return self._infer_call(func, expr)
    elif expr.op == "getattr":
        value = self.infer_constant(expr.value.name, loc=expr.loc)
        return self._infer_getattr(value, expr)
    elif expr.op == "build_list":
        return [self.infer_constant(i.name, loc=expr.loc) for i in expr.items]
    elif expr.op == "build_tuple":
        return tuple(self.infer_constant(i.name, loc=expr.loc) for i in expr.items)
    self._fail(expr)
# Buggy code
def __init__(self, value, loc=None):
    self.value = value
    msg = "Cannot make a constant from: %s" % value
    super(ConstantInferenceError, self).__init__(msg, loc=loc)


# Traceback (ConstantInferenceError)
---------------------------------------------------------------------------
ConstantInferenceError                    Traceback (most recent call last)
<ipython-input-29-41c708083646> in <module>
5     return a*b
6
----> 7 problem(1,2)

~/.virtualenvs/dl4cv/lib/python3.7/site-packages/numba/dispatcher.py in _compile_for_args(self, *args, **kws)
358             # this is from trying to infer something as constant when it isn't
359             # or isn't supported as a constant
--> 360             error_rewrite(e, 'constant_inference')
361         except Exception as e:
362             if config.SHOW_HELP:

~/.virtualenvs/dl4cv/lib/python3.7/site-packages/numba/dispatcher.py in error_rewrite(e, issue_type)
313                 raise e
314             else:
--> 315                 reraise(type(e), e, None)
316
317         argtypes = []

~/.virtualenvs/dl4cv/lib/python3.7/site-packages/numba/six.py in reraise(tp, value, tb)
656             value = tp()
657         if value.__traceback__ is not tb:
--> 658             raise value.with_traceback(tb)
659         raise value
660

ConstantInferenceError: Failed in nopython mode pipeline (step: nopython rewrites)
Cannot make a constant from: Cannot make a constant from: Cannot make a constant from: constant inference not possible for arg(0, name=a)
Numba could not make a constant out of something that it decided should be
a constant. This could well be a current limitation in Numba's internals,
please either raise a bug report along with a minimal reproducer at:
https://github.com/numba/numba/issues/new

# Fixed code
def __init__(self, value, loc=None):
    super(ConstantInferenceError, self).__init__(value, loc=loc)
# Buggy code
def from_types(cls, tys, pyclass=None):
    """
    Instantiate the right tuple type for the given element types.
    """
    homogeneous = False
    if tys:
        first = tys[0]
        for ty in tys[1:]:
            if ty != first:
                break
        else:
            homogeneous = True

    if pyclass is not None and pyclass is not tuple:
        # A subclass => is it a namedtuple?
        assert issubclass(pyclass, tuple)
        if hasattr(pyclass, "_asdict"):
            if homogeneous:
                return NamedUniTuple(first, len(tys), pyclass)
            else:
                return NamedTuple(tys, pyclass)
    if homogeneous:
        return UniTuple(first, len(tys))
    else:
        return Tuple(tys)


# Traceback (TypingError)
---------------------------------------------------------------------------
TypingError                               Traceback (most recent call last)
<ipython-input-60-b047fa49e45c> in <module>()
----> 1 call(1, 1)

/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/numba/dispatcher.py in _compile_for_args(self, *args, **kws)
346                 e.patch_message(msg)
347
--> 348             error_rewrite(e, 'typing')
349         except errors.UnsupportedError as e:
350             # Something unsupported is present in the user code, add help info

/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/numba/dispatcher.py in error_rewrite(e, issue_type)
313                 raise e
314             else:
--> 315                 reraise(type(e), e, None)
316
317         argtypes = []

/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/numba/six.py in reraise(tp, value, tb)
656             value = tp()
657         if value.__traceback__ is not tb:
--> 658             raise value.with_traceback(tb)
659         raise value
660

TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Cannot unify Data2(int64, Literal[int](0)) and Data2(int64 x 2) for 'result', defined at <ipython-input-59-68b6396882a7> (14)

File "<ipython-input-59-68b6396882a7>", line 14:
def call(i, j):
<source elided>
if j == 0:
result = Data1(i)
^

[1] During: typing of assignment at <ipython-input-59-68b6396882a7> (16)

File "<ipython-input-59-68b6396882a7>", line 16:
def call(i, j):
<source elided>
else:
result = Data2(i, j)
^

# Fixed code
def from_types(cls, tys, pyclass=None):
    """
    Instantiate the right tuple type for the given element types.
    """
    if pyclass is not None and pyclass is not tuple:
        # A subclass => is it a namedtuple?
        assert issubclass(pyclass, tuple)
        if hasattr(pyclass, "_asdict"):
            tys = tuple(map(unliteral, tys))
            homogeneous = is_homogeneous(*tys)
            if homogeneous:
                return NamedUniTuple(tys[0], len(tys), pyclass)
            else:
                return NamedTuple(tys, pyclass)
    else:
        # non-named tuple
        homogeneous = is_homogeneous(*tys)
        if homogeneous:
            return UniTuple(tys[0], len(tys))
        else:
            return Tuple(tys)
# Buggy code
def __init__(
    self,
    native,
    modname,
    qualname,
    unique_name,
    doc,
    typemap,
    restype,
    calltypes,
    args,
    kws,
    mangler=None,
    argtypes=None,
    inline=False,
    noalias=False,
    env_name=None,
):
    self.native = native
    self.modname = modname
    self.qualname = qualname
    self.unique_name = unique_name
    self.doc = doc
    # XXX typemap and calltypes should be on the compile result,
    # not the FunctionDescriptor
    self.typemap = typemap
    self.calltypes = calltypes
    self.args = args
    self.kws = kws
    self.restype = restype
    # Argument types
    if argtypes is not None:
        assert isinstance(argtypes, tuple), argtypes
        self.argtypes = argtypes
    else:
        # Get argument types from the type inference result
        # (note the "arg.FOO" convention as used in typeinfer
        self.argtypes = tuple(self.typemap["arg." + a] for a in args)
    mangler = default_mangler if mangler is None else mangler
    # The mangled name *must* be unique, else the wrong function can
    # be chosen at link time.
    qualprefix = qualifying_prefix(self.modname, self.unique_name)
    self.mangled_name = mangler(qualprefix, self.argtypes)
    if env_name is None:
        env_name = mangler(".NumbaEnv.{}".format(qualprefix), self.argtypes)
    self.env_name = env_name
    self.inline = inline
    self.noalias = noalias


# Traceback (NameError)
Traceback (most recent call last):
File "tmp_tests/obj_gen_test.py", line 14, in <module>
g()
NameError: global name 'np' is not defined

# Fixed code
def __init__(
    self,
    native,
    modname,
    qualname,
    unique_name,
    doc,
    typemap,
    restype,
    calltypes,
    args,
    kws,
    mangler=None,
    argtypes=None,
    inline=False,
    noalias=False,
    env_name=None,
    global_dict=None,
):
    self.native = native
    self.modname = modname
    self.global_dict = global_dict
    self.qualname = qualname
    self.unique_name = unique_name
    self.doc = doc
    # XXX typemap and calltypes should be on the compile result,
    # not the FunctionDescriptor
    self.typemap = typemap
    self.calltypes = calltypes
    self.args = args
    self.kws = kws
    self.restype = restype
    # Argument types
    if argtypes is not None:
        assert isinstance(argtypes, tuple), argtypes
        self.argtypes = argtypes
    else:
        # Get argument types from the type inference result
        # (note the "arg.FOO" convention as used in typeinfer
        self.argtypes = tuple(self.typemap["arg." + a] for a in args)
    mangler = default_mangler if mangler is None else mangler
    # The mangled name *must* be unique, else the wrong function can
    # be chosen at link time.
    qualprefix = qualifying_prefix(self.modname, self.unique_name)
    self.mangled_name = mangler(qualprefix, self.argtypes)
    if env_name is None:
        env_name = mangler(".NumbaEnv.{}".format(qualprefix), self.argtypes)
    self.env_name = env_name
    self.inline = inline
    self.noalias = noalias
# Buggy code
def _get_function_info(cls, func_ir):
    """
    Returns
    -------
    qualname, unique_name, modname, doc, args, kws, globals

    ``unique_name`` must be a unique name.
    """
    func = func_ir.func_id.func
    qualname = func_ir.func_id.func_qualname
    # XXX to func_id
    modname = func.__module__
    doc = func.__doc__ or ""
    args = tuple(func_ir.arg_names)
    kws = ()  # TODO

    if modname is None:
        # Dynamically generated function.
        modname = _dynamic_modname

    unique_name = func_ir.func_id.unique_name

    return qualname, unique_name, modname, doc, args, kws


# Traceback (NameError)
Traceback (most recent call last):
File "tmp_tests/obj_gen_test.py", line 14, in <module>
g()
NameError: global name 'np' is not defined

# Fixed code
def _get_function_info(cls, func_ir):
    """
    Returns
    -------
    qualname, unique_name, modname, doc, args, kws, globals

    ``unique_name`` must be a unique name.
    """
    func = func_ir.func_id.func
    qualname = func_ir.func_id.func_qualname
    # XXX to func_id
    modname = func.__module__
    doc = func.__doc__ or ""
    args = tuple(func_ir.arg_names)
    kws = ()  # TODO
    global_dict = None

    if modname is None:
        # Dynamically generated function.
        modname = _dynamic_modname
        # Retain a reference to the dictionary of the function.
        # This disables caching, serialization and pickling.
        global_dict = func_ir.func_id.func.__globals__

    unique_name = func_ir.func_id.unique_name

    return qualname, unique_name, modname, doc, args, kws, global_dict
# Buggy code
def _from_python_function(
    cls,
    func_ir,
    typemap,
    restype,
    calltypes,
    native,
    mangler=None,
    inline=False,
    noalias=False,
):
    (
        qualname,
        unique_name,
        modname,
        doc,
        args,
        kws,
    ) = cls._get_function_info(func_ir)
    self = cls(
        native,
        modname,
        qualname,
        unique_name,
        doc,
        typemap,
        restype,
        calltypes,
        args,
        kws,
        mangler=mangler,
        inline=inline,
        noalias=noalias,
    )
    return self


# Traceback (NameError)
Traceback (most recent call last):
File "tmp_tests/obj_gen_test.py", line 14, in <module>
g()
NameError: global name 'np' is not defined

# Fixed code
def _from_python_function(
    cls,
    func_ir,
    typemap,
    restype,
    calltypes,
    native,
    mangler=None,
    inline=False,
    noalias=False,
):
    (
        qualname,
        unique_name,
        modname,
        doc,
        args,
        kws,
        global_dict,
    ) = cls._get_function_info(func_ir)

    self = cls(
        native,
        modname,
        qualname,
        unique_name,
        doc,
        typemap,
        restype,
        calltypes,
        args,
        kws,
        mangler=mangler,
        inline=inline,
        noalias=noalias,
        global_dict=global_dict,
    )
    return self
# Buggy code
def from_fndesc(cls, fndesc):
    mod = fndesc.lookup_module()
    try:
        # Avoid creating new Env
        return cls._memo[fndesc.env_name]
    except KeyError:
        inst = cls(mod.__dict__)
        inst.env_name = fndesc.env_name
        cls._memo[fndesc.env_name] = inst
        return inst


# Traceback (NameError)
Traceback (most recent call last):
File "tmp_tests/obj_gen_test.py", line 14, in <module>
g()
NameError: global name 'np' is not defined

# Fixed code
def from_fndesc(cls, fndesc):
    try:
        # Avoid creating new Env
        return cls._memo[fndesc.env_name]
    except KeyError:
        inst = cls(fndesc.lookup_globals())
        inst.env_name = fndesc.env_name
        cls._memo[fndesc.env_name] = inst
        return inst
# Buggy code
def from_cuda_array_interface(desc, owner=None):
    """Create a DeviceNDArray from a cuda-array-interface description.
    The *owner* is the owner of the underlying memory.
    The resulting DeviceNDArray will acquire a reference from it.
    """
    shape = desc["shape"]
    strides = desc.get("strides")
    dtype = np.dtype(desc["typestr"])

    shape, strides, dtype = _prepare_shape_strides_dtype(
        shape, strides, dtype, order="C"
    )

    devptr = driver.get_devptr_for_active_ctx(desc["data"][0])
    data = driver.MemoryPointer(
        current_context(), devptr, size=np.prod(shape) * dtype.itemsize, owner=owner
    )
    da = devicearray.DeviceNDArray(
        shape=shape, strides=strides, dtype=dtype, gpu_data=data
    )
    return da


# Traceback (AttributeError)
$ python repro_indexing.py
Traceback (most recent call last):
File "repro_indexing.py", line 8, in <module>
ext_arrslice = ext_arr[:5]
File "/scratch/USERS/fordas/workspace/numba_min/.conda/lib/python3.7/site-packages/numba/cuda/cudadrv/devices.py", line 212, in _require_cuda_context
return fn(*args, **kws)
File "/scratch/USERS/fordas/workspace/numba_min/.conda/lib/python3.7/site-packages/numba/cuda/cudadrv/devicearray.py", line 468, in __getitem__
return self._do_getitem(item)
File "/scratch/USERS/fordas/workspace/numba_min/.conda/lib/python3.7/site-packages/numba/cuda/cudadrv/devicearray.py", line 482, in _do_getitem
newdata = self.gpu_data.view(*extents[0])
File "/scratch/USERS/fordas/workspace/numba_min/.conda/lib/python3.7/site-packages/numba/cuda/cudadrv/driver.py", line 1214, in view
return OwnedPointer(weakref.proxy(self.owner), view)
File "/scratch/USERS/fordas/workspace/numba_min/.conda/lib/python3.7/site-packages/numba/cuda/cudadrv/driver.py", line 1298, in __init__
self._mem.refct += 1
AttributeError: 'DeviceNDArray' object has no attribute 'refct'

# Fixed code
def from_cuda_array_interface(desc, owner=None):
    """Create a DeviceNDArray from a cuda-array-interface description.
    The *owner* is the owner of the underlying memory.
    The resulting DeviceNDArray will acquire a reference from it.
    """
    shape = desc["shape"]
    strides = desc.get("strides")
    dtype = np.dtype(desc["typestr"])

    shape, strides, dtype = _prepare_shape_strides_dtype(
        shape, strides, dtype, order="C"
    )
    size = driver.memory_size_from_info(shape, strides, dtype.itemsize)

    devptr = driver.get_devptr_for_active_ctx(desc["data"][0])
    data = driver.MemoryPointer(current_context(), devptr, size=size, owner=owner)
    da = devicearray.DeviceNDArray(
        shape=shape, strides=strides, dtype=dtype, gpu_data=data
    )
    return da
# Buggy code
def view(self, start, stop=None):
    if stop is None:
        size = self.size - start
    else:
        size = stop - start

    # Handle NULL/empty memory buffer
    if self.device_pointer.value is None:
        if size != 0:
            raise RuntimeError("non-empty slice into empty slice")
        view = self  # new view is just a reference to self
    # Handle normal case
    else:
        base = self.device_pointer.value + start
        if size < 0:
            raise RuntimeError("size cannot be negative")
        pointer = drvapi.cu_device_ptr(base)
        view = MemoryPointer(self.context, pointer, size, owner=self.owner)
    return OwnedPointer(weakref.proxy(self.owner), view)


# Traceback (AttributeError)
$ python repro_indexing.py
Traceback (most recent call last):
File "repro_indexing.py", line 8, in <module>
ext_arrslice = ext_arr[:5]
File "/scratch/USERS/fordas/workspace/numba_min/.conda/lib/python3.7/site-packages/numba/cuda/cudadrv/devices.py", line 212, in _require_cuda_context
return fn(*args, **kws)
File "/scratch/USERS/fordas/workspace/numba_min/.conda/lib/python3.7/site-packages/numba/cuda/cudadrv/devicearray.py", line 468, in __getitem__
return self._do_getitem(item)
File "/scratch/USERS/fordas/workspace/numba_min/.conda/lib/python3.7/site-packages/numba/cuda/cudadrv/devicearray.py", line 482, in _do_getitem
newdata = self.gpu_data.view(*extents[0])
File "/scratch/USERS/fordas/workspace/numba_min/.conda/lib/python3.7/site-packages/numba/cuda/cudadrv/driver.py", line 1214, in view
return OwnedPointer(weakref.proxy(self.owner), view)
File "/scratch/USERS/fordas/workspace/numba_min/.conda/lib/python3.7/site-packages/numba/cuda/cudadrv/driver.py", line 1298, in __init__
self._mem.refct += 1
AttributeError: 'DeviceNDArray' object has no attribute 'refct'

# Fixed code
def view(self, start, stop=None):
    if stop is None:
        size = self.size - start
    else:
        size = stop - start

    # Handle NULL/empty memory buffer
    if self.device_pointer.value is None:
        if size != 0:
            raise RuntimeError("non-empty slice into empty slice")
        view = self  # new view is just a reference to self
    # Handle normal case
    else:
        base = self.device_pointer.value + start
        if size < 0:
            raise RuntimeError("size cannot be negative")
        pointer = drvapi.cu_device_ptr(base)
        view = MemoryPointer(self.context, pointer, size, owner=self.owner)

    if isinstance(self.owner, (MemoryPointer, OwnedPointer)):
        # Owned by a numba-managed memory segment, take an owned reference
        return OwnedPointer(weakref.proxy(self.owner), view)
    else:
        # Owned by external alloc, return view with same external owner
        return view
# Buggy code
def min_parallel_impl(return_type, arg):
    # XXX: use prange for 1D arrays since pndindex returns a 1-tuple instead of
    # integer. This causes type and fusion issues.
    if arg.ndim == 1:

        def min_1(in_arr):
            numba.parfor.init_prange()
            val = numba.targets.builtins.get_type_max_value(in_arr.dtype)
            for i in numba.parfor.internal_prange(len(in_arr)):
                val = min(val, in_arr[i])
            return val
    else:

        def min_1(in_arr):
            numba.parfor.init_prange()
            val = numba.targets.builtins.get_type_max_value(in_arr.dtype)
            for i in numba.pndindex(in_arr.shape):
                val = min(val, in_arr[i])
            return val

    return min_1


# Traceback (ValueError)
In [324]: def test_0d_min(X):
...:     return np.min(X)
...:
...:

In [325]: test_0d_min(np.array([]))  # correct behavior
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
... (omitted)
ValueError: zero-size array to reduction operation minimum which has no identity

In [326]: nb.jit(test_0d_min)(np.array([]))  # incorrect
Out[326]: 0.0

In [328]: nb.jit(test_0d_min, parallel=True)(np.array([]))  # incorrect
Out[328]: 1.7976931348623157e+308

# Fixed code
def min_parallel_impl(return_type, arg):
    # XXX: use prange for 1D arrays since pndindex returns a 1-tuple instead of
    # integer. This causes type and fusion issues.
    if arg.ndim == 1:

        def min_1(in_arr):
            numba.parfor.init_prange()
            min_checker(len(in_arr))
            val = numba.targets.builtins.get_type_max_value(in_arr.dtype)
            for i in numba.parfor.internal_prange(len(in_arr)):
                val = min(val, in_arr[i])
            return val
    else:

        def min_1(in_arr):
            numba.parfor.init_prange()
            min_checker(len(in_arr))
            val = numba.targets.builtins.get_type_max_value(in_arr.dtype)
            for i in numba.pndindex(in_arr.shape):
                val = min(val, in_arr[i])
            return val

    return min_1
# Buggy code
def min_1(in_arr):
    numba.parfor.init_prange()
    val = numba.targets.builtins.get_type_max_value(in_arr.dtype)
    for i in numba.pndindex(in_arr.shape):
        val = min(val, in_arr[i])
    return val


# Traceback (ValueError)
In [324]: def test_0d_min(X):
...:     return np.min(X)
...:
...:

In [325]: test_0d_min(np.array([]))  # correct behavior
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
... (omitted)
ValueError: zero-size array to reduction operation minimum which has no identity

In [326]: nb.jit(test_0d_min)(np.array([]))  # incorrect
Out[326]: 0.0

In [328]: nb.jit(test_0d_min, parallel=True)(np.array([]))  # incorrect
Out[328]: 1.7976931348623157e+308

# Fixed code
def min_1(in_arr):
    numba.parfor.init_prange()
    min_checker(len(in_arr))
    val = numba.targets.builtins.get_type_max_value(in_arr.dtype)
    for i in numba.pndindex(in_arr.shape):
        val = min(val, in_arr[i])
    return val
# Buggy code
def max_parallel_impl(return_type, arg):
    if arg.ndim == 1:

        def max_1(in_arr):
            numba.parfor.init_prange()
            val = numba.targets.builtins.get_type_min_value(in_arr.dtype)
            for i in numba.parfor.internal_prange(len(in_arr)):
                val = max(val, in_arr[i])
            return val
    else:

        def max_1(in_arr):
            numba.parfor.init_prange()
            val = numba.targets.builtins.get_type_min_value(in_arr.dtype)
            for i in numba.pndindex(in_arr.shape):
                val = max(val, in_arr[i])
            return val

    return max_1


# Traceback (ValueError)
In [324]: def test_0d_min(X):
...:     return np.min(X)
...:
...:

In [325]: test_0d_min(np.array([]))  # correct behavior
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
... (omitted)
ValueError: zero-size array to reduction operation minimum which has no identity

In [326]: nb.jit(test_0d_min)(np.array([]))  # incorrect
Out[326]: 0.0

In [328]: nb.jit(test_0d_min, parallel=True)(np.array([]))  # incorrect
Out[328]: 1.7976931348623157e+308

# Fixed code
def max_parallel_impl(return_type, arg):
    if arg.ndim == 1:

        def max_1(in_arr):
            numba.parfor.init_prange()
            max_checker(len(in_arr))
            val = numba.targets.builtins.get_type_min_value(in_arr.dtype)
            for i in numba.parfor.internal_prange(len(in_arr)):
                val = max(val, in_arr[i])
            return val
    else:

        def max_1(in_arr):
            numba.parfor.init_prange()
            max_checker(len(in_arr))
            val = numba.targets.builtins.get_type_min_value(in_arr.dtype)
            for i in numba.pndindex(in_arr.shape):
                val = max(val, in_arr[i])
            return val

    return max_1
# Buggy code
def max_1(in_arr):
    numba.parfor.init_prange()
    val = numba.targets.builtins.get_type_min_value(in_arr.dtype)
    for i in numba.pndindex(in_arr.shape):
        val = max(val, in_arr[i])
    return val


# Traceback (ValueError)
In [324]: def test_0d_min(X):
...:     return np.min(X)
...:
...:

In [325]: test_0d_min(np.array([]))  # correct behavior
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
... (omitted)
ValueError: zero-size array to reduction operation minimum which has no identity

In [326]: nb.jit(test_0d_min)(np.array([]))  # incorrect
Out[326]: 0.0

In [328]: nb.jit(test_0d_min, parallel=True)(np.array([]))  # incorrect
Out[328]: 1.7976931348623157e+308

# Fixed code
def max_1(in_arr):
    numba.parfor.init_prange()
    max_checker(len(in_arr))
    val = numba.targets.builtins.get_type_min_value(in_arr.dtype)
    for i in numba.pndindex(in_arr.shape):
        val = max(val, in_arr[i])
    return val
# Buggy code
def argmin_parallel_impl(in_arr):
    numba.parfor.init_prange()
    A = in_arr.ravel()
    init_val = numba.targets.builtins.get_type_max_value(A.dtype)
    ival = numba.typing.builtins.IndexValue(0, init_val)
    for i in numba.parfor.internal_prange(len(A)):
        curr_ival = numba.typing.builtins.IndexValue(i, A[i])
        ival = min(ival, curr_ival)
    return ival.index


# Traceback (ValueError)
In [324]: def test_0d_min(X):
...:     return np.min(X)
...:
...:

In [325]: test_0d_min(np.array([]))  # correct behavior
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
... (omitted)
ValueError: zero-size array to reduction operation minimum which has no identity

In [326]: nb.jit(test_0d_min)(np.array([]))  # incorrect
Out[326]: 0.0

In [328]: nb.jit(test_0d_min, parallel=True)(np.array([]))  # incorrect
Out[328]: 1.7976931348623157e+308

# Fixed code
def argmin_parallel_impl(in_arr):
    numba.parfor.init_prange()
    argmin_checker(len(in_arr))
    A = in_arr.ravel()
    init_val = numba.targets.builtins.get_type_max_value(A.dtype)
    ival = numba.typing.builtins.IndexValue(0, init_val)
    for i in numba.parfor.internal_prange(len(A)):
        curr_ival = numba.typing.builtins.IndexValue(i, A[i])
        ival = min(ival, curr_ival)
    return ival.index
# Buggy code
def argmax_parallel_impl(in_arr):
    numba.parfor.init_prange()
    A = in_arr.ravel()
    init_val = numba.targets.builtins.get_type_min_value(A.dtype)
    ival = numba.typing.builtins.IndexValue(0, init_val)
    for i in numba.parfor.internal_prange(len(A)):
        curr_ival = numba.typing.builtins.IndexValue(i, A[i])
        ival = max(ival, curr_ival)
    return ival.index


# Traceback (ValueError)
In [324]: def test_0d_min(X):
...:     return np.min(X)
...:
...:

In [325]: test_0d_min(np.array([]))  # correct behavior
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
... (omitted)
ValueError: zero-size array to reduction operation minimum which has no identity

In [326]: nb.jit(test_0d_min)(np.array([]))  # incorrect
Out[326]: 0.0

In [328]: nb.jit(test_0d_min, parallel=True)(np.array([]))  # incorrect
Out[328]: 1.7976931348623157e+308

# Fixed code
def argmax_parallel_impl(in_arr):
    numba.parfor.init_prange()
    argmax_checker(len(in_arr))
    A = in_arr.ravel()
    init_val = numba.targets.builtins.get_type_min_value(A.dtype)
    ival = numba.typing.builtins.IndexValue(0, init_val)
    for i in numba.parfor.internal_prange(len(A)):
        curr_ival = numba.typing.builtins.IndexValue(i, A[i])
        ival = max(ival, curr_ival)
    return ival.index
# Buggy code
def replace_func():
    func_def = get_definition(self.func_ir, expr.func)
    callname = find_callname(self.func_ir, expr)
    repl_func = replace_functions_map.get(callname, None)
    require(repl_func != None)
    typs = tuple(self.typemap[x.name] for x in expr.args)
    try:
        new_func = repl_func(lhs_typ, *typs)
    except:
        new_func = None
    require(new_func != None)
    g = copy.copy(self.func_ir.func_id.func.__globals__)
    g["numba"] = numba
    g["np"] = numpy
    g["math"] = math
    # inline the parallel implementation
    inline_closure_call(
        self.func_ir,
        g,
        block,
        i,
        new_func,
        self.typingctx,
        typs,
        self.typemap,
        self.calltypes,
        work_list,
    )
    return True


# Traceback (ValueError)
In [324]: def test_0d_min(X):
...:     return np.min(X)
...:
...:

In [325]: test_0d_min(np.array([]))  # correct behavior
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
... (omitted)
ValueError: zero-size array to reduction operation minimum which has no identity

In [326]: nb.jit(test_0d_min)(np.array([]))  # incorrect
Out[326]: 0.0

In [328]: nb.jit(test_0d_min, parallel=True)(np.array([]))  # incorrect
Out[328]: 1.7976931348623157e+308

# Fixed code
def replace_func():
    func_def = get_definition(self.func_ir, expr.func)
    callname = find_callname(self.func_ir, expr)
    repl_func = replace_functions_map.get(callname, None)
    require(repl_func != None)
    typs = tuple(self.typemap[x.name] for x in expr.args)
    try:
        new_func = repl_func(lhs_typ, *typs)
    except:
        new_func = None
    require(new_func != None)
    g = copy.copy(self.func_ir.func_id.func.__globals__)
    g["numba"] = numba
    g["np"] = numpy
    g["math"] = math
    # if the function being inlined has a function
    # checking the inputs, find it and add it to globals
    check = replace_functions_checkers_map.get(callname, None)
    if check is not None:
        g[check.name] = check.func
    # inline the parallel implementation
    inline_closure_call(
        self.func_ir,
        g,
        block,
        i,
        new_func,
        self.typingctx,
        typs,
        self.typemap,
        self.calltypes,
        work_list,
    )
    return True
# Buggy code
def array_min_impl(arry):
    it = np.nditer(arry)
    for view in it:
        min_value = view.item()
        break

    for view in it:
        v = view.item()
        if v < min_value:
            min_value = v
    return min_value


# Traceback (ValueError)
In [324]: def test_0d_min(X):
...:     return np.min(X)
...:
...:

In [325]: test_0d_min(np.array([]))  # correct behavior
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
... (omitted)
ValueError: zero-size array to reduction operation minimum which has no identity

In [326]: nb.jit(test_0d_min)(np.array([]))  # incorrect
Out[326]: 0.0

In [328]: nb.jit(test_0d_min, parallel=True)(np.array([]))  # incorrect
Out[328]: 1.7976931348623157e+308

# Fixed code
def array_min_impl(arry):
    if arry.size == 0:
        raise ValueError(
            ("zero-size array to reduction operation minimum which has no identity")
        )
    it = np.nditer(arry)
    for view in it:
        min_value = view.item()
        break

    for view in it:
        v = view.item()
        if v < min_value:
            min_value = v
    return min_value
# Buggy code
def array_max(context, builder, sig, args):
    def array_max_impl(arry):
        it = np.nditer(arry)
        for view in it:
            max_value = view.item()
            break

        for view in it:
            v = view.item()
            if v > max_value:
                max_value = v
        return max_value

    res = context.compile_internal(builder, array_max_impl, sig, args)
    return impl_ret_borrowed(context, builder, sig.return_type, res)


# Traceback (ValueError)
In [324]: def test_0d_min(X):
...:     return np.min(X)
...:
...:

In [325]: test_0d_min(np.array([]))  # correct behavior
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
... (omitted)
ValueError: zero-size array to reduction operation minimum which has no identity

In [326]: nb.jit(test_0d_min)(np.array([]))  # incorrect
Out[326]: 0.0

In [328]: nb.jit(test_0d_min, parallel=True)(np.array([]))  # incorrect
Out[328]: 1.7976931348623157e+308

# Fixed code
def array_max(context, builder, sig, args):
    def array_max_impl(arry):
        if arry.size == 0:
            raise ValueError(
                ("zero-size array to reduction operation maximum which has no identity")
            )
        it = np.nditer(arry)
        for view in it:
            max_value = view.item()
            break

        for view in it:
            v = view.item()
            if v > max_value:
                max_value = v
        return max_value

    res = context.compile_internal(builder, array_max_impl, sig, args)
    return impl_ret_borrowed(context, builder, sig.return_type, res)
# Buggy code
def array_max_impl(arry):
    it = np.nditer(arry)
    for view in it:
        max_value = view.item()
        break

    for view in it:
        v = view.item()
        if v > max_value:
            max_value = v
    return max_value


# Traceback (ValueError)
In [324]: def test_0d_min(X):
...:     return np.min(X)
...:
...:

In [325]: test_0d_min(np.array([]))  # correct behavior
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
... (omitted)
ValueError: zero-size array to reduction operation minimum which has no identity

In [326]: nb.jit(test_0d_min)(np.array([]))  # incorrect
Out[326]: 0.0

In [328]: nb.jit(test_0d_min, parallel=True)(np.array([]))  # incorrect
Out[328]: 1.7976931348623157e+308

# Fixed code
def array_max_impl(arry):
    if arry.size == 0:
        raise ValueError(
            ("zero-size array to reduction operation maximum which has no identity")
        )
    it = np.nditer(arry)
    for view in it:
        max_value = view.item()
        break

    for view in it:
        v = view.item()
        if v > max_value:
            max_value = v
    return max_value
# Buggy code
def array_argmin_impl(arry):
    for v in arry.flat:
        min_value = v
        min_idx = 0
        break

    idx = 0
    for v in arry.flat:
        if v < min_value:
            min_value = v
            min_idx = idx
        idx += 1
    return min_idx


# Traceback (ValueError)
In [324]: def test_0d_min(X):
...:     return np.min(X)
...:
...:

In [325]: test_0d_min(np.array([]))  # correct behavior
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
... (omitted)
ValueError: zero-size array to reduction operation minimum which has no identity

In [326]: nb.jit(test_0d_min)(np.array([]))  # incorrect
Out[326]: 0.0

In [328]: nb.jit(test_0d_min, parallel=True)(np.array([]))  # incorrect
Out[328]: 1.7976931348623157e+308

# Fixed code
def array_argmin_impl(arry):
    if arry.size == 0:
        raise ValueError("attempt to get argmin of an empty sequence")
    for v in arry.flat:
        min_value = v
        min_idx = 0
        break

    idx = 0
    for v in arry.flat:
        if v < min_value:
            min_value = v
            min_idx = idx
        idx += 1
    return min_idx
# Buggy code
def array_argmax(context, builder, sig, args):
    def array_argmax_impl(arry):
        for v in arry.flat:
            max_value = v
            max_idx = 0
            break

        idx = 0
        for v in arry.flat:
            if v > max_value:
                max_value = v
                max_idx = idx
            idx += 1
        return max_idx

    res = context.compile_internal(builder, array_argmax_impl, sig, args)
    return impl_ret_untracked(context, builder, sig.return_type, res)


# Traceback (ValueError)
In [324]: def test_0d_min(X):
...:     return np.min(X)
...:
...:

In [325]: test_0d_min(np.array([]))  # correct behavior
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
... (omitted)
ValueError: zero-size array to reduction operation minimum which has no identity

In [326]: nb.jit(test_0d_min)(np.array([]))  # incorrect
Out[326]: 0.0

In [328]: nb.jit(test_0d_min, parallel=True)(np.array([]))  # incorrect
Out[328]: 1.7976931348623157e+308

# Fixed code
def array_argmax(context, builder, sig, args):
    def array_argmax_impl(arry):
        if arry.size == 0:
            raise ValueError("attempt to get argmax of an empty sequence")
        for v in arry.flat:
            max_value = v
            max_idx = 0
            break

        idx = 0
        for v in arry.flat:
            if v > max_value:
                max_value = v
                max_idx = idx
            idx += 1
        return max_idx

    res = context.compile_internal(builder, array_argmax_impl, sig, args)
    return impl_ret_untracked(context, builder, sig.return_type, res)
# Buggy code
def array_argmax_impl(arry):
    for v in arry.flat:
        max_value = v
        max_idx = 0
        break

    idx = 0
    for v in arry.flat:
        if v > max_value:
            max_value = v
            max_idx = idx
        idx += 1
    return max_idx


# Traceback (ValueError)
In [324]: def test_0d_min(X):
...:     return np.min(X)
...:
...:

In [325]: test_0d_min(np.array([]))  # correct behavior
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
... (omitted)
ValueError: zero-size array to reduction operation minimum which has no identity

In [326]: nb.jit(test_0d_min)(np.array([]))  # incorrect
Out[326]: 0.0

In [328]: nb.jit(test_0d_min, parallel=True)(np.array([]))  # incorrect
Out[328]: 1.7976931348623157e+308

# Fixed code
def array_argmax_impl(arry):
    if arry.size == 0:
        raise ValueError("attempt to get argmax of an empty sequence")
    for v in arry.flat:
        max_value = v
        max_idx = 0
        break

    idx = 0
    for v in arry.flat:
        if v > max_value:
            max_value = v
            max_idx = idx
        idx += 1
    return max_idx
# Buggy code
def find_potential_aliases_parfor(parfor, args, typemap, alias_map, arg_aliases):
    blocks = wrap_parfor_blocks(parfor)
    ir_utils.find_potential_aliases(blocks, args, typemap, alias_map, arg_aliases)
    unwrap_parfor_blocks(parfor)
    return


# Traceback (LoweringError)
Serial:
[ 0  1  2  3  4 15 16 17 18 19]

Parallel:
Parallel for-loop #0 is produced from pattern '('prange', 'user')' at <ipython-input-1-f9ca7dd40116> (18)
After fusion, function parallel has 1 parallel for-loop(s) #set([0]).

---------------------------------------------------------------------------
LoweringError                             Traceback (most recent call last)
<ipython-input-1-f9ca7dd40116> in <module>()
27 print('\nParallel:')
28 A = np.arange(10)
---> 29 parallel(A)
30 print(A)

/home/lgarrison/anaconda2/lib/python2.7/site-packages/numba/dispatcher.pyc in _compile_for_args(self, *args, **kws)
358                     e.patch_message(''.join(e.args) + help_msg)
359             # ignore the FULL_TRACEBACKS config, this needs reporting!
--> 360             raise e
361
362     def inspect_llvm(self, signature=None):

LoweringError: Failed at nopython (nopython mode backend)
Failed at nopython (nopython mode backend)
expecting {{i8*, i8*, i64, i64, i64*, [1 x i64], [1 x i64]}, i64, i64*} but got i8*

File "<ipython-input-1-f9ca7dd40116>", line 18:
def parallel(A):
<source elided>
N = len(A)
for i in numba.prange(N):
^
[1] During: lowering "id=0[LoopNest(index_variable = parfor_index.2, range = (0, $N.4, 1))]{40: <ir.Block at <ipython-input-1-f9ca7dd40116> (18)>, 81: <ir.Block at <ipython-input-1-f9ca7dd40116> (18)>, 59: <ir.Block at <ipython-input-1-f9ca7dd40116> (19)>}Var(parfor_index.2, <ipython-input-1-f9ca7dd40116> (18))" at <ipython-input-1-f9ca7dd40116> (18)
-------------------------------------------------------------------------------
This should not have happened, a problem has occurred in Numba's internals.

Please report the error message and traceback, along with a minimal reproducer
at: https://github.com/numba/numba/issues/new

If you need help writing a minimal reproducer please see:
http://matthewrocklin.com/blog/work/2018/02/28/minimal-bug-reports

If more help is needed please feel free to speak to the Numba core developers
directly at: https://gitter.im/numba/numba

Thanks in advance for your help in improving Numba!

# Fixed code
def find_potential_aliases_parfor(
    parfor, args, typemap, func_ir, alias_map, arg_aliases
):
    blocks = wrap_parfor_blocks(parfor)
    ir_utils.find_potential_aliases(
        blocks, args, typemap, func_ir, alias_map, arg_aliases
    )
    unwrap_parfor_blocks(parfor)
    return
# Buggy code
def build_parfor_definitions(parfor, definitions=None):
    """get variable definition table for parfors"""
    if definitions is None:
        definitions = dict()

    blocks = wrap_parfor_blocks(parfor)
    build_definitions(blocks, definitions)
    unwrap_parfor_blocks(parfor)
    return definitions


# Traceback (LoweringError)
Serial:
[ 0  1  2  3  4 15 16 17 18 19]

Parallel:
Parallel for-loop #0 is produced from pattern '('prange', 'user')' at <ipython-input-1-f9ca7dd40116> (18)
After fusion, function parallel has 1 parallel for-loop(s) #set([0]).

---------------------------------------------------------------------------
LoweringError                             Traceback (most recent call last)
<ipython-input-1-f9ca7dd40116> in <module>()
27 print('\nParallel:')
28 A = np.arange(10)
---> 29 parallel(A)
30 print(A)

/home/lgarrison/anaconda2/lib/python2.7/site-packages/numba/dispatcher.pyc in _compile_for_args(self, *args, **kws)
358                     e.patch_message(''.join(e.args) + help_msg)
359             # ignore the FULL_TRACEBACKS config, this needs reporting!
--> 360             raise e
361
362     def inspect_llvm(self, signature=None):

LoweringError: Failed at nopython (nopython mode backend)
Failed at nopython (nopython mode backend)
expecting {{i8*, i8*, i64, i64, i64*, [1 x i64], [1 x i64]}, i64, i64*} but got i8*

File "<ipython-input-1-f9ca7dd40116>", line 18:
def parallel(A):
<source elided>
N = len(A)
for i in numba.prange(N):
^
[1] During: lowering "id=0[LoopNest(index_variable = parfor_index.2, range = (0, $N.4, 1))]{40: <ir.Block at <ipython-input-1-f9ca7dd40116> (18)>, 81: <ir.Block at <ipython-input-1-f9ca7dd40116> (18)>, 59: <ir.Block at <ipython-input-1-f9ca7dd40116> (19)>}Var(parfor_index.2, <ipython-input-1-f9ca7dd40116> (18))" at <ipython-input-1-f9ca7dd40116> (18)
-------------------------------------------------------------------------------
This should not have happened, a problem has occurred in Numba's internals.

Please report the error message and traceback, along with a minimal reproducer
at: https://github.com/numba/numba/issues/new

If you need help writing a minimal reproducer please see:
http://matthewrocklin.com/blog/work/2018/02/28/minimal-bug-reports

If more help is needed please feel free to speak to the Numba core developers
directly at: https://gitter.im/numba/numba

Thanks in advance for your help in improving Numba!

# Fixed code
def build_parfor_definitions(parfor, definitions=None):
    """get variable definition table for parfors"""
    if definitions is None:
        definitions = defaultdict(list)

    # avoid wrap_parfor_blocks() since build_definitions is called inside
    # find_potential_aliases_parfor where the parfor is already wrapped
    build_definitions(parfor.loop_body, definitions)
    build_definitions({0: parfor.init_block}, definitions)
    return definitions