yum-mirror/glslang

git clone https://git.yummers.dev/yum-mirror/glslang

Jeff Bolzfix handling of values around infinity for e4m3 constantsd09cc266

vulkan-sdk-1.4.350.0
42.1 KiB1174 linesraw
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
28namespace spvutils {
29
30class Float16 {
31 public:
32  Float16(uint16_t v) : val(v) {}
33  Float16() {}
34  static bool isNan(const Float16& val) {
35    return ((val.val & 0x7C00) == 0x7C00) && ((val.val & 0x3FF) != 0);
36  }
37  // Returns true if the given value is any kind of infinity.
38  static bool isInfinity(const Float16& val) {
39    return ((val.val & 0x7C00) == 0x7C00) && ((val.val & 0x3FF) == 0);
40  }
41  Float16(const Float16& other) { val = other.val; }
42  uint16_t get_value() const { return val; }
43
44  // Returns the maximum normal value.
45  static Float16 max() { return Float16(0x7bff); }
46  // Returns the lowest normal value.
47  static Float16 lowest() { return Float16(0xfbff); }
48
49 private:
50  uint16_t val;
51};
52
53class FloatE5M2 {
54 public:
55  FloatE5M2(uint8_t v) : val(v) {}
56  FloatE5M2() {}
57  static bool isNan(const FloatE5M2& val) {
58    return ((val.val & 0x7C) == 0x7C) && ((val.val & 0x3) != 0);
59  }
60  // Returns true if the given value is any kind of infinity.
61  static bool isInfinity(const FloatE5M2& val) {
62    return ((val.val & 0x7C) == 0x7C) && ((val.val & 0x3) == 0);
63  }
64  FloatE5M2(const FloatE5M2& other) { val = other.val; }
65  uint8_t get_value() const { return val; }
66
67  // Returns the maximum normal value.
68  static FloatE5M2 max() { return FloatE5M2(0x7B); }
69  // Returns the lowest normal value.
70  static FloatE5M2 lowest() { return FloatE5M2(0xFB); }
71
72 private:
73  uint8_t val;
74};
75
76class FloatE4M3 {
77 public:
78  FloatE4M3(uint8_t v) : val(v) {}
79  FloatE4M3() {}
80  static bool isNan(const FloatE4M3& val) {
81    return (val.val & 0x7F) == 0x7F;
82  }
83  // Returns true if the given value is any kind of infinity.
84  static bool isInfinity(const FloatE4M3&) {
85    return false;
86  }
87  FloatE4M3(const FloatE4M3& other) { val = other.val; }
88  uint8_t get_value() const { return val; }
89
90  // Returns the maximum normal value.
91  static FloatE4M3 max() { return FloatE4M3(0x7E); }
92  // Returns the lowest normal value.
93  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.
103template <typename T>
104struct FloatProxyTraits {
105  typedef void uint_type;
106};
107
108template <>
109struct FloatProxyTraits<float> {
110  typedef uint32_t uint_type;
111  static bool isNan(float f) { return std::isnan(f); }
112  // Returns true if the given value is any kind of infinity.
113  static bool isInfinity(float f) { return std::isinf(f); }
114  // Returns the maximum normal value.
115  static float max() { return std::numeric_limits<float>::max(); }
116  // Returns the lowest normal value.
117  static float lowest() { return std::numeric_limits<float>::lowest(); }
118};
119
120template <>
121struct FloatProxyTraits<double> {
122  typedef uint64_t uint_type;
123  static bool isNan(double f) { return std::isnan(f); }
124  // Returns true if the given value is any kind of infinity.
125  static bool isInfinity(double f) { return std::isinf(f); }
126  // Returns the maximum normal value.
127  static double max() { return std::numeric_limits<double>::max(); }
128  // Returns the lowest normal value.
129  static double lowest() { return std::numeric_limits<double>::lowest(); }
130};
131
132template <>
133struct FloatProxyTraits<Float16> {
134  typedef uint16_t uint_type;
135  static bool isNan(Float16 f) { return Float16::isNan(f); }
136  // Returns true if the given value is any kind of infinity.
137  static bool isInfinity(Float16 f) { return Float16::isInfinity(f); }
138  // Returns the maximum normal value.
139  static Float16 max() { return Float16::max(); }
140  // Returns the lowest normal value.
141  static Float16 lowest() { return Float16::lowest(); }
142};
143
144template <>
145struct FloatProxyTraits<FloatE5M2> {
146  typedef uint8_t uint_type;
147  static bool isNan(FloatE5M2 f) { return FloatE5M2::isNan(f); }
148  // Returns true if the given value is any kind of infinity.
149  static bool isInfinity(FloatE5M2 f) { return FloatE5M2::isInfinity(f); }
150  // Returns the maximum normal value.
151  static FloatE5M2 max() { return FloatE5M2::max(); }
152  // Returns the lowest normal value.
153  static FloatE5M2 lowest() { return FloatE5M2::lowest(); }
154};
155
156template <>
157struct FloatProxyTraits<FloatE4M3> {
158  typedef uint8_t uint_type;
159  static bool isNan(FloatE4M3 f) { return FloatE4M3::isNan(f); }
160  // Returns true if the given value is any kind of infinity.
161  static bool isInfinity(FloatE4M3 f) { return FloatE4M3::isInfinity(f); }
162  // Returns the maximum normal value.
163  static FloatE4M3 max() { return FloatE4M3::max(); }
164  // Returns the lowest normal value.
165  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.
171template <typename T>
172class 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  FloatProxy() {}
179
180  // Intentionally non-explicit. This is a proxy type so
181  // implicit conversions allow us to use it more transparently.
182  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  FloatProxy(uint_type val) { data_ = val; }
187
188  // This is helpful to have and is guaranteed not to stomp bits.
189  FloatProxy<T> operator-() const {
190    return static_cast<uint_type>(data_ ^
191                                  (uint_type(0x1) << (sizeof(T) * 8 - 1)));
192  }
193
194  // Returns the data as a floating point value.
195  T getAsFloat() const { return BitwiseCast<T>(data_); }
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  bool isInfinity() { return FloatProxyTraits<T>::isInfinity(getAsFloat()); }
204
205  // Returns the maximum normal value.
206  static FloatProxy<T> max() {
207    return FloatProxy<T>(FloatProxyTraits<T>::max());
208  }
209  // Returns the lowest normal value.
210  static FloatProxy<T> lowest() {
211    return FloatProxy<T>(FloatProxyTraits<T>::lowest());
212  }
213
214 private:
215  uint_type data_;
216};
217
218template <typename T>
219bool 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.
224template <typename T>
225std::istream& operator>>(std::istream& is, FloatProxy<T>& value) {
226  T float_val;
227  is >> float_val;
228  value = FloatProxy<T>(float_val);
229  return is;
230}
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.
234template <typename T>
235struct 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.
260template <>
261struct 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  static bool supportsInfinity() { return true; }
271};
272
273// Traits for IEEE double.
274// 1 sign bit, 11 exponent bits, 52 fractional bits.
275template <>
276struct 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  static bool supportsInfinity() { return true; }
286};
287
288// Traits for IEEE half.
289// 1 sign bit, 5 exponent bits, 10 fractional bits.
290template <>
291struct 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  static bool supportsInfinity() { return true; }
301};
302
303template <>
304struct 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  static bool supportsInfinity() { return true; }
314};
315
316template <>
317struct 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  static bool supportsInfinity() { return false; }
327};
328
329enum 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.
339template <typename T, typename Traits = HexFloatTraits<T>>
340class 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  explicit HexFloat(T f) : value_(f) {}
349
350  T value() const { return value_; }
351  void set_value(T f) { value_ = f; }
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  uint_type getBits() const { return spvutils::BitwiseCast<uint_type>(value_); }
414
415  // Returns the bits associated with the value, without the leading sign bit.
416  uint_type getUnsignedBits() const {
417    return static_cast<uint_type>(spvutils::BitwiseCast<uint_type>(value_) &
418                                  ~sign_mask);
419  }
420
421  // Returns the bits associated with the exponent, shifted to start at the
422  // lsb of the type.
423  const uint_type getExponentBits() const {
424    return static_cast<uint_type>((getBits() & exponent_mask) >>
425                                  num_fraction_bits);
426  }
427
428  // Returns the exponent in unbiased form. This is the exponent in the
429  // human-friendly form.
430  const int_type getUnbiasedExponent() const {
431    return static_cast<int_type>(getExponentBits() - exponent_bias);
432  }
433
434  // Returns just the significand bits from the value.
435  const uint_type getSignificandBits() const {
436    return getBits() & fraction_encode_mask;
437  }
438
439  // If the number was normalized, returns the unbiased exponent.
440  // If the number was denormal, normalize the exponent first.
441  const int_type getUnbiasedNormalizedExponent() const {
442    if ((getBits() & ~sign_mask) == 0) {  // special case if everything is 0
443      return 0;
444    }
445    int_type exp = getUnbiasedExponent();
446    if (exp == min_exponent) {  // We are in denorm land.
447      uint_type significand_bits = getSignificandBits();
448      while ((significand_bits & (first_exponent_bit >> 1)) == 0) {
449        significand_bits = static_cast<uint_type>(significand_bits << 1);
450        exp = static_cast<int_type>(exp - 1);
451      }
452      significand_bits &= fraction_encode_mask;
453    }
454    return exp;
455  }
456
457  // Returns the signficand after it has been normalized.
458  const uint_type getNormalizedSignificand() const {
459    int_type unbiased_exponent = getUnbiasedNormalizedExponent();
460    uint_type significand = getSignificandBits();
461    for (int_type i = unbiased_exponent; i <= min_exponent; ++i) {
462      significand = static_cast<uint_type>(significand << 1);
463    }
464    significand &= fraction_encode_mask;
465    return significand;
466  }
467
468  // Returns true if this number represents a negative value.
469  bool isNegative() const { return (getBits() & sign_mask) != 0; }
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      bool round_denorm_up) {
486    bool significand_is_zero = significand == 0;
487
488    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      significand_is_zero = false;
492      significand |= first_exponent_bit;
493      significand = static_cast<uint_type>(significand >> 1);
494    }
495
496    while (exponent < min_exponent) {
497      significand = static_cast<uint_type>(significand >> 1);
498      ++exponent;
499    }
500
501    if (exponent == min_exponent) {
502      if (significand == 0 && !significand_is_zero && round_denorm_up) {
503        significand = static_cast<uint_type>(0x1);
504      }
505    }
506
507    uint_type new_value = 0;
508    if (negative) {
509      new_value = static_cast<uint_type>(new_value | sign_mask);
510    }
511    exponent = static_cast<int_type>(exponent + exponent_bias);
512    assert(exponent >= 0);
513
514    // put it all together
515    exponent = static_cast<uint_type>((exponent << exponent_left_shift) &
516                                      exponent_mask);
517    significand = static_cast<uint_type>(significand & fraction_encode_mask);
518    new_value = static_cast<uint_type>(new_value | (exponent | significand));
519    value_ = BitwiseCast<T>(new_value);
520  }
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                                        uint_type to_increment, bool* carry) {
530    significand = static_cast<uint_type>(significand + to_increment);
531    *carry = false;
532    if (significand & first_exponent_bit) {
533      *carry = true;
534      // The implicit 1-bit will have carried, so we should zero-out the
535      // top bit and shift back.
536      significand = static_cast<uint_type>(significand & ~first_exponent_bit);
537      significand = static_cast<uint_type>(significand >> 1);
538    }
539    return significand;
540  }
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  {
550    if(N >= 0)
551      return val << N;
552
553    return val >> -N;
554  }
555
556  template <typename int_type>
557  uint_type negatable_right_shift(int_type N, uint_type val)
558  {
559    if(N >= 0)
560      return val >> N;
561
562    return val << -N;
563  }
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      round_direction dir, bool* carry_bit) {
572    typedef typename other_T::uint_type other_uint_type;
573    static const int_type num_throwaway_bits =
574        static_cast<int_type>(num_fraction_bits) -
575        static_cast<int_type>(other_T::num_fraction_bits);
576
577    static const uint_type last_significant_bit =
578        (num_throwaway_bits < 0)
579            ? 0
580            : negatable_left_shift(num_throwaway_bits, 1u);
581    static const uint_type first_rounded_bit =
582        (num_throwaway_bits < 1)
583            ? 0
584            : negatable_left_shift(num_throwaway_bits - 1, 1u);
585
586    static const uint_type throwaway_mask_bits =
587        num_throwaway_bits > 0 ? num_throwaway_bits : 0;
588    static const uint_type throwaway_mask =
589        spvutils::SetBits<uint_type, 0, throwaway_mask_bits>::get;
590
591    *carry_bit = false;
592    other_uint_type out_val = 0;
593    uint_type significand = getNormalizedSignificand();
594    // If we are up-casting, then we just have to shift to the right location.
595    if (num_throwaway_bits <= 0) {
596      out_val = static_cast<other_uint_type>(significand);
597      uint_type shift_amount = static_cast<uint_type>(-num_throwaway_bits);
598      out_val = static_cast<other_uint_type>(out_val << shift_amount);
599      return out_val;
600    }
601
602    // If every non-representable bit is 0, then we don't have any casting to
603    // do.
604    if ((significand & throwaway_mask) == 0) {
605      return static_cast<other_uint_type>(
606          negatable_right_shift(num_throwaway_bits, significand));
607    }
608
609    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    switch (dir) {
613      case kRoundToZero:
614        break;
615      case kRoundToPositiveInfinity:
616        round_away_from_zero = !isNegative();
617        break;
618      case kRoundToNegativeInfinity:
619        round_away_from_zero = isNegative();
620        break;
621      case kRoundToNearestEven:
622        // Have to round down, round bit is 0
623        if ((first_rounded_bit & significand) == 0) {
624          break;
625        }
626        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          round_away_from_zero = true;
630          break;
631        }
632        // We are exactly half-way between 2 numbers, pick even.
633        if ((significand & last_significant_bit) != 0) {
634          // 1 for our last bit, round up.
635          round_away_from_zero = true;
636          break;
637        }
638        break;
639    }
640
641    if (round_away_from_zero) {
642      return static_cast<other_uint_type>(
643          negatable_right_shift(num_throwaway_bits, incrementSignificand(
644              significand, last_significant_bit, carry_bit)));
645    } else {
646      return static_cast<other_uint_type>(
647          negatable_right_shift(num_throwaway_bits, significand));
648    }
649  }
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  void castTo(other_T& other, round_direction round_dir) {
659    other = other_T(static_cast<typename other_T::native_type>(0));
660    bool negate = isNegative();
661    if (getUnsignedBits() == 0) {
662      if (negate) {
663        other.set_value(-other.value());
664      }
665      return;
666    }
667    uint_type significand = getSignificandBits();
668    bool carried = false;
669    typename other_T::uint_type rounded_significand =
670        getRoundedNormalizedSignificand<other_T>(round_dir, &carried);
671
672    int_type exponent = getUnbiasedExponent();
673    if (exponent == min_exponent) {
674      // If we are denormal, normalize the exponent, so that we can encode
675      // easily.
676      exponent = static_cast<int_type>(exponent + 1);
677      for (uint_type check_bit = first_exponent_bit >> 1; check_bit != 0;
678           check_bit = static_cast<uint_type>(check_bit >> 1)) {
679        exponent = static_cast<int_type>(exponent - 1);
680        if (check_bit & significand) break;
681      }
682    }
683
684    bool is_nan =
685        (getBits() & exponent_mask) == exponent_mask && significand != 0;
686    bool is_inf =
687        !is_nan &&
688        (((exponent + carried) > static_cast<int_type>(other_T::exponent_bias) && other_T::Traits_T::supportsInfinity()) ||
689         ((exponent + carried) > static_cast<int_type>(other_T::exponent_bias + 1) && !other_T::Traits_T::supportsInfinity()) ||
690         (significand == 0 && (getBits() & exponent_mask) == exponent_mask));
691
692    // If we are Nan or Inf we should pass that through.
693    if (is_inf) {
694      if (other_T::Traits_T::supportsInfinity()) {
695        // encode as +/-inf
696        other.set_value(BitwiseCast<typename other_T::underlying_type>(
697            static_cast<typename other_T::uint_type>(
698                (negate ? other_T::sign_mask : 0) | other_T::exponent_mask)));
699      } else {
700        // encode as +/-nan
701        other.set_value(BitwiseCast<typename other_T::underlying_type>(
702            static_cast<typename other_T::uint_type>(negate ? ~0 : ~other_T::sign_mask)));
703      }
704      return;
705    }
706    if (is_nan) {
707      typename other_T::uint_type shifted_significand;
708      shifted_significand = static_cast<typename other_T::uint_type>(
709          negatable_left_shift(
710              static_cast<int_type>(other_T::num_fraction_bits) -
711              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      other.set_value(BitwiseCast<typename other_T::underlying_type>(
717          static_cast<typename other_T::uint_type>(
718              (negate ? other_T::sign_mask : 0) | other_T::exponent_mask |
719              (shifted_significand == 0 ? 0x1 : shifted_significand))));
720      return;
721    }
722
723    bool round_underflow_up =
724        isNegative() ? round_dir == kRoundToNegativeInfinity
725                     : round_dir == kRoundToPositiveInfinity;
726    typedef typename other_T::int_type other_int_type;
727    // setFromSignUnbiasedExponentAndNormalizedSignificand will
728    // zero out any underflowing value (but retain the sign).
729    other.setFromSignUnbiasedExponentAndNormalizedSignificand(
730        negate, static_cast<other_int_type>(exponent), rounded_significand,
731        round_underflow_up);
732    return;
733  }
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.
745inline uint8_t get_nibble_from_character(int character) {
746  const char* dec = "0123456789";
747  const char* lower = "abcdef";
748  const char* upper = "ABCDEF";
749  const char* p = nullptr;
750  if ((p = strchr(dec, character))) {
751    return static_cast<uint8_t>(p - dec);
752  } else if ((p = strchr(lower, character))) {
753    return static_cast<uint8_t>(p - lower + 0xa);
754  } else if ((p = strchr(upper, character))) {
755    return static_cast<uint8_t>(p - upper + 0xa);
756  }
757
758  assert(false && "This was called with a non-hex character");
759  return 0;
760}
761
762// Outputs the given HexFloat to the stream.
763template <typename T, typename Traits>
764std::ostream& operator<<(std::ostream& os, const HexFloat<T, Traits>& value) {
765  typedef HexFloat<T, Traits> HF;
766  typedef typename HF::uint_type uint_type;
767  typedef typename HF::int_type int_type;
768
769  static_assert(HF::num_used_bits != 0,
770                "num_used_bits must be non-zero for a valid float");
771  static_assert(HF::num_exponent_bits != 0,
772                "num_exponent_bits must be non-zero for a valid float");
773  static_assert(HF::num_fraction_bits != 0,
774                "num_fractin_bits must be non-zero for a valid float");
775
776  const uint_type bits = spvutils::BitwiseCast<uint_type>(value.value());
777  const char* const sign = (bits & HF::sign_mask) ? "-" : "";
778  const uint_type exponent = static_cast<uint_type>(
779      (bits & HF::exponent_mask) >> HF::num_fraction_bits);
780
781  uint_type fraction = static_cast<uint_type>((bits & HF::fraction_encode_mask)
782                                              << HF::num_overflow_bits);
783
784  const bool is_zero = exponent == 0 && fraction == 0;
785  const bool is_denorm = exponent == 0 && !is_zero;
786
787  // exponent contains the biased exponent we have to convert it back into
788  // the normal range.
789  int_type int_exponent = static_cast<int_type>(exponent - HF::exponent_bias);
790  // If the number is all zeros, then we actually have to NOT shift the
791  // exponent.
792  int_exponent = is_zero ? 0 : int_exponent;
793
794  // If we are denorm, then start shifting, and decreasing the exponent until
795  // our leading bit is 1.
796
797  if (is_denorm) {
798    while ((fraction & HF::fraction_top_bit) == 0) {
799      fraction = static_cast<uint_type>(fraction << 1);
800      int_exponent = static_cast<int_type>(int_exponent - 1);
801    }
802    // Since this is denormalized, we have to consume the leading 1 since it
803    // will end up being implicit.
804    fraction = static_cast<uint_type>(fraction << 1);  // eat the leading 1
805    fraction &= HF::fraction_represent_mask;
806  }
807
808  uint_type fraction_nibbles = HF::fraction_nibbles;
809  // We do not have to display any trailing 0s, since this represents the
810  // fractional part.
811  while (fraction_nibbles > 0 && (fraction & 0xF) == 0) {
812    // Shift off any trailing values;
813    fraction = static_cast<uint_type>(fraction >> 4);
814    --fraction_nibbles;
815  }
816
817  const auto saved_flags = os.flags();
818  const auto saved_fill = os.fill();
819
820  os << sign << "0x" << (is_zero ? '0' : '1');
821  if (fraction_nibbles) {
822    // Make sure to keep the leading 0s in place, since this is the fractional
823    // part.
824    os << "." << std::setw(static_cast<int>(fraction_nibbles))
825       << std::setfill('0') << std::hex << fraction;
826  }
827  os << "p" << std::dec << (int_exponent >= 0 ? "+" : "") << int_exponent;
828
829  os.flags(saved_flags);
830  os.fill(saved_fill);
831
832  return os;
833}
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.
838template <typename T, typename Traits>
839inline bool RejectParseDueToLeadingSign(std::istream& is, bool negate_value,
840                                        HexFloat<T, Traits>& value) {
841  if (negate_value) {
842    auto next_char = is.peek();
843    if (next_char == '-' || next_char == '+') {
844      // Fail the parse.  Emulate standard behaviour by setting the value to
845      // the zero value, and set the fail bit on the stream.
846      value = HexFloat<T, Traits>(typename HexFloat<T, Traits>::uint_type(0));
847      is.setstate(std::ios_base::failbit);
848      return true;
849    }
850  }
851  return false;
852}
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.
864template <typename T, typename Traits>
865inline std::istream& ParseNormalFloat(std::istream& is, bool negate_value,
866                                      HexFloat<T, Traits>& value) {
867  if (RejectParseDueToLeadingSign(is, negate_value, value)) {
868    return is;
869  }
870  T val;
871  is >> val;
872  if (negate_value) {
873    val = -val;
874  }
875  value.set_value(val);
876  // In the failure case, map -0.0 to 0.0.
877  if (is.fail() && value.getUnsignedBits() == 0u) {
878    value = HexFloat<T, Traits>(typename HexFloat<T, Traits>::uint_type(0));
879  }
880  if (val.isInfinity()) {
881    // Fail the parse.  Emulate standard behaviour by setting the value to
882    // the closest normal value, and set the fail bit on the stream.
883    value.set_value((value.isNegative() || negate_value) ? T::lowest()
884                                                         : T::max());
885    is.setstate(std::ios_base::failbit);
886  }
887  return is;
888}
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.
902template <>
903inline std::istream&
904ParseNormalFloat<FloatProxy<Float16>, HexFloatTraits<FloatProxy<Float16>>>(
905    std::istream& is, bool negate_value,
906    HexFloat<FloatProxy<Float16>, HexFloatTraits<FloatProxy<Float16>>>& value) {
907  // First parse as a 32-bit float.
908  HexFloat<FloatProxy<float>> float_val(0.0f);
909  ParseNormalFloat(is, negate_value, float_val);
910
911  // Then convert to 16-bit float, saturating at infinities, and
912  // rounding toward zero.
913  float_val.castTo(value, kRoundToZero);
914
915  // Overflow on 16-bit behaves the same as for 32- and 64-bit: set the
916  // fail bit and set the lowest or highest value.
917  if (Float16::isInfinity(value.value().getAsFloat())) {
918    value.set_value(value.isNegative() ? Float16::lowest() : Float16::max());
919    is.setstate(std::ios_base::failbit);
920  }
921  return is;
922}
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)
943template <typename T, typename Traits>
944std::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.
1148template <typename T>
1149std::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
1166template <>
1167inline std::ostream& operator<<<Float16>(std::ostream& os,
1168                                         const FloatProxy<Float16>& value) {
1169  os << HexFloat<FloatProxy<Float16>>(value);
1170  return os;
1171}
1172}
1173
1174#endif  // LIBSPIRV_UTIL_HEX_FLOAT_H_