# Random Search and Guaranteed Correctness with CryptOpt

> Source: <https://stng.substack.com/p/random-search-and-guaranteed-correctness>
> Published: 2026-10-27 12:22:18+00:00

**Recommendation:** When hand-tuned assembly beats verified code generation, search over straightline variants and benchmark them on real hardware, then verify each candidate to keep correctness guarantees.
More in the playbook "Verifying model output": <https://wpnews.pro/playbooks/output-verification>

Let me continue this sequence of posts making the case for [deriving programs step-by-step from specifications, in a way that guarantees correctness](https://stng.substack.com/p/correct-by-construction-code-via), as contrasted with how LLM-powered coding assistants are being used widely today. I have already given two examples, one each in [software](https://stng.substack.com/p/high-level-algebra-for-low-level) and [hardware](https://stng.substack.com/p/deriving-efficient-hardware-in-the). What those examples have in common is use of *proven rewrite rules* to transform program representations. That is, a rule is stated *and proved mathematically* in full generality, and then it can be applied to individual programs at low cost.

It is not always feasible to think up the perfect library of rewrite rules in advance. Even if we wake up one day knowing the perfect rules, proving them in general can be harder than proving their specific uses for concrete programs. Luckily, correct-by-construction derivation can *also* sometimes work with a more-flexible approach. I covered one example a few months back in a [presentation of formal verification from an evolutionary perspective](https://stng.substack.com/p/formal-verification-the-ultimate). Now I’d like to go into more detail on how it works.

# Straightline Code Deserves Formal Verification, Too

We [previously reviewed](https://stng.substack.com/p/codesign-for-ai-and-programming) classic computer-science results around [formally undecidable](https://en.wikipedia.org/wiki/Undecidable_problem) problems in automatic program understanding. The trouble comes down to programming features like [loops](<https://en.wikipedia.org/wiki/Loop_(statement)>) and [recursion](<https://en.wikipedia.org/wiki/Recursion_(computer_science)>) that allow programs to run forever. So what if we focus on *straightline code*, which outlaws such features?

But then which interesting programs will qualify? It turns out that some of the trickiest cryptographic code, involving design decisions critical to both performance and security, is straightline. [Our Fiat Cryptography project](https://adam.chlipala.net/papers/FiatCryptoSP19/) involved formally verified generation of such code. At some level, formal verification of compilers has been considered a “solved problem,” one of the first big success stories for the field via [the C compiler CompCert](https://en.wikipedia.org/wiki/CompCert). There were some new puzzles to solve in building Fiat Cryptography, but we didn’t solve all of them, because the code we produced was still significantly slower than examples handwritten by the top experts.

To be more specific, we produced roughly the fastest-known code in [the C programming language](<https://en.wikipedia.org/wiki/C_(programming_language)>) for various algorithms. Most programmers think of C as the lowest level of grungy detail that they’ll consider visiting, but even lower-level is [assembly language](https://en.wikipedia.org/wiki/Assembly_language). Indeed, the champion implementations were handwritten in assembly (or, actually, most commonly relied on scripts generating assembly, like in [perlasm](https://github.com/openssl/openssl/blob/master/crypto/perlasm/README.md) from [OpenSSL](https://en.wikipedia.org/wiki/OpenSSL)). Compilers for higher-level languages hadn’t been given the right smarts to generate the fastest code automatically. One big reason is that the fastest coding patterns could change across processor versions, which suggested that benchmarking code against real processors could be helpful. However, conventional compilers are expected to run *quickly*, and it just wasn’t in their maintainers’ playbook to kick off extensive benchmarking of many variants.

But it was totally feasible for a scrappy academic project! And we could even combine it with formal verification! The result is a rare moment of having our cake and eating it, too. This project, [CryptOpt](https://adam.chlipala.net/papers/CryptoptPLDI23/), improved the Fiat Cryptography story in these two ways simultaneously, where most projects need to trade off between such goals.

1. It *improved performance* of generated code substantially, to the point where we even set some new performance records for particular important algorithms on relatively new CPUs.
2. It *removed the need to trust anything about off-the-shelf compilers* . Instead, the whole logical-reasoning path from whiteboard-level math to assembly language was certified from first principles.

It even turns out that it’s worth using a rather slow compiler to produce important cryptographic code, so we take advantage of domain specialization that wouldn’t make sense for conventional compilers. One of the fun outcomes of our experimental evaluation was that we set a new performance record for [secp256k1](https://en.bitcoin.it/wiki/Secp256k1), part of the [bitcoin](https://en.wikipedia.org/wiki/Bitcoin) implementation, on a particular recent Intel processor. A CryptOpt implementation of [Curve25519](https://en.wikipedia.org/wiki/Curve25519) was also merged into the [BoringSSL](https://en.wikipedia.org/wiki/OpenSSL#BoringSSL) library and hence into the Chrome web browser (which was already using Fiat Cryptography, with significantly slower generated C code).

There are two main parts of the project. One is random program search (in the tradition of [superoptimization](https://en.wikipedia.org/wiki/Superoptimization)), which tries many behavior-preserving ways to reorganize an assembly program, benchmarking each variant, so we can keep the fastest version in the end. This aspect was implemented by lead student Joel Kuepper and our other collaborators you can read off [the paper](https://adam.chlipala.net/papers/CryptoptPLDI23/) metadata. The search process can derail arbitrarily, introducing arbitrary bugs, because we guarantee to catch them before outputting code. Credit there goes to the other main part, a formally verified program-equivalence checker (in the tradition of [translation validation](https://en.wikipedia.org/wiki/Compiler_correctness#Translation_validation:_compiler_correctness_on_a_given_program)), which can not only compare assembly programs for identical behavior but also compare an assembly program with a higher-level program in the shared middle-end language of Fiat Cryptography. I do mean a checker in the spirit of formal verification, which covers *equivalence under all possible inputs*, not just running on large but incomplete test suites. Development (including verification) of this checker was led by my (then) PhD students [Andres Erbsen](https://andres.systems/) and [Jason Gross](https://jasongross.github.io/), with contributions by undergraduates [Owen Conoly](https://github.com/OwenConoly) and [Livia Sun](https://web.stanford.edu/~chuyues/). Let me give a sense of how it works.

# A Running Example

Let’s take the example of computing 5*x* + *y* + *c* modulo 2 to the 64th power, the modulus that today’s CPUs generally implement directly in their [registers](https://en.wikipedia.org/wiki/Processor_register). Assume that register `rdi` stores *x*, `rsi` stores *y*, and `rdx` stores *c* (this last one thought of as a carry bit, as often needs to be threaded through in big-integer machine arithmetic). Then the Fiat Cryptography compiler may have produced the following assembly program from the mathematical expression. (For folks not used to reading [x86](https://en.wikipedia.org/wiki/X86) assembly, I’ve included comments after semicolons, explaining the operations in more-standard mathematical notation.)

```
imul rax, rdi, 5          ; rax = 5*x
add  rax, rsi             ; rax = rax + y
add  rax, rdx             ; rax = rax + c
```

CryptOpt performs a few kinds of random program mutations, of which we will use two in this example. One is *instruction selection*, substituting a different named processor instruction to compute values in a different way. Another is *reordering*, moving an instruction to some other point in a program where all of its inputs are ready to read. Either may bring performance improvements that can seem mysterious. For instance, reordering may move an instruction that consumes a value closer to the instruction that produces it, reducing the need for temporary storage of that value, which matters because processors have tight budgets for temporary storage (the scarce registers are preferred, and expanding to consider memory leads to slower accesses).

Imagine that random mutation produced the following alternative program.

```
lea  rax, [rsi + rdx]     ; rax = y + c
lea  rcx, [rdi + 4*rdi]   ; rcx = x + 4*x
add  rax, rcx             ; rax = rax + rcx
```

The funny-looking `lea` instructions are just computing basic arithmetic. While “`lea`” stands for “load effective address,” and the instruction was designed for memory-address arithmetic, it has been used by savvy programmers since the 20th century as a backdoor way to do other simple arithmetic. The benefit comes from specialization: address arithmetic is typically less general than arithmetic broadly, so specialized circuits are used, and they run more quickly. Not only did we switch to this clever instruction, but we also swapped the order of the first two instructions. (I’m not promising this particular swap improves performance on any particular processor, but it’ll make for a good pedagogical example.)

Our mission is now to confirm that these two programs compute the same answers, stored in register `rax`. We will use a simple program-equivalence checker.

# A Data Structure to Normalize Expressions

The original program computes 5*x* + *y* + *c*. The optimized program computes (*y* + *c*) + (*x* + 4*x*). We need to prove equality of these two expressions. In general, we want an algorithm that handles many equivalence problems of this kind.

Our approach is inspired by the [e-graph](https://en.wikipedia.org/wiki/E-graph) data structure behind [SMT solvers](https://en.wikipedia.org/wiki/Satisfiability_modulo_theories), a popular category of automated theorem prover, which I will have more to say about in near-future articles. However, we pared down functionality to the minimum needed to support this domain of formal verification, for instance never merging *[equivalence classes](https://en.wikipedia.org/wiki/Equivalence_class)* of expressions after they are created. What we keep from e-graphs is a *canonicalization* property: an e-graph is a [graph](<https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)>) in the computer-science sense of “a boxes-and-edges diagram,” where each node stands for one equivalence class of logical expressions that are known to equal each other. Hence, to check if two terms are equal, we can *internalize* them both into the graph and then check that their root nodes are *exactly the same*. Internalization works via bottom-up traversal of [syntax trees](https://en.wikipedia.org/wiki/Abstract_syntax_tree) for the math expressions, applying algebraic-simplification rules at each step.

It would be natural to ask why we didn’t just use an off-the-shelf SMT solver for these checks. The downside would be *trusting that the SMT solver is implemented correctly*. Our new checker was simple enough for us to prove correct from first principles, an exercise not yet nearly completed for a production-strength SMT solver.

Let’s look at how this process works for our running example. Here is the starting point: two syntax trees, not obviously computing the same mathematical function.

Now we step through internalizing the first expression. Every one of the nodes in its tree winds up associated with a different node in the graph we are building. In this diagram and others, a final graph visualization omits showing nodes that became unreachable from the root (always shown at the top), which creates apparent skipped node ID numbers.

The most interesting step was the last one, choosing the node for 5*x* + *y* + *c*. CryptOpt’s equivalence checker takes advantage of the fact that addition and multiplication are associative and commutative. In this case, we have represented an addition as *taking three arguments*, flattening the details of how a larger tree of additions rolled up into this form. That is, when one argument to an eligible operator is itself a use of the same operator, the nested operation’s parameters can be inlined instead of referenced indirectly. Flattening arguments naturally removes the need to consider associativity directly. We also *sort the arguments of an addition or multiplication by their node IDs in the graph*. Hence, if we later find *another* addition that adds *the same operands but in a different order*, sorting naturally helps us recognize that we have merely computed the same answer. It is important that we sort by internal node IDs, not shallow surface properties of subterms in the math expression. The reason is that earlier steps of internalization have done the hard work of mapping provably equal expressions to the same nodes.

Now consider where the action is in internalizing the second expression. We will depend critically on an algebraic rewrite rule: when we add one copy of an expression to itself, just multiplied by different coefficients, we can combine them into that expression multiplied by a single combined coefficient.

Now here is the convenient final graph. The two expressions have been mapped to precisely the same graph node, so by construction they are equal. The implementation of this mapping is simple: every time a node is added to the graph, we scan the whole graph for a preexisting node with the same operation and argument list. If we find a match, we reuse that node instead of creating a new one. (This kind of naive scan may sound impractical for programs of a bit over 1000 instructions, as we dealt with, but I was pleasantly surprised to find that performance was fine, once expectations are set for compilation not being instant.)

The compact visual presentation can hide how effectively we have reasoned about an astronomically large space of possible program inputs. Testing the code against all of them is quite infeasible. Instead, a simple procedure based on algebraic simplification gets the job done.

# Symbolic Execution

The last example left implicit how we know which nodes to throw into the graph when. We apply a standard approach called *[symbolic execution](https://en.wikipedia.org/wiki/Symbolic_execution)*. Normal program execution would associate variables or registers with, say, concrete numbers. Classic symbolic execution instead associates them with mathematical expressions, over variables that stand for program inputs. Instead of using expressions, though, we associate registers with *node IDs in the graph we are building*, which is very compact and supports cheap equality tests.

Here is an example showing symbolic execution of the optimized program, where we maintain a mapping from registers to graph node IDs.

CryptOpt actually supports fancier program features than this example shows. Programs may use memory in particular stylized ways, and symbolic execution also associates *symbolic memory addresses* with graph node IDs. That is, such memory addresses aren’t particular numbers but instead mathematical expressions in a limited language. One challenge is confirming which memory addresses are *disjoint* from each other, so that a write to one doesn’t change the value stored at another. We use a tame version of [separation logic](https://en.wikipedia.org/wiki/Separation_logic) to handle the simple memory patterns characteristic of cryptographic code. It turns out that simplicity is very helpful to achieve security, since complex memory accesses can lead to execution time revealing secret data (see the notion of [cryptographic constant time](https://en.wikipedia.org/wiki/Timing_attack)).

# Comparison with What Anthropic Announced Recently

It’s also useful to do a quick comparison between CryptOpt and [a formal-verification project just announced by Anthropic](https://www.anthropic.com/research/formal-verification), whose listed last author is the same [Jason Gross](https://jasongross.github.io/), from the CryptOpt team during his student days. This newer effort goes way beyond straightline code, proving theorems about a variety of important real-world code, now at the level of [machine code](https://en.wikipedia.org/wiki/Machine_code) (which is lower-level than assembly language, though not by much). They get around the lack of formal specifications for popular software packages in a clever way: by using those packages’ own test suites, certifying that they pass for all possible program inputs within length limits (while conventional testing would only attempt relatively few inputs). As described so far, this flow compares very favorably with CryptOpt, for minimizing trust assumptions in verifying production software. The main issue is that test suites, especially those written for fuzz testing, are not as complete as functional correctness, like CryptOpt establishes. That is, usually not every aspect of functional behavior is covered by a test case.

The actual experiments in question were all structured around [fuzz testing](https://en.wikipedia.org/wiki/Fuzzing), where programs are subjected to many random inputs, in an effort to trigger rare code paths and their bugs. To catch such bugs, compiler *sanitizers* are turned on, to add extra code to detect violations of generic properties like [memory safety](https://en.wikipedia.org/wiki/Memory_safety). Now the formal theorems can rule out not just explicit failures noted in test cases but also memory-safety violations (if the sanitizer would catch them), which is a nice step up. However, sanitizers are usually disabled in building production code. If we want assurance about production code, then this method dramatically grows the set of verification code we need to trust, because *the compiler itself becomes trusted*, which is not the case with CryptOpt. We are trusting that the compiler outputs sanitized code that is *sufficiently similar* to the no-sanitizer code for production, and bugs throughout the compiler could falsify the assumption. There is also the risk of sanitization itself introducing new bugs or even masking bugs in original code. If we do decide to take the performance hit and keep sanitization in production, then this new formal verification is only helping avoid runtime failures where violations are detected and programs abort safely (which is, of course, valuable; we don’t want a server to go down because a user managed to cause an almost-violation of memory safety).

# Conclusion

This article has a twist ending. I started out motivating this technique as a way to avoid needing to identify all of the useful rewrite rules for program derivation upfront. Then I presented a flow that includes its own vocabulary of proved rewrite rules internally. More importantly, the whole program-equivalence checker is a kind of complex rewrite rule that applies to arbitrary “before” and “after” programs, and this checker itself is quite some work to prove correct! However, once we have the proof, the checker fits nicely into fully automated workflows, probably including ones that would use LLMs to generate program variants.

OK, that’s it for this week’s installment. I’m planning the next article in the series to expand on e-graphs, for more intensive generation of provable equalities about programs, in cases where it is not clear how to find canonical forms for all expressions of interest. If a few things line up in time, though, next week will have an announcement as a break from the technical stuff.
