Search code examples
coptimizationpointerscompiler-construction

Compiler optimization about elimination of pointer operation on inline function in C?


If this function Func1 is inlined,

inline int Func1 (int* a)
{
    return *a + 1;
}

int main ()
{
    int v = GetIntFromUserInput(); // Unknown at compile-time.   
    return Func1(&v);
}

Can I expect a smart compiler to eliminate the pointer operations? (&a and *a) As I guess, the function will be transformed into something like this,

int main ()
{
    int v = GetIntFromUserInput(); // Unknown at compile-time.
    int* a = &v;
    return *a + 1;
}

and finally,

int main ()
{
    int v = GetIntFromUserInput(); // Unknown at compile-time.
    return v + 1;
}

Pointer operations look easily being eliminated. But I heard that pointer operation is something special and cannot be optimized.


Solution

  • It is reasonable that it might occur. For example, gcc -O3 does so:

    .globl main
            .type   main, @function
    main:
            pushl   %ebp
            movl    %esp, %ebp
            andl    $-16, %esp
            call    GetIntFromUserInput
            movl    %ebp, %esp
            popl    %ebp
            addl    $1, %eax
            ret
    

    Notice that it takes the return value from the function, adds one, and returns.

    Interestingly, it also compiled a Func1, probably since inline seems like it should have the meaning of static, but an external function (like GetIntFromUserInput) ought to be able to call it. If I add static (and leave inline), it does remove the function's code.