138451Smsmith/* ===-- popcountdi2.c - Implement __popcountdi2 ----------------------------===
238451Smsmith *
338451Smsmith *                     The LLVM Compiler Infrastructure
438451Smsmith *
538451Smsmith * This file is dual licensed under the MIT and the University of Illinois Open
638451Smsmith * Source Licenses. See LICENSE.TXT for details.
738451Smsmith *
838451Smsmith * ===----------------------------------------------------------------------===
938451Smsmith *
1084221Sdillon * This file implements __popcountdi2 for the compiler_rt library.
1184221Sdillon *
1284221Sdillon * ===----------------------------------------------------------------------===
1338451Smsmith */
1438451Smsmith
1538451Smsmith#include "int_lib.h"
1638451Smsmith
1738451Smsmith/* Returns: count of 1 bits */
1838451Smsmith
1938451SmsmithCOMPILER_RT_ABI si_int
2038451Smsmith__popcountdi2(di_int a)
2138451Smsmith{
2238451Smsmith    du_int x2 = (du_int)a;
2338451Smsmith    x2 = x2 - ((x2 >> 1) & 0x5555555555555555uLL);
2438451Smsmith    /* Every 2 bits holds the sum of every pair of bits (32) */
2538451Smsmith    x2 = ((x2 >> 2) & 0x3333333333333333uLL) + (x2 & 0x3333333333333333uLL);
2638451Smsmith    /* Every 4 bits holds the sum of every 4-set of bits (3 significant bits) (16) */
2738451Smsmith    x2 = (x2 + (x2 >> 4)) & 0x0F0F0F0F0F0F0F0FuLL;
2838451Smsmith    /* Every 8 bits holds the sum of every 8-set of bits (4 significant bits) (8) */
2938451Smsmith    su_int x = (su_int)(x2 + (x2 >> 32));
3038451Smsmith    /* The lower 32 bits hold four 16 bit sums (5 significant bits). */
3138451Smsmith    /*   Upper 32 bits are garbage */
3238451Smsmith    x = x + (x >> 16);
3338451Smsmith    /* The lower 16 bits hold two 32 bit sums (6 significant bits). */
3438451Smsmith    /*   Upper 16 bits are garbage */
35301056Sian    return (x + (x >> 8)) & 0x0000007F;  /* (7 significant bits) */
3638451Smsmith}
3738451Smsmith