Пример #1
0
def run_tests():
    for name in test_inputs:
        parser = SLRParser("new_grammar.txt", '../testInputs/' + name + '.txt')
        syn_tree = parser.parse()[0]
        syn_tree.genCases(parser.grammar)

        sym_table = SymbolTable()
        named_sym_table = NamedSymbolTable()

        valid = errorCheck(syn_tree, sym_table, named_sym_table,
                           parser.lexer.infileLines)

        llvm_custom_types = create_llvm_types(named_sym_table)
        module = ir.Module(name=name)
        generated_ir = codegen(syn_tree, named_sym_table, {
            'mod': module,
            'llvm_custom_types': llvm_custom_types
        })
        binding.initialize()
        binding.initialize_native_target()
        binding.initialize_native_asmprinter()  # yes, even this one
        binding.load_library_permanently('../runtime.so')

        binding.parse_assembly(str(module), None)
        engine = create_execution_engine()
        mod = compile_ir(engine, str(module))
        test_inputs[name](engine)
Пример #2
0
def JIT(file_name, function_name, args, opt_on=False, verbose=False):
    src = ""
    with open(file_name, "r") as src_file:
        src = src_file.read()
    if (verbose):
        print("Reading source:")
        print(src)

    llvm.initialize()
    llvm.initialize_native_target()
    llvm.initialize_native_asmprinter()
    transformer = pAST.PythonVisitor()
    ast = transformer(src)
    module = ir.Module(name="JITPy")

    #for only 1 arg
    args_in = []
    if (len(args_in) == 1):
        args.append(args)
    else:
        args_in = args

    infer_ty, ret_ty, arg_tys = type_infer(src, ast, function_name, args_in)
    #print(infer_ty)
    ir_module = specialize(ast, infer_ty)
    llvm_ir = str(ir_module)
    if (verbose):
        print(llvm_ir)
    engine = create_execution_engine()
    mod = compile_ir(engine, llvm_ir)
    cfunc = wrap_function(ret_ty, args_in, function_name, engine)
    result = cfunc(*args_in)
    result_str = function_name + "(" + str(args_in) + ")" + " = " + str(result)
    print(result_str)
Пример #3
0
 def setUp(self):
     llvm.initialize()
     llvm.initialize_native_target()
     llvm.initialize_native_asmprinter()
     gc.collect()
     self.old_garbage = gc.garbage[:]
     gc.garbage[:] = []
Пример #4
0
def run(llvm_ir):
    # Load the runtime
    ctypes._dlopen(os.path.join(_path, 'gonert.so'), ctypes.RTLD_GLOBAL)

    # Initialize LLVM
    llvm.initialize()
    llvm.initialize_native_target()
    llvm.initialize_native_asmprinter()

    target = llvm.Target.from_default_triple()
    target_machine = target.create_target_machine()
    mod = llvm.parse_assembly(llvm_ir)
    mod.verify()

    engine = llvm.create_mcjit_compiler(mod, target_machine)

    # Execute the main() function
    #
    # !!! Note: Requires modification in Project 8 (see below)
    # main_ptr = engine.get_function_address('main')
    # main_func = ctypes.CFUNCTYPE(None)(main_ptr)
    # main_func()
    init_ptr = engine.get_function_address('__init')
    init_func = ctypes.CFUNCTYPE(None)(init_ptr)
    init_func()
    main_ptr = engine.get_function_address('_gone_main')
    main_func = ctypes.CFUNCTYPE(None)(main_ptr)
    main_func()
Пример #5
0
def main():
    """Entry point for the CLI."""

    # Tokenize the input:
    file_stream = FileStream(sys.argv[1])  # FIXME: use argparse/click.
    lexer = XLexer(file_stream)
    token_stream = CommonTokenStream(lexer)

    # Parse the program:
    parser = XParser(token_stream)
    tree = parser.program()

    # Compile the code:
    code_generator = CodeGenerator()
    code_generator.visit(tree)

    llvm.initialize()
    llvm.initialize_native_target()
    llvm.initialize_native_asmprinter()

    target = llvm.Target.from_default_triple()
    target_machine = target.create_target_machine()

    backing_module = llvm.parse_assembly('')
    engine = llvm.create_mcjit_compiler(backing_module, target_machine)

    module = llvm.parse_assembly(code_generator.code)
    module.verify()
    engine.add_module(module)
    engine.finalize_object()

    func_ptr = engine.get_function_address('main')
    c_func = CFUNCTYPE(c_int)(func_ptr)
    print(c_func())
Пример #6
0
    def __init__(self):
        llvm.initialize()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()

        self.codegen = LLVMCodeGenerator()
        self.target = llvm.Target.from_default_triple()
Пример #7
0
    def test_inline_asm(self):
        """The InlineAsm class from llvmlite.ir has no 'name' attr the refcount
        pruning pass should be tolerant to this"""
        llvm.initialize()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()
        llvm.initialize_native_asmparser()

        @intrinsic
        def bar(tyctx, x, y):
            def codegen(cgctx, builder, sig, args):
                (arg_0, arg_1) = args
                fty = ir.FunctionType(
                    ir.IntType(64),
                    [ir.IntType(64), ir.IntType(64)])
                mul = builder.asm(fty,
                                  "mov $2, $0; imul $1, $0",
                                  "=r,r,r", (arg_0, arg_1),
                                  name="asm_mul",
                                  side_effect=False)
                return impl_ret_untracked(cgctx, builder, sig.return_type, mul)

            return signature(x, x, x), codegen

        @njit(['int64(int64)'])
        def foo(x):
            x += 1
            z = bar(x, 2)
            return z

        self.assertEqual(foo(10), 22)  # expect (10 + 1) * 2 = 22
Пример #8
0
def execute(ir_mod):
    llvm.initialize()
    llvm.initialize_native_target()
    llvm.initialize_native_asmprinter()

    llmod = llvm.parse_assembly(str(ir_mod))

    print('optimized'.center(80, '-'))
    pmb = llvm.create_pass_manager_builder()
    pmb.opt_level = 1
    pm = llvm.create_module_pass_manager()
    pmb.populate(pm)
    pm.run(llmod)
    print(llmod)

    target_machine = llvm.Target.from_default_triple().create_target_machine()

    with llvm.create_mcjit_compiler(llmod, target_machine) as ee:
        ee.finalize_object()
        cfptr = ee.get_function_address("entry_fib")

        from ctypes import CFUNCTYPE, c_int

        cfunc = CFUNCTYPE(c_int, c_int)(cfptr)

        # TEST
        for i in range(12):
            res = cfunc(i)
            print('fib({}) = {}'.format(i, res))

        # Get CFG
        ll_fib_more = llmod.get_function('fib_more')
        cfg = llvm.get_function_cfg(ll_fib_more)
        llvm.view_dot_graph(cfg, view=True)
Пример #9
0
def initialize_codegen():
    # init LLVM
    logger.debug('Initialize LLVM bindings')
    binding.initialize()
    binding.initialize_native_target()
    binding.initialize_native_asmparser()
    binding.initialize_native_asmprinter()
Пример #10
0
    def compile_ir(self):
        """
        Execute generated code.
        """
        # initialize the LLVM machine
        # These are all required (apparently)
        llvm.initialize()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()

        # Create engine and attach the generated module
        # Create a target machine representing the host
        target = llvm.Target.from_default_triple()
        target_machine = target.create_target_machine()
        # And an execution engine with an empty backing module
        backing_mod = llvm.parse_assembly("")
        engine = llvm.create_mcjit_compiler(backing_mod, target_machine)

        # Parse our generated module
        mod = llvm.parse_assembly(str(self.module))
        mod.verify()
        # Now add the module and make sure it is ready for execution
        engine.add_module(mod)
        engine.finalize_object()

        # Look up the function pointer (a Python int)
        func_ptr = engine.get_function_address("main")

        # Run the function via ctypes
        c_fn = CFUNCTYPE(c_int)(func_ptr)
        c_fn()
Пример #11
0
    def __init__(self):
        llvm.initialize()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()

        self.target = llvm.Target.from_default_triple()
        self.reset()
Пример #12
0
def initialize_llvm():
    global _llvm_initialized
    if not _llvm_initialized:
        ll.initialize()
        ll.initialize_native_target()
        ll.initialize_native_asmprinter()
        _llvm_initialized = True
Пример #13
0
def run(llvm_ir):
    # Load the runtime
    if os.name != 'nt':
        ctypes._dlopen(os.path.join(_path, 'gonert.so'), ctypes.RTLD_GLOBAL)
    else:
        ctypes._dlopen(os.path.join(_path, 'gonert.dll'), ctypes.RTLD_GLOBAL)

    # Initialize LLVM
    llvm.initialize()
    llvm.initialize_native_target()
    llvm.initialize_native_asmprinter()

    target = llvm.Target.from_default_triple()
    target_machine = target.create_target_machine()
    mod = llvm.parse_assembly(llvm_ir)
    mod.verify()

    engine = llvm.create_mcjit_compiler(mod, target_machine)

    # Execute the main() function
    #
    # !!! Note: Requires modification in Project 8 (see below)

    init_ptr = engine.get_function_address('__init')
    init_func = ctypes.CFUNCTYPE(None)(init_ptr)
    init_func()

    main_ptr = engine.get_function_address('_gone_main')
    main_func = ctypes.CFUNCTYPE(None)(main_ptr)
    main_func()
Пример #14
0
    def test_inline_asm(self):
        """The InlineAsm class from llvmlite.ir has no 'name' attr the refcount
        pruning pass should be tolerant to this"""
        llvm.initialize()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()
        llvm.initialize_native_asmparser()

        @intrinsic
        def bar(tyctx, x, y):
            def codegen(cgctx, builder, sig, args):
                (arg_0, arg_1) = args
                fty = ir.FunctionType(ir.IntType(64), [ir.IntType(64),
                                                       ir.IntType(64)])
                mul = builder.asm(fty, "mov $2, $0; imul $1, $0", "=r,r,r",
                                  (arg_0, arg_1), name="asm_mul",
                                  side_effect=False)
                return impl_ret_untracked(cgctx, builder, sig.return_type, mul)
            return signature(x, x, x), codegen

        @njit(['int64(int64)'])
        def foo(x):
            x += 1
            z = bar(x, 2)
            return z

        self.assertEqual(foo(10), 22) # expect (10 + 1) * 2 = 22
Пример #15
0
def main():
    llvm.initialize()
    llvm.initialize_native_target()
    llvm.initialize_native_asmprinter()

    i64 = ir.IntType(64)

    # int64_t main()
    ftype_main = ir.FunctionType(i64, [])
    module = ir.Module(name='sokoide_module')
    fn_main = ir.Function(module, ftype_main, name="main")
    block = fn_main.append_basic_block(name='entrypoint')

    # function prototype (external linkage implemented in builtin.c) for
    # void write(int64_t)
    ftype_write = ir.FunctionType(ir.VoidType(), [i64])
    fn_write = ir.Function(module, ftype_write, name="write")

    # make a block for main (entrypoint)
    builder = ir.IRBuilder(block)
    # call write(42)
    builder.call(fn_write, (ir.Constant(i64, 42), ), name="write")
    # return 42
    builder.ret(ir.Constant(i64, 42))

    llvm_ir = str(module)
    llvm_ir_parsed = llvm.parse_assembly(llvm_ir)
    with open("out.ll", "w") as f:
        f.write(str(llvm_ir_parsed))
Пример #16
0
    def __init__(self, code):
        self.semantica = Semantica(code)
        self.arvore = self.semantica.ast
        llvm.initialize()
        llvm.initialize_all_targets()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()
        self.module = ir.Module('meu_modulo.bc')
        self.module.triple = llvm.get_process_triple()
        target = llvm.Target.from_triple(self.module.triple)
        target_machine = target.create_target_machine()
        self.module.data_layout = target_machine.target_data

        #llvm.shutdown()
        self.variaveis = []
        self.variaveisGlobais = []
        self.escopo = "global"
        self.funcs = []
        self.andaArvore(self.arvore)
        self.funcllvm = ''
        self.endBlock = ''
        arquivo = open('meu_modulo.ll', 'w')
        arquivo.write(str(self.module))
        arquivo.close()
        print(self.module)
Пример #17
0
def init_llvm(basename):
    llvm.initialize()
    llvm.initialize_native_target()
    llvm.initialize_native_asmprinter()

    global gLlvmModule
    gLlvmModule = ir.Module(name=basename)
    def __init__(self, **kwargs):
        self.info = {"global_variables": []}
        self.local_vars = []
        self.aux = []
        self.functions = []
        self.module = ir.module.Module()

        llvm.initialize()
        llvm.initialize_all_targets()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()

        self.module = ir.Module('module.bc')
        self.module.triple = llvm.get_default_triple()
        target = llvm.Target.from_triple(self.module.triple)
        target_machine = target.create_target_machine()
        self.module.data_layout = target_machine.target_data

        self.escrevaInteiro = ir.Function(self.module,
                                          ir.FunctionType(
                                              ir.VoidType(), [ir.IntType(32)]),
                                          name="escrevaInteiro")
        self.escrevaFlutuante = ir.Function(self.module,
                                            ir.FunctionType(
                                                ir.VoidType(),
                                                [ir.FloatType()]),
                                            name="escrevaFlutuante")
        self.leiaInteiro = ir.Function(self.module,
                                       ir.FunctionType(ir.IntType(32), []),
                                       name="leiaInteiro")
        self.leiaFlutuante = ir.Function(self.module,
                                         ir.FunctionType(ir.FloatType(), []),
                                         name="leiaFlutuante")
Пример #19
0
def initialize_llvm():
    global _llvm_initialized
    if not _llvm_initialized:
        ll.initialize()
        ll.initialize_native_target()
        ll.initialize_native_asmprinter()
        _llvm_initialized = True
Пример #20
0
 def target_initialize(self):
     """
     Initialize LLVM for target.
     """
     llvm.initialize()
     llvm.initialize_native_target()
     llvm.initialize_native_asmprinter()
Пример #21
0
def Codegen(ast: ProgramNode, printIR: bool = True):
    """Genera l'LLVM IR dall'AST in input. 

    Args:
        ast: L'albero di sintassi astratto.
        printIR (bool): Un boolean che indica se fare un print dell'IR generato (default `False`)

    Returns:
        L'IR generato sotto forma di `str`

    Raises:
        StdlibNotFoundError: Se la standard lib non puo' essere trovata
    """

    llvm.initialize()
    llvm.initialize_native_target()
    llvm.initialize_native_asmprinter()

    # Decide l'estensione della stdlib
    ext = None
    if platform.system() == 'Windows':
        ext = 'dll'
    elif platform.system() == 'Darwin':
        ext = 'dylib'
    elif platform.system() == 'Linux':
        ext = 'so'

    path = pathlib.Path(__file__).parent.absolute()
    try:
        llvm.load_library_permanently(
            str(path) + "/../../bin/tiny_hi_core.{}".format(ext))
    except Exception:
        print("StdlibNotFoundError: Cannot find the standard library (tiny_hi_core.{})".format(ext))
        return (None, None)

    module = Module()
    builder = IRBuilder()
    context = Context(module)

    entry = None

    llmod = None

    try:
        entry = ast.entry_point()
        ast.codegen(builder, context)

        strmod = str(module)

        if printIR:
            print(strmod)

        llmod = llvm.parse_assembly(strmod)

    except Exception as e:
        print("Codegen Failed")
        print("{}: {}".format(type(e).__name__, e))
    finally:
        return (llmod, entry)
Пример #22
0
    def __init__(self):
        llvm.initialize()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()

        self.codegen = LLVMCodeGenerator()

        self.target = llvm.Target.from_default_triple()
Пример #23
0
def main(optimize: bool):
    text = FileStream("test.txt")
    lexer = WappaLexer(text)
    tokens = CommonTokenStream(lexer)
    parser = Wappa(tokens)
    parser.buildParseTrees = True

    tree = parser.compilationUnit()
    visitor = WappaVisitor()
    module = visitor.visit(tree)

    with open("ex/test.ll", "w") as f:
        f.write(module)

    # print('=== LLVM IR')
    # print(module)

    llvm.initialize()
    llvm.initialize_native_target()
    llvm.initialize_native_asmprinter()

    llvm_module = llvm.parse_assembly(str(module))

    if optimize:
        builder = llvm.create_pass_manager_builder()
        builder.inlining_threshold = 2
        builder.loop_vectorize = True
        builder.opt_level = 3
        builder.slp_vectorize = True

        mpm = llvm.create_module_pass_manager()
        builder.populate(mpm)
        mpm.run(llvm_module)

    tm = llvm.Target.from_default_triple().create_target_machine()

    with llvm.create_mcjit_compiler(llvm_module, tm) as ee:
        ee.finalize_object()

        asm = tm.emit_assembly(llvm_module)

        # print('=== Assembly')
        # print(asm)

        with open('ex/test.asm', 'w') as f:
            f.write(asm)

        print('The result of "sum" is',
              get_func(ee, 'sum', c_int, c_int, c_int)(17, 42))

        print('The result of "eq" is',
              get_func(ee, 'eq', c_bool, c_double, c_double)(17, 42))

        print('The result of "eq" is',
              get_func(ee, 'eq', c_bool, c_double, c_double)(42, 42))

        print('The result of "neq" is',
              get_func(ee, 'neq', c_bool, c_double, c_double)(17, 42))
Пример #24
0
 def __init__(self):
     llvm.initialize()
     llvm.initialize_native_target()
     llvm.initialize_native_asmprinter()
     self.builder = ll.IRBuilder()
     self.variable_table = {}
     fntype = ll.FunctionType(ll.VoidType(), [])
     self.module = ll.Module()
     self.func = ll.Function(self.module, fntype, name='main')
Пример #25
0
def main():
    m = ir.Module()
    func_ty = ir.FunctionType(ir.VoidType(), [])
    i32_ty = ir.IntType(32)
    func = ir.Function(m, func_ty, name="printer")

    voidptr_ty = ir.IntType(8).as_pointer()

    fmt = "Hello, %s! %i times!\n\0"
    c_fmt = ir.Constant(ir.ArrayType(ir.IntType(8), len(fmt)),
                        bytearray(fmt.encode("utf8")))
    global_fmt = ir.GlobalVariable(m, c_fmt.type, name="fstr")
    global_fmt.linkage = 'internal'
    global_fmt.global_constant = True
    global_fmt.initializer = c_fmt

    arg = "World\0"
    c_str_val = ir.Constant(ir.ArrayType(ir.IntType(8), len(arg)),
                            bytearray(arg.encode("utf8")))

    printf_ty = ir.FunctionType(ir.IntType(32), [voidptr_ty], var_arg=True)
    printf = ir.Function(m, printf_ty, name="printf")

    builder = ir.IRBuilder(func.append_basic_block('entry'))

    c_str = builder.alloca(c_str_val.type)
    builder.store(c_str_val, c_str)

    # this val can come from anywhere
    int_val = builder.add(i32_ty(5), i32_ty(3))

    fmt_arg = builder.bitcast(global_fmt, voidptr_ty)
    builder.call(printf, [fmt_arg, c_str, int_val])

    builder.ret_void()

    llvm.initialize()
    llvm.initialize_native_target()
    llvm.initialize_native_asmprinter()

    f = open("test.txt", "w")
    old = sys.stdout
    sys.stdout = f
    print(str(m))
    sys.stdout = old
    f.close()
    f = open("test.txt", "r")
    print(f.read())
    f.close()
    llvm_module = llvm.parse_assembly(str(m))
    tm = llvm.Target.from_default_triple().create_target_machine()

    with llvm.create_mcjit_compiler(llvm_module, tm) as ee:
        ee.finalize_object()
        fptr = ee.get_function_address("printer")
        py_func = CFUNCTYPE(None)(fptr)
        py_func()
Пример #26
0
def get_jit_engine():
    binding.initialize()
    binding.initialize_native_target()
    binding.initialize_native_asmprinter()

    target = binding.Target.from_default_triple()
    target_machine = target.create_target_machine()
    backing_module = binding.parse_assembly("")
    return binding.create_mcjit_compiler(backing_module, target_machine)
Пример #27
0
def _ensure_llvm():
    """Ensure that LLVM has been initialised."""
    if _ensure_llvm.was_initialized:
        return

    llvm.initialize()
    llvm.initialize_native_target()
    llvm.initialize_native_asmprinter()
    _ensure_llvm.was_initialized = True
Пример #28
0
    def __init__(self):
        llvm.initialize()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()

        self.target = llvm.Target.from_default_triple()
        backing_mod = llvm.parse_assembly("")
        self.engine = llvm.create_mcjit_compiler(backing_mod,
                                                 self.target.create_target_machine())
Пример #29
0
    def bindAndRun(self):
        print("Binding to LLVM and running. Here is the LLVM to be run:")
        llvm.load_library_permanently(r"./runtime/runtimelib.so")

        void = self.getType("void")

        # self.builder.ret_void()
        self.builder.ret(self.getType("true"))
        #print(self.builder.basic_block)

        llvm.initialize()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()  # yes, even this one

        llvm_ir = self.getIR()

        print("------------------Output-----------------------")

        def create_execution_engine():
            """
            Create an ExecutionEngine suitable for JIT code generation on
            the host CPU.  The engine is reusable for an arbitrary number of
            modules.
            """
            # Create a target machine representing the host
            target = llvm.Target.from_default_triple()
            target_machine = target.create_target_machine()
            # And an execution engine with an empty backing module
            backing_mod = llvm.parse_assembly("")
            engine = llvm.create_mcjit_compiler(backing_mod, target_machine)
            return engine

        def compile_ir(engine, llvm_ir):
            """
            Compile the LLVM IR string with the given engine.
            The compiled module object is returned.
            """
            # Create a LLVM module object from the IR
            mod = llvm.parse_assembly(llvm_ir)
            mod.verify()
            # Now add the module and make sure it is ready for execution
            engine.add_module(mod)
            engine.finalize_object()
            engine.run_static_constructors()
            return mod

        engine = create_execution_engine()
        mod = compile_ir(engine, llvm_ir)

        # Look up the function pointer (a Python int)
        func_ptr = engine.get_function_address("main")

        # Run the function via ctypes
        cfunc = CFUNCTYPE(c_bool)(func_ptr)
        res = cfunc()
        print("Exit: ", res)
Пример #30
0
    def __init__(self, input_fName, output_fName):
        self.symbolTable = SymbolTable()
        self.parser = Parser(input_fName)
        self.output_fName = output_fName
        self._has_errors = False

        # llvm setup
        binding.initialize()
        binding.initialize_native_target()
        binding.initialize_native_asmprinter()
Пример #31
0
    def __init__(self):
        llvm.initialize()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()

        self.env = dict()
        self.module = ir.Module(name=__file__)
        self._headers()
        self._main()
        self.target = llvm.Target.from_default_triple()
Пример #32
0
	def __init__(self):
		bind.initialize()
		bind.initialize_native_target()
		bind.initialize_native_asmprinter()  # yes, even this one
			 # Create a target machine representing the host
		target = bind.Target.from_default_triple()
		self.target_machine = target.create_target_machine()
	    # And an execution engine with an empty backing module
		backing_mod = bind.parse_assembly("")
		self.engine = bind.create_mcjit_compiler(backing_mod, self.target_machine)
Пример #33
0
def gen_asm(llvm_ir):
    # All these initializations are required for code generation!
    llvm.initialize()
    llvm.initialize_native_target()
    llvm.initialize_native_asmprinter()  # yes, even this one    
    
    engine = create_execution_engine()
    mod = compile_ir(engine, str(ir_ula.module))
    
    return target_machine.emit_assembly(mod)
Пример #34
0
    def __init__(self):
        llvm.initialize()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()

        self.codegen = LLVMCodeGenerator()
        self.parser = Parser()
        self._add_builtins(self.codegen.module)

        self.target = llvm.Target.from_default_triple()
Пример #35
0
    def __init__(self):
        llvm.initialize()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()

        self.codegen = LLVMCodeGenerator()
        self.parser = Parser()
        self._add_builtins(self.codegen.module)

        self.target = llvm.Target.from_default_triple()
Пример #36
0
 def __init__(self, name: str):
     self.module = ir.Module(name=name)
     self.functypes: Dict[str, Tuple[Ftypein, Ftypeout]] = dict()
     self.funcs: Dict[str, ir.Function] = dict()
     binding.initialize()
     binding.initialize_native_target()
     binding.initialize_native_asmprinter()
     target: binding.Target = binding.Target.from_default_triple()
     self.target_machine: binding.TargetMachine = target.create_target_machine(
     )
Пример #37
0
    def __init__(self):
        llvm.initialize()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()
        self.prop={}
        self.function_name_table = {}
        self.function_symbol_table = {}
        self.var_symbolTBL = {}
        self.var_ptr_symbolTBL = {}
        self.var_ptr_symbolTBL['var_symbolTBL'] = self.var_symbolTBL

        self.tm = llvm.Target.from_default_triple().create_target_machine()
Пример #38
0
    def __init__(self, triple="DEFAULT"):
        llvm.initialize()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()

        if triple == "DEFAULT":
            target = llvm.Target.from_default_triple()
        else:
            target = llvm.Target.from_triple(triple=triple)

        self.target_machine = target.create_target_machine()
        backing_mod = llvm.parse_assembly("")
        self.engine = llvm.create_mcjit_compiler(module=backing_mod, target_machine=self.target_machine)
Пример #39
0
def run_ir(llvm_ir):
    # All these initializations are required for code generation!
    llvm.initialize()
    llvm.initialize_native_target()
    llvm.initialize_native_asmprinter()  # yes, even this one    
    
    engine = create_execution_engine()
    mod = compile_ir(engine, llvm_ir)
    
    # Run the code
    func_ptr = engine.get_function_address("main")
    cfunc = CFUNCTYPE(c_float)(func_ptr)
    res = cfunc()
    return res
Пример #40
0
    def __init__(self, module):
        llvm.initialize()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()

        self.module = module
        self.module.translate()

        self.cge = CGEnv()
        self.cge.module = module

        self.llvm = self.makeStub()

        for _, func in self.module.namestore.all(ir.Function):
            self.blockAndCode(func)

        self.target_machine = llvm.Target.from_default_triple().create_target_machine()

        logging.debug("Verifying... ")
        self._llmod = None
Пример #41
0
from __future__ import print_function

from ctypes import CFUNCTYPE, c_double

import llvmlite.binding as llvm


# All these initializations are required for code generation!
llvm.initialize()
llvm.initialize_native_target()
llvm.initialize_native_asmprinter()  # yes, even this one

llvm_ir = """
   ; ModuleID = "examples/ir_fpadd.py"
   target triple = "unknown-unknown-unknown"
   target datalayout = ""

   define double @"fpadd"(double %".1", double %".2")
   {
   entry:
     %"res" = fadd double %".1", %".2"
     ret double %"res"
   }
   """

def create_execution_engine():
    """
    Create an ExecutionEngine suitable for JIT code generation on
    the host CPU.  The engine is reusable for an arbitrary number of
    modules.
    """
Пример #42
0
import subprocess
import sys
import os
import stat

from llvmlite import ir, binding

SOURCE_DIRECTORY = pathlib.Path(__file__).parent.resolve() / 'bbprogram'
SOURCE_FILENAME = 'bbprogram.s'
EXECUTABLE_FILENAME = 'bbprogram'
SYSTEM_SHARED = pathlib.Path('/usr/lib/x86_64-linux-gnu')

# All these initializations are required for code generation!
binding.initialize()
binding.initialize_native_target()
binding.initialize_native_asmprinter()  # yes, even this one

# Load libraries
def load_shared_library(name):
    """Find and load shared library."""
    if (SOURCE_DIRECTORY / name).exists():
        binding.load_library_permanently(str(SOURCE_DIRECTORY / name))
    else:
        binding.load_library_permanently(str(SYSTEM_SHARED / name))

# Create some useful types
UCHAR_T = ir.IntType(16)
USTR_T = ir.PointerType(UCHAR_T)
INT32_T = ir.IntType(32)
FLOAT32_T = ir.FloatType()
VOID_T = ir.VoidType()
Пример #43
0
def init():
    llvm.initialize()
    llvm.initialize_all_targets()
    llvm.initialize_native_asmprinter()
    llvm.initialize_native_target()
Пример #44
0
def initialize_llvm():
    """Safe to use multiple times.
    """
    ll.initialize()
    ll.initialize_native_target()
    ll.initialize_native_asmprinter()
Пример #45
0
 def setUp(self):
     llvm.initialize()
     llvm.initialize_native_target()
     llvm.initialize_native_asmprinter()
Пример #46
0

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: %s (llvmlite|llvmpy)"
              % (sys.executable,), file=sys.stderr)
        sys.exit(1)
    impl = sys.argv[1]

    if impl == 'llvmlite':
        import llvmlite.binding as llvm
        import llvmlite.llvmpy.core as lc
        from llvmlite.llvmpy import ee

        llvm.initialize()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()

        del llvm

    elif impl == 'llvmpy':
        import llvm.core as lc
        from llvm import ee

    else:
        raise RuntimeError("Wrong implementation %r" % (impl,))

    for i in range(3):
        run_bench(True)
        print()
Пример #47
0
from ctypes import CFUNCTYPE, c_int32

import llvmlite.ir as ir
import llvmlite.binding as binding

binding.initialize()
binding.initialize_native_target()
binding.initialize_native_asmprinter()

def make_add_fn():
    global ee
    int32 = llvm.ir.IntType(32)

    module = ir.Module()
    adder_type = ir.FunctionType(int32, (int32, int32))
    adder = ir.Function(module, adder_type, 'add')
    adder.args[0].name = 'a'
    adder.args[1].name = 'b'

    bb_entry = adder.append_basic_block('entry')
    irbuilder = ir.IRBuilder(bb_entry)
    s = irbuilder.add(adder.args[0], adder.args[1])
    irbuilder.ret(s)

    llvm_module = binding.parse_assembly(str(module))
    tm = binding.Target.from_default_triple().create_target_machine()

    ee = binding.create_mcjit_compiler(llvm_module, tm)
    ee.finalize_object()

    cfptr = ee.get_function_address('add')