One aspect of Clojure that I've always liked is that it is, first and foremost, a pragmatic language. It will steer you towards using functional style by default, but it also offers imperative escape hatches for performance. For example, transients are used for cases when you need to build up a big vector in a tight loop. We can mutate a transient freely, then hand back an immutable value at the end by calling persistent!. What makes transients safe is that the mutation is explicitly scoped since any further attempt to mutate the data after persistent! was called throws. So, we can have the performance benefit of working with mutable data in a local scope, and the semantics of transients ensure that it can't leak to the outer context.
I decided to see if I could apply a similar pattern at an even lower level in Jolt, which resulted in the idea of having native regions. A region drops out of the managed runtime entirely to run as plain C, then returns a Jolt array at the end:
(require '[jolt.native :refer [native]])
(defn norm [^doubles xs]
(native [^doubles xs]
(loop [i 0 s 0.0]
(if (< i (alength xs))
(recur (inc i) (+ s (* (aget xs i) (aget xs i))))
(Math/sqrt s)))))
The body of a native macro is a numeric subset of Clojure that can be safely compiled to C. When jolt build produces a binary, the region's C is compiled and linked in, while in the REPL or under jolt run, the code gets compiled by a JIT the first time the call site loads.
Why not just call C?
You might ask why even bother with such a mechanism since Jolt already supports FFI. Naturally, before diving into writing any code, I did a bit of testing with heavy numerical computation linked as a static native library. As expected, the C ran 6.3x faster than hinted Jolt, but the cost of getting data across the boundary overshadowed the benefits for small amounts of data. Opening an FFI arena, allocating into it, then copying doubles back out using write-array takes hundreds of ns. So, FFI is only useful when there is a significant amount of work being done to justify the overhead.
On the other hand, regions don't need to marshal anything because Jolt's double-array is a Chez Scheme flvector, and emitted C can be written directly against its layout. When a region borrows a ^doubles or a ^longs argument, C gets a pointer to the array's own storage where it can read and write the elements in place. And that's how regions skip having to copy the data along with all the ceremony involved in the FFI layer. Since the region works directly on memory Jolt already owns, the overhead for each call is just a few nanoseconds.
Memory safety without a garbage collector
One tricky aspect of regions is that they bypass the GC. Since arrays get created using calloc, they have to be freed exactly once on every path, including cases when something throws inside a loop. Here, Jolt borrows ideas from Carp to track ownership with a pass modelled on Carp's Memory.hs approach.
Every array a region allocates must have a single owner, and its ownership has to move when it's passed from one owner to another. Reading an array constitutes a borrow, allowing the checker to confirm that it's still live at the point of use. When a let scope ends, it frees the values that haven't been given away, while an error exit will free whatever is left live at the point of failure. The only way an array can leave a region is as a fresh Jolt array.
A region can also call helper functions, which are defined using defnative. They are handy for things like a dot product or a vector normalization that several regions share. Helpers compile to a plain C functions inside a region while acting as ordinary Clojure functions outside them.
Helpers don't need ownership annotations because the compiler reads their body to decide what happens to an array when a region passes it to a helper. If some path in the body gives the array away by returning it or recurring with it, then the helper takes ownership of it. Otherwise the helper only borrows the array and the original caller still owns it. If you try to use an array after a helper has taken ownership of it, the compiler gives a descriptive error indicating which helper took it and why:
native region: borrows a after it was given away (moved);
native-test/keep-it took ownership of its 1st argument (it returns it);
use (aclone x) to keep a copy
Typed using existing hints
The only type annotations a region needs are the hints on its initial parameters: ^long, ^double, ^boolean, ^doubles, ^longs and ^bytes. Everything else can be inferred by the compiler, meaning that helpers used in a region don't need hints of their own. Each defnative also gets compiled once per distinct set of argument types at its call sites, which is inspired by the way Carp concretizes its generic functions.
Threads and the collector trade offs
Since Chez uses a stop-the-world collector which waits for every active thread to reach a safe point, a plain foreign call has to keep its thread active resulting in a long-running region stalling garbage collection for the whole process. This is the famous Python GIL problem we're all familiar with.
Jolt follows G1's region pinning and GHC's safe foreign calls instead. Each array is first pinned within the region that borrows it so the collector won't move it, then the call goes through Chez's __collect_safe convention when the thread steps out of the runtime. This way, other threads can keep running and collecting while the pinned arrays stay put. To ensure that nothing can unwind in the interim, interrupts are disabled between locking and unlocking, nor is region code allowed to throw an exception into Scheme or call back into it.
Since pinning regions this way costs about 45ns a call, the overhead ends up dominating for a region that finishes quickly. To address that, there is a ^:hold-gc hint to opt into a plain call instead:
(native ^:hold-gc [^double x] (* x x))
With ^:hold-gc a call finishes in about 2.5ns while holding every other thread's collection until the region returns. You can think of it as a global lock that can be used when the critical section is short.
A few further optimizations are possible in the generated C code itself. These optimizations include a range analysis that computes intervals for loop variables, which removes the need for overflow and bounds checks when those checks can be proven not to fire. It also tracks symbolic bounds, so an index under a ^long parameter or another array's length is guarded once on entry rather than on every iteration. Meanwhile, small constant-size arrays can go on the C stack instead of the heap, and arrays that are only touched at constant indexes are packed into a C local per element, allowing a vec3 to stay in registers.
Generating C at runtime
Jolt now bundles MIR which is a small JIT that's just over half a megabyte in size. Having a C compiler inside the process means that regions can be compiled at runtime as well as during the build step. For example, listing parameters under :specialize makes the JIT compile a variant of the region for each distinct value of those parameters that the call site sees:
(defn msum [^long n ^doubles m]
(native ^{:specialize [n]} [^long n ^doubles m]
(loop [i 0 s 0.0]
(if (< i n)
(recur (inc i) (loop [j 0 s s] (if (< j n) (recur (inc j) (+ s (aget m (+ (* i n) j)))) s)))
s))))
With n = 4, the range analysis knows that (+ (* i n) j) stays within [0, 15], so the variant checks the length of the array once up front and drops the overflow and bounds checks inside the loop. A call site compiles up to 8 variants by default, which can be further tuned using :max-variants.
A region can also be built from data at runtime using native-fn which takes the parameters and the body as data and returns a function backed by native code:
(def sq (native-fn '[^long n] '((* n n))))
(sq 7) ;=> 49
Then, jolt.native.layout can use it to turn a binary record layout into a parser. The offsets, widths, byte order and sign extension become constants in C, so there's no interpretation needed at runtime:
(require '[jolt.native.layout :as layout])
(def header [[:magic :u32] [:version :u8] [:pad 1] [:count :u16] [:size :i64]])
((layout/parser header) buf 0) ; => long-array of the fields
((layout/column header :size) buf) ; => :size of every record in buf
Since each distinct region stays compiled for the life of the process, the mechanism works best when you generate a region per shape of data, then pass it the values that change as parameters.
Finally, it's worth mentioning defnative macro which accepts a body per platform under C preprocessor guards, allowing a SIMD path and a portable one to coexist. The JIT defines the feature macros of the CPU it's running on (__AVX2__, __FMA__, __ARM_NEON and so on), and each machine ends up running the body it supports. MIR has no SIMD intrinsics, so the SIMD body has to call a C function that's built with them through defextern:
; built with AVX2, in a :jolt/native lib
(defextern ^double dot-avx2 [^doubles xs ^doubles ys])
(defnative dot [xs ys]
(on "defined(__AVX2__)" (dot-avx2 xs ys))
(on :default (loop [i 0 s 0.0] ...)))
Conclusion
Native regions are a good example of the types of optimizations that become possible on a runtime that embraces the native ecosystem. The JVM creates an environment that's isolated from the underlying system, which in turn imposes inherent costs on crossing its barriers. For instance, the FFM API's Arena and MemorySegment abstractions can generate temporary Java objects in hot paths, such as when wrapping a ByteBuffer for a native copy, forcing low-latency applications to either absorb GC pressure or fall back to unsafe pointer arithmetic. On the other hand, the Chez runtime is designed to provide ways to reach into the native environment as needed, which I would argue fits better with the pragmatic philosophy of Clojure.
Native regions currently cover a small subset of Clojure aimed at numeric computation, which is where this kind of optimization pays off most often, but the subset can grow to cover other work such as string manipulation going forward. What makes the mechanic interesting is that the outer shell of your program is written as dynamically typed Clojure, while a hot loop can become a region that gets compiled to native code. In effect, Jolt now has a statically typed, borrow checked sublanguage living inside a dynamically typed one.
Full documentation for the feature is available on the official site.