GCC (and Clang also), provide this __builtin_expect
for human-assisted branch prediction, as explained here. Informally, people explain its semantics in the following way: "compiler just processes the indicated branch unconditionally, and if the condition should turn out to be different than indicated, an expensive roll-back takes place".
But if I have a piece of code as the following:
if (__builtin_expect(p != 0, 1)) // line 1
p->access_object(); // line 2
If I treated the informal explanation above literally, the compiler can just execute line 2 without waiting for the computation of the condition in line 1, and therefore cause an undefined behavior (null pointer dereference), should the pointer happen to be null.
My question is, if I use __builtin_expect
do I still get the guarantee, that my defensive checks work? And if so, do I get any run-time benefit if I use __builtin_expect
in defensive checks as the above one?
(Note: my goal for using __builtin_expect
like this is to get the maximum performance for the cases where p
is non-null, at the expense of slowing down (even by orders of magnitude) the cases where p
is null; Even if the latter case appears quite often.)