Standard library · Compiler and tools

llvm

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.

llvm-guide-text.salam
import llvm
import io
import os

func main:
    path := os.TempDir() + "/salam_guide_sum.ll"
    _ := io.WriteFile(path, `define i32 @main() {
entry:
  br label %loop
loop:
  %i = phi i32 [ 1, %entry ], [ %next, %loop ]
  %acc = phi i32 [ 0, %entry ], [ %sum, %loop ]
  %sum = add i32 %acc, %i
  %next = add i32 %i, 1
  %more = icmp sle i32 %next, 10
  br i1 %more, label %loop, label %done
done:
  ret i32 %sum
}
`)
    parsed := llvm.ParseIR(path)
    if not parsed.ok:
        println "parse error:", parsed.err
        ret 1
    end
    checked := llvm.Verify(parsed.mod)
    println "valid:", checked.ok
    llvm.FreeModule(parsed.mod)
    llvm.FreeContext(parsed.ctx)
    r := llvm.RunJIT(path)
    println "sum of 1..10 =", r.rc
end

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
import str

func main:
    program := "2 3 + 4 * 6 -"
    ctx := llvm.NewContext()
    mod := llvm.NewModule(ctx, "rpn")
    b := llvm.NewBuilder(ctx)
    i32 := llvm.Int32Type(ctx)
    none := Vector {} as Vector<llvm.Type>
    fn := llvm.AddFunction(mod, "main", llvm.FunctionType(i32, none, false))
    llvm.PositionAtEnd(b, llvm.AppendBlock(ctx, fn, "entry"))
    mut stack := Vector {} as Vector<llvm.Value>
    each word in str.Split(program, " "):
        if word == "+" or word == "-" or word == "*":
            r := stack.Pop()
            l := stack.Pop()
            if word == "+": stack.Push(llvm.Add(b, l, r, "t")) end
            if word == "-": stack.Push(llvm.Sub(b, l, r, "t")) end
            if word == "*": stack.Push(llvm.Mul(b, l, r, "t")) end
        else:
            stack.Push(llvm.ConstInt(i32, str.ToInt(word) as i64))
        end
    end
    _ := 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.

llvm-guide-verify.salam
import llvm

func main:
    ctx := llvm.NewContext()
    mod := llvm.NewModule(ctx, "broken")
    b := llvm.NewBuilder(ctx)
    i32 := llvm.Int32Type(ctx)
    none := Vector {} as Vector<llvm.Type>
    fn := llvm.AddFunction(mod, "answer", llvm.FunctionType(i32, none, false))
    llvm.PositionAtEnd(b, llvm.AppendBlock(ctx, fn, "entry"))
    _ := llvm.Add(b, llvm.ConstInt(i32, 40), llvm.ConstInt(i32, 2), "x")
    checked := llvm.Verify(mod)
    if not checked.ok:
        println "rejected:", checked.err
    end
    llvm.FreeBuilder(b)
    llvm.FreeModule(mod)
    llvm.FreeContext(ctx)
end

An object file and a static program

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

func main:
    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)
    if not built.ok:
        println "compile failed:", built.error
        ret 1
    end
    println "can link here:", llvm.CanLinkTriple(opts.target_triple)
    linked := llvm.LinkAuto(opts.output_file, dir + "/salam_guide_static", opts)
    if not linked.ok:
        println "link failed:", linked.err
        ret 1
    end
    println "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.

llvm-guide-opt.salam
import llvm
import io
import os
import str

func main:
    path := os.TempDir() + "/salam_guide_square.ll"
    _ := io.WriteFile(path, `define i32 @square_sum(i32 %n) {
entry:
  %a = alloca i32
  store i32 0, ptr %a
  %x = mul i32 %n, %n
  %old = load i32, ptr %a
  %new = add i32 %old, %x
  store i32 %new, ptr %a
  %r = load i32, ptr %a
  ret i32 %r
}
`)
    parsed := llvm.ParseIR(path)
    if not parsed.ok:
        println parsed.err
        ret 1
    end
    made := llvm.NewTargetMachine("x86_64-unknown-linux-gnu", llvm.OPT_O2, false)
    if not made.ok:
        println made.err
        ret 1
    end
    llvm.SetTargetTriple(parsed.mod, "x86_64-unknown-linux-gnu")
    llvm.ApplyDataLayout(parsed.mod, made.tm)
    opt := llvm.RunOpt(parsed.mod, made.tm, llvm.OPT_O2)
    if not opt.ok:
        println opt.err
        ret 1
    end
    text := llvm.ModuleToString(parsed.mod)
    each line in str.Split(text, "\n"):
        if str.StartsWith(line, "define") or str.StartsWith(line, "  "):
            println line
        end
    end
    asm := os.TempDir() + "/salam_guide_square.s"
    emitted := llvm.EmitAsm(parsed.mod, made.tm, asm)
    if not emitted.ok:
        println emitted.err
        ret 1
    end
    each line in str.Split(io.ReadFile(asm), "\n"):
        if str.StartsWith(line, "\t") and not str.StartsWith(line, "\t."):
            println str.Trim(str.Replace(line, "\t", " "))
        end
    end
    llvm.FreeTargetMachine(made.tm)
    llvm.FreeModule(parsed.mod)
    llvm.FreeContext(parsed.ctx)
end
define i32 @square_sum(i32 %n) local_unnamed_addr #0 {
  %x = mul i32 %n, %n
  ret i32 %x
movl %edi, %eax
imull %edi, %eax
retq

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

JobFunctions
Read IR textParseIR, then Verify
Build IR from codeNewContext, NewModule, NewBuilder, then AddFunction, AppendBlock and the instruction functions
Run it nowRunJIT, RunJITArgs
The whole pipeline from a fileRun with OptionsDefault
Fine control over optimizing and emittingNewTargetMachine, RunOpt, EmitObject, EmitAsm
Link an objectLinkAuto, or LinkExternal for the system linker

Types

TargetMachine

struct TargetMachine
The target machine: the architecture, the CPU and the optimization level for generating code.
NameTypeDescription
handlevoid*The internal LLVM handle.
llvm-Target.salam
import llvm
import os

func build(ctx: llvm.Context): llvm.Module:
    mod := llvm.NewModule(ctx, "calc")
    b := llvm.NewBuilder(ctx)
    i32 := llvm.Int32Type(ctx)
    mut two := Vector {} as Vector<llvm.Type>
    two.Push(i32)
    two.Push(i32)
    fn := llvm.AddFunction(mod, "salam_add", llvm.FunctionType(i32, two, false))
    llvm.PositionAtEnd(b, llvm.AppendBlock(ctx, fn, "entry"))
    _ := llvm.Ret(b, llvm.Add(b, llvm.Param(fn, 0), llvm.Param(fn, 1), "s"))
    llvm.FreeBuilder(b)
    ret mod
end

func main:
    llvm.InitTargets()
    println llvm.DefaultTriple().Len() > 0
    println llvm.CodeGenLevelOf(llvm.OPT_O2) == llvm.CODEGEN_LEVEL_DEFAULT, llvm.PassPipelineOf(llvm.OPT_O3)
    println llvm.OPT_O0, llvm.OPT_O1, llvm.OPT_OS, llvm.OPT_OZ
    println llvm.CODEGEN_LEVEL_NONE, llvm.CODEGEN_LEVEL_LESS, llvm.CODEGEN_LEVEL_AGGRESSIVE
    println llvm.CODEGEN_FILE_ASSEMBLY, llvm.CODEGEN_FILE_OBJECT, llvm.RELOC_DEFAULT, llvm.RELOC_PIC, llvm.CODE_MODEL_DEFAULT

    machine := llvm.NewTargetMachine("", llvm.OPT_O2, false)
    if not machine.ok:
        println "the target machine was not built:", machine.err
        ret
    end
    ctx := llvm.NewContext()
    mod := build(ctx)
    llvm.ApplyDataLayout(mod, machine.tm)
    optimized := llvm.RunOpt(mod, machine.tm, llvm.OPT_O2)
    println optimized.ok
    dir := os.TempDir()
    println llvm.EmitAsm(mod, machine.tm, dir + "/salam_add_en.s").ok
    println llvm.EmitObject(mod, machine.tm, dir + "/salam_add_en.o").ok
    println llvm.EmitBitcode(mod, dir + "/salam_add_en.bc").ok

    println llvm.ParallelJobs() > 0
    parts := llvm.ParallelPartitions(mod, 4)
    println parts >= 1
    mod2 := build(ctx)
    parallel := llvm.OptimizeEmitParallel(mod2, machine.tm, llvm.OPT_O2, 2, dir + "/salam_part_en")
    println parallel.ok, parallel.objects.Len() >= 1
    llvm.FreeModule(mod)
    llvm.FreeModule(mod2)
    llvm.FreeTargetMachine(machine.tm)
    llvm.FreeContext(ctx)
end

TargetData

struct TargetData
A target's data layout.
NameTypeDescription
handlevoid*The internal LLVM handle.

The example for this item is shown with the ones above: llvm-Target.salam

TargetMachineResult

struct TargetMachineResult
The result of making a target machine.
NameTypeDescription
tmTargetMachineThe target machine.
okbool = falseIt worked.
errstr = ""The error message.

The example for this item is shown with the ones above: llvm-Target.salam

LinkResult

struct LinkResult
The result of linking.
NameTypeDescription
okbool = falseIt worked.
errstr = ""The error message.
llvm-Run.salam
import llvm
import io
import os
import mem

func main:
    println llvm.Available()
    dir := os.TempDir()
    ll := dir + "/salam_args_en.ll"
    _ := io.WriteFile(ll, `define i32 @main(i32 %argc, ptr %argv) {
entry:
  %n = mul i32 %argc, 10
  ret i32 %n
}
`)

    parsed := llvm.ParseIR(ll)
    println parsed.ok
    checked := llvm.Verify(parsed.mod)
    println checked.ok, llvm.VERIFY_RETURN_STATUS
    llvm.SetTargetTriple(parsed.mod, llvm.DefaultTriple())
    println llvm.TargetTripleOf(parsed.mod) == llvm.DefaultTriple()
    llvm.FreeModule(parsed.mod)
    llvm.FreeContext(parsed.ctx)

    mut args := Vector {} as Vector<str>
    args.Push("a")
    args.Push("b")
    println llvm.RunJITArgs(ll, args).rc

    mut opts := llvm.OptionsDefault()
    println opts.opt_level, opts.output_mode
    opts.output_mode = llvm.OUT_JIT
    opts.run_args = args
    println llvm.Run(ll, opts).rc
    opts.output_mode = llvm.OUT_OBJ
    opts.output_file = dir + "/salam_args_en.o"
    println llvm.Run(ll, opts).ok
    opts.output_mode = llvm.OUT_ASM
    opts.output_file = dir + "/salam_args_en.s"
    println llvm.Run(ll, opts).ok
    println llvm.OUT_IR, llvm.OUT_BITCODE, llvm.OUT_EXEC

    println llvm.HostLinkTriple(), llvm.LldAvailable()
    println llvm.CanLinkTriple("x86_64-unknown-linux-musl"), llvm.CanLinkTriple("x86_64-w64-windows-gnu"), llvm.CanLinkTriple("aarch64-apple-darwin")
    println llvm.LLD_ELF, llvm.LLD_MINGW, llvm.LLD_COFF, llvm.LLD_MACHO, llvm.LLD_WASM
    linked := llvm.LinkExternal(dir + "/salam_args_en.o", dir + "/salam_args_en", llvm.OptionsDefault())
    println linked.ok, linked.err
    if linked.ok:
        println os.Run(dir + "/salam_args_en x y")
    end

    mut musl := llvm.OptionsDefault()
    musl.target_triple = "x86_64-unknown-linux-musl"
    println llvm.LinkAuto(dir + "/salam_args_en.o", dir + "/salam_args_en_musl", musl).ok
    _ := llvm.LinkElf(dir + "/a.o", dir + "/a", musl)
    _ := llvm.LinkMingw(dir + "/a.o", dir + "/a.exe", musl)
    _ := llvm.LinkWasi(dir + "/a.o", dir + "/a.wasm", musl)
    mut argv := mem.Allocate(64 as u64) as str*
    argv[0] = "ld.lld"
    argv[1] = "--version"
    println llvm.Link(llvm.LLD_ELF, argv as void*, 2)
    mem.Free(argv as void*)
end

EmitResult

struct EmitResult
The result of emitting a file.
NameTypeDescription
okbool = falseIt worked.
errstr = ""The error message.

The example for this item is shown with the ones above: llvm-Target.salam

Context

struct Context
An LLVM context; every type and module belongs to one.
NameTypeDescription
handlevoid*The internal LLVM handle.
llvm-Build.salam
import llvm
import io
import os

func main:
    ctx := llvm.NewContext()
    mod := llvm.NewModule(ctx, "fib")
    b := llvm.NewBuilder(ctx)
    i32 := llvm.Int32Type(ctx)

    none := Vector {} as Vector<llvm.Type>
    main_type := llvm.FunctionType(i32, none, false)
    entry_fn := llvm.AddFunction(mod, "main", main_type)
    start := llvm.AppendBlock(ctx, entry_fn, "entry")
    body := llvm.AppendBlock(ctx, entry_fn, "loop")
    tail := llvm.AppendBlock(ctx, entry_fn, "done")

    llvm.PositionAtEnd(b, start)
    _ := llvm.Br(b, body)
    llvm.PositionAtEnd(b, body)
    counter := llvm.Phi(b, i32, "i")
    a := llvm.Phi(b, i32, "a")
    c := llvm.Phi(b, i32, "b")
    total := llvm.Add(b, a, c, "sum")
    next := llvm.Add(b, counter, llvm.ConstInt(i32, 1), "inext")
    more := llvm.ICmp(b, llvm.INT_SLT, next, llvm.ConstInt(i32, 10), "more")
    _ := llvm.CondBr(b, more, body, tail)

    mut sources := Vector {} as Vector<llvm.BasicBlock>
    sources.Push(start)
    sources.Push(body)
    mut counter_in := Vector {} as Vector<llvm.Value>
    counter_in.Push(llvm.ConstInt(i32, 0))
    counter_in.Push(next)
    llvm.AddIncoming(counter, counter_in, sources)
    mut a_in := Vector {} as Vector<llvm.Value>
    a_in.Push(llvm.ConstInt(i32, 0))
    a_in.Push(c)
    llvm.AddIncoming(a, a_in, sources)
    mut c_in := Vector {} as Vector<llvm.Value>
    c_in.Push(llvm.ConstInt(i32, 1))
    c_in.Push(total)
    llvm.AddIncoming(c, c_in, sources)
    llvm.PositionAtEnd(b, tail)
    _ := llvm.Ret(b, c)

    checked := llvm.Verify(mod)
    println checked.ok
    print llvm.ModuleToString(mod)
    path := os.TempDir() + "/salam_fib_en.ll"
    _ := io.WriteFile(path, llvm.ModuleToString(mod))
    r := llvm.RunJIT(path)
    println r.ok, r.rc
    llvm.FreeBuilder(b)
    llvm.FreeModule(mod)
    llvm.FreeContext(ctx)
end

Module

struct Module
One module: its functions and global variables.
NameTypeDescription
handlevoid*The internal LLVM handle.

The example for this item is shown with the ones above: llvm-Build.salam

ParseResult

struct ParseResult
The result of parsing IR.
NameTypeDescription
ctxContextThe context that was made; free it too.
modModuleThe module.
okbool = falseIt worked.
errstr = ""The error message.

The example for this item is shown with the ones above: llvm-Run.salam

VerifyResult

struct VerifyResult
The result of verifying.
NameTypeDescription
okbool = falseThe module is correct.
errstr = ""What the error is.

The example for this item is shown with the ones above: llvm-Build.salam

Type

struct Type
One LLVM type.
NameTypeDescription
handlevoid*The internal LLVM handle.

The example for this item is shown with the ones above: llvm-Build.salam

Value

struct Value
One value: a constant, an instruction, a parameter or a function.
NameTypeDescription
handlevoid*The internal LLVM handle.

The example for this item is shown with the ones above: llvm-Build.salam

BasicBlock

struct BasicBlock
One basic block: the instructions that end with a jump or a return.
NameTypeDescription
handlevoid*The internal LLVM handle.

The example for this item is shown with the ones above: llvm-Build.salam

Builder

struct Builder
The instruction builder; it adds the instructions at the end of the current block.
NameTypeDescription
handlevoid*The internal LLVM handle.

The example for this item is shown with the ones above: llvm-Build.salam

RunResult

struct RunResult
The result of running with the JIT.
NameTypeDescription
okbool = falseIt worked.
rcint = 0What main returned.
errstr = ""The error message.

The example for this item is shown with the ones above: llvm-Build.salam

OptResult

struct OptResult
The result of optimizing.
NameTypeDescription
okbool = falseIt worked.
errstr = ""The error message.

The example for this item is shown with the ones above: llvm-Target.salam

Options

struct Options
The options of the Run pipeline.
NameTypeDescription
opt_levelint = 0The optimization level.
debug_infobool = falseKeep the debug information.
verify_modulebool = falseVerify the module before generating.
native_cpubool = falseOptimize for this machine's own CPU.
cpustr = ""Build for this CPU level, such as x86-64-v3 (x86-64 targets only).
output_modeint = 0The output kind, one of the OUT_... constants.
output_filestr = ""The output path.
target_triplestr = ""The target triple; empty means the module's triple.
link_libsVectorThe libraries that are linked.
link_kindsVectorEach library's kind: static or dynamic.
sysrootstr = ""The target system's root for cross linking.
lib_pathsVectorThe library search paths.
extra_objectsVectorOther object files to link.
run_argsVectorThe arguments for running with the JIT.

The example for this item is shown with the ones above: llvm-Run.salam

Output

struct Output
The result of Run.
NameTypeDescription
okbool = falseIt worked.
errorstr = ""The error message.
rcint = 0The program's exit code in JIT mode.

The example for this item is shown with the ones above: llvm-Build.salam

ParallelResult

struct ParallelResult
The result of generating in parallel.
NameTypeDescription
okbool = falseIt worked.
errstr = ""The error message.
objectsVectorThe object files that were built.

The example for this item is shown with the ones above: llvm-Target.salam

Constants and variables

LLD_ELF

const LLD_ELF: i32 = 0
The LLD flavour for ELF.

The example for this item is shown with the ones above: llvm-Run.salam

LLD_MINGW

const LLD_MINGW: i32 = 1
The LLD flavour for MinGW.

The example for this item is shown with the ones above: llvm-Run.salam

LLD_COFF

const LLD_COFF: i32 = 2
The LLD flavour for Windows COFF.

The example for this item is shown with the ones above: llvm-Run.salam

LLD_MACHO

const LLD_MACHO: i32 = 3
The LLD flavour for macOS Mach-O.

The example for this item is shown with the ones above: llvm-Run.salam

LLD_WASM

const LLD_WASM: i32 = 4
The LLD flavour for WebAssembly.

The example for this item is shown with the ones above: llvm-Run.salam

VERIFY_RETURN_STATUS

const VERIFY_RETURN_STATUS: i32 = 2
The verifying mode that returns the error instead of stopping the program.

The example for this item is shown with the ones above: llvm-Run.salam

INT_EQ

const INT_EQ: i32 = 32
Integer comparison predicate: equal.
llvm-Program.salam
import llvm
import io
import os

func main:
    ctx := llvm.NewContext()
    mod := llvm.NewModule(ctx, "hello")
    b := llvm.NewBuilder(ctx)
    i32 := llvm.Int32Type(ctx)
    i64 := llvm.Int64Type(ctx)
    f64 := llvm.DoubleType(ctx)
    ptr := llvm.PointerType(ctx)
    _ := llvm.Int1Type(ctx)
    _ := llvm.Int8Type(ctx)
    _ := llvm.Int16Type(ctx)
    _ := llvm.FloatType(ctx)
    _ := llvm.ArrayType(i32, 4)

    mut fmt_params := Vector {} as Vector<llvm.Type>
    fmt_params.Push(ptr)
    fmt_type := llvm.FunctionType(i32, fmt_params, true)
    _ := llvm.AddFunction(mod, "printf", fmt_type)
    printer := llvm.NamedFunction(mod, "printf")

    mut two_numbers := Vector {} as Vector<llvm.Type>
    two_numbers.Push(i64)
    two_numbers.Push(i64)
    calc_type := llvm.FunctionType(i64, two_numbers, false)
    calc := llvm.AddFunction(mod, "calc", calc_type)
    llvm.SetLinkage(calc, llvm.LINKAGE_INTERNAL)
    llvm.PositionAtEnd(b, llvm.AppendBlock(ctx, calc, "entry"))
    l := llvm.Param(calc, 0)
    r := llvm.Param(calc, 1)
    t := llvm.Sub(b, llvm.Mul(b, l, r, "m"), llvm.SDiv(b, l, r, "d"), "t")
    _ := llvm.Ret(b, llvm.Add(b, t, llvm.SRem(b, l, r, "r"), "x"))

    count := llvm.AddGlobal(mod, i64, "count")
    llvm.SetInitializer(count, llvm.ConstInt(i64, 40))
    pi := llvm.AddGlobal(mod, f64, "pi")
    llvm.SetInitializer(pi, llvm.ConstReal(f64, 3.14))
    llvm.SetGlobalConstant(pi, true)

    none := Vector {} as Vector<llvm.Type>
    entry_fn := llvm.AddFunction(mod, "main", llvm.FunctionType(i32, none, false))
    llvm.PositionAtEnd(b, llvm.AppendBlock(ctx, entry_fn, "entry"))
    println llvm.InsertBlock(b).handle != null
    slot := llvm.Alloca(b, i64, "n")
    _ := llvm.Store(b, llvm.Load(b, i64, count, "c"), slot)
    mut args := Vector {} as Vector<llvm.Value>
    args.Push(llvm.Load(b, i64, slot, "n1"))
    args.Push(llvm.ConstInt(i64, 8))
    result := llvm.Call(b, calc_type, calc, args, "v")
    mut fmt_args := Vector {} as Vector<llvm.Value>
    fmt_args.Push(llvm.GlobalString(b, "calc(40, 8) = %lld\n", "fmt"))
    fmt_args.Push(result)
    _ := llvm.Call(b, fmt_type, printer, fmt_args, "")
    _ := llvm.Ret(b, llvm.ConstInt(i32, 0))

    empty := Vector {} as Vector<llvm.Type>
    noop := llvm.AddFunction(mod, "noop", llvm.FunctionType(llvm.VoidType(ctx), empty, false))
    llvm.SetLinkage(noop, llvm.LINKAGE_PRIVATE)
    llvm.PositionAtEnd(b, llvm.AppendBlock(ctx, noop, "entry"))
    _ := llvm.RetVoid(b)
    println llvm.LINKAGE_EXTERNAL, llvm.Verify(mod).ok
    println llvm.INT_EQ, llvm.INT_NE, llvm.INT_UGT, llvm.INT_UGE, llvm.INT_ULT, llvm.INT_ULE
    println llvm.INT_SGT, llvm.INT_SGE, llvm.INT_SLT, llvm.INT_SLE

    path := os.TempDir() + "/salam_hello_en.ll"
    _ := io.WriteFile(path, llvm.ModuleToString(mod))
    println llvm.RunJIT(path).rc
    llvm.FreeBuilder(b)
    llvm.FreeModule(mod)
    llvm.FreeContext(ctx)
end

INT_NE

const INT_NE: i32 = 33
Integer comparison predicate: not equal.

The example for this item is shown with the ones above: llvm-Program.salam

INT_UGT

const INT_UGT: i32 = 34
Integer comparison predicate: greater, unsigned.

The example for this item is shown with the ones above: llvm-Program.salam

INT_UGE

const INT_UGE: i32 = 35
Integer comparison predicate: greater or equal, unsigned.

The example for this item is shown with the ones above: llvm-Program.salam

INT_ULT

const INT_ULT: i32 = 36
Integer comparison predicate: less, unsigned.

The example for this item is shown with the ones above: llvm-Program.salam

INT_ULE

const INT_ULE: i32 = 37
Integer comparison predicate: less or equal, unsigned.

The example for this item is shown with the ones above: llvm-Program.salam

INT_SGT

const INT_SGT: i32 = 38
Integer comparison predicate: greater, signed.

The example for this item is shown with the ones above: llvm-Program.salam

INT_SGE

const INT_SGE: i32 = 39
Integer comparison predicate: greater or equal, signed.

The example for this item is shown with the ones above: llvm-Program.salam

INT_SLT

const INT_SLT: i32 = 40
Integer comparison predicate: less, signed.

The example for this item is shown with the ones above: llvm-Build.salam

INT_SLE

const INT_SLE: i32 = 41
Integer comparison predicate: less or equal, signed.

The example for this item is shown with the ones above: llvm-Program.salam

LINKAGE_EXTERNAL

const LINKAGE_EXTERNAL: i32 = 0
External linkage: it is seen from other modules.

The example for this item is shown with the ones above: llvm-Program.salam

LINKAGE_INTERNAL

const LINKAGE_INTERNAL: i32 = 8
Internal linkage: only in this module, like static in C.

The example for this item is shown with the ones above: llvm-Program.salam

LINKAGE_PRIVATE

const LINKAGE_PRIVATE: i32 = 9
Private linkage: it does not even appear in the symbol table.

The example for this item is shown with the ones above: llvm-Program.salam

OPT_O0

const OPT_O0: i32 = 0
Optimization level: no optimization.

The example for this item is shown with the ones above: llvm-Target.salam

OPT_O1

const OPT_O1: i32 = 1
Optimization level: a little optimization.

The example for this item is shown with the ones above: llvm-Target.salam

OPT_O2

const OPT_O2: i32 = 2
Optimization level: the usual optimization.

The example for this item is shown with the ones above: llvm-Target.salam

OPT_O3

const OPT_O3: i32 = 3
Optimization level: aggressive optimization.

The example for this item is shown with the ones above: llvm-Target.salam

OPT_OS

const OPT_OS: i32 = 4
Optimization level: make the code small.

The example for this item is shown with the ones above: llvm-Target.salam

OPT_OZ

const OPT_OZ: i32 = 5
Optimization level: the smallest code.

The example for this item is shown with the ones above: llvm-Target.salam

OUT_IR

const OUT_IR: i32 = 0
Output kind: IR text.

The example for this item is shown with the ones above: llvm-Run.salam

OUT_ASM

const OUT_ASM: i32 = 1
Output kind: assembly.

The example for this item is shown with the ones above: llvm-Run.salam

OUT_OBJ

const OUT_OBJ: i32 = 2
Output kind: an object file.

The example for this item is shown with the ones above: llvm-Run.salam

OUT_BITCODE

const OUT_BITCODE: i32 = 3
Output kind: bitcode.

The example for this item is shown with the ones above: llvm-Run.salam

OUT_EXEC

const OUT_EXEC: i32 = 4
Output kind: an executable.

The example for this item is shown with the ones above: llvm-Run.salam

OUT_JIT

const OUT_JIT: i32 = 5
Output kind: running with the JIT.

The example for this item is shown with the ones above: llvm-Run.salam

CODEGEN_FILE_ASSEMBLY

const CODEGEN_FILE_ASSEMBLY: i32 = 0
The generated file kind: assembly.

The example for this item is shown with the ones above: llvm-Target.salam

CODEGEN_FILE_OBJECT

const CODEGEN_FILE_OBJECT: i32 = 1
The generated file kind: an object.

The example for this item is shown with the ones above: llvm-Target.salam

CODEGEN_LEVEL_NONE

const CODEGEN_LEVEL_NONE: i32 = 0
Code generation level: no optimization.

The example for this item is shown with the ones above: llvm-Target.salam

CODEGEN_LEVEL_LESS

const CODEGEN_LEVEL_LESS: i32 = 1
Code generation level: less.

The example for this item is shown with the ones above: llvm-Target.salam

CODEGEN_LEVEL_DEFAULT

const CODEGEN_LEVEL_DEFAULT: i32 = 2
Code generation level: the default.

The example for this item is shown with the ones above: llvm-Target.salam

CODEGEN_LEVEL_AGGRESSIVE

const CODEGEN_LEVEL_AGGRESSIVE: i32 = 3
Code generation level: aggressive.

The example for this item is shown with the ones above: llvm-Target.salam

RELOC_DEFAULT

const RELOC_DEFAULT: i32 = 0
The default relocation model.

The example for this item is shown with the ones above: llvm-Target.salam

RELOC_PIC

const RELOC_PIC: i32 = 2
Position independent code, for shared libraries.

The example for this item is shown with the ones above: llvm-Target.salam

CODE_MODEL_DEFAULT

const CODE_MODEL_DEFAULT: i32 = 0
The default code model.

The example for this item is shown with the ones above: llvm-Target.salam

Functions

InitTargets

func InitTargets()
Initializes every LLVM target; call it once before making a target machine.

The example for this item is shown with the ones above: llvm-Target.salam

CodeGenLevelOf

func CodeGenLevelOf(opt_level: int): int
The code generation level that matches an optimization level.

The example for this item is shown with the ones above: llvm-Target.salam

PassPipelineOf

func PassPipelineOf(opt_level: int): str
The pass pipeline for an optimization level, like default<O3>.

The example for this item is shown with the ones above: llvm-Target.salam

DefaultTriple

func DefaultTriple(): str
The host machine's target triple, like x86_64-unknown-linux-gnu.

The example for this item is shown with the ones above: llvm-Target.salam

NewTargetMachine

func NewTargetMachine(triple: str, opt_level: int, native_cpu: bool): TargetMachineResult
Makes a target machine for a triple, an optimization level and the native CPU; an empty triple means the host.

The example for this item is shown with the ones above: llvm-Target.salam

FreeTargetMachine

func FreeTargetMachine(tm: TargetMachine)
Frees the target machine.

The example for this item is shown with the ones above: llvm-Target.salam

ApplyDataLayout

func ApplyDataLayout(mod: Module, tm: TargetMachine)
Puts the target machine's data layout and triple on the module.

The example for this item is shown with the ones above: llvm-Target.salam

CanLinkTriple

func CanLinkTriple(t: str): bool
This target links with the in-process LLD: Windows with MinGW, Linux with musl and WASI. It does not check that the sysroot is installed.

The example for this item is shown with the ones above: llvm-Run.salam

LinkExternal

func LinkExternal(obj: str, out_path: str, opts: Options): LinkResult
Links with the system linker, like cc.

The example for this item is shown with the ones above: llvm-Run.salam

HostLinkTriple

func HostLinkTriple(): str
The host triple if the in process LLD can link for it; otherwise empty.

The example for this item is shown with the ones above: llvm-Run.salam

LinkElf

func LinkElf(obj: str, out_path: str, opts: Options): LinkResult
A static Linux executable with musl.

The example for this item is shown with the ones above: llvm-Run.salam

LinkWasi

func LinkWasi(obj: str, out_path: str, opts: Options): LinkResult
A WebAssembly module for WASI.

The example for this item is shown with the ones above: llvm-Run.salam

LinkMingw

func LinkMingw(obj: str, out_path: str, opts: Options): LinkResult
A Windows executable with MinGW.

The example for this item is shown with the ones above: llvm-Run.salam

LinkAuto

func LinkAuto(obj: str, out_path: str, opts: Options): LinkResult
Picks the in-process linker from the options' target triple. It needs the target's sysroot (musl, MinGW or WASI) and fails for other triples.

The example for this item is shown with the ones above: llvm-Run.salam

Available

func Available(): bool
LLVM support is in this build.

The example for this item is shown with the ones above: llvm-Run.salam

Run

func Run(ll_path: str, opts: Options): Output
Runs the whole pipeline on a .ll file with the options: parsing, optimizing and emitting the output or running with the JIT.

The example for this item is shown with the ones above: llvm-Run.salam

LldAvailable

func LldAvailable(): bool
LLD is linked into this build.

The example for this item is shown with the ones above: llvm-Run.salam

func Link(flavor: int, argv: void*, argc: int): bool
Runs LLD with command line arguments; argv is an array of strings whose first one is the program name.

The example for this item is shown with the ones above: llvm-Run.salam

EmitAsm

func EmitAsm(mod: Module, tm: TargetMachine, path: str): EmitResult
Writes the module as assembly.

The example for this item is shown with the ones above: llvm-Target.salam

EmitObject

func EmitObject(mod: Module, tm: TargetMachine, path: str): EmitResult
Writes the module as an object file.

The example for this item is shown with the ones above: llvm-Target.salam

EmitBitcode

func EmitBitcode(mod: Module, path: str): EmitResult
Writes the module as LLVM bitcode.

The example for this item is shown with the ones above: llvm-Target.salam

NewContext

func NewContext(): Context
A new context.

The example for this item is shown with the ones above: llvm-Build.salam

FreeContext

func FreeContext(ctx: Context)
Frees the context, after its modules.

The example for this item is shown with the ones above: llvm-Build.salam

FreeModule

func FreeModule(mod: Module)
Frees the module.

The example for this item is shown with the ones above: llvm-Build.salam

ParseIR

func ParseIR(ll_path: str): ParseResult
Parses a text .ll file in a new context.

The example for this item is shown with the ones above: llvm-Run.salam

Verify

func Verify(mod: Module): VerifyResult
Verifies the module; call it before generating code or using the JIT.

The example for this item is shown with the ones above: llvm-Build.salam

TargetTripleOf

func TargetTripleOf(mod: Module): str
The module's target triple.

The example for this item is shown with the ones above: llvm-Run.salam

SetTargetTriple

func SetTargetTriple(mod: Module, triple: str)
Sets the module's target triple.

The example for this item is shown with the ones above: llvm-Run.salam

NewModule

func NewModule(ctx: Context, name: str): Module
A new module with a name.

The example for this item is shown with the ones above: llvm-Build.salam

ModuleToString

func ModuleToString(mod: Module): str
The module's IR text.

The example for this item is shown with the ones above: llvm-Build.salam

Int1Type

func Int1Type(c: Context): Type
The i1 type, for a boolean.

The example for this item is shown with the ones above: llvm-Program.salam

Int8Type

func Int8Type(c: Context): Type
The i8 type.

The example for this item is shown with the ones above: llvm-Program.salam

Int16Type

func Int16Type(c: Context): Type
The i16 type.

The example for this item is shown with the ones above: llvm-Program.salam

Int32Type

func Int32Type(c: Context): Type
The i32 type.

The example for this item is shown with the ones above: llvm-Build.salam

Int64Type

func Int64Type(c: Context): Type
The i64 type.

The example for this item is shown with the ones above: llvm-Program.salam

VoidType

func VoidType(c: Context): Type
The void type.

The example for this item is shown with the ones above: llvm-Program.salam

FloatType

func FloatType(c: Context): Type
The 32 bit float type.

The example for this item is shown with the ones above: llvm-Program.salam

DoubleType

func DoubleType(c: Context): Type
The 64 bit double type.

The example for this item is shown with the ones above: llvm-Program.salam

PointerType

func PointerType(c: Context): Type
The untyped ptr pointer type.

The example for this item is shown with the ones above: llvm-Program.salam

ArrayType

func ArrayType(elem: Type, n: i64): Type
An array type with a fixed length.

The example for this item is shown with the ones above: llvm-Program.salam

FunctionType

func FunctionType(ret_ty: Type, params: Vector<Type>, vararg: bool): Type
A function type with a return type, the parameters and the variadic flag, like printf.

The example for this item is shown with the ones above: llvm-Build.salam

AddFunction

func AddFunction(mod: Module, name: str, fnty: Type): Value
Adds a function to the module; with no block it is only a declaration.

The example for this item is shown with the ones above: llvm-Build.salam

NamedFunction

func NamedFunction(mod: Module, name: str): Value
The function with this name.

The example for this item is shown with the ones above: llvm-Program.salam

Param

func Param(fn: Value, idx: int): Value
Parameter number i of a function.

The example for this item is shown with the ones above: llvm-Program.salam

SetLinkage

func SetLinkage(v: Value, linkage: int)
Sets the linkage kind.

The example for this item is shown with the ones above: llvm-Program.salam

AppendBlock

func AppendBlock(c: Context, fn: Value, name: str): BasicBlock
Adds a new block at the end of a function.

The example for this item is shown with the ones above: llvm-Build.salam

NewBuilder

func NewBuilder(c: Context): Builder
A new builder.

The example for this item is shown with the ones above: llvm-Build.salam

PositionAtEnd

func PositionAtEnd(b: Builder, bb: BasicBlock)
Moves the builder to the end of a block.

The example for this item is shown with the ones above: llvm-Build.salam

InsertBlock

func InsertBlock(b: Builder): BasicBlock
The block the builder is writing in right now.

The example for this item is shown with the ones above: llvm-Program.salam

FreeBuilder

func FreeBuilder(b: Builder)
Frees the builder.

The example for this item is shown with the ones above: llvm-Build.salam

ConstInt

func ConstInt(ty: Type, v: i64): Value
An integer constant.

The example for this item is shown with the ones above: llvm-Build.salam

ConstReal

func ConstReal(ty: Type, v: f64): Value
A float constant.

The example for this item is shown with the ones above: llvm-Program.salam

Ret

func Ret(b: Builder, v: Value): Value
Returns from the function with a value.

The example for this item is shown with the ones above: llvm-Build.salam

RetVoid

func RetVoid(b: Builder): Value
Returns from the function with no value.

The example for this item is shown with the ones above: llvm-Program.salam

Add

func Add(b: Builder, l: Value, r: Value, name: str): Value
Addition.

The example for this item is shown with the ones above: llvm-Build.salam

Sub

func Sub(b: Builder, l: Value, r: Value, name: str): Value
Subtraction.

The example for this item is shown with the ones above: llvm-Program.salam

Mul

func Mul(b: Builder, l: Value, r: Value, name: str): Value
Multiplication.

The example for this item is shown with the ones above: llvm-Program.salam

SDiv

func SDiv(b: Builder, l: Value, r: Value, name: str): Value
Signed integer division.

The example for this item is shown with the ones above: llvm-Program.salam

SRem

func SRem(b: Builder, l: Value, r: Value, name: str): Value
Signed remainder.

The example for this item is shown with the ones above: llvm-Program.salam

ICmp

func ICmp(b: Builder, pred: int, l: Value, r: Value, name: str): Value
An integer comparison with one of the INT_... predicates; the result is an i1.

The example for this item is shown with the ones above: llvm-Build.salam

Br

func Br(b: Builder, dest: BasicBlock): Value
An unconditional jump.

The example for this item is shown with the ones above: llvm-Build.salam

CondBr

func CondBr(b: Builder, cond: Value, t: BasicBlock, f: BasicBlock): Value
A conditional jump.

The example for this item is shown with the ones above: llvm-Build.salam

Phi

func Phi(b: Builder, ty: Type, name: str): Value
The phi instruction: a value that depends on the block it came from; for loops.

The example for this item is shown with the ones above: llvm-Build.salam

AddIncoming

func AddIncoming(phi: Value, vals: Vector<Value>, blocks: Vector<BasicBlock>)
Adds pairs of a value and the block it came from to a phi.

The example for this item is shown with the ones above: llvm-Build.salam

Call

func Call(b: Builder, fnty: Type, fn: Value, args: Vector<Value>, name: str): Value
Calls a function with its type and the arguments; for a void function leave the name empty.

The example for this item is shown with the ones above: llvm-Program.salam

Alloca

func Alloca(b: Builder, ty: Type, name: str): Value
Takes room on the stack and returns a pointer to it.

The example for this item is shown with the ones above: llvm-Program.salam

Load

func Load(b: Builder, ty: Type, ptr: Value, name: str): Value
Reads a value from a pointer.

The example for this item is shown with the ones above: llvm-Program.salam

Store

func Store(b: Builder, val: Value, ptr: Value): Value
Writes a value into a pointer.

The example for this item is shown with the ones above: llvm-Program.salam

GlobalString

func GlobalString(b: Builder, s: str, name: str): Value
A global constant string and a pointer to it.

The example for this item is shown with the ones above: llvm-Program.salam

AddGlobal

func AddGlobal(mod: Module, ty: Type, name: str): Value
Adds a global variable.

The example for this item is shown with the ones above: llvm-Program.salam

SetInitializer

func SetInitializer(g: Value, v: Value)
A global variable's starting value.

The example for this item is shown with the ones above: llvm-Program.salam

SetGlobalConstant

func SetGlobalConstant(g: Value, flag: bool)
Makes a global variable constant.

The example for this item is shown with the ones above: llvm-Program.salam

RunJIT

func RunJIT(ll_path: str): RunResult
Runs a .ll file with the ORC JIT in this same process and calls main.

The example for this item is shown with the ones above: llvm-Build.salam

RunJITArgs

func RunJITArgs(ll_path: str, args: Vector<str>): RunResult
Like the routine above, with command line arguments.

The example for this item is shown with the ones above: llvm-Run.salam

RunOpt

func RunOpt(mod: Module, tm: TargetMachine, opt_level: int): OptResult
Runs the optimization passes on the module.

The example for this item is shown with the ones above: llvm-Target.salam

OptionsDefault

func OptionsDefault(): Options
The default options.

The example for this item is shown with the ones above: llvm-Run.salam

ParallelJobs

func ParallelJobs(): int
The number of parallel jobs, from the number of cores.

The example for this item is shown with the ones above: llvm-Target.salam

ParallelPartitions

func ParallelPartitions(mod: Module, jobs: int): int
The module is split into this many independent parts; never more than jobs.

The example for this item is shown with the ones above: llvm-Target.salam

OptimizeEmitParallel

func OptimizeEmitParallel(mod: Module, tm: TargetMachine, opt_level: int, parts: int, out_prefix: str): ParallelResult
Optimizes the module, splits it into parts and builds the object files in parallel, for building large programs faster.

The example for this item is shown with the ones above: llvm-Target.salam