* lib/count-one-bits.h: Add comments. (From Bruno Haible.)
[gnulib.git] / lib / count-one-bits.h
1 /* count-one-bits.h -- counts the number of 1-bits in a word.
2    Copyright (C) 2007 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
17
18 /* Written by Ben Pfaff.  */
19
20 #ifndef COUNT_ONE_BITS_H
21 # define COUNT_ONE_BITS_H 1
22
23 #include <stdlib.h>
24 #include "verify.h"
25
26 /* Expand the code which computes the number of 1-bits of the local
27    variable 'x' of type TYPE (an unsigned integer type) and returns it
28    from the current function.  */
29 #if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR >= 4)
30 #define COUNT_ONE_BITS(BUILTIN, TYPE)              \
31         return BUILTIN (x);
32 #else
33 #define COUNT_ONE_BITS(BUILTIN, TYPE)                                       \
34         verify ((TYPE) -1 >> 31 >> 31 <= 3); /* TYPE has at most 64 bits */ \
35         int count = count_one_bits_32 (x);                                  \
36         if (1 < (TYPE) -1 >> 31) /* TYPE has more than 32 bits? */          \
37           count += count_one_bits_32 (x >> 31 >> 1);                        \
38         return count;
39
40 /* Compute and return the the number of 1-bits set in the least
41    significant 32 bits of X. */
42 static inline int
43 count_one_bits_32 (unsigned int x)
44 {
45   x = ((x & 0xaaaaaaaaU) >> 1) + (x & 0x55555555U);
46   x = ((x & 0xccccccccU) >> 2) + (x & 0x33333333U);
47   x = (x >> 16) + (x & 0xffff);
48   x = ((x & 0xf0f0) >> 4) + (x & 0x0f0f);
49   return (x >> 8) + (x & 0x00ff);
50 }
51 #endif
52
53 /* Compute and return the number of 1-bits set in X. */
54 static inline int
55 count_one_bits (unsigned int x)
56 {
57   COUNT_ONE_BITS (__builtin_popcount, unsigned int);
58 }
59
60 /* Compute and return the number of 1-bits set in X. */
61 static inline int
62 count_one_bits_l (unsigned long int x)
63 {
64   COUNT_ONE_BITS (__builtin_popcountl, unsigned long int);
65 }
66
67 #if HAVE_UNSIGNED_LONG_LONG_INT
68 /* Compute and return the number of 1-bits set in X. */
69 static inline int
70 count_one_bits_ll (unsigned long long int x)
71 {
72   COUNT_ONE_BITS (__builtin_popcountll, unsigned long long int);
73 }
74 #endif
75
76 #endif /* COUNT_ONE_BITS_H */