Skip to content

Commit 92682bb

Browse files
committed
Add fast CTZ for MSVC and properly guard the builtin checks for gcc and clang.
1 parent ce50807 commit 92682bb

File tree

1 file changed

+30
-3
lines changed

1 file changed

+30
-3
lines changed

src/quicktions.pyx

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,17 +103,44 @@ cdef extern from *:
103103
#define _PyLong_GCD(a, b) (NULL)
104104
#endif
105105
106-
#if defined(__GCC__) && __has_builtin(__builtin_ctz) && __has_builtin(__builtin_ctzl) && __has_builtin(__builtin_ctzll)
106+
#ifdef __has_builtin
107+
#if __has_builtin(__builtin_ctz) && __has_builtin(__builtin_ctzl) && __has_builtin(__builtin_ctzll)
107108
#define __Quicktions_HAS_FAST_CTZ 1
108109
#define __Quicktions_trailing_zeros_uint(x) __builtin_ctz(x)
109110
#define __Quicktions_trailing_zeros_ulong(x) __builtin_ctzl(x)
110111
#define __Quicktions_trailing_zeros_ullong(x) __builtin_ctzll(x)
111-
#elif defined(__clang__) && __has_builtin(__builtin_ctzg)
112+
#elif __has_builtin(__builtin_ctzg)
112113
#define __Quicktions_HAS_FAST_CTZ 1
113114
#define __Quicktions_trailing_zeros_uint(x) __builtin_ctzg(x)
114115
#define __Quicktions_trailing_zeros_ulong(x) __builtin_ctzg(x)
115116
#define __Quicktions_trailing_zeros_ullong(x) __builtin_ctzg(x)
116-
#else
117+
#endif
118+
#elif defined(__GNUC__)
119+
#define __Quicktions_HAS_FAST_CTZ 1
120+
#define __Quicktions_trailing_zeros_uint(x) __builtin_ctz(x)
121+
#define __Quicktions_trailing_zeros_ulong(x) __builtin_ctzl(x)
122+
#define __Quicktions_trailing_zeros_ullong(x) __builtin_ctzll(x)
123+
#elif defined(_MSC_VER) && SIZEOF_INT == 4 && SIZEOF_LONG == 4 && SIZEOF_LONG_LONG == 8
124+
/* Typical Windows config. */
125+
#define __Quicktions_HAS_FAST_CTZ 1
126+
#pragma intrinsic(_BitScanForward, _BitScanForward64)
127+
static CYTHON_INLINE int __Quicktions_trailing_zeros_uint(uint32_t x) {
128+
unsigned long bits;
129+
_BitScanForward(&bits, x);
130+
return (int) bits;
131+
}
132+
static CYTHON_INLINE int __Quicktions_trailing_zeros_ulong(uint32_t x) {
133+
unsigned long bits;
134+
_BitScanForward(&bits, x);
135+
return (int) bits;
136+
}
137+
static CYTHON_INLINE int __Quicktions_trailing_zeros_ullong(uint64_t x) {
138+
unsigned long bits;
139+
_BitScanForward64(&bits, x);
140+
return (int) bits;
141+
}
142+
#endif
143+
#if !defined(__Quicktions_HAS_FAST_CTZ)
117144
#define __Quicktions_HAS_FAST_CTZ 0
118145
#define __Quicktions_trailing_zeros_uint(x) (0)
119146
#define __Quicktions_trailing_zeros_ulong(x) (0)

0 commit comments

Comments
 (0)