A direct -O0 code generator for LLVM An experiment that compiles functions directly from LLVM IR to machine code bytes, bypassing the MachineFunction pipeline and falling back to the regular pipeline one function at a time, cut compile-time instruction counts by 14% on x86-64 and 21% on AArch64 for `-O0 -g` builds, according to the post's compile-time tracker. The generated code is 10% larger on x86-64 and about the same size on AArch64, and `clang -S` output assembles to the same code `clang -c` emits. The author states the work relied heavily on an LLM agent (Claude Code), which wrote most of the code and drafted the post, with the author steering, and notes TPDE's single-pass back end executes 1.8x (sqlite3) to 3.5x (tramp3d) fewer instructions than this approach. This post describes an experiment that compiles a function directly from LLVM IR to machine code bytes, without building a MachineFunction , and falls back to the regular pipeline one function at a time. On the compile-time tracker, -O0 -g builds take 14% fewer instructions on x86-64 and 21% fewer on AArch64. The generated code is 10% larger on x86-64 and about the same size on AArch64, and clang -S output assembles to the same code that clang -c emits. Skipping the pipeline creates an obligation, and most of this post is about that obligation. This post relies heavily on an LLM agent Claude Code . It wrote most of the code and drafted this post, which I then edited. My part was steering. -O0 back-end time goes The back end's share of a clang -O0 compile ranges from 13% for ScalarEvolution.cpp to 39% for sqlite3. Within the back end, the cost is spread out: FastISel with its SelectionDAG fallback, RegAllocFast, prologue/epilogue insertion, the remaining MIR passes, legacy pass manager overhead, and MC lowering. Shares of back-end cycles from a profile llc -O0 -relocation-model=pic on x86-64, no assertions, bitcode parsing excluded, tramp3d built with -fno-exceptions , good to a few points: | Layer | sqlite3 | tramp3d | sqlite3 -g | tramp3d -g | |---|---|---|---|---| | ISel FastISel, SelectionDAG, driver | 43% | 28% | 30% | 19% | | RegAllocFast | 10% | 8% | 7% | 6% | | Prologue/epilogue insertion | 6% | 7% | 4% | 5% | | IR preparation passes | 7% | 9% | 6% | 6% | | Legacy pass manager | 5% | 10% | 3% | 7% | | MachineFunction allocation, other MIR passes, CFI | 9% | 8% | 7% | 6% | | LiveDebugValues | 0% | 1% | 9% | 9% | | AsmPrinter MI to MCInst | 7% | 6% | 6% | 5% | | MC encoding, streamer, object writer | 11% | 22% | 10% | 17% | | DWARF and .eh frame emission | 1% | 2% | 19% | 22% | llc -O0 -mtriple=x86 64-linux-gnu -debug-pass=Structure on define void @f { ret void } prints 72 entries under the function pass manager, counting repeated analyses, the printer and Free MachineFunction . An excerpt: FunctionPass Manager Expand IR instructions Expand Atomic instructions ... Exception handling preparation Prepare inline asm insts Safe Stack instrumentation pass Insert stack protectors Module Verifier Assignment Tracking Analysis X86 DAG- DAG Instruction Selection ... Eliminate PHI nodes for register allocation Machine Register Class Info Analysis Fast Register Allocator ... Prologue/Epilogue Insertion & Frame Finalization Post-RA pseudo instruction expansion pass X86 pseudo instruction expansion pass Insert KCFI indirect call checks Analyze Machine Code For Garbage Collection Insert fentry calls Insert XRay ops Implement the 'patchable-function' attribute X86 Indirect Branch Tracking ... Live DEBUG VALUE analysis ... X86 Indirect Thunks X86 Return Thunks Check CFA info and insert CFI instructions if needed X86 Load Value Injection LVI Ret-Hardening ... X86 Assembly Printer Free MachineFunction FastISel 2008 selects most instructions itself, hands the rest of a block to SelectionDAG when it cannot, and then runs the full MIR pipeline. GlobalISel is the AArch64 -O0 default. TPDE is a single-pass back end with per-module fallback, no DWARF, and its own ELF writer. TPDE's back end executes 1.8x sqlite3 to 3.5x tramp3d fewer instructions than the one described here. What this experiment adds is fallback per function into the same object file, debug info, respect for function attributes, hardening, and text output. From-scratch compilers written with AI assistance, such as Anthropic's CCC February 2026, Rust, with its own assembler and linker , are a useful contrast rather than a competitor. Counted like for like, its x86-64 and AArch64 code generators with their shared layer are about 30K lines, against about 5.9K here. They carry a register allocator, peepholes, inline asm, i128 and x87, with no fallback; the direct code generator hands those to the regular pipeline and carries DWARF, exception tables and hardening instead. The advantages worth claiming are structural: a small delta inside LLVM, the regular pipeline as a differential oracle for every function, per-function fallback, and reused DWARF and object writing. IR goes to encoded bytes with no MIR in between. It is not "one pass": the bytes are patched afterwards, and emission still goes through AsmPrinter and MC. DirectCodeGen is a function pass, first in the -O0 codegen function pass manager, enabled by -direct-codegen . It compiles a function into a private buffer: bytes, fixups, CFI points, line rows, variable slots, and a call-site table. Nothing shared is touched until the function succeeds, and the IR is never modified. On success, AsmPrinter::emitCompiledFunction emits the function header, the bytes and the tables, and the pass tells the pass manager to skip the remaining passes for this function. On failure, the function takes the regular pipeline into the same object file. php IR function | DirectCodeGen pass ---- any failure ---- regular pipeline | ISel, MIR passes, AsmPrinter | success | AsmPrinter::emitCompiledFunction | | | MCStreamer: the same .o or .s <---------------+ Section selection, linkage, alignment, DWARF and the object writer are reused, because they are not where the time goes. -direct-codegen-report prints the reason for each fallback, and -direct-codegen-abort turns a fallback into an error. A compare used only by its branch, a load used only by the next instruction, and a constant-offset address are folded into their user. Here is a small function with a local, a branch and a call: struct S { int n, count; }; int g int ; int f struct S p, int d { int t = d 2; if t 0 p- count += g t ; return p- count; } clang -O0 -emit-llvm gives, trimmed to the instructions: entry: %p.addr = alloca ptr, align 8 %d.addr = alloca i32, align 4 %t = alloca i32, align 4 store ptr %p, ptr %p.addr, align 8 store i32 %d, ptr %d.addr, align 4 %0 = load i32, ptr %d.addr, align 4 %mul = mul nsw i32 %0, 2 store i32 %mul, ptr %t, align 4 %1 = load i32, ptr %t, align 4 %cmp = icmp sgt i32 %1, 0 br i1 %cmp, label %if.then, label %if.end if.then: %2 = load i32, ptr %t, align 4 %call = call i32 @g i32 noundef %2 %3 = load ptr, ptr %p.addr, align 8 %count = getelementptr inbounds nuw %struct.S, ptr %3, i32 0, i32 1 %4 = load i32, ptr %count, align 4 %add = add nsw i32 %4, %call store i32 %add, ptr %count, align 4 br label %if.end if.end: %5 = load ptr, ptr %p.addr, align 8 %count1 = getelementptr inbounds nuw %struct.S, ptr %5, i32 0, i32 1 %6 = load i32, ptr %count1, align 4 ret i32 %6 and clang -O0 -S -mllvm -direct-codegen gives directives removed, comments added : f: pushq %rbp movq %rsp, %rbp subq $32, %rsp frame size patched in after the last block movq %rdi, -8 %rbp %p.addr: fixed slot movl %esi, -12 %rbp %d.addr: fixed slot movl -12 %rbp , %eax %0: one use in its block, register only imull $2, %eax, %eax %mul: register only, stored to %t movl %eax, -16 %rbp %t: fixed slot cmpl $0, -16 %rbp %1 folded into the compare, %cmp into the branch jle .Ltmp0 movl -16 %rbp , %edi %2: loaded straight into the argument register callq g@PLT %call stays in %eax movq -8 %rbp , %r10 %3 leaq 4 %r10 , %r10 %count has two uses: movq %r10, -24 %rbp stored to its own slot, %r10 kept as a clean copy movl %r10 , %r10d %4 takes over %r10 addl %eax, %r10d %add movq -24 %rbp , %rax %count reloaded from its slot for the store movl %r10d, %rax .Ltmp0: if.then falls through to if.end movq -8 %rbp , %rax %5 movl 4 %rax , %eax %count1 folded into the load of %6 leave retq Blocks are compiled in layout order, not dominance order. A decision taken at a definition, such as folding a constant-offset address into its users, must therefore respect a slot that a use in an earlier-laid-out block has already reserved. On x86-64, instructions are built as MCInst s and encoded by the target's MCCodeEmitter , with the encodings of fixup-free instructions cached. The frame is rbp -based; the sub that allocates it is patched at the end, or removed when the function needs no adjustment an empty frame, or a leaf that fits the red zone . Jumps start as rel32 and are shortened to rel8, to the same fixpoint the assembler's relaxation reaches. On AArch64, the frame record sits below the locals, so a slot offset from x29 is final when the slot is allocated and fits a scaled load/store offset. The frame size is known only at the end, so the prologue is written last into space reserved at the function start, and every return branches to one shared epilogue. The target-independent part DirectCodeGen.h and DirectCodeGen.cpp is about 2.0K lines, x86-64 1.8K, AArch64 1.7K, plus about 0.4K in AsmPrinter. The split goes through virtual hooks. A third target would implement the 35 pure virtual hooks of DirectCompiler frame, slots, constants, branches, calls, and one hook per instruction class , the pass's subtarget gate, and its own calling convention, since both targets hand-write theirs without CCState . Every MIR pass, frame-lowering feature and AsmPrinter feature must either be reimplemented or send the function to the regular pipeline. FastISel never has this problem, because the same passes run after it. The direct pass also runs before the IR preparation passes, so it must reject or implement anything they lower. The pass list above reads as a list of obligations: stack protectors, KCFI, fentry, XRay, patchable functions and indirect branch tracking all happen in skipped passes. Gates cannot look only at IR. Skipped passes also key on subtarget features including -mattr , cl::opt s, the triple and TargetOptions . The gates query the subtarget, so -mattr counts like the attribute, and they check the TargetOptions fields and options of skipped passes that could change the output. The policy is that unknown means fall back, because slow is a better failure than wrong. A plain allowlist makes that policy expensive. ASan, TSan, MSan and PGO instrumentation each add a module flag that only the instrumentation pass reads, and any SVE-capable -march puts vscale range on every function; rejecting what is unknown would send those whole modules to the regular pipeline. An allowlist also fails silently on new IR: one new upstream function attribute can make every C++ inline function fall back. Enum attributes therefore go through an exhaustive switch with no default , in three groups: no effect on code generation, implemented, and left to the regular pipeline. Adding an attribute to LLVM then fails the build until someone puts it in a group. String attributes, metadata and module flags stay on allowlists, guarded by a clang test that aborts on fallback for common flag sets on both targets, among them PIC, -g , -fsanitize=function , -fprofile-instr-generate , -march=armv9-a , and the hardening flags below. Some features are reimplemented: the stack protector, ENDBR64 for IBT, PAC and BTI with the A key, and stack clash protection for frames that need no probe loop. With distro hardening flags, 99.6-99.7% of sqlite3 and tramp3d functions stay on the direct path on x86-64 and 99.2-99.5% on AArch64. Others are sent back: -pg , -mfentry , -finstrument-functions , XRay, patchable function entries, HWASan, MTE, shadow call stack, KCFI, retpolines and SLS. One gate is structural. Skipping the remaining passes stops emission only if the AsmPrinter is in the same function pass manager. A module pass in the codegen pipeline, such as the one -fjmc adds, splits the function pass manager, so the direct pass cannot find the AsmPrinter and the whole module falls back. Plain -O0 and PGO-instrumented builds fall back for 2.4% of functions over the llvm-test-suite single-source programs on x86-64; the AArch64 rate is about 12%, mostly from loads of types that are not handled. Sanitizers raise the x86-64 rate: | Configuration | Functions that fall back | Missing lowering | |---|---|---| | UBSan | 12% | .with.overflow intrinsics | | MSan | 15% | TLS globals, constant expressions | | ASan | 18% | ptrtoint constants in asan.module ctor / dtor , dynamic alloca ... align 32 | | TSan | 85% | llvm.returnaddress | What remains unsolved is a feature switched on only by a cl::opt or a TargetOptions field. It has no forcing function like the attribute switch . -S must print what -c encodes The MCInst s are scratch values: each is encoded into the private buffer and dropped. Printing them as they are created cannot work, because the function may still fail, branches target byte offsets, and bytes are edited after encoding. For a text streamer, the compiler keeps each MCInst with its offset, and emitCompiledFunction replays them on success. Every later edit of the bytes has a counterpart on the list: the x86 frame sub is deleted or given its immediate, offsets are remapped after jumps shrink, the AArch64 prologue written last is rotated to the front, and branch operands become labels. The exception table uses label differences in text, because the assembler chooses instruction lengths. Gates must give the same answer for both file types, so the branch-padding check asks an MCAsmBackend created from the TargetMachine , not the streamer's. Disassembling the final bytes is not an option: neither cc1 nor llc registers a disassembler, and the x86 encoder folds constants into pc-relative fixup expressions that would have to be unfolded. The test is llc -filetype=asm | llvm-mc against llc -filetype=obj . For the two to agree on x86-64, the object path has to pick the encodings the assembler picks: accumulator forms test $1, %al , shifts by one, and jump sizes, where one pass of shrinking from rel32 does not reach the assembler's fixpoint of growing from rel8. It uses the helpers X86MCInstLower uses and a relaxation that starts every jump short and grows the ones out of range. All 272 modules of a corpus consumer-typeset, lencod, mafft, sqlite3 and tramp3d on both targets give identical disassembly and relocations, and the sqlite3 and tramp3d objects are identical files, exception tables included. The line table's end address and the section order differ between text and object output with -g , as they do in the regular pipeline. The round trip also found differences in the regular pipeline: fadd %st, %st 0 and imul $-2 are encoded differently by -c and by -S plus the assembler, and on AArch64 a function named fp , h1 or b1 makes bl fp unassemblable. -fno-integrated-as output assembles with GNU as to the same code bytes, checked on one file per target. DwarfDebug consumes MachineInstr s, so emitCompiledFunction builds a skeleton MachineFunction with one placeholder instruction per line row and a fixed frame object per variable, and drives the existing debug handlers with it. The invariant is that debug info never changes the code. Nine -g variants, including -gdwarf64 , -gsplit-dwarf , -gline-tables-only and -gkey-instructions , produce .text identical to the build without debug info. Records that cannot be described from the generated code are dropped, as FastISel does. The skeleton starts with a frame-setup instruction. Without one, DwarfDebug sees an empty prologue and skips the scope-line row, and the prologue is attributed to the last line of the previous function. Two gaps are open: an elided fall-through branch loses its line, and a folded value takes the line of its user. Calls inside an invoke range record call-site entries, and the compiler encodes the action records and type infos itself. For object output the LSDA is written from known byte offsets; for text output the same table uses label differences. A landing pad with PHIs gets a stub that keeps the exception registers intact. Adjacent call sites with the same landing pad and action are not merged, so .gcc except table is 46% larger on tramp3d. With the pipeline gone, MC's end-of-module work was 20% of llc time on tramp3d. Several changes came out of this and landed on their own, helping every pipeline: an early return in X86 finishLayout 245114 https://github.com/llvm/llvm-project/pull/245114 , CFI advance folding 245130 https://github.com/llvm/llvm-project/pull/245130 , hashing mergeable-section names once 245122 https://github.com/llvm/llvm-project/pull/245122 , section group names as StringRef instead of Twine 245125 https://github.com/llvm/llvm-project/pull/245125 , and relocation section names 245121 https://github.com/llvm/llvm-project/pull/245121 . A faster string table tail merge has not landed. What is still there: section selection per function, the string table sort, and generic fixup evaluation for FDEs. The tracker run measured a commit without the -S support or the x86 encoding changes. instructions:u geomeans: stage2-O0-g -14.3% sqlite3 -29.9%, 7zip -3.6% and aarch64-O0-g -21.0% sqlite3 -43.3% . max-rss falls 3.1% and 2.4%. The measured commit also includes Instruction::getNumber ; optimized configurations change by -0.2% to -0.3% in instructions and +0.1% to +0.3% in max-rss, and neither change has been attributed. The range is wide because the back end's share of a compile differs by a factor of three between 7zip and sqlite3. Back-end instructions on x86-64 llc -O0 minus bitcode parsing, a build without assertions, on an older commit : regular direct ratio sqlite3 963M 165M 5.8x tramp3d -fno-exceptions 3246M 711M 4.6x tramp3d 5226M 851M 6.1x sqlite3 -g 1382M 430M 3.2x tramp3d -g 6770M 1859M 3.6x The remaining time goes to MCInst construction and encoding, the AsmPrinter's per-function work, and MC. The tracker's size-text geomean for -O0 -g is +9.9% on x86-64, larger on all 11 benchmarks +3.5% SPASS to +17.1% mafft , and -0.1% on AArch64, with seven benchmarks smaller and four larger -9.3% sqlite3 to +24.6% consumer-typeset . .text against the regular pipeline with llc -relocation-model=pic on five programs, on the current tree: x86-64 vs FastISel AArch64 vs GlobalISel consumer-typeset +14.2% +25.1% lencod +14.7% +5.8% mafft +16.6% +2.2% sqlite3 +6.6% -9.9% tramp3d +13.5% -1.2% A few cheap optimizations are implemented: leave , allocates xmm0 - xmm7 before xmm8 - xmm15 which need a REX prefix , and gives allocas their natural alignment, which keeps more frame offsets in 8 bits; cbz / cbnz for a compare with zero. Not done: scaled-index addressing on x86, which needs a second temporary at every address computation; folding :lo12: into AArch64 loads and stores, which needs the alignment of the global; a per-block cache of global addresses on AArch64; jump tables, so a switch is a compare chain; and constant pools, so an FP constant is built with movabs . test %r, %r for a compare with zero would save under 0.3%. On AArch64 a global's address is rematerialized at every use, where GlobalISel does it once per function; in exchange there are far fewer unconditional branches, which is why some benchmarks shrink. bump on x86-64 updates two fields through a pointer: struct Node { int key; int count; Node next; double weight; }; void bump Node n, int d { n- count += d; n- weight = 2; } The regular pipeline FastISel , 14 instructions, 48 bytes, plus an 8-byte constant-pool entry: pushq %rbp movq %rsp, %rbp movq %rdi, -8 %rbp movl %esi, -12 %rbp movl -12 %rbp , %ecx movq -8 %rbp , %rax addl 4 %rax , %ecx movl %ecx, 4 %rax movq -8 %rbp , %rax movsd .LCPI1 0 %rip , %xmm0 mulsd 16 %rax , %xmm0 movsd %xmm0, 16 %rax popq %rbp retq The direct code generator, 23 instructions, 84 bytes: pushq %rbp movq %rsp, %rbp movq %rdi, -8 %rbp movl %esi, -12 %rbp movl -12 %rbp , %eax movq -8 %rbp , %r10 leaq 4 %r10 , %r10 movq %r10, -24 %rbp movl %r10 , %r10d addl %eax, %r10d movq -24 %rbp , %rax movl %r10d, %rax movq -8 %rbp , %rax leaq 16 %rax , %rax movq %rax, -32 %rbp movsd %rax , %xmm7 movabsq $4611686018427387904, %rax movq %rax, %xmm6 mulsd %xmm6, %xmm7 movq -32 %rbp , %rax movsd %xmm7, %rax leave retq Each field address has two uses, so it is stored to a slot and reloaded, where FastISel folds it into both memory operands. The FP constant is built with movabs . touch on AArch64 reads and writes three globals: extern int g ext; int g def; static int g tab 16 ; int touch { g def += g ext; g tab g def & 15 += g def; g ext = g tab 3 + g def; return g def; } The regular pipeline GlobalISel , 21 instructions, 84 bytes: adrp x10, :got:g ext ldr x10, x10, :got lo12:g ext adrp x8, g def adrp x9, ZL5g tab add x9, x9, :lo12: ZL5g tab ldr w12, x10 ldr w11, x8, :lo12:g def add w11, w11, w12 str w11, x8, :lo12:g def ldr w13, x8, :lo12:g def ldr w11, x8, :lo12:g def and w12, w11, 0xf ldr w11, x9, w12, sxtw 2 add w11, w11, w13 str w11, x9, w12, sxtw 2 ldr w9, x9, 12 ldr w11, x8, :lo12:g def add w9, w9, w11 str w9, x10 ldr w0, x8, :lo12:g def ret The direct code generator, 43 instructions, 172 bytes: stp x29, x30, sp, -32 mov x29, sp adrp x9, :got:g ext ldr x9, x9, :got lo12:g ext ldr w9, x9 adrp x10, g def add x10, x10, :lo12:g def ldr w10, x10 add w10, w10, w9 adrp x9, g def add x9, x9, :lo12:g def str w10, x9 adrp x9, g def add x9, x9, :lo12:g def ldr w9, x9 adrp x10, g def add x10, x10, :lo12:g def ldr w10, x10 and w10, w10, 0xf sxtw x10, w10 adrp x11, ZL5g tab add x11, x11, :lo12: ZL5g tab add x11, x11, x10, lsl 2 str x11, x29, 16 ldr w11, x11 add w11, w11, w9 ldr x9, x29, 16 str w11, x9 adrp x9, ZL5g tab+12 add x9, x9, :lo12: ZL5g tab+12 ldr w9, x9 adrp x10, g def add x10, x10, :lo12:g def ldr w10, x10 add w9, w9, w10 adrp x10, :got:g ext ldr x10, x10, :got lo12:g ext str w9, x10 adrp x9, g def add x9, x9, :lo12:g def ldr w0, x9 ldp x29, x30, sp , 32 ret Every reference to g def is an adrp + add + ldr or str , where GlobalISel materializes the page once and folds :lo12: into the access. The output is not byte-identical to the regular pipeline, so acceptance is behavioral. A differential harness compiles each of the 2643 llvm-test-suite single-source programs through both pipelines, links, runs, and compares output and exit status. About 1890 build and run on x86-64 and 1860 on AArch64 under qemu. The variants are PIE, static, -g with llvm-dwarfdump --verify and code identity against the module without debug info , hardening flags, text output assemble the .s , then link and run , ASan, MSan, TSan, UBSan, and instrumented PGO with counter comparison. The mismatches left are not the code generator's: return-addr.c prints stack addresses, flops.c prints timings, sign.c reads uninitialized memory, and a few text-output runs hit the regular-pipeline differences from the -S section in functions that fell back. gdb sessions on about 1880 programs show matching arguments, locals and unwinding. Not done: a self-hosted stage-2 clang running check-llvm , Csmith or YARPGen runs with the regular pipeline as the oracle, and a run-time comparison of the output. | | Direct | FastISel | GlobalISel | |---|---|---|---| | MIR passes | skipped | all run after it | all run after it | | Can miss a gate | yes | no | no | | Platforms at -O0 | x86-64 and AArch64 ELF, small code model | X86, and through the generic part ARM, PowerPC, Mips and WebAssembly | the AArch64 default | | Text output | yes | yes | yes | | Hand-written lines | 2.0K shared, 1.8K x86-64, 1.7K AArch64, 0.4K AsmPrinter | X86FastISel.cpp 4.2K, FastISel.cpp 2.4K | not counted | On the tracker, the direct code generator against FastISel on x86-64 is -14.3% in -O0 -g instructions and +9.9% in .text ; against GlobalISel on AArch64 it is -21.0% and -0.1%. The fallback granularity differs: FastISel hands the rest of a block to SelectionDAG, and the direct code generator hands over a whole function. It adds a selector and removes none. AArch64 FastISel is reached at -O0 only where GlobalISel is excluded, X86 FastISel still serves i386, COFF and Mach-O, and the generic part serves four other targets. MCInst and MCCodeEmitter would address about a third of the remaining time. Text output depends on the The branch direct-codegen has two commits: IR Add Instruction::getNumber and one commit for the code generator. The -S support and the x86 encoding changes are not committed yet. Nothing has been posted for review.