Search code examples
gccdead-codelto

Does GCC LTO perform cross-file dead code elimination?


Say I have a function

void do_something() {
    //....
    #ifdef FEATURE_X
        feature_x();
    #endif
    //....
}

I can compile and run this with no problems; if I want the feature I can pass -D FEATURE_X and it works.

However, what if I would like to put do_something into another file (And not have to recompile that file as well each time I decide to change the option). If it was in the same file, I assume that

const int FEATURE_X=0;

void do_something() {
    //....
    if(FEATURE_X) {
        feature_x();
    }
    //....
}

will use dead code elimination properly, eliminating the call. If I put this in another file, without LTO,

extern const int FEATURE_X;

void do_something() {
    //....
    if(FEATURE_X) {
        feature_x();
    }
    //....
}

It will not remove the code (It has no way of knowing). So, with link time optimization enabled, can the compiler detect the value of FEATURE_X at link time, determine if the code is used or not, and remove it if appropriate?


Solution

  • GCC does cross module unreachable function removal, but it will not be able to determine the code is dead in your last testcase, because the constant value of FEATURE_X will be determined too late.

    If you will use -D way or put your const int FEATURE_X=0; into every module then yes, the code will be eliminated.