mulodi4.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*===-- mulodi4.c - Implement __mulodi4 -----------------------------------===
  2. *
  3. * The LLVM Compiler Infrastructure
  4. *
  5. * This file is dual licensed under the MIT and the University of Illinois Open
  6. * Source Licenses. See LICENSE.TXT for details.
  7. *
  8. * ===----------------------------------------------------------------------===
  9. *
  10. * This file implements __mulodi4 for the compiler_rt library.
  11. *
  12. * ===----------------------------------------------------------------------===
  13. */
  14. #if 0
  15. #include "int_lib.h"
  16. #else
  17. #define COMPILER_RT_ABI
  18. #define di_int int64_t
  19. #define di_uint uint64_t
  20. #include "torint.h"
  21. di_int __mulodi4(di_int a, di_int b, int* overflow);
  22. #endif
  23. /* Returns: a * b */
  24. /* Effects: sets *overflow to 1 if a * b overflows */
  25. COMPILER_RT_ABI di_int
  26. __mulodi4(di_int a, di_int b, int* overflow)
  27. {
  28. const int N = (int)(sizeof(di_int) * CHAR_BIT);
  29. const di_int MIN = (di_int) ((di_uint)1 << (N-1));
  30. const di_int MAX = ~MIN;
  31. *overflow = 0;
  32. di_int result = a * b;
  33. if (a == MIN)
  34. {
  35. if (b != 0 && b != 1)
  36. *overflow = 1;
  37. return result;
  38. }
  39. if (b == MIN)
  40. {
  41. if (a != 0 && a != 1)
  42. *overflow = 1;
  43. return result;
  44. }
  45. di_int sa = a >> (N - 1);
  46. di_int abs_a = (a ^ sa) - sa;
  47. di_int sb = b >> (N - 1);
  48. di_int abs_b = (b ^ sb) - sb;
  49. if (abs_a < 2 || abs_b < 2)
  50. return result;
  51. if (sa == sb)
  52. {
  53. if (abs_a > MAX / abs_b)
  54. *overflow = 1;
  55. }
  56. else
  57. {
  58. if (abs_a > MIN / -abs_b)
  59. *overflow = 1;
  60. }
  61. return result;
  62. }