Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ variable alias - what's that exactly, and why is it better to turn if off?

I've read the essay Surviving the Release Version.

Under the "Aliasing bugs" clause it says:

You can get tighter code if you tell the compiler that it can assume no aliasing....

I've also read Aliasing (computing).

What exactly is a variable alias? I understand it means using a pointer to a variable is an alias, but, how/why does it affect badly, or in other words - why telling the compiler that it can assume no aliasing would get me a "tighter code"

like image 936
Poni Avatar asked May 31 '10 18:05

Poni


2 Answers

Aliasing is when you have two different references to the same underlying memory. Consider this made up example:

int doit(int *n1, int *n2)
{
    int x = 0;

    if (*n1 == 1)
    {
        *n2 = 0;

        x += *n1  // line of interest
    }

    return x;
}

int main()
{
    int x = 1;

    doit(&x, &x);   // aliasing happening
}

If the compiler has to allow for aliasing, it needs to consider the possibility that n1 == n2. Therefore, when it needs to use the value of *n1 at "line of interest", it needs to allow for the possibility it was changed by the line *n2 = 0.

If the compiler can assume no aliasing, it can assume at "line of interest" that *n1 == 1 (because otherwise we would not be inside the if). The optimizer can then use this information to optimize the code (in this case, change "line of interest" from following the pointer and doing a general purpose addition to using a simple increment).

like image 142
R Samuel Klatchko Avatar answered Nov 16 '22 04:11

R Samuel Klatchko


Disallowing aliasing means if you have a pointer char* b, you can assume that b is the only pointer in the program that points to that particular memory location, which means the only time that memory location is going to change is when the programmer uses b to change it. The generated assembly thus doesn't need to reload the memory pointed to by b into a register as long as the compiler knows nothing has used b to modify it. If aliasing is allowed it's possible there's another pointer char* c = b; that was used elsewhere to mess with that memory

like image 33
Michael Mrozek Avatar answered Nov 16 '22 04:11

Michael Mrozek