vinix-ports / tests / x11 / llvm.v
60 lines · 55 sloc · 2.07 KB · 0ea984f3e8f435039dc8079e50bb3fea133ffce2
Raw
1// Execute LLVM-generated machine code with the runtime used by software Gallium.
2module main
3
4#include <llvm-c/Core.h>
5#include <llvm-c/ExecutionEngine.h>
6#include <llvm-c/IRReader.h>
7#include <llvm-c/Target.h>
8
9fn C.LLVMContextCreate() voidptr
10fn C.LLVMContextDispose(voidptr)
11fn C.LLVMCreateMemoryBufferWithMemoryRangeCopy(&char, usize, &char) voidptr
12fn C.LLVMParseIRInContext(voidptr, voidptr, voidptr, &&char) int
13fn C.LLVMDisposeMessage(&char)
14fn C.LLVMLinkInMCJIT()
15fn C.LLVMInitializeNativeTarget() int
16fn C.LLVMInitializeNativeAsmPrinter() int
17fn C.LLVMCreateJITCompilerForModule(voidptr, voidptr, u32, &&char) int
18fn C.LLVMDisposeExecutionEngine(voidptr)
19fn C.LLVMGetFunctionAddress(voidptr, &char) u64
20
21type Add = fn (i32, i32) i32
22
23fn execute() ! {
24 C.LLVMLinkInMCJIT()
25 if C.LLVMInitializeNativeTarget() != 0 || C.LLVMInitializeNativeAsmPrinter() != 0 {
26 return error('LLVM did not initialize the native target and assembly printer')
27 }
28 context := C.LLVMContextCreate()
29 defer { C.LLVMContextDispose(context) }
30 ir := 'define i32 @add(i32 %a, i32 %b) { %sum = add i32 %a, %b ret i32 %sum }'
31 buffer := C.LLVMCreateMemoryBufferWithMemoryRangeCopy(ir.str, usize(ir.len), c'vinix-guest')
32 mut program := voidptr(0)
33 mut message := &char(unsafe { nil })
34 if C.LLVMParseIRInContext(context, buffer, voidptr(&program), &message) != 0 {
35 defer { C.LLVMDisposeMessage(message) }
36 return error(unsafe { cstring_to_vstring(message) })
37 }
38 mut engine := voidptr(0)
39 if C.LLVMCreateJITCompilerForModule(voidptr(&engine), program, 1, &message) != 0 {
40 defer { C.LLVMDisposeMessage(message) }
41 return error(unsafe { cstring_to_vstring(message) })
42 }
43 defer { C.LLVMDisposeExecutionEngine(engine) }
44 address := C.LLVMGetFunctionAddress(engine, c'add')
45 if address == 0 {
46 return error('LLVM did not emit the add function')
47 }
48 add := unsafe { Add(usize(address)) }
49 if add(19, 23) != 42 || add(-5, 2) != -3 {
50 return error('generated code returned incorrect sums')
51 }
52 println('LLVM generated and executed native addition for both argument pairs.')
53}
54
55fn main() {
56 execute() or {
57 eprintln(err)
58 exit(1)
59 }
60}
61