floatuntixf.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //===-- floatuntixf.c - Implement __floatuntixf ---------------------------===//
  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. // This file implements __floatuntixf for the compiler_rt library.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "int_lib.h"
  13. #ifdef CRT_HAS_128BIT
  14. // Returns: convert a to a long double, rounding toward even.
  15. // Assumption: long double is a IEEE 80 bit floating point type padded to 128
  16. // bits tu_int is a 128 bit integral type
  17. // gggg gggg gggg gggg gggg gggg gggg gggg | gggg gggg gggg gggg seee eeee eeee
  18. // eeee | 1mmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm | mmmm mmmm mmmm mmmm mmmm
  19. // mmmm mmmm mmmm
  20. COMPILER_RT_ABI xf_float __floatuntixf(tu_int a) {
  21. if (a == 0)
  22. return 0.0;
  23. const unsigned N = sizeof(tu_int) * CHAR_BIT;
  24. int sd = N - __clzti2(a); // number of significant digits
  25. int e = sd - 1; // exponent
  26. if (sd > LDBL_MANT_DIG) {
  27. // start: 0000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQxxxxxxxxxxxxxxxxxx
  28. // finish: 000000000000000000000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQR
  29. // 12345678901234567890123456
  30. // 1 = msb 1 bit
  31. // P = bit LDBL_MANT_DIG-1 bits to the right of 1
  32. // Q = bit LDBL_MANT_DIG bits to the right of 1
  33. // R = "or" of all bits to the right of Q
  34. switch (sd) {
  35. case LDBL_MANT_DIG + 1:
  36. a <<= 1;
  37. break;
  38. case LDBL_MANT_DIG + 2:
  39. break;
  40. default:
  41. a = (a >> (sd - (LDBL_MANT_DIG + 2))) |
  42. ((a & ((tu_int)(-1) >> ((N + LDBL_MANT_DIG + 2) - sd))) != 0);
  43. };
  44. // finish:
  45. a |= (a & 4) != 0; // Or P into R
  46. ++a; // round - this step may add a significant bit
  47. a >>= 2; // dump Q and R
  48. // a is now rounded to LDBL_MANT_DIG or LDBL_MANT_DIG+1 bits
  49. if (a & ((tu_int)1 << LDBL_MANT_DIG)) {
  50. a >>= 1;
  51. ++e;
  52. }
  53. // a is now rounded to LDBL_MANT_DIG bits
  54. } else {
  55. a <<= (LDBL_MANT_DIG - sd);
  56. // a is now rounded to LDBL_MANT_DIG bits
  57. }
  58. xf_bits fb;
  59. fb.u.high.s.low = (e + 16383); // exponent
  60. fb.u.low.all = (du_int)a; // mantissa
  61. return fb.f;
  62. }
  63. #endif