Skip to content

Instantly share code, notes, and snippets.

@TheGag96
Created December 17, 2024 14:02
Show Gist options
  • Save TheGag96/ba67dde34365afc951c35bc52ecbcf55 to your computer and use it in GitHub Desktop.
Save TheGag96/ba67dde34365afc951c35bc52ecbcf55 to your computer and use it in GitHub Desktop.
Hacky ARM64 atomics in Jai
// ARM64 hack: Unlike x64, even though aligned reads are atomic, ARM64 doesn't guarantee acquire semantics with
// normal reads and release semantics with normal stores. There are separate instructions for those,
// and since we don't have ARM64 inline assembly yet, we must implement them with this very very spooky
// hack where we hardcode the machine instructions we want. The parameters are assumed to be passed
// according to Jai's current LLVM ABI!
// Thanks @ctpeepee!
atomic_read :: no_inline (pointer: *s64) -> s64 {
// ldr x1, [x1] x1 initially contains a pointer to "pointer", which itself is a pointer
// ldar x1, [x1]
// str x1, [x2] x2 here contains a pointer to the first return value.
defer #bytes .[0x21, 0x00, 0x40, 0xF9, 0x21, 0xFC, 0xDF, 0xC8, 0x41, 0x00, 0x00, 0xF9];
return 0;
}
atomic_write :: no_inline (pointer: *s64, new_value: s64) {
// ldr x2, [x2] x2 initially contains a pointer to "new_value"
// ldr x1, [x1] x1 initially contains a pointer to "pointer", which itself is a pointer
// stlr x2, [x1]
#bytes .[0x42, 0x00, 0x40, 0xF9, 0x21, 0x00, 0x40, 0xF9, 0x22, 0xFC, 0x9F, 0xC8];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment