Hacker News

Implementing 128-bit atomics in Cranelift

Atomics on ARM

Before digging into the Cranelift codebase, which was at the time uncharted territory for me, I wanted to take the time to understand which instruction sequences I wanted to emit.

Fortunately, ARM publishes the Architecture Reference Manual on its website. It's a 124MB PDF with over 17,000 pages, but it will come in handy later when we implement new instructions in Cranelift. I'll be referring to version M.d from September 2026.

Atomics on 64-bit ARM are not very different than on other architectures: The base instruction set contains instruction pairs ldar / stlr (64-bit) and ldaxp / stlxp (128-bit) that allow us to perform atomic loads and stores. These instructions have acquire/release semantics.

We'll have to implement four operations: load, store, compare-and-swap (CAS) and read-modify-write (RMW). While loads and stores are straightforward, CAS or RMW operations are actually much more complicated.

The ARMv8.0 baseline does not provide one single instruction to perform these operations. In ARMv8.1, ARM introduced the Large System Extensions (LSE), which add various very useful instructions for 64-bit atomic operations. This was later extended in ARMv9.3 with LSE128, which adds limited support for some 128-bit atomic operations.

However, we cannot make use of these extensions because they are not part of the target baseline. Ideally, we would generate better code if the target features for LSE or LSE128 are enabled, but for implementing any kind of support for 128-bit atomics at all, we will need to use less optimal fallbacks.

Atomics in WASM

Cranelift is written first and foremost for wasmtime, a WebAssembly runtime. This means that its model of atomics is heavily influenced by WebAssembly's needs. Most importantly, WebAssembly requires sequentially consistent memory ordering for atomic memory accesses.

This is relevant for us on ARM, because there atomic load instructions instead only have acquire semantics, and atomic stores have release semantics. All the atomic operations we are going to be implementing have to be implemented sequentially consistently.

Learning from LLVM

Let's take a look at how LLVM handles this. Ideally, we'll make Cranelift emit the same instructions as LLVM. Compiler Explorer is an incredibly useful tool to see what assembly LLVM outputs for a given snippet of, in this case, Rust code.

All the following examples can be found in this Compiler Explorer snippet. Note the use of -Ctarget-feature=-outline-atomics, which forces LLVM to inline the atomic operations. If we didn't set this flag, LLVM would instead emit calls to helper functions that detect whether LSE is available or not and conditionally make use of LSE if available, and otherwise use a fallback. But these calls hide the assembly that we're after.

Let's look at add_u128:

add_u128:
    mov x8, x0
.LBB0_1:
    ldaxp x0, x1, [x8]
    adds x9, x0, x2
    adc x10, x1, x3
    stlxp w11, x9, x10, [x8]
    cbnz w11, .LBB0_1
    ret

This is actually a loop, and it is a common pattern for all the read-modify-write operations (in this case, the "modify" is adding a number to the value). The loop follows this pattern:

  • Atomically load the value at the memory location and mark it as exclusively accessed (with ldaxp)
  • Compute a new value based on the previous value and our operand (adds, adc)
  • Atomically store the new value to the memory location with exclusive access (stlxp)
  • If the store failed to update the value, go to 1. (cbnz)

A load with ldaxp marks the address as accessed with exclusive access, and stlxp will only write back the value to memory if no other store to the address was performed in the meantime. If such a store occurred, the store would fail and the entire operation retried thanks to the loop. Overall, this implementation will ensure sequential consistency.

Also worth checking out is how LLVM ensures sequentially consistent memory ordering for load_u128:

load_u128:
    mov x8, x0
.LBB4_1:
    ldaxp x0, x1, [x8]
    stlxp w9, x0, x1, [x8]
    cbnz w9, .LBB4_1
    ret

It simply attempts to store back the loaded value in a loop. Because it uses the exclusive load and store instructions, which use the exclusive monitor on ARM CPUs, we establish a single total modification order with the other sequentially consistent atomic operations.

Cranelift

Cranelift lives inside the wasmtime monorepository, and fortunately we'll mostly be working with a very small part of the wasmtime codebase, all of which except for some tests resides inside the cranelift/codegen/ directory. As an example, we'll be implementing the 128-bit atomic load; the other operations are quite similar and only require generating slightly more complex instruction sequences.

Finding a starting point

At first, I didn't really know where to start, so I figured the best approach would be to find the place where atomics are wired up in codegen by making it error. From the top-level cranelift directory, running fd atomic gave me a bunch of interesting results:

...
filetests/filetests/isa/aarch64/atomic-cas.clif
filetests/filetests/isa/aarch64/atomic-rmw-lse.clif
filetests/filetests/isa/aarch64/atomic-rmw.clif
filetests/filetests/isa/aarch64/atomic_load.clif
filetests/filetests/isa/aarch64/atomic_store.clif
...

These testcases look very promising.

Adding a failing test

The tests set a bunch of options at the beginning, for example: test compile precise-output to specify that this is a codegen test, as opposed to a test that is intended to be run, target aarch64 to enable a test for AArch64, target aarch64 has_lse to enable a test for AArch64 and use LSE instructions.

What follows are function definitions in CLIF, Cranelift's intermediate representation (IR). For example, atomic_load.clif contains the following function:

function %atomic_load_i64(i64) -> i64 {
block0(v0: i64):
    v1 = atomic_load.i64 v0
    return v1
}

This performs a 64-bit atomic load from the address in v0 and returns the value read. The function definition is followed by a comment with the expected output: first the expected VCode[1] and then the expected assembly. The test runner will check the actual output against this comment, and there is tooling to automatically generate or update the expected output.

; VCode:
; block0:
; ldar x0, [x0]
; ret
;
; Disassembled:
; block0:
; offset 0x0
; ldar x0, [x0]
; trap: heap_oob
; ret

So what happens when we just try to use 128-bit atomics?

function %atomic_load_i128(i64) -> i128 {
block0(v0: i64):
    v1 = atomic_load.i128 v0
    return v1
}

Let's run the test:

$ cargo run -p cranelift-tools -- test filetests/filetests/isa/aarch64/atomic_load.clif
[2026-10-26T15:48:45Z ERROR cranelift_filetests::concurrent] FAIL: compile FAIL filetests/filetests/isa/aarch64/atomic_load.clif: compile
Caused by: Unsupported feature: should be implemented in ISLE: inst = `v1 = atomic_load.i128 v0`, type = `Some(types::I128)`
1 tests
Error: 1 failure

The error is expected, but it even tells us what to do! Presumably, we need to teach Cranelift what to do when it encounters an atomic_load instruction with a type of i128.

ISLE lowerings

Let's try to look for the code that handles the atomic_load instruction:

$ rg atomic_load src/isa/aarch64/
src/isa/aarch64/lower.isle
1326:(rule 1 (lower (uextend (fits_in_64 out) x @ (and (value_type in) (atomic_load _ (little_or_native_endian flags) _))))
1328: (load_acquire in flags (sink_atomic_load mem_op)))
2385:(rule (lower (atomic_load (valid_atomic_transaction ty) (little_or_native_endian flags) addr))
...

That looks promising! Specifically, lower.isle around line 2385:

;;;; Rules for `AtomicLoad` ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(rule (lower (atomic_load (valid_atomic_transaction ty) (little_or_native_endian flags) addr))
    (load_acquire ty flags addr))

What we're looking at here is ISLE, which stands for "Instruction Selection Lowering Expressions". There's a great introduction to ISLE that can be found here, but at the time, I didn't read it and we don't need to know a lot about it other than: it's a LISP-flavored DSL for term rewriting.

Specifically, this ISLE expression tells Cranelift that atomic_load should be rewritten to load_acquire, provided that the type ty is a valid_atomic_transaction. But what does load_acquire then get rewritten to? The answer can be found in inst.isle:

;; Helper for emitting `MInst.LoadAcquire` instructions.
(decl load_acquire (Type MemFlagsData Reg) Reg)
(rule (load_acquire ty flags addr)
    (let ((dst WritableReg (temp_writable_reg $I64))
          (_ Unit (emit (MInst.LoadAcquire ty dst addr flags))))
    dst))

There's a lot going on here. load_acquire takes a type, some flags and a register with the address, and returns the value in a register. It allocates a new writable register for storing the result and then emits the LoadAcquire instruction to load the value into this register and then finally returns the register.

The LoadAcquire instruction definition can be found a bit earlier in the same file:

;; Read `access_ty` bits from address `rt`, either 8, 16, 32 or 64-bits, and put
;; it in `rn`, optionally zero-extending to fill a word or double word result.
;; This instruction is sequentially consistent.
(LoadAcquire (access_ty Type) ;; I8, I16, I32 or I64
             (rt WritableReg)
             (rn Reg)
             (flags MemFlagsData))

From the definition of LoadAcquire, it's obvious that it is not a suitable instruction to use for a 128-bit atomic load. For a 64-bit atomic load, one destination register (rt) is sufficient, but if we want to perform a 128-bit atomic load and store the result in GPRs, we will need two destination registers.

Wiring it up

Therefore, we will need to add a new instruction, LoadAcquire128. It'll look as follows:

;; Read 128 bits from address `rn` and put the lower and upper halves in `rt1` and `rt2`
;; respectively.
;; This instruction is sequentially consistent.
(LoadAcquire128 (rt1 WritableReg)
                (rt2 WritableReg)
                (rn Reg)
                (scratch WritableReg)
                (flags MemFlagsData))

Why do we need scratch here? Remember: our implementation of the atomic load must be sequentially consistent. We will use an exclusive load-store loop to guarantee this ordering. scratch is a register we will use to hold the success status of the store operation, its value before and after the instruction has no meaning.

We'll also need a helper for emitting the instruction in CLIF:

;; Helper for emitting `MInst.LoadAcquire128` instructions.
(decl load_acquire_128 (MemFlagsData Reg) ValueRegs)
(rule (load_acquire_128 flags addr)
    (let ((dst_lo WritableReg (temp_writable_reg $I64))
          (dst_hi WritableReg (temp_writable_reg $I64))
          (scratch WritableReg (temp_writable_reg $I64))
          (_ Unit (emit (MInst.LoadAcquire128 dst_lo dst_hi addr scratch flags))))
    (value_regs dst_lo dst_hi)))

Nothing particularly exciting, we allocate the necessary registers and return the resulting loaded value in a pair of GPRs. Now, we want to make sure that an atomic_load.i128 gets lowered to load_acquire_128 rather than load_acquire. We can do so by adding a more specific lowering rule:

;; Lower 128-bit `atomic_load` through a special case
(rule 1 (lower (atomic_load $I128 (little_or_native_endian flags) addr))
    (load_acquire_128 flags addr))

rule 1 sets the precedence for this rule higher than the one for the smaller atomic loads, which used just rule and therefore defaults to precedence 0.

Attempting to compile Cranelift right after adding this new instruction will fail. We need to teach Cranelift a few things about our instruction before this will compile. In src/isa/aarch64/inst/mod.rs, there's two matches on the Inst enum (which gets auto-generated from the ISLE definitions) that need branches for the new instruction. One of them, print_with_state, is for pretty-printing it, but the other case needs a bit more careful treatment.

regalloc

The register allocator needs to know how the registers are being used by our new Cranelift instruction. The value in rn is the address to perform the atomic load from; we will not write to it, so we're going to tell the register allocator that the register is an input that's being used but not written to. rt1 and rt2 are the two registers we'll write the value to, so we will tell regalloc that they're getting redefined. Similarly, we don't care about the value of scratch at the beginning of the instruction, but we'll be writing to it.

// fn aarch64_get_operands
Inst::LoadAcquire128 { rt1, rt2, rn, scratch, .. } => {
    collector.reg_use(rn);
    collector.reg_def(rt1);
    collector.reg_def(rt2);
    collector.reg_def(scratch);
}

A neat thing here is that, in Cranelift, Writable and Reg are separate types, and you can only call reg_def with a Writable. In case you want to convert from Writable to Reg, you can use Writable::to_reg(). This prevents some footguns like marking a read-only register

Read on Hacker News ↗ ← Back to News

Comments

No comments yet. Start the discussion.