Optimizing beyond the compiler with kernel‑checked equivalence proofs
An agent rewrites hot functions in compiled programs and proves that each rewrite behaves like the original.
- loop:
- ldrb eor ubfiz ldr eor
- ldurb eor ubfiz ldr eor
- ldurb eor ubfiz ldr eor
- ldurb eor ubfiz ldr eor
- ldurb eor ubfiz ldr eor
- ldurb eor ubfiz ldr eor
- ldurb eor ubfiz ldr eor
- ldurb eor ubfiz ldr eor
- add x19, x19, #8
- cmp x19, x8
- b.ne loop
- loop:
- cbnz x7, check
- ldr x11, [x19], #8
- crc32x w0, w0, x11
- cmp x19, x8
- b.ne loop
✓ proved equivalent in Lean
For decades, compiler optimization has been an endeavor guided by heuristics: rules of thumb for when to inline, how far to unroll a loop, or which instructions to pick. Each optimization is tuned to work well across all programs while staying semantically faithful to the source code. A heuristic is built to be safe for all code it might see, so it can’t take advantage of the particular features of a given program.1
An agent doesn’t share that limit. It can read one function and write code for that function and the processor it runs on. Recent work shows this produces faster code.2 The catch is trust. A compiler applies a set of reviewable rules trusted for every program; an agent’s one-off optimizations follow no predictable rules. Every rewrite needs its own review, and even then we can’t be certain the rewrite preserved semantic meaning.
We close that gap with Lean: the agent proves that the assembled binary of its rewrite is equivalent to the original. The proof is stated over a Lean model of what each Arm64 instruction does, which we extended from the one in Google DeepMind’s recent paper on verifying the Signal protocol. Not only do we prove functional equivalence at the level of inputs and outputs, but we also check that the rewrite keeps the program’s security protections.3 For cryptographic code such as libsignal, we also prove that the rewrite runs in constant time, so its timing doesn’t depend on secrets.4
On unzip, the Unicode library ICU, and libsignal, the agent’s rewrites make the whole program 1.33× as fast on average. It also speeds up several hand-written cryptographic routines from AWS’s s2n-bignum.
How it works#
We profile a compiled program to find the few functions that account for most of its running time. For each one, the agent is given the function’s machine code, the source, and a library of Lean lemmas for reasoning about Arm64 programs. The agent may change the function however it likes, as long as it can prove that the result behaves the same as the original.
The statement the agent proves is fixed before it starts, and it is the same for every function. Roughly: on any call the original function handles, the rewrite returns the same results, leaves memory in the same state and makes the same system calls. Calls to other code are treated as arbitrary black boxes that follow the calling convention, so the rewrite must make the same calls, with the same arguments, in the same order.
When the agent is done, an automated acceptance step takes over:
- Lean’s kernel checks the proof from scratch, against the statement filled in with the exact bytes of the rewrite.
- A second check confirms that the patch writes exactly those bytes and nothing else.
- Checks on the rewrite’s bytes confirm that it keeps return-address signing, branch landing pads and stack-overflow protection.
- For code that handles secrets, a checker that is itself proved correct in Lean confirms that the rewrite never branches on secret data or uses it to pick a memory address.
If all of them pass, a small loader patches the program when it starts, after confirming that it is the exact build the proof is about.5 The source code is left untouched. We overall aim to minimize the surface area of trust when patching a binary. 6
An example: ICU’s text encoder#
ICU is the most widely used library for handling Unicode text. When it converts text to UTF-16, about two thirds of the run goes into one function, the encoder _UTF16LEFromUnicodeWithOffsets, which writes each character to the output a byte at a time.
The pointer to the output is kept on the stack rather than in a register. After writing the first byte of a character, the compiled code reloads that pointer before writing the second. As far as the compiler can tell, the write might have overwritten the pointer itself. In a real run it never does, but the reload puts a round trip through memory between each character and the next.
The agent’s version keeps the pointer in a register and writes through it. It still checks that the copy on the stack hasn’t changed, but that check runs alongside the writes instead of holding them up. If it ever did change, the rewrite would fall back: it would jump into the original code at the reload, and the original would carry on exactly as before. With the rewrite in place, ICU’s conversion runs 1.28× as fast end to end.
- mov x23, x22
- ldrh w10, [x23], #2
- and w14, w10, #0xf800
- cmp w14, w12
- b.ne …
- strb w10, [x8]
- lsr w8, w10, #8
- mov x22, x23
- ldr x10, [sp, #8]
- strb w8, [x10, #1]
- add x8, x10, #2
- subs w11, w11, #1
- str x8, [sp, #8]
- b.eq …
The pointer goes to memory and comes back before each character's second byte.
- ldrh w10, [x22], #2
- and w14, w10, #0xf800
- cmp w14, w12
- b.eq …
- strb w10, [x8]
- lsr w23, w10, #8
- ldr x10, [sp, #8]
- cmp x10, x8
- b.ne fallback
- strb w23, [x8, #1]
- add x8, x8, #2
- subs w11, w11, #1
- str x8, [sp, #8]
- b.ne …
The pointer stays in x8. The reload is only compared, off to the side.
In theory, a compiler could have made this change. In practice, none did, even at the highest optimization level.
Proving equivalence#
More precisely, writing for the original, for the rewrite, and for “started in state , returns in state ”, the agent must prove the statement
Here ranges over every machine state, which includes every program the function could sit in and every behavior of the code it calls. The relation compares what a caller can see,7 so scratch registers and the like may differ.
The statement is about equivalence, not correctness. It never says what the function is supposed to compute, only that the rewrite does what the original did, so no one has to write or check a specification. It also covers every call on which the original returns, and says nothing about calls on which it doesn’t.8
Proving the statement directly would mean reasoning about every program and every input at once. Instead, we proved once, in Lean, that the statement follows from a simpler property: a step-by-step correspondence between the two programs’ runs, called a simulation. The agent uses this for functions that call other code, like ICU’s encoder. It picks matching points in the two runs and states what must hold between the two machine states at each one. It then proves that if the states are related at one matching point, they are related again at the next. Each step from one matching point to the next is proved a few instructions at a time.
The matching points are the entry, each call, the return, and the head of each loop. A loop can run any number of times, but its head is reached on every pass. The relation at a loop head is a loop invariant: proving that one pass preserves it covers the whole loop.
In ICU’s encoder, the agent changed only the loop. The rewrite turns one of the original’s instructions into a jump to the new loop. Everywhere else it runs the original’s own instructions, and a fallback jumps back into them when the check fails. Where both sides run the same instructions, library lemmas show automatically that the two states stay equal. Only the loop needs real reasoning, and its key fact is that the pointer the rewrite keeps in a register is the one the original would reload from the stack.
Functions that make no calls, such as the cryptographic routines below, are proved differently. The agent describes what the function computes in terms of preconditions and postconditions, and proves that both versions satisfy that description. No one has to check it: the description is a step in the proof, not part of the statement being proved, so a wrong one can’t produce a false result. It can only leave the proof unfinished.
Results#
We ran the agent on unzip (C), ICU (C++) and libsignal (Rust), and on ten hand-written assembly routines for field arithmetic from AWS’s s2n-bignum. We timed each program doing its whole job, against the best of several builds we made with different compilers and flags. We timed each s2n-bignum routine on its own, against AWS’s reference version. Everything ran on AWS Graviton4, on inputs that differ from the ones the agent saw.9
| Program | What we timed | Functions replaced | Speedup |
|---|---|---|---|
| unzip | Extracting an archive | 1 | 1.61× |
| ICU | Converting text from UTF-8 to UTF-16 | 1 | 1.28× |
| libsignal | Setting up sessions and sending messages | 2 | 1.13× |
| s2n-bignum | Each of ten routines, on its own | 10 | 1.04× to 1.34× |
For each of the three programs, we gave the agent the two functions it spends the most time in. It produced accepted rewrites for all six, and four gave a speedup.
The rewrites use a handful of ideas, each fitted to the code and the processor:
- unzip’s checksum. The CRC loop looks up a 256-entry table a byte at a time. Arm64 has an instruction that computes the checksum of eight bytes at once, but it matches the loop only if the table holds the standard values, and since the table sits in writable memory, the rewrite can’t assume it does. So it checks each entry the first time it is used and switches to the instruction once all 256 are confirmed.
- ICU’s encoder. The pointer stays in a register, and the check that the stored copy hasn’t changed runs alongside the writes, as in the example above.
- libsignal’s field arithmetic. Multiplication keeps every limb in a register and computes multiples of 19 with shifts and additions. Repeated squaring works on doubled operands, with fewer multiplications, which is exact because the proof bounds the output of each squaring.
- s2n-bignum. Most rewrites replace Karatsuba multiplication with plain schoolbook multiplication, which is faster on Graviton4.10 Others restructure the reduction steps, or use an instruction order found by search on the hardware.
AWS also ships hand-optimized _alt versions of these routines,11 which beat the agent’s rewrites on eight of the ten. Starting from the _alt versions, the agent sped up five of them by a further 1.05× to 1.06×, all proved constant-time.12
Limitations#
Some of these limitations reflect the scope of the Arm64 model we build on, which covers a single thread in user mode. We extended it with pointer authentication, whose behavior we checked against Graviton4. Signals and exception handling fall outside it, so we handle them with checks.
- One function at a time. Because calls are treated as black boxes, a rewrite must make the same calls as the original, so it can’t inline, merge or remove them.
- Memory. A rewrite may only touch bytes the original touches. Wide loads of those bytes are fine (the CRC rewrite reads eight at a time), but reading ahead of the original in a buffer, as vectorized loops often do, can’t be proved.
- Code shape. No jump tables or other indirect jumps, no system calls made directly from the function’s own code (calls through a C library wrapper are allowed and typical), no recursion other than tail calls, and no functions that exceptions unwind through.
- Threads and signals. The proofs assume a single thread and no signals. A signal handler runs on the program’s stack and can overwrite anything below the stack pointer, so a check confirms that the rewrite keeps nothing there; that this rule is enough is argued, not proved.
- Constant time. It is proved only for functions without calls, and the checker doesn’t handle vector instructions, which ruled out one faster rewrite. Like most constant-time guarantees, ours doesn’t cover speculative execution.
- Hardware. Arm64 Linux only, timed on one processor so far.
What’s next#
The largest restriction is that the agent works on one function at a time. Next, we want statements that let a rewrite span several functions, inlining or merging calls, so the agent can optimize a whole hot path. We also want to admit loops that read ahead of the original, which vectorized code relies on.
We eventually want this to run as a step in CI, to extend the Arm64 model so that more of what we now check can be proved, and to bring the method to x86. Compiler optimizations need to be correct for every program; agents only need to be correct for yours.
Contact [email protected] with questions.
-
Profile-guided and chip-specific builds tune these optimizations further, but each heuristic must still be safe for arbitrary code. ↩︎
-
AlphaEvolve sped up a FlashAttention kernel 32% by editing compiler output. SuperCoder beats
gcc -O3on assembly by 1.46×. ↩︎ -
Return-address signing, branch landing pads and stack-overflow protection. ↩︎
-
The proof covers branches, memory addresses (and so cache behavior) and the inputs to slow instructions such as division. ↩︎
-
With access to the build, the rewrite could instead be substituted into the program’s assembly before linking. ↩︎
-
We trust Lean’s kernel, the Arm64 model, the fixed statement, the checks on the rewrite’s bytes, the loader and the processor. ↩︎
-
The result registers, the registers a function must preserve, the stack pointer, memory outside the function’s scratch space, and the record of system calls. ↩︎
-
We also proved once that these statements compose: a program with several rewritten functions behaves like the original, if the rest of it follows the calling convention. ↩︎
-
Each version runs 11 times, alternating with a control that times the original against itself. A result counts only if its gain beats the control’s by twice the run-to-run spread. ↩︎
-
Karatsuba saves multiplications at the cost of extra additions, subtractions and sign fixes. On Graviton4 that extra work costs more than the multiplications it saves, so plain schoolbook multiplication is faster. ↩︎
-
AWS’s default optimized versions, scheduled for an earlier processor, run 0.87× to 1.00× as fast as the reference on Graviton4, and all ten of ours beat them. ↩︎
-
The agent’s other four
_altrewrites are within noise of the function before rewriting. On the tenth, it couldn’t prove equivalence. ↩︎