Consider this code, compiled with gcc and -Ofast:
int f1(const char *p) {
if (!p[0])
return 0;
f2(); //not inlined
if (p[0]) { //not optimized out
//do something
return 0;
} else {
//do something else
//not optimized out
return 1;
}
}
how can I get behavior where the second test and lower branch are optimized out (since p[0] is const and has already been tested)?
There is no reason for the compiler to assume that function f2 may not modify what p is pointing to. The fact that p is defined as const char *p only tells the compiler that p cannot be used to modify the data it points to, not that the data itself is constant.
If you know the array is indeed not modified by function f2(), you can modify the code to not read it again and see if gcc will optimize accordingly:
int f1(const char *p) {
char c = *p;
if (!c)
return 0;
f2(); //not inlined
if (c) { //should be always true
//do something
return 0;
} else {
//should be optimized out
//do something else
return 1;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With