Re:Nine ways to break your systems code using volatile
by jstimpfle on Friday October 06, 2023 @08:46AM
(#37790044)
I'm almost out of my depth here, but I believe this isn't (only) about escape analysis. A function call (like pthread_mutex_lock(), or any other) is running on the same thread.
I can see how failure to prove that a variable hasn't escaped a certain scope must prevent compiler reordering when a function of unknown implementation is called -- but not how that failure should require emitting memory barrier instructions.
However I realize that setjmp()/longjmp() isn't about threading either. What those functions do is quite weird.
Re:Nine ways to break your systems code using volatile
by gpderetta on Friday October 06, 2023 @08:57AM
(#37790178)
The compiler won't emit memory barriers for pthread_mutex_lock. It only need to make sure that all globally observable (i.e whose address has escaped)values are flushed from registers into memory. In practice this means that opaque function calls act as compiler memory barriers. Any additional required hardware memory barrier instruction is inside the implementation of pthread_mutex_lock itself.
Re:Nine ways to break your systems code using volatile
by jstimpfle on Friday October 06, 2023 @12:16PM
(#37792720)
Yes. I can see how setjmp()/longjmp() would need additional/special treatment by escape analysis. Now I'm only wondering why the problem would be limited to (syntactically) automatic local variables. If the control flow (returns twice etc) is surprising to the compiler, couldn't that affect optimizations to non-local variables too?
longjump is special: it can return twice and the effect is observable even for non-escaping variables: so values that must be preserved across function calls need to be forced to memory by declaring them volatile.
GCC specifically marks longjmp as returns_twice, which as far as I can tell prevents the surrounding function from being inlinable and additionally treats all local variables as volatile at the point of the longjmp call (forcing them to memory even if not escaping), but that's a GCC extension.