-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathfloat16.h
More file actions
534 lines (488 loc) · 19.3 KB
/
Copy pathfloat16.h
File metadata and controls
534 lines (488 loc) · 19.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
// Copyright (c) 2015 Nuxi, https://nuxi.nl/
//
// SPDX-License-Identifier: BSD-2-Clause
#ifndef COMMON_FLOAT16_H
#define COMMON_FLOAT16_H
#include <common/overflow.h>
#include <assert.h>
#include <fenv.h>
#include <float.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
// Converter for base-16 floating point literals to native types.
//
// This structure and functions below can be used to convert base-16
// string representations of floating point numbers to the native
// floating point types of the system.
//
// The following example shows how the string "0x123.cafep0" can be
// converted to a float:
//
// struct f16enc f16;
// f16enc_init(&f16);
// f16enc_push_xdigit(&f16, 1); // '1'
// f16enc_push_xdigit(&f16, 2); // '2'
// f16enc_push_xdigit(&f16, 3); // '3'
// f16enc_push_xdigit(&f16, 12); // 'c'
// f16enc_push_xdigit(&f16, 10); // 'a'
// f16enc_push_xdigit(&f16, 15); // 'f'
// f16enc_push_xdigit(&f16, 14); // 'e'
// bool have_range_error;
// float f = f16enc_get_float(&f16, -16, FE_TONEAREST, &have_range_error);
//
// The encoder does not support the concept of a radix character, as it
// can simply be emulated by adjusting the exponent.
typedef uint64_t f16_part_t;
#define F16_PART_BITS 64
#define F16_NPARTS 2
// Creats a bitmask with the n'th bit set.
static inline f16_part_t f16_bit(unsigned int n) {
return (f16_part_t)1 << (F16_PART_BITS - 1) >> (n % F16_PART_BITS);
}
// Returns whether one of the 'amount' last bits of the significand is
// non-zero.
static inline bool f16_has_trailing_bits(const f16_part_t *parts,
unsigned int amount) {
// Test complete parts.
for (unsigned int i = F16_NPARTS - amount / F16_PART_BITS; i < F16_NPARTS;
++i)
if (parts[i] != 0)
return true;
// Test bits within a part.
return (parts[F16_NPARTS - amount / F16_PART_BITS - 1] &
(((f16_part_t)1 << (amount % F16_PART_BITS)) - 1)) != 0;
}
// Determines whether the significand is all zero.
static inline bool f16_is_zero(const f16_part_t *parts) {
for (unsigned int i = 0; i < F16_NPARTS; i++)
if (parts[i] != 0)
return false;
return true;
}
// Shifts a significand to the left.
static inline void f16_shift_left(f16_part_t *parts, unsigned int amount) {
assert(amount < F16_PART_BITS && "Shifting more than one part");
unsigned int i = 0;
for (;;) {
parts[i] <<= amount;
if (i == F16_NPARTS - 1)
return;
parts[i] |= parts[i + 1] >> (F16_PART_BITS - amount);
++i;
}
}
// Shifts a significand to the right, while preserving the final bits
// for rounding.
static inline void f16_shift_right(f16_part_t *parts, unsigned int amount) {
// Keep track of whether one of the bits we're going to discard is
// non-zero. If that's the case, we set the very last bit to 1, so
// that rounding works all right.
bool trailing_bits = f16_has_trailing_bits(parts, amount);
// Shift entire significand right by the specified number of bits.
unsigned int idx = amount / F16_PART_BITS;
unsigned int shift = amount % F16_PART_BITS;
unsigned int i = F16_NPARTS - 1;
for (;;) {
f16_part_t right = i >= idx ? parts[i - idx] : 0;
if (shift == 0) {
// Shift by an exact number of parts.
parts[i] = right;
} else {
// Shift by a number of bits that is not a multiple of the parts
// width. Merge successive parts together.
f16_part_t left = i >= idx + 1 ? parts[i - idx - 1] : 0;
left <<= 64 - shift;
right >>= shift;
parts[i] = left | right;
}
if (i-- == 0)
break;
}
// Set trailing bit to make rounding work.
if (trailing_bits)
parts[F16_NPARTS - 1] |= 0x1;
}
// Rounds a significand to the width of the resulting floating point
// type. The rounding mode is provided in the form of a <fenv.h> mode.
static inline void f16_apply_rounding(f16_part_t *parts, int *exponent,
int round, unsigned int mant_dig) {
// We should round the number upwards in two cases, namely when
// performing nearest neighbour rounding and the top bit of the
// truncated part of the significand is set, or when performing upward
// rounding and any of the bits in the truncated part is set.
if ((round == FE_TONEAREST &&
(parts[mant_dig / F16_PART_BITS] & (f16_bit(mant_dig))) != 0) ||
(round == FE_UPWARD &&
f16_has_trailing_bits(parts, F16_PART_BITS * F16_NPARTS - mant_dig))) {
// Increment the retained part of the significand by one.
unsigned int i = --mant_dig / F16_PART_BITS;
f16_part_t inc = f16_bit(mant_dig);
for (;;) {
if (!add_overflow(parts[i], inc, &parts[i]))
return;
if (i-- == 0) {
// Increment overflowed the significand. Increment the exponent.
parts[0] = f16_bit(0);
++*exponent;
return;
}
// Increment overflowed a part of the significand. Continue
// incrementing the parts that lead up to it.
inc = 1;
}
}
}
struct f16enc {
f16_part_t parts[F16_NPARTS]; // Parts of the significand.
unsigned int bits; // Total number of bits inserted.
};
// Initializes an encoder object.
static inline void f16enc_init(struct f16enc *f16) {
for (size_t i = 0; i < F16_NPARTS; ++i)
f16->parts[i] = 0;
f16->bits = 0;
}
// Pushes a hexadecimal digit into the encoder state.
static inline void f16enc_push_xdigit(struct f16enc *f16, uint8_t xdigit) {
assert(xdigit < 16 && "Digit out of bounds");
if (f16->bits == 0) {
// First digit. Discard leading zeroes.
if (xdigit == 0)
return;
// Shift character until the top bit is set. This ensures that the
// resulting floating point value is normalized.
f16->parts[0] |= (f16_part_t)xdigit << (F16_PART_BITS - 4);
while ((f16->parts[0] & f16_bit(0)) == 0) {
f16->parts[0] <<= 1;
--f16->bits;
}
} else if (f16->bits >= F16_PART_BITS * F16_NPARTS - 4) {
// We're pushing more digits than we can store internally. If we try
// to parse a very long number like 0x1.000.....0001 and have to
// round up, we must not discard any input.
f16->parts[F16_NPARTS - 1] |= xdigit;
} else {
// Digit somewhere in the middle. Store the bits in the right place.
unsigned int idx = f16->bits / F16_PART_BITS;
unsigned int shift = f16->bits % F16_PART_BITS;
f16->parts[idx] |= (f16_part_t)xdigit << (F16_PART_BITS - 4) >> shift;
// Digit is stored at the very end of the part. Let bits that don't
// fit trickle into the next part.
if (shift > F16_PART_BITS - 4)
f16->parts[idx + 1] = (f16_part_t)xdigit
<< (F16_PART_BITS * 2 - 4 - shift);
}
f16->bits += 4;
}
// Common code for f16enc_get_bin*().
#define F16ENC_GET_BIN(exp_dig, mant_dig, has_subnorm) \
f16_part_t parts[F16_NPARTS]; \
do { \
for (size_t i = 0; i < F16_NPARTS; ++i) \
parts[i] = f16->parts[i]; \
if (parts[0] == 0) { \
/* Floating point value zero. */ \
assert(f16->bits == 0 && "Invalid bit count"); \
*have_range_error = false; \
return 0.0; \
} \
assert((parts[0] & f16_bit(0)) != 0 && \
"Floating point value not normalized"); \
\
/* Add correction for input length and bias to the exponent. */ \
exponent += f16->bits + (1 << (exp_dig - 1)) - 2; \
static const int max_exp = (1 << exp_dig) - 2; \
if (exponent > max_exp) { \
/* Overflow. */ \
*have_range_error = true; \
return INFINITY; \
} else if (exponent <= 0) { \
if (has_subnorm && exponent > 1 - mant_dig) { \
/* Number is in subnormal range. */ \
f16_shift_right(parts, 1 - exponent); \
exponent = 1; \
} else { \
/* Smaller than subnormal. */ \
*have_range_error = true; \
return 0.0; \
} \
} \
\
/* Apply rounding. This may cause an overflow once more. */ \
f16_apply_rounding(parts, &exponent, round, mant_dig); \
if (exponent > max_exp) { \
/* Overflow. */ \
*have_range_error = true; \
return INFINITY; \
} \
\
/* Quirk: subnormals use an exponent of zero instead of 1. */ \
if (has_subnorm && exponent == 1 && (parts[0] & f16_bit(0)) == 0) \
exponent = 0; \
\
/* Going to return a valid floating point value. */ \
*have_range_error = false; \
} while (0)
// IEEE 754-2008 "binary32": Single-precision floating-point.
#define F16_BIN32_MANT_DIG 24
#if FLT_MANT_DIG == F16_BIN32_MANT_DIG
typedef float f16_bin32_t;
#define F16_BIN32_HAS_SUBNORM FLT_HAS_SUBNORM
#elif DBL_MANT_DIG == F16_BIN32_MANT_DIG
typedef double f16_bin32_t;
#define F16_BIN32_HAS_SUBNORM DBL_HAS_SUBNORM
#elif LDBL_MANT_DIG == F16_BIN32_MANT_DIG
typedef long double f16_bin32_t;
#define F16_BIN32_HAS_SUBNORM LDBL_HAS_SUBNORM
#else
#define F16_NO_BIN32
#endif
#ifndef F16_NO_BIN32
static inline f16_bin32_t f16enc_get_bin32(const struct f16enc *f16,
int exponent, int round,
bool *have_range_error) {
F16ENC_GET_BIN(8, F16_BIN32_MANT_DIG, F16_BIN32_HAS_SUBNORM);
// Convert significand and exponent to native floating point type.
union {
uint32_t i;
f16_bin32_t f;
} result = {.i = (uint32_t)exponent << (F16_BIN32_MANT_DIG - 1) |
parts[0] << 1 >> (1 + F16_PART_BITS - F16_BIN32_MANT_DIG)};
static_assert(sizeof(result.i) == sizeof(result.f), "Size mismatch");
return result.f;
}
#endif
// IEEE 754-2008 "binary64": Double-precision floating-point.
#define F16_BIN64_MANT_DIG 53
#if FLT_MANT_DIG == F16_BIN64_MANT_DIG
typedef float f16_bin64_t;
#define F16_BIN64_HAS_SUBNORM FLT_HAS_SUBNORM
#elif DBL_MANT_DIG == F16_BIN64_MANT_DIG
typedef double f16_bin64_t;
#define F16_BIN64_HAS_SUBNORM DBL_HAS_SUBNORM
#elif LDBL_MANT_DIG == F16_BIN64_MANT_DIG
typedef long double f16_bin64_t;
#define F16_BIN64_HAS_SUBNORM LDBL_HAS_SUBNORM
#else
#define F16_NO_BIN64
#endif
#ifndef F16_NO_BIN64
static inline f16_bin64_t f16enc_get_bin64(const struct f16enc *f16,
int exponent, int round,
bool *have_range_error) {
F16ENC_GET_BIN(11, F16_BIN64_MANT_DIG, F16_BIN64_HAS_SUBNORM);
// Convert significand and exponent to native floating point type.
union {
uint64_t i;
f16_bin64_t f;
} result = {.i = (uint64_t)exponent << (F16_BIN64_MANT_DIG - 1) |
parts[0] << 1 >> (1 + F16_PART_BITS - F16_BIN64_MANT_DIG)};
static_assert(sizeof(result.i) == sizeof(result.f), "Size mismatch");
return result.f;
}
#endif
// x86 80-bit Extended Precision Format.
#define F16_BIN80_MANT_DIG 64
#if FLT_MANT_DIG == F16_BIN80_MANT_DIG
typedef float f16_bin80_t;
#define F16_BIN80_HAS_SUBNORM FLT_HAS_SUBNORM
#elif DBL_MANT_DIG == F16_BIN80_MANT_DIG
typedef double f16_bin80_t;
#define F16_BIN80_HAS_SUBNORM DBL_HAS_SUBNORM
#elif LDBL_MANT_DIG == F16_BIN80_MANT_DIG
typedef long double f16_bin80_t;
#define F16_BIN80_HAS_SUBNORM LDBL_HAS_SUBNORM
#else
#define F16_NO_BIN80
#endif
#ifndef F16_NO_BIN80
static inline f16_bin80_t f16enc_get_bin80(const struct f16enc *f16,
int exponent, int round,
bool *have_range_error) {
F16ENC_GET_BIN(15, F16_BIN80_MANT_DIG, F16_BIN80_HAS_SUBNORM);
// Convert significand and exponent to native floating point type.
union {
struct {
uint64_t significand;
#ifdef __i386__
uint32_t exponent;
#else
uint64_t exponent;
#endif
} i;
f16_bin80_t f;
} result = {.i = {.significand = parts[0], .exponent = exponent}};
static_assert(sizeof(result.i) == sizeof(result.f), "Size mismatch");
return result.f;
}
#endif
// IEEE 754-2008 "binary128": Quadruple-precision floating-point.
#define F16_BIN128_MANT_DIG 113
#if FLT_MANT_DIG == F16_BIN128_MANT_DIG
typedef float f16_bin128_t;
#define F16_BIN128_HAS_SUBNORM FLT_HAS_SUBNORM
#elif DBL_MANT_DIG == F16_BIN128_MANT_DIG
typedef double f16_bin128_t;
#define F16_BIN128_HAS_SUBNORM DBL_HAS_SUBNORM
#elif LDBL_MANT_DIG == F16_BIN128_MANT_DIG
typedef long double f16_bin128_t;
#define F16_BIN128_HAS_SUBNORM LDBL_HAS_SUBNORM
#else
#define F16_NO_BIN128
#endif
#ifndef F16_NO_BIN128
static inline f16_bin128_t f16enc_get_bin128(const struct f16enc *f16,
int exponent, int round,
bool *have_range_error) {
F16ENC_GET_BIN(15, F16_BIN128_MANT_DIG, F16_BIN128_HAS_SUBNORM);
// Convert significand and exponent to native floating point type.
union {
uint64_t i[2];
f16_bin128_t f;
} result = {.i = {
parts[0] << 49 | parts[1] >> 15,
(uint64_t)exponent << 48 | (parts[0] & ~f16_bit(0)) >> 15,
}};
static_assert(sizeof(result.i) == sizeof(result.f), "Size mismatch");
return result.f;
}
#endif
static inline float f16enc_get_float(const struct f16enc *f16, int exponent,
int round, bool *have_range_error) {
#if FLT_MANT_DIG == F16_BIN32_MANT_DIG
return f16enc_get_bin32(f16, exponent, round, have_range_error);
#elif FLT_MANT_DIG == F16_BIN64_MANT_DIG
return f16enc_get_bin64(f16, exponent, round, have_range_error);
#elif FLT_MANT_DIG == F16_BIN80_MANT_DIG
return f16enc_get_bin80(f16, exponent, round, have_range_error);
#elif FLT_MANT_DIG == F16_BIN128_MANT_DIG
return f16enc_get_bin128(f16, exponent, round, have_range_error);
#else
#error "Unsupported format"
#endif
}
static inline double f16enc_get_double(const struct f16enc *f16, int exponent,
int round, bool *have_range_error) {
#if DBL_MANT_DIG == F16_BIN32_MANT_DIG
return f16enc_get_bin32(f16, exponent, round, have_range_error);
#elif DBL_MANT_DIG == F16_BIN64_MANT_DIG
return f16enc_get_bin64(f16, exponent, round, have_range_error);
#elif DBL_MANT_DIG == F16_BIN80_MANT_DIG
return f16enc_get_bin80(f16, exponent, round, have_range_error);
#elif DBL_MANT_DIG == F16_BIN128_MANT_DIG
return f16enc_get_bin128(f16, exponent, round, have_range_error);
#else
#error "Unsupported format"
#endif
}
static inline long double f16enc_get_long_double(const struct f16enc *f16,
int exponent, int round,
bool *have_range_error) {
#if LDBL_MANT_DIG == F16_BIN32_MANT_DIG
return f16enc_get_bin32(f16, exponent, round, have_range_error);
#elif LDBL_MANT_DIG == F16_BIN64_MANT_DIG
return f16enc_get_bin64(f16, exponent, round, have_range_error);
#elif LDBL_MANT_DIG == F16_BIN80_MANT_DIG
return f16enc_get_bin80(f16, exponent, round, have_range_error);
#elif LDBL_MANT_DIG == F16_BIN128_MANT_DIG
return f16enc_get_bin128(f16, exponent, round, have_range_error);
#else
#error "Unsupported format"
#endif
}
// Converter for floating point native types to base-16 literals.
//
// This function can convert a normal or subnormal floating point value
// to a sequence of hexadecimal digits and extract its exponent. This
// can be used to implement printf()'s "%a".
//
// The following piece of code converts the floating point value 1.51 to
// a hexadecimal representation with a precision of two digits, rounding
// the number upward to 0x1.83p0:
//
// unsigned char digits[2];
// size_t ndigits = 2;
// int exponent;
// f16dec(1.51, digits, &ndigits, &exponent, FE_UPWARD);
//
// The digits array will now hold the numbers 8 and 3.
static inline void f16dec(long double f, unsigned char *digits, size_t *ndigits,
int *exponent, int round) {
// Invert the rounding mode if the value is negative, so that the code
// below does not need to take the sign bit into account.
if (signbit(f)) {
if (round == FE_UPWARD)
round = FE_DOWNWARD;
else if (round == FE_DOWNWARD)
round = FE_UPWARD;
}
#if LDBL_MANT_DIG == 53
// Extract the significand and the exponent from the floating point value.
union {
long double f;
uint64_t i;
} value = {.f = f};
static_assert(sizeof(value.f) == sizeof(value.i), "Size mismatch");
f16_part_t parts[F16_NPARTS] = {value.i << 11};
*exponent = (value.i >> 52) & 0x7ff;
#elif LDBL_MANT_DIG == 64
union {
long double f;
struct {
uint64_t significand;
#ifdef __i386__
uint32_t exponent;
#else
uint64_t exponent;
#endif
} i;
} value = {.f = f};
static_assert(sizeof(value.f) == sizeof(value.i), "Size mismatch");
f16_part_t parts[F16_NPARTS] = {value.i.significand};
*exponent = value.i.exponent & 0x7fff;
#elif LDBL_MANT_DIG == 113
union {
long double f;
uint64_t i[2];
} value = {.f = f};
static_assert(sizeof(value.f) == sizeof(value.i), "Size mismatch");
f16_part_t parts[F16_NPARTS] = {
value.i[1] << 15 | value.i[0] >> 49,
value.i[0] << 15,
};
*exponent = (value.i[1] >> 48) & 0x7fff;
#else
#error "Unsupported format"
#endif
if (*exponent == 0) {
// Subnormal floating point value. Normalize it.
assert(!f16_is_zero(parts) && "Floating point has value zero");
*exponent = LDBL_MIN_EXP - 1;
while ((parts[0] & f16_bit(0)) == 0) {
f16_shift_left(parts, 1);
--*exponent;
}
} else {
// Normal floating point value.
parts[0] |= f16_bit(0);
*exponent += LDBL_MIN_EXP - 2;
}
// Apply rounding if the number of digits requested is less than the
// size of the significand.
size_t nbits = *ndigits * 4 + 1;
if (nbits < F16_PART_BITS * F16_NPARTS)
f16_apply_rounding(parts, exponent, round, nbits);
// Convert bits after the radix to hexadecimal digits.
f16_shift_left(parts, 1);
for (size_t i = 0; i < *ndigits; ++i) {
if (f16_is_zero(parts)) {
*ndigits = i;
break;
}
digits[i] = parts[0] >> (F16_PART_BITS - 4);
f16_shift_left(parts, 4);
}
}
#endif