Skip to content
Compilers & AI Scheduling · Codegen & FFI

Cranelift JIT, LLVM AOT & FFI

Weyl's dual-backend codegen strategy—sub-second pure-Rust Cranelift JIT with inline double-double loops, peak-throughput LLVM AOT, TermRecord ABI layout, and the thin weyl-ffi boundary.

Computational physics naturally splits into two contrasting workloads: interactive exploration and oracle verification (REPL probes, ray-sweep ED checks, single-sector Lanczos, pCUT inner loops), where sub-second compilation latency and zero native toolchain dependencies matter most; and long-running production numerics (DMRG/MPO contractions, quantum bootstrap SDPs, large Krylov solves), where AVX-512/NEON vectorization and GPU/OpenMP throughput dominate. Weyl answers both with a dual-backend codegen strategy—Cranelift JIT (weyl-jit-clif) paired with LLVM AOT (via weyl-mlir)—and exposes compiled artifacts through a thin FFI boundary (weyl-ffi).

Cranelift JIT (weyl-jit-clif): Sub-Second Interactive & ED Kernels ​

During Stage B exact diagonalization (e.g. a stabilizer-reduced L=12,W=2L=12, W=2 cylinder sector), over 90% of wall time goes into matrix-free w=H⋅vw = H \cdot v inside Lanczos. For an nn-qubit Pauli Hamiltonian on the full computational basis, row bb evaluates as:

out[b]=∑t=1Mct⋅st(b⊕ft)⋅in[b⊕ft]\text{out}[b] = \sum_{t=1}^{M} c_t \cdot s_t(b \oplus f_t) \cdot \text{in}[b \oplus f_t]

where ftf_t is the flip mask (X,YX, Y sites) of Pauli word tt, and st(k)=(−1)popcnt(k & mt)s_t(k) = (-1)^{\text{popcnt}(k \,\&\, m_t)} is its sign on ket ∣k⟩|k\rangle (mtm_t marks Y,ZY, Z sites; factors of ii from each YY are folded into the word phase at compile time, and purely imaginary words are skipped in real symmetric kernels).

weyl-jit-clif compiles TirKernel::MatVec directly to native machine code, baking every flip, sign_mask, and scalar coeff into the instruction stream as immediates. This eliminates interpreter dispatch and table lookups: each Pauli term compiles to one XOR, one load, one hardware popcnt, and one multiply-add.

rust
// crates/weyl-jit-clif/src/lib.rs — Native compiled MatVec handle
pub struct CompiledMatVec {
    pub basis_dim: usize,
    pub precision: Precision,   // F64 or DoubleDouble
    pub n_terms: usize,         // Real-phase nonzero terms
    /// Native entry point: fn(input, output, start_row, end_row)
    entry: unsafe extern "C" fn(*const f64, *mut f64, i64, i64),
    module: Option<JITModule>,  // Owns executable memory; freed safely on Drop
}

Inline Double-Double Loops & Deterministic Floating-Point ​

For high-order residual-slope checks (Precision::DoubleDouble), weyl-jit-clif emits Knuth's TwoSum, Dekker's QuickTwoSum, and hardware-FMA TwoProd directly into Cranelift IR, matching weyl_num::dd::Dd instruction for instruction:

rust
// crates/weyl-jit-clif/src/lib.rs — Cranelift IR emission for TwoSum and FMA TwoProd
fn two_sum(b: &mut FunctionBuilder, x: Value, y: Value) -> (Value, Value) {
    let s  = b.ins().fadd(x, y);
    let bb = b.ins().fsub(s, x);
    let t1 = b.ins().fsub(s, bb);
    let t2 = b.ins().fsub(x, t1);
    let t3 = b.ins().fsub(y, bb);
    (s, b.ins().fadd(t2, t3))
}

fn mul(b: &mut FunctionBuilder, x: (Value, Value), y: (Value, Value)) -> (Value, Value) {
    let p1    = b.ins().fmul(x.0, y.0);
    let neg   = b.ins().fneg(p1);
    let p2    = b.ins().fma(x.0, y.0, neg);     // Exact rounding error: x.hi * y.hi - p1
    let cross = b.ins().fadd(b.ins().fmul(x.0, y.1), b.ins().fmul(x.1, y.0));
    Self::quick_two_sum(b, p1, b.ins().fadd(p2, cross))
}

Strict Floating-Point Flags & Bit-Exact Parity

To guarantee bit-for-bit parity with the pure-Rust weyl-tir reference interpreter across any thread count (partitioned in fixed chunks of ROWS_PER_TASK = 1 << 14), weyl-jit-clif accumulates terms in exact TirKernel order with no fast-math reassociation (reassoc) or cross-term fusion. In CI, differential tests run both TirKernel::apply_matvec_f64/apply_matvec_dd and CompiledMatVec on randomized kernels and compare to_bits() directly, so even a 1-ULP discrepancy fails the build.

Lock-Free Row Partitioning & Thread Determinism ​

CompiledMatVec is Send + Sync: the generated machine code only reads input, writes disjoint slices output[start..end], and touches zero shared mutable state. Dispatch scales automatically with basis dimension:

rust
// crates/weyl-jit-clif/src/lib.rs — Lock-free row partitioning
const ROWS_PER_TASK: usize = 1 << 14; // At least 16,384 rows per worker

// Below 2^17 (131,072) basis states, execute on the calling thread to avoid wake overhead;
// above it, fan out disjoint row ranges via std::thread::scope calling entry(in, out, s, e).
let workers = if dim < 1 << 17 {
    1
} else {
    std::thread::available_parallelism()
        .map_or(1, |w| w.get())
        .min(dim.div_ceil(ROWS_PER_TASK))
};

Because every row output[b] sums its MM Pauli terms independently in fixed kernel order, changing thread counts never alters floating-point evaluation order—guaranteeing bit-identical outputs from 1 to 64 threads.

LLVM AOT Pipeline: Peak Throughput & Heterogeneous Targets Draft ​

Current status of the LLVM path

What exists today is in weyl-mlir: MatVec (f64) and series kernels lower to standard-dialect MLIR, and weyl_mlir::aot::Toolchain compiles a module to an object file or shared library by running an installed mlir-opt, mlir-translate and clang (tested with LLVM 23). The compiled H·v agrees bit for bit with the reference interpreter. See Symbolic Middle-End & MLIR Lowering.

There is no weylc build command, no --backend switch, no double-double or SIMD-specialised LLVM code. weyl-ffi does exist (a C ABI in weyl.h and a PyO3 module), but its interface differs from the one shown below; the commands and C header below describe the design, not the current tool. From the CLI, weylc dump-ir --emit mlir and --emit llvm-ir print the modules.

For multi-hour DMRG/MPO sweeps, SDP block solves, and large multi-sector Krylov jobs, a few seconds of compile time are negligible compared to runtime throughput. Once weyl-mlir lowers TirKernel to MLIR's llvm dialect, the LLVM AOT pipeline emits native objects (.o) or shared libraries (.so/.dylib) with wide SIMD vectorization targeting AVX-512 (x86_64) and SVE/NEON (aarch64) over SoA-packed buffers for 8-wide f64 fused multiply-add throughput. For high-rank tensor contractions, the pipeline applies polyhedral loop tiling, prefetching, and OpenMP thread parallelism, with optional CUDA/ROCm offloading for large linalg.matmul and block-sparse MatVec kernels. Throughout, AOT builds default to -fno-fast-math -ffp-contract=off (permitting hardware FMA only on explicit fma ops), preserving IEEE 754 rounding semantics while embedding error-lattice metadata in a .weyl.err object section.

Dual-Backend Trade-Off Matrix ​

DimensionCranelift JIT (weyl-jit-clif)LLVM AOT (weyl-mlir → LLVM)
Compile latency2–30 ms, ideal for REPL & sweeps0.5–15 s, suited for production runs
Native dependenciesPure Rust, zero system LLVM neededSystem LLVM/MLIR (Phase 3 feature)
Runtime throughputScalar + basic SIMD (~60%–85% of LLVM)Peak throughput (AVX-512 / NEON / GPU)
Double-double codegenInline TwoSum/TwoProd per termWide-vector SoA TwoSum/TwoProd
Primary workloadsStage A/B ED oracle, pCUT probes, REPLPhase 3 DMRG/MPO, SDP bootstrap, HPC

Arithmetic Intensity: How Double-Double Shifts the Bottleneck ​

For a matrix-free MatVec with MM nonzero Pauli words per row, changing scalar precision shifts the hardware bottleneck dramatically. Under Precision::F64, each term loads 8 B and performs ~2 FLOPs—an arithmetic intensity of ≈0.25 FLOP/B\approx 0.25\text{ FLOP/B}—so execution is strictly memory-bandwidth bound, and Cranelift JIT saturates memory bandwidth almost as effectively as LLVM AOT. Under Precision::DoubleDouble, each term loads 16 B (hi, lo), while TwoSum, QuickTwoSum, and FMA TwoProd execute ~25–30 FLOPs, lifting arithmetic intensity to ≈1.8 FLOP/B\approx 1.8\text{ FLOP/B} and pushing the loop into a compute-bound regime where LLVM AOT's wide AVX-512 SoA vectorization delivers a 3–6×3\text{–}6\times speedup on long-running large-cylinder sweeps (e.g. L=16L=16).

TermRecord & Numerical Kernel C-ABI Layout ​

Both the symbolic kernel stream and numerical FFI boundary use explicitly aligned #[repr(C)] layouts to avoid serialization copies across languages:

rust
// 1. Flat KIR sparse term header (8-byte aligned for zero-copy mmap / external spill)
#[repr(C, align(8))]
pub struct TermHeader {
    pub len: u32,       // Total record byte length (padded to 8-byte alignment)
    pub mono_len: u16,  // Byte length of canonical monomial encoding
    pub flags: u16,     // Bit 0: imaginary flag (i^1 vs i^0)
}
// Memory layout: [TermHeader (8B)][coeff: [u64; K] (8*K B)][mono: [u8; mono_len]][pad]

// 2. Double-double scalar (16-byte aligned, identical to C struct { double hi; double lo; })
#[repr(C)]
#[derive(Copy, Clone)]
pub struct Dd {
    pub hi: f64,
    pub lo: f64,
}

Thin Interop Layer (weyl-ffi) Draft ​

To keep the compiler core 100% pure Rust (preserving determinism, memory safety, and data-race freedom), all foreign bindings are isolated in weyl-ffi (rlib + cdylib). Core crates never depend on weyl-ffi.

c
/* weyl_ffi.h — Stable C ABI for C / Fortran / Julia / Python ctypes */
typedef struct WeylMatVecHandle WeylMatVecHandle;

typedef struct {
    double hi;
    double lo;
} WeylDd;

int32_t weyl_matvec_apply_f64(
    const WeylMatVecHandle* handle,
    const double* input,
    double* output,
    size_t dim
);

int32_t weyl_matvec_apply_dd(
    const WeylMatVecHandle* handle,
    const WeylDd* input,
    WeylDd* output,
    size_t dim
);

weyl-ffi organizes foreign interop around three strict boundary invariants. Its PyO3 Python extension exposes verified SeriesTable values and compiled CompiledMatVec handles as zero-copy NumPy/SciPy LinearOperator objects for TeNPy and downstream plotting. For template-heavy C++ libraries that lack a C ABI—such as ITensor C++, Eigen, and the MLIR C++ API—it relies on a safe cxx bridge that prevents C++ exceptions from unwinding across the boundary by translating them into Rust Result values. Across every foreign surface, opaque handles enforce provenance isolation: any numerical result returned by an external library carries an External source and is never treated as an Exact symbolic value.

bash
# Emit an LLVM AOT shared library with C ABI and Python bindings
$ weylc build examples/toric_boundary.weyl --backend=llvm --emit=cdylib -o libtoric_ed.so
# Or run zero-dependency Cranelift JIT in Phase 1
$ weylc run examples/toric_boundary.weyl --backend=cranelift --verify-ed

With weyl-ffi's PyO3 extension, Python callers wrap a compiled MatVec directly into SciPy while inspecting its preserved error-lattice tag:

python
import numpy as np
from scipy.sparse.linalg import LinearOperator, eigsh
import weyl

kernel = weyl.load_matvec("libtoric_ed.so", sector="k=0,W_e_top=+1")
assert kernel.error_tag.epi == "Exact"  # Verify symbolic Hamiltonian provenance

op = LinearOperator(
    shape=(kernel.dim, kernel.dim),
    matvec=lambda v: kernel.apply_f64(np.ascontiguousarray(v, dtype=np.float64)),
    dtype=np.float64,
)
vals, _ = eigsh(op, k=2, which="SA", tol=1e-13)
print(f"E0 = {vals[0]:.12f}, gap_intra = {vals[1] - vals[0]:.12f}")

Weyl v0.1 · MIT License