Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Link C in llvmlite

Im writing an compiler in Python, using llvmlite to generate intermediate LLVM IR. Lexer and parser are finished, now im doing code generation. The compiler will be dynamic and weakly typed, so i will need to do somethings at runtime, like allocation. For this, i've already implemented some functions in C, and now i want to call these functions using builder.call from llvmlite.

I have not found documentation or examples of how to do this.

This function its just an simple example, the real ones are much larger.

C:

int some_function(int a)
{
     return a + 4;
}

Python:

...

    main_ty = ir.FunctionType(ir.IntType(32), [])
    func = ir.Function(module, main_ty, 'main')
    block = func.append_basic_block('entry')
    builder = ir.IRBuilder(block)

    # I want to do something like this...

    ret = builder.call(some_function, [ir.Constant(ir.IntType(32), 34)]);

...

I could write the functions directly using llvmlite builders, but will be much quick, cleaner and easy do it in C. Any help are welcome!

like image 261
Batata Avatar asked Apr 16 '16 00:04

Batata


2 Answers

You could import a dynamic library containing the runtime.

llvmlite.binding.load_library_permanently("runtime.so")

Then you could simply generate normal function calls.

like image 83
Coder3000 Avatar answered Sep 23 '22 03:09

Coder3000


On the LLVM IR side you can just declare the functions with the right signature (and no body), and insert calls to them like any other function. This is just like how in C you might call a function which is defined in another file.

From there, you would have to somehow link against your C functions. The details here depend on how you intend to use your generated IR code. For example, you could use clang to turn it into object files, and then link it like any other program. Or you could use the llvm JIT, in which case @Coder3000's answer (llvmlite.binding.load_library_permanently) should work to let LLVM resolve your function calls.

like image 32
Ismail Badawi Avatar answered Sep 22 '22 03:09

Ismail Badawi