示例#1
0
文件: test_nrt.py 项目: seibert/numba
    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
示例#2
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()
示例#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 initialize_llvm():
    global _llvm_initialized
    if not _llvm_initialized:
        ll.initialize()
        ll.initialize_native_target()
        ll.initialize_native_asmprinter()
        _llvm_initialized = True
    def __init__(self):
        llvm.initialize()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()

        self.codegen = LLVMCodeGenerator()

        self.target = llvm.Target.from_default_triple()
示例#6
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()
示例#7
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()
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)
示例#9
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)
示例#10
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()
示例#11
0
def initialize():
    '''
    Initalize llvm and module
    Return module
    '''
    llvm.initialize()
    llvm.initialize_native_target()
    llvm.initialize_native_asmprinter()

    module = ir.Module(name="prog")
    module.triple = llvm.get_default_triple()
    return module
示例#12
0
 def codegen(self):
     self._codegen(self.root)
     llvm_ir = self.module.__repr__()
     llvm.initialize()
     llvm.initialize_native_target()
     llvm.initialize_native_asmprinter()
     self.mod = llvm.parse_assembly(llvm_ir)
     # mod.verify()
     target = llvm.Target.from_default_triple()
     target_machine = target.create_target_machine()
     asm = target_machine.emit_assembly(self.mod)
     return asm
示例#13
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()
示例#14
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()
示例#15
0
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
    import llvmlite.binding as llvm

    #     llvm_ir = """
    #     define double @add4531207233431041901(double %a, double %b) {
    # entry:
    #   %0 = alloca double
    #   store double %a, double* %0
    #   %1 = alloca double
    #   store double %b, double* %1
    #   %retval = alloca double
    #   %2 = load double, double* %0
    #   %3 = load double, double* %1
    #   %4 = fadd double %2, %3
    #   store double %4, double* %retval
    #   br label %exit
    #
    # exit:
    #   %5 = load double, double* %retval
    #   ret double %5
    # }

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

    mod = llvm.parse_assembly(llvm_ir)
    mod.verify()

    # Optionally, could use passManagerBuilder to reuse the same options across JIT.
    funcPass = llvm.create_function_pass_manager(module=mod)
    funcPass.initialize()

    funcPass.add_dead_arg_elimination_pass()
    funcPass.add_dead_code_elimination_pass()

    passManager = llvm.create_pass_manager_builder()
    passManager.opt_level = 3
    passManager.loop_vectorize = True
    passManager.slp_vectorize = False

    funcPass.finalize()

    # 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
示例#16
0
def test_linux64_program_write(capfd):
    source_ll = r"""
@.message = internal constant [14 x i8] c"Hello, world!\0A"

; write(STDOUT, message, message_len)
define i64 @write(i64 %STDOUT, i8* %message, i64 %message_len) {
    %1 = call i64 asm sideeffect "syscall",
        "={rax},{rax},{rdi},{rsi},{rdx},~{rcx},~{r11},~{dirflag},~{fpsr},~{flags}"
        ( i64 1            ; {rax} SYSCALL_WRITE
        , i64 %STDOUT      ; {rdi} STDOUT
        , i8* %message     ; {rsi} message
        , i64 %message_len ; {rdx} message_len
        )
    ret i64 %1
}

; exit(int exit_code)
define void @exit(i64 %exit_code) {
    call i64 asm sideeffect "syscall",
        "={rax},{rax},{rdi},~{rcx},~{r11},~{dirflag},~{fpsr},~{flags}"
        ( i64 60          ; {rax} SYSCALL_EXIT
        , i64 %exit_code  ; {rdi} exit_code
        )
    ret void
}

define void @_start() {
    %message_ptr = getelementptr [14 x i8], [14 x i8]* @.message , i64 0, i64 0

    call i64 @write(i64 1, i8* %message_ptr, i64 14)
    call void @exit(i64 42)
    ret void
}
    """
    with TemporaryDirectory() as tmpdir:
        objfile = os.path.join(tmpdir, "test1.o")
        binfile = os.path.join(tmpdir, "test1")
        llvm.initialize()
        llvm.initialize_native_asmprinter()
        llvm.initialize_native_asmparser()
        llvm.initialize_native_target()
        target = llvm.Target.from_triple(llvm.get_default_triple())
        target_machine = target.create_target_machine()
        mod = llvm.parse_assembly(source_ll)
        mod.verify()
        with open(objfile, "wb") as o:
            o.write(target_machine.emit_object(mod))
        linker(["-o", binfile, objfile])
        r = call("%s" % binfile)
        assert r == 42
        out = capfd.readouterr().out
        assert out == "Hello, world!\n"
示例#17
0
def _binding_initialize():
    global __initialized
    if not __initialized:
        binding.initialize()
        if not ptx_enabled:
            # native == currently running CPU. ASM printer includes opcode emission
            binding.initialize_native_target()
            binding.initialize_native_asmprinter()
        else:
            binding.initialize_all_targets()
            binding.initialize_all_asmprinters()

        __initialized = True
def optimize(module, level):
    llvm.initialize()
    llvm.initialize_native_target()
    llvm.initialize_native_asmprinter()
    module_ref = llvm.parse_assembly(str(module))
    if level is None:
        return module_ref
    pmb = llvm.create_pass_manager_builder()
    pm = llvm.create_module_pass_manager()
    pmb.opt_level = level
    pmb.populate(pm)
    pm.run(module_ref)
    return module_ref
示例#19
0
文件: compiler.py 项目: LFUnion/left
    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)
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
示例#21
0
def test_linux64_program():
    """
    This is the simplest assembly program that uses Linux 64bit syscall to
    return an exit value.
    """
    # Named registers are used in the `asm` block, so that LLVM handles
    # register allocation.
    #
    # The calling convention for syscall on x86-64 (see `man syscall`) is to
    # pass the system call number in {rax}, the return value is returned in
    # {rax}, and the system call arguments in:
    #     {rdi},{rsi},{rdx},{r10},{r8},{r9}
    # The syscall kernel call clobbers {rcx} and {r11} registers.
    #
    # The LLVM's `asm` call itself clobbers the following registers:
    #   * {flags} (EFLAGS: status flags register)
    #   * {dirflag} (DF: direction flag; modeled separately from {flags})
    #   * {fpsr} (floating point status register)
    source_ll = r"""
; exit(int exit_code)
define void @exit(i64 %exit_code) {
    call i64 asm sideeffect "syscall",
        "={rax},{rax},{rdi},~{rcx},~{r11},~{dirflag},~{fpsr},~{flags}"
        ( i64 60          ; {rax} SYSCALL_EXIT
        , i64 %exit_code  ; {rdi} exit_code
        )
    ret void
}

define void @_start() {
    call void @exit(i64 42)
    ret void
}
    """
    with TemporaryDirectory() as tmpdir:
        objfile = os.path.join(tmpdir, "test1.o")
        binfile = os.path.join(tmpdir, "test1")
        llvm.initialize()
        llvm.initialize_native_asmprinter()
        llvm.initialize_native_asmparser()
        llvm.initialize_native_target()
        target = llvm.Target.from_triple(llvm.get_default_triple())
        target_machine = target.create_target_machine()
        mod = llvm.parse_assembly(source_ll)
        mod.verify()
        with open(objfile, "wb") as o:
            o.write(target_machine.emit_object(mod))
        linker(["-o", binfile, objfile])
        r = call("%s" % binfile)
        assert r == 42
示例#22
0
    def __init__(self):
        llvm.initialize()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()  # yes, even this one

        # Create a target machine representing the host
        target = llvm.Target.from_default_triple()
        target_machine = target.create_target_machine()

        # And an execution engine with a backing module
        self.main_mod = self.compile_ir('')

        self.engine = llvm.create_mcjit_compiler(self.main_mod, target_machine)
        self.files = set()
示例#23
0
    def __init__(self, probability: float, tolerance: float, seed: int = None):
        super().__init__(probability, tolerance, seed)

        self.name = f'bernoulli_{self.base:02d}bits_{hex(self.num)}'
        self.code = generate_ir(self.name, self.base, self.ops.ops)
        logging.info('module %s:\n%s', self.name, self.code)

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

        self.engine = init_execution_engine()
        self.mod = compile_ir(self.engine, str(self.code))
        self.func_ptr = self.engine.get_function_address(self.name)
        self.cfunc = CFUNCTYPE(c_long, *([c_long] * self.base))(self.func_ptr)
示例#24
0
def main():
    binding.initialize()
    binding.initialize_native_target()
    binding.initialize_native_asmprinter()
    # inicializando módulo principal
    #module = Module.new('main')
    module = ir.Module('my_module')
    # inicializando a tabela de símbolos
    symbols = {}
    # inicializando o gerenciador de passos de otimização e funções
    passes = None
    # FunctionPassManager.new(module)
    # configurando o motor de execução
    ee = create_execution_engine()
    # configuração dos passos de otimização
    # registra os passos já realizados em uma estrutura para executar
    # passes.add(ee.target_data)
    # combina e remove instruções redundantes
    # passes.add(PASS_INSTCOMBINE)
    # reassocia instruções para otimizar aritmética de constantes
    # passes.add(PASS_REASSOCIATE)
    # elimina subexpressões comuns
    # passes.add(PASS_GVN)
    # remove blocos básicos sem predecessor, elimina nó PHI para blocos básicos
    # com um único predecessor e elimina blocos que contém salto incondicional
    # passes.add(PASS_SIMPLIFYCFG)
    # inicializa as otimizações
    # passes.initialize()
    code = ''
    if len(sys.argv) >= 2:
        # lexer = Lexer()
        f = open(sys.argv[1])
        # lexer.test(f.read())
        code = f.read()
    '''
    while True:
        try:
            code = input('TPlusPlus => ')
            # code = './exemplo.tpp'
            # code = 'exemplo.tpp'
        except KeyboardInterrupt:
            print()
            break
            '''
    driver = Gen(code, module, symbols, ee, passes, OPTIMIZATION, DEBUG)
    if SHOW_END_CODE:
        print('\n\n=== Código LLVM final ===')
        print(module)
示例#25
0
def pi_llvm_jit(module):
    # 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(module))

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

    # Run the function via ctypes
    cfunc = CFUNCTYPE(c_void_p)(func_ptr)
    res = cfunc()
    print("main_function() =", res)
示例#26
0
def test__clone():
    llvm.initialize()
    llvm.initialize_native_target()
    llvm.initialize_native_asmprinter()

    p = run_llvmpass('basic.ll', PASS_SO_PATH, '-clonefuncs')
    p.wait()
    pout = StringIO(p.stdout.read().decode('utf-8'))

    m = llvm.parse_assembly(pout.getvalue())
    m.verify()

    expected = set(['fact', 'fact.1'])
    actual = set([f.name for f in m.functions])

    assert expected == actual
示例#27
0
 def _create_execution_engine(self):
     """
     Create an ExecutionEngine suitable for JIT code generation on the host
     CPU. The engine is reusable for any number of modules.
     """
     # Initialization...
     binding.initialize()
     binding.initialize_native_target()
     binding.initialize_native_asmprinter()
     # Create a target machine representing the host
     target = binding.Target.from_default_triple()
     target_machine = target.create_target_machine()
     # And an execution engine with an empty backing module
     backing_mod = binding.parse_assembly("")
     engine = binding.create_mcjit_compiler(backing_mod, target_machine)
     return engine
示例#28
0
def run(compiler: Compiler):
    # All these initializations are required for code generation!
    llvm.initialize()
    llvm.initialize_native_target()
    llvm.initialize_native_asmprinter()  # yes, even this one

    # llvm.load_library_permanently("/usr/lib/libc.dylib")
    # llvm.add_symbol("abs", llvm.address_of_symbol("abs"))

    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)
        compiler.compile(target_machine.target_data)
        return engine, str(compiler.module)

    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, llvm_ir = 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_int8)(func_ptr)
    print(cfunc())
示例#29
0
    def visitCompilationUnit(self, ctx: SoLangParser.CompilationUnitContext):
        # global function table
        # functions[function-name] = function-pointer
        self.functions = {}
        # global variable table
        # variables[function-name][variable-name] = variable-pointer
        self.variables = {}
        self.current_function = ''

        # llvm init
        llvm.initialize()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()

        # set target
        target = llvm.Target.from_default_triple()

        # define types
        self.i64 = ir.IntType(64)
        self.f64 = ir.FloatType()

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

        self.visitChildren(ctx)

        # generate code
        llvm_ir = str(self.module)
        llvm_ir_parsed = llvm.parse_assembly(llvm_ir)

        # optimizer
        if self.optimize:
            pmb = llvm.create_pass_manager_builder()
            pmb.opt_level = 1
            pm = llvm.create_module_pass_manager()
            pmb.populate(pm)
            pm.run(llvm_ir_parsed)

        with open('build/out.ll', 'w') as f:
            f.write(str(llvm_ir_parsed))

        return None
示例#30
0
    def __init__(self):
        llvm.initialize()
        llvm.initialize_all_targets()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()

        self.module = None
        self._llvmmod = llvm.parse_assembly("")
        self.target = llvm.Target.from_default_triple()
        self.cpu = llvm.get_host_cpu_name()
        self.cpu_features = llvm.get_host_cpu_features()
        self.target_machine = self.target.create_target_machine(
            cpu=self.cpu, features=self.cpu_features.flatten(), opt=2)
        llvm.check_jit_execution()
        self.ee = llvm.create_mcjit_compiler(self.llvmmod, self.target_machine)
        self.ee.finalize_object()
        self.fptr = None
示例#31
0
def build(filenames: Sequence[str]):
    # initialize llvm targets
    binding.initialize()
    binding.initialize_native_target()
    binding.initialize_native_asmparser()
    binding.initialize_native_asmprinter()

    # initialize workspace context
    workspace = Workspace(paths=[os.getcwd()])
    for filename in filenames:
        document = workspace.get_or_create_document(filename)
        module = document.module
        exit_diagnostics(document.diagnostics)

        if module:
            generator = ModuleCodegen(document.model.context, document.name)
            generator.emit(module)
            print(generator)
示例#32
0
 def begin(self):
     global ir
     global llvm
     global c_fn_type
     global c_int64
     global engine
     global int_type
     from llvmlite import ir
     import llvmlite.binding as llvm
     from ctypes import CFUNCTYPE as c_fn_type
     from ctypes import c_int64
     llvm.initialize()
     llvm.initialize_native_target()
     llvm.initialize_native_asmprinter()
     target = llvm.Target.from_default_triple()
     target_machine = target.create_target_machine()
     backing_mod = llvm.parse_assembly("")
     engine = llvm.create_mcjit_compiler(backing_mod, target_machine)
     int_type = ir.IntType(64)
示例#33
0
    def __init__(self, code, module, optz=False, debug=True):
        semantica = Semantica(code)
        self.module = module
        binding.initialize()
        binding.initialize_native_target()
        binding.initialize_native_asmprinter()
        self.ee = self.execution_engine()

        # self.passes = passes
        self.optimization = optz
        self.builder = None
        self.funcao = None
        self.leia = None
        self.escreva = None
        self.debug = debug
        self.scope = "global"
        self.table = semantica.table
        self.tree = semantica.tree
        self.gen_top(self.tree)
示例#34
0
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.
    """
    import llvmlite.binding as llvm

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

    # 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, target_machine
示例#35
0
def emit_object_file(module, output_file, triple=None): # pragma: nocover
    """Emit object file from a module.

    Args:
        module (Module): Module with an LLVM IR.
        output_file (str): Where to put emitted object file.
        triple (str, optional): Platform triple.
    """
    llvm.initialize()
    llvm.initialize_native_asmprinter()
    llvm.initialize_native_target()
    if triple is None:
        target = llvm.Target.from_default_triple()
    else:
        target = llvm.Target.from_triple(triple)
    machine = target.create_target_machine()
    mod = llvm.parse_assembly(str(module))
    mod.verify()
    with open(output_file, 'wb') as f:
        f.write(machine.emit_object(mod))
示例#36
0
    def __init__(self):
        llvm.initialize()
        llvm.initialize_native_asmprinter()
        llvm.initialize_native_target()

        target = llvm.Target.from_default_triple()
        self.target_machine = target.create_target_machine()
        self.target_machine.set_asm_verbosity(True)
        mod = llvm.parse_assembly("")
        mod.verify()
        self.ee = llvm.create_mcjit_compiler(mod, self.target_machine)

        pmb = llvm.create_pass_manager_builder()
        pmb.opt_level = 3
        pmb.loop_vectorize = True
        pmb.slp_vectorize = True
        self.pm = llvm.create_module_pass_manager()
        pmb.populate(self.pm)

        load_lfortran_runtime_library()
示例#37
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
示例#38
0
def run_jit(module):
    import llvmlite.binding as llvm

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

    target = llvm.Target.from_default_triple()
    target_machine = target.create_target_machine()
    compiled_mod = llvm.parse_assembly(str(module))
    engine = llvm.create_mcjit_compiler(compiled_mod, target_machine)

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

    # Turn into a Python callable using ctypes
    from ctypes import CFUNCTYPE, c_int
    hello = CFUNCTYPE(c_int)(func_ptr)

    res = hello()
    print('hello() returned', res)
def compile_ir(m):
    llvm.initialize()
    llvm.initialize_native_target()
    llvm.initialize_native_asmprinter()

    target = llvm.Target.from_default_triple()
    target_machine = target.create_target_machine()
    backing_mod = llvm.parse_assembly("")
    engine = llvm.create_mcjit_compiler(backing_mod, target_machine)

    mod = llvm.parse_assembly(m)
    mod.verify()

    engine.add_module(mod)
    engine.finalize_object()
    engine.run_static_constructors()

    func_ptr = engine.get_function_address("main")

    cfunc = CFUNCTYPE(c_int)(func_ptr)
    cfunc()
示例#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
def main(verbose=True):
    llvm.initialize()
    llvm.initialize_native_asmprinter()
    llvm.initialize_native_target()

    target = llvm.Target.from_triple(llvm.get_default_triple())
    target_machine = target.create_target_machine()
    target_machine.set_asm_verbosity(True)

    # Empty backing module
    backing_mod = llvm.parse_assembly("")
    backing_mod.verify()
    engine = llvm.create_mcjit_compiler(backing_mod, target_machine)

    print("Interactive Fortran.")
    print("  * Use Ctrl-D to exit.")
    print("  * Use Enter to submit.")
    print("  * Features:")
    print("    - Multi-line editing (use Alt-Enter)")
    print("    - History")
    print("    - Syntax highlighting")
    print()

    fortran_evaluator = FortranEvaluator()

    session = PromptSession('> ',
                            lexer=PygmentsLexer(FortranLexer),
                            multiline=True,
                            key_bindings=kb)
    try:
        while True:
            text = session.prompt()
            if verbose:
                print()
            handle_input(engine, fortran_evaluator, text, verbose)
            if verbose:
                print()
    except EOFError:
        print("Exiting.")
示例#42
0
文件: codegen.py 项目: cpcloud/numba
def initialize_llvm():
    """Safe to use multiple times.
    """
    ll.initialize()
    ll.initialize_native_target()
    ll.initialize_native_asmprinter()
示例#43
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.
    """
示例#44
0
def init():
    llvm.initialize()
    llvm.initialize_all_targets()
    llvm.initialize_native_asmprinter()
    llvm.initialize_native_target()
示例#45
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')
示例#46
0
 def setUp(self):
     llvm.initialize()
     llvm.initialize_native_target()
     llvm.initialize_native_asmprinter()