3 ms·
No, if you try this with the various optimization levels you can see that it's not a bug; without optimization it doesn't happen. Instead what seems plausible t
by dom0 9y ago
No, if you try this with the various optimization levels you can see that it's not a bug; without optimization it doesn't happen. Instead what seems plausible to me is that some optimization pass analyses the possible values for "Do", which is tractable, since it's static and can't be aliased. Because the value must be initialized before Do() the optimizer seems to unconditionally use the only possible initialization, even if it is unreachable.
With -O1 you can see that this part already happens. With optimization cranked further up it just inlines EraseAll, and EraseAll ceases to exist as a separate symbol. This is possible since Do is static and not aliased. Meanwhile NeverCalled continues to exist as a retq, since it is not static.
- titzer 9y agoSorry, you are right. I don't think compilers know that main() is really the entrypoint, since there is some code in the C runtime that runs before main. If compilers treated main like the program entrypoint, then my original comment would stand.
- tom_mellior 9y ago> I don't think compilers know that main() is really the entrypoint Yes they do. > since there is some code in the C runtime that runs before main So? From the point of view of the C standard, main is the entrypoint to the C code in the program the compiler is asked to compile. (Edited to add: This particular example program is in C++, but whatever.)
- tom_mellior 9y ago> it's not a bug It's not a bug in what? The compiler or the input program? [The answer is, the compiler is fine, the input program has undefined behavior.] > without optimization it doesn't happen That's fine. As the input program has undefined behavior, the compiler is free to compile it differently at different optimization levels.
- phkahler 9y agoI've seen plenty of people blame the optimizer for bugs in their code. This is especially common with people doing embedded stuff when they don't understand the "volatile" keyword. Just because it works without optimization doesn't mean your code is correct. Some of them will insist on not using the optimizer because it can introduce bugs. I take the opposite attitude - let's go with -o3 from day one because we'll eventually run out of CPU time and have to turn it on anyway. If that uncovers bugs in the code or compiler it's better to find them early.