Hint the C compiler (GCC or Clang) of possible variable value/range

Viewed 750

In the following code, only one comparison will be done, because the compiler knows the conditions are exclusive and we will always enter the second condition as bar will be necessary > 32:

int foo(int bar) {
    if (bar <= 64)
        return 1;
    if (bar > 32) {
        printf("Too many elements");
    }
    return 0;
}

Now, imagine I know bar is always higher than 64. Because of the input of the system, configuration, or else. How can I hint the compiler to do no comparison at all, like if the if (bar <= 64) return was compiled, except it actually isn't kept in the final ASM.

Something like:

int foo(int bar) {
    @precond(bar > 64);
    if (bar > 32) {
        printf("Too many elements");
    }
    return 0;
}

Is my only solution to write eg a LLVM pass?

1 Answers

You can use __builtin_unreachable in GCC:

if (bar > 32) {
  __builtin_unreachable();
}

__builtin_assume in Clang:

__builtin_assume(bar <= 32);

and __assume in MSVC:

__assume(bar <= 32);
Related