Am Samstag, dem 26.10.2024 um 18:55 +0200 schrieb Richard Biener via Gcc: > > > Am 26.10.2024 um 17:30 schrieb Iain Sandoe <i...@sandoe.co.uk>: > > > > Hi, > > > > The background here is that I made a trial implementation of P1494r4 - > > std::observable() - and want to produce testcases. > > > > —— so ….. > > > > I am looking for either examples where GCC produces time-travel > > optimisation (or alternately some evidence that these are not expected). > >
A conforming compiler can not do time-travel optimizations across function calls. For a function call the compiler must assume that it exits the program or uses a non-local return, so it can not assume that UB that comes later will happen. This then typically applies to I/O which is hidden behind function calls. Where compilers do not observe this, this causes bugs, e.g. this old bug which broke Postgresql: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=41239 Or this recent in MSVC which I found when investigating this question (now fixed): https://developercommunity.visualstudio.com/t/Invalid-optimization-in-CC/10337428?q=muecker C23 clarifies that time-travel is not allowed (it was never really supported by the wording in the C standard). One area where GCC is not conforming are volatile accesses: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=104800 Martin > > (In case someone is not familiar with the time-travel analogy) a simple > > example from P1494: > > > > void b(int &r, int *p) { > > if (!p) std::fprintf(stderr, "count: %d\n", ++r); > > if (!p) std::fprintf(stderr, "p is null\n"); > > *p += r; // p may be assumed non-null > > } > > > > Since dereferencing p is UB, the compiler may assume that p is non-null - > > and therefore elide the check(s) before (thus time-travel). > > > > In practice, (at least on the platform I am testing on) GCC trunk does not > > do this - it does reorder code to eliminate the second null test - but it > > still prints both sets of output. > > I think we at least do not optimistically propagate backwards - that is, the > conditional code may not exit or infinitely loop. Printf due to callbacks > might, so I suggest to rework to tell GCC the conditional code will still > make sure the dereference is reached.