Path: blob/master/thirdparty/glslang/SPIRV/hex_float.h
9902 views
// Copyright (c) 2015-2016 The Khronos Group Inc.1//2// Licensed under the Apache License, Version 2.0 (the "License");3// you may not use this file except in compliance with the License.4// You may obtain a copy of the License at5//6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314#ifndef LIBSPIRV_UTIL_HEX_FLOAT_H_15#define LIBSPIRV_UTIL_HEX_FLOAT_H_1617#include <cassert>18#include <cctype>19#include <cmath>20#include <cstdint>21#include <iomanip>22#include <limits>23#include <sstream>2425#include "bitutils.h"2627namespace spvutils {2829class Float16 {30public:31Float16(uint16_t v) : val(v) {}32Float16() {}33static bool isNan(const Float16& val) {34return ((val.val & 0x7C00) == 0x7C00) && ((val.val & 0x3FF) != 0);35}36// Returns true if the given value is any kind of infinity.37static bool isInfinity(const Float16& val) {38return ((val.val & 0x7C00) == 0x7C00) && ((val.val & 0x3FF) == 0);39}40Float16(const Float16& other) { val = other.val; }41uint16_t get_value() const { return val; }4243// Returns the maximum normal value.44static Float16 max() { return Float16(0x7bff); }45// Returns the lowest normal value.46static Float16 lowest() { return Float16(0xfbff); }4748private:49uint16_t val;50};5152// To specialize this type, you must override uint_type to define53// an unsigned integer that can fit your floating point type.54// You must also add a isNan function that returns true if55// a value is Nan.56template <typename T>57struct FloatProxyTraits {58typedef void uint_type;59};6061template <>62struct FloatProxyTraits<float> {63typedef uint32_t uint_type;64static bool isNan(float f) { return std::isnan(f); }65// Returns true if the given value is any kind of infinity.66static bool isInfinity(float f) { return std::isinf(f); }67// Returns the maximum normal value.68static float max() { return std::numeric_limits<float>::max(); }69// Returns the lowest normal value.70static float lowest() { return std::numeric_limits<float>::lowest(); }71};7273template <>74struct FloatProxyTraits<double> {75typedef uint64_t uint_type;76static bool isNan(double f) { return std::isnan(f); }77// Returns true if the given value is any kind of infinity.78static bool isInfinity(double f) { return std::isinf(f); }79// Returns the maximum normal value.80static double max() { return std::numeric_limits<double>::max(); }81// Returns the lowest normal value.82static double lowest() { return std::numeric_limits<double>::lowest(); }83};8485template <>86struct FloatProxyTraits<Float16> {87typedef uint16_t uint_type;88static bool isNan(Float16 f) { return Float16::isNan(f); }89// Returns true if the given value is any kind of infinity.90static bool isInfinity(Float16 f) { return Float16::isInfinity(f); }91// Returns the maximum normal value.92static Float16 max() { return Float16::max(); }93// Returns the lowest normal value.94static Float16 lowest() { return Float16::lowest(); }95};9697// Since copying a floating point number (especially if it is NaN)98// does not guarantee that bits are preserved, this class lets us99// store the type and use it as a float when necessary.100template <typename T>101class FloatProxy {102public:103typedef typename FloatProxyTraits<T>::uint_type uint_type;104105// Since this is to act similar to the normal floats,106// do not initialize the data by default.107FloatProxy() {}108109// Intentionally non-explicit. This is a proxy type so110// implicit conversions allow us to use it more transparently.111FloatProxy(T val) { data_ = BitwiseCast<uint_type>(val); }112113// Intentionally non-explicit. This is a proxy type so114// implicit conversions allow us to use it more transparently.115FloatProxy(uint_type val) { data_ = val; }116117// This is helpful to have and is guaranteed not to stomp bits.118FloatProxy<T> operator-() const {119return static_cast<uint_type>(data_ ^120(uint_type(0x1) << (sizeof(T) * 8 - 1)));121}122123// Returns the data as a floating point value.124T getAsFloat() const { return BitwiseCast<T>(data_); }125126// Returns the raw data.127uint_type data() const { return data_; }128129// Returns true if the value represents any type of NaN.130bool isNan() { return FloatProxyTraits<T>::isNan(getAsFloat()); }131// Returns true if the value represents any type of infinity.132bool isInfinity() { return FloatProxyTraits<T>::isInfinity(getAsFloat()); }133134// Returns the maximum normal value.135static FloatProxy<T> max() {136return FloatProxy<T>(FloatProxyTraits<T>::max());137}138// Returns the lowest normal value.139static FloatProxy<T> lowest() {140return FloatProxy<T>(FloatProxyTraits<T>::lowest());141}142143private:144uint_type data_;145};146147template <typename T>148bool operator==(const FloatProxy<T>& first, const FloatProxy<T>& second) {149return first.data() == second.data();150}151152// Reads a FloatProxy value as a normal float from a stream.153template <typename T>154std::istream& operator>>(std::istream& is, FloatProxy<T>& value) {155T float_val;156is >> float_val;157value = FloatProxy<T>(float_val);158return is;159}160161// This is an example traits. It is not meant to be used in practice, but will162// be the default for any non-specialized type.163template <typename T>164struct HexFloatTraits {165// Integer type that can store this hex-float.166typedef void uint_type;167// Signed integer type that can store this hex-float.168typedef void int_type;169// The numerical type that this HexFloat represents.170typedef void underlying_type;171// The type needed to construct the underlying type.172typedef void native_type;173// The number of bits that are actually relevant in the uint_type.174// This allows us to deal with, for example, 24-bit values in a 32-bit175// integer.176static const uint32_t num_used_bits = 0;177// Number of bits that represent the exponent.178static const uint32_t num_exponent_bits = 0;179// Number of bits that represent the fractional part.180static const uint32_t num_fraction_bits = 0;181// The bias of the exponent. (How much we need to subtract from the stored182// value to get the correct value.)183static const uint32_t exponent_bias = 0;184};185186// Traits for IEEE float.187// 1 sign bit, 8 exponent bits, 23 fractional bits.188template <>189struct HexFloatTraits<FloatProxy<float>> {190typedef uint32_t uint_type;191typedef int32_t int_type;192typedef FloatProxy<float> underlying_type;193typedef float native_type;194static const uint_type num_used_bits = 32;195static const uint_type num_exponent_bits = 8;196static const uint_type num_fraction_bits = 23;197static const uint_type exponent_bias = 127;198};199200// Traits for IEEE double.201// 1 sign bit, 11 exponent bits, 52 fractional bits.202template <>203struct HexFloatTraits<FloatProxy<double>> {204typedef uint64_t uint_type;205typedef int64_t int_type;206typedef FloatProxy<double> underlying_type;207typedef double native_type;208static const uint_type num_used_bits = 64;209static const uint_type num_exponent_bits = 11;210static const uint_type num_fraction_bits = 52;211static const uint_type exponent_bias = 1023;212};213214// Traits for IEEE half.215// 1 sign bit, 5 exponent bits, 10 fractional bits.216template <>217struct HexFloatTraits<FloatProxy<Float16>> {218typedef uint16_t uint_type;219typedef int16_t int_type;220typedef uint16_t underlying_type;221typedef uint16_t native_type;222static const uint_type num_used_bits = 16;223static const uint_type num_exponent_bits = 5;224static const uint_type num_fraction_bits = 10;225static const uint_type exponent_bias = 15;226};227228enum round_direction {229kRoundToZero,230kRoundToNearestEven,231kRoundToPositiveInfinity,232kRoundToNegativeInfinity233};234235// Template class that houses a floating pointer number.236// It exposes a number of constants based on the provided traits to237// assist in interpreting the bits of the value.238template <typename T, typename Traits = HexFloatTraits<T>>239class HexFloat {240public:241typedef typename Traits::uint_type uint_type;242typedef typename Traits::int_type int_type;243typedef typename Traits::underlying_type underlying_type;244typedef typename Traits::native_type native_type;245246explicit HexFloat(T f) : value_(f) {}247248T value() const { return value_; }249void set_value(T f) { value_ = f; }250251// These are all written like this because it is convenient to have252// compile-time constants for all of these values.253254// Pass-through values to save typing.255static const uint32_t num_used_bits = Traits::num_used_bits;256static const uint32_t exponent_bias = Traits::exponent_bias;257static const uint32_t num_exponent_bits = Traits::num_exponent_bits;258static const uint32_t num_fraction_bits = Traits::num_fraction_bits;259260// Number of bits to shift left to set the highest relevant bit.261static const uint32_t top_bit_left_shift = num_used_bits - 1;262// How many nibbles (hex characters) the fractional part takes up.263static const uint32_t fraction_nibbles = (num_fraction_bits + 3) / 4;264// If the fractional part does not fit evenly into a hex character (4-bits)265// then we have to left-shift to get rid of leading 0s. This is the amount266// we have to shift (might be 0).267static const uint32_t num_overflow_bits =268fraction_nibbles * 4 - num_fraction_bits;269270// The representation of the fraction, not the actual bits. This271// includes the leading bit that is usually implicit.272static const uint_type fraction_represent_mask =273spvutils::SetBits<uint_type, 0,274num_fraction_bits + num_overflow_bits>::get;275276// The topmost bit in the nibble-aligned fraction.277static const uint_type fraction_top_bit =278uint_type(1) << (num_fraction_bits + num_overflow_bits - 1);279280// The least significant bit in the exponent, which is also the bit281// immediately to the left of the significand.282static const uint_type first_exponent_bit = uint_type(1)283<< (num_fraction_bits);284285// The mask for the encoded fraction. It does not include the286// implicit bit.287static const uint_type fraction_encode_mask =288spvutils::SetBits<uint_type, 0, num_fraction_bits>::get;289290// The bit that is used as a sign.291static const uint_type sign_mask = uint_type(1) << top_bit_left_shift;292293// The bits that represent the exponent.294static const uint_type exponent_mask =295spvutils::SetBits<uint_type, num_fraction_bits, num_exponent_bits>::get;296297// How far left the exponent is shifted.298static const uint32_t exponent_left_shift = num_fraction_bits;299300// How far from the right edge the fraction is shifted.301static const uint32_t fraction_right_shift =302static_cast<uint32_t>(sizeof(uint_type) * 8) - num_fraction_bits;303304// The maximum representable unbiased exponent.305static const int_type max_exponent =306(exponent_mask >> num_fraction_bits) - exponent_bias;307// The minimum representable exponent for normalized numbers.308static const int_type min_exponent = -static_cast<int_type>(exponent_bias);309310// Returns the bits associated with the value.311uint_type getBits() const { return spvutils::BitwiseCast<uint_type>(value_); }312313// Returns the bits associated with the value, without the leading sign bit.314uint_type getUnsignedBits() const {315return static_cast<uint_type>(spvutils::BitwiseCast<uint_type>(value_) &316~sign_mask);317}318319// Returns the bits associated with the exponent, shifted to start at the320// lsb of the type.321const uint_type getExponentBits() const {322return static_cast<uint_type>((getBits() & exponent_mask) >>323num_fraction_bits);324}325326// Returns the exponent in unbiased form. This is the exponent in the327// human-friendly form.328const int_type getUnbiasedExponent() const {329return static_cast<int_type>(getExponentBits() - exponent_bias);330}331332// Returns just the significand bits from the value.333const uint_type getSignificandBits() const {334return getBits() & fraction_encode_mask;335}336337// If the number was normalized, returns the unbiased exponent.338// If the number was denormal, normalize the exponent first.339const int_type getUnbiasedNormalizedExponent() const {340if ((getBits() & ~sign_mask) == 0) { // special case if everything is 0341return 0;342}343int_type exp = getUnbiasedExponent();344if (exp == min_exponent) { // We are in denorm land.345uint_type significand_bits = getSignificandBits();346while ((significand_bits & (first_exponent_bit >> 1)) == 0) {347significand_bits = static_cast<uint_type>(significand_bits << 1);348exp = static_cast<int_type>(exp - 1);349}350significand_bits &= fraction_encode_mask;351}352return exp;353}354355// Returns the signficand after it has been normalized.356const uint_type getNormalizedSignificand() const {357int_type unbiased_exponent = getUnbiasedNormalizedExponent();358uint_type significand = getSignificandBits();359for (int_type i = unbiased_exponent; i <= min_exponent; ++i) {360significand = static_cast<uint_type>(significand << 1);361}362significand &= fraction_encode_mask;363return significand;364}365366// Returns true if this number represents a negative value.367bool isNegative() const { return (getBits() & sign_mask) != 0; }368369// Sets this HexFloat from the individual components.370// Note this assumes EVERY significand is normalized, and has an implicit371// leading one. This means that the only way that this method will set 0,372// is if you set a number so denormalized that it underflows.373// Do not use this method with raw bits extracted from a subnormal number,374// since subnormals do not have an implicit leading 1 in the significand.375// The significand is also expected to be in the376// lowest-most num_fraction_bits of the uint_type.377// The exponent is expected to be unbiased, meaning an exponent of378// 0 actually means 0.379// If underflow_round_up is set, then on underflow, if a number is non-0380// and would underflow, we round up to the smallest denorm.381void setFromSignUnbiasedExponentAndNormalizedSignificand(382bool negative, int_type exponent, uint_type significand,383bool round_denorm_up) {384bool significand_is_zero = significand == 0;385386if (exponent <= min_exponent) {387// If this was denormalized, then we have to shift the bit on, meaning388// the significand is not zero.389significand_is_zero = false;390significand |= first_exponent_bit;391significand = static_cast<uint_type>(significand >> 1);392}393394while (exponent < min_exponent) {395significand = static_cast<uint_type>(significand >> 1);396++exponent;397}398399if (exponent == min_exponent) {400if (significand == 0 && !significand_is_zero && round_denorm_up) {401significand = static_cast<uint_type>(0x1);402}403}404405uint_type new_value = 0;406if (negative) {407new_value = static_cast<uint_type>(new_value | sign_mask);408}409exponent = static_cast<int_type>(exponent + exponent_bias);410assert(exponent >= 0);411412// put it all together413exponent = static_cast<uint_type>((exponent << exponent_left_shift) &414exponent_mask);415significand = static_cast<uint_type>(significand & fraction_encode_mask);416new_value = static_cast<uint_type>(new_value | (exponent | significand));417value_ = BitwiseCast<T>(new_value);418}419420// Increments the significand of this number by the given amount.421// If this would spill the significand into the implicit bit,422// carry is set to true and the significand is shifted to fit into423// the correct location, otherwise carry is set to false.424// All significands and to_increment are assumed to be within the bounds425// for a valid significand.426static uint_type incrementSignificand(uint_type significand,427uint_type to_increment, bool* carry) {428significand = static_cast<uint_type>(significand + to_increment);429*carry = false;430if (significand & first_exponent_bit) {431*carry = true;432// The implicit 1-bit will have carried, so we should zero-out the433// top bit and shift back.434significand = static_cast<uint_type>(significand & ~first_exponent_bit);435significand = static_cast<uint_type>(significand >> 1);436}437return significand;438}439440// These exist because MSVC throws warnings on negative right-shifts441// even if they are not going to be executed. Eg:442// constant_number < 0? 0: constant_number443// These convert the negative left-shifts into right shifts.444445template <typename int_type>446uint_type negatable_left_shift(int_type N, uint_type val)447{448if(N >= 0)449return val << N;450451return val >> -N;452}453454template <typename int_type>455uint_type negatable_right_shift(int_type N, uint_type val)456{457if(N >= 0)458return val >> N;459460return val << -N;461}462463// Returns the significand, rounded to fit in a significand in464// other_T. This is shifted so that the most significant465// bit of the rounded number lines up with the most significant bit466// of the returned significand.467template <typename other_T>468typename other_T::uint_type getRoundedNormalizedSignificand(469round_direction dir, bool* carry_bit) {470typedef typename other_T::uint_type other_uint_type;471static const int_type num_throwaway_bits =472static_cast<int_type>(num_fraction_bits) -473static_cast<int_type>(other_T::num_fraction_bits);474475static const uint_type last_significant_bit =476(num_throwaway_bits < 0)477? 0478: negatable_left_shift(num_throwaway_bits, 1u);479static const uint_type first_rounded_bit =480(num_throwaway_bits < 1)481? 0482: negatable_left_shift(num_throwaway_bits - 1, 1u);483484static const uint_type throwaway_mask_bits =485num_throwaway_bits > 0 ? num_throwaway_bits : 0;486static const uint_type throwaway_mask =487spvutils::SetBits<uint_type, 0, throwaway_mask_bits>::get;488489*carry_bit = false;490other_uint_type out_val = 0;491uint_type significand = getNormalizedSignificand();492// If we are up-casting, then we just have to shift to the right location.493if (num_throwaway_bits <= 0) {494out_val = static_cast<other_uint_type>(significand);495uint_type shift_amount = static_cast<uint_type>(-num_throwaway_bits);496out_val = static_cast<other_uint_type>(out_val << shift_amount);497return out_val;498}499500// If every non-representable bit is 0, then we don't have any casting to501// do.502if ((significand & throwaway_mask) == 0) {503return static_cast<other_uint_type>(504negatable_right_shift(num_throwaway_bits, significand));505}506507bool round_away_from_zero = false;508// We actually have to narrow the significand here, so we have to follow the509// rounding rules.510switch (dir) {511case kRoundToZero:512break;513case kRoundToPositiveInfinity:514round_away_from_zero = !isNegative();515break;516case kRoundToNegativeInfinity:517round_away_from_zero = isNegative();518break;519case kRoundToNearestEven:520// Have to round down, round bit is 0521if ((first_rounded_bit & significand) == 0) {522break;523}524if (((significand & throwaway_mask) & ~first_rounded_bit) != 0) {525// If any subsequent bit of the rounded portion is non-0 then we round526// up.527round_away_from_zero = true;528break;529}530// We are exactly half-way between 2 numbers, pick even.531if ((significand & last_significant_bit) != 0) {532// 1 for our last bit, round up.533round_away_from_zero = true;534break;535}536break;537}538539if (round_away_from_zero) {540return static_cast<other_uint_type>(541negatable_right_shift(num_throwaway_bits, incrementSignificand(542significand, last_significant_bit, carry_bit)));543} else {544return static_cast<other_uint_type>(545negatable_right_shift(num_throwaway_bits, significand));546}547}548549// Casts this value to another HexFloat. If the cast is widening,550// then round_dir is ignored. If the cast is narrowing, then551// the result is rounded in the direction specified.552// This number will retain Nan and Inf values.553// It will also saturate to Inf if the number overflows, and554// underflow to (0 or min depending on rounding) if the number underflows.555template <typename other_T>556void castTo(other_T& other, round_direction round_dir) {557other = other_T(static_cast<typename other_T::native_type>(0));558bool negate = isNegative();559if (getUnsignedBits() == 0) {560if (negate) {561other.set_value(-other.value());562}563return;564}565uint_type significand = getSignificandBits();566bool carried = false;567typename other_T::uint_type rounded_significand =568getRoundedNormalizedSignificand<other_T>(round_dir, &carried);569570int_type exponent = getUnbiasedExponent();571if (exponent == min_exponent) {572// If we are denormal, normalize the exponent, so that we can encode573// easily.574exponent = static_cast<int_type>(exponent + 1);575for (uint_type check_bit = first_exponent_bit >> 1; check_bit != 0;576check_bit = static_cast<uint_type>(check_bit >> 1)) {577exponent = static_cast<int_type>(exponent - 1);578if (check_bit & significand) break;579}580}581582bool is_nan =583(getBits() & exponent_mask) == exponent_mask && significand != 0;584bool is_inf =585!is_nan &&586((exponent + carried) > static_cast<int_type>(other_T::exponent_bias) ||587(significand == 0 && (getBits() & exponent_mask) == exponent_mask));588589// If we are Nan or Inf we should pass that through.590if (is_inf) {591other.set_value(BitwiseCast<typename other_T::underlying_type>(592static_cast<typename other_T::uint_type>(593(negate ? other_T::sign_mask : 0) | other_T::exponent_mask)));594return;595}596if (is_nan) {597typename other_T::uint_type shifted_significand;598shifted_significand = static_cast<typename other_T::uint_type>(599negatable_left_shift(600static_cast<int_type>(other_T::num_fraction_bits) -601static_cast<int_type>(num_fraction_bits), significand));602603// We are some sort of Nan. We try to keep the bit-pattern of the Nan604// as close as possible. If we had to shift off bits so we are 0, then we605// just set the last bit.606other.set_value(BitwiseCast<typename other_T::underlying_type>(607static_cast<typename other_T::uint_type>(608(negate ? other_T::sign_mask : 0) | other_T::exponent_mask |609(shifted_significand == 0 ? 0x1 : shifted_significand))));610return;611}612613bool round_underflow_up =614isNegative() ? round_dir == kRoundToNegativeInfinity615: round_dir == kRoundToPositiveInfinity;616typedef typename other_T::int_type other_int_type;617// setFromSignUnbiasedExponentAndNormalizedSignificand will618// zero out any underflowing value (but retain the sign).619other.setFromSignUnbiasedExponentAndNormalizedSignificand(620negate, static_cast<other_int_type>(exponent), rounded_significand,621round_underflow_up);622return;623}624625private:626T value_;627628static_assert(num_used_bits ==629Traits::num_exponent_bits + Traits::num_fraction_bits + 1,630"The number of bits do not fit");631static_assert(sizeof(T) == sizeof(uint_type), "The type sizes do not match");632};633634// Returns 4 bits represented by the hex character.635inline uint8_t get_nibble_from_character(int character) {636const char* dec = "0123456789";637const char* lower = "abcdef";638const char* upper = "ABCDEF";639const char* p = nullptr;640if ((p = strchr(dec, character))) {641return static_cast<uint8_t>(p - dec);642} else if ((p = strchr(lower, character))) {643return static_cast<uint8_t>(p - lower + 0xa);644} else if ((p = strchr(upper, character))) {645return static_cast<uint8_t>(p - upper + 0xa);646}647648assert(false && "This was called with a non-hex character");649return 0;650}651652// Outputs the given HexFloat to the stream.653template <typename T, typename Traits>654std::ostream& operator<<(std::ostream& os, const HexFloat<T, Traits>& value) {655typedef HexFloat<T, Traits> HF;656typedef typename HF::uint_type uint_type;657typedef typename HF::int_type int_type;658659static_assert(HF::num_used_bits != 0,660"num_used_bits must be non-zero for a valid float");661static_assert(HF::num_exponent_bits != 0,662"num_exponent_bits must be non-zero for a valid float");663static_assert(HF::num_fraction_bits != 0,664"num_fractin_bits must be non-zero for a valid float");665666const uint_type bits = spvutils::BitwiseCast<uint_type>(value.value());667const char* const sign = (bits & HF::sign_mask) ? "-" : "";668const uint_type exponent = static_cast<uint_type>(669(bits & HF::exponent_mask) >> HF::num_fraction_bits);670671uint_type fraction = static_cast<uint_type>((bits & HF::fraction_encode_mask)672<< HF::num_overflow_bits);673674const bool is_zero = exponent == 0 && fraction == 0;675const bool is_denorm = exponent == 0 && !is_zero;676677// exponent contains the biased exponent we have to convert it back into678// the normal range.679int_type int_exponent = static_cast<int_type>(exponent - HF::exponent_bias);680// If the number is all zeros, then we actually have to NOT shift the681// exponent.682int_exponent = is_zero ? 0 : int_exponent;683684// If we are denorm, then start shifting, and decreasing the exponent until685// our leading bit is 1.686687if (is_denorm) {688while ((fraction & HF::fraction_top_bit) == 0) {689fraction = static_cast<uint_type>(fraction << 1);690int_exponent = static_cast<int_type>(int_exponent - 1);691}692// Since this is denormalized, we have to consume the leading 1 since it693// will end up being implicit.694fraction = static_cast<uint_type>(fraction << 1); // eat the leading 1695fraction &= HF::fraction_represent_mask;696}697698uint_type fraction_nibbles = HF::fraction_nibbles;699// We do not have to display any trailing 0s, since this represents the700// fractional part.701while (fraction_nibbles > 0 && (fraction & 0xF) == 0) {702// Shift off any trailing values;703fraction = static_cast<uint_type>(fraction >> 4);704--fraction_nibbles;705}706707const auto saved_flags = os.flags();708const auto saved_fill = os.fill();709710os << sign << "0x" << (is_zero ? '0' : '1');711if (fraction_nibbles) {712// Make sure to keep the leading 0s in place, since this is the fractional713// part.714os << "." << std::setw(static_cast<int>(fraction_nibbles))715<< std::setfill('0') << std::hex << fraction;716}717os << "p" << std::dec << (int_exponent >= 0 ? "+" : "") << int_exponent;718719os.flags(saved_flags);720os.fill(saved_fill);721722return os;723}724725// Returns true if negate_value is true and the next character on the726// input stream is a plus or minus sign. In that case we also set the fail bit727// on the stream and set the value to the zero value for its type.728template <typename T, typename Traits>729inline bool RejectParseDueToLeadingSign(std::istream& is, bool negate_value,730HexFloat<T, Traits>& value) {731if (negate_value) {732auto next_char = is.peek();733if (next_char == '-' || next_char == '+') {734// Fail the parse. Emulate standard behaviour by setting the value to735// the zero value, and set the fail bit on the stream.736value = HexFloat<T, Traits>(typename HexFloat<T, Traits>::uint_type(0));737is.setstate(std::ios_base::failbit);738return true;739}740}741return false;742}743744// Parses a floating point number from the given stream and stores it into the745// value parameter.746// If negate_value is true then the number may not have a leading minus or747// plus, and if it successfully parses, then the number is negated before748// being stored into the value parameter.749// If the value cannot be correctly parsed or overflows the target floating750// point type, then set the fail bit on the stream.751// TODO(dneto): Promise C++11 standard behavior in how the value is set in752// the error case, but only after all target platforms implement it correctly.753// In particular, the Microsoft C++ runtime appears to be out of spec.754template <typename T, typename Traits>755inline std::istream& ParseNormalFloat(std::istream& is, bool negate_value,756HexFloat<T, Traits>& value) {757if (RejectParseDueToLeadingSign(is, negate_value, value)) {758return is;759}760T val;761is >> val;762if (negate_value) {763val = -val;764}765value.set_value(val);766// In the failure case, map -0.0 to 0.0.767if (is.fail() && value.getUnsignedBits() == 0u) {768value = HexFloat<T, Traits>(typename HexFloat<T, Traits>::uint_type(0));769}770if (val.isInfinity()) {771// Fail the parse. Emulate standard behaviour by setting the value to772// the closest normal value, and set the fail bit on the stream.773value.set_value((value.isNegative() || negate_value) ? T::lowest()774: T::max());775is.setstate(std::ios_base::failbit);776}777return is;778}779780// Specialization of ParseNormalFloat for FloatProxy<Float16> values.781// This will parse the float as it were a 32-bit floating point number,782// and then round it down to fit into a Float16 value.783// The number is rounded towards zero.784// If negate_value is true then the number may not have a leading minus or785// plus, and if it successfully parses, then the number is negated before786// being stored into the value parameter.787// If the value cannot be correctly parsed or overflows the target floating788// point type, then set the fail bit on the stream.789// TODO(dneto): Promise C++11 standard behavior in how the value is set in790// the error case, but only after all target platforms implement it correctly.791// In particular, the Microsoft C++ runtime appears to be out of spec.792template <>793inline std::istream&794ParseNormalFloat<FloatProxy<Float16>, HexFloatTraits<FloatProxy<Float16>>>(795std::istream& is, bool negate_value,796HexFloat<FloatProxy<Float16>, HexFloatTraits<FloatProxy<Float16>>>& value) {797// First parse as a 32-bit float.798HexFloat<FloatProxy<float>> float_val(0.0f);799ParseNormalFloat(is, negate_value, float_val);800801// Then convert to 16-bit float, saturating at infinities, and802// rounding toward zero.803float_val.castTo(value, kRoundToZero);804805// Overflow on 16-bit behaves the same as for 32- and 64-bit: set the806// fail bit and set the lowest or highest value.807if (Float16::isInfinity(value.value().getAsFloat())) {808value.set_value(value.isNegative() ? Float16::lowest() : Float16::max());809is.setstate(std::ios_base::failbit);810}811return is;812}813814// Reads a HexFloat from the given stream.815// If the float is not encoded as a hex-float then it will be parsed816// as a regular float.817// This may fail if your stream does not support at least one unget.818// Nan values can be encoded with "0x1.<not zero>p+exponent_bias".819// This would normally overflow a float and round to820// infinity but this special pattern is the exact representation for a NaN,821// and therefore is actually encoded as the correct NaN. To encode inf,822// either 0x0p+exponent_bias can be specified or any exponent greater than823// exponent_bias.824// Examples using IEEE 32-bit float encoding.825// 0x1.0p+128 (+inf)826// -0x1.0p-128 (-inf)827//828// 0x1.1p+128 (+Nan)829// -0x1.1p+128 (-Nan)830//831// 0x1p+129 (+inf)832// -0x1p+129 (-inf)833template <typename T, typename Traits>834std::istream& operator>>(std::istream& is, HexFloat<T, Traits>& value) {835using HF = HexFloat<T, Traits>;836using uint_type = typename HF::uint_type;837using int_type = typename HF::int_type;838839value.set_value(static_cast<typename HF::native_type>(0.f));840841if (is.flags() & std::ios::skipws) {842// If the user wants to skip whitespace , then we should obey that.843while (std::isspace(is.peek())) {844is.get();845}846}847848auto next_char = is.peek();849bool negate_value = false;850851if (next_char != '-' && next_char != '0') {852return ParseNormalFloat(is, negate_value, value);853}854855if (next_char == '-') {856negate_value = true;857is.get();858next_char = is.peek();859}860861if (next_char == '0') {862is.get(); // We may have to unget this.863auto maybe_hex_start = is.peek();864if (maybe_hex_start != 'x' && maybe_hex_start != 'X') {865is.unget();866return ParseNormalFloat(is, negate_value, value);867} else {868is.get(); // Throw away the 'x';869}870} else {871return ParseNormalFloat(is, negate_value, value);872}873874// This "looks" like a hex-float so treat it as one.875bool seen_p = false;876bool seen_dot = false;877uint_type fraction_index = 0;878879uint_type fraction = 0;880int_type exponent = HF::exponent_bias;881882// Strip off leading zeros so we don't have to special-case them later.883while ((next_char = is.peek()) == '0') {884is.get();885}886887bool is_denorm =888true; // Assume denorm "representation" until we hear otherwise.889// NB: This does not mean the value is actually denorm,890// it just means that it was written 0.891bool bits_written = false; // Stays false until we write a bit.892while (!seen_p && !seen_dot) {893// Handle characters that are left of the fractional part.894if (next_char == '.') {895seen_dot = true;896} else if (next_char == 'p') {897seen_p = true;898} else if (::isxdigit(next_char)) {899// We know this is not denormalized since we have stripped all leading900// zeroes and we are not a ".".901is_denorm = false;902int number = get_nibble_from_character(next_char);903for (int i = 0; i < 4; ++i, number <<= 1) {904uint_type write_bit = (number & 0x8) ? 0x1 : 0x0;905if (bits_written) {906// If we are here the bits represented belong in the fractional907// part of the float, and we have to adjust the exponent accordingly.908fraction = static_cast<uint_type>(909fraction |910static_cast<uint_type>(911write_bit << (HF::top_bit_left_shift - fraction_index++)));912exponent = static_cast<int_type>(exponent + 1);913}914bits_written |= write_bit != 0;915}916} else {917// We have not found our exponent yet, so we have to fail.918is.setstate(std::ios::failbit);919return is;920}921is.get();922next_char = is.peek();923}924bits_written = false;925while (seen_dot && !seen_p) {926// Handle only fractional parts now.927if (next_char == 'p') {928seen_p = true;929} else if (::isxdigit(next_char)) {930int number = get_nibble_from_character(next_char);931for (int i = 0; i < 4; ++i, number <<= 1) {932uint_type write_bit = (number & 0x8) ? 0x01 : 0x00;933bits_written |= write_bit != 0;934if (is_denorm && !bits_written) {935// Handle modifying the exponent here this way we can handle936// an arbitrary number of hex values without overflowing our937// integer.938exponent = static_cast<int_type>(exponent - 1);939} else {940fraction = static_cast<uint_type>(941fraction |942static_cast<uint_type>(943write_bit << (HF::top_bit_left_shift - fraction_index++)));944}945}946} else {947// We still have not found our 'p' exponent yet, so this is not a valid948// hex-float.949is.setstate(std::ios::failbit);950return is;951}952is.get();953next_char = is.peek();954}955956bool seen_sign = false;957int8_t exponent_sign = 1;958int_type written_exponent = 0;959while (true) {960if ((next_char == '-' || next_char == '+')) {961if (seen_sign) {962is.setstate(std::ios::failbit);963return is;964}965seen_sign = true;966exponent_sign = (next_char == '-') ? -1 : 1;967} else if (::isdigit(next_char)) {968// Hex-floats express their exponent as decimal.969written_exponent = static_cast<int_type>(written_exponent * 10);970written_exponent =971static_cast<int_type>(written_exponent + (next_char - '0'));972} else {973break;974}975is.get();976next_char = is.peek();977}978979written_exponent = static_cast<int_type>(written_exponent * exponent_sign);980exponent = static_cast<int_type>(exponent + written_exponent);981982bool is_zero = is_denorm && (fraction == 0);983if (is_denorm && !is_zero) {984fraction = static_cast<uint_type>(fraction << 1);985exponent = static_cast<int_type>(exponent - 1);986} else if (is_zero) {987exponent = 0;988}989990if (exponent <= 0 && !is_zero) {991fraction = static_cast<uint_type>(fraction >> 1);992fraction |= static_cast<uint_type>(1) << HF::top_bit_left_shift;993}994995fraction = (fraction >> HF::fraction_right_shift) & HF::fraction_encode_mask;996997const int_type max_exponent =998SetBits<uint_type, 0, HF::num_exponent_bits>::get;9991000// Handle actual denorm numbers1001while (exponent < 0 && !is_zero) {1002fraction = static_cast<uint_type>(fraction >> 1);1003exponent = static_cast<int_type>(exponent + 1);10041005fraction &= HF::fraction_encode_mask;1006if (fraction == 0) {1007// We have underflowed our fraction. We should clamp to zero.1008is_zero = true;1009exponent = 0;1010}1011}10121013// We have overflowed so we should be inf/-inf.1014if (exponent > max_exponent) {1015exponent = max_exponent;1016fraction = 0;1017}10181019uint_type output_bits = static_cast<uint_type>(1020static_cast<uint_type>(negate_value ? 1 : 0) << HF::top_bit_left_shift);1021output_bits |= fraction;10221023uint_type shifted_exponent = static_cast<uint_type>(1024static_cast<uint_type>(exponent << HF::exponent_left_shift) &1025HF::exponent_mask);1026output_bits |= shifted_exponent;10271028T output_float = spvutils::BitwiseCast<T>(output_bits);1029value.set_value(output_float);10301031return is;1032}10331034// Writes a FloatProxy value to a stream.1035// Zero and normal numbers are printed in the usual notation, but with1036// enough digits to fully reproduce the value. Other values (subnormal,1037// NaN, and infinity) are printed as a hex float.1038template <typename T>1039std::ostream& operator<<(std::ostream& os, const FloatProxy<T>& value) {1040auto float_val = value.getAsFloat();1041switch (std::fpclassify(float_val)) {1042case FP_ZERO:1043case FP_NORMAL: {1044auto saved_precision = os.precision();1045os.precision(std::numeric_limits<T>::digits10);1046os << float_val;1047os.precision(saved_precision);1048} break;1049default:1050os << HexFloat<FloatProxy<T>>(value);1051break;1052}1053return os;1054}10551056template <>1057inline std::ostream& operator<<<Float16>(std::ostream& os,1058const FloatProxy<Float16>& value) {1059os << HexFloat<FloatProxy<Float16>>(value);1060return os;1061}1062}10631064#endif // LIBSPIRV_UTIL_HEX_FLOAT_H_106510661067