2
0
mirror of https://gitlab.com/libeigen/eigen.git synced 2025-01-12 14:25:16 +08:00

Avoid undefined behavior by union type punning in float_to_bfloat16_rtne

Use `numext::as_uint`, instead of union based type punning, to avoid undefined behavior.
See also C++ Core Guidelines: "Don't use a union for type punning"
https://github.com/isocpp/CppCoreGuidelines/blob/v0.8/CppCoreGuidelines.md#c183-dont-use-a-union-for-type-punning

`numext::as_uint` was suggested by David Tellenbach
This commit is contained in:
Niels Dekker 2020-07-14 19:55:20 +02:00
parent 56b3e3f3f8
commit b11f817bcf

View File

@ -326,19 +326,11 @@ EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC __bfloat16_raw raw_uint16_to_bfloat16(unsi
return h;
}
union float32_bits {
unsigned int u;
float f;
};
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC __bfloat16_raw float_to_bfloat16_rtne(float ff) {
#if (defined(EIGEN_HAS_CUDA_BF16) && defined(EIGEN_HAS_HIP_BF16))
// Nothing to do here
#else
unsigned int input;
float32_bits f;
f.f = ff;
input = f.u;
unsigned int input = numext::as_uint(ff);
__bfloat16_raw output;
if (Eigen::numext::isnan EIGEN_NOT_A_MACRO(ff)) {