// Execute LLVM-generated machine code with the runtime used by software Gallium. module main #include #include #include #include fn C.LLVMContextCreate() voidptr fn C.LLVMContextDispose(voidptr) fn C.LLVMCreateMemoryBufferWithMemoryRangeCopy(&char, usize, &char) voidptr fn C.LLVMParseIRInContext(voidptr, voidptr, voidptr, &&char) int fn C.LLVMDisposeMessage(&char) fn C.LLVMLinkInMCJIT() fn C.LLVMInitializeNativeTarget() int fn C.LLVMInitializeNativeAsmPrinter() int fn C.LLVMCreateJITCompilerForModule(voidptr, voidptr, u32, &&char) int fn C.LLVMDisposeExecutionEngine(voidptr) fn C.LLVMGetFunctionAddress(voidptr, &char) u64 type Add = fn (i32, i32) i32 fn execute() ! { C.LLVMLinkInMCJIT() if C.LLVMInitializeNativeTarget() != 0 || C.LLVMInitializeNativeAsmPrinter() != 0 { return error('LLVM did not initialize the native target and assembly printer') } context := C.LLVMContextCreate() defer { C.LLVMContextDispose(context) } ir := 'define i32 @add(i32 %a, i32 %b) { %sum = add i32 %a, %b ret i32 %sum }' buffer := C.LLVMCreateMemoryBufferWithMemoryRangeCopy(ir.str, usize(ir.len), c'vinix-guest') mut program := voidptr(0) mut message := &char(unsafe { nil }) if C.LLVMParseIRInContext(context, buffer, voidptr(&program), &message) != 0 { defer { C.LLVMDisposeMessage(message) } return error(unsafe { cstring_to_vstring(message) }) } mut engine := voidptr(0) if C.LLVMCreateJITCompilerForModule(voidptr(&engine), program, 1, &message) != 0 { defer { C.LLVMDisposeMessage(message) } return error(unsafe { cstring_to_vstring(message) }) } defer { C.LLVMDisposeExecutionEngine(engine) } address := C.LLVMGetFunctionAddress(engine, c'add') if address == 0 { return error('LLVM did not emit the add function') } add := unsafe { Add(usize(address)) } if add(19, 23) != 42 || add(-5, 2) != -3 { return error('generated code returned incorrect sums') } println('LLVM generated and executed native addition for both argument pairs.') } fn main() { execute() or { eprintln(err) exit(1) } }