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