xchg
Exchange register/memory with register
Exchanges the values of its two operands.
8086 and later
CFPFAFZFSFDFOF –––––––
- Changes no flag
Forms
Operands
reg- A general-purpose register matching the operation’s size, for example
al,ax,eaxorrax. The byte registersah,bh,chanddhcannot be used with a REX prefix, which is required byspl,bpl,sil,dilandr8–r15. r/m- A general-purpose register or memory location matching the operation’s size, for example
raxorqword [rbp-8]. The byte registersah,bh,chanddhcannot be used with a REX prefix, including when the memory address usesr8–r15. acc- The accumulator matching the operation’s size:
al,ax,eaxorrax. A shorter encoding may be available.
When one of them is in memory, the exchange is always atomic, lock prefix or not, so xchg with memory is a ready-made synchronisation primitive, and slower than an ordinary move for that reason. A lock prefix on an exchange of two registers raises an invalid-opcode fault.
In 64-bit code a 32-bit exchange clears the upper halves of both 64-bit registers, xchg eax, eax included: NASM assembles that as a real exchange rather than as 90h, which in 64-bit mode is always a nop.
global _start
section .text
_start:
mov rax, 12
mov rbx, 5
mov rcx, 3
mov rsi, 9
xchg rax, rbx
mov rax, 60 ; syscall 60: exit
xor rdi, rdi
syscall