by pizza234 · 3y ago · 0 comments
Torvalds was famously critical of it (https://yarchive.net/comp/linux/cmov.html); part of the criticism is now moot though, due to low latencies on modern processors (it seems 1 cycle or less, although the instruction consumes internal flags).
His idea seems to be still applicable and consistent with Intel's recommendation: make branches predictable, and only after, use CMOV for the remaining ones. His fundametnal assumption is that "even if you were to know that something is unpredictable, it's going to be very rare.".
I can only assume the compiler is marking all the bounds checks as unlikely to fail, and correctly predicted branches must be more or less free in modern CPUs. It’s the only way I can explain it.
It is a common low level optimization to add a wide boundary check in the beginning to avoid successive smaller bounds checks.
You can see this pretty easily in compiler explorer. This is a simple array lookup compiled in release mode:
[0] https://clang.llvm.org/docs/LanguageExtensions.html#builtin-...
Thanks!
I've always felt uncomfortable about PGO for more complex programs because of this.