by glitchc · 1w ago · 0 comments
call __printf_chk@PLT mov ecx, DWORD PTR 0[rbp] mov rdx, rbp mov edi, 2 mov DWORD PTR -96[rbx], 7
C and C++ happen to have a particularly restrictive view on what “the semantics” of a program really are, such that there are a lot of things you can write in syntactically-legal C that officially erase the semantic meaning of the code. Within that definition of the program’s semantics, gcc’s optimizer is not supposed to change them, and any such change would be a bug. You’re taking a more expansive view of program semantics than the actual language specifies. If you do that, then any optimizing compiler is going to consider it to be acceptable to violate your special bespoke definition of them.
For this particular example the line should be clear. If the variable is volatile, memory access can't be removed or reordered. If it's not volatile, everything is fair game.
Mandatory Godbolt link: https://godbolt.org/z/fjKs4hbjo
Or strange issues with optimizing infinite loops and the Halting problem preventing a full automated solution.
The C compilers like GCC just hide stuff away and break things silently.
If you open the possibility of other notions of “the semantics” besides what the language spec lays out, then changing those semantics is an inherent part of an optimizer.
What people (IMO fairly reasonably) want is a different C language spec with less undefined behavior and compilers that follow that spec. But people don’t think about it clearly and skip major parts of that picture when complaining about it.
If that's true, you have a bad language.
What is known to be the case with C, but this is not a desirable nor a necessary state of affairs. A language can and should have defined semantics.
I’m talking about the question of what should be covered by the official semantics. That’s inherently subjective and a matter of opinion.
Gcc’s optimizer does not accept changing language-level semantics based on which optimizations are performed. That the above comment thinks it does means that the commenter has a different notion of what should count as “the semantics” from what the language spec says. Which is a perfectly legitimate opinion, but if you take that position then you have to accept that other people will have other ideas of what should count, and therefore any optimizer might change “the semantics” of code according to at least some of those ideas.