llvm jit acting at runtime, like libgccjit ?


i mainly code in c/c++ on linux.

I would like to know if I can generate code at runtime using llvm, like libgccjit -> libgccjit — libgccjit 13.0.0 (experimental ) documentation

My needs are : create functions, conditions, loops at runtime. libgccjit does the job pretty well but I would like to test llvm too (licence issue).

Is it possible ?
Is there a resource that helps in that regard ? Kaleidoscope doesn't seems to be what I expect.




Yes, LLVM can do this and has been able to long before libgccjit. Kaleidoscope gives an introduction - what exactly is it about Kaleidoscope that differs from your expectations?



Thanks James,

Kaleidoscope seems to differ in the sense that I cannot really understand how to create, say, a loop. It all looks like very complicated (http://llvm.org/docs/tutorial/LangImpl3.html)

llvm is new to me.

it is pretty basic, but the tutorial page of the libgccjit is very helpful in that regard (how to create a function, a condition, a loop…)

I will keep doing my homework, but a bit of help is very welcome :slight_smile:


Once you have a Module and Function created, which Kaleidoscope can show you how to do, the important thing is to understand what the LLVM IR you want to create will look like. You can do this by writing a trivial function with a loop in Clang and running:

clang -O0 -emit-llvm -S -o - my-trivial-program.c

Clang, like any frontend, produces deliberately poor code and expects LLVM to clean it up - if you want more cleaned up code use -O2.

The IR reference is here: http://llvm.org/docs/LangRef.html
The IRBuilder reference, which is the object you use to build up some IR programatically, is here: http://llvm.org/docs/doxygen/html/classllvm_1_1IRBuilder.html (and http://llvm.org/docs/doxygen/html/classllvm_1_1IRBuilderBase.html )

To create a simple loop you will need to create at least two blocks: the loop header, and loop body. The header will perform your exit test and conditionally exit the loop. The body will do all your work and then increment/decrement the loop counter.

Best of luck,


I find it is more useful to use this:

clang -cc1 -O1 -disable-llvm-optzns -S -emit-llvm prog.c

-O0 produces some extra rubbish that is just noise.
-O1 and above can get rid of the code altogether - so using the
disable optimizations flag appears to help.