155505Sshin/* ===-- popcountti2.c - Implement __popcountti2 ----------------------------===
255505Sshin *
355505Sshin *                     The LLVM Compiler Infrastructure
455505Sshin *
555505Sshin * This file is dual licensed under the MIT and the University of Illinois Open
655505Sshin * Source Licenses. See LICENSE.TXT for details.
755505Sshin *
855505Sshin * ===----------------------------------------------------------------------===
955505Sshin *
1055505Sshin * This file implements __popcountti2 for the compiler_rt library.
1155505Sshin *
1255505Sshin * ===----------------------------------------------------------------------===
1355505Sshin */
1455505Sshin
1555505Sshin#include "int_lib.h"
1655505Sshin
1755505Sshin#ifdef CRT_HAS_128BIT
1855505Sshin
1955505Sshin/* Returns: count of 1 bits */
2055505Sshin
2155505SshinCOMPILER_RT_ABI si_int
2255505Sshin__popcountti2(ti_int a)
2355505Sshin{
2455505Sshin    tu_int x3 = (tu_int)a;
2555505Sshin    x3 = x3 - ((x3 >> 1) & (((tu_int)0x5555555555555555uLL << 64) |
2655505Sshin                                     0x5555555555555555uLL));
27122107Sume    /* Every 2 bits holds the sum of every pair of bits (64) */
2855505Sshin    x3 = ((x3 >> 2) & (((tu_int)0x3333333333333333uLL << 64) | 0x3333333333333333uLL))
2955505Sshin       + (x3 & (((tu_int)0x3333333333333333uLL << 64) | 0x3333333333333333uLL));
3055505Sshin    /* Every 4 bits holds the sum of every 4-set of bits (3 significant bits) (32) */
31119071Sobrien    x3 = (x3 + (x3 >> 4))
3262583Sitojun       & (((tu_int)0x0F0F0F0F0F0F0F0FuLL << 64) | 0x0F0F0F0F0F0F0F0FuLL);
3369640Sobrien    /* Every 8 bits holds the sum of every 8-set of bits (4 significant bits) (16) */
3459266Ssteve    du_int x2 = (du_int)(x3 + (x3 >> 64));
3559266Ssteve    /* Every 8 bits holds the sum of every 8-set of bits (5 significant bits) (8) */
3659266Ssteve    su_int x = (su_int)(x2 + (x2 >> 32));
3759266Ssteve    /* Every 8 bits holds the sum of every 8-set of bits (6 significant bits) (4) */
3855505Sshin    x = x + (x >> 16);
3962583Sitojun    /* Every 8 bits holds the sum of every 8-set of bits (7 significant bits) (2) */
4062583Sitojun    /* Upper 16 bits are garbage */
4155505Sshin    return (x + (x >> 8)) & 0xFF;  /* (8 significant bits) */
4255505Sshin}
4362583Sitojun
4455505Sshin#endif /* CRT_HAS_128BIT */
4558906Sshin