XOR swap algorithm



In computer programming, the exclusive or swap (sometimes shortened to XOR swap) is an algorithm that uses the exclusive or bitwise operation to swap the values of two variables without using the temporary variable which is normally required.

The algorithm is primarily a novelty and a way of demonstrating properties of the exclusive or operation. It is sometimes discussed as a program optimization, but there are almost no cases where swapping via exclusive or provides benefit over the standard, obvious technique.

The algorithm
Conventional swapping requires the use of a temporary storage variable. Using the XOR swap algorithm, however, no temporary storage is needed. The algorithm is as follows:

Since XOR is a commutative operation, either X XOR Y or Y XOR X can be used interchangeably in any of the foregoing three lines. Note that on some architectures the first operand of the XOR instruction specifies the target location at which the result of the operation is stored, preventing this interchangeability. The algorithm typically corresponds to three machine-code instructions, represented by corresponding pseudocode and assembly instructions in the three rows of the following table:

In the above System/370 assembly code sample, R1 and R2 are distinct registers, and each XR operation leaves its result in the register named in the first argument. Using x86 assembly, values X and Y are in registers eax and ebx (respectively), and xor places the result of the operation in the first register.

However, in the pseudocode or high-level language version or implementation, the algorithm fails if x and y use the same storage location, since the value stored in that location will be zeroed out by the first XOR instruction, and then remain zero; it will not be "swapped with itself". This is not the same as if x and y have the same values. The trouble only comes when x and y use the same storage location, in which case their values must already be equal. That is, if x and y use the same storage location, then the line: sets x to zero (because x = y so X XOR Y is zero) and sets y to zero (since it uses the same storage location), causing x and y to lose their original values.

Proof of correctness
The binary operation XOR over bit strings of length $$N$$ exhibits the following properties (where $$\oplus$$ denotes XOR):


 * L1. Commutativity: $$A \oplus B = B \oplus A$$
 * L2. Associativity: $$(A \oplus B) \oplus C = A \oplus (B \oplus C)$$
 * L3. Identity exists: there is a bit string, 0, (of length N) such that $$A \oplus 0 = A$$ for any $$A$$
 * L4. Each element is its own inverse: for each $$A$$, $$A \oplus A = 0$$.

Suppose that we have two distinct registers  and   as in the table below, with initial values A and B respectively. We perform the operations below in sequence, and reduce our results using the properties listed above.

Linear algebra interpretation
As XOR can be interpreted as binary addition and a pair of bits can be interpreted as a vector in a two-dimensional vector space over the field with two elements, the steps in the algorithm can be interpreted as multiplication by 2&times;2 matrices over the field with two elements. For simplicity, assume initially that x and y are each single bits, not bit vectors.

For example, the step: which also has the implicit: corresponds to the matrix $$\left(\begin{smallmatrix}1 & 1\\0 & 1\end{smallmatrix}\right)$$ as
 * $$\begin{pmatrix}1 & 1\\0 & 1\end{pmatrix} \begin{pmatrix}x\\y\end{pmatrix}

= \begin{pmatrix}x+y\\y\end{pmatrix}. $$ The sequence of operations is then expressed as:

\begin{pmatrix}1 & 1\\0 & 1\end{pmatrix} \begin{pmatrix}1 & 0\\1 & 1\end{pmatrix} \begin{pmatrix}1 & 1\\0 & 1\end{pmatrix} = \begin{pmatrix}0 & 1\\1 & 0\end{pmatrix} $$ (working with binary values, so $$1 + 1 = 0$$), which expresses the elementary matrix of switching two rows (or columns) in terms of the transvections (shears) of adding one element to the other.

To generalize to where X and Y are not single bits, but instead bit vectors of length n, these 2&times;2 matrices are replaced by 2n&times;2n block matrices such as $$\left(\begin{smallmatrix}I_n & I_n\\0 & I_n\end{smallmatrix}\right).$$

These matrices are operating on values, not on variables (with storage locations), hence this interpretation abstracts away from issues of storage location and the problem of both variables sharing the same storage location.

Code example
A C function that implements the XOR swap algorithm:

The code first checks if the addresses are distinct and uses a guard clause to exit the function early if they are equal. Without that check, if they were equal, the algorithm would fold to a triple  resulting in zero.

The XOR swap algorithm can also be defined with a macro:

Reasons for avoidance in practice
On modern CPU architectures, the XOR technique can be slower than using a temporary variable to do swapping. At least on recent x86 CPUs, both by AMD and Intel, moving between registers regularly incurs zero latency. (This is called MOV-elimination.) Even if there is not any architectural register available to use, the  instruction will be at least as fast as the three XORs taken together. Another reason is that modern CPUs strive to execute instructions in parallel via instruction pipelines. In the XOR technique, the inputs to each operation depend on the results of the previous operation, so they must be executed in strictly sequential order, negating any benefits of instruction-level parallelism.

Aliasing
The XOR swap is also complicated in practice by aliasing. If an attempt is made to XOR-swap the contents of some location with itself, the result is that the location is zeroed out and its value lost. Therefore, XOR swapping must not be used blindly in a high-level language if aliasing is possible. This issue does not apply if the technique is used in assembly to swap the contents of two registers.

Similar problems occur with call by name, as in Jensen's Device, where swapping  and   via a temporary variable yields incorrect results due to the arguments being related: swapping via   changes the value for   in the second statement, which then results in the incorrect   value for   in the third statement.

Variations
The underlying principle of the XOR swap algorithm can be applied to any operation meeting criteria L1 through L4 above. Replacing XOR by addition and subtraction gives various slightly different, but largely equivalent, formulations. For example:

Unlike the XOR swap, this variation requires that the underlying processor or programming language uses a method such as modular arithmetic or bignums to guarantee that the computation of  cannot cause an error due to integer overflow. Therefore, it is seen even more rarely in practice than the XOR swap.

However, the implementation of  above in the C programming language always works even in case of integer overflow, since, according to the C standard, addition and subtraction of unsigned integers follow the rules of modular arithmetic, i. e. are done in the cyclic group $$\mathbb Z/2^s\mathbb Z$$ where $$s$$ is the number of bits of. Indeed, the correctness of the algorithm follows from the fact that the formulas $$(x + y) - y = x$$ and $$(x + y) - ((x + y) - y) = y$$ hold in any abelian group. This generalizes the proof for the XOR swap algorithm: XOR is both the addition and subtraction in the abelian group $$(\mathbb Z/2\mathbb Z)^{s}$$ (which is the direct sum of s copies of $$\mathbb Z/2\mathbb Z$$).

This doesn't hold when dealing with the  type (the default for  ). Signed integer overflow is an undefined behavior in C and thus modular arithmetic is not guaranteed by the standard, which may lead to incorrect results.

The sequence of operations in  can be expressed via matrix multiplication as:

\begin{pmatrix}1 & -1\\0 & 1\end{pmatrix} \begin{pmatrix}1 & 0\\1 & -1\end{pmatrix} \begin{pmatrix}1 & 1\\0 & 1\end{pmatrix} = \begin{pmatrix}0 & 1\\1 & 0\end{pmatrix} $$

Application to register allocation
On architectures lacking a dedicated swap instruction, because it avoids the extra temporary register, the XOR swap algorithm is required for optimal register allocation. This is particularly important for compilers using static single assignment form for register allocation; these compilers occasionally produce programs that need to swap two registers when no registers are free. The XOR swap algorithm avoids the need to reserve an extra register or to spill any registers to main memory. The addition/subtraction variant can also be used for the same purpose.

This method of register allocation is particularly relevant to GPU shader compilers. On modern GPU architectures, spilling variables is expensive due to limited memory bandwidth and high memory latency, while limiting register usage can improve performance due to dynamic partitioning of the register file. The XOR swap algorithm is therefore required by some GPU compilers.