How to use the llvmlite.ir.IRBuilder function in llvmlite

To help you get started, we’ve selected a few llvmlite examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github PrincetonUniversity / PsyNeuLink / tests / llvm / matmul.py View on Github external
start = timeit.default_timer()

with pnlvm.LLVMBuilderContext() as ctx:
    double_ptr_ty = ctx.float_ty.as_pointer()
    func_ty = ir.FunctionType(ir.VoidType(), (double_ptr_ty, double_ptr_ty, double_ptr_ty))

    # get builtin IR
    builtin = ctx.get_llvm_function('__pnl_builtin_vxm')

    # Create square vector matrix multiply
    function = ir.Function(ctx.module, func_ty, name="vxsqm")
    _x = ctx.int32_ty(x)
    _y = ctx.int32_ty(y)
    _v, _m, _o = function.args
    block = function.append_basic_block(name="entry")
    builder = ir.IRBuilder(block)
    builder.call(builtin, [_v, _m, _x, _y, _o])
    builder.ret_void()

# This triggers recompile if needed so it should be included in the measurement
binf2 = pnlvm.LLVMBinaryFunction.get('vxsqm')
stop = timeit.default_timer()
print("Build time elapsed {:f}".format(stop-start))

start = timeit.default_timer()
for _ in range(ITERATIONS):
    binf2(ct_vec, ct_mat, ct_res)
stop = timeit.default_timer()
print("LLVM-custom time elapsed {:f}".format(stop-start))

# Use all close to ignore rounding errors
if not np.allclose(llvm_res, result):
github numba / numba / numba / datamodel / testing.py View on Github external
def test_as_arg(self):
        """
        - Is as_arg() and from_arg() implemented?
        - Are they the inverse of each other?
        """
        fnty = ir.FunctionType(ir.VoidType(), [])
        function = ir.Function(self.module, fnty, name="test_as_arg")
        builder = ir.IRBuilder()
        builder.position_at_end(function.append_basic_block())

        undef_value = ir.Constant(self.datamodel.get_value_type(), None)
        args = self.datamodel.as_argument(builder, undef_value)
        self.assertIsNot(args, NotImplemented, "as_argument returned "
                                               "NotImplementedError")

        if isinstance(args, (tuple, list)):
            def recur_tuplize(args, func=None):
                for arg in args:
                    if isinstance(arg, (tuple, list)):
                        yield tuple(recur_tuplize(arg, func=func))
                    else:
                        if func is None:
                            yield arg
                        else:
github PurpleMyst / bf_compiler / bf_compiler.py View on Github external
def bf_to_ir(bf):
    ast = parse(bf)

    byte = ir.IntType(8)
    int32 = ir.IntType(32)
    size_t = ir.IntType(64)

    void = ir.VoidType()

    module = ir.Module(name=__file__)
    main_type = ir.FunctionType(int32, ())
    main_func = ir.Function(module, main_type, name="main")
    entry = main_func.append_basic_block(name="entry")

    builder = ir.IRBuilder(entry)

    putchar_type = ir.FunctionType(int32, (int32,))
    putchar = ir.Function(module, putchar_type, name="putchar")

    getchar_type = ir.FunctionType(int32, ())
    getchar = ir.Function(module, getchar_type, name="getchar")

    bzero_type = ir.FunctionType(void, (byte.as_pointer(), size_t))
    bzero = ir.Function(module, bzero_type, name="bzero")

    index_type = ir.IntType(INDEX_BIT_SIZE)
    index = builder.alloca(index_type)
    builder.store(ir.Constant(index_type, 0), index)

    tape_type = byte
    tape = builder.alloca(tape_type, size=2 ** INDEX_BIT_SIZE)
github hassanalinali / Lesma / src / lesma / compiler / builtins.py View on Github external
def dynamic_array_set(self, dyn_array_ptr, array_type):
    # START
    dyn_array_set_type = ir.FunctionType(type_map[VOID], [dyn_array_ptr, type_map[INT], array_type])
    dyn_array_set = ir.Function(self.module, dyn_array_set_type, '{}.array.set'.format(str(array_type)))
    dyn_array_set.args[0].name = 'self'
    dyn_array_set_entry = dyn_array_set.append_basic_block('entry')
    builder = ir.IRBuilder(dyn_array_set_entry)
    self.builder = builder
    dyn_array_set_exit = dyn_array_set.append_basic_block('exit')
    dyn_array_set_index_out_of_bounds = dyn_array_set.append_basic_block('index_out_of_bounds')
    dyn_array_set_is_index_less_than_zero = dyn_array_set.append_basic_block('is_index_less_than_zero')
    dyn_array_set_negative_index = dyn_array_set.append_basic_block('negative_index')
    dyn_array_set_block = dyn_array_set.append_basic_block('set')
    builder.position_at_end(dyn_array_set_entry)
    array_ptr = builder.alloca(dyn_array_ptr)
    builder.store(dyn_array_set.args[0], array_ptr)
    index_ptr = builder.alloca(type_map[INT])
    builder.store(dyn_array_set.args[1], index_ptr)
    value_ptr = builder.alloca(array_type)
    builder.store(dyn_array_set.args[2], value_ptr)

    # BODY
    index_val = builder.load(index_ptr)
github mathics / Mathics / mathics / builtin / compile / ir.py View on Github external
'''
        # assume that the function returns a real. Note that this is verified by
        # looking at the type of the head of the converted expression.
        ret_type = real_type if self._known_ret_type is None else self._known_ret_type

        # create an empty module
        module = ir.Module(name=__file__)

        func_type = ir.FunctionType(ret_type, tuple(arg.type for arg in self.args))

        # declare a function inside the module
        func = ir.Function(module, func_type, name=self.func_name)

        # implement the function
        block = func.append_basic_block(name='entry')
        self.builder = ir.IRBuilder(block)

        self.lookup_args = {arg.name: func_arg for arg, func_arg in zip(self.args, func.args)}

        ir_code = self._gen_ir(self.expr)

        # if the return type isn't correct then try again
        if self._known_ret_type is None:
            # determine the type returned
            if ir_code.type == void_type:
                if self._returned_type is not None:
                    # we returned something so use that type
                    self._known_ret_type = self._returned_type
                    # force generation again in case multiple returns of different types
                    return self.generate_ir()
                else:
                    # actually returned void e.g. Print[]
github hassanalinali / Lesma / src / lesma / compiler / builtins.py View on Github external
def dynamic_array_get(self, dyn_array_ptr, array_type):
    # START
    dyn_array_get_type = ir.FunctionType(array_type, [dyn_array_ptr, type_map[INT]])
    dyn_array_get = ir.Function(self.module, dyn_array_get_type, '{}.array.get'.format(str(array_type)))
    dyn_array_get.args[0].name = 'self'
    dyn_array_get_entry = dyn_array_get.append_basic_block('entry')
    builder = ir.IRBuilder(dyn_array_get_entry)
    self.builder = builder
    dyn_array_get_exit = dyn_array_get.append_basic_block('exit')
    dyn_array_get_index_out_of_bounds = dyn_array_get.append_basic_block('index_out_of_bounds')
    dyn_array_get_is_index_less_than_zero = dyn_array_get.append_basic_block('is_index_less_than_zero')
    dyn_array_get_negative_index = dyn_array_get.append_basic_block('negative_index')
    dyn_array_get_block = dyn_array_get.append_basic_block('get')
    builder.position_at_end(dyn_array_get_entry)
    array_ptr = builder.alloca(dyn_array_ptr)
    builder.store(dyn_array_get.args[0], array_ptr)
    index_ptr = builder.alloca(type_map[INT])
    builder.store(dyn_array_get.args[1], index_ptr)

    # BODY
    index_val = builder.load(index_ptr)
    size_ptr = builder.gep(builder.load(array_ptr), [zero_32, zero_32], inbounds=True)
    size_val = builder.load(size_ptr)
github numba / numba / numba / runtime / nrtdynmod.py View on Github external
def _define_nrt_decref(module, atomic_decr):
    """
    Implement NRT_decref in the module
    """
    fn_decref = module.get_or_insert_function(incref_decref_ty,
                                              name="NRT_decref")
    # Cannot inline this for refcount pruning to work
    fn_decref.attributes.add('noinline')
    calldtor = module.add_function(ir.FunctionType(ir.VoidType(), [_pointer_type]),
                                   name="NRT_MemInfo_call_dtor")

    builder = ir.IRBuilder(fn_decref.append_basic_block())
    [ptr] = fn_decref.args
    is_null = builder.icmp_unsigned("==", ptr, cgutils.get_null_value(ptr.type))
    with cgutils.if_unlikely(builder, is_null):
        builder.ret_void()

    if _debug_print:
        cgutils.printf(builder, "*** NRT_Decref %zu [%p]\n", builder.load(ptr),
                       ptr)
    if binding.get_process_triple().startswith("powerpc"):
        builder.fence("release")
    newrefct = builder.call(atomic_decr,
                            [builder.bitcast(ptr, atomic_decr.args[0].type)])

    refct_eq_0 = builder.icmp_unsigned("==", newrefct,
                                       ir.Constant(newrefct.type, 0))
    with cgutils.if_unlikely(builder, refct_eq_0):
github numba / numba / numba / runtime / nrtdynmod.py View on Github external
def _define_nrt_unresolved_abort(ctx, module):
    """
    Defines an abort function due to unresolved symbol.

    The function takes no args and will always raise an exception.
    It should be safe to call this function with incorrect number of arguments.
    """
    fnty = ctx.call_conv.get_function_type(types.none, ())
    fn = ir.Function(module, fnty, name="nrt_unresolved_abort")
    bb = fn.append_basic_block()
    builder = ir.IRBuilder(bb)
    msg = "numba jitted function aborted due to unresolved symbol"
    ctx.call_conv.return_user_exc(builder, RuntimeError, (msg,))
    return fn
github numba / llvmlite / llvmlite / llvmpy / core.py View on Github external
FCMP_ONE: '!=',
    FCMP_ORD: 'ord',
    }

_fcmp_umap = {
    FCMP_UEQ: '==',
    FCMP_UGT: '>',
    FCMP_UGE: '>=',
    FCMP_ULT: '<',
    FCMP_ULE: '<=',
    FCMP_UNE: '!=',
    FCMP_UNO: 'uno',
    }


class Builder(ir.IRBuilder):

    def icmp(self, pred, lhs, rhs, name=''):
        if pred in _icmp_umap:
            return self.icmp_unsigned(_icmp_umap[pred], lhs, rhs, name=name)
        else:
            return self.icmp_signed(_icmp_smap[pred], lhs, rhs, name=name)

    def fcmp(self, pred, lhs, rhs, name=''):
        if pred in _fcmp_umap:
            return self.fcmp_unordered(_fcmp_umap[pred], lhs, rhs, name=name)
        else:
            return self.fcmp_ordered(_fcmp_omap[pred], lhs, rhs, name=name)


class MetaDataString(ir.MetaDataString):
    @staticmethod