bitops.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
  3. *
  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.
  9. */
  10. #ifndef VPX_VPX_PORTS_BITOPS_H_
  11. #define VPX_VPX_PORTS_BITOPS_H_
  12. #include <assert.h>
  13. #include "vpx_ports/msvc.h"
  14. #ifdef _MSC_VER
  15. #if defined(_M_X64) || defined(_M_IX86)
  16. #include <intrin.h>
  17. #define USE_MSC_INTRINSICS
  18. #endif
  19. #endif
  20. #ifdef __cplusplus
  21. extern "C" {
  22. #endif
  23. // These versions of get_msb() are only valid when n != 0 because all
  24. // of the optimized versions are undefined when n == 0:
  25. // https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
  26. // use GNU builtins where available.
  27. #if defined(__GNUC__) && \
  28. ((__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || __GNUC__ >= 4)
  29. static INLINE int get_msb(unsigned int n) {
  30. assert(n != 0);
  31. return 31 ^ __builtin_clz(n);
  32. }
  33. #elif defined(USE_MSC_INTRINSICS)
  34. #pragma intrinsic(_BitScanReverse)
  35. static INLINE int get_msb(unsigned int n) {
  36. unsigned long first_set_bit;
  37. assert(n != 0);
  38. _BitScanReverse(&first_set_bit, n);
  39. return first_set_bit;
  40. }
  41. #undef USE_MSC_INTRINSICS
  42. #else
  43. // Returns (int)floor(log2(n)). n must be > 0.
  44. static INLINE int get_msb(unsigned int n) {
  45. int log = 0;
  46. unsigned int value = n;
  47. int i;
  48. assert(n != 0);
  49. for (i = 4; i >= 0; --i) {
  50. const int shift = (1 << i);
  51. const unsigned int x = value >> shift;
  52. if (x != 0) {
  53. value = x;
  54. log += shift;
  55. }
  56. }
  57. return log;
  58. }
  59. #endif
  60. #ifdef __cplusplus
  61. } // extern "C"
  62. #endif
  63. #endif // VPX_VPX_PORTS_BITOPS_H_