From 929bc0e191d0927b1735b9a1ddc0e8b77e3a25ec Mon Sep 17 00:00:00 2001 From: Alexander Grund Date: Mon, 20 Sep 2021 10:37:50 +0200 Subject: [PATCH] Fix alias violation in BFloat16 reinterpret_cast between unrelated types is undefined behavior and leads to misoptimizations on some platforms. Use the safer (and faster) version via bit_cast (cherry picked from commit b5eaa4269503f77d0aa58d2f8ed9419e1ba7784d) --- Eigen/src/Core/arch/Default/BFloat16.h | 16 ++-------------- 1 file changed, 2 insertions(+), 14 deletions(-) diff --git a/Eigen/src/Core/arch/Default/BFloat16.h b/Eigen/src/Core/arch/Default/BFloat16.h index 1c28f4f95..f21d1a0a3 100644 --- a/Eigen/src/Core/arch/Default/BFloat16.h +++ b/Eigen/src/Core/arch/Default/BFloat16.h @@ -251,12 +251,7 @@ EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC __bfloat16_raw truncate_to_bfloat16(const output.value = std::signbit(v) ? 0xFFC0: 0x7FC0; return output; } - const uint16_t* p = reinterpret_cast(&v); -#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ - output.value = p[0]; -#else - output.value = p[1]; -#endif + output.value = static_cast(numext::bit_cast(v) >> 16); return output; } @@ -462,14 +457,7 @@ EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC __bfloat16_raw float_to_bfloat16_rtne(&result); -#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ - q[0] = h.value; -#else - q[1] = h.value; -#endif - return result; + return numext::bit_cast(static_cast(h.value) << 16); } // --- standard functions ---