cgcccompiler-optimization

The gcc compiler can recognize the function semantics of free and make optimizations. Why and how does it do it?


In the following code, apb and apb->amp are both pointers, pointing to a malloc address. The phenomenon is that apb->amp=NULL will be optimized and will not be executed, but when I remove free(apb), the assignment to apb->amp will not be optimized.

if (apb) {
    if (apb->amp) {
        free(apb->amp);
        apb->amp = NULL;
    }
    free(apb);
}

I checked the optimization options of gcc and found through experiments that it was caused by the optimization option "-ftree-dse":

-ftree-dse
Perform dead store elimination (DSE) on trees. A dead store is a store into a memory location that is later overwritten by another store without any intervening loads. In this case the earlier store can be deleted. This flag is enabled by default at -O1 and higher.

I know that there is a problem with the logic of this code. After apb is released, the address pointed to by apb can no longer be used. The problem is (I am very curious about this): how does the compiler know the semantics of the free function and optimize it for this kind of situation? Can the compiler also recognize the semantics of other functions and optimize them?


Solution

  • how does the compiler know the semantics of the free function and optimize it for this kind of situation? Can the compiler also recognize the semantics of other functions and optimize them?

    The free function has specified semantics in the C standard. The compiler can simply use this to make assumptions about the semantics of this specific function, either by special handling this specific function hard-coded in the compiler or by using some compiler builtin or attribute that is attached to the declaration of free in the C library to indicate its specific behavior.

    Compilers use the specification of functions in the C standard library for special handling of optimizations in other cases as well, whatever cases the compiler developers thought were worth it to implement special handling for.