Path: blob/master/thirdparty/glslang/SPIRV/hex_float.h
21520 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};5152class FloatE5M2 {53public:54FloatE5M2(uint8_t v) : val(v) {}55FloatE5M2() {}56static bool isNan(const FloatE5M2& val) {57return ((val.val & 0x7C) == 0x7C) && ((val.val & 0x3) != 0);58}59// Returns true if the given value is any kind of infinity.60static bool isInfinity(const FloatE5M2& val) {61return ((val.val & 0x7C) == 0x7C) && ((val.val & 0x3) == 0);62}63FloatE5M2(const FloatE5M2& other) { val = other.val; }64uint8_t get_value() const { return val; }6566// Returns the maximum normal value.67static FloatE5M2 max() { return FloatE5M2(0x7B); }68// Returns the lowest normal value.69static FloatE5M2 lowest() { return FloatE5M2(0xFB); }7071private:72uint8_t val;73};7475class FloatE4M3 {76public:77FloatE4M3(uint8_t v) : val(v) {}78FloatE4M3() {}79static bool isNan(const FloatE4M3& val) {80return (val.val & 0x7F) == 0x7F;81}82// Returns true if the given value is any kind of infinity.83static bool isInfinity(const FloatE4M3&) {84return false;85}86FloatE4M3(const FloatE4M3& other) { val = other.val; }87uint8_t get_value() const { return val; }8889// Returns the maximum normal value.90static FloatE4M3 max() { return FloatE4M3(0x7E); }91// Returns the lowest normal value.92static FloatE4M3 lowest() { return FloatE4M3(0xFE); }9394private:95uint8_t val;96};9798// To specialize this type, you must override uint_type to define99// an unsigned integer that can fit your floating point type.100// You must also add a isNan function that returns true if101// a value is Nan.102template <typename T>103struct FloatProxyTraits {104typedef void uint_type;105};106107template <>108struct FloatProxyTraits<float> {109typedef uint32_t uint_type;110static bool isNan(float f) { return std::isnan(f); }111// Returns true if the given value is any kind of infinity.112static bool isInfinity(float f) { return std::isinf(f); }113// Returns the maximum normal value.114static float max() { return std::numeric_limits<float>::max(); }115// Returns the lowest normal value.116static float lowest() { return std::numeric_limits<float>::lowest(); }117};118119template <>120struct FloatProxyTraits<double> {121typedef uint64_t uint_type;122static bool isNan(double f) { return std::isnan(f); }123// Returns true if the given value is any kind of infinity.124static bool isInfinity(double f) { return std::isinf(f); }125// Returns the maximum normal value.126static double max() { return std::numeric_limits<double>::max(); }127// Returns the lowest normal value.128static double lowest() { return std::numeric_limits<double>::lowest(); }129};130131template <>132struct FloatProxyTraits<Float16> {133typedef uint16_t uint_type;134static bool isNan(Float16 f) { return Float16::isNan(f); }135// Returns true if the given value is any kind of infinity.136static bool isInfinity(Float16 f) { return Float16::isInfinity(f); }137// Returns the maximum normal value.138static Float16 max() { return Float16::max(); }139// Returns the lowest normal value.140static Float16 lowest() { return Float16::lowest(); }141};142143template <>144struct FloatProxyTraits<FloatE5M2> {145typedef uint8_t uint_type;146static bool isNan(FloatE5M2 f) { return FloatE5M2::isNan(f); }147// Returns true if the given value is any kind of infinity.148static bool isInfinity(FloatE5M2 f) { return FloatE5M2::isInfinity(f); }149// Returns the maximum normal value.150static FloatE5M2 max() { return FloatE5M2::max(); }151// Returns the lowest normal value.152static FloatE5M2 lowest() { return FloatE5M2::lowest(); }153};154155template <>156struct FloatProxyTraits<FloatE4M3> {157typedef uint8_t uint_type;158static bool isNan(FloatE4M3 f) { return FloatE4M3::isNan(f); }159// Returns true if the given value is any kind of infinity.160static bool isInfinity(FloatE4M3 f) { return FloatE4M3::isInfinity(f); }161// Returns the maximum normal value.162static FloatE4M3 max() { return FloatE4M3::max(); }163// Returns the lowest normal value.164static FloatE4M3 lowest() { return FloatE4M3::lowest(); }165};166167// Since copying a floating point number (especially if it is NaN)168// does not guarantee that bits are preserved, this class lets us169// store the type and use it as a float when necessary.170template <typename T>171class FloatProxy {172public:173typedef typename FloatProxyTraits<T>::uint_type uint_type;174175// Since this is to act similar to the normal floats,176// do not initialize the data by default.177FloatProxy() {}178179// Intentionally non-explicit. This is a proxy type so180// implicit conversions allow us to use it more transparently.181FloatProxy(T val) { data_ = BitwiseCast<uint_type>(val); }182183// Intentionally non-explicit. This is a proxy type so184// implicit conversions allow us to use it more transparently.185FloatProxy(uint_type val) { data_ = val; }186187// This is helpful to have and is guaranteed not to stomp bits.188FloatProxy<T> operator-() const {189return static_cast<uint_type>(data_ ^190(uint_type(0x1) << (sizeof(T) * 8 - 1)));191}192193// Returns the data as a floating point value.194T getAsFloat() const { return BitwiseCast<T>(data_); }195196// Returns the raw data.197uint_type data() const { return data_; }198199// Returns true if the value represents any type of NaN.200bool isNan() { return FloatProxyTraits<T>::isNan(getAsFloat()); }201// Returns true if the value represents any type of infinity.202bool isInfinity() { return FloatProxyTraits<T>::isInfinity(getAsFloat()); }203204// Returns the maximum normal value.205static FloatProxy<T> max() {206return FloatProxy<T>(FloatProxyTraits<T>::max());207}208// Returns the lowest normal value.209static FloatProxy<T> lowest() {210return FloatProxy<T>(FloatProxyTraits<T>::lowest());211}212213private:214uint_type data_;215};216217template <typename T>218bool operator==(const FloatProxy<T>& first, const FloatProxy<T>& second) {219return first.data() == second.data();220}221222// Reads a FloatProxy value as a normal float from a stream.223template <typename T>224std::istream& operator>>(std::istream& is, FloatProxy<T>& value) {225T float_val;226is >> float_val;227value = FloatProxy<T>(float_val);228return is;229}230231// This is an example traits. It is not meant to be used in practice, but will232// be the default for any non-specialized type.233template <typename T>234struct HexFloatTraits {235// Integer type that can store this hex-float.236typedef void uint_type;237// Signed integer type that can store this hex-float.238typedef void int_type;239// The numerical type that this HexFloat represents.240typedef void underlying_type;241// The type needed to construct the underlying type.242typedef void native_type;243// The number of bits that are actually relevant in the uint_type.244// This allows us to deal with, for example, 24-bit values in a 32-bit245// integer.246static const uint32_t num_used_bits = 0;247// Number of bits that represent the exponent.248static const uint32_t num_exponent_bits = 0;249// Number of bits that represent the fractional part.250static const uint32_t num_fraction_bits = 0;251// The bias of the exponent. (How much we need to subtract from the stored252// value to get the correct value.)253static const uint32_t exponent_bias = 0;254static bool supportsInfinity() { return true; }255};256257// Traits for IEEE float.258// 1 sign bit, 8 exponent bits, 23 fractional bits.259template <>260struct HexFloatTraits<FloatProxy<float>> {261typedef uint32_t uint_type;262typedef int32_t int_type;263typedef FloatProxy<float> underlying_type;264typedef float native_type;265static const uint_type num_used_bits = 32;266static const uint_type num_exponent_bits = 8;267static const uint_type num_fraction_bits = 23;268static const uint_type exponent_bias = 127;269static bool supportsInfinity() { return true; }270};271272// Traits for IEEE double.273// 1 sign bit, 11 exponent bits, 52 fractional bits.274template <>275struct HexFloatTraits<FloatProxy<double>> {276typedef uint64_t uint_type;277typedef int64_t int_type;278typedef FloatProxy<double> underlying_type;279typedef double native_type;280static const uint_type num_used_bits = 64;281static const uint_type num_exponent_bits = 11;282static const uint_type num_fraction_bits = 52;283static const uint_type exponent_bias = 1023;284static bool supportsInfinity() { return true; }285};286287// Traits for IEEE half.288// 1 sign bit, 5 exponent bits, 10 fractional bits.289template <>290struct HexFloatTraits<FloatProxy<Float16>> {291typedef uint16_t uint_type;292typedef int16_t int_type;293typedef uint16_t underlying_type;294typedef uint16_t native_type;295static const uint_type num_used_bits = 16;296static const uint_type num_exponent_bits = 5;297static const uint_type num_fraction_bits = 10;298static const uint_type exponent_bias = 15;299static bool supportsInfinity() { return true; }300};301302template <>303struct HexFloatTraits<FloatProxy<FloatE5M2>> {304typedef uint8_t uint_type;305typedef int8_t int_type;306typedef uint8_t underlying_type;307typedef uint8_t native_type;308static const uint_type num_used_bits = 8;309static const uint_type num_exponent_bits = 5;310static const uint_type num_fraction_bits = 2;311static const uint_type exponent_bias = 15;312static bool supportsInfinity() { return true; }313};314315template <>316struct HexFloatTraits<FloatProxy<FloatE4M3>> {317typedef uint8_t uint_type;318typedef int8_t int_type;319typedef uint8_t underlying_type;320typedef uint8_t native_type;321static const uint_type num_used_bits = 8;322static const uint_type num_exponent_bits = 4;323static const uint_type num_fraction_bits = 3;324static const uint_type exponent_bias = 7;325static bool supportsInfinity() { return false; }326};327328enum round_direction {329kRoundToZero,330kRoundToNearestEven,331kRoundToPositiveInfinity,332kRoundToNegativeInfinity333};334335// Template class that houses a floating pointer number.336// It exposes a number of constants based on the provided traits to337// assist in interpreting the bits of the value.338template <typename T, typename Traits = HexFloatTraits<T>>339class HexFloat {340public:341typedef typename Traits::uint_type uint_type;342typedef typename Traits::int_type int_type;343typedef typename Traits::underlying_type underlying_type;344typedef typename Traits::native_type native_type;345using Traits_T = Traits;346347explicit HexFloat(T f) : value_(f) {}348349T value() const { return value_; }350void set_value(T f) { value_ = f; }351352// These are all written like this because it is convenient to have353// compile-time constants for all of these values.354355// Pass-through values to save typing.356static const uint32_t num_used_bits = Traits::num_used_bits;357static const uint32_t exponent_bias = Traits::exponent_bias;358static const uint32_t num_exponent_bits = Traits::num_exponent_bits;359static const uint32_t num_fraction_bits = Traits::num_fraction_bits;360361// Number of bits to shift left to set the highest relevant bit.362static const uint32_t top_bit_left_shift = num_used_bits - 1;363// How many nibbles (hex characters) the fractional part takes up.364static const uint32_t fraction_nibbles = (num_fraction_bits + 3) / 4;365// If the fractional part does not fit evenly into a hex character (4-bits)366// then we have to left-shift to get rid of leading 0s. This is the amount367// we have to shift (might be 0).368static const uint32_t num_overflow_bits =369fraction_nibbles * 4 - num_fraction_bits;370371// The representation of the fraction, not the actual bits. This372// includes the leading bit that is usually implicit.373static const uint_type fraction_represent_mask =374spvutils::SetBits<uint_type, 0,375num_fraction_bits + num_overflow_bits>::get;376377// The topmost bit in the nibble-aligned fraction.378static const uint_type fraction_top_bit =379uint_type(1) << (num_fraction_bits + num_overflow_bits - 1);380381// The least significant bit in the exponent, which is also the bit382// immediately to the left of the significand.383static const uint_type first_exponent_bit = uint_type(1)384<< (num_fraction_bits);385386// The mask for the encoded fraction. It does not include the387// implicit bit.388static const uint_type fraction_encode_mask =389spvutils::SetBits<uint_type, 0, num_fraction_bits>::get;390391// The bit that is used as a sign.392static const uint_type sign_mask = uint_type(1) << top_bit_left_shift;393394// The bits that represent the exponent.395static const uint_type exponent_mask =396spvutils::SetBits<uint_type, num_fraction_bits, num_exponent_bits>::get;397398// How far left the exponent is shifted.399static const uint32_t exponent_left_shift = num_fraction_bits;400401// How far from the right edge the fraction is shifted.402static const uint32_t fraction_right_shift =403static_cast<uint32_t>(sizeof(uint_type) * 8) - num_fraction_bits;404405// The maximum representable unbiased exponent.406static const int_type max_exponent =407(exponent_mask >> num_fraction_bits) - exponent_bias;408// The minimum representable exponent for normalized numbers.409static const int_type min_exponent = -static_cast<int_type>(exponent_bias);410411// Returns the bits associated with the value.412uint_type getBits() const { return spvutils::BitwiseCast<uint_type>(value_); }413414// Returns the bits associated with the value, without the leading sign bit.415uint_type getUnsignedBits() const {416return static_cast<uint_type>(spvutils::BitwiseCast<uint_type>(value_) &417~sign_mask);418}419420// Returns the bits associated with the exponent, shifted to start at the421// lsb of the type.422const uint_type getExponentBits() const {423return static_cast<uint_type>((getBits() & exponent_mask) >>424num_fraction_bits);425}426427// Returns the exponent in unbiased form. This is the exponent in the428// human-friendly form.429const int_type getUnbiasedExponent() const {430return static_cast<int_type>(getExponentBits() - exponent_bias);431}432433// Returns just the significand bits from the value.434const uint_type getSignificandBits() const {435return getBits() & fraction_encode_mask;436}437438// If the number was normalized, returns the unbiased exponent.439// If the number was denormal, normalize the exponent first.440const int_type getUnbiasedNormalizedExponent() const {441if ((getBits() & ~sign_mask) == 0) { // special case if everything is 0442return 0;443}444int_type exp = getUnbiasedExponent();445if (exp == min_exponent) { // We are in denorm land.446uint_type significand_bits = getSignificandBits();447while ((significand_bits & (first_exponent_bit >> 1)) == 0) {448significand_bits = static_cast<uint_type>(significand_bits << 1);449exp = static_cast<int_type>(exp - 1);450}451significand_bits &= fraction_encode_mask;452}453return exp;454}455456// Returns the signficand after it has been normalized.457const uint_type getNormalizedSignificand() const {458int_type unbiased_exponent = getUnbiasedNormalizedExponent();459uint_type significand = getSignificandBits();460for (int_type i = unbiased_exponent; i <= min_exponent; ++i) {461significand = static_cast<uint_type>(significand << 1);462}463significand &= fraction_encode_mask;464return significand;465}466467// Returns true if this number represents a negative value.468bool isNegative() const { return (getBits() & sign_mask) != 0; }469470// Sets this HexFloat from the individual components.471// Note this assumes EVERY significand is normalized, and has an implicit472// leading one. This means that the only way that this method will set 0,473// is if you set a number so denormalized that it underflows.474// Do not use this method with raw bits extracted from a subnormal number,475// since subnormals do not have an implicit leading 1 in the significand.476// The significand is also expected to be in the477// lowest-most num_fraction_bits of the uint_type.478// The exponent is expected to be unbiased, meaning an exponent of479// 0 actually means 0.480// If underflow_round_up is set, then on underflow, if a number is non-0481// and would underflow, we round up to the smallest denorm.482void setFromSignUnbiasedExponentAndNormalizedSignificand(483bool negative, int_type exponent, uint_type significand,484bool round_denorm_up) {485bool significand_is_zero = significand == 0;486487if (exponent <= min_exponent) {488// If this was denormalized, then we have to shift the bit on, meaning489// the significand is not zero.490significand_is_zero = false;491significand |= first_exponent_bit;492significand = static_cast<uint_type>(significand >> 1);493}494495while (exponent < min_exponent) {496significand = static_cast<uint_type>(significand >> 1);497++exponent;498}499500if (exponent == min_exponent) {501if (significand == 0 && !significand_is_zero && round_denorm_up) {502significand = static_cast<uint_type>(0x1);503}504}505506uint_type new_value = 0;507if (negative) {508new_value = static_cast<uint_type>(new_value | sign_mask);509}510exponent = static_cast<int_type>(exponent + exponent_bias);511assert(exponent >= 0);512513// put it all together514exponent = static_cast<uint_type>((exponent << exponent_left_shift) &515exponent_mask);516significand = static_cast<uint_type>(significand & fraction_encode_mask);517new_value = static_cast<uint_type>(new_value | (exponent | significand));518value_ = BitwiseCast<T>(new_value);519}520521// Increments the significand of this number by the given amount.522// If this would spill the significand into the implicit bit,523// carry is set to true and the significand is shifted to fit into524// the correct location, otherwise carry is set to false.525// All significands and to_increment are assumed to be within the bounds526// for a valid significand.527static uint_type incrementSignificand(uint_type significand,528uint_type to_increment, bool* carry) {529significand = static_cast<uint_type>(significand + to_increment);530*carry = false;531if (significand & first_exponent_bit) {532*carry = true;533// The implicit 1-bit will have carried, so we should zero-out the534// top bit and shift back.535significand = static_cast<uint_type>(significand & ~first_exponent_bit);536significand = static_cast<uint_type>(significand >> 1);537}538return significand;539}540541// These exist because MSVC throws warnings on negative right-shifts542// even if they are not going to be executed. Eg:543// constant_number < 0? 0: constant_number544// These convert the negative left-shifts into right shifts.545546template <typename int_type>547uint_type negatable_left_shift(int_type N, uint_type val)548{549if(N >= 0)550return val << N;551552return val >> -N;553}554555template <typename int_type>556uint_type negatable_right_shift(int_type N, uint_type val)557{558if(N >= 0)559return val >> N;560561return val << -N;562}563564// Returns the significand, rounded to fit in a significand in565// other_T. This is shifted so that the most significant566// bit of the rounded number lines up with the most significant bit567// of the returned significand.568template <typename other_T>569typename other_T::uint_type getRoundedNormalizedSignificand(570round_direction dir, bool* carry_bit) {571typedef typename other_T::uint_type other_uint_type;572static const int_type num_throwaway_bits =573static_cast<int_type>(num_fraction_bits) -574static_cast<int_type>(other_T::num_fraction_bits);575576static const uint_type last_significant_bit =577(num_throwaway_bits < 0)578? 0579: negatable_left_shift(num_throwaway_bits, 1u);580static const uint_type first_rounded_bit =581(num_throwaway_bits < 1)582? 0583: negatable_left_shift(num_throwaway_bits - 1, 1u);584585static const uint_type throwaway_mask_bits =586num_throwaway_bits > 0 ? num_throwaway_bits : 0;587static const uint_type throwaway_mask =588spvutils::SetBits<uint_type, 0, throwaway_mask_bits>::get;589590*carry_bit = false;591other_uint_type out_val = 0;592uint_type significand = getNormalizedSignificand();593// If we are up-casting, then we just have to shift to the right location.594if (num_throwaway_bits <= 0) {595out_val = static_cast<other_uint_type>(significand);596uint_type shift_amount = static_cast<uint_type>(-num_throwaway_bits);597out_val = static_cast<other_uint_type>(out_val << shift_amount);598return out_val;599}600601// If every non-representable bit is 0, then we don't have any casting to602// do.603if ((significand & throwaway_mask) == 0) {604return static_cast<other_uint_type>(605negatable_right_shift(num_throwaway_bits, significand));606}607608bool round_away_from_zero = false;609// We actually have to narrow the significand here, so we have to follow the610// rounding rules.611switch (dir) {612case kRoundToZero:613break;614case kRoundToPositiveInfinity:615round_away_from_zero = !isNegative();616break;617case kRoundToNegativeInfinity:618round_away_from_zero = isNegative();619break;620case kRoundToNearestEven:621// Have to round down, round bit is 0622if ((first_rounded_bit & significand) == 0) {623break;624}625if (((significand & throwaway_mask) & ~first_rounded_bit) != 0) {626// If any subsequent bit of the rounded portion is non-0 then we round627// up.628round_away_from_zero = true;629break;630}631// We are exactly half-way between 2 numbers, pick even.632if ((significand & last_significant_bit) != 0) {633// 1 for our last bit, round up.634round_away_from_zero = true;635break;636}637break;638}639640if (round_away_from_zero) {641return static_cast<other_uint_type>(642negatable_right_shift(num_throwaway_bits, incrementSignificand(643significand, last_significant_bit, carry_bit)));644} else {645return static_cast<other_uint_type>(646negatable_right_shift(num_throwaway_bits, significand));647}648}649650// Casts this value to another HexFloat. If the cast is widening,651// then round_dir is ignored. If the cast is narrowing, then652// the result is rounded in the direction specified.653// This number will retain Nan and Inf values.654// It will also saturate to Inf if the number overflows, and655// underflow to (0 or min depending on rounding) if the number underflows.656template <typename other_T>657void castTo(other_T& other, round_direction round_dir) {658other = other_T(static_cast<typename other_T::native_type>(0));659bool negate = isNegative();660if (getUnsignedBits() == 0) {661if (negate) {662other.set_value(-other.value());663}664return;665}666uint_type significand = getSignificandBits();667bool carried = false;668typename other_T::uint_type rounded_significand =669getRoundedNormalizedSignificand<other_T>(round_dir, &carried);670671int_type exponent = getUnbiasedExponent();672if (exponent == min_exponent) {673// If we are denormal, normalize the exponent, so that we can encode674// easily.675exponent = static_cast<int_type>(exponent + 1);676for (uint_type check_bit = first_exponent_bit >> 1; check_bit != 0;677check_bit = static_cast<uint_type>(check_bit >> 1)) {678exponent = static_cast<int_type>(exponent - 1);679if (check_bit & significand) break;680}681}682683bool is_nan =684(getBits() & exponent_mask) == exponent_mask && significand != 0;685bool is_inf =686!is_nan &&687(((exponent + carried) > static_cast<int_type>(other_T::exponent_bias) && other_T::Traits_T::supportsInfinity()) ||688((exponent + carried) > static_cast<int_type>(other_T::exponent_bias + 1) && !other_T::Traits_T::supportsInfinity()) ||689(significand == 0 && (getBits() & exponent_mask) == exponent_mask));690691// If we are Nan or Inf we should pass that through.692if (is_inf) {693if (other_T::Traits_T::supportsInfinity()) {694// encode as +/-inf695other.set_value(BitwiseCast<typename other_T::underlying_type>(696static_cast<typename other_T::uint_type>(697(negate ? other_T::sign_mask : 0) | other_T::exponent_mask)));698} else {699// encode as +/-nan700other.set_value(BitwiseCast<typename other_T::underlying_type>(701static_cast<typename other_T::uint_type>(negate ? ~0 : ~other_T::sign_mask)));702}703return;704}705if (is_nan) {706typename other_T::uint_type shifted_significand;707shifted_significand = static_cast<typename other_T::uint_type>(708negatable_left_shift(709static_cast<int_type>(other_T::num_fraction_bits) -710static_cast<int_type>(num_fraction_bits), significand));711712// We are some sort of Nan. We try to keep the bit-pattern of the Nan713// as close as possible. If we had to shift off bits so we are 0, then we714// just set the last bit.715other.set_value(BitwiseCast<typename other_T::underlying_type>(716static_cast<typename other_T::uint_type>(717(negate ? other_T::sign_mask : 0) | other_T::exponent_mask |718(shifted_significand == 0 ? 0x1 : shifted_significand))));719return;720}721722bool round_underflow_up =723isNegative() ? round_dir == kRoundToNegativeInfinity724: round_dir == kRoundToPositiveInfinity;725typedef typename other_T::int_type other_int_type;726// setFromSignUnbiasedExponentAndNormalizedSignificand will727// zero out any underflowing value (but retain the sign).728other.setFromSignUnbiasedExponentAndNormalizedSignificand(729negate, static_cast<other_int_type>(exponent), rounded_significand,730round_underflow_up);731return;732}733734private:735T value_;736737static_assert(num_used_bits ==738Traits::num_exponent_bits + Traits::num_fraction_bits + 1,739"The number of bits do not fit");740static_assert(sizeof(T) == sizeof(uint_type), "The type sizes do not match");741};742743// Returns 4 bits represented by the hex character.744inline uint8_t get_nibble_from_character(int character) {745const char* dec = "0123456789";746const char* lower = "abcdef";747const char* upper = "ABCDEF";748const char* p = nullptr;749if ((p = strchr(dec, character))) {750return static_cast<uint8_t>(p - dec);751} else if ((p = strchr(lower, character))) {752return static_cast<uint8_t>(p - lower + 0xa);753} else if ((p = strchr(upper, character))) {754return static_cast<uint8_t>(p - upper + 0xa);755}756757assert(false && "This was called with a non-hex character");758return 0;759}760761// Outputs the given HexFloat to the stream.762template <typename T, typename Traits>763std::ostream& operator<<(std::ostream& os, const HexFloat<T, Traits>& value) {764typedef HexFloat<T, Traits> HF;765typedef typename HF::uint_type uint_type;766typedef typename HF::int_type int_type;767768static_assert(HF::num_used_bits != 0,769"num_used_bits must be non-zero for a valid float");770static_assert(HF::num_exponent_bits != 0,771"num_exponent_bits must be non-zero for a valid float");772static_assert(HF::num_fraction_bits != 0,773"num_fractin_bits must be non-zero for a valid float");774775const uint_type bits = spvutils::BitwiseCast<uint_type>(value.value());776const char* const sign = (bits & HF::sign_mask) ? "-" : "";777const uint_type exponent = static_cast<uint_type>(778(bits & HF::exponent_mask) >> HF::num_fraction_bits);779780uint_type fraction = static_cast<uint_type>((bits & HF::fraction_encode_mask)781<< HF::num_overflow_bits);782783const bool is_zero = exponent == 0 && fraction == 0;784const bool is_denorm = exponent == 0 && !is_zero;785786// exponent contains the biased exponent we have to convert it back into787// the normal range.788int_type int_exponent = static_cast<int_type>(exponent - HF::exponent_bias);789// If the number is all zeros, then we actually have to NOT shift the790// exponent.791int_exponent = is_zero ? 0 : int_exponent;792793// If we are denorm, then start shifting, and decreasing the exponent until794// our leading bit is 1.795796if (is_denorm) {797while ((fraction & HF::fraction_top_bit) == 0) {798fraction = static_cast<uint_type>(fraction << 1);799int_exponent = static_cast<int_type>(int_exponent - 1);800}801// Since this is denormalized, we have to consume the leading 1 since it802// will end up being implicit.803fraction = static_cast<uint_type>(fraction << 1); // eat the leading 1804fraction &= HF::fraction_represent_mask;805}806807uint_type fraction_nibbles = HF::fraction_nibbles;808// We do not have to display any trailing 0s, since this represents the809// fractional part.810while (fraction_nibbles > 0 && (fraction & 0xF) == 0) {811// Shift off any trailing values;812fraction = static_cast<uint_type>(fraction >> 4);813--fraction_nibbles;814}815816const auto saved_flags = os.flags();817const auto saved_fill = os.fill();818819os << sign << "0x" << (is_zero ? '0' : '1');820if (fraction_nibbles) {821// Make sure to keep the leading 0s in place, since this is the fractional822// part.823os << "." << std::setw(static_cast<int>(fraction_nibbles))824<< std::setfill('0') << std::hex << fraction;825}826os << "p" << std::dec << (int_exponent >= 0 ? "+" : "") << int_exponent;827828os.flags(saved_flags);829os.fill(saved_fill);830831return os;832}833834// Returns true if negate_value is true and the next character on the835// input stream is a plus or minus sign. In that case we also set the fail bit836// on the stream and set the value to the zero value for its type.837template <typename T, typename Traits>838inline bool RejectParseDueToLeadingSign(std::istream& is, bool negate_value,839HexFloat<T, Traits>& value) {840if (negate_value) {841auto next_char = is.peek();842if (next_char == '-' || next_char == '+') {843// Fail the parse. Emulate standard behaviour by setting the value to844// the zero value, and set the fail bit on the stream.845value = HexFloat<T, Traits>(typename HexFloat<T, Traits>::uint_type(0));846is.setstate(std::ios_base::failbit);847return true;848}849}850return false;851}852853// Parses a floating point number from the given stream and stores it into the854// value parameter.855// If negate_value is true then the number may not have a leading minus or856// plus, and if it successfully parses, then the number is negated before857// being stored into the value parameter.858// If the value cannot be correctly parsed or overflows the target floating859// point type, then set the fail bit on the stream.860// TODO(dneto): Promise C++11 standard behavior in how the value is set in861// the error case, but only after all target platforms implement it correctly.862// In particular, the Microsoft C++ runtime appears to be out of spec.863template <typename T, typename Traits>864inline std::istream& ParseNormalFloat(std::istream& is, bool negate_value,865HexFloat<T, Traits>& value) {866if (RejectParseDueToLeadingSign(is, negate_value, value)) {867return is;868}869T val;870is >> val;871if (negate_value) {872val = -val;873}874value.set_value(val);875// In the failure case, map -0.0 to 0.0.876if (is.fail() && value.getUnsignedBits() == 0u) {877value = HexFloat<T, Traits>(typename HexFloat<T, Traits>::uint_type(0));878}879if (val.isInfinity()) {880// Fail the parse. Emulate standard behaviour by setting the value to881// the closest normal value, and set the fail bit on the stream.882value.set_value((value.isNegative() || negate_value) ? T::lowest()883: T::max());884is.setstate(std::ios_base::failbit);885}886return is;887}888889// Specialization of ParseNormalFloat for FloatProxy<Float16> values.890// This will parse the float as it were a 32-bit floating point number,891// and then round it down to fit into a Float16 value.892// The number is rounded towards zero.893// If negate_value is true then the number may not have a leading minus or894// plus, and if it successfully parses, then the number is negated before895// being stored into the value parameter.896// If the value cannot be correctly parsed or overflows the target floating897// point type, then set the fail bit on the stream.898// TODO(dneto): Promise C++11 standard behavior in how the value is set in899// the error case, but only after all target platforms implement it correctly.900// In particular, the Microsoft C++ runtime appears to be out of spec.901template <>902inline std::istream&903ParseNormalFloat<FloatProxy<Float16>, HexFloatTraits<FloatProxy<Float16>>>(904std::istream& is, bool negate_value,905HexFloat<FloatProxy<Float16>, HexFloatTraits<FloatProxy<Float16>>>& value) {906// First parse as a 32-bit float.907HexFloat<FloatProxy<float>> float_val(0.0f);908ParseNormalFloat(is, negate_value, float_val);909910// Then convert to 16-bit float, saturating at infinities, and911// rounding toward zero.912float_val.castTo(value, kRoundToZero);913914// Overflow on 16-bit behaves the same as for 32- and 64-bit: set the915// fail bit and set the lowest or highest value.916if (Float16::isInfinity(value.value().getAsFloat())) {917value.set_value(value.isNegative() ? Float16::lowest() : Float16::max());918is.setstate(std::ios_base::failbit);919}920return is;921}922923// Reads a HexFloat from the given stream.924// If the float is not encoded as a hex-float then it will be parsed925// as a regular float.926// This may fail if your stream does not support at least one unget.927// Nan values can be encoded with "0x1.<not zero>p+exponent_bias".928// This would normally overflow a float and round to929// infinity but this special pattern is the exact representation for a NaN,930// and therefore is actually encoded as the correct NaN. To encode inf,931// either 0x0p+exponent_bias can be specified or any exponent greater than932// exponent_bias.933// Examples using IEEE 32-bit float encoding.934// 0x1.0p+128 (+inf)935// -0x1.0p-128 (-inf)936//937// 0x1.1p+128 (+Nan)938// -0x1.1p+128 (-Nan)939//940// 0x1p+129 (+inf)941// -0x1p+129 (-inf)942template <typename T, typename Traits>943std::istream& operator>>(std::istream& is, HexFloat<T, Traits>& value) {944using HF = HexFloat<T, Traits>;945using uint_type = typename HF::uint_type;946using int_type = typename HF::int_type;947948value.set_value(static_cast<typename HF::native_type>(0.f));949950if (is.flags() & std::ios::skipws) {951// If the user wants to skip whitespace , then we should obey that.952while (std::isspace(is.peek())) {953is.get();954}955}956957auto next_char = is.peek();958bool negate_value = false;959960if (next_char != '-' && next_char != '0') {961return ParseNormalFloat(is, negate_value, value);962}963964if (next_char == '-') {965negate_value = true;966is.get();967next_char = is.peek();968}969970if (next_char == '0') {971is.get(); // We may have to unget this.972auto maybe_hex_start = is.peek();973if (maybe_hex_start != 'x' && maybe_hex_start != 'X') {974is.unget();975return ParseNormalFloat(is, negate_value, value);976} else {977is.get(); // Throw away the 'x';978}979} else {980return ParseNormalFloat(is, negate_value, value);981}982983// This "looks" like a hex-float so treat it as one.984bool seen_p = false;985bool seen_dot = false;986uint_type fraction_index = 0;987988uint_type fraction = 0;989int_type exponent = HF::exponent_bias;990991// Strip off leading zeros so we don't have to special-case them later.992while ((next_char = is.peek()) == '0') {993is.get();994}995996bool is_denorm =997true; // Assume denorm "representation" until we hear otherwise.998// NB: This does not mean the value is actually denorm,999// it just means that it was written 0.1000bool bits_written = false; // Stays false until we write a bit.1001while (!seen_p && !seen_dot) {1002// Handle characters that are left of the fractional part.1003if (next_char == '.') {1004seen_dot = true;1005} else if (next_char == 'p') {1006seen_p = true;1007} else if (::isxdigit(next_char)) {1008// We know this is not denormalized since we have stripped all leading1009// zeroes and we are not a ".".1010is_denorm = false;1011int number = get_nibble_from_character(next_char);1012for (int i = 0; i < 4; ++i, number <<= 1) {1013uint_type write_bit = (number & 0x8) ? 0x1 : 0x0;1014if (bits_written) {1015// If we are here the bits represented belong in the fractional1016// part of the float, and we have to adjust the exponent accordingly.1017fraction = static_cast<uint_type>(1018fraction |1019static_cast<uint_type>(1020write_bit << (HF::top_bit_left_shift - fraction_index++)));1021exponent = static_cast<int_type>(exponent + 1);1022}1023bits_written |= write_bit != 0;1024}1025} else {1026// We have not found our exponent yet, so we have to fail.1027is.setstate(std::ios::failbit);1028return is;1029}1030is.get();1031next_char = is.peek();1032}1033bits_written = false;1034while (seen_dot && !seen_p) {1035// Handle only fractional parts now.1036if (next_char == 'p') {1037seen_p = true;1038} else if (::isxdigit(next_char)) {1039int number = get_nibble_from_character(next_char);1040for (int i = 0; i < 4; ++i, number <<= 1) {1041uint_type write_bit = (number & 0x8) ? 0x01 : 0x00;1042bits_written |= write_bit != 0;1043if (is_denorm && !bits_written) {1044// Handle modifying the exponent here this way we can handle1045// an arbitrary number of hex values without overflowing our1046// integer.1047exponent = static_cast<int_type>(exponent - 1);1048} else {1049fraction = static_cast<uint_type>(1050fraction |1051static_cast<uint_type>(1052write_bit << (HF::top_bit_left_shift - fraction_index++)));1053}1054}1055} else {1056// We still have not found our 'p' exponent yet, so this is not a valid1057// hex-float.1058is.setstate(std::ios::failbit);1059return is;1060}1061is.get();1062next_char = is.peek();1063}10641065bool seen_sign = false;1066int8_t exponent_sign = 1;1067int_type written_exponent = 0;1068while (true) {1069if ((next_char == '-' || next_char == '+')) {1070if (seen_sign) {1071is.setstate(std::ios::failbit);1072return is;1073}1074seen_sign = true;1075exponent_sign = (next_char == '-') ? -1 : 1;1076} else if (::isdigit(next_char)) {1077// Hex-floats express their exponent as decimal.1078written_exponent = static_cast<int_type>(written_exponent * 10);1079written_exponent =1080static_cast<int_type>(written_exponent + (next_char - '0'));1081} else {1082break;1083}1084is.get();1085next_char = is.peek();1086}10871088written_exponent = static_cast<int_type>(written_exponent * exponent_sign);1089exponent = static_cast<int_type>(exponent + written_exponent);10901091bool is_zero = is_denorm && (fraction == 0);1092if (is_denorm && !is_zero) {1093fraction = static_cast<uint_type>(fraction << 1);1094exponent = static_cast<int_type>(exponent - 1);1095} else if (is_zero) {1096exponent = 0;1097}10981099if (exponent <= 0 && !is_zero) {1100fraction = static_cast<uint_type>(fraction >> 1);1101fraction |= static_cast<uint_type>(1) << HF::top_bit_left_shift;1102}11031104fraction = (fraction >> HF::fraction_right_shift) & HF::fraction_encode_mask;11051106const int_type max_exponent =1107SetBits<uint_type, 0, HF::num_exponent_bits>::get;11081109// Handle actual denorm numbers1110while (exponent < 0 && !is_zero) {1111fraction = static_cast<uint_type>(fraction >> 1);1112exponent = static_cast<int_type>(exponent + 1);11131114fraction &= HF::fraction_encode_mask;1115if (fraction == 0) {1116// We have underflowed our fraction. We should clamp to zero.1117is_zero = true;1118exponent = 0;1119}1120}11211122// We have overflowed so we should be inf/-inf.1123if (exponent > max_exponent) {1124exponent = max_exponent;1125fraction = 0;1126}11271128uint_type output_bits = static_cast<uint_type>(1129static_cast<uint_type>(negate_value ? 1 : 0) << HF::top_bit_left_shift);1130output_bits |= fraction;11311132uint_type shifted_exponent = static_cast<uint_type>(1133static_cast<uint_type>(exponent << HF::exponent_left_shift) &1134HF::exponent_mask);1135output_bits |= shifted_exponent;11361137T output_float = spvutils::BitwiseCast<T>(output_bits);1138value.set_value(output_float);11391140return is;1141}11421143// Writes a FloatProxy value to a stream.1144// Zero and normal numbers are printed in the usual notation, but with1145// enough digits to fully reproduce the value. Other values (subnormal,1146// NaN, and infinity) are printed as a hex float.1147template <typename T>1148std::ostream& operator<<(std::ostream& os, const FloatProxy<T>& value) {1149auto float_val = value.getAsFloat();1150switch (std::fpclassify(float_val)) {1151case FP_ZERO:1152case FP_NORMAL: {1153auto saved_precision = os.precision();1154os.precision(std::numeric_limits<T>::digits10);1155os << float_val;1156os.precision(saved_precision);1157} break;1158default:1159os << HexFloat<FloatProxy<T>>(value);1160break;1161}1162return os;1163}11641165template <>1166inline std::ostream& operator<<<Float16>(std::ostream& os,1167const FloatProxy<Float16>& value) {1168os << HexFloat<FloatProxy<Float16>>(value);1169return os;1170}1171}11721173#endif // LIBSPIRV_UTIL_HEX_FLOAT_H_117411751176