I'm learning AArch64 assembly. Coming from x86 I found it interesting that there doesn't seem to be any single instruction like xchg to swap two registers. Unless I'm mistaken, the swp instruction only swaps a register with memory (which is of course a much more important case due to atomicity).
There are a few obvious ways to do this, with various tradeoffs. I'll use x0, x1 as examples.
- Using a scratch register: three instructions, one extra register.
mov x2, x0
mov x0, x1
mov x1, x2
- Using the exclusive-or trick: three instructions, no extra register
eor x0, x0, x1
eor x1, x0, x1
eor x0, x0, x1
- Using the stack: two instructions, no extra register, two 16-byte memory accesses:
stp x0, x1, [sp, -16]!
ldp x1, x0, [sp], 16
Are there any better approaches that I am missing? "Better" could be any of: smaller code, faster code (on typical machines), fewer registers needed, less memory access, more idiomatic.
I'd also be interested in approaches that work for the SIMD/FP registers.
(I know this would be a silly thing to try to optimize in most cases; this is more just a way for me to learn about the instruction set than anything else.)