int_to_fp_impl.inc 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //===-- int_to_fp_impl.inc - integer to floating point conversion ---------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Thsi file implements a generic conversion from an integer type to an
  10. // IEEE-754 floating point type, allowing a common implementation to be hsared
  11. // without copy and paste.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "int_to_fp.h"
  15. static __inline dst_t __floatXiYf__(src_t a) {
  16. if (a == 0)
  17. return 0.0;
  18. enum {
  19. dstMantDig = dstSigBits + 1,
  20. srcBits = sizeof(src_t) * CHAR_BIT,
  21. srcIsSigned = ((src_t)-1) < 0,
  22. };
  23. const src_t s = srcIsSigned ? a >> (srcBits - 1) : 0;
  24. a = (usrc_t)(a ^ s) - s;
  25. int sd = srcBits - clzSrcT(a); // number of significant digits
  26. int e = sd - 1; // exponent
  27. if (sd > dstMantDig) {
  28. // start: 0000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQxxxxxxxxxxxxxxxxxx
  29. // finish: 000000000000000000000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQR
  30. // 12345678901234567890123456
  31. // 1 = msb 1 bit
  32. // P = bit dstMantDig-1 bits to the right of 1
  33. // Q = bit dstMantDig bits to the right of 1
  34. // R = "or" of all bits to the right of Q
  35. if (sd == dstMantDig + 1) {
  36. a <<= 1;
  37. } else if (sd == dstMantDig + 2) {
  38. // Do nothing.
  39. } else {
  40. a = ((usrc_t)a >> (sd - (dstMantDig + 2))) |
  41. ((a & ((usrc_t)(-1) >> ((srcBits + dstMantDig + 2) - sd))) != 0);
  42. }
  43. // finish:
  44. a |= (a & 4) != 0; // Or P into R
  45. ++a; // round - this step may add a significant bit
  46. a >>= 2; // dump Q and R
  47. // a is now rounded to dstMantDig or dstMantDig+1 bits
  48. if (a & ((usrc_t)1 << dstMantDig)) {
  49. a >>= 1;
  50. ++e;
  51. }
  52. // a is now rounded to dstMantDig bits
  53. } else {
  54. a <<= (dstMantDig - sd);
  55. // a is now rounded to dstMantDig bits
  56. }
  57. const int dstBits = sizeof(dst_t) * CHAR_BIT;
  58. const dst_rep_t dstSignMask = DST_REP_C(1) << (dstBits - 1);
  59. const int dstExpBits = dstBits - dstSigBits - 1;
  60. const int dstExpBias = (1 << (dstExpBits - 1)) - 1;
  61. const dst_rep_t dstSignificandMask = (DST_REP_C(1) << dstSigBits) - 1;
  62. // Combine sign, exponent, and mantissa.
  63. const dst_rep_t result = ((dst_rep_t)s & dstSignMask) |
  64. ((dst_rep_t)(e + dstExpBias) << dstSigBits) |
  65. ((dst_rep_t)(a) & dstSignificandMask);
  66. return dstFromRep(result);
  67. }