• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //---------------------------------------------------------------------------//
2 // Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>
3 //
4 // Distributed under the Boost Software License, Version 1.0
5 // See accompanying file LICENSE_1_0.txt or copy at
6 // http://www.boost.org/LICENSE_1_0.txt
7 //
8 // See http://boostorg.github.com/compute for more information.
9 //---------------------------------------------------------------------------//
10 
11 #ifndef BOOST_COMPUTE_FUNCTIONAL_POPCOUNT_HPP
12 #define BOOST_COMPUTE_FUNCTIONAL_POPCOUNT_HPP
13 
14 #include <boost/compute/function.hpp>
15 #include <boost/compute/type_traits/type_name.hpp>
16 
17 namespace boost {
18 namespace compute {
19 
20 /// Returns the number of non-zero bits in \p x.
21 ///
22 /// \see_opencl_ref{popcount}
23 template<class T>
24 class popcount : public function<T(T)>
25 {
26 public:
popcount()27     popcount()
28         : function<T(T)>("boost_popcount")
29     {
30         std::stringstream s;
31         s << "inline " << type_name<T>() << " boost_popcount"
32           << "(const " << type_name<T>() << " x)\n"
33           << "{\n"
34           // use built-in popcount if opencl 1.2 is supported
35           << "#if __OPENCL_VERSION__ >= 120\n"
36           << "    return popcount(x);\n"
37           // fallback to generic popcount() implementation
38           << "#else\n"
39           << "    " << type_name<T>() << " count = 0;\n"
40           << "    for(" << type_name<T>() << " i = 0; i < sizeof(i) * CHAR_BIT; i++){\n"
41           << "        if(x & (" << type_name<T>() << ") 1 << i){\n"
42           << "            count++;\n"
43           << "        }\n"
44           << "    }\n"
45           << "    return count;\n"
46           << "#endif\n"
47           << "}\n";
48         this->set_source(s.str());
49     }
50 };
51 
52 } // end compute namespace
53 } // end boost namespace
54 
55 #endif // BOOST_COMPUTE_FUNCTIONAL_POPCOUNT_HPP
56