]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - contrib/compiler-rt/lib/ctzsi2.c
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / contrib / compiler-rt / lib / ctzsi2.c
1 /* ===-- ctzsi2.c - Implement __ctzsi2 -------------------------------------===
2  *
3  *                     The LLVM Compiler Infrastructure
4  *
5  * This file is dual licensed under the MIT and the University of Illinois Open
6  * Source Licenses. See LICENSE.TXT for details.
7  *
8  * ===----------------------------------------------------------------------===
9  *
10  * This file implements __ctzsi2 for the compiler_rt library.
11  *
12  * ===----------------------------------------------------------------------===
13  */
14 #include "abi.h"
15
16 #include "int_lib.h"
17
18 /* Returns: the number of trailing 0-bits */
19
20 /* Precondition: a != 0 */
21
22 COMPILER_RT_ABI si_int
23 __ctzsi2(si_int a)
24 {
25     su_int x = (su_int)a;
26     si_int t = ((x & 0x0000FFFF) == 0) << 4;  /* if (x has no small bits) t = 16 else 0 */
27     x >>= t;           /* x = [0 - 0xFFFF] + higher garbage bits */
28     su_int r = t;       /* r = [0, 16]  */
29     /* return r + ctz(x) */
30     t = ((x & 0x00FF) == 0) << 3;
31     x >>= t;           /* x = [0 - 0xFF] + higher garbage bits */
32     r += t;            /* r = [0, 8, 16, 24] */
33     /* return r + ctz(x) */
34     t = ((x & 0x0F) == 0) << 2;
35     x >>= t;           /* x = [0 - 0xF] + higher garbage bits */
36     r += t;            /* r = [0, 4, 8, 12, 16, 20, 24, 28] */
37     /* return r + ctz(x) */
38     t = ((x & 0x3) == 0) << 1;
39     x >>= t;
40     x &= 3;            /* x = [0 - 3] */
41     r += t;            /* r = [0 - 30] and is even */
42     /* return r + ctz(x) */
43
44 /*  The branch-less return statement below is equivalent
45  *  to the following switch statement:
46  *     switch (x)
47  *    {
48  *     case 0:
49  *         return r + 2;
50  *     case 2:
51  *         return r + 1;
52  *     case 1:
53  *     case 3:
54  *         return r;
55  *     }
56  */
57     return r + ((2 - (x >> 1)) & -((x & 1) == 0));
58 }