|
|
|
|
|
by mikeash
4008 days ago
|
|
Let's say I write a function that looks like: int ComputeStuff(int value) {
if(value < 27) {
long and complex computation specialized for values under 27
return result
} else {
long and complex computation specialized for values 27 or more
return result
}
}
Then I call it from somewhere else like so: int x = ComputeStuff(12);
Let's say the compiler decides this is a good candidate for inlining. Since the programmer wrote code with the intention of it running, are you saying that the compiler should not take advantage of the fact that it knows the exact value being passed into the function in this case and can delete half the code knowing it will never run? |
|
Yes, in this case, you would get a warning, but it is illustrative of the kinds of things can cause optimizers to do very unexpected things to your code. And it is surprisingly easy to find the UB conditions.
It's worth reading through this three-part post called What Every C Programmer Should Know About Undefined Behavior[1] from the LLVM folks to see how UB can screw with you, including removing NULL checks, eliminating overflow checks, and making debugging incredibly difficult to follow. It also explains why they can't just generate errors while optimizing.
1. http://blog.llvm.org/2011/05/what-every-c-programmer-should-...