2 * Copyright 2012 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "folly/Bits.h"
19 #include "folly/CpuId.h"
21 // None of this is necessary if we're compiling for a target that supports
27 int popcount_inst(unsigned int x) {
29 asm ("popcntl %1, %0" : "=r" (n) : "r" (x));
33 int popcount_builtin(unsigned int x) {
34 return __builtin_popcount(x);
37 int popcountll_inst(unsigned long long x) {
39 asm ("popcntq %1, %0" : "=r" (n) : "r" (x));
43 int popcountll_builtin(unsigned long long x) {
44 return __builtin_popcountll(x);
47 typedef decltype(popcount_builtin) Type_popcount;
48 typedef decltype(popcountll_builtin) Type_popcountll;
52 // This function is called on startup to resolve folly::detail::popcount
53 extern "C" Type_popcount* folly_popcount_ifunc() {
54 return folly::CpuId().popcnt() ? popcount_inst : popcount_builtin;
57 // This function is called on startup to resolve folly::detail::popcountll
58 extern "C" Type_popcountll* folly_popcountll_ifunc() {
59 return folly::CpuId().popcnt() ? popcountll_inst : popcountll_builtin;
65 // Call folly_popcount_ifunc on startup to resolve to either popcount_inst
66 // or popcount_builtin
67 int popcount(unsigned int x)
68 __attribute__((ifunc("folly_popcount_ifunc")));
70 // Call folly_popcount_ifunc on startup to resolve to either popcountll_inst
71 // or popcountll_builtin
72 int popcountll(unsigned long long x)
73 __attribute__((ifunc("folly_popcountll_ifunc")));
78 #endif /* !__POPCNT__ */