xref: /freebsd/contrib/llvm-project/compiler-rt/lib/builtins/popcountdi2.c (revision e25152834cdf3b353892835a4f3b157e066a8ed4)
10b57cec5SDimitry Andric //===-- popcountdi2.c - Implement __popcountdi2 ---------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements __popcountdi2 for the compiler_rt library.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "int_lib.h"
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric // Returns: count of 1 bits
160b57cec5SDimitry Andric 
__popcountdi2(di_int a)17*5ffd83dbSDimitry Andric COMPILER_RT_ABI int __popcountdi2(di_int a) {
180b57cec5SDimitry Andric   du_int x2 = (du_int)a;
190b57cec5SDimitry Andric   x2 = x2 - ((x2 >> 1) & 0x5555555555555555uLL);
200b57cec5SDimitry Andric   // Every 2 bits holds the sum of every pair of bits (32)
210b57cec5SDimitry Andric   x2 = ((x2 >> 2) & 0x3333333333333333uLL) + (x2 & 0x3333333333333333uLL);
220b57cec5SDimitry Andric   // Every 4 bits holds the sum of every 4-set of bits (3 significant bits) (16)
230b57cec5SDimitry Andric   x2 = (x2 + (x2 >> 4)) & 0x0F0F0F0F0F0F0F0FuLL;
240b57cec5SDimitry Andric   // Every 8 bits holds the sum of every 8-set of bits (4 significant bits) (8)
250b57cec5SDimitry Andric   su_int x = (su_int)(x2 + (x2 >> 32));
260b57cec5SDimitry Andric   // The lower 32 bits hold four 16 bit sums (5 significant bits).
270b57cec5SDimitry Andric   //   Upper 32 bits are garbage
280b57cec5SDimitry Andric   x = x + (x >> 16);
290b57cec5SDimitry Andric   // The lower 16 bits hold two 32 bit sums (6 significant bits).
300b57cec5SDimitry Andric   //   Upper 16 bits are garbage
310b57cec5SDimitry Andric   return (x + (x >> 8)) & 0x0000007F; // (7 significant bits)
320b57cec5SDimitry Andric }
33