Detect popcnt instruction at runtime, use it if available.
[folly.git] / folly / Bits.cpp
1 /*
2  * Copyright 2012 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include "folly/Bits.h"
18
19 #include "folly/CpuId.h"
20
21 // None of this is necessary if we're compiling for a target that supports
22 // popcnt
23 #ifndef __POPCNT__
24
25 namespace {
26
27 int popcount_inst(unsigned int x) {
28   asm ("popcntl %0, %0" : "=r" (x) : "0" (x));
29   return x;
30 }
31
32 int popcount_builtin(unsigned int x) {
33   return __builtin_popcount(x);
34 }
35
36 int popcountll_inst(unsigned long long x) {
37   asm ("popcntq %0, %0" : "=r" (x) : "0" (x));
38   return x;
39 }
40
41 int popcountll_builtin(unsigned long long x) {
42   return __builtin_popcountll(x);
43 }
44
45 typedef decltype(popcount_builtin) Type_popcount;
46 typedef decltype(popcountll_builtin) Type_popcountll;
47
48 }  // namespace
49
50 // This function is called on startup to resolve folly::detail::popcount
51 extern "C" Type_popcount* folly_popcount_ifunc() {
52   return folly::CpuId().popcnt() ?  popcount_inst : popcount_builtin;
53 }
54
55 // This function is called on startup to resolve folly::detail::popcountll
56 extern "C" Type_popcountll* folly_popcountll_ifunc() {
57   return folly::CpuId().popcnt() ?  popcountll_inst : popcountll_builtin;
58 }
59
60 namespace folly {
61 namespace detail {
62
63 // Call folly_popcount_ifunc on startup to resolve to either popcount_inst
64 // or popcount_builtin
65 int popcount(unsigned int x)
66   __attribute__((ifunc("folly_popcount_ifunc")));
67
68 // Call folly_popcount_ifunc on startup to resolve to either popcountll_inst
69 // or popcountll_builtin
70 int popcountll(unsigned long long x)
71   __attribute__((ifunc("folly_popcountll_ifunc")));
72
73 }  // namespace detail
74 }  // namespace folly
75
76 #endif  /* !__POPCNT__ */
77