2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
11 #ifndef VPX_VPX_PORTS_BITOPS_H_
12 #define VPX_VPX_PORTS_BITOPS_H_
16 #include "vpx_ports/msvc.h"
19 #if defined(_M_X64) || defined(_M_IX86)
21 #define USE_MSC_INTRINSICS
29 // These versions of get_lsb() and get_msb() are only valid when n != 0
30 // because all of the optimized versions are undefined when n == 0:
31 // https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
33 // use GNU builtins where available.
34 #if defined(__GNUC__) && \
35 ((__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || __GNUC__ >= 4)
36 static INLINE int get_lsb(unsigned int n) {
38 return __builtin_ctz(n);
41 static INLINE int get_msb(unsigned int n) {
43 return 31 ^ __builtin_clz(n);
45 #elif defined(USE_MSC_INTRINSICS)
46 #pragma intrinsic(_BitScanForward)
47 #pragma intrinsic(_BitScanReverse)
49 static INLINE int get_lsb(unsigned int n) {
50 unsigned long first_set_bit; // NOLINT(runtime/int)
51 _BitScanForward(&first_set_bit, n);
55 static INLINE int get_msb(unsigned int n) {
56 unsigned long first_set_bit;
58 _BitScanReverse(&first_set_bit, n);
61 #undef USE_MSC_INTRINSICS
63 static INLINE int get_lsb(unsigned int n) {
66 for (i = 0; i < 32 && !(n & 1); ++i) n >>= 1;
70 // Returns (int)floor(log2(n)). n must be > 0.
71 static INLINE int get_msb(unsigned int n) {
73 unsigned int value = n;
78 for (i = 4; i >= 0; --i) {
79 const int shift = (1 << i);
80 const unsigned int x = value >> shift;
94 #endif // VPX_VPX_PORTS_BITOPS_H_