Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
C

codegen

> AI 编程
Open source

Experimental wrapper over LLVM for generating and compiling code at run-time.

380 stars0 likes3 views
WebsiteGitHub

About

Experimental wrapper over LLVM for generating and compiling code at run-time.

CodeGen

Experimental wrapper over LLVM for generating and compiling code at run-time.

About

CodeGen is a library that builds on top of LLVM. It facilitates just-in-time code generation and compilation, including debugging information and human-readable source code. C++ type system is employed to guard against, at least some, errors in the generated intermediate representation. The intention is to allow the application to improve performance by taking advantage of information that becomes available only once it is running. A sample use case would be prepared statements in of database engines.

The general idea is not unlike that described in P1609R0: C++ Should Support Just-in-Time Compilation.

Building

The build requirements are as follows:

  • CMake 3.12
  • GCC 8+ or Clang 8+
  • LLVM 8
  • fmt
  • Google Test (optional)

fedora:30 docker container may be a good place to start.

The build instructions are quite usual for a CMake-based project:

cd 
cmake -DCMAKE_BUILD_TYPE= -G Ninja 
ninja
ninja test

Design

The main object representing the JIT compiler is codegen::compiler. All function pointers to the compiled code remain valid during its lifetime. codegen::module_builder allows creating an LLVM builder, while codegen::module represents an already compiled module. The general template that for CodeGen use looks as follows:

cpp
  namespace cg = codegen;
  auto compiler = cg::compiler{};
  auto builder = cg::module_builder(compiler, "module_name");

  auto function_reference = builder.create_function("function_name",
    [](cg::value v) {
      /* more logic here */
      cg::return_(v + cg::constant(1));
    });

  auto module = std::move(builder).build();
  using function_pointer_type = int(*)(int);
  function_pointer_type function_pointer = module.get_address(function_reference);

The code above compiles a function that returns an integer that was passed to it as an argument incremented by one. Each module may contain multiple functions. codegen::module_builder::create_function returns a function reference that can be used to obtain a pointer to the function after the module is compiled (as in this example) or to call it from another function generated with CodeGen.

codegen::value is a typed equivalent of llvm::Value and represents a SSA value. As of now, only fundamental types are supported. CodeGen provides operators for those arithmetic and relational operations that make sense for a given type. Expression templates are used in a limited fashion to allow producing more concise human-readable source code. Unlike C++ there are no automatic promotions or implicit casts of any kind. Instead, bit_cast or cast need to be explicitly used where needed.

SSA starts getting a bit more cumbersome to use once the control flow diverges, and a Φ function is required. This can be avoided by using local variables codegen::variable. The resulting IR is not going to be perfect, but the LLVM optimisation passes tend to do an excellent job converting those memory accesses.

Statements

  • return_(), return_(Value) – returns from function. Note, that the type of the returned value is not verified and CodeGen will not prevent generating a function of type int() that returns void.
  • load(Pointer) – takes a pointer of type T* and loads the value from memory, codegen::value.
  • store(Value, Pointer) – stores Value of type T at the location pointed to by Pointer. The type of the pointer needs to be T*.
  • if_(Value, TrueBlock, FalseBlock), if_(Value, TrueBlock) – an if conditional statement. The type of the provided value needs to be bool. TrueBlock and FalseBlock are expected to be lambdas. For example:
cpp
auto silly_function = builder.create_function("silly_function",
    [](cg::value is_true) {
      cg::if_(is_true, [] { cg::return_(cg::true_()); }, [] { cg::return_(cg::false_()); });
    });
  • while_(Condition, LoopBody) – a while loop. Condition is a lambda returning a value of type bool. LoopBody is a lambda that generates the body of the loop. For example:
cpp
auto silly_function2 = builder.create_function("silly_function2",
    [](cg::value target) {
      auto var = cg::variable("var", cg::constant(0));
      cg::while_([&] { return var.get() (1));
        });
      cg::return_(var.get());
    });
  • call(Function, Arguments...) – a function call. Function is a function reference. Arguments... is a list of arguments matching the function type.

Examples

Tuple comparator

In this example, let's consider tuples which element's types are known only at run-time. If the goal is to write a less-comparator for such tuples, the naive approach would be to have a virtual function call for each element. That is far from ideal if the actual comparison is very cheap, e.g. the elements are integers. With CodeGen, we can do better. First, let's write a comparator for an element of a fundamental type:

cpp
template
size_t less_cmp(cg::value a_ptr, cg::value b_ptr, size_t off) {
  auto a_val = cg::load(cg::bit_cast(a_ptr + cg::constant(off)));
  auto b_val = cg::load(cg::bit_cast(b_ptr + cg::constant(off)));
  cg::if_(a_val  b_val, [&] { cg::return_(cg::false_()); });
  return sizeof(T) + off;
}

This function template generates comparison code for any fundamental type. The arguments are pointers to buffers containing both tuples and an offset at which the element is located. The return value is the offset of the next element.

Now, let's say we want to generate a less-comparator for tuple.

cpp
  auto less = builder.create_function(
      "less", [&](cg::value a_ptr, cg::value b_ptr) {
        size_t offset = 0;
        offset = less_cmp(a_ptr, b_ptr, offset);
        offset = less_cmp(a_ptr, b_ptr, offset);
        offset = less_cmp(a_ptr, b_ptr, offset);
        (void)offset;
        cg::return_(cg::false_());
      });

As we can see, building the actual comparator is quite straightforward. The human-readable source code that CodeGen generates looks like this:

c
1   bool less(byte* arg0, byte* arg1) {
2       val0 = *bit_cast((arg0 + 0))
3       val1 = *bit_cast((arg1 + 0))
4       if ((val0  val1)) {
8           return false;
9       }
10      val2 = *bit_cast((arg0 + 4))
11      val3 = *bit_cast((arg1 + 4))
12      if ((val2  val3)) {
16          return false;
17      }
18      val4 = *bit_cast((arg0 + 8))
19      val5 = *bit_cast((arg1 + 8))
20      if ((val4  val5)) {
24          return false;
25      }
26      return false;
27  }

The assembly that LLVM emits:

…

Since CodeGen takes care of emitting all necessary debugging information, and informing GDB about the JIT-ed functions, the debugging experience shouldn't be too bad:

(gdb) b 3
Breakpoint 2 at 0x7fffefd57002: file /tmp/examples-11076310111440055155/tuple_i32f32u16_less.txt, line 3.
(gdb) c
Continuing.

Breakpoint 2, less (arg0=0x60200001c7b0 "", arg1=0x60200001c790 "\001") at /tmp/examples-11076310111440055155/tuple_i32f32u16_less.txt:3
3	    val1 = *bit_cast((arg1 + 0))
(gdb) p val0
$1 = 0
(gdb) n
4	    if ((val0 `:

```c++
  auto less = builder.create_function(
      "less", [&](cg::value a_ptr, cg::value b_ptr) {
        size_t offset = 0;
        offset = less_cmp(a_ptr, b_ptr, offset);

        auto a_len = cg::load(cg::bit_cast(a_ptr + cg::constant(offset)));
        auto b_len = cg::load(cg::bit_cast(b_ptr + cg::constant(offset)));
        // TODO: extract to a separate function
        auto len = cg::call(min, a_len, b_len);
        auto ret = cg::builtin::memcmp(a_ptr + cg::constant(offset) + 4_u64,
                                       b_ptr + cg::constant(offset) + 4_u64, len);
        cg::if_(ret  0_i32, [&] { cg::return_(cg::false_()); });
        cg::return_(a_len :   push   %rbp
   0x00007fffefd47011 :   push   %r14
   0x00007fffefd47013 :   push   %rbx

8      val6 = *bit_cast((arg0 + 0))
   0x00007fffefd47014 :   mov    (%rdi),%eax

9      val7 = *bit_cast((arg1 + 0))
   0x00007fffefd47016 :   mov    (%rsi),%ecx
   0x00007fffefd47018 :   mov    $0x1,%bl

10      if ((val6 :  cmp    %ecx,%eax
   0x00007fffefd4701c :  jl     0x7fffefd4704e 

12      }
13      if ((val6 > val7)) {
   0x00007fffefd4701e :  cmp    %ecx,%eax
   0x00007fffefd47020 :  jle    0x7fffefd47026 
   0x00007fffefd47022 :  xor    %ebx,%ebx
   0x00007fffefd47024 :  jmp    0x7fffefd4704e 

14          return false;
15      }
16      val8 = *bit_cast((arg0 + 4))
   0x00007fffefd47026 :  mov    0x4(%rdi),%r14d

17      val9 = *bit_cast((arg1 + 4))
   0x00007fffefd4702a :  mov    0x4(%rsi),%ebp

2      if ((arg0 :  cmp    %ebp,%r14d
   0x00007fffefd47030 :  mov    %ebp,%edx
   0x00007fffefd47032 :  cmovb  %r14d,%edx

18      min_ret = min(val8, val9, );
19      memcmp_ret = memcmp(((arg0 + 4) + 4), ((arg1 + 4) + 4), min_ret);
   0x00007fffefd47036 :  add    $0x8,%rdi
   0x00007fffefd4703a :  add    $0x8,%rsi
   0x00007fffefd4703e :  movabs $0x7ffff764bd90,%rax
   0x00007fffefd47048 :  callq  *%rax

20      if ((memcmp_ret :  test   %eax,%eax
   0x00007fffefd4704c :  jns    0x7fffefd47055 

11          return true;
   0x00007fffefd4704e :  mov    %ebx,%eax
   0x00007fffefd47050 :  pop    %rbx
   0x00007fffefd47051 :  pop    %r14
   0x00007fffefd47053 :  pop    %rbp
   0x00007fffefd47054 :  retq

2      if ((arg0 :  cmp    %ebp,%r14d
   0x00007fffefd47058 :  setb   %cl

21          return true;
22      }
23      if ((memcmp_ret > 0)) {
   0x00007fffefd4705b :  test   %eax,%eax
   0x00007fffefd4705d :  sete   %al
   0x00007fffefd47060 :  and    %cl,%al
   0x00007fffefd47062 :  pop    %rbx
   0x00007fffefd47063 :  pop    %r14
   0x00007fffefd47065 :  pop    %rbp
   0x00007fffefd47066 :  retq

…

c++
  auto compute = builder.create_function(
      "compute", [&](cg::value a, cg::value b_ptr, cg::value c_ptr,
                     cg::value d_ptr, cg::value n) {
        auto idx = cg::variable("idx", 0_u64);
        cg::while_([&] { return idx.get() :    vpmulld (%rsi,%r9,4),%ymm0,%ymm1
   0x00007fffefd27146 :    vpmulld 0x20(%rsi,%r9,4),%ymm0,%ymm2
   0x00007fffefd2714d :    vpmulld 0x40(%rsi,%r9,4),%ymm0,%ymm3
   0x00007fffefd27154 :    vpmulld 0x60(%rsi,%r9,4),%ymm0,%ymm4
   0x00007fffefd2715b :    vpaddd (%rdx,%r9,4),%ymm1,%ymm1
   0x00007fffefd27161 :    vpaddd 0x20(%rdx,%r9,4),%ymm2,%ymm2
   0x00007fffefd27168 :    vpaddd 0x40(%rdx,%r9,4),%ymm3,%ymm3
   0x00007fffefd2716f :    vpaddd 0x60(%rdx,%r9,4),%ymm4,%ymm4
   0x00007fffefd27176 :    vmovdqu %ymm1,(%rcx,%r9,4)
   0x00007fffefd2717c :    vmovdqu %ymm2,0x20(%rcx,%r9,4)
   0x00007fffefd27183 :    vmovdqu %ymm3,0x40(%rcx,%r9,4)
   0x00007fffefd2718a :    vmovdqu %ymm4,0x60(%rcx,%r9,4)
   0x00007fffefd27191 :    vpmulld 0x80(%rsi,%r9,4),%ymm0,%ymm1
   0x00007fffefd2719b :    vpmulld 0xa0(%rsi,%r9,4),%ymm0,%ymm2
   0x00007fffefd271a5 :    vpmulld 0xc0(%rsi,%r9,4),%ymm0,%ymm3
   0x00007fffefd271af :    vpmulld 0xe0(%rsi,%r9,4),%ymm0,%ymm4
   0x00007fffefd271b9 :    vpaddd 0x80(%rdx,%r9,4),%ymm1,%ymm1
   0x00007fffefd271c3 :    vpaddd 0xa0(%rdx,%r9,4),%ymm2,%ymm2
   0x00007fffefd271cd :    vpaddd 0xc0(%rdx,%r9,4),%ymm3,%ymm3
   0x00007fffefd271d7 :    vpaddd 0xe0(%rdx,%r9,4),%ymm4,%ymm4
   0x00007fffefd271e1 :    vmovdqu %ymm1,0x80(%rcx,%r9,4)
   0x00007fffefd271eb :    vmovdqu %ymm2,0xa0(%rcx,%r9,4)
   0x00007fffefd271f5 :    vmovdqu %ymm3,0xc0(%rcx,%r9,4)
   0x00007fffefd271ff :    vmovdqu %ymm4,0xe0(%rcx,%r9,4)
8            idx = (idx + 1);
   0x00007fffefd27209 :    add    $0x40,%r9
   0x00007fffefd2720d :    add    $0x2,%r11
   0x00007fffefd27211 :    jne    0x7fffefd27140 
   0x00007fffefd27217 :    test   %r10,%r10
   0x00007fffefd2721a :    je     0x7fffefd2726d 

At the moment, CodeGen doesn't need to know anything about the ABI or the hardware architecture, which means that it can easily support all compilation targets that LLVM does. Below is the

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C++c-plus-pluscodegenjitllvm

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
CategoryAI 编程
PricingOpen source

> Related tools

G
GitHub Copilot
GitHub 官方 AI 编程助手,覆盖补全、Chat 与 Agent 模式。
C
Cursor
AI 原生代码编辑器,对话改代码、多文件 Agent 与规则体系是其核心。
S
skills
Skills for Real Engineers. Straight from my .agents directory.