How do I write output from within Python's LLVM bindings?

328 Views Asked by At

I am using Python's LLVM bindings to generate code for a custom language.

Now I want to run programs and check if their output works correctly - but I am unable to figure out exactly how to output anything.

Is there some way to write to stdout or to a file using LLVM bindings?

Or do I need to call printf from the C library?

How do I do either one of these?

Note: I am not using JIT / ExecutionEngine, so LLVM doesn't automatically find the printf function.

1

There are 1 best solutions below

3
On BEST ANSWER

LLVM can generate an object file (.o) that should be able to link to printf() as long as you define it properly and link to glibc (or msvcrt if you're on Windows). They also seem to have a library called llvm_cbuilder as part of llvmpy that could help you do that. They even have a test case just for printf():

https://github.com/llvmpy/llvmpy/blob/master/llvm_cbuilder/tests/test_print.py

Another option is to have your own suite of utility functions, including some that print. You can then pass a pointer to a table holding all of those to your generated function. What I like about this solution is that it allows you to load the generated function on runtime and avoid real linking (but you have to consider relocations).

Last but not least, Numba is always a good source of llvmpy examples.