monkeyelite 1 day ago

Show me some O2 optimizations that will act contrary to code I wrote - meaning they violate the “as if” rule.

2
Maxatar 1 day ago

Two points... the first is you want an optimization that violates the "as if" rule, sure... copy constructors are allowed to violate the "as if" rule, so here you go:

    https://godbolt.org/z/jzWWTW85j
Compile that without optimizations and you get one set of output, compile it with optimizations and you get another. There are actually an entire suite of exceptions to the "as-if" rule.

The second point is that the whole reason for having an "as if" rule in the first place is to give permission for the compiler to discard the literal interpretation of the source code and instead only consider semantics that are defined to be observable, which the language standard defines not you the developer.

There would be no need for an "as if" rule if the compiler strictly did exactly what it was told. Its very existence should be a clue that the compiler is allowed to reinterpret the source code in ways that do not reflect its literal interpretation.

William_BB 8 hours ago

The standard says that "Copy elision is <...> one of the two allowed forms of optimization, alongside allocation elision and extension,(since C++14) that can change observable side-effects"

I agree you have a valid point though. I'd be interested to know the committee's reasoning.

monkeyelite 13 hours ago

> if the compiler strictly did exactly what it was told.

What does this mean since I am not writing assembly and there is no specified correspondence between assembly and C++.

RUnconcerned 1 day ago

I dunno about what you wrote, but here is one that clearly violates what OP said!

https://godbolt.org/z/Y4Yjb7z9c

clang notices that in the second loop I'm multiplying by 0, and thus the result is just 0, so it just returns that. Critically, this is not "exactly and only what the programmer specifies", since I very much told it to do all those additions and multiplications and it decided to optimize them away.

monkeyelite 13 hours ago

What? But the result is the same!