Emitting Object Code In Memory With LLVM's C API

405 views Asked by At

I'm using the LLVM-C API for a compiler project and need to emit object code from IR to an in memory buffer. I'm aware the JIT can do this, but the resulting code will be executed many times with different arguments so statically compiling once rather than JIT compiling each time makes more sense.

What I want is a buffer of object code which I can then set executable, likely by using mmap (but let me know if there's a simpler approach), and then run.

I've found the function LLVMTargetMachineEmitToMemoryBuffer which seems to do the first part of what I need, but it requires an existing LLVM memory buffer type to write into. From what I can tell I want LLVMCreateMemoryBufferWithRange for this, which takes a pointer to char and a size. But now I need to know how many bytes LLVMTargetMachineEmitToMemoryBuffer will write in advance to provide it with the correct buffer, which as it's generating object code from arbitrary IR could be arbitrarily large, so I feel like I'm taking the wrong approach here, but I'm unsure how else to go about this.

How can I achieve this using LLVM's API?

0

There are 0 answers