hex_float.h 41 KB

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