1 /*
2  * D phobos intrinsics for LDC
3  *
4  * From GDC ... public domain!
5  */
6 module ldc.bitmanip;
7 
8 // Check for the right compiler
9 version(LDC)
10 {
11     // OK
12 }
13 else
14 {
15     static assert(false, "This module is only valid for LDC");
16 }
17 
18 int bsf(uint v)
19 {
20     uint m = 1;
21     uint i;
22     for (i = 0; i < 32; i++,m<<=1) {
23         if (v&m)
24         return i;
25     }
26     return i; // supposed to be undefined
27 }
28 
29 int bsr(size_t v)
30 {
31     size_t m = 0x80000000;
32     size_t i;
33     for (i = 32; i ; i--,m>>>=1) {
34     if (v&m)
35         return i-1;
36     }
37     return i; // supposed to be undefined
38 }
39 
40 int bt(size_t* p, size_t bitnum)
41 {
42     return (p[bitnum / (size_t.sizeof*8)] & (1<<(bitnum & ((size_t.sizeof*8)-1)))) ? -1 : 0 ;
43 }
44 
45 int btc(size_t* p, size_t bitnum)
46 {
47     size_t* q = p + (bitnum / (size_t.sizeof*8));
48     size_t mask = 1 << (bitnum & ((size_t.sizeof*8) - 1));
49     int result = *q & mask;
50     *q ^= mask;
51     return result ? -1 : 0;
52 }
53 
54 int btr(size_t* p, size_t bitnum)
55 {
56     size_t* q = p + (bitnum / (size_t.sizeof*8));
57     size_t mask = 1 << (bitnum & ((size_t.sizeof*8) - 1));
58     int result = *q & mask;
59     *q &= ~mask;
60     return result ? -1 : 0;
61 }
62 
63 int bts(size_t* p, size_t bitnum)
64 {
65     size_t* q = p + (bitnum / (size_t.sizeof*8));
66     size_t mask = 1 << (bitnum & ((size_t.sizeof*8) - 1));
67     int result = *q & mask;
68     *q |= mask;
69     return result ? -1 : 0;
70 }
71 
72 pragma(intrinsic, "llvm.bswap.i32")
73     uint bswap(uint val);
74 
75 ubyte  inp(uint p) { throw new Exception("inp intrinsic not yet implemented"); }
76 ushort inpw(uint p) { throw new Exception("inpw intrinsic not yet implemented"); }
77 uint   inpl(uint p) { throw new Exception("inpl intrinsic not yet implemented"); }
78 
79 ubyte  outp(uint p, ubyte v) { throw new Exception("outp intrinsic not yet implemented"); }
80 ushort outpw(uint p, ushort v) { throw new Exception("outpw intrinsic not yet implemented"); }
81 uint   outpl(uint p, uint v) { throw new Exception("outpl intrinsic not yet implemented"); }