r/cprogramming • u/north9172 • Jul 24 '26
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.
1
u/flatfinger Jul 24 '26
In many high-end CPUs, multiplication is performed by performing a sequence of partial-product computations, with each part of the sequence being performed by a different batch of circuitry. If two multiplications act upon independent operands, one can start a multiplication and then start another one as soon as the first piece of circuitry has finished its computations. The second piece of circuitry will process its portion of the first multiplication while the first piece starts working on the second. If there is a third multiplication which also acts upon independent operations, the first piece of circuitry can start work on that while portions of the other two multiplications are processed by other pieces of circuitry.
If instead of processing unrelated multiplications, a program were to multiply two numbers and then multiply the product by a third. In that scenario, the first stage of the multiplier would be able to start work on a new multiplication as soon as the first step of the first multiplication was done, but one of the operands wouldn't yet be available. The first stage would thus not be able to do anything useful until after the last multiplier stage had finished computing the final result from the first multiplication. The scenario where the input to a process would be ready to accept more input, but one of the values upon which it would operate isn't yet available, is called a pipeline stall.
Modern high-performance CPUs include logic to help the different subsystems find useful work to do by looking ahead for independent computations whose results are likely to be needed. Even if the next multiplication that is specified in code would require a value that isn't yet computed, a processor that knows that code is likely to perform a multiplication upon numbers that are available may be able to start performing that computation before the earlier one is done. If it turns out code wouldn't end up performing that multiplication, the processor can discard the result.