Debian Codegraph @

src/asahi/isa/agx_minifloat.h

raw
1 /*
2 * Copyright 2021 Alyssa Rosenzweig
3 * SPDX-License-Identifier: MIT
4 */
5
6 #pragma once
7
8 #include <math.h>
9 #include <stdbool.h>
10 #include <string.h>
11 #include "util/macros.h"
12
13 /* AGX includes an 8-bit floating-point format for small dyadic immediates,
14 * consisting of 3 bits for the exponent, 4 bits for the mantissa, and 1-bit
15 * for sign, in the usual order. Zero exponent has special handling. */
16
17 static inline float
18 agx_minifloat_decode(uint8_t imm)
19 {
20 float sign = (imm & 0x80) ? -1.0 : 1.0;
21 signed exp = (imm & 0x70) >> 4;
22 unsigned mantissa = (imm & 0xF);
23
24 if (exp)
25 return ldexpf(sign * (float)(mantissa | 0x10), exp - 7);
26 else
27 return ldexpf(sign * ((float)mantissa), -6);
28 }
29
30 /* Encodes a float. Results are only valid if the float can be represented
31 * exactly, if not the result of this function is UNDEFINED. However, it is
32 * guaranteed that this function will not crash on out-of-spec inputs, so it is
33 * safe to call on any input. signbit() is used to ensure -0.0 is handled
34 * correctly.
35 */
36 static inline uint8_t
37 agx_minifloat_encode(float f)
38 {
39 unsigned sign = signbit(f) ? 0x80 : 0;
40 f = fabsf(f);
41
42 /* frac is in [0.5, 1) and f = frac * 2^exp */
43 int exp = 0;
44 float frac = frexpf(f, &exp);
45
46 if (f >= 0.25) {
47 unsigned mantissa = (frac * 32.0);
48 exp -= 5; /* 2^5 = 32 */
49 exp = CLAMP(exp + 7, 0, 7);
50
51 return sign | (exp << 4) | (mantissa & 0xF);
52 } else {
53 unsigned mantissa = (f * 64.0f);
54
55 return sign | mantissa;
56 }
57 }
58
59 static inline bool
60 agx_minifloat_exact(float f)
61 {
62 float f_ = agx_minifloat_decode(agx_minifloat_encode(f));
63 return memcmp(&f, &f_, sizeof(float)) == 0;
64 }