RFR: JDK-8300080: offset_of for GCC/Clang exhibits undefined behavior and is not always a compile-time constant
Justin King
jcking at openjdk.org
Fri Jan 13 14:40:15 UTC 2023
On Thu, 12 Jan 2023 20:28:50 GMT, Justin King <jcking at openjdk.org> wrote:
> The implementation of `offset_of` for GCC/Clang only deals with types are aligned to 16 bytes or less, if they are more, such as `zCollectedHeap` the behavior is undefined. UBSan also suggests that `offset_of` is not always a compile time constant, as the stack trace came from the dynamic loader during library loading. This patch changes `offset_of` to use `offsetof` and disables the warning `invalid-offsetof` for the JVM.
I read JDK-8239357 and related information. I am not sure I understand why `offsetof` is being avoided given that C++17 shifted the behavior to be `conditionally-supported`. `conditionally-supported` is a nice way of saying it's up to the compiler on whether it gives meaningful answers or fails to compile. All compilers I am aware of give meaningful answers. Were going to have to agree to disagree on the rationale of not using `offsetof`, but it appears Clang/GCC optimize it nicely at least in isolation.
Looking at godbolt, the current definition of `offset_of` produces some horrific assembly without optimizations. Thankfully with `-O2` it boils down to a constant. I am guessing UBSan prevents the optimization so it can instrument it, or rather it instruments it making it unable to optimize it. Perhaps we should apply `ALWAYSINLINE` to the lambda to get better results regardless of build mode and use `alignas` now due to `std::aligned_storage_t` being deprecated in C++23?
-------------
PR: https://git.openjdk.org/jdk/pull/11978
More information about the hotspot-dev
mailing list