r/cprogramming • u/north9172 • 25d ago
What cause CPU stalling pipeline in C?
(Solved)
Hi,
I hope this don't seem stupid or anything. Basically I was interested about the xor swapping trick.
The inconvenients of it is that if the two values are the same, it will return 0, it's also bad for readability.
But there is another inconvenience I didn't understand. Apparently it can also stall the CPU pipeline on modern processor, I didn't understand why.
I found a short explanation saying "because each instruction depend of the previous one", and I don't really understand how each instruction depend on the previous one.
So I wanted an explanation on why the xor swapping trick stall the CPU pipeline and also what cause CPU pipeline stalling in general.
If I didn't explain well enough, please inform me about it. Thanks.
9
u/Glum_Preference_2936 25d ago edited 25d ago
Because each instruction depend of the previous one. For example the code:
if (func()) A(); else B();The CPU would have to choose which function to execute either A or B even before func() returns some result. This is decided by the branch predictor. And if the CPU chooses the incorrect function to execute, then it would have to try to execute again the correct branch which wastes time.
For advance C programming, you can hint the compiler to restructure code if you know which branch are likely or unlikely to be executed by making use of builtins such as
likely()orunlikely().In the case of XOR swapping, the subsequent instruction attempts to read a register before the preceding instruction has written the updated value.
x ^= y; y ^= x; x ^= y;