hex_float.h 39 KB

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