xref: /haiku/src/system/libroot/posix/musl/internal/atomic.h (revision 21258e2674226d6aa732321b6f8494841895af5f)
1 #ifndef _ATOMIC_H
2 #define _ATOMIC_H
3 
4 #include <stdint.h>
5 
6 #include "atomic_arch.h"
7 
8 #ifndef a_ctz_32
9 #define a_ctz_32 a_ctz_32
10 static inline int a_ctz_32(uint32_t x)
11 {
12 #ifdef a_clz_32
13 	return 31-a_clz_32(x&-x);
14 #else
15 	static const char debruijn32[32] = {
16 		0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13,
17 		31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14
18 	};
19 	return debruijn32[(x&-x)*0x076be629 >> 27];
20 #endif
21 }
22 #endif
23 
24 #ifndef a_ctz_64
25 #define a_ctz_64 a_ctz_64
26 static inline int a_ctz_64(uint64_t x)
27 {
28 	static const char debruijn64[64] = {
29 		0, 1, 2, 53, 3, 7, 54, 27, 4, 38, 41, 8, 34, 55, 48, 28,
30 		62, 5, 39, 46, 44, 42, 22, 9, 24, 35, 59, 56, 49, 18, 29, 11,
31 		63, 52, 6, 26, 37, 40, 33, 47, 61, 45, 43, 21, 23, 58, 17, 10,
32 		51, 25, 36, 32, 60, 20, 57, 16, 50, 31, 19, 15, 30, 14, 13, 12
33 	};
34 	if (sizeof(long) < 8) {
35 		uint32_t y = x;
36 		if (!y) {
37 			y = x>>32;
38 			return 32 + a_ctz_32(y);
39 		}
40 		return a_ctz_32(y);
41 	}
42 	return debruijn64[(x&-x)*0x022fdd63cc95386dull >> 58];
43 }
44 #endif
45 
46 static inline int a_ctz_l(unsigned long x)
47 {
48 	return (sizeof(long) < 8) ? a_ctz_32(x) : a_ctz_64(x);
49 }
50 
51 #ifndef a_clz_64
52 #define a_clz_64 a_clz_64
53 static inline int a_clz_64(uint64_t x)
54 {
55 #ifdef a_clz_32
56 	if (x>>32)
57 		return a_clz_32(x>>32);
58 	return a_clz_32(x) + 32;
59 #else
60 	uint32_t y;
61 	int r;
62 	if (x>>32) y=x>>32, r=0; else y=x, r=32;
63 	if (y>>16) y>>=16; else r |= 16;
64 	if (y>>8) y>>=8; else r |= 8;
65 	if (y>>4) y>>=4; else r |= 4;
66 	if (y>>2) y>>=2; else r |= 2;
67 	return r | !(y>>1);
68 #endif
69 }
70 #endif
71 
72 #endif
73