Skip to content

Instantly share code, notes, and snippets.

@Maumagnaguagno
Last active November 10, 2016 05:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Maumagnaguagno/07dcd6153484ae822bf99bdda9bf95ac to your computer and use it in GitHub Desktop.
Save Maumagnaguagno/07dcd6153484ae822bf99bdda9bf95ac to your computer and use it in GitHub Desktop.
Optimizing C to know ranges

Unexpected output from x86-x64 GCC 7 -O3 only fully optimizes func3, proof that compilers still require good programmers.

func(int):
        mov     edx, edi
        imul    edx, edi
        imul    edx, edi
        imul    edx, edx
        mov     eax, edx
        imul    eax, edi
        ret
func2(int):
        cmp     edi, 1
        mov     eax, 1
        je      .L2
        mov     eax, edi
        imul    eax, edi
        imul    eax, edi
        imul    eax, eax
        imul    eax, edi
.L2:
        rep ret
func3(int):
        mov     eax, edi
        ret
func4(unsigned int):
        xor     eax, eax
        test    edi, edi
        setne   al
        ret
#define assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0)
int func(int x){
assume(x == 0 || x == 1);
return x*x*x*x*x*x*x;
}
int func2(int x){
if(x == 1)
return x*x*x*x*x*x*x;
else
return x*x*x*x*x*x*x;
}
int func3(int x){
assume(x == 0 || x == 1);
if(x == 1)
return x*x*x*x*x*x*x;
else
return x*x*x*x*x*x*x;
}
int func4(unsigned int x){
if(x == 0)
return x*x*x*x*x*x*x;
else if (x == 1)
return x*x*x*x*x*x*x;
__builtin_unreachable();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment