fixunstfdi.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  2. // See https://llvm.org/LICENSE.txt for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. // uint64_t __fixunstfdi(long double x);
  5. // This file implements the PowerPC 128-bit double-double -> uint64_t conversion
  6. #include "DD.h"
  7. uint64_t __fixunstfdi(long double input) {
  8. const DD x = {.ld = input};
  9. const doublebits hibits = {.d = x.s.hi};
  10. const uint32_t highWordMinusOne =
  11. (uint32_t)(hibits.x >> 32) - UINT32_C(0x3ff00000);
  12. // If (1.0 - tiny) <= input < 0x1.0p64:
  13. if (UINT32_C(0x04000000) > highWordMinusOne) {
  14. const int unbiasedHeadExponent = highWordMinusOne >> 20;
  15. uint64_t result = hibits.x & UINT64_C(0x000fffffffffffff); // mantissa(hi)
  16. result |= UINT64_C(0x0010000000000000); // matissa(hi) with implicit bit
  17. result <<= 11; // mantissa(hi) left aligned in the int64 field.
  18. // If the tail is non-zero, we need to patch in the tail bits.
  19. if (0.0 != x.s.lo) {
  20. const doublebits lobits = {.d = x.s.lo};
  21. int64_t tailMantissa = lobits.x & INT64_C(0x000fffffffffffff);
  22. tailMantissa |= INT64_C(0x0010000000000000);
  23. // At this point we have the mantissa of |tail|
  24. const int64_t negationMask = ((int64_t)(lobits.x)) >> 63;
  25. tailMantissa = (tailMantissa ^ negationMask) - negationMask;
  26. // Now we have the mantissa of tail as a signed 2s-complement integer
  27. const int biasedTailExponent = (int)(lobits.x >> 52) & 0x7ff;
  28. // Shift the tail mantissa into the right position, accounting for the
  29. // bias of 11 that we shifted the head mantissa by.
  30. tailMantissa >>=
  31. (unbiasedHeadExponent - (biasedTailExponent - (1023 - 11)));
  32. result += tailMantissa;
  33. }
  34. result >>= (63 - unbiasedHeadExponent);
  35. return result;
  36. }
  37. // Edge cases are handled here, with saturation.
  38. if (1.0 > x.s.hi)
  39. return UINT64_C(0);
  40. else
  41. return UINT64_MAX;
  42. }