xchg

Exchange register/memory with register

Exchanges the values of its two operands.

8086 and later

Intel's reference: XCHG

CFPFAFZFSFDFOF –––––––
  • Changes no flag

Forms

Operands

reg
A general-purpose register matching the operation’s size, for example al, ax, eax or rax. The byte registers ah, bh, ch and dh cannot be used with a REX prefix, which is required by spl, bpl, sil, dil and r8–r15.
r/m
A general-purpose register or memory location matching the operation’s size, for example rax or qword [rbp-8]. The byte registers ah, bh, ch and dh cannot be used with a REX prefix, including when the memory address uses r8–r15.
acc
The accumulator matching the operation’s size: al, ax, eax or rax. 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