Skip to content

Commit 8006a6a

Browse files
committed
[libc] Implement basic 'fenv.h' utilities on the AMD GPU
Summary: This patch implements a basic floating point environment on the AMDGPU. Users should be able to check rounding modes or certain floating point exceptions using the standard functions. This patch implements the basic set, but only exposes the `fegetround` and `fesetround` utilities. This ps because getting the exceptions to work is difficult due to the behavior with the DX10_CLAMP bit that is always set. It is worth noting that this utility is not strictly standards conformant because we can only control this behavior on individual warps. Whether or not we can say it's truly implemented then is an exercise to the reader.
1 parent 23f3651 commit 8006a6a

File tree

6 files changed

+335
-18
lines changed

6 files changed

+335
-18
lines changed

libc/config/gpu/api.td

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def StdlibAPI : PublicAPI<"stdlib.h"> {
5454
}
5555

5656
def FenvAPI: PublicAPI<"fenv.h"> {
57-
let Types = ["fenv_t"];
57+
let Types = ["fenv_t", "fexcept_t"];
5858
}
5959

6060
def StdIOAPI : PublicAPI<"stdio.h"> {

libc/config/gpu/entrypoints.txt

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,19 @@ set(TARGET_LIBC_ENTRYPOINTS
183183
libc.src.gpu.rpc_host_call
184184
)
185185

186+
if(LIBC_TARGET_ARCHITECTURE_IS_AMDGPU)
187+
set(extra_entrypoints
188+
# fenv.h entrypoints
189+
libc.src.fenv.fegetenv
190+
libc.src.fenv.fegetround
191+
libc.src.fenv.fesetenv
192+
libc.src.fenv.fesetround
193+
)
194+
endif()
195+
186196
set(TARGET_LIBM_ENTRYPOINTS
197+
${extra_entrypoints}
198+
187199
# math.h entrypoints
188200
libc.src.math.acos
189201
libc.src.math.acosf

libc/include/llvm-libc-macros/math-macros.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@
3232
#define math_errhandling 0
3333
#elif defined(__NO_MATH_ERRNO__)
3434
#define math_errhandling (MATH_ERREXCEPT)
35+
#elif defined(__AMDGPU__)
36+
#define math_errhandling (MATH_ERREXCEPT)
3537
#elif defined(__NVPTX__) || defined(__AMDGPU__)
3638
#define math_errhandling (MATH_ERRNO)
3739
#else

libc/src/__support/FPUtil/FEnvImpl.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@
3333
#include "arm/FEnvImpl.h"
3434
#elif defined(LIBC_TARGET_ARCH_IS_ANY_RISCV)
3535
#include "riscv/FEnvImpl.h"
36+
#elif defined(LIBC_TARGET_ARCH_IS_AMDGPU)
37+
#include "amdgpu/FEnvImpl.h"
3638
#else
3739

3840
namespace LIBC_NAMESPACE::fputil {
Lines changed: 301 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,301 @@
1+
//===-- amdgpu floating point env manipulation functions --------*- C++ -*-===//
2+
//
3+
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4+
// See https://llvm.org/LICENSE.txt for license information.
5+
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6+
//
7+
//===----------------------------------------------------------------------===//
8+
9+
#ifndef LLVM_LIBC_SRC___SUPPORT_FPUTIL_AMDGPU_FENVIMPL_H
10+
#define LLVM_LIBC_SRC___SUPPORT_FPUTIL_AMDGPU_FENVIMPL_H
11+
12+
#include "src/__support/GPU/utils.h"
13+
#include "src/__support/macros/attributes.h"
14+
#include "src/__support/macros/properties/architectures.h"
15+
16+
#if !defined(LIBC_TARGET_ARCH_IS_AMDGPU)
17+
#error "Invalid include"
18+
#endif
19+
20+
#include <fenv.h>
21+
#include <stdint.h>
22+
23+
namespace LIBC_NAMESPACE {
24+
namespace fputil {
25+
26+
namespace internal {
27+
28+
// Gets the immediate argument to access the AMDGPU hardware register. The
29+
// register access is encoded in a 16-bit immediate value according to the
30+
// following layout.
31+
//
32+
// ┌──────────────┬──────────────┬───────────────┐
33+
// │ SIZE[15:11] │ OFFSET[10:6] │ ID[5:0] │
34+
// └──────────────┴──────────────┴───────────────┘
35+
//
36+
// This will read the size number of bits starting at the offset bit from the
37+
// corresponding hardware register ID.
38+
constexpr uint16_t get_register(uint8_t id, uint8_t offset, uint8_t size) {
39+
return static_cast<uint16_t>(size << 11 | offset << 6 | id);
40+
}
41+
42+
// Integral identifiers for the relevant hardware registers.
43+
enum Register : uint16_t {
44+
// The mode register controls the floating point behaviour of the device. It
45+
// can be read or written to by the kernel during runtime It is laid out as a
46+
// bit field with the following offsets and sizes listed for the relevant
47+
// entries.
48+
//
49+
// ┌─────┬─────────────┬─────┬─────────┬──────────┬─────────────┬────────────┐
50+
// │ ... │ EXCP[20:12] │ ... │ IEEE[9] │ CLAMP[8] │ DENOMR[7:4] │ ROUND[3:0] │
51+
// └─────┴─────────────┴─────┴─────────┴──────────┴─────────────┴────────────┘
52+
//
53+
// The rounding mode and denormal modes both control f64/f16 and f32 precision
54+
// operations separately with two bits. The accepted values for the rounding
55+
// mode are nearest, upward, downward, and toward given 0, 1, 2, and 3
56+
// respectively.
57+
//
58+
// The CLAMP bit indicates that DirectX 10 handling of NaNs is enabled in the
59+
// vector ALU. When set this will clamp NaN values to zero and pass them
60+
// otherwise. A hardware bug causes this bit to prevent floating exceptions
61+
// from being recorded if this bit is set on all generations before GFX12.
62+
//
63+
// The IEEE bit controls whether or not floating point operations supporting
64+
// exception gathering are IEEE 754-2008 compliant.
65+
//
66+
// The EXCP field indicates which exceptions will cause the instruction to
67+
// take a trap if traps are enabled, see the status register. The bit layout
68+
// is identical to that in the trap status register. We are only concerned
69+
// with the first six bits and ignore the other three.
70+
HW_REG_MODE = 1,
71+
HW_REG_MODE_ROUND = get_register(HW_REG_MODE, 0, 4),
72+
HW_REG_MODE_CLAMP = get_register(HW_REG_MODE, 8, 1),
73+
HW_REG_MODE_EXCP = get_register(HW_REG_MODE, 12, 6),
74+
75+
// The status register is a read-only register that contains information about
76+
// how the kernel was launched. The sixth bit TRAP_EN[6] indicates whether or
77+
// not traps are enabled for this kernel. If this bit is set along with the
78+
// corresponding bit in the mode register then a trap will be taken.
79+
HW_REG_STATUS = 2,
80+
HW_REG_STATUS_TRAP_EN = get_register(HW_REG_STATUS, 6, 1),
81+
82+
// The trap status register contains information about the status of the
83+
// exceptions. These bits are accumulated regarless of trap handling statuss
84+
// and are sticky until cleared.
85+
//
86+
// 5 4 3 2 1 0
87+
// ┌─────────┬───────────┬──────────┬────────────────┬──────────┬─────────┐
88+
// │ Inexact │ Underflow │ Overflow │ Divide by zero │ Denormal │ Invalid │
89+
// └─────────┴───────────┴──────────┴────────────────┴──────────┴─────────┘
90+
//
91+
// These exceptions indicate that at least one lane in the current wavefront
92+
// signalled an floating point exception. There is no way to increase the
93+
// granularity.
94+
HW_REG_TRAPSTS = 3,
95+
HW_REG_TRAPSTS_EXCP = get_register(HW_REG_TRAPSTS, 0, 6),
96+
};
97+
98+
// The six bits used to encode the standard floating point exceptions in the
99+
// trap status register.
100+
enum ExceptionFlags : uint32_t {
101+
EXCP_INVALID_F = 0x1,
102+
EXCP_DENORMAL_F = 0x2,
103+
EXCP_DIV_BY_ZERO_F = 0x4,
104+
EXCP_OVERFLOW_F = 0x8,
105+
EXCP_UNDERFLOW_F = 0x10,
106+
EXCP_INEXACT_F = 0x20,
107+
};
108+
109+
// The two bit encoded rounding modes used in the mode register.
110+
enum RoundingFlags : uint32_t {
111+
ROUND_TO_NEAREST = 0x0,
112+
ROUND_UPWARD = 0x1,
113+
ROUND_DOWNWARD = 0x2,
114+
ROUND_TOWARD_ZERO = 0x3,
115+
};
116+
117+
// Exception flags are individual bits in the corresponding hardware register.
118+
// This converts between the exported C standard values and the hardware values.
119+
LIBC_INLINE uint32_t get_status_value_for_except(uint32_t excepts) {
120+
return (excepts & FE_INVALID ? EXCP_INVALID_F : 0) |
121+
#ifdef __FE_DENORM
122+
(excepts & __FE_DENORM ? EXCP_DENORMAL_F : 0) |
123+
#endif // __FE_DENORM
124+
(excepts & FE_DIVBYZERO ? EXCP_DIV_BY_ZERO_F : 0) |
125+
(excepts & FE_OVERFLOW ? EXCP_OVERFLOW_F : 0) |
126+
(excepts & FE_UNDERFLOW ? EXCP_UNDERFLOW_F : 0) |
127+
(excepts & FE_INEXACT ? EXCP_INEXACT_F : 0);
128+
}
129+
130+
LIBC_INLINE uint32_t get_except_value_for_status(uint32_t status) {
131+
return (status & EXCP_INVALID_F ? FE_INVALID : 0) |
132+
#ifdef __FE_DENORM
133+
(status & EXCP_DENORMAL_F ? __FE_DENORM : 0) |
134+
#endif // __FE_DENORM
135+
(status & EXCP_DIV_BY_ZERO_F ? FE_DIVBYZERO : 0) |
136+
(status & EXCP_OVERFLOW_F ? FE_OVERFLOW : 0) |
137+
(status & EXCP_UNDERFLOW_F ? FE_UNDERFLOW : 0) |
138+
(status & EXCP_INEXACT_F ? FE_INEXACT : 0);
139+
}
140+
141+
// FIXME: These require the 'noinline' attribute to pessimistically flush the
142+
// state. Otherwise, reading from the register may return stale results.
143+
144+
// Access the six bits in the trap status register for the floating point
145+
// exceptions.
146+
[[gnu::noinline]] LIBC_INLINE void set_trap_status(uint32_t status) {
147+
uint32_t val = gpu::broadcast_value(gpu::get_lane_mask(), status);
148+
__builtin_amdgcn_s_setreg(HW_REG_TRAPSTS_EXCP, val);
149+
}
150+
151+
[[gnu::noinline]] LIBC_INLINE uint32_t get_trap_status() {
152+
return __builtin_amdgcn_s_getreg(HW_REG_TRAPSTS_EXCP);
153+
}
154+
155+
// Access the six bits in the mode register that control which exceptions will
156+
// result in a trap being taken. Uses the same flags as the status register.
157+
[[gnu::noinline]] LIBC_INLINE void set_enabled_trap(uint32_t flags) {
158+
uint32_t val = gpu::broadcast_value(gpu::get_lane_mask(), flags);
159+
__builtin_amdgcn_s_setreg(HW_REG_MODE_EXCP, val);
160+
}
161+
162+
[[gnu::noinline]] LIBC_INLINE uint32_t get_enabled_trap() {
163+
return __builtin_amdgcn_s_getreg(HW_REG_MODE_EXCP);
164+
}
165+
166+
// Access the four bits in the mode register's ROUND[3:0] field. The hardware
167+
// supports setting the f64/f16 and f32 precision rounding modes separately but
168+
// we will assume that these always match.
169+
[[gnu::noinline]] LIBC_INLINE void set_rounding_mode(uint32_t flags) {
170+
uint32_t val = gpu::broadcast_value(gpu::get_lane_mask(), flags);
171+
__builtin_amdgcn_s_setreg(HW_REG_MODE_ROUND, val << 2 | val);
172+
}
173+
174+
[[gnu::noinline]] LIBC_INLINE uint32_t get_rounding_mode() {
175+
return __builtin_amdgcn_s_getreg(HW_REG_MODE_ROUND) & 0x3;
176+
}
177+
178+
// NOTE: On architectures before GFX12 the DX10_CLAMP bit supresses all floating
179+
// point exceptions. In order to get them to be presented we need to
180+
// manually set if off.
181+
[[gnu::noinline]] LIBC_INLINE void set_clamp_low() {
182+
__builtin_amdgcn_s_setreg(HW_REG_MODE_CLAMP, 0);
183+
}
184+
185+
[[gnu::noinline]] LIBC_INLINE void set_clamp_high() {
186+
__builtin_amdgcn_s_setreg(HW_REG_MODE_CLAMP, 1);
187+
}
188+
189+
} // namespace internal
190+
191+
LIBC_INLINE int clear_except(int excepts) {
192+
uint32_t status = internal::get_status_value_for_except(excepts);
193+
uint32_t invert = ~status & 0x3f;
194+
uint32_t active = internal::get_trap_status();
195+
internal::set_trap_status(active & invert);
196+
return 0;
197+
}
198+
199+
LIBC_INLINE int test_except(int excepts) {
200+
uint32_t status = internal::get_status_value_for_except(excepts);
201+
uint32_t active = internal::get_trap_status();
202+
return internal::get_except_value_for_status(active) & status;
203+
}
204+
205+
LIBC_INLINE int get_except() { return internal::get_trap_status(); }
206+
207+
LIBC_INLINE int set_except(int excepts) {
208+
internal::set_trap_status(internal::get_status_value_for_except(excepts));
209+
return 0;
210+
}
211+
212+
LIBC_INLINE int enable_except(int excepts) {
213+
uint32_t status = internal::get_status_value_for_except(excepts);
214+
uint32_t active = internal::get_trap_status();
215+
internal::set_enabled_trap(status);
216+
return internal::get_except_value_for_status(active);
217+
}
218+
219+
LIBC_INLINE int disable_except(int excepts) {
220+
uint32_t status = internal::get_status_value_for_except(excepts);
221+
uint32_t invert = ~status & 0x3f;
222+
uint32_t active = internal::get_enabled_trap();
223+
internal::set_enabled_trap(active & invert);
224+
return active;
225+
}
226+
227+
LIBC_INLINE int raise_except(int excepts) {
228+
uint32_t status = internal::get_status_value_for_except(excepts);
229+
enable_except(status);
230+
internal::set_trap_status(status);
231+
return 0;
232+
}
233+
234+
LIBC_INLINE int get_round() {
235+
switch (internal::get_rounding_mode()) {
236+
case internal::ROUND_TO_NEAREST:
237+
return FE_TONEAREST;
238+
case internal::ROUND_UPWARD:
239+
return FE_UPWARD;
240+
case internal::ROUND_DOWNWARD:
241+
return FE_DOWNWARD;
242+
case internal::ROUND_TOWARD_ZERO:
243+
return FE_TOWARDZERO;
244+
}
245+
__builtin_unreachable();
246+
}
247+
248+
LIBC_INLINE int set_round(int rounding_mode) {
249+
switch (rounding_mode) {
250+
case FE_TONEAREST:
251+
internal::set_rounding_mode(internal::ROUND_TO_NEAREST);
252+
break;
253+
case FE_UPWARD:
254+
internal::set_rounding_mode(internal::ROUND_UPWARD);
255+
break;
256+
case FE_DOWNWARD:
257+
internal::set_rounding_mode(internal::ROUND_DOWNWARD);
258+
break;
259+
case FE_TOWARDZERO:
260+
internal::set_rounding_mode(internal::ROUND_TOWARD_ZERO);
261+
break;
262+
default:
263+
return 1;
264+
}
265+
return 0;
266+
}
267+
268+
// The fenv_t struct for the AMD GPU is simply a 32-bit integer field of the
269+
// current state. We combine the four bits for the rounding mode with the six
270+
// bits for the exception state and the six bits for the enabled exceptions.
271+
//
272+
// ┌────────────────────────────┬─────────────────┬─────────────┬─────────────┐
273+
// │ UNUSED[31:16] │ ENABLED[15:10] │ STATUS[9:4] │ ROUND[3:0] │
274+
// └────────────────────────────┴─────────────────┴─────────────┴─────────────┘
275+
//
276+
// The top sixteen bits are currently unused and should be zero.
277+
LIBC_INLINE int get_env(fenv_t *env) {
278+
if (!env)
279+
return 1;
280+
281+
uint32_t rounding = internal::get_rounding_mode();
282+
uint32_t status = internal::get_trap_status();
283+
uint32_t enabled = internal::get_enabled_trap();
284+
env->__fpc = enabled << 10 | status << 4 | rounding;
285+
return 0;
286+
}
287+
288+
LIBC_INLINE int set_env(const fenv_t *env) {
289+
if (!env)
290+
return 1;
291+
292+
internal::set_rounding_mode(env->__fpc & 0xf);
293+
internal::set_trap_status((env->__fpc >> 4) & 0x3f);
294+
internal::set_enabled_trap((env->__fpc >> 10) & 0x3f);
295+
return 0;
296+
}
297+
298+
} // namespace fputil
299+
} // namespace LIBC_NAMESPACE
300+
301+
#endif // LLVM_LIBC_SRC___SUPPORT_FPUTIL_AMDGPU_FENVIMPL_H

0 commit comments

Comments
 (0)