Building, optimizing, running and linking code with LLVM.
import llvm
LLVM is the compiler infrastructure behind Salam's own native backend. This package binds its C API so that a Salam program can be a compiler: build or read IR in a Module, check it with Verify, optimize it, then run it at once with the JIT or write an object file and link it into an executable. Use it when you are writing a language, a query compiler or a code generator. To run Salam code itself you do not need it; salam build already goes through LLVM.
Core ideas
•
Context, module, builder. A Context owns everything LLVM allocates. A Module is one translation unit of functions and globals inside it. A Builder is a cursor that appends instructions to the end of a block.
•
Values are not numbers.Add, Load and the other instruction functions return a Value: the result the generated code will compute when it runs, not a result now.
•
Two ways in. Write IR as text and read it with ParseIR, or build it call by call. Both end in the same Module.
•
Two ways out.RunJIT compiles in memory and calls main. Run with an Options value, or NewTargetMachine, RunOpt and EmitObject step by step, write files for any target LLVM knows.
Things that trip people up
•
ParseIR, RunJIT and Run take the path of a .ll file, not the IR text. Write the text to a file first, as the examples do.
•
RunJIT parses that file again by itself; it does not run a module you already have. Its rc is the i32 that main returned.
•
Invalid IR can crash LLVM later instead of producing an error. Call Verify on everything you build before you optimize or emit it.
•
The linker inside the program (LinkAuto) still needs the target's C library files: a musl sysroot for Linux, MinGW for Windows, a WASI sysroot for WebAssembly. Without one the link fails with a message naming the directory it looked in; point $SALAM_SYSROOTS or Options.sysroot at one.
•
Free in reverse order: builder, then module, then context.
Programs that use this package link against libsalam_llvm, so the site only compiles them. Build the library as the repository's LLVM backend instructions describe, then run them with salam run. The output shown is what they printed with LLVM 22 on x86-64 Linux.
Running IR you wrote as text
The shortest way in is to write LLVM IR as text, the same .ll format clang -S -emit-llvm prints, and save it to a file. ParseIR reads that file into a module in a fresh context and reports syntax errors in err; Verify then checks the rules the parser does not, such as every block ending in a branch or a return. RunJIT compiles the same file in memory and calls its main.
The loop adds 1 to 10, so the program prints valid: true and then sum of 1..10 = 55. The value of main comes back as rc, just like an exit code, which keeps the round trip simple while you are experimenting.
A tiny compiler with the builder
A real compiler does not glue strings together; it walks its own syntax tree and calls the builder. This one reads arithmetic in reverse Polish notation: a number pushes a constant on a stack, and an operator pops two values and pushes the instruction that combines them. A Value stands for a result that will exist at run time, so the stack holds instructions, not numbers.
llvm-guide-rpn.salam
import llvm
import io
import os
importstrfuncmain:
program := "2 3 + 4 * 6 -"
ctx := llvm.NewContext()
mod := llvm.NewModule(ctx, "rpn")
b := llvm.NewBuilder(ctx)
i32 := llvm.Int32Type(ctx)
none := Vector {} asVector<llvm.Type>
fn := llvm.AddFunction(
mod, "main", llvm.FunctionType(i32, none, false)
)
llvm.PositionAtEnd(b, llvm.AppendBlock(ctx, fn, "entry"))
mut stack := Vector {} asVector<llvm.Value>
each word instr.Split(program, " "):
if word == "+"or word == "-"or word == "*":
r := stack.Pop()
l := stack.Pop()
if word == "+": stack.Push(llvm.Add(b, l, r, "t")) endif word == "-": stack.Push(llvm.Sub(b, l, r, "t")) endif word == "*": stack.Push(llvm.Mul(b, l, r, "t")) endelse:
stack.Push(llvm.ConstInt(i32, str.ToInt(word) asi64))
endend
_ := llvm.Ret(b, stack.Pop())
println llvm.Verify(mod).ok
path := os.TempDir() + "/salam_guide_rpn.ll"
_ := io.WriteFile(path, llvm.ModuleToString(mod))
println program, "=", llvm.RunJIT(path).rc
llvm.FreeBuilder(b)
llvm.FreeModule(mod)
llvm.FreeContext(ctx)
end
(2 + 3) * 4 - 6 is 14, and that is what the JIT returns. With constants only, LLVM's builder folds the whole expression while you build it, so the IR is just ret i32 14; with parameters or loaded values you would see the add, mul and sub instructions.
Let Verify catch your mistakes
Bugs in a code generator usually produce IR that is not valid, and LLVM may crash on it later instead of reporting it. Call Verify after building a module and before optimizing or running it. Here the block computes a value but never returns, so the module is rejected with a message that names the problem.
Run takes the whole pipeline from one Options value: the optimization level, the target triple and what to produce. OUT_OBJ writes an object file for the chosen triple, even one that is not the machine you are on. For x86_64-unknown-linux-musl, LLD inside the program links it into a static executable with no system linker involved; CanLinkTriple says whether that is possible for a triple.
llvm-guide-static.salam
import llvm
import io
import os
funcmain:
dir := os.TempDir()
ll := dir + "/salam_guide_static.ll"
_ := io.WriteFile(ll, `define i32 @main() {
entry:
ret i32 7
}
`)
mut opts := llvm.OptionsDefault()
opts.opt_level = llvm.OPT_O2
opts.target_triple = "x86_64-unknown-linux-musl"
opts.output_mode = llvm.OUT_OBJ
opts.output_file = dir + "/salam_guide_static.o"
built := llvm.Run(ll, opts)
ifnot built.ok:
println"compile failed:", built.error
ret1endprintln"can link here:", llvm.CanLinkTriple(opts.target_triple)
linked := llvm.LinkAuto(opts.output_file, dir + "/salam_guide_static", opts)
ifnot linked.ok:
println"link failed:", linked.err
ret1endprintln"built", dir + "/salam_guide_static"end
On a machine without musl's files in /usr/lib/x86_64-linux-musl (the musl-dev package) or under $SALAM_SYSROOTS, the object is still written but the link step reports no musl sysroot. CanLinkTriple only tells you that LLD is built in and knows the triple; it does not look for the sysroot. The program it builds just exits with 7. For a Windows target use x86_64-w64-windows-gnu and an output ending in .exe; to work out sizes and file names from a triple without LLVM at all, see llvm.triple.
Optimize, then read the result
Looking at the optimized IR and the machine code is how you check that your generator produces what you meant. NewTargetMachine describes the target CPU; give the module the same triple and its data layout with SetTargetTriple and ApplyDataLayout, then RunOpt runs LLVM's standard O2 pipeline on it in place. ModuleToString prints the module as text and EmitAsm writes assembly to a file.
The input stores through a stack slot the way a naive code generator would. The optimizer turns the slot into registers, drops the add of zero and leaves one multiply, which becomes two x86 instructions. A front end can emit simple, slow-looking code like this and leave the cleanup to LLVM; that is the usual design. OPT_OS optimizes for size instead, and EmitObject writes a .o instead of assembly.
Which function for which job
Job
Functions
Read IR text
ParseIR, then Verify
Build IR from code
NewContext, NewModule, NewBuilder, then AddFunction, AppendBlock and the instruction functions