Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import numpy as np
import os
import re
from typing import Set
import weakref
from psyneulink.core.scheduling.time import Time
from psyneulink.core.globals.sampleiterator import SampleIterator
from psyneulink.core import llvm as pnlvm
from . import codegen
from .debug import debug_env
__all__ = ['LLVMBuilderContext', '_modules', '_find_llvm_function']
_modules: Set[ir.Module] = set()
_all_modules: Set[ir.Module] = set()
_struct_count = 0
@atexit.register
def module_count():
if "stat" in debug_env:
print("Total LLVM modules: ", len(_all_modules))
print("Total structures generated: ", _struct_count)
s = LLVMBuilderContext.get_global()
print("Total generations by global context: {}".format(s._llvm_generation))
print("Object cache in global context: {} hits, {} misses".format(s._stats["cache_requests"] - s._stats["cache_misses"], s._stats["cache_misses"]))
for stat in ("input", "output", "param", "state", "data"):
gen_stat = s._stats[stat + "_structs_generated"]
print("Total {} structs generated by global context: {}".format(stat, gen_stat))
print("Total python types converted by global context: {}".format(s._stats["types_converted"]))
def lift(filename):
root = et.parse(filename).getroot()
module = ir.Module(name="lifted")
for register in root.find('globals').findall('register'):
if register.get('name') in flags:
var = ir.GlobalVariable(module, ir.IntType(1), register.get('name'))
var.initializer = ir.Constant(ir.IntType(1), None)
var.linkage = 'internal'
registers[register.get('name')] = var
elif register.get('name') in pointers:
var = ir.GlobalVariable(module, ir.PointerType(ir.IntType(8)), register.get('name'))
var.initializer = ir.Constant(ir.PointerType(ir.IntType(8)), None)
var.linkage = 'internal'
registers[register.get('name')] = var
else:
var = ir.GlobalVariable(module, ir.IntType(8 * int(register.get('size'))), register.get('name'))
var.initializer = ir.Constant(ir.IntType(8 * int(register.get('size'))), None)
var.linkage = 'internal'
from llvmlite import ir
from . import builtins
from . import codegen
from .builder_context import *
from .builder_context import _all_modules, _convert_llvm_ir_to_ctype
from .debug import debug_env
from .execution import *
from .execution import _tupleize
from .jit_engine import *
__all__ = ['LLVMBuilderContext']
_compiled_modules: Set[ir.Module] = set()
_binary_generation = 0
def _llvm_build(target_generation=_binary_generation + 1):
global _binary_generation
if target_generation <= _binary_generation:
if "compile" in debug_env:
print("SKIPPING COMPILATION: {} -> {}".format(_binary_generation, target_generation))
return
if "compile" in debug_env:
print("COMPILING GENERATION: {} -> {}".format(_binary_generation, target_generation))
_cpu_engine.compile_modules(_modules, _compiled_modules)
if ptx_enabled:
_ptx_engine.compile_modules(_modules, set())
def __init__(self):
self.module: llvmlite.ir.Module = llvmlite.ir.Module()
self.ir_builder: typing.Optional[llvmlite.ir.IRBuilder] = None
self.named_values = {}
def _get_ll_pointer_type(self, target_data, context=None):
"""
Convert this type object to an LLVM type.
"""
from llvmlite.ir import Module, GlobalVariable
from llvmlite.binding import parse_assembly
if context is None:
m = Module()
else:
m = Module(context=context)
foo = GlobalVariable(m, self, name="foo")
with parse_assembly(str(m)) as llmod:
return llmod.get_global_variable(foo.name).type
def __init__(
self,
module: Optional[ir.Module] = None,
typemgr=None,
module_name: Optional[str] = None,
other_modules: list = [],
):
# Create an LLVM module if we aren't passed one.
if module is None:
self.module = ir.Module(name=module_name)
self.module.triple = binding.Target.from_default_triple().triple
else:
self.module = module
self.fn: Optional[FuncState] = None
self.text: Optional[str] = None
self.unsafe_set = False
# Create a type manager module if we aren't passed one.
if typemgr is None:
self.typemgr = AkiTypeMgr(module=self.module)
self.types = self.typemgr.types
else:
self.typemgr = typemgr
self.types = typemgr.types
def __init__(self, module=None, anon_vartype=None, vartypes=None):
if module is None:
module = ir.Module(None)
self.module = module
if vartypes is None:
vartypes = generate_vartypes()
self.vartypes = vartypes
if anon_vartype is None:
self.anon_vartype = self.vartypes._DEFAULT_TYPE
else:
self.anon_vartype = anon_vartype
self.token_generator = None
self.cur_tok = None
self.local_types = {}
self.consts = {}
self.level = 0
self.top_return = False
def translate(self):
self.llvm = ll.Module('__stella__'+str(self.__class__.i), context=ll.context.Context())
self.__class__.i += 1
for _, impl in self.namestore.all(Function):
impl.translate(self)
def generate_ir(self):
'''
generates LLVM IR for a given expression
'''
# 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:
from llvmlite import binding as llvm
from llvmlite import ir as lc
llvm.initialize()
llvm.initialize_native_target()
llvm.initialize_native_asmprinter()
mod = lc.Module()
mod.triple = llvm.get_default_triple()
func = lc.Function(mod, lc.FunctionType(lc.VoidType(), [lc.IntType(32)]),
name='foo')
builder = lc.IRBuilder(func.append_basic_block())
builder.ret_void()
print(mod)
mod = llvm.parse_assembly(str(mod))
mod.verify()
print(repr(mod))
print(mod)
with llvm.create_module_pass_manager() as pm:
with llvm.create_pass_manager_builder() as pmb: