"Bonus bonus chatter: The xor trick doesn’t work for Itanium because mathematical operations don’t reset the NaT bit. Fortunately, Itanium also has a dedicated zero register, so you don’t need this trick. You can just move zero into your desired destination."<p>Will remember for the next time I write asm for Itanium!
It should be noted that XOR is just (bitwise) subtraction modulo 2.<p>There are many kinds of SUB instructions in the x86-64 ISA, which do subtraction modulo 2^64, modulo 2^32, modulo 2^16 or modulo 2^8.<p>To produce a null result, any kind of subtraction can be used, and XOR is just a particular case of subtraction, it is not a different kind of operation.<p>Unlike for bigger moduli, when operations are done modulo 2 addition and subtraction are the same, so XOR can be used for either addition modulo 2 or subtraction modulo 2.
The obvious answer is that XOR is faster. To do a subtract, you have to propagate the carry bit from the least-significant bit to the most-significant bit. In XOR you don't have to do that because the output of every bit is independent of the other adjacent bits.<p>Probably, there are ALU pipeline designs where you don't pay an explicit penalty. But not all, and so XOR is faster.<p>Surely, someone as awesome as Raymond Chen knows that. The answer is so obvious and basic I must be missing something myself?
> The answer is so obvious<p>A tangent, but what is Obvious depends on what you know.<p>Often experts don't explain the things they think are Obvious, but those things are only Obvious to them, because they are the expert.<p>We should all kind, and explain also the Obvious things those who do not know.
His point is that in x86 there is no performance difference but everyone except his colleague/friend uses xor, while sub actually leaves cleaner flags behind. So he suspects its some kind of social convention selected at random and then propagated via spurious arguments in support (or that it “looks cooler” as a bit of a term of art).<p>It could also be as a result of most people working in assembly being aware of the properties of logic gates, so they carry the understanding that under the hood it might somehow be better.
That comment is not very useful without pointing to realworld CPUs where SUB is more expensive than XOR ;)<p>E.g. on Z80 and 6502 both have the same cycle count.
Cortex A8 vsub reads the second source register a cycle earlier than veor, so that can add one cycle latency<p>Not scalar, but still sub vs xor. Though you’d use vmov immediate for zeroing anyway.
Harvard Mark I? Not sure why people think programming started with Z80.
From TFA:<p>> It encodes to the same number of bytes, executes in the same number of cycles.
As TFA says, on x86 `sub eax, eax` encodes to the same number of bytes and executes in the same number of cycles.
On modern ones, x86 has quite a history and the idiom might carry on from an even older machine.<p>Edit: Looked at comments, seems like x86 and the major 8bit cpu's had the same speed, pondering in this might be a remnant from the 4-bit ALU times.
> seems like x86 and the major 8bit cpu's had the same speed, pondering in this might be a remnant from the 4-bit ALU times.<p>I think that era of CPUs used a single circuit capable of doing add, sub, xor etc. They'd have 8 of them and the signals propagate through them in a row. I think this page explains the situation on the 6502: <a href="https://c74project.com/card-b-alu-cu/" rel="nofollow">https://c74project.com/card-b-alu-cu/</a><p>And this one for the ARM 1: <a href="https://daveshacks.blogspot.com/2015/12/inside-alu-of-armv1-first-arm.html" rel="nofollow">https://daveshacks.blogspot.com/2015/12/inside-alu-of-armv1-...</a><p>But I'm a software engineer speculating about how hardware works. You might want to ask a hardware engineer instead.
I'm not actually aware of any CPUs that preform a XOR faster than a SUB. And more importantly, they have identical timings on the 8086, which is where this pattern comes from.
I had a similar reaction when learning 8086 assembly and finding the correct way to do `if x==y` was a CMP instruction which performed a subtraction and set only the flags. (The book had a section with all the branch instructions to use for a variety of comparison operators.) I think I spent a few minutes experimenting with XOR to see if I could fashion a compare-two-values-and-branch macro that avoided any subtraction.
The operation is slightly more complex yes, but has there ever been an x86 CPU where SUB or XOR takes more than a single CPU cycle?
It's like 0.5 cycles vs 0.9 cycles. So both are 1 cycle, considering synchronization.
I would be surprised if modern CPUs didn't decode "xor eax, eax" into a set of micro-ops that simply moves from an externally invisible dedicated 0 register. These days the x86 ISA is more of an API contract than an actual representation of what the hardware internals do.
From TFA:<p><pre><code> The predominance of these idioms as a way to zero out a register led Intel to add special xor r, r-detection and sub r, r-detection in the instruction decoding front-end and rename the destination to an internal zero register, bypassing the execution of the instruction entirely. You can imagine that the instruction, in some sense, “takes zero cycles to execute”.</code></pre>
Zero micro ops to be precise, that’s handled entirely at the register rename stage with no data movement.
XOR and SUB have had identical cycle counts and latencies since the 8088. That's because you can "look ahead" when doing carries in binary. It's just a matter of how much floorspace on the chip you want to use.<p><a href="https://en.wikipedia.org/wiki/Carry-lookahead_adder" rel="nofollow">https://en.wikipedia.org/wiki/Carry-lookahead_adder</a><p>The only minor difference between the two on x86, really, is SUB sets OF and CF according to the result while XOR always clears them.
The non-obvious bit is why there isn't an even faster and shorter "mov <register>,0" instructions - the processors started short-circuiting xor <register>,<register> much later.
Because he is explicitly talking about x86 - maybe you missed that.
It amazes me how entertaining Raymond's writing on most mundane aspects of computing often is.
Back when I was in university, one of the units touching Assembly[0] required students to use subtraction to zero out the register instead of using the move instruction (which also worked), as it used fewer cycles.<p>I looked it up afterwards and xor was also a valid instruction in that architecture to zero out a register, and used even fewer cycles than the subtraction method; but it was not listed in the subset of the assembly language instructions we were allowed to use for that unit. I suspect that it was deemed a bit off-topic, since you would need to explain what the mathematical XOR operation was (if you didn't already learn about it in other units), when the unit was about something else entirely- but everyone knows what subtraction is, and that subtracting a number by itself leads to zero.<p>[0] Not x86, I do not recall the exact architecture.
Relatedly, there's a steganographic opportunity to hide info in machine code by using "XOR rax,rax" for a "zero" and "SUB rax,rax" for a "one" in your executable. Shouldn't be too hard to add a compiler feature to allow you to specify the string you want encoded into its output.
It might be because XOR is rarely (in terms of static count, dynamically it surely appears a lot in some hot loops) used for anything else, so it is easier to spot and identify as "special" if you are writing manual assembly.
XOR appears a lot in any code touching encryption.<p>PS. What is static vs dynamic <i>count</i>?
And helps with SMT<p>Edit: this is apparently not the case, see @tliltocatl's comment down the thread
I ran into this rabbithole while writing an x86-64 asm rewriter.<p>xor was the default zeroing idiom.I onkly did sub reg,reg when I actually want its flags result. Otherwise the main rule is: do not touch either form unless flags liveness makes the rewrite obviously safe. Had about 40 such idioms for the passes.
The hw implementation of xor is simpler than sub, so it should consume slightly less energy. Wondering how much energy was saved in the whole world by using xor instead of sub.
I doubt any of that is measurable, since all ALU operations are usually implemented with the same logic (e.g. see <a href="https://www.righto.com/2013/09/the-z-80-has-4-bit-alu-heres-how-it.html" rel="nofollow">https://www.righto.com/2013/09/the-z-80-has-4-bit-alu-heres-...</a>)
I guess everything what was saved was burned by the first useless image created per AI
My favorite (admittedly not super useful) trick in this domain is that <i>sbb eax, eax</i> breaks the dependency on the previous value of <i>eax</i> (just like <i>xor</i> and <i>sub</i>) and only depends on the carry flag. arm64 is less obtuse and just gives you <i>csetm</i> (special case of <i>csinv</i>) for this purpose.
<p><pre><code> Once an instruction has an edge, even if only extremely slight, that’s enough to tip the scales and rally everyone to that side.
</code></pre>
And this, interestingly, is why life on earth uses left-handed amino acids and right-handed sugars .. and why left handed sugar is perfect for diet sodas.
You still need to explain why this case creates a positive feedback loop rather than a negative one. I mean left/right fuel intakes in cars and male/female ratios somehow tend to balance at 50/50.
Regarding gender ratios: <a href="https://en.wikipedia.org/wiki/Fisher's_principle" rel="nofollow">https://en.wikipedia.org/wiki/Fisher's_principle</a><p>There's exceptions, but they tend to be colonial animals in the broadest sense e.g. how clownfish males are famously able to become female but each group has one breeding male and one breeding female at any given time*, or bees where the males (drones) are functionally flying sperm and there's only one fertile female in any given colony; or some reptiles which have a temperature-dependent sex determination that may have been 50/50 before we started causing rapid climate change but in many cases isn't now: <a href="https://en.wikipedia.org/wiki/Temperature-dependent_sex_determination" rel="nofollow">https://en.wikipedia.org/wiki/Temperature-dependent_sex_dete...</a><p>* Wolves, despite being where nomenclature of "alpha" comes from, are not this. The researcher who coined the term realised they made a mistake and what he thought of as the "alpha" pair were simply the parents of the others in that specific situation: <a href="https://davemech.org/wolf-news-and-information/" rel="nofollow">https://davemech.org/wolf-news-and-information/</a>
products of an asymmetric reaction performed without enantiomeric control can selectively catalyse the formation of more products with the same handedness -- this is called autocatalysis. so the first full reaction might produce a left-handed product (by chance) but that left-handed product will then cause future products to be preferentially left-handed. see the [Soai reaction](<a href="https://en.wikipedia.org/wiki/Soai_reaction?wprov=sfla1" rel="nofollow">https://en.wikipedia.org/wiki/Soai_reaction?wprov=sfla1</a>) for an example of this.<p>as mentioned by others this is conjectural but it is a popular (if somewhat unfalsifiable) explanation for homochirality
Wrt amino acids and sugars I personally don't have to explain as a good many others have already.<p>eg: For one, Isaac Asimov in the 1970s wrote at length on this in his role as a non fiction science writer with a Chemistry Phd<p>> male/female ratios somehow tend to balance at 50/50.<p>This is different to the case of actual right handed dominance in humans and to L- Vs R- dominance in chirality ...<p>( Men and women aren't actual mirror images of each other ... )
This is a hypothesis about why the chirality of life on earth is what it is, but I don't think there's enough evidence to state that this (or any competing hypothesis) is definitely the correct explanation.
Well "definitely correct" has no real place in probabilistic arguments almost by ipso factum absurdum :-)<p>The chirality argument made is more akin to dynamic systems balance; yes, you can balance a pencil on its point .. but given a bit of random tilt one way or the other it's going to tend to keep going and end near flat on the table.
Back in the stone ages XOR ing was just 1 byte of opcode. Habbits stick. In effect XORing is no longer faster since a long time.
The XOR trick is implemented as a (malloc from register file) on modern processors, implemented in the decoder and it won't even issue a uOp to the execution pipelines.<p>Its basically free today. Of course, mov RAX, 0 is also free and does the same thing. But CPUs have limited decoder lengths per clock tick, so the more instructions you fit in a given size, the more parallel a modern CPU can potentially execute.<p>So.... definitely still use XOR trick today. But really, let the compiler handle it. Its pretty good at keeping track of these things in practice.<p>-----------<p>I'm not sure if "sub" is hard-coded to be recognized in the decoder as a zero'd out allocation from the register file. There's only certain instructions that have been guaranteed to do this by Intel/AMD.
Depending on what's stone-age for you, a SUB with a register was also only one byte, and was the same cost as XOR, at least in the Intel/Zilog lineage all the way back to the 70s ;)
Looking at some random 1989 Zenith 386SX bios written in assembly so purely programmer preferences:<p>8 'sub al, al', 14 'sub ah, ah', 3 'sub ax, ax'<p>26 'xor al, al', 43 'xor ah, ah', 3 'xor ax, ax'<p>edit: checked a 2010 bios and not a single 'sub x, x'
[dead]
If you’re not first, you’re last.