Coverage Report

Created: 2025-08-29 07:31

/src/shaderc/third_party/glslang/SPIRV/hex_float.h
Line
Count
Source (jump to first uncovered line)
1
// Copyright (c) 2015-2016 The Khronos Group Inc.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
#ifndef LIBSPIRV_UTIL_HEX_FLOAT_H_
16
#define LIBSPIRV_UTIL_HEX_FLOAT_H_
17
18
#include <cassert>
19
#include <cctype>
20
#include <cmath>
21
#include <cstdint>
22
#include <iomanip>
23
#include <limits>
24
#include <sstream>
25
26
#include "bitutils.h"
27
28
namespace spvutils {
29
30
class Float16 {
31
 public:
32
0
  Float16(uint16_t v) : val(v) {}
33
955
  Float16() {}
34
0
  static bool isNan(const Float16& val) {
35
0
    return ((val.val & 0x7C00) == 0x7C00) && ((val.val & 0x3FF) != 0);
36
0
  }
37
  // Returns true if the given value is any kind of infinity.
38
0
  static bool isInfinity(const Float16& val) {
39
0
    return ((val.val & 0x7C00) == 0x7C00) && ((val.val & 0x3FF) == 0);
40
0
  }
41
0
  Float16(const Float16& other) { val = other.val; }
42
955
  uint16_t get_value() const { return val; }
43
44
  // Returns the maximum normal value.
45
0
  static Float16 max() { return Float16(0x7bff); }
46
  // Returns the lowest normal value.
47
0
  static Float16 lowest() { return Float16(0xfbff); }
48
49
 private:
50
  uint16_t val;
51
};
52
53
class FloatE5M2 {
54
 public:
55
0
  FloatE5M2(uint8_t v) : val(v) {}
56
0
  FloatE5M2() {}
57
0
  static bool isNan(const FloatE5M2& val) {
58
0
    return ((val.val & 0x7C) == 0x7C) && ((val.val & 0x3) != 0);
59
0
  }
60
  // Returns true if the given value is any kind of infinity.
61
0
  static bool isInfinity(const FloatE5M2& val) {
62
0
    return ((val.val & 0x7C) == 0x7C) && ((val.val & 0x3) == 0);
63
0
  }
64
0
  FloatE5M2(const FloatE5M2& other) { val = other.val; }
65
0
  uint8_t get_value() const { return val; }
66
67
  // Returns the maximum normal value.
68
0
  static FloatE5M2 max() { return FloatE5M2(0x7B); }
69
  // Returns the lowest normal value.
70
0
  static FloatE5M2 lowest() { return FloatE5M2(0xFB); }
71
72
 private:
73
  uint8_t val;
74
};
75
76
class FloatE4M3 {
77
 public:
78
0
  FloatE4M3(uint8_t v) : val(v) {}
79
0
  FloatE4M3() {}
80
0
  static bool isNan(const FloatE4M3& val) {
81
0
    return (val.val & 0x7F) == 0x7F;
82
0
  }
83
  // Returns true if the given value is any kind of infinity.
84
0
  static bool isInfinity(const FloatE4M3&) {
85
0
    return false;
86
0
  }
87
0
  FloatE4M3(const FloatE4M3& other) { val = other.val; }
88
0
  uint8_t get_value() const { return val; }
89
90
  // Returns the maximum normal value.
91
0
  static FloatE4M3 max() { return FloatE4M3(0x7E); }
92
  // Returns the lowest normal value.
93
0
  static FloatE4M3 lowest() { return FloatE4M3(0xFE); }
94
95
 private:
96
  uint8_t val;
97
};
98
99
// To specialize this type, you must override uint_type to define
100
// an unsigned integer that can fit your floating point type.
101
// You must also add a isNan function that returns true if
102
// a value is Nan.
103
template <typename T>
104
struct FloatProxyTraits {
105
  typedef void uint_type;
106
};
107
108
template <>
109
struct FloatProxyTraits<float> {
110
  typedef uint32_t uint_type;
111
0
  static bool isNan(float f) { return std::isnan(f); }
112
  // Returns true if the given value is any kind of infinity.
113
0
  static bool isInfinity(float f) { return std::isinf(f); }
114
  // Returns the maximum normal value.
115
0
  static float max() { return std::numeric_limits<float>::max(); }
116
  // Returns the lowest normal value.
117
0
  static float lowest() { return std::numeric_limits<float>::lowest(); }
118
};
119
120
template <>
121
struct FloatProxyTraits<double> {
122
  typedef uint64_t uint_type;
123
0
  static bool isNan(double f) { return std::isnan(f); }
124
  // Returns true if the given value is any kind of infinity.
125
0
  static bool isInfinity(double f) { return std::isinf(f); }
126
  // Returns the maximum normal value.
127
0
  static double max() { return std::numeric_limits<double>::max(); }
128
  // Returns the lowest normal value.
129
0
  static double lowest() { return std::numeric_limits<double>::lowest(); }
130
};
131
132
template <>
133
struct FloatProxyTraits<Float16> {
134
  typedef uint16_t uint_type;
135
0
  static bool isNan(Float16 f) { return Float16::isNan(f); }
136
  // Returns true if the given value is any kind of infinity.
137
0
  static bool isInfinity(Float16 f) { return Float16::isInfinity(f); }
138
  // Returns the maximum normal value.
139
0
  static Float16 max() { return Float16::max(); }
140
  // Returns the lowest normal value.
141
0
  static Float16 lowest() { return Float16::lowest(); }
142
};
143
144
template <>
145
struct FloatProxyTraits<FloatE5M2> {
146
  typedef uint8_t uint_type;
147
0
  static bool isNan(FloatE5M2 f) { return FloatE5M2::isNan(f); }
148
  // Returns true if the given value is any kind of infinity.
149
0
  static bool isInfinity(FloatE5M2 f) { return FloatE5M2::isInfinity(f); }
150
  // Returns the maximum normal value.
151
0
  static FloatE5M2 max() { return FloatE5M2::max(); }
152
  // Returns the lowest normal value.
153
0
  static FloatE5M2 lowest() { return FloatE5M2::lowest(); }
154
};
155
156
template <>
157
struct FloatProxyTraits<FloatE4M3> {
158
  typedef uint8_t uint_type;
159
0
  static bool isNan(FloatE4M3 f) { return FloatE4M3::isNan(f); }
160
  // Returns true if the given value is any kind of infinity.
161
0
  static bool isInfinity(FloatE4M3 f) { return FloatE4M3::isInfinity(f); }
162
  // Returns the maximum normal value.
163
0
  static FloatE4M3 max() { return FloatE4M3::max(); }
164
  // Returns the lowest normal value.
165
0
  static FloatE4M3 lowest() { return FloatE4M3::lowest(); }
166
};
167
168
// Since copying a floating point number (especially if it is NaN)
169
// does not guarantee that bits are preserved, this class lets us
170
// store the type and use it as a float when necessary.
171
template <typename T>
172
class FloatProxy {
173
 public:
174
  typedef typename FloatProxyTraits<T>::uint_type uint_type;
175
176
  // Since this is to act similar to the normal floats,
177
  // do not initialize the data by default.
178
750
  FloatProxy() {}
spvutils::FloatProxy<spvutils::Float16>::FloatProxy()
Line
Count
Source
178
750
  FloatProxy() {}
Unexecuted instantiation: spvutils::FloatProxy<spvutils::FloatE5M2>::FloatProxy()
Unexecuted instantiation: spvutils::FloatProxy<spvutils::FloatE4M3>::FloatProxy()
179
180
  // Intentionally non-explicit. This is a proxy type so
181
  // implicit conversions allow us to use it more transparently.
182
955
  FloatProxy(T val) { data_ = BitwiseCast<uint_type>(val); }
183
184
  // Intentionally non-explicit. This is a proxy type so
185
  // implicit conversions allow us to use it more transparently.
186
1.91k
  FloatProxy(uint_type val) { data_ = val; }
spvutils::FloatProxy<spvutils::Float16>::FloatProxy(unsigned short)
Line
Count
Source
186
1.91k
  FloatProxy(uint_type val) { data_ = val; }
Unexecuted instantiation: spvutils::FloatProxy<spvutils::FloatE5M2>::FloatProxy(unsigned char)
Unexecuted instantiation: spvutils::FloatProxy<spvutils::FloatE4M3>::FloatProxy(unsigned char)
187
188
  // This is helpful to have and is guaranteed not to stomp bits.
189
0
  FloatProxy<T> operator-() const {
190
0
    return static_cast<uint_type>(data_ ^
191
0
                                  (uint_type(0x1) << (sizeof(T) * 8 - 1)));
192
0
  }
Unexecuted instantiation: spvutils::FloatProxy<spvutils::Float16>::operator-() const
Unexecuted instantiation: spvutils::FloatProxy<spvutils::FloatE5M2>::operator-() const
Unexecuted instantiation: spvutils::FloatProxy<spvutils::FloatE4M3>::operator-() const
Unexecuted instantiation: spvutils::FloatProxy<float>::operator-() const
193
194
  // Returns the data as a floating point value.
195
955
  T getAsFloat() const { return BitwiseCast<T>(data_); }
spvutils::FloatProxy<spvutils::Float16>::getAsFloat() const
Line
Count
Source
195
955
  T getAsFloat() const { return BitwiseCast<T>(data_); }
Unexecuted instantiation: spvutils::FloatProxy<spvutils::FloatE5M2>::getAsFloat() const
Unexecuted instantiation: spvutils::FloatProxy<spvutils::FloatE4M3>::getAsFloat() const
Unexecuted instantiation: spvutils::FloatProxy<float>::getAsFloat() const
196
197
  // Returns the raw data.
198
  uint_type data() const { return data_; }
199
200
  // Returns true if the value represents any type of NaN.
201
  bool isNan() { return FloatProxyTraits<T>::isNan(getAsFloat()); }
202
  // Returns true if the value represents any type of infinity.
203
0
  bool isInfinity() { return FloatProxyTraits<T>::isInfinity(getAsFloat()); }
204
205
  // Returns the maximum normal value.
206
0
  static FloatProxy<T> max() {
207
0
    return FloatProxy<T>(FloatProxyTraits<T>::max());
208
0
  }
209
  // Returns the lowest normal value.
210
0
  static FloatProxy<T> lowest() {
211
0
    return FloatProxy<T>(FloatProxyTraits<T>::lowest());
212
0
  }
213
214
 private:
215
  uint_type data_;
216
};
217
218
template <typename T>
219
bool operator==(const FloatProxy<T>& first, const FloatProxy<T>& second) {
220
  return first.data() == second.data();
221
}
222
223
// Reads a FloatProxy value as a normal float from a stream.
224
template <typename T>
225
0
std::istream& operator>>(std::istream& is, FloatProxy<T>& value) {
226
0
  T float_val;
227
0
  is >> float_val;
228
0
  value = FloatProxy<T>(float_val);
229
0
  return is;
230
0
}
231
232
// This is an example traits. It is not meant to be used in practice, but will
233
// be the default for any non-specialized type.
234
template <typename T>
235
struct HexFloatTraits {
236
  // Integer type that can store this hex-float.
237
  typedef void uint_type;
238
  // Signed integer type that can store this hex-float.
239
  typedef void int_type;
240
  // The numerical type that this HexFloat represents.
241
  typedef void underlying_type;
242
  // The type needed to construct the underlying type.
243
  typedef void native_type;
244
  // The number of bits that are actually relevant in the uint_type.
245
  // This allows us to deal with, for example, 24-bit values in a 32-bit
246
  // integer.
247
  static const uint32_t num_used_bits = 0;
248
  // Number of bits that represent the exponent.
249
  static const uint32_t num_exponent_bits = 0;
250
  // Number of bits that represent the fractional part.
251
  static const uint32_t num_fraction_bits = 0;
252
  // The bias of the exponent. (How much we need to subtract from the stored
253
  // value to get the correct value.)
254
  static const uint32_t exponent_bias = 0;
255
  static bool supportsInfinity() { return true; }
256
};
257
258
// Traits for IEEE float.
259
// 1 sign bit, 8 exponent bits, 23 fractional bits.
260
template <>
261
struct HexFloatTraits<FloatProxy<float>> {
262
  typedef uint32_t uint_type;
263
  typedef int32_t int_type;
264
  typedef FloatProxy<float> underlying_type;
265
  typedef float native_type;
266
  static const uint_type num_used_bits = 32;
267
  static const uint_type num_exponent_bits = 8;
268
  static const uint_type num_fraction_bits = 23;
269
  static const uint_type exponent_bias = 127;
270
0
  static bool supportsInfinity() { return true; }
271
};
272
273
// Traits for IEEE double.
274
// 1 sign bit, 11 exponent bits, 52 fractional bits.
275
template <>
276
struct HexFloatTraits<FloatProxy<double>> {
277
  typedef uint64_t uint_type;
278
  typedef int64_t int_type;
279
  typedef FloatProxy<double> underlying_type;
280
  typedef double native_type;
281
  static const uint_type num_used_bits = 64;
282
  static const uint_type num_exponent_bits = 11;
283
  static const uint_type num_fraction_bits = 52;
284
  static const uint_type exponent_bias = 1023;
285
0
  static bool supportsInfinity() { return true; }
286
};
287
288
// Traits for IEEE half.
289
// 1 sign bit, 5 exponent bits, 10 fractional bits.
290
template <>
291
struct HexFloatTraits<FloatProxy<Float16>> {
292
  typedef uint16_t uint_type;
293
  typedef int16_t int_type;
294
  typedef uint16_t underlying_type;
295
  typedef uint16_t native_type;
296
  static const uint_type num_used_bits = 16;
297
  static const uint_type num_exponent_bits = 5;
298
  static const uint_type num_fraction_bits = 10;
299
  static const uint_type exponent_bias = 15;
300
0
  static bool supportsInfinity() { return true; }
301
};
302
303
template <>
304
struct HexFloatTraits<FloatProxy<FloatE5M2>> {
305
  typedef uint8_t uint_type;
306
  typedef int8_t int_type;
307
  typedef uint8_t underlying_type;
308
  typedef uint8_t native_type;
309
  static const uint_type num_used_bits = 8;
310
  static const uint_type num_exponent_bits = 5;
311
  static const uint_type num_fraction_bits = 2;
312
  static const uint_type exponent_bias = 15;
313
0
  static bool supportsInfinity() { return true; }
314
};
315
316
template <>
317
struct HexFloatTraits<FloatProxy<FloatE4M3>> {
318
  typedef uint8_t uint_type;
319
  typedef int8_t int_type;
320
  typedef uint8_t underlying_type;
321
  typedef uint8_t native_type;
322
  static const uint_type num_used_bits = 8;
323
  static const uint_type num_exponent_bits = 4;
324
  static const uint_type num_fraction_bits = 3;
325
  static const uint_type exponent_bias = 7;
326
0
  static bool supportsInfinity() { return false; }
327
};
328
329
enum round_direction {
330
  kRoundToZero,
331
  kRoundToNearestEven,
332
  kRoundToPositiveInfinity,
333
  kRoundToNegativeInfinity
334
};
335
336
// Template class that houses a floating pointer number.
337
// It exposes a number of constants based on the provided traits to
338
// assist in interpreting the bits of the value.
339
template <typename T, typename Traits = HexFloatTraits<T>>
340
class HexFloat {
341
 public:
342
  typedef typename Traits::uint_type uint_type;
343
  typedef typename Traits::int_type int_type;
344
  typedef typename Traits::underlying_type underlying_type;
345
  typedef typename Traits::native_type native_type;
346
  using Traits_T = Traits;
347
348
2.86k
  explicit HexFloat(T f) : value_(f) {}
spvutils::HexFloat<spvutils::FloatProxy<float>, spvutils::HexFloatTraits<spvutils::FloatProxy<float> > >::HexFloat(spvutils::FloatProxy<float>)
Line
Count
Source
348
955
  explicit HexFloat(T f) : value_(f) {}
spvutils::HexFloat<spvutils::FloatProxy<spvutils::Float16>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::Float16> > >::HexFloat(spvutils::FloatProxy<spvutils::Float16>)
Line
Count
Source
348
1.91k
  explicit HexFloat(T f) : value_(f) {}
Unexecuted instantiation: spvutils::HexFloat<spvutils::FloatProxy<spvutils::FloatE5M2>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::FloatE5M2> > >::HexFloat(spvutils::FloatProxy<spvutils::FloatE5M2>)
Unexecuted instantiation: spvutils::HexFloat<spvutils::FloatProxy<spvutils::FloatE4M3>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::FloatE4M3> > >::HexFloat(spvutils::FloatProxy<spvutils::FloatE4M3>)
349
350
955
  T value() const { return value_; }
spvutils::HexFloat<spvutils::FloatProxy<spvutils::Float16>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::Float16> > >::value() const
Line
Count
Source
350
955
  T value() const { return value_; }
Unexecuted instantiation: spvutils::HexFloat<spvutils::FloatProxy<spvutils::FloatE5M2>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::FloatE5M2> > >::value() const
Unexecuted instantiation: spvutils::HexFloat<spvutils::FloatProxy<spvutils::FloatE4M3>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::FloatE4M3> > >::value() const
351
0
  void set_value(T f) { value_ = f; }
Unexecuted instantiation: spvutils::HexFloat<spvutils::FloatProxy<spvutils::Float16>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::Float16> > >::set_value(spvutils::FloatProxy<spvutils::Float16>)
Unexecuted instantiation: spvutils::HexFloat<spvutils::FloatProxy<spvutils::FloatE5M2>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::FloatE5M2> > >::set_value(spvutils::FloatProxy<spvutils::FloatE5M2>)
Unexecuted instantiation: spvutils::HexFloat<spvutils::FloatProxy<spvutils::FloatE4M3>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::FloatE4M3> > >::set_value(spvutils::FloatProxy<spvutils::FloatE4M3>)
Unexecuted instantiation: spvutils::HexFloat<spvutils::FloatProxy<float>, spvutils::HexFloatTraits<spvutils::FloatProxy<float> > >::set_value(spvutils::FloatProxy<float>)
352
353
  // These are all written like this because it is convenient to have
354
  // compile-time constants for all of these values.
355
356
  // Pass-through values to save typing.
357
  static const uint32_t num_used_bits = Traits::num_used_bits;
358
  static const uint32_t exponent_bias = Traits::exponent_bias;
359
  static const uint32_t num_exponent_bits = Traits::num_exponent_bits;
360
  static const uint32_t num_fraction_bits = Traits::num_fraction_bits;
361
362
  // Number of bits to shift left to set the highest relevant bit.
363
  static const uint32_t top_bit_left_shift = num_used_bits - 1;
364
  // How many nibbles (hex characters) the fractional part takes up.
365
  static const uint32_t fraction_nibbles = (num_fraction_bits + 3) / 4;
366
  // If the fractional part does not fit evenly into a hex character (4-bits)
367
  // then we have to left-shift to get rid of leading 0s. This is the amount
368
  // we have to shift (might be 0).
369
  static const uint32_t num_overflow_bits =
370
      fraction_nibbles * 4 - num_fraction_bits;
371
372
  // The representation of the fraction, not the actual bits. This
373
  // includes the leading bit that is usually implicit.
374
  static const uint_type fraction_represent_mask =
375
      spvutils::SetBits<uint_type, 0,
376
                        num_fraction_bits + num_overflow_bits>::get;
377
378
  // The topmost bit in the nibble-aligned fraction.
379
  static const uint_type fraction_top_bit =
380
      uint_type(1) << (num_fraction_bits + num_overflow_bits - 1);
381
382
  // The least significant bit in the exponent, which is also the bit
383
  // immediately to the left of the significand.
384
  static const uint_type first_exponent_bit = uint_type(1)
385
                                              << (num_fraction_bits);
386
387
  // The mask for the encoded fraction. It does not include the
388
  // implicit bit.
389
  static const uint_type fraction_encode_mask =
390
      spvutils::SetBits<uint_type, 0, num_fraction_bits>::get;
391
392
  // The bit that is used as a sign.
393
  static const uint_type sign_mask = uint_type(1) << top_bit_left_shift;
394
395
  // The bits that represent the exponent.
396
  static const uint_type exponent_mask =
397
      spvutils::SetBits<uint_type, num_fraction_bits, num_exponent_bits>::get;
398
399
  // How far left the exponent is shifted.
400
  static const uint32_t exponent_left_shift = num_fraction_bits;
401
402
  // How far from the right edge the fraction is shifted.
403
  static const uint32_t fraction_right_shift =
404
      static_cast<uint32_t>(sizeof(uint_type) * 8) - num_fraction_bits;
405
406
  // The maximum representable unbiased exponent.
407
  static const int_type max_exponent =
408
      (exponent_mask >> num_fraction_bits) - exponent_bias;
409
  // The minimum representable exponent for normalized numbers.
410
  static const int_type min_exponent = -static_cast<int_type>(exponent_bias);
411
412
  // Returns the bits associated with the value.
413
6.35k
  uint_type getBits() const { return spvutils::BitwiseCast<uint_type>(value_); }
spvutils::HexFloat<spvutils::FloatProxy<float>, spvutils::HexFloatTraits<spvutils::FloatProxy<float> > >::getBits() const
Line
Count
Source
413
6.35k
  uint_type getBits() const { return spvutils::BitwiseCast<uint_type>(value_); }
Unexecuted instantiation: spvutils::HexFloat<spvutils::FloatProxy<spvutils::Float16>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::Float16> > >::getBits() const
414
415
  // Returns the bits associated with the value, without the leading sign bit.
416
955
  uint_type getUnsignedBits() const {
417
955
    return static_cast<uint_type>(spvutils::BitwiseCast<uint_type>(value_) &
418
955
                                  ~sign_mask);
419
955
  }
420
421
  // Returns the bits associated with the exponent, shifted to start at the
422
  // lsb of the type.
423
1.50k
  const uint_type getExponentBits() const {
424
1.50k
    return static_cast<uint_type>((getBits() & exponent_mask) >>
425
1.50k
                                  num_fraction_bits);
426
1.50k
  }
427
428
  // Returns the exponent in unbiased form. This is the exponent in the
429
  // human-friendly form.
430
1.50k
  const int_type getUnbiasedExponent() const {
431
1.50k
    return static_cast<int_type>(getExponentBits() - exponent_bias);
432
1.50k
  }
433
434
  // Returns just the significand bits from the value.
435
1.50k
  const uint_type getSignificandBits() const {
436
1.50k
    return getBits() & fraction_encode_mask;
437
1.50k
  }
438
439
  // If the number was normalized, returns the unbiased exponent.
440
  // If the number was denormal, normalize the exponent first.
441
750
  const int_type getUnbiasedNormalizedExponent() const {
442
750
    if ((getBits() & ~sign_mask) == 0) {  // special case if everything is 0
443
0
      return 0;
444
0
    }
445
750
    int_type exp = getUnbiasedExponent();
446
750
    if (exp == min_exponent) {  // We are in denorm land.
447
0
      uint_type significand_bits = getSignificandBits();
448
0
      while ((significand_bits & (first_exponent_bit >> 1)) == 0) {
449
0
        significand_bits = static_cast<uint_type>(significand_bits << 1);
450
0
        exp = static_cast<int_type>(exp - 1);
451
0
      }
452
0
      significand_bits &= fraction_encode_mask;
453
0
    }
454
750
    return exp;
455
750
  }
456
457
  // Returns the signficand after it has been normalized.
458
750
  const uint_type getNormalizedSignificand() const {
459
750
    int_type unbiased_exponent = getUnbiasedNormalizedExponent();
460
750
    uint_type significand = getSignificandBits();
461
750
    for (int_type i = unbiased_exponent; i <= min_exponent; ++i) {
462
0
      significand = static_cast<uint_type>(significand << 1);
463
0
    }
464
750
    significand &= fraction_encode_mask;
465
750
    return significand;
466
750
  }
467
468
  // Returns true if this number represents a negative value.
469
1.70k
  bool isNegative() const { return (getBits() & sign_mask) != 0; }
spvutils::HexFloat<spvutils::FloatProxy<float>, spvutils::HexFloatTraits<spvutils::FloatProxy<float> > >::isNegative() const
Line
Count
Source
469
1.70k
  bool isNegative() const { return (getBits() & sign_mask) != 0; }
Unexecuted instantiation: spvutils::HexFloat<spvutils::FloatProxy<spvutils::Float16>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::Float16> > >::isNegative() const
470
471
  // Sets this HexFloat from the individual components.
472
  // Note this assumes EVERY significand is normalized, and has an implicit
473
  // leading one. This means that the only way that this method will set 0,
474
  // is if you set a number so denormalized that it underflows.
475
  // Do not use this method with raw bits extracted from a subnormal number,
476
  // since subnormals do not have an implicit leading 1 in the significand.
477
  // The significand is also expected to be in the
478
  // lowest-most num_fraction_bits of the uint_type.
479
  // The exponent is expected to be unbiased, meaning an exponent of
480
  // 0 actually means 0.
481
  // If underflow_round_up is set, then on underflow, if a number is non-0
482
  // and would underflow, we round up to the smallest denorm.
483
  void setFromSignUnbiasedExponentAndNormalizedSignificand(
484
      bool negative, int_type exponent, uint_type significand,
485
750
      bool round_denorm_up) {
486
750
    bool significand_is_zero = significand == 0;
487
488
750
    if (exponent <= min_exponent) {
489
      // If this was denormalized, then we have to shift the bit on, meaning
490
      // the significand is not zero.
491
0
      significand_is_zero = false;
492
0
      significand |= first_exponent_bit;
493
0
      significand = static_cast<uint_type>(significand >> 1);
494
0
    }
495
496
750
    while (exponent < min_exponent) {
497
0
      significand = static_cast<uint_type>(significand >> 1);
498
0
      ++exponent;
499
0
    }
500
501
750
    if (exponent == min_exponent) {
502
0
      if (significand == 0 && !significand_is_zero && round_denorm_up) {
503
0
        significand = static_cast<uint_type>(0x1);
504
0
      }
505
0
    }
506
507
750
    uint_type new_value = 0;
508
750
    if (negative) {
509
0
      new_value = static_cast<uint_type>(new_value | sign_mask);
510
0
    }
511
750
    exponent = static_cast<int_type>(exponent + exponent_bias);
512
750
    assert(exponent >= 0);
513
514
    // put it all together
515
750
    exponent = static_cast<uint_type>((exponent << exponent_left_shift) &
516
750
                                      exponent_mask);
517
750
    significand = static_cast<uint_type>(significand & fraction_encode_mask);
518
750
    new_value = static_cast<uint_type>(new_value | (exponent | significand));
519
750
    value_ = BitwiseCast<T>(new_value);
520
750
  }
spvutils::HexFloat<spvutils::FloatProxy<spvutils::Float16>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::Float16> > >::setFromSignUnbiasedExponentAndNormalizedSignificand(bool, short, unsigned short, bool)
Line
Count
Source
485
750
      bool round_denorm_up) {
486
750
    bool significand_is_zero = significand == 0;
487
488
750
    if (exponent <= min_exponent) {
489
      // If this was denormalized, then we have to shift the bit on, meaning
490
      // the significand is not zero.
491
0
      significand_is_zero = false;
492
0
      significand |= first_exponent_bit;
493
0
      significand = static_cast<uint_type>(significand >> 1);
494
0
    }
495
496
750
    while (exponent < min_exponent) {
497
0
      significand = static_cast<uint_type>(significand >> 1);
498
0
      ++exponent;
499
0
    }
500
501
750
    if (exponent == min_exponent) {
502
0
      if (significand == 0 && !significand_is_zero && round_denorm_up) {
503
0
        significand = static_cast<uint_type>(0x1);
504
0
      }
505
0
    }
506
507
750
    uint_type new_value = 0;
508
750
    if (negative) {
509
0
      new_value = static_cast<uint_type>(new_value | sign_mask);
510
0
    }
511
750
    exponent = static_cast<int_type>(exponent + exponent_bias);
512
750
    assert(exponent >= 0);
513
514
    // put it all together
515
750
    exponent = static_cast<uint_type>((exponent << exponent_left_shift) &
516
750
                                      exponent_mask);
517
750
    significand = static_cast<uint_type>(significand & fraction_encode_mask);
518
750
    new_value = static_cast<uint_type>(new_value | (exponent | significand));
519
750
    value_ = BitwiseCast<T>(new_value);
520
750
  }
Unexecuted instantiation: spvutils::HexFloat<spvutils::FloatProxy<spvutils::FloatE5M2>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::FloatE5M2> > >::setFromSignUnbiasedExponentAndNormalizedSignificand(bool, signed char, unsigned char, bool)
Unexecuted instantiation: spvutils::HexFloat<spvutils::FloatProxy<spvutils::FloatE4M3>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::FloatE4M3> > >::setFromSignUnbiasedExponentAndNormalizedSignificand(bool, signed char, unsigned char, bool)
521
522
  // Increments the significand of this number by the given amount.
523
  // If this would spill the significand into the implicit bit,
524
  // carry is set to true and the significand is shifted to fit into
525
  // the correct location, otherwise carry is set to false.
526
  // All significands and to_increment are assumed to be within the bounds
527
  // for a valid significand.
528
  static uint_type incrementSignificand(uint_type significand,
529
0
                                        uint_type to_increment, bool* carry) {
530
0
    significand = static_cast<uint_type>(significand + to_increment);
531
0
    *carry = false;
532
0
    if (significand & first_exponent_bit) {
533
0
      *carry = true;
534
      // The implicit 1-bit will have carried, so we should zero-out the
535
      // top bit and shift back.
536
0
      significand = static_cast<uint_type>(significand & ~first_exponent_bit);
537
0
      significand = static_cast<uint_type>(significand >> 1);
538
0
    }
539
0
    return significand;
540
0
  }
541
542
  // These exist because MSVC throws warnings on negative right-shifts
543
  // even if they are not going to be executed. Eg:
544
  // constant_number < 0? 0: constant_number
545
  // These convert the negative left-shifts into right shifts.
546
547
  template <typename int_type>
548
  uint_type negatable_left_shift(int_type N, uint_type val)
549
6
  {
550
6
    if(N >= 0)
551
6
      return val << N;
552
553
0
    return val >> -N;
554
6
  }
555
556
  template <typename int_type>
557
  uint_type negatable_right_shift(int_type N, uint_type val)
558
750
  {
559
750
    if(N >= 0)
560
750
      return val >> N;
561
562
0
    return val << -N;
563
750
  }
564
565
  // Returns the significand, rounded to fit in a significand in
566
  // other_T. This is shifted so that the most significant
567
  // bit of the rounded number lines up with the most significant bit
568
  // of the returned significand.
569
  template <typename other_T>
570
  typename other_T::uint_type getRoundedNormalizedSignificand(
571
750
      round_direction dir, bool* carry_bit) {
572
750
    typedef typename other_T::uint_type other_uint_type;
573
750
    static const int_type num_throwaway_bits =
574
750
        static_cast<int_type>(num_fraction_bits) -
575
750
        static_cast<int_type>(other_T::num_fraction_bits);
576
577
750
    static const uint_type last_significant_bit =
578
750
        (num_throwaway_bits < 0)
579
750
            ? 0
580
750
            : negatable_left_shift(num_throwaway_bits, 1u);
581
750
    static const uint_type first_rounded_bit =
582
750
        (num_throwaway_bits < 1)
583
750
            ? 0
584
750
            : negatable_left_shift(num_throwaway_bits - 1, 1u);
585
586
750
    static const uint_type throwaway_mask_bits =
587
750
        num_throwaway_bits > 0 ? num_throwaway_bits : 0;
588
750
    static const uint_type throwaway_mask =
589
750
        spvutils::SetBits<uint_type, 0, throwaway_mask_bits>::get;
590
591
750
    *carry_bit = false;
592
750
    other_uint_type out_val = 0;
593
750
    uint_type significand = getNormalizedSignificand();
594
    // If we are up-casting, then we just have to shift to the right location.
595
750
    if (num_throwaway_bits <= 0) {
596
0
      out_val = static_cast<other_uint_type>(significand);
597
0
      uint_type shift_amount = static_cast<uint_type>(-num_throwaway_bits);
598
0
      out_val = static_cast<other_uint_type>(out_val << shift_amount);
599
0
      return out_val;
600
0
    }
601
602
    // If every non-representable bit is 0, then we don't have any casting to
603
    // do.
604
750
    if ((significand & throwaway_mask) == 0) {
605
750
      return static_cast<other_uint_type>(
606
750
          negatable_right_shift(num_throwaway_bits, significand));
607
750
    }
608
609
0
    bool round_away_from_zero = false;
610
    // We actually have to narrow the significand here, so we have to follow the
611
    // rounding rules.
612
0
    switch (dir) {
613
0
      case kRoundToZero:
614
0
        break;
615
0
      case kRoundToPositiveInfinity:
616
0
        round_away_from_zero = !isNegative();
617
0
        break;
618
0
      case kRoundToNegativeInfinity:
619
0
        round_away_from_zero = isNegative();
620
0
        break;
621
0
      case kRoundToNearestEven:
622
        // Have to round down, round bit is 0
623
0
        if ((first_rounded_bit & significand) == 0) {
624
0
          break;
625
0
        }
626
0
        if (((significand & throwaway_mask) & ~first_rounded_bit) != 0) {
627
          // If any subsequent bit of the rounded portion is non-0 then we round
628
          // up.
629
0
          round_away_from_zero = true;
630
0
          break;
631
0
        }
632
        // We are exactly half-way between 2 numbers, pick even.
633
0
        if ((significand & last_significant_bit) != 0) {
634
          // 1 for our last bit, round up.
635
0
          round_away_from_zero = true;
636
0
          break;
637
0
        }
638
0
        break;
639
0
    }
640
641
0
    if (round_away_from_zero) {
642
0
      return static_cast<other_uint_type>(
643
0
          negatable_right_shift(num_throwaway_bits, incrementSignificand(
644
0
              significand, last_significant_bit, carry_bit)));
645
0
    } else {
646
0
      return static_cast<other_uint_type>(
647
0
          negatable_right_shift(num_throwaway_bits, significand));
648
0
    }
649
0
  }
spvutils::HexFloat<spvutils::FloatProxy<spvutils::Float16>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::Float16> > >::uint_type spvutils::HexFloat<spvutils::FloatProxy<float>, spvutils::HexFloatTraits<spvutils::FloatProxy<float> > >::getRoundedNormalizedSignificand<spvutils::HexFloat<spvutils::FloatProxy<spvutils::Float16>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::Float16> > > >(spvutils::round_direction, bool*)
Line
Count
Source
571
750
      round_direction dir, bool* carry_bit) {
572
750
    typedef typename other_T::uint_type other_uint_type;
573
750
    static const int_type num_throwaway_bits =
574
750
        static_cast<int_type>(num_fraction_bits) -
575
750
        static_cast<int_type>(other_T::num_fraction_bits);
576
577
750
    static const uint_type last_significant_bit =
578
750
        (num_throwaway_bits < 0)
579
750
            ? 0
580
750
            : negatable_left_shift(num_throwaway_bits, 1u);
581
750
    static const uint_type first_rounded_bit =
582
750
        (num_throwaway_bits < 1)
583
750
            ? 0
584
750
            : negatable_left_shift(num_throwaway_bits - 1, 1u);
585
586
750
    static const uint_type throwaway_mask_bits =
587
750
        num_throwaway_bits > 0 ? num_throwaway_bits : 0;
588
750
    static const uint_type throwaway_mask =
589
750
        spvutils::SetBits<uint_type, 0, throwaway_mask_bits>::get;
590
591
750
    *carry_bit = false;
592
750
    other_uint_type out_val = 0;
593
750
    uint_type significand = getNormalizedSignificand();
594
    // If we are up-casting, then we just have to shift to the right location.
595
750
    if (num_throwaway_bits <= 0) {
596
0
      out_val = static_cast<other_uint_type>(significand);
597
0
      uint_type shift_amount = static_cast<uint_type>(-num_throwaway_bits);
598
0
      out_val = static_cast<other_uint_type>(out_val << shift_amount);
599
0
      return out_val;
600
0
    }
601
602
    // If every non-representable bit is 0, then we don't have any casting to
603
    // do.
604
750
    if ((significand & throwaway_mask) == 0) {
605
750
      return static_cast<other_uint_type>(
606
750
          negatable_right_shift(num_throwaway_bits, significand));
607
750
    }
608
609
0
    bool round_away_from_zero = false;
610
    // We actually have to narrow the significand here, so we have to follow the
611
    // rounding rules.
612
0
    switch (dir) {
613
0
      case kRoundToZero:
614
0
        break;
615
0
      case kRoundToPositiveInfinity:
616
0
        round_away_from_zero = !isNegative();
617
0
        break;
618
0
      case kRoundToNegativeInfinity:
619
0
        round_away_from_zero = isNegative();
620
0
        break;
621
0
      case kRoundToNearestEven:
622
        // Have to round down, round bit is 0
623
0
        if ((first_rounded_bit & significand) == 0) {
624
0
          break;
625
0
        }
626
0
        if (((significand & throwaway_mask) & ~first_rounded_bit) != 0) {
627
          // If any subsequent bit of the rounded portion is non-0 then we round
628
          // up.
629
0
          round_away_from_zero = true;
630
0
          break;
631
0
        }
632
        // We are exactly half-way between 2 numbers, pick even.
633
0
        if ((significand & last_significant_bit) != 0) {
634
          // 1 for our last bit, round up.
635
0
          round_away_from_zero = true;
636
0
          break;
637
0
        }
638
0
        break;
639
0
    }
640
641
0
    if (round_away_from_zero) {
642
0
      return static_cast<other_uint_type>(
643
0
          negatable_right_shift(num_throwaway_bits, incrementSignificand(
644
0
              significand, last_significant_bit, carry_bit)));
645
0
    } else {
646
0
      return static_cast<other_uint_type>(
647
0
          negatable_right_shift(num_throwaway_bits, significand));
648
0
    }
649
0
  }
Unexecuted instantiation: spvutils::HexFloat<spvutils::FloatProxy<spvutils::FloatE5M2>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::FloatE5M2> > >::uint_type spvutils::HexFloat<spvutils::FloatProxy<float>, spvutils::HexFloatTraits<spvutils::FloatProxy<float> > >::getRoundedNormalizedSignificand<spvutils::HexFloat<spvutils::FloatProxy<spvutils::FloatE5M2>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::FloatE5M2> > > >(spvutils::round_direction, bool*)
Unexecuted instantiation: spvutils::HexFloat<spvutils::FloatProxy<spvutils::FloatE4M3>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::FloatE4M3> > >::uint_type spvutils::HexFloat<spvutils::FloatProxy<float>, spvutils::HexFloatTraits<spvutils::FloatProxy<float> > >::getRoundedNormalizedSignificand<spvutils::HexFloat<spvutils::FloatProxy<spvutils::FloatE4M3>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::FloatE4M3> > > >(spvutils::round_direction, bool*)
650
651
  // Casts this value to another HexFloat. If the cast is widening,
652
  // then round_dir is ignored. If the cast is narrowing, then
653
  // the result is rounded in the direction specified.
654
  // This number will retain Nan and Inf values.
655
  // It will also saturate to Inf if the number overflows, and
656
  // underflow to (0 or min depending on rounding) if the number underflows.
657
  template <typename other_T>
658
955
  void castTo(other_T& other, round_direction round_dir) {
659
955
    other = other_T(static_cast<typename other_T::native_type>(0));
660
955
    bool negate = isNegative();
661
955
    if (getUnsignedBits() == 0) {
662
205
      if (negate) {
663
0
        other.set_value(-other.value());
664
0
      }
665
205
      return;
666
205
    }
667
750
    uint_type significand = getSignificandBits();
668
750
    bool carried = false;
669
750
    typename other_T::uint_type rounded_significand =
670
750
        getRoundedNormalizedSignificand<other_T>(round_dir, &carried);
671
672
750
    int_type exponent = getUnbiasedExponent();
673
750
    if (exponent == min_exponent) {
674
      // If we are denormal, normalize the exponent, so that we can encode
675
      // easily.
676
0
      exponent = static_cast<int_type>(exponent + 1);
677
0
      for (uint_type check_bit = first_exponent_bit >> 1; check_bit != 0;
678
0
           check_bit = static_cast<uint_type>(check_bit >> 1)) {
679
0
        exponent = static_cast<int_type>(exponent - 1);
680
0
        if (check_bit & significand) break;
681
0
      }
682
0
    }
683
684
750
    bool is_nan =
685
750
        (getBits() & exponent_mask) == exponent_mask && significand != 0;
686
750
    bool is_inf =
687
750
        !is_nan &&
688
750
        (((exponent + carried) > static_cast<int_type>(other_T::exponent_bias) && other_T::Traits_T::supportsInfinity()) ||
689
750
         ((exponent + carried) > static_cast<int_type>(other_T::exponent_bias + 1) && !other_T::Traits_T::supportsInfinity()) ||
690
750
         (significand == 0 && (getBits() & exponent_mask) == exponent_mask));
691
692
    // If we are Nan or Inf we should pass that through.
693
750
    if (is_inf) {
694
0
      if (other_T::Traits_T::supportsInfinity()) {
695
        // encode as +/-inf
696
0
        other.set_value(BitwiseCast<typename other_T::underlying_type>(
697
0
            static_cast<typename other_T::uint_type>(
698
0
                (negate ? other_T::sign_mask : 0) | other_T::exponent_mask)));
699
0
      } else {
700
        // encode as +/-nan
701
0
        other.set_value(BitwiseCast<typename other_T::underlying_type>(
702
0
            static_cast<typename other_T::uint_type>(negate ? ~0 : ~other_T::sign_mask)));
703
0
      }
704
0
      return;
705
0
    }
706
750
    if (is_nan) {
707
0
      typename other_T::uint_type shifted_significand;
708
0
      shifted_significand = static_cast<typename other_T::uint_type>(
709
0
          negatable_left_shift(
710
0
              static_cast<int_type>(other_T::num_fraction_bits) -
711
0
              static_cast<int_type>(num_fraction_bits), significand));
712
713
      // We are some sort of Nan. We try to keep the bit-pattern of the Nan
714
      // as close as possible. If we had to shift off bits so we are 0, then we
715
      // just set the last bit.
716
0
      other.set_value(BitwiseCast<typename other_T::underlying_type>(
717
0
          static_cast<typename other_T::uint_type>(
718
0
              (negate ? other_T::sign_mask : 0) | other_T::exponent_mask |
719
0
              (shifted_significand == 0 ? 0x1 : shifted_significand))));
720
0
      return;
721
0
    }
722
723
750
    bool round_underflow_up =
724
750
        isNegative() ? round_dir == kRoundToNegativeInfinity
725
750
                     : round_dir == kRoundToPositiveInfinity;
726
750
    typedef typename other_T::int_type other_int_type;
727
    // setFromSignUnbiasedExponentAndNormalizedSignificand will
728
    // zero out any underflowing value (but retain the sign).
729
750
    other.setFromSignUnbiasedExponentAndNormalizedSignificand(
730
750
        negate, static_cast<other_int_type>(exponent), rounded_significand,
731
750
        round_underflow_up);
732
750
    return;
733
750
  }
void spvutils::HexFloat<spvutils::FloatProxy<float>, spvutils::HexFloatTraits<spvutils::FloatProxy<float> > >::castTo<spvutils::HexFloat<spvutils::FloatProxy<spvutils::Float16>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::Float16> > > >(spvutils::HexFloat<spvutils::FloatProxy<spvutils::Float16>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::Float16> > >&, spvutils::round_direction)
Line
Count
Source
658
955
  void castTo(other_T& other, round_direction round_dir) {
659
955
    other = other_T(static_cast<typename other_T::native_type>(0));
660
955
    bool negate = isNegative();
661
955
    if (getUnsignedBits() == 0) {
662
205
      if (negate) {
663
0
        other.set_value(-other.value());
664
0
      }
665
205
      return;
666
205
    }
667
750
    uint_type significand = getSignificandBits();
668
750
    bool carried = false;
669
750
    typename other_T::uint_type rounded_significand =
670
750
        getRoundedNormalizedSignificand<other_T>(round_dir, &carried);
671
672
750
    int_type exponent = getUnbiasedExponent();
673
750
    if (exponent == min_exponent) {
674
      // If we are denormal, normalize the exponent, so that we can encode
675
      // easily.
676
0
      exponent = static_cast<int_type>(exponent + 1);
677
0
      for (uint_type check_bit = first_exponent_bit >> 1; check_bit != 0;
678
0
           check_bit = static_cast<uint_type>(check_bit >> 1)) {
679
0
        exponent = static_cast<int_type>(exponent - 1);
680
0
        if (check_bit & significand) break;
681
0
      }
682
0
    }
683
684
750
    bool is_nan =
685
750
        (getBits() & exponent_mask) == exponent_mask && significand != 0;
686
750
    bool is_inf =
687
750
        !is_nan &&
688
750
        (((exponent + carried) > static_cast<int_type>(other_T::exponent_bias) && other_T::Traits_T::supportsInfinity()) ||
689
750
         ((exponent + carried) > static_cast<int_type>(other_T::exponent_bias + 1) && !other_T::Traits_T::supportsInfinity()) ||
690
750
         (significand == 0 && (getBits() & exponent_mask) == exponent_mask));
691
692
    // If we are Nan or Inf we should pass that through.
693
750
    if (is_inf) {
694
0
      if (other_T::Traits_T::supportsInfinity()) {
695
        // encode as +/-inf
696
0
        other.set_value(BitwiseCast<typename other_T::underlying_type>(
697
0
            static_cast<typename other_T::uint_type>(
698
0
                (negate ? other_T::sign_mask : 0) | other_T::exponent_mask)));
699
0
      } else {
700
        // encode as +/-nan
701
0
        other.set_value(BitwiseCast<typename other_T::underlying_type>(
702
0
            static_cast<typename other_T::uint_type>(negate ? ~0 : ~other_T::sign_mask)));
703
0
      }
704
0
      return;
705
0
    }
706
750
    if (is_nan) {
707
0
      typename other_T::uint_type shifted_significand;
708
0
      shifted_significand = static_cast<typename other_T::uint_type>(
709
0
          negatable_left_shift(
710
0
              static_cast<int_type>(other_T::num_fraction_bits) -
711
0
              static_cast<int_type>(num_fraction_bits), significand));
712
713
      // We are some sort of Nan. We try to keep the bit-pattern of the Nan
714
      // as close as possible. If we had to shift off bits so we are 0, then we
715
      // just set the last bit.
716
0
      other.set_value(BitwiseCast<typename other_T::underlying_type>(
717
0
          static_cast<typename other_T::uint_type>(
718
0
              (negate ? other_T::sign_mask : 0) | other_T::exponent_mask |
719
0
              (shifted_significand == 0 ? 0x1 : shifted_significand))));
720
0
      return;
721
0
    }
722
723
750
    bool round_underflow_up =
724
750
        isNegative() ? round_dir == kRoundToNegativeInfinity
725
750
                     : round_dir == kRoundToPositiveInfinity;
726
750
    typedef typename other_T::int_type other_int_type;
727
    // setFromSignUnbiasedExponentAndNormalizedSignificand will
728
    // zero out any underflowing value (but retain the sign).
729
750
    other.setFromSignUnbiasedExponentAndNormalizedSignificand(
730
750
        negate, static_cast<other_int_type>(exponent), rounded_significand,
731
750
        round_underflow_up);
732
750
    return;
733
750
  }
Unexecuted instantiation: void spvutils::HexFloat<spvutils::FloatProxy<float>, spvutils::HexFloatTraits<spvutils::FloatProxy<float> > >::castTo<spvutils::HexFloat<spvutils::FloatProxy<spvutils::FloatE5M2>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::FloatE5M2> > > >(spvutils::HexFloat<spvutils::FloatProxy<spvutils::FloatE5M2>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::FloatE5M2> > >&, spvutils::round_direction)
Unexecuted instantiation: void spvutils::HexFloat<spvutils::FloatProxy<float>, spvutils::HexFloatTraits<spvutils::FloatProxy<float> > >::castTo<spvutils::HexFloat<spvutils::FloatProxy<spvutils::FloatE4M3>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::FloatE4M3> > > >(spvutils::HexFloat<spvutils::FloatProxy<spvutils::FloatE4M3>, spvutils::HexFloatTraits<spvutils::FloatProxy<spvutils::FloatE4M3> > >&, spvutils::round_direction)
734
735
 private:
736
  T value_;
737
738
  static_assert(num_used_bits ==
739
                    Traits::num_exponent_bits + Traits::num_fraction_bits + 1,
740
                "The number of bits do not fit");
741
  static_assert(sizeof(T) == sizeof(uint_type), "The type sizes do not match");
742
};
743
744
// Returns 4 bits represented by the hex character.
745
0
inline uint8_t get_nibble_from_character(int character) {
746
0
  const char* dec = "0123456789";
747
0
  const char* lower = "abcdef";
748
0
  const char* upper = "ABCDEF";
749
0
  const char* p = nullptr;
750
0
  if ((p = strchr(dec, character))) {
751
0
    return static_cast<uint8_t>(p - dec);
752
0
  } else if ((p = strchr(lower, character))) {
753
0
    return static_cast<uint8_t>(p - lower + 0xa);
754
0
  } else if ((p = strchr(upper, character))) {
755
0
    return static_cast<uint8_t>(p - upper + 0xa);
756
0
  }
757
0
758
0
  assert(false && "This was called with a non-hex character");
759
0
  return 0;
760
0
}
761
762
// Outputs the given HexFloat to the stream.
763
template <typename T, typename Traits>
764
0
std::ostream& operator<<(std::ostream& os, const HexFloat<T, Traits>& value) {
765
0
  typedef HexFloat<T, Traits> HF;
766
0
  typedef typename HF::uint_type uint_type;
767
0
  typedef typename HF::int_type int_type;
768
0
769
0
  static_assert(HF::num_used_bits != 0,
770
0
                "num_used_bits must be non-zero for a valid float");
771
0
  static_assert(HF::num_exponent_bits != 0,
772
0
                "num_exponent_bits must be non-zero for a valid float");
773
0
  static_assert(HF::num_fraction_bits != 0,
774
0
                "num_fractin_bits must be non-zero for a valid float");
775
0
776
0
  const uint_type bits = spvutils::BitwiseCast<uint_type>(value.value());
777
0
  const char* const sign = (bits & HF::sign_mask) ? "-" : "";
778
0
  const uint_type exponent = static_cast<uint_type>(
779
0
      (bits & HF::exponent_mask) >> HF::num_fraction_bits);
780
0
781
0
  uint_type fraction = static_cast<uint_type>((bits & HF::fraction_encode_mask)
782
0
                                              << HF::num_overflow_bits);
783
0
784
0
  const bool is_zero = exponent == 0 && fraction == 0;
785
0
  const bool is_denorm = exponent == 0 && !is_zero;
786
0
787
0
  // exponent contains the biased exponent we have to convert it back into
788
0
  // the normal range.
789
0
  int_type int_exponent = static_cast<int_type>(exponent - HF::exponent_bias);
790
0
  // If the number is all zeros, then we actually have to NOT shift the
791
0
  // exponent.
792
0
  int_exponent = is_zero ? 0 : int_exponent;
793
0
794
0
  // If we are denorm, then start shifting, and decreasing the exponent until
795
0
  // our leading bit is 1.
796
0
797
0
  if (is_denorm) {
798
0
    while ((fraction & HF::fraction_top_bit) == 0) {
799
0
      fraction = static_cast<uint_type>(fraction << 1);
800
0
      int_exponent = static_cast<int_type>(int_exponent - 1);
801
0
    }
802
0
    // Since this is denormalized, we have to consume the leading 1 since it
803
0
    // will end up being implicit.
804
0
    fraction = static_cast<uint_type>(fraction << 1);  // eat the leading 1
805
0
    fraction &= HF::fraction_represent_mask;
806
0
  }
807
0
808
0
  uint_type fraction_nibbles = HF::fraction_nibbles;
809
0
  // We do not have to display any trailing 0s, since this represents the
810
0
  // fractional part.
811
0
  while (fraction_nibbles > 0 && (fraction & 0xF) == 0) {
812
0
    // Shift off any trailing values;
813
0
    fraction = static_cast<uint_type>(fraction >> 4);
814
0
    --fraction_nibbles;
815
0
  }
816
0
817
0
  const auto saved_flags = os.flags();
818
0
  const auto saved_fill = os.fill();
819
0
820
0
  os << sign << "0x" << (is_zero ? '0' : '1');
821
0
  if (fraction_nibbles) {
822
0
    // Make sure to keep the leading 0s in place, since this is the fractional
823
0
    // part.
824
0
    os << "." << std::setw(static_cast<int>(fraction_nibbles))
825
0
       << std::setfill('0') << std::hex << fraction;
826
0
  }
827
0
  os << "p" << std::dec << (int_exponent >= 0 ? "+" : "") << int_exponent;
828
0
829
0
  os.flags(saved_flags);
830
0
  os.fill(saved_fill);
831
0
832
0
  return os;
833
0
}
834
835
// Returns true if negate_value is true and the next character on the
836
// input stream is a plus or minus sign.  In that case we also set the fail bit
837
// on the stream and set the value to the zero value for its type.
838
template <typename T, typename Traits>
839
inline bool RejectParseDueToLeadingSign(std::istream& is, bool negate_value,
840
0
                                        HexFloat<T, Traits>& value) {
841
0
  if (negate_value) {
842
0
    auto next_char = is.peek();
843
0
    if (next_char == '-' || next_char == '+') {
844
0
      // Fail the parse.  Emulate standard behaviour by setting the value to
845
0
      // the zero value, and set the fail bit on the stream.
846
0
      value = HexFloat<T, Traits>(typename HexFloat<T, Traits>::uint_type(0));
847
0
      is.setstate(std::ios_base::failbit);
848
0
      return true;
849
0
    }
850
0
  }
851
0
  return false;
852
0
}
853
854
// Parses a floating point number from the given stream and stores it into the
855
// value parameter.
856
// If negate_value is true then the number may not have a leading minus or
857
// plus, and if it successfully parses, then the number is negated before
858
// being stored into the value parameter.
859
// If the value cannot be correctly parsed or overflows the target floating
860
// point type, then set the fail bit on the stream.
861
// TODO(dneto): Promise C++11 standard behavior in how the value is set in
862
// the error case, but only after all target platforms implement it correctly.
863
// In particular, the Microsoft C++ runtime appears to be out of spec.
864
template <typename T, typename Traits>
865
inline std::istream& ParseNormalFloat(std::istream& is, bool negate_value,
866
0
                                      HexFloat<T, Traits>& value) {
867
0
  if (RejectParseDueToLeadingSign(is, negate_value, value)) {
868
0
    return is;
869
0
  }
870
0
  T val;
871
0
  is >> val;
872
0
  if (negate_value) {
873
0
    val = -val;
874
0
  }
875
0
  value.set_value(val);
876
0
  // In the failure case, map -0.0 to 0.0.
877
0
  if (is.fail() && value.getUnsignedBits() == 0u) {
878
0
    value = HexFloat<T, Traits>(typename HexFloat<T, Traits>::uint_type(0));
879
0
  }
880
0
  if (val.isInfinity()) {
881
0
    // Fail the parse.  Emulate standard behaviour by setting the value to
882
0
    // the closest normal value, and set the fail bit on the stream.
883
0
    value.set_value((value.isNegative() || negate_value) ? T::lowest()
884
0
                                                         : T::max());
885
0
    is.setstate(std::ios_base::failbit);
886
0
  }
887
0
  return is;
888
0
}
889
890
// Specialization of ParseNormalFloat for FloatProxy<Float16> values.
891
// This will parse the float as it were a 32-bit floating point number,
892
// and then round it down to fit into a Float16 value.
893
// The number is rounded towards zero.
894
// If negate_value is true then the number may not have a leading minus or
895
// plus, and if it successfully parses, then the number is negated before
896
// being stored into the value parameter.
897
// If the value cannot be correctly parsed or overflows the target floating
898
// point type, then set the fail bit on the stream.
899
// TODO(dneto): Promise C++11 standard behavior in how the value is set in
900
// the error case, but only after all target platforms implement it correctly.
901
// In particular, the Microsoft C++ runtime appears to be out of spec.
902
template <>
903
inline std::istream&
904
ParseNormalFloat<FloatProxy<Float16>, HexFloatTraits<FloatProxy<Float16>>>(
905
    std::istream& is, bool negate_value,
906
0
    HexFloat<FloatProxy<Float16>, HexFloatTraits<FloatProxy<Float16>>>& value) {
907
0
  // First parse as a 32-bit float.
908
0
  HexFloat<FloatProxy<float>> float_val(0.0f);
909
0
  ParseNormalFloat(is, negate_value, float_val);
910
0
911
0
  // Then convert to 16-bit float, saturating at infinities, and
912
0
  // rounding toward zero.
913
0
  float_val.castTo(value, kRoundToZero);
914
0
915
0
  // Overflow on 16-bit behaves the same as for 32- and 64-bit: set the
916
0
  // fail bit and set the lowest or highest value.
917
0
  if (Float16::isInfinity(value.value().getAsFloat())) {
918
0
    value.set_value(value.isNegative() ? Float16::lowest() : Float16::max());
919
0
    is.setstate(std::ios_base::failbit);
920
0
  }
921
0
  return is;
922
0
}
923
924
// Reads a HexFloat from the given stream.
925
// If the float is not encoded as a hex-float then it will be parsed
926
// as a regular float.
927
// This may fail if your stream does not support at least one unget.
928
// Nan values can be encoded with "0x1.<not zero>p+exponent_bias".
929
// This would normally overflow a float and round to
930
// infinity but this special pattern is the exact representation for a NaN,
931
// and therefore is actually encoded as the correct NaN. To encode inf,
932
// either 0x0p+exponent_bias can be specified or any exponent greater than
933
// exponent_bias.
934
// Examples using IEEE 32-bit float encoding.
935
//    0x1.0p+128 (+inf)
936
//    -0x1.0p-128 (-inf)
937
//
938
//    0x1.1p+128 (+Nan)
939
//    -0x1.1p+128 (-Nan)
940
//
941
//    0x1p+129 (+inf)
942
//    -0x1p+129 (-inf)
943
template <typename T, typename Traits>
944
std::istream& operator>>(std::istream& is, HexFloat<T, Traits>& value) {
945
  using HF = HexFloat<T, Traits>;
946
  using uint_type = typename HF::uint_type;
947
  using int_type = typename HF::int_type;
948
949
  value.set_value(static_cast<typename HF::native_type>(0.f));
950
951
  if (is.flags() & std::ios::skipws) {
952
    // If the user wants to skip whitespace , then we should obey that.
953
    while (std::isspace(is.peek())) {
954
      is.get();
955
    }
956
  }
957
958
  auto next_char = is.peek();
959
  bool negate_value = false;
960
961
  if (next_char != '-' && next_char != '0') {
962
    return ParseNormalFloat(is, negate_value, value);
963
  }
964
965
  if (next_char == '-') {
966
    negate_value = true;
967
    is.get();
968
    next_char = is.peek();
969
  }
970
971
  if (next_char == '0') {
972
    is.get();  // We may have to unget this.
973
    auto maybe_hex_start = is.peek();
974
    if (maybe_hex_start != 'x' && maybe_hex_start != 'X') {
975
      is.unget();
976
      return ParseNormalFloat(is, negate_value, value);
977
    } else {
978
      is.get();  // Throw away the 'x';
979
    }
980
  } else {
981
    return ParseNormalFloat(is, negate_value, value);
982
  }
983
984
  // This "looks" like a hex-float so treat it as one.
985
  bool seen_p = false;
986
  bool seen_dot = false;
987
  uint_type fraction_index = 0;
988
989
  uint_type fraction = 0;
990
  int_type exponent = HF::exponent_bias;
991
992
  // Strip off leading zeros so we don't have to special-case them later.
993
  while ((next_char = is.peek()) == '0') {
994
    is.get();
995
  }
996
997
  bool is_denorm =
998
      true;  // Assume denorm "representation" until we hear otherwise.
999
             // NB: This does not mean the value is actually denorm,
1000
             // it just means that it was written 0.
1001
  bool bits_written = false;  // Stays false until we write a bit.
1002
  while (!seen_p && !seen_dot) {
1003
    // Handle characters that are left of the fractional part.
1004
    if (next_char == '.') {
1005
      seen_dot = true;
1006
    } else if (next_char == 'p') {
1007
      seen_p = true;
1008
    } else if (::isxdigit(next_char)) {
1009
      // We know this is not denormalized since we have stripped all leading
1010
      // zeroes and we are not a ".".
1011
      is_denorm = false;
1012
      int number = get_nibble_from_character(next_char);
1013
      for (int i = 0; i < 4; ++i, number <<= 1) {
1014
        uint_type write_bit = (number & 0x8) ? 0x1 : 0x0;
1015
        if (bits_written) {
1016
          // If we are here the bits represented belong in the fractional
1017
          // part of the float, and we have to adjust the exponent accordingly.
1018
          fraction = static_cast<uint_type>(
1019
              fraction |
1020
              static_cast<uint_type>(
1021
                  write_bit << (HF::top_bit_left_shift - fraction_index++)));
1022
          exponent = static_cast<int_type>(exponent + 1);
1023
        }
1024
        bits_written |= write_bit != 0;
1025
      }
1026
    } else {
1027
      // We have not found our exponent yet, so we have to fail.
1028
      is.setstate(std::ios::failbit);
1029
      return is;
1030
    }
1031
    is.get();
1032
    next_char = is.peek();
1033
  }
1034
  bits_written = false;
1035
  while (seen_dot && !seen_p) {
1036
    // Handle only fractional parts now.
1037
    if (next_char == 'p') {
1038
      seen_p = true;
1039
    } else if (::isxdigit(next_char)) {
1040
      int number = get_nibble_from_character(next_char);
1041
      for (int i = 0; i < 4; ++i, number <<= 1) {
1042
        uint_type write_bit = (number & 0x8) ? 0x01 : 0x00;
1043
        bits_written |= write_bit != 0;
1044
        if (is_denorm && !bits_written) {
1045
          // Handle modifying the exponent here this way we can handle
1046
          // an arbitrary number of hex values without overflowing our
1047
          // integer.
1048
          exponent = static_cast<int_type>(exponent - 1);
1049
        } else {
1050
          fraction = static_cast<uint_type>(
1051
              fraction |
1052
              static_cast<uint_type>(
1053
                  write_bit << (HF::top_bit_left_shift - fraction_index++)));
1054
        }
1055
      }
1056
    } else {
1057
      // We still have not found our 'p' exponent yet, so this is not a valid
1058
      // hex-float.
1059
      is.setstate(std::ios::failbit);
1060
      return is;
1061
    }
1062
    is.get();
1063
    next_char = is.peek();
1064
  }
1065
1066
  bool seen_sign = false;
1067
  int8_t exponent_sign = 1;
1068
  int_type written_exponent = 0;
1069
  while (true) {
1070
    if ((next_char == '-' || next_char == '+')) {
1071
      if (seen_sign) {
1072
        is.setstate(std::ios::failbit);
1073
        return is;
1074
      }
1075
      seen_sign = true;
1076
      exponent_sign = (next_char == '-') ? -1 : 1;
1077
    } else if (::isdigit(next_char)) {
1078
      // Hex-floats express their exponent as decimal.
1079
      written_exponent = static_cast<int_type>(written_exponent * 10);
1080
      written_exponent =
1081
          static_cast<int_type>(written_exponent + (next_char - '0'));
1082
    } else {
1083
      break;
1084
    }
1085
    is.get();
1086
    next_char = is.peek();
1087
  }
1088
1089
  written_exponent = static_cast<int_type>(written_exponent * exponent_sign);
1090
  exponent = static_cast<int_type>(exponent + written_exponent);
1091
1092
  bool is_zero = is_denorm && (fraction == 0);
1093
  if (is_denorm && !is_zero) {
1094
    fraction = static_cast<uint_type>(fraction << 1);
1095
    exponent = static_cast<int_type>(exponent - 1);
1096
  } else if (is_zero) {
1097
    exponent = 0;
1098
  }
1099
1100
  if (exponent <= 0 && !is_zero) {
1101
    fraction = static_cast<uint_type>(fraction >> 1);
1102
    fraction |= static_cast<uint_type>(1) << HF::top_bit_left_shift;
1103
  }
1104
1105
  fraction = (fraction >> HF::fraction_right_shift) & HF::fraction_encode_mask;
1106
1107
  const int_type max_exponent =
1108
      SetBits<uint_type, 0, HF::num_exponent_bits>::get;
1109
1110
  // Handle actual denorm numbers
1111
  while (exponent < 0 && !is_zero) {
1112
    fraction = static_cast<uint_type>(fraction >> 1);
1113
    exponent = static_cast<int_type>(exponent + 1);
1114
1115
    fraction &= HF::fraction_encode_mask;
1116
    if (fraction == 0) {
1117
      // We have underflowed our fraction. We should clamp to zero.
1118
      is_zero = true;
1119
      exponent = 0;
1120
    }
1121
  }
1122
1123
  // We have overflowed so we should be inf/-inf.
1124
  if (exponent > max_exponent) {
1125
    exponent = max_exponent;
1126
    fraction = 0;
1127
  }
1128
1129
  uint_type output_bits = static_cast<uint_type>(
1130
      static_cast<uint_type>(negate_value ? 1 : 0) << HF::top_bit_left_shift);
1131
  output_bits |= fraction;
1132
1133
  uint_type shifted_exponent = static_cast<uint_type>(
1134
      static_cast<uint_type>(exponent << HF::exponent_left_shift) &
1135
      HF::exponent_mask);
1136
  output_bits |= shifted_exponent;
1137
1138
  T output_float = spvutils::BitwiseCast<T>(output_bits);
1139
  value.set_value(output_float);
1140
1141
  return is;
1142
}
1143
1144
// Writes a FloatProxy value to a stream.
1145
// Zero and normal numbers are printed in the usual notation, but with
1146
// enough digits to fully reproduce the value.  Other values (subnormal,
1147
// NaN, and infinity) are printed as a hex float.
1148
template <typename T>
1149
std::ostream& operator<<(std::ostream& os, const FloatProxy<T>& value) {
1150
  auto float_val = value.getAsFloat();
1151
  switch (std::fpclassify(float_val)) {
1152
    case FP_ZERO:
1153
    case FP_NORMAL: {
1154
      auto saved_precision = os.precision();
1155
      os.precision(std::numeric_limits<T>::digits10);
1156
      os << float_val;
1157
      os.precision(saved_precision);
1158
    } break;
1159
    default:
1160
      os << HexFloat<FloatProxy<T>>(value);
1161
      break;
1162
  }
1163
  return os;
1164
}
1165
1166
template <>
1167
inline std::ostream& operator<<<Float16>(std::ostream& os,
1168
0
                                         const FloatProxy<Float16>& value) {
1169
0
  os << HexFloat<FloatProxy<Float16>>(value);
1170
0
  return os;
1171
0
}
1172
}
1173
1174
#endif  // LIBSPIRV_UTIL_HEX_FLOAT_H_