Compiling OxCaml with MLIR
SPEAKERS
ABSTRACT
OCaml has a fairly fixed path out of the type checker -> Typedtree, Lambda, Slambda, Flambda 2, Cmm, CFG, and finally assembly. At every stage, some information is lost. Lambda erases types, Cmm no longer distinguishes clearly between an OCaml value and a machine word, CFG turns structured control flow into a lower-level representation.
Flambda 2 is an excellent optimiser, but part of its job is recovering information that was discarded earlier in the pipeline. For example, a float may have been boxed because of an earlier representation decision, only for Flambda 2 to later figure out that it can be unboxed.
Moonshot is a fork of OxCaml that takes a different approach. Instead of going through Lambda, Cmm, and CFG, it translates the typed AST directly into a custom ocaml MLIR dialect. From there, it uses MLIR's existing lowering infrastructure to reach LLVM IR and eventually a native object file.
The main goal is performance. The idea is simple: if OCaml already knows something at the type checking stage, we should try to keep that information instead of throwing it away and recovering it later.
This talk is about what MLIR can bring to OCaml and OxCaml, and how we plan to get there.
OxCaml has already extended the type system with information about layouts, modes, and unboxed data. However, much of this information is eventually flattened when the compiler reaches Cmm. With an MLIR dialect, this information has a place to remain in the backend.
For example, floats can be represented in an unboxed form by construction instead of relying on a later optimisation pass to recover that fact. Auto-vectorisation, which ocamlopt currently does not provide, also becomes much more accessible through MLIR's vector and affine dialects. Immutability and non-aliasing can be represented as metadata that LLVM can use during optimisation.
It also changes how optimisation work can be developed. Instead of relying mainly on a large and complex whole-program optimiser, individual optimisations can be implemented as passes that are easier to understand, test, and contribute to.
I will go through the project milestone by milestone. We start with runtime and GC integration, followed by data representation, closures, and exceptions. Then we move towards compiling a real package end to end. After that comes a proper benchmark baseline against Flambda 2 and CFG. Only once those pieces are working do we move into the larger optimisation work that they enable.
I will cover published evidence showing that the same optimisation can sometimes run more effectively on a higher-level IR than on a lower-level one, the performance numbers we are targeting, and the correctness work that has to happen before any of those numbers matter.