BitOps.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Runtime.CompilerServices;
  5. using System.Runtime.InteropServices;
  6. using System.Runtime.Intrinsics.X86;
  7. using Internal.Runtime.CompilerServices;
  8. // Some routines inspired by the Stanford Bit Twiddling Hacks by Sean Eron Anderson:
  9. // http://graphics.stanford.edu/~seander/bithacks.html
  10. namespace System
  11. {
  12. internal static class BitOps
  13. {
  14. // C# no-alloc optimization that directly wraps the data section of the dll (similar to string constants)
  15. // https://github.com/dotnet/roslyn/pull/24621
  16. private static ReadOnlySpan<byte> s_TrailingZeroCountDeBruijn => new byte[32]
  17. {
  18. 00, 01, 28, 02, 29, 14, 24, 03,
  19. 30, 22, 20, 15, 25, 17, 04, 08,
  20. 31, 27, 13, 23, 21, 19, 16, 07,
  21. 26, 12, 18, 06, 11, 05, 10, 09
  22. };
  23. private static ReadOnlySpan<byte> s_Log2DeBruijn => new byte[32]
  24. {
  25. 00, 09, 01, 10, 13, 21, 02, 29,
  26. 11, 14, 16, 18, 22, 25, 03, 30,
  27. 08, 12, 20, 28, 15, 17, 24, 07,
  28. 19, 27, 23, 06, 26, 05, 04, 31
  29. };
  30. /// <summary>
  31. /// Count the number of trailing zero bits in an integer value.
  32. /// Similar in behavior to the x86 instruction TZCNT.
  33. /// </summary>
  34. /// <param name="value">The value.</param>
  35. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  36. public static int TrailingZeroCount(int value)
  37. => TrailingZeroCount((uint)value);
  38. /// <summary>
  39. /// Count the number of trailing zero bits in an integer value.
  40. /// Similar in behavior to the x86 instruction TZCNT.
  41. /// </summary>
  42. /// <param name="value">The value.</param>
  43. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  44. public static int TrailingZeroCount(uint value)
  45. {
  46. if (Bmi1.IsSupported)
  47. {
  48. // Note that TZCNT contract specifies 0->32
  49. return (int)Bmi1.TrailingZeroCount(value);
  50. }
  51. // Software fallback has behavior 0->0, so special-case to match intrinsic path 0->32
  52. if (value == 0)
  53. {
  54. return 32;
  55. }
  56. // uint.MaxValue >> 27 is always in range [0 - 31] so we use Unsafe.AddByteOffset to avoid bounds check
  57. return Unsafe.AddByteOffset(
  58. // Using deBruijn sequence, k=2, n=5 (2^5=32) : 0b_0000_0111_0111_1100_1011_0101_0011_0001u
  59. ref MemoryMarshal.GetReference(s_TrailingZeroCountDeBruijn),
  60. // long -> IntPtr cast on 32-bit platforms is expensive - it does overflow checks not needed here
  61. (IntPtr)(int)(((uint)((value & -value) * 0x077CB531u)) >> 27)); // shift over long also expensive on 32-bit
  62. }
  63. /// <summary>
  64. /// Count the number of trailing zero bits in a mask.
  65. /// Similar in behavior to the x86 instruction TZCNT.
  66. /// </summary>
  67. /// <param name="value">The value.</param>
  68. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  69. public static int TrailingZeroCount(long value)
  70. => TrailingZeroCount((ulong)value);
  71. /// <summary>
  72. /// Count the number of trailing zero bits in a mask.
  73. /// Similar in behavior to the x86 instruction TZCNT.
  74. /// </summary>
  75. /// <param name="value">The value.</param>
  76. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  77. public static int TrailingZeroCount(ulong value)
  78. {
  79. if (Bmi1.X64.IsSupported)
  80. {
  81. // Note that TZCNT contract specifies 0->64
  82. return (int)Bmi1.X64.TrailingZeroCount(value);
  83. }
  84. uint lo = (uint)value;
  85. if (lo == 0)
  86. {
  87. return 32 + TrailingZeroCount((uint)(value >> 32));
  88. }
  89. return TrailingZeroCount(lo);
  90. }
  91. /// <summary>
  92. /// Count the number of leading zero bits in a mask.
  93. /// Similar in behavior to the x86 instruction LZCNT.
  94. /// </summary>
  95. /// <param name="value">The value.</param>
  96. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  97. public static int LeadingZeroCount(uint value)
  98. {
  99. if (Lzcnt.IsSupported)
  100. {
  101. // Note that LZCNT contract specifies 0->32
  102. return (int)Lzcnt.LeadingZeroCount(value);
  103. }
  104. // Software fallback has behavior 0->0, so special-case to match intrinsic path 0->32
  105. if (value == 0)
  106. {
  107. return 32;
  108. }
  109. return 31 - Log2(value);
  110. }
  111. /// <summary>
  112. /// Count the number of leading zero bits in a mask.
  113. /// Similar in behavior to the x86 instruction LZCNT.
  114. /// </summary>
  115. /// <param name="value">The value.</param>
  116. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  117. public static int LeadingZeroCount(ulong value)
  118. {
  119. if (Lzcnt.X64.IsSupported)
  120. {
  121. // Note that LZCNT contract specifies 0->64
  122. return (int)Lzcnt.X64.LeadingZeroCount(value);
  123. }
  124. uint hi = (uint)(value >> 32);
  125. if (hi == 0)
  126. {
  127. return 32 + LeadingZeroCount((uint)value);
  128. }
  129. return LeadingZeroCount(hi);
  130. }
  131. /// <summary>
  132. /// Returns the integer (floor) log of the specified value, base 2.
  133. /// Note that by convention, input value 0 returns 0 since Log(0) is undefined.
  134. /// </summary>
  135. /// <param name="value">The value.</param>
  136. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  137. public static int Log2(uint value)
  138. {
  139. // value lzcnt actual expected
  140. // ..0000 32 0 0 (by convention, guard clause)
  141. // ..0001 31 31-31 0
  142. // ..0010 30 31-30 1
  143. // 0010.. 2 31-2 29
  144. // 0100.. 1 31-1 30
  145. // 1000.. 0 31-0 31
  146. if (Lzcnt.IsSupported)
  147. {
  148. // Enforce conventional contract 0->0 (since Log(0) is undefined)
  149. if (value == 0)
  150. {
  151. return 0;
  152. }
  153. // Note that LZCNT contract specifies 0->32
  154. return 31 - (int)Lzcnt.LeadingZeroCount(value);
  155. }
  156. // Already has contract 0->0, without branching
  157. return Log2SoftwareFallback(value);
  158. }
  159. /// <summary>
  160. /// Returns the integer (floor) log of the specified value, base 2.
  161. /// Note that by convention, input value 0 returns 0 since Log(0) is undefined.
  162. /// Does not incur branching.
  163. /// </summary>
  164. /// <param name="value">The value.</param>
  165. private static int Log2SoftwareFallback(uint value)
  166. {
  167. // No AggressiveInlining due to large method size
  168. value |= value >> 01;
  169. value |= value >> 02;
  170. value |= value >> 04;
  171. value |= value >> 08;
  172. value |= value >> 16;
  173. // uint.MaxValue >> 27 is always in range [0 - 31] so we use Unsafe.AddByteOffset to avoid bounds check
  174. return Unsafe.AddByteOffset(
  175. // Using deBruijn sequence, k=2, n=5 (2^5=32) : 0b_0000_0111_1100_0100_1010_1100_1101_1101u
  176. ref MemoryMarshal.GetReference(s_Log2DeBruijn),
  177. // long -> IntPtr cast on 32-bit platforms is expensive - it does overflow checks not needed here
  178. (IntPtr)(int)((value * 0x07C4ACDDu) >> 27));
  179. }
  180. /// <summary>
  181. /// Returns the integer (floor) log of the specified value, base 2.
  182. /// Note that by convention, input value 0 returns 0 since Log(0) is undefined.
  183. /// </summary>
  184. /// <param name="value">The value.</param>
  185. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  186. public static int Log2(ulong value)
  187. {
  188. if (Lzcnt.X64.IsSupported)
  189. {
  190. // Enforce conventional contract 0->0 (since Log(0) is undefined)
  191. if (value == 0)
  192. {
  193. return 0;
  194. }
  195. // Note that LZCNT contract specifies 0->64
  196. return 63 - (int)Lzcnt.X64.LeadingZeroCount(value);
  197. }
  198. uint hi = (uint)(value >> 32);
  199. if (hi == 0)
  200. {
  201. return Log2((uint)value);
  202. }
  203. return 32 + Log2(hi);
  204. }
  205. }
  206. }