1 #include "Python.h"
2
3 #ifdef X87_DOUBLE_ROUNDING
4 /* On x86 platforms using an x87 FPU, this function is called from the
5 Py_FORCE_DOUBLE macro (defined in pymath.h) to force a floating-point
6 number out of an 80-bit x87 FPU register and into a 64-bit memory location,
7 thus rounding from extended precision to double precision. */
_Py_force_double(double x)8 double _Py_force_double(double x)
9 {
10 volatile double y;
11 y = x;
12 return y;
13 }
14 #endif
15
16 #ifdef HAVE_GCC_ASM_FOR_X87
17
18 /* inline assembly for getting and setting the 387 FPU control word on
19 gcc/x86 */
20 #ifdef _Py_MEMORY_SANITIZER
21 __attribute__((no_sanitize_memory))
22 #endif
_Py_get_387controlword(void)23 unsigned short _Py_get_387controlword(void) {
24 unsigned short cw;
25 __asm__ __volatile__ ("fnstcw %0" : "=m" (cw));
26 return cw;
27 }
28
_Py_set_387controlword(unsigned short cw)29 void _Py_set_387controlword(unsigned short cw) {
30 __asm__ __volatile__ ("fldcw %0" : : "m" (cw));
31 }
32
33 #endif
34
35
36 #ifndef HAVE_HYPOT
hypot(double x,double y)37 double hypot(double x, double y)
38 {
39 double yx;
40
41 x = fabs(x);
42 y = fabs(y);
43 if (x < y) {
44 double temp = x;
45 x = y;
46 y = temp;
47 }
48 if (x == 0.)
49 return 0.;
50 else {
51 yx = y/x;
52 return x*sqrt(1.+yx*yx);
53 }
54 }
55 #endif /* HAVE_HYPOT */
56
57 #ifndef HAVE_COPYSIGN
58 double
copysign(double x,double y)59 copysign(double x, double y)
60 {
61 /* use atan2 to distinguish -0. from 0. */
62 if (y > 0. || (y == 0. && atan2(y, -1.) > 0.)) {
63 return fabs(x);
64 } else {
65 return -fabs(x);
66 }
67 }
68 #endif /* HAVE_COPYSIGN */
69
70 #ifndef HAVE_ROUND
71 double
round(double x)72 round(double x)
73 {
74 double absx, y;
75 absx = fabs(x);
76 y = floor(absx);
77 if (absx - y >= 0.5)
78 y += 1.0;
79 return copysign(y, x);
80 }
81 #endif /* HAVE_ROUND */
82
83 static const unsigned int BitLengthTable[32] = {
84 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
85 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
86 };
87
_Py_bit_length(unsigned long d)88 unsigned int _Py_bit_length(unsigned long d) {
89 unsigned int d_bits = 0;
90 while (d >= 32) {
91 d_bits += 6;
92 d >>= 6;
93 }
94 d_bits += BitLengthTable[d];
95 return d_bits;
96 }
97