]> gitweb.factorcode.org Git - factor.git/blob - vm/bitwise_hacks.hpp
vm: Make macos almost compile.
[factor.git] / vm / bitwise_hacks.hpp
1 namespace factor {
2
3 inline cell log2(cell x) {
4   cell n;
5 #if defined(FACTOR_X86)
6 #if defined(_MSC_VER)
7   _BitScanReverse((unsigned long*)&n, x);
8 #else
9   asm("bsr %1, %0;" : "=r"(n) : "r"(x));
10 #endif
11
12 #elif defined(FACTOR_AMD64)
13 #if defined(_MSC_VER)
14   n = 0;
15   _BitScanReverse64((unsigned long*)&n, x);
16 #else
17   asm("bsr %1, %0;" : "=r"(n) : "r"(x));
18 #endif
19
20 #elif defined(FACTOR_ARM64)
21 #if defined(_MSC_VER)
22   n = 0;
23   _BitScanReverse64((unsigned long*)&n, x);
24 #else
25   asm("bsr %1, %0;" : "=r"(n) : "r"(x));
26 #endif
27
28 #elif defined(FACTOR_PPC64)
29 #if defined(__GNUC__)
30   n = (63 - __builtin_clzll(x));
31 #else
32 #error Unsupported compiler
33 #endif
34
35 #elif defined(FACTOR_PPC32)
36 #if defined(__GNUC__)
37   n = (31 - __builtin_clz(x));
38 #else
39 #error Unsupported compiler
40 #endif
41
42 #else
43 #error Unsupported CPU
44 #endif
45   return n;
46 }
47
48 inline cell rightmost_clear_bit(cell x) { return log2(~x & (x + 1)); }
49
50 inline cell rightmost_set_bit(cell x) { return log2(x & (~x + 1)); }
51
52 inline cell popcount(cell x) {
53 #if defined(__GNUC__)
54 #ifdef FACTOR_64
55   return __builtin_popcountll(x);
56 #else
57   return __builtin_popcount(x);
58 #endif
59 #else
60 #ifdef FACTOR_64
61   uint64_t k1 = 0x5555555555555555ll;
62   uint64_t k2 = 0x3333333333333333ll;
63   uint64_t k4 = 0x0f0f0f0f0f0f0f0fll;
64   uint64_t kf = 0x0101010101010101ll;
65   cell ks = 56;
66 #else
67   uint32_t k1 = 0x55555555;
68   uint32_t k2 = 0x33333333;
69   uint32_t k4 = 0xf0f0f0f;
70   uint32_t kf = 0x1010101;
71   cell ks = 24;
72 #endif
73
74   x = x - ((x >> 1) & k1);         // put count of each 2 bits into those 2 bits
75   x = (x & k2) + ((x >> 2) & k2);  // put count of each 4 bits into those 4 bits
76   x = (x + (x >> 4)) & k4;         // put count of each 8 bits into those 8 bits
77   x = (x * kf) >> ks;  // returns 8 most significant bits of x + (x<<8) +
78                        // (x<<16) + (x<<24) + ...
79
80   return x;
81 #endif
82 }
83
84 inline bool bitmap_p(uint8_t* bitmap, cell index) {
85   cell byte = index >> 3;
86   cell bit = index & 7;
87   return (bitmap[byte] & (1 << bit)) != 0;
88 }
89
90 }