cgccoptimizationgcc6

Is it possible to force GCC to output the exact bitwise instructions I give it without inline assembly?


I've written code which looks like this:

char* xor_and_print(byte arr[], size_t buffSize, byte key)
{
    size_t i;

    for(i = 0; i < buffSize; i++)
    {
        printf("%c", (arr[i] & ~key) | (key & ~arr[i]));
    }
    putchar('\n');
}

This is an xor operation blown up into more instructions. I am using gcc-6.3.0. Even when I compile with -O0 flag, gcc turns this into one single xor instruction in the disassembly. Is it possible to coerce it into writing those specific asm instructions with a flag or must I use inline assembly language?


Solution

  • Using volatile should avoid this optimization:

    for(i = 0; i < buffSize; i++)
    {
        byte volatile b = arr[i];
        printf("%c", (b & ~key) | (key & ~b));
    }
    

    But it will stay unoptimized for higher optimization levels too.