{"slug": "a-direct-o0-code-generator-for-llvm", "title": "A direct -O0 code generator for LLVM", "summary": "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.", "body_md": "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.\nOn the compile-time tracker, `-O0 -g` builds take 14% fewer instructions on x86-64 and 21% fewer on AArch64.\nThe 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.\nSkipping the pipeline creates an obligation, and most of this post is about that obligation.\n\nThis 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.\n\n`-O0` back-end time goes\nThe back end's share of a `clang -O0` compile ranges from 13% for ScalarEvolution.cpp to 39% for sqlite3.\nWithin 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.\nShares 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:\n\n| Layer | sqlite3 | tramp3d | sqlite3 -g | tramp3d -g | \n|---|---|---|---|---|\n| ISel (FastISel, SelectionDAG, driver) | 43% | 28% | 30% | 19% | \n| RegAllocFast | 10% | 8% | 7% | 6% | \n| Prologue/epilogue insertion | 6% | 7% | 4% | 5% | \n| IR preparation passes | 7% | 9% | 6% | 6% | \n| Legacy pass manager | 5% | 10% | 3% | 7% | \n| MachineFunction allocation, other MIR passes, CFI | 9% | 8% | 7% | 6% | \n| LiveDebugValues | 0% | 1% | 9% | 9% | \n| AsmPrinter (MI to MCInst) | 7% | 6% | 6% | 5% | \n| MC encoding, streamer, object writer | 11% | 22% | 10% | 17% | \n| DWARF and `.eh_frame` emission | 1% | 2% | 19% | 22% | \n\n`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`.\nAn excerpt:\n\n```\n    FunctionPass Manager\n      Expand IR instructions\n      Expand Atomic instructions\n      ...\n      Exception handling preparation\n      Prepare inline asm insts\n      Safe Stack instrumentation pass\n      Insert stack protectors\n      Module Verifier\n      Assignment Tracking Analysis\n      X86 DAG->DAG Instruction Selection\n      ...\n      Eliminate PHI nodes for register allocation\n      Machine Register Class Info Analysis\n      Fast Register Allocator\n      ...\n      Prologue/Epilogue Insertion & Frame Finalization\n      Post-RA pseudo instruction expansion pass\n      X86 pseudo instruction expansion pass\n      Insert KCFI indirect call checks\n      Analyze Machine Code For Garbage Collection\n      Insert fentry calls\n      Insert XRay ops\n      Implement the 'patchable-function' attribute\n      X86 Indirect Branch Tracking\n      ...\n      Live DEBUG_VALUE analysis\n      ...\n      X86 Indirect Thunks\n      X86 Return Thunks\n      Check CFA info and insert CFI instructions if needed\n      X86 Load Value Injection (LVI) Ret-Hardening\n      ...\n      X86 Assembly Printer\n      Free MachineFunction\n```\n\nFastISel (2008) selects most instructions itself, hands the rest of a block to SelectionDAG when it cannot, and then runs the full MIR pipeline.\nGlobalISel is the AArch64 `-O0` default.\n\nTPDE 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.\n\nFrom-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.\nCounted like for like, its x86-64 and AArch64 code generators with their shared layer are about 30K lines, against about 5.9K here.\nThey 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.\n\nThe 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.\n\nIR 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.\n\n`DirectCodeGen` is a function pass, first in the `-O0` codegen function pass manager, enabled by `-direct-codegen`.\nIt compiles a function into a private buffer: bytes, fixups, CFI points, line rows, variable slots, and a call-site table.\nNothing shared is touched until the function succeeds, and the IR is never modified.\nOn 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.\nOn failure, the function takes the regular pipeline into the same object file.\n\n``` php\nIR function\n    |\nDirectCodeGen pass ---- any failure ----> regular pipeline\n    |                                    (ISel, MIR passes, AsmPrinter)\n    | success                                  |\nAsmPrinter::emitCompiledFunction               |\n    |                                          |\nMCStreamer: the same .o or .s  <---------------+\n```\n\nSection selection, linkage, alignment, DWARF and the object writer are reused, because they are not where the time goes.\n`-direct-codegen-report` prints the reason for each fallback, and `-direct-codegen-abort` turns a fallback into an error.\n\nA compare used only by its branch, a load used only by the next instruction, and a constant-offset address are folded into their user.\n\nHere is a small function with a local, a branch and a call:\n\n```\nstruct S { int n, count; };\nint g(int);\nint f(struct S *p, int d) {\n  int t = d * 2;\n  if (t > 0)\n    p->count += g(t);\n  return p->count;\n}\n```\n\n`clang -O0 -emit-llvm` gives, trimmed to the instructions:\n\n```\nentry:\n  %p.addr = alloca ptr, align 8\n  %d.addr = alloca i32, align 4\n  %t = alloca i32, align 4\n  store ptr %p, ptr %p.addr, align 8\n  store i32 %d, ptr %d.addr, align 4\n  %0 = load i32, ptr %d.addr, align 4\n  %mul = mul nsw i32 %0, 2\n  store i32 %mul, ptr %t, align 4\n  %1 = load i32, ptr %t, align 4\n  %cmp = icmp sgt i32 %1, 0\n  br i1 %cmp, label %if.then, label %if.end\nif.then:\n  %2 = load i32, ptr %t, align 4\n  %call = call i32 @g(i32 noundef %2)\n  %3 = load ptr, ptr %p.addr, align 8\n  %count = getelementptr inbounds nuw %struct.S, ptr %3, i32 0, i32 1\n  %4 = load i32, ptr %count, align 4\n  %add = add nsw i32 %4, %call\n  store i32 %add, ptr %count, align 4\n  br label %if.end\nif.end:\n  %5 = load ptr, ptr %p.addr, align 8\n  %count1 = getelementptr inbounds nuw %struct.S, ptr %5, i32 0, i32 1\n  %6 = load i32, ptr %count1, align 4\n  ret i32 %6\n```\n\nand `clang -O0 -S -mllvm -direct-codegen` gives (directives removed, comments added):\n\n```\nf:\n\tpushq\t%rbp\n\tmovq\t%rsp, %rbp\n\tsubq\t$32, %rsp            # frame size patched in after the last block\n\tmovq\t%rdi, -8(%rbp)       # %p.addr: fixed slot\n\tmovl\t%esi, -12(%rbp)      # %d.addr: fixed slot\n\tmovl\t-12(%rbp), %eax      # %0: one use in its block, register only\n\timull\t$2, %eax, %eax       # %mul: register only, stored to %t\n\tmovl\t%eax, -16(%rbp)      # %t: fixed slot\n\tcmpl\t$0, -16(%rbp)        # %1 folded into the compare, %cmp into the branch\n\tjle\t.Ltmp0\n\tmovl\t-16(%rbp), %edi      # %2: loaded straight into the argument register\n\tcallq\tg@PLT                # %call stays in %eax\n\tmovq\t-8(%rbp), %r10       # %3\n\tleaq\t4(%r10), %r10        # %count has two uses:\n\tmovq\t%r10, -24(%rbp)      #   stored to its own slot, %r10 kept as a clean copy\n\tmovl\t(%r10), %r10d        # %4 takes over %r10\n\taddl\t%eax, %r10d          # %add\n\tmovq\t-24(%rbp), %rax      # %count reloaded from its slot for the store\n\tmovl\t%r10d, (%rax)\n.Ltmp0:                              # if.then falls through to if.end\n\tmovq\t-8(%rbp), %rax       # %5\n\tmovl\t4(%rax), %eax        # %count1 folded into the load of %6\n\tleave\n\tretq\n```\n\nBlocks 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.\n\nOn x86-64, instructions are built as `MCInst` s and encoded by the target's `MCCodeEmitter`, with the encodings of fixup-free instructions cached.\nThe 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).\nJumps start as rel32 and are shortened to rel8, to the same fixpoint the assembler's relaxation reaches.\n\nOn 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.\nThe 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.\n\nThe 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.\nThe split goes through virtual hooks.\n\nA 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`.\n\nEvery 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.\n\nGates cannot look only at IR.\nSkipped passes also key on subtarget features (including `-mattr`), `cl::opt` s, the triple and `TargetOptions`.\nThe 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.\n\nThe policy is that unknown means fall back, because slow is a better failure than wrong.\nA plain allowlist makes that policy expensive.\nASan, 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.\nAn allowlist also fails silently on new IR: one new upstream function attribute can make every C++ inline function fall back.\n\nEnum 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.\nAdding an attribute to LLVM then fails the build until someone puts it in a group.\nString 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.\n\nSome 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.\nWith 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.\nOthers are sent back: `-pg`, `-mfentry`, `-finstrument-functions`, XRay, patchable function entries, HWASan, MTE, shadow call stack, KCFI, retpolines and SLS.\n\nOne gate is structural.\nSkipping the remaining passes stops emission only if the AsmPrinter is in the same function pass manager.\nA 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.\n\nPlain `-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.\nSanitizers raise the x86-64 rate:\n\n| Configuration | Functions that fall back | Missing lowering | \n|---|---|---|\n| UBSan | 12% | `*.with.overflow` intrinsics | \n| MSan | 15% | TLS globals, constant expressions | \n| ASan | 18% | `ptrtoint` constants in`asan.module_ctor` /`dtor` , dynamic`alloca ... align 32` | \n| TSan | 85% | `llvm.returnaddress` | \n\nWhat remains unsolved is a feature switched on only by a `cl::opt` or a `TargetOptions` field.\nIt has no forcing function like the attribute `switch`.\n\n`-S` must print what `-c` encodes\nThe `MCInst` s are scratch values: each is encoded into the private buffer and dropped.\nPrinting them as they are created cannot work, because the function may still fail, branches target byte offsets, and bytes are edited after encoding.\nFor a text streamer, the compiler keeps each `MCInst` with its offset, and `emitCompiledFunction` replays them on success.\nEvery 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.\nThe exception table uses label differences in text, because the assembler chooses instruction lengths.\nGates 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.\n\nDisassembling 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.\n\nThe test is `llc -filetype=asm | llvm-mc` against `llc -filetype=obj`.\nFor 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.\nIt uses the helpers `X86MCInstLower` uses and a relaxation that starts every jump short and grows the ones out of range.\nAll 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.\n\nThe line table's end address and the section order differ between text and object output with `-g`, as they do in the regular pipeline.\nThe 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.\n`-fno-integrated-as` output assembles with GNU as to the same code bytes, checked on one file per target.\n\nDwarfDebug 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.\n\nThe invariant is that debug info never changes the code.\nNine `-g` variants, including `-gdwarf64`, `-gsplit-dwarf`, `-gline-tables-only` and `-gkey-instructions`, produce `.text` identical to the build without debug info.\nRecords that cannot be described from the generated code are dropped, as FastISel does.\n\nThe 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.\n\nTwo gaps are open: an elided fall-through branch loses its line, and a folded value takes the line of its user.\n\nCalls inside an invoke range record call-site entries, and the compiler encodes the action records and type infos itself.\nFor object output the LSDA is written from known byte offsets; for text output the same table uses label differences.\nA landing pad with PHIs gets a stub that keeps the exception registers intact.\nAdjacent call sites with the same landing pad and action are not merged, so `.gcc_except_table` is 46% larger on tramp3d.\n\nWith the pipeline gone, MC's end-of-module work was 20% of `llc` time on tramp3d.\nSeveral 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)).\nA faster string table tail merge has not landed.\nWhat is still there: section selection per function, the string table sort, and generic fixup evaluation for FDEs.\n\nThe tracker run measured a commit without the `-S` support or the x86 encoding changes.\n`instructions:u` geomeans: stage2-O0-g -14.3% (sqlite3 -29.9%, 7zip -3.6%) and aarch64-O0-g -21.0% (sqlite3 -43.3%).\nmax-rss falls 3.1% and 2.4%.\nThe 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.\n\nThe range is wide because the back end's share of a compile differs by a factor of three between 7zip and sqlite3.\nBack-end instructions on x86-64 (`llc -O0` minus bitcode parsing, a build without assertions, on an older commit):\n\n```\n                          regular  direct  ratio\nsqlite3                      963M    165M   5.8x\ntramp3d -fno-exceptions     3246M    711M   4.6x\ntramp3d                     5226M    851M   6.1x\nsqlite3 -g                  1382M    430M   3.2x\ntramp3d -g                  6770M   1859M   3.6x\n```\n\nThe remaining time goes to `MCInst` construction and encoding, the AsmPrinter's per-function work, and MC.\n\nThe 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).\n`.text` against the regular pipeline with `llc -relocation-model=pic` on five programs, on the current tree:\n\n```\n                    x86-64 vs FastISel    AArch64 vs GlobalISel\nconsumer-typeset         +14.2%                +25.1%\nlencod                   +14.7%                 +5.8%\nmafft                    +16.6%                 +2.2%\nsqlite3                   +6.6%                 -9.9%\ntramp3d                  +13.5%                 -1.2%\n```\n\nA few cheap optimizations are implemented:\n\n`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.\nNot 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`.\n`test %r, %r` for a compare with zero would save under 0.3%.\n\nOn 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.\n\n`bump` on x86-64 updates two fields through a pointer:\n\n```\nstruct Node { int key; int count; Node *next; double weight; };\nvoid bump(Node *n, int d) {\n  n->count += d;\n  n->weight *= 2;\n}\n```\n\nThe regular pipeline (FastISel), 14 instructions, 48 bytes, plus an 8-byte constant-pool entry:\n\n```\n\tpushq\t%rbp\n\tmovq\t%rsp, %rbp\n\tmovq\t%rdi, -8(%rbp)\n\tmovl\t%esi, -12(%rbp)\n\tmovl\t-12(%rbp), %ecx\n\tmovq\t-8(%rbp), %rax\n\taddl\t4(%rax), %ecx\n\tmovl\t%ecx, 4(%rax)\n\tmovq\t-8(%rbp), %rax\n\tmovsd\t.LCPI1_0(%rip), %xmm0\n\tmulsd\t16(%rax), %xmm0\n\tmovsd\t%xmm0, 16(%rax)\n\tpopq\t%rbp\n\tretq\n```\n\nThe direct code generator, 23 instructions, 84 bytes:\n\n```\n\tpushq\t%rbp\n\tmovq\t%rsp, %rbp\n\tmovq\t%rdi, -8(%rbp)\n\tmovl\t%esi, -12(%rbp)\n\tmovl\t-12(%rbp), %eax\n\tmovq\t-8(%rbp), %r10\n\tleaq\t4(%r10), %r10\n\tmovq\t%r10, -24(%rbp)\n\tmovl\t(%r10), %r10d\n\taddl\t%eax, %r10d\n\tmovq\t-24(%rbp), %rax\n\tmovl\t%r10d, (%rax)\n\tmovq\t-8(%rbp), %rax\n\tleaq\t16(%rax), %rax\n\tmovq\t%rax, -32(%rbp)\n\tmovsd\t(%rax), %xmm7\n\tmovabsq\t$4611686018427387904, %rax\n\tmovq\t%rax, %xmm6\n\tmulsd\t%xmm6, %xmm7\n\tmovq\t-32(%rbp), %rax\n\tmovsd\t%xmm7, (%rax)\n\tleave\n\tretq\n```\n\nEach field address has two uses, so it is stored to a slot and reloaded, where FastISel folds it into both memory operands.\nThe FP constant is built with `movabs`.\n\n`touch` on AArch64 reads and writes three globals:\n\n```\nextern int g_ext;\nint g_def;\nstatic int g_tab[16];\nint touch() {\n  g_def += g_ext;\n  g_tab[g_def & 15] += g_def;\n  g_ext = g_tab[3] + g_def;\n  return g_def;\n}\n```\n\nThe regular pipeline (GlobalISel), 21 instructions, 84 bytes:\n\n```\n\tadrp\tx10, :got:g_ext\n\tldr\tx10, [x10, :got_lo12:g_ext]\n\tadrp\tx8, g_def\n\tadrp\tx9, _ZL5g_tab\n\tadd\tx9, x9, :lo12:_ZL5g_tab\n\tldr\tw12, [x10]\n\tldr\tw11, [x8, :lo12:g_def]\n\tadd\tw11, w11, w12\n\tstr\tw11, [x8, :lo12:g_def]\n\tldr\tw13, [x8, :lo12:g_def]\n\tldr\tw11, [x8, :lo12:g_def]\n\tand\tw12, w11, #0xf\n\tldr\tw11, [x9, w12, sxtw #2]\n\tadd\tw11, w11, w13\n\tstr\tw11, [x9, w12, sxtw #2]\n\tldr\tw9, [x9, #12]\n\tldr\tw11, [x8, :lo12:g_def]\n\tadd\tw9, w9, w11\n\tstr\tw9, [x10]\n\tldr\tw0, [x8, :lo12:g_def]\n\tret\n```\n\nThe direct code generator, 43 instructions, 172 bytes:\n\n```\n\tstp\tx29, x30, [sp, #-32]!\n\tmov\tx29, sp\n\tadrp\tx9, :got:g_ext\n\tldr\tx9, [x9, :got_lo12:g_ext]\n\tldr\tw9, [x9]\n\tadrp\tx10, g_def\n\tadd\tx10, x10, :lo12:g_def\n\tldr\tw10, [x10]\n\tadd\tw10, w10, w9\n\tadrp\tx9, g_def\n\tadd\tx9, x9, :lo12:g_def\n\tstr\tw10, [x9]\n\tadrp\tx9, g_def\n\tadd\tx9, x9, :lo12:g_def\n\tldr\tw9, [x9]\n\tadrp\tx10, g_def\n\tadd\tx10, x10, :lo12:g_def\n\tldr\tw10, [x10]\n\tand\tw10, w10, #0xf\n\tsxtw\tx10, w10\n\tadrp\tx11, _ZL5g_tab\n\tadd\tx11, x11, :lo12:_ZL5g_tab\n\tadd\tx11, x11, x10, lsl #2\n\tstr\tx11, [x29, #16]\n\tldr\tw11, [x11]\n\tadd\tw11, w11, w9\n\tldr\tx9, [x29, #16]\n\tstr\tw11, [x9]\n\tadrp\tx9, _ZL5g_tab+12\n\tadd\tx9, x9, :lo12:_ZL5g_tab+12\n\tldr\tw9, [x9]\n\tadrp\tx10, g_def\n\tadd\tx10, x10, :lo12:g_def\n\tldr\tw10, [x10]\n\tadd\tw9, w9, w10\n\tadrp\tx10, :got:g_ext\n\tldr\tx10, [x10, :got_lo12:g_ext]\n\tstr\tw9, [x10]\n\tadrp\tx9, g_def\n\tadd\tx9, x9, :lo12:g_def\n\tldr\tw0, [x9]\n\tldp\tx29, x30, [sp], #32\n\tret\n```\n\nEvery reference to `g_def` is an `adrp`+` add`+` ldr` or `str`, where GlobalISel materializes the page once and folds `:lo12:` into the access.\n\nThe output is not byte-identical to the regular pipeline, so acceptance is behavioral.\nA differential harness compiles each of the 2643 llvm-test-suite single-source programs through both pipelines, links, runs, and compares output and exit status.\nAbout 1890 build and run on x86-64 and 1860 on AArch64 under qemu.\nThe 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.\nThe 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.\n\ngdb sessions on about 1880 programs show matching arguments, locals and unwinding.\n\nNot 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.\n\n|  | Direct | FastISel | GlobalISel | \n|---|---|---|---|\n| MIR passes | skipped | all run after it | all run after it | \n| Can miss a gate | yes | no | no | \n| 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 | \n| Text output | yes | yes | yes | \n| 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 | \n\nOn 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%.\n\nThe fallback granularity differs: FastISel hands the rest of a block to SelectionDAG, and the direct code generator hands over a whole function.\n\nIt adds a selector and removes none.\nAArch64 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.\n\n`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.\nThe `-S` support and the x86 encoding changes are not committed yet.\nNothing has been posted for review.", "url": "https://wpnews.pro/news/a-direct-o0-code-generator-for-llvm", "canonical_source": "https://maskray.me/blog/llvm-direct-o0-code-generator", "published_at": "2026-11-25 00:00:00+00:00", "updated_at": "2026-11-26 08:15:41.653545+00:00", "lang": "en", "topics": ["developer-tools", "artificial-intelligence"], "entities": ["LLVM", "Claude Code", "TPDE", "Anthropic", "sqlite3", "tramp3d", "GlobalISel", "FastISel"], "also_reported_by": [], "takeaway": "A direct -O0 IR-to-machine-code path that skips MachineFunction construction cuts compile-time instruction counts 14% on x86-64 and 21% on AArch64 for -O0 -g builds, at the cost of 10% larger x86-64 code and roughly unchanged AArch64 code size.", "recommendation": null, "alternates": {"html": "https://wpnews.pro/news/a-direct-o0-code-generator-for-llvm", "markdown": "https://wpnews.pro/news/a-direct-o0-code-generator-for-llvm.md", "text": "https://wpnews.pro/news/a-direct-o0-code-generator-for-llvm.txt", "jsonld": "https://wpnews.pro/news/a-direct-o0-code-generator-for-llvm.jsonld"}}