forked from tinygrad/tinygrad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ops_llvm.py
47 lines (43 loc) · 2.31 KB
/
ops_llvm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from __future__ import annotations
import ctypes, functools
from typing import Tuple
from tinygrad.device import Compiled, MallocAllocator, Compiler, CompilerOptions
from tinygrad.helpers import DEBUG, cpu_time_execution
from tinygrad.renderer.llvmir import uops_to_llvm_ir
import llvmlite.binding as llvm
class LLVMCompiler(Compiler):
compiler_opts = CompilerOptions("LLVM", supports_float4=False, has_local=False, has_shared=False)
def __init__(self, device:LLVMDevice):
self.device = device
super().__init__("compile_llvm")
def render(self, name:str, uops) -> str: return uops_to_llvm_ir(name, uops)
def compile(self, src:str) -> bytes:
mod = llvm.parse_assembly(src)
mod.verify()
self.device.optimizer.run(mod)
if DEBUG >= 5: print(self.device.target_machine.emit_assembly(mod))
return self.device.target_machine.emit_object(mod)
class LLVMProgram:
def __init__(self, device:LLVMDevice, name:str, lib:bytes):
self.name, self.lib = name, lib
device.engine.add_object_file(llvm.object_file.ObjectFileRef.from_data(lib))
self.fxn = device.engine.get_function_address(name)
def __call__(self, *bufs, vals:Tuple[int, ...]=(), wait=False):
if not hasattr(self, 'cfunc'):
self.cfunc = ctypes.CFUNCTYPE(ctypes.c_int, *([ctypes.c_void_p]*len(bufs)), *([ctypes.c_int32]*len(vals)))(self.fxn)
return cpu_time_execution(lambda: self.cfunc(*bufs, *vals), enable=wait)
class LLVMDevice(Compiled):
def __init__(self, device:str):
llvm.initialize()
llvm.initialize_native_target()
llvm.initialize_native_asmprinter()
llvm.initialize_native_asmparser()
self.optimizer: llvm.passmanagers.ModulePassManager = llvm.create_module_pass_manager()
# this opt actually can change things. ex: opt=3 means no FMA, opt=2 means FMA
self.target_machine: llvm.targets.TargetMachine = llvm.Target.from_triple(llvm.get_process_triple()).create_target_machine(opt=2)
self.target_machine.add_analysis_passes(self.optimizer)
self.target_machine.set_asm_verbosity(True)
backing_mod = llvm.parse_assembly(str())
backing_mod.triple = llvm.get_process_triple()
self.engine: llvm.executionengine.ExecutionEngine = llvm.create_mcjit_compiler(backing_mod, self.target_machine)
super().__init__(device, MallocAllocator, LLVMCompiler(self), functools.partial(LLVMProgram, self))