Why is gcc allowed to speculatively load from a struct?
Example Showing the gcc Optimization and User Code that May Fault The function 'foo' in the snippet below will load only one of the struct members A or B; well at least that is the intention of the unoptimized code. typedef struct { int A; int B; } Pair; int foo(const Pair *P, int c) { int x; if (c) x = P->A; else x = P->B; return c/102 + x; } Here is what gcc -O3 gives: mov eax, esi mov edx, -1600085855 test esi, esi mov ecx, DWORD PTR [rdi+4] <-- ***load P->B** cmovne ecx, DWORD PTR [rdi] <-- ***load P->A*** imul edx lea eax, [rdx+rsi] sar esi, 31 sar eax, 6 sub eax, esi add eax, ecx ret So