Yes, this is usually called Dead Store Elimination (read = load and write = stored in compiler language).
In general, any useless operation can be optimized by the compiler if it can prove that you (the user) cannot notice it (within the limits set by the language).
To destroy the Dead Store, in particular, it is usually limited to:
- body of a single function (however inline is used here)
- no intermediate calls to opaque functions
Some examples:
struct Foo { int a; int b; }; void opaque(Foo& x); // opaque, aka unknown definition Foo foo() { Foo x{1, 2}; xa = 3; return x; // provably returns {3, 2} // thus equivalent to Foo foo() { return {3, 2}; } } Foo bar() { Foo x{1, 2}; opaque(x); // may use xa, so need to leave it at '1' for now xa = 3; return x; } Foo baz() { Foo x{1, 2}; opaque(x); xa = 1; // xa may have been changed, cannot be optimized return x; }
Note that regardless of whether you keep the same value or not, as long as the compiler can prove that the variable is not read between the two operations of the repository, it can safely eliminate the first.
Special case: according to the specification in C ++, loading / saving in volatile cannot be optimized. This is due to the fact that volatile was specified in order to allow interaction with the hardware, and thus, the compiler cannot know a priori whether the hardware will read or write the variable behind the program back.
Another special case: in order to optimize memory synchronization operations (fences, barriers, etc.) used in multi-threaded programs can also prevent such optimizations. This is because, as with volatile , synchronization means that another thread of execution can change the variable behind that thread.
Finally, like all optimizations, its effectiveness is largely dependent on knowledge of the context. If it is proven that opaque either does not read or does not write to xa , then some stores can be optimized (it can be proved if the compiler can verify the definition of opaque ), so in general it really depends on embedding and constant distribution.