C# as of 7.0 makes this possible:
(a, b) = (b, a); (a, b) = (b, a);I'm a total .NET noob, but this attempt in Compiler Explorer shows it not using the xor trick.
https://godbolt.org/z/jhzqxEKzT
Maybe I need some extra compiler flags or something.
If the compiler had decided to put two locals located already in registers, and had the swap in a branch, like so:
if (foo()) {
bar();
(a, b) = (b, a);
}
Then the registers might get swapped with an xchg instruction or something, I don’t know. The compiler’s goal is to have pipelined execution be as fast as possible, so there’s no way it’s going to use bit-mangling operations that would get in the way of that.It better not. The CLR trick introduces a data dependency that slows down the code on modern CPUs.
Compilers sometimes also can compile this down to zero instructions. Nothing says the variable-to-register mapping has to be constant in a single function.