hex_float.h 44 KB

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