AMD amd64 architecture User Manual

Page of 336
General-Purpose Programming
65
24592—Rev. 3.15—November 2009
AMD64 Technology
CMPXCHG—Compare and Exchange
CMPXCHG8B—Compare and Exchange Eight Bytes
CMPXCHG16B—Compare and Exchange Sixteen Bytes
XADD—Exchange and Add
XCHG—Exchange
The CMPXCHG instruction compares a value in the AL or rAX register with the first (destination)
operand, and sets the arithmetic flags (ZF, OF, SF, AF, CF, PF) according to the result. If the compared
values are equal, the source operand is loaded into the destination operand. If they are not equal, the
first operand is loaded into the accumulator. CMPXCHG can be used to try to intercept a semaphore,
i.e. test if its state is free, and if so, load a new value into the semaphore, making its state busy. The test
and load are performed atomically, so that concurrent processes or threads which use the semaphore to
access a shared object will not conflict.
The CMPXCHG8B instruction compares the 64-bit values in the EDX:EAX registers with a 64-bit
memory location. If the values are equal, the zero flag (ZF) is set, and the ECX:EBX value is copied to
the memory location. Otherwise, the ZF flag is cleared, and the memory value is copied to EDX:EAX.
The CMPXCHG16B instruction compares the 128-bit value in the RDX:RAX and RCX:RBX
registers with a 128-bit memory location. If the values are equal, the zero flag (ZF) is set, and the
RCX:RBX value is copied to the memory location. Otherwise, the ZF flag is cleared, and the memory
value is copied to rDX:rAX.
The XADD instruction exchanges the values of its two operands, then it stores their sum in the first
(destination) operand.
A LOCK prefix can be used to make the CMPXCHG, CMPXCHG8B and XADD instructions atomic
if one of the operands is a memory location.
The XCHG instruction exchanges the values of its two operands. If one of the operands is in memory,
the processor’s bus-locking mechanism is engaged automatically during the exchange, whether or not
the LOCK prefix is used.
3.3.15 Processor Information
CPUID—Processor Identification
The CPUID instruction returns information about the processor implementation and its support for
instruction subsets and architectural features. Software operating at any privilege level can execute the
CPUID instruction to read this information. After the information is read, software can select
procedures that optimize performance for a particular hardware implementation.
Some processor implementations may not support the CPUID instruction. Support for the CPUID
instruction is determined by testing the RFLAGS.ID bit. If software can write this bit, then the CPUID
instruction is supported by the processor implementation. Otherwise, execution of CPUID results in an
invalid-opcode exception.