| 1 | // Execute LLVM-generated machine code with the runtime used by software Gallium. |
| 2 | module 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 | |
| 9 | fn C.LLVMContextCreate() voidptr |
| 10 | fn C.LLVMContextDispose(voidptr) |
| 11 | fn C.LLVMCreateMemoryBufferWithMemoryRangeCopy(&char, usize, &char) voidptr |
| 12 | fn C.LLVMParseIRInContext(voidptr, voidptr, voidptr, &&char) int |
| 13 | fn C.LLVMDisposeMessage(&char) |
| 14 | fn C.LLVMLinkInMCJIT() |
| 15 | fn C.LLVMInitializeNativeTarget() int |
| 16 | fn C.LLVMInitializeNativeAsmPrinter() int |
| 17 | fn C.LLVMCreateJITCompilerForModule(voidptr, voidptr, u32, &&char) int |
| 18 | fn C.LLVMDisposeExecutionEngine(voidptr) |
| 19 | fn C.LLVMGetFunctionAddress(voidptr, &char) u64 |
| 20 | |
| 21 | type Add = fn (i32, i32) i32 |
| 22 | |
| 23 | fn 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 | |
| 55 | fn main() { |
| 56 | execute() or { |
| 57 | eprintln(err) |
| 58 | exit(1) |
| 59 | } |
| 60 | } |
| 61 | |