|
| 1 | +/*************************************************************************** |
| 2 | + * Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and * |
| 3 | + * Martin Renou * |
| 4 | + * Copyright (c) QuantStack * |
| 5 | + * Copyright (c) Serge Guelton * |
| 6 | + * Copyright (c) Marco Barbone * |
| 7 | + * * |
| 8 | + * Distributed under the terms of the BSD 3-Clause License. * |
| 9 | + * * |
| 10 | + * The full license is in the file LICENSE, distributed with this software. * |
| 11 | + ****************************************************************************/ |
| 12 | + |
| 13 | +#ifndef XSIMD_COMMON_BITWISE_HPP |
| 14 | +#define XSIMD_COMMON_BITWISE_HPP |
| 15 | + |
| 16 | +#include "./xsimd_common_details.hpp" |
| 17 | + |
| 18 | +#include <climits> |
| 19 | +#include <cstddef> |
| 20 | + |
| 21 | +namespace xsimd |
| 22 | +{ |
| 23 | + |
| 24 | + namespace kernel |
| 25 | + { |
| 26 | + |
| 27 | + using namespace types; |
| 28 | + |
| 29 | + namespace detail |
| 30 | + { |
| 31 | + // bit i is set when i / s is even: 0x55.. for s == 1, 0x33.. for |
| 32 | + // s == 2, 0x0f0f.. for s == 4, and so on up to s == bits / 2 |
| 33 | + template <class U> |
| 34 | + constexpr U alternating_mask(unsigned s) noexcept |
| 35 | + { |
| 36 | + U m = 0; |
| 37 | + for (unsigned i = 0; i < sizeof(U) * CHAR_BIT; ++i) |
| 38 | + if (((i / s) & 1u) == 0u) |
| 39 | + m = U(m | U(U(1) << i)); |
| 40 | + return m; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + // popcount |
| 45 | + // SWAR fold, popcount64b from Hacker's Delight, listed in |
| 46 | + // https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation |
| 47 | + template <class A, class T, class /*=std::enable_if_t<std::is_integral_v<T>>*/> |
| 48 | + XSIMD_INLINE batch<T, A> popcount(batch<T, A> const& self, requires_arch<common>) noexcept |
| 49 | + { |
| 50 | + using U = as_unsigned_integer_t<T>; |
| 51 | + using b_type = batch<U, A>; |
| 52 | + constexpr std::size_t bits = sizeof(T) * CHAR_BIT; |
| 53 | + |
| 54 | + b_type x = bitwise_cast<U>(self); |
| 55 | + x = x - ((x >> 1) & b_type(detail::alternating_mask<U>(1))); |
| 56 | + b_type const m2(detail::alternating_mask<U>(2)); |
| 57 | + x = (x & m2) + ((x >> 2) & m2); |
| 58 | + x = (x + (x >> 4)) & b_type(detail::alternating_mask<U>(4)); |
| 59 | + if constexpr (bits >= 16) |
| 60 | + x = (x + (x >> 8)) & b_type(detail::alternating_mask<U>(8)); |
| 61 | + if constexpr (bits >= 32) |
| 62 | + x = (x + (x >> 16)) & b_type(detail::alternating_mask<U>(16)); |
| 63 | + if constexpr (bits >= 64) |
| 64 | + x = (x + (x >> 32)) & b_type(detail::alternating_mask<U>(32)); |
| 65 | + return bitwise_cast<T>(x); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +#endif |
0 commit comments