Exemple #1
0
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):
        if binding.get_process_triple().startswith("powerpc"):
            builder.fence("acquire")
        builder.call(calldtor, [ptr])
    builder.ret_void()
Exemple #2
0
    def test_get_host_cpu_features(self):
        try:
            features = llvm.get_host_cpu_features()
        except RuntimeError:
            # Allow non-x86 arch to pass even if an RuntimeError is raised
            triple = llvm.get_process_triple()
            # For now, we know for sure that x86 is supported.
            # We can restrict the test if we know this works on other arch.
            is_x86 = triple.startswith('x86')
            self.assertFalse(is_x86,
                             msg="get_host_cpu_features() should not raise")
            return
        # Check the content of `features`
        self.assertIsInstance(features, dict)
        self.assertIsInstance(features, llvm.FeatureMap)
        for k, v in features.items():
            self.assertIsInstance(k, str)
            self.assertTrue(k)  # feature string cannot be empty
            self.assertIsInstance(v, bool)
        self.assertIsInstance(features.flatten(), str)

        re_term = r"[+\-][a-zA-Z0-9\._-]+"
        regex = r"^({0}|{0}(,{0})*)?$".format(re_term)
        # quick check for our regex
        self.assertIsNotNone(re.match(regex, ""))
        self.assertIsNotNone(re.match(regex, "+aa"))
        self.assertIsNotNone(re.match(regex, "+a,-bb"))
        # check CpuFeature.flatten()
        self.assertIsNotNone(re.match(regex, features.flatten()))
def main():
    if (len(sys.argv) < 2):
        print("ERRO - Por Favor Informe Um Arquivo .tpp")
    else:
        file = open(sys.argv[1], 'r', encoding='utf-8')
        sin = Sintatica(file.read(), Lexica().tokens)
        dot = Digraph(comment='TREE')
        Tree().printTree(sin.ast, dot)
        #dot.render('out/sintatica/normal.gv', view=True)
        Tree().poda(sin.ast)
        dot = Digraph(comment='TREE')
        Tree().printTreeCut(sin.ast, dot)
        #dot.render('out/semantica/poda.gv', view=True)
        sema = Semantica()
        sema.percorrerTree(sin.ast)
        sema.verificacoes()
        #sema.printTabSymbols()
        llvm.initialize()
        llvm.initialize_all_targets()
        llvm.initialize_native_target()
        llvm.initialize_native_asmparser()
        modulo = ir.Module(sys.argv[1])
        modulo.triple = llvm.get_process_triple()
        target = llvm.Target.from_triple(modulo.triple)
        targetMachine = target.create_target_machine()
        modulo.data_layout = targetMachine.target_data
        Geracao().percorrer(sin.ast, modulo)
        arquivo = open('teste.ll', 'w')
        arquivo.write(str(modulo))
        arquivo.close()
        print(modulo)
Exemple #4
0
    def _init(self, llvm_module):
        assert list(llvm_module.global_variables) == [], "Module isn't empty"

        target = ll.Target.from_triple(ll.get_process_triple())
        tm_options = dict(opt=config.OPT)
        self._tm_features = self._customize_tm_features()
        self._customize_tm_options(tm_options)
        tm = target.create_target_machine(**tm_options)
        engine = ll.create_mcjit_compiler(llvm_module, tm)

        if config.ENABLE_PROFILING:
            engine.enable_jit_events()

        self._tm = tm
        self._engine = JitEngine(engine)
        self._target_data = engine.target_data
        self._data_layout = str(self._target_data)
        self._mpm_cheap = self._module_pass_manager(loop_vectorize=False,
                                                    slp_vectorize=False,
                                                    opt=1)
        self._mpm_full = self._module_pass_manager()

        self._engine.set_object_cache(
            self._library_class._object_compiled_hook,
            self._library_class._object_getbuffer_hook)
Exemple #5
0
def _make_cas_function():
    """
    Generate a compare-and-swap function for portability sake.
    """
    # Generate IR
    mod = lc.Module.new('generate-cas')
    llint = lc.Type.int()
    llintp = lc.Type.pointer(llint)
    fnty = lc.Type.function(llint, [llintp, llint, llint])
    fn = mod.add_function(fnty, name='.numba.parallel.ufunc.cas')
    ptr, old, repl = fn.args
    bb = fn.append_basic_block('')
    builder = lc.Builder.new(bb)
    outpack = builder.cmpxchg(ptr, old, repl, ordering='monotonic')
    out = builder.extract_value(outpack, 0)
    failed = builder.extract_value(outpack, 1)
    builder.ret(builder.select(failed, old, out))

    # Build & Link
    llmod = ll.parse_assembly(str(mod))

    target = ll.Target.from_triple(ll.get_process_triple())
    tm = target.create_target_machine()
    engine = ll.create_mcjit_compiler(llmod, tm)
    ptr = engine.get_function_address(fn.name)
    return engine, ptr
Exemple #6
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)
Exemple #7
0
def get_engine():
    s = """; ModuleID = "__module__"
    target triple = "unknown-unknown-unknown"
    target datalayout = ""

    define void @run_forever() 
    {
    entry:
      br label %loop
    loop:
      br label %loop
    exit:
      ret void
    }
    
    define void @finish_now()
    {
    entry:
      ret void
    }
    """
    target = llvm.Target.from_triple(llvm.get_process_triple())
    target_machine = target.create_target_machine()
    mod = llvm.parse_assembly(s)
    mod.verify()
    engine = llvm.create_mcjit_compiler(mod, target_machine)
    engine.finalize_object()
    return engine
Exemple #8
0
    def test_get_process_triple(self):
        triple = llvm.get_process_triple()
        default = llvm.get_default_triple()
        self.assertIsInstance(triple, str)
        self.assertTrue(triple)

        default_parts = default.split('-')
        triple_parts = triple.split('-')
        # Arch must be equal
        self.assertEqual(default_parts[0], triple_parts[0])
Exemple #9
0
    def _init(self, llvm_module):
        assert list(llvm_module.global_variables) == [], "Module isn't empty"

        target = ll.Target.from_triple(ll.get_process_triple())
        tm_options = dict(opt=config.OPT)
        self._tm_features = self._customize_tm_features()
        self._customize_tm_options(tm_options)
        tm = target.create_target_machine(**tm_options)
        engine = ll.create_mcjit_compiler(llvm_module, tm)

        self._tm = tm
        self._engine = engine
        self._target_data = engine.target_data
        self._data_layout = str(self._target_data)
        self._mpm = self._module_pass_manager()

        self._engine.set_object_cache(self._library_class._object_compiled_hook,
                                      self._library_class._object_getbuffer_hook)
Exemple #10
0
    def compile_ir(self, llvm_ir, name, verbose, optimize=True):
        """
        Compile the LLVM IR string with the given engine.
        The compiled module object is returned.
        """
        engine = self.engine

        # Create a LLVM module object from the IR
        mod = binding.parse_assembly(llvm_ir)
        mod.verify()
        # Assign triple, so the IR can be saved and compiled with llc
        mod.triple = self.triple
        if verbose:
            print('====== IR (parsed) ======')
            print(mod)

        # Optimize
        if optimize:
            pmb = binding.PassManagerBuilder()
            pmb.opt_level = 2  # 0-3 (default=2)
            pmb.loop_vectorize = True

            mpm = binding.ModulePassManager()
            # Needed for automatic vectorization
            triple = binding.get_process_triple()
            target = binding.Target.from_triple(triple)
            tm = target.create_target_machine()
            tm.add_analysis_passes(mpm)

            pmb.populate(mpm)
            mpm.run(mod)

            if verbose:
                print('====== IR (optimized) ======')
                print(mod)

        # 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
def main():
    global root, func_table, var_table, module
    arg = sys.argv[1]
    if not arg.endswith('.tpp'):
        raise IOError("Not a tpp file!")

    data = open(arg, 'r')
    source_file = data.read()
    data.close()

    tree = SemanticAnalyzer(source_file)

    root = tree.root
    func_table = tree.func_table
    var_table = tree.var_table

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

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

    generate_code()
    tree.set_atribution_asto()
    tree.export_tree()

    arquivo = open('atribuicao.ll', 'w')
    arquivo.write(str(module))
    arquivo.close()
    print(module)
    llvm.shutdown()
Exemple #12
0
 def _create_empty_module(self, name):
     ir_module = lc.Module(cgutils.normalize_ir_text(name))
     ir_module.triple = ll.get_process_triple()
     if self._data_layout:
         ir_module.data_layout = self._data_layout
     return ir_module
        file = argv[1]
    data = file

    raiz = semantica_main(data)

    print("------------------------------------------")
    print("Geração de código®")
    print("------------------------------------------")

    llvm.initialize()
    llvm.initialize_all_targets()
    llvm.initialize_native_target()
    llvm.initialize_native_asmparser()

    moduloFinal = ir.Module(file)
    moduloFinal.triple = llvm.get_process_triple()
    target = llvm.Target.from_triple(moduloFinal.triple)
    targetMachine = target.create_target_machine()
    moduloFinal.data_layout = targetMachine.target_data
    print("------------------------------------------")
    print("Percorrendo a árvore na ger. cod®")
    print("------------------------------------------")

    _escrevaI = ir.FunctionType(ir.VoidType(), [ir.IntType(32)])
    escrevaI = ir.Function(moduloFinal, _escrevaI, "escrevaInteiro")

    _escrevaF = ir.FunctionType(ir.VoidType(), [ir.FloatType()])
    escrevaF = ir.Function(moduloFinal, _escrevaF, "escrevaFlutuante")

    _leiaI = ir.FunctionType(ir.IntType(32), [])
    leiaI = ir.Function(moduloFinal, _leiaI, "leiaInteiro")
Exemple #14
0
 def _create_empty_module(self, name):
     ir_module = lc.Module(name)
     ir_module.triple = ll.get_process_triple()
     if self._data_layout:
         ir_module.data_layout = self._data_layout
     return ir_module
Exemple #15
0
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

# Could be useful if you want to compile for other targets.
# llvmlite.binding.initialize_all_targets()

# Ensure JIT execution is allowed
llvm.check_jit_execution()

target = llvm.Target.from_triple(llvm.get_process_triple())
target_machine = target.create_target_machine(codemodel="default")
target_data = target_machine.target_data

# Configure optimization pass manager builder
# https://llvmlite.readthedocs.io/en/latest/user-guide/binding/optimization-passes.html#llvmlite.binding.PassManagerBuilder
pm_builder = llvm.PassManagerBuilder()
pm_builder.disable_unroll_loops = False
pm_builder.inlining_threshold = 100
pm_builder.loop_vectorize = True
pm_builder.slp_vectorize = True
pm_builder.opt_level = 3
pm_builder.size_level = 0

pass_manager = llvm.ModulePassManager()
pm_builder.populate(pass_manager)

# Target specific optimizations