Skip to content

Commit 081c168

Browse files
swolchokpytorchmergebot
authored andcommitted
Remove UB type punning from c10/util/floating_point_utils.h (pytorch#140567)
Accessing the inactive member of a union is undefined behavior. Fortunately, we have c10::bit_cast. Differential Revision: [D65888680](https://our.internmc.facebook.com/intern/diff/D65888680/) Pull Request resolved: pytorch#140567 Approved by: https://github.com/Skylion007, https://github.com/malfet ghstack dependencies: pytorch#140564, pytorch#140565, pytorch#140566
1 parent f59ec98 commit 081c168

File tree

1 file changed

+5
-12
lines changed

1 file changed

+5
-12
lines changed

c10/util/floating_point_utils.h

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,32 @@
11
#pragma once
22

33
#include <c10/macros/Macros.h>
4+
#include <c10/util/bit_cast.h>
45
#include <cstdint>
56

67
namespace c10::detail {
78

89
C10_HOST_DEVICE inline float fp32_from_bits(uint32_t w) {
910
#if defined(__OPENCL_VERSION__)
1011
return as_float(w);
11-
#elif defined(__CUDA_ARCH__)
12+
#elif defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__)
1213
return __uint_as_float((unsigned int)w);
1314
#elif defined(__INTEL_COMPILER)
1415
return _castu32_f32(w);
1516
#else
16-
union {
17-
uint32_t as_bits;
18-
float as_value;
19-
} fp32 = {w};
20-
return fp32.as_value;
17+
return c10::bit_cast<float>(w);
2118
#endif
2219
}
2320

2421
C10_HOST_DEVICE inline uint32_t fp32_to_bits(float f) {
2522
#if defined(__OPENCL_VERSION__)
2623
return as_uint(f);
27-
#elif defined(__CUDA_ARCH__)
24+
#elif defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__)
2825
return (uint32_t)__float_as_uint(f);
2926
#elif defined(__INTEL_COMPILER)
3027
return _castf32_u32(f);
3128
#else
32-
union {
33-
float as_value;
34-
uint32_t as_bits;
35-
} fp32 = {f};
36-
return fp32.as_bits;
29+
return c10::bit_cast<uint32_t>(f);
3730
#endif
3831
}
3932

0 commit comments

Comments
 (0)