BitOps.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. /// <summary>
  13. /// Utility methods for intrinsic bit-twiddling operations.
  14. /// The methods use hardware intrinsics when available on the underlying platform,
  15. /// otherwise they use optimized software fallbacks.
  16. /// </summary>
  17. internal static class BitOps
  18. {
  19. // C# no-alloc optimization that directly wraps the data section of the dll (similar to string constants)
  20. // https://github.com/dotnet/roslyn/pull/24621
  21. private static ReadOnlySpan<byte> s_TrailingZeroCountDeBruijn => new byte[32]
  22. {
  23. 00, 01, 28, 02, 29, 14, 24, 03,
  24. 30, 22, 20, 15, 25, 17, 04, 08,
  25. 31, 27, 13, 23, 21, 19, 16, 07,
  26. 26, 12, 18, 06, 11, 05, 10, 09
  27. };
  28. private static ReadOnlySpan<byte> s_Log2DeBruijn => new byte[32]
  29. {
  30. 00, 09, 01, 10, 13, 21, 02, 29,
  31. 11, 14, 16, 18, 22, 25, 03, 30,
  32. 08, 12, 20, 28, 15, 17, 24, 07,
  33. 19, 27, 23, 06, 26, 05, 04, 31
  34. };
  35. /// <summary>
  36. /// Count the number of trailing zero bits in an integer value.
  37. /// Similar in behavior to the x86 instruction TZCNT.
  38. /// </summary>
  39. /// <param name="value">The value.</param>
  40. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  41. public static int TrailingZeroCount(int value)
  42. => TrailingZeroCount((uint)value);
  43. /// <summary>
  44. /// Count the number of trailing zero bits in an integer value.
  45. /// Similar in behavior to the x86 instruction TZCNT.
  46. /// </summary>
  47. /// <param name="value">The value.</param>
  48. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  49. public static int TrailingZeroCount(uint value)
  50. {
  51. if (Bmi1.IsSupported)
  52. {
  53. // TZCNT contract is 0->32
  54. return (int)Bmi1.TrailingZeroCount(value);
  55. }
  56. // Unguarded fallback contract is 0->0
  57. if (value == 0)
  58. {
  59. return 32;
  60. }
  61. // uint.MaxValue >> 27 is always in range [0 - 31] so we use Unsafe.AddByteOffset to avoid bounds check
  62. return Unsafe.AddByteOffset(
  63. // Using deBruijn sequence, k=2, n=5 (2^5=32) : 0b_0000_0111_0111_1100_1011_0101_0011_0001u
  64. ref MemoryMarshal.GetReference(s_TrailingZeroCountDeBruijn),
  65. // uint|long -> IntPtr cast on 32-bit platforms does expensive overflow checks not needed here
  66. (IntPtr)(int)(((value & (uint)-(int)value) * 0x077CB531u) >> 27)); // Multi-cast mitigates redundant conv.u8
  67. }
  68. /// <summary>
  69. /// Count the number of trailing zero bits in a mask.
  70. /// Similar in behavior to the x86 instruction TZCNT.
  71. /// </summary>
  72. /// <param name="value">The value.</param>
  73. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  74. public static int TrailingZeroCount(long value)
  75. => TrailingZeroCount((ulong)value);
  76. /// <summary>
  77. /// Count the number of trailing zero bits in a mask.
  78. /// Similar in behavior to the x86 instruction TZCNT.
  79. /// </summary>
  80. /// <param name="value">The value.</param>
  81. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  82. public static int TrailingZeroCount(ulong value)
  83. {
  84. if (Bmi1.X64.IsSupported)
  85. {
  86. // TZCNT contract is 0->64
  87. return (int)Bmi1.X64.TrailingZeroCount(value);
  88. }
  89. uint lo = (uint)value;
  90. if (lo == 0)
  91. {
  92. return 32 + TrailingZeroCount((uint)(value >> 32));
  93. }
  94. return TrailingZeroCount(lo);
  95. }
  96. /// <summary>
  97. /// Count the number of leading zero bits in a mask.
  98. /// Similar in behavior to the x86 instruction LZCNT.
  99. /// </summary>
  100. /// <param name="value">The value.</param>
  101. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  102. public static int LeadingZeroCount(uint value)
  103. {
  104. if (Lzcnt.IsSupported)
  105. {
  106. // LZCNT contract is 0->32
  107. return (int)Lzcnt.LeadingZeroCount(value);
  108. }
  109. // Unguarded fallback contract is 0->31
  110. if (value == 0)
  111. {
  112. return 32;
  113. }
  114. return 31 - Log2SoftwareFallback(value);
  115. }
  116. /// <summary>
  117. /// Count the number of leading zero bits in a mask.
  118. /// Similar in behavior to the x86 instruction LZCNT.
  119. /// </summary>
  120. /// <param name="value">The value.</param>
  121. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  122. public static int LeadingZeroCount(ulong value)
  123. {
  124. if (Lzcnt.X64.IsSupported)
  125. {
  126. // LZCNT contract is 0->64
  127. return (int)Lzcnt.X64.LeadingZeroCount(value);
  128. }
  129. uint hi = (uint)(value >> 32);
  130. if (hi == 0)
  131. {
  132. return 32 + LeadingZeroCount((uint)value);
  133. }
  134. return LeadingZeroCount(hi);
  135. }
  136. /// <summary>
  137. /// Returns the integer (floor) log of the specified value, base 2.
  138. /// Note that by convention, input value 0 returns 0 since Log(0) is undefined.
  139. /// </summary>
  140. /// <param name="value">The value.</param>
  141. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  142. public static int Log2(uint value)
  143. {
  144. // value lzcnt actual expected
  145. // ..0000 32 0 0 (by convention, guard clause)
  146. // ..0001 31 31-31 0
  147. // ..0010 30 31-30 1
  148. // 0010.. 2 31-2 29
  149. // 0100.. 1 31-1 30
  150. // 1000.. 0 31-0 31
  151. if (Lzcnt.IsSupported)
  152. {
  153. // Enforce conventional contract 0->0 (Log(0) is undefined)
  154. if (value == 0)
  155. {
  156. return 0;
  157. }
  158. // LZCNT contract is 0->32
  159. return 31 - (int)Lzcnt.LeadingZeroCount(value);
  160. }
  161. // Fallback contract is 0->0
  162. return Log2SoftwareFallback(value);
  163. }
  164. /// <summary>
  165. /// Returns the integer (floor) log of the specified value, base 2.
  166. /// Note that by convention, input value 0 returns 0 since Log(0) is undefined.
  167. /// Does not directly use any hardware intrinsics, nor does it incur branching.
  168. /// </summary>
  169. /// <param name="value">The value.</param>
  170. private static int Log2SoftwareFallback(uint value)
  171. {
  172. // No AggressiveInlining due to large method size
  173. // Has conventional contract 0->0 (Log(0) is undefined)
  174. // Fill trailing zeros with ones, eg 00010010 becomes 00011111
  175. value |= value >> 01;
  176. value |= value >> 02;
  177. value |= value >> 04;
  178. value |= value >> 08;
  179. value |= value >> 16;
  180. // uint.MaxValue >> 27 is always in range [0 - 31] so we use Unsafe.AddByteOffset to avoid bounds check
  181. return Unsafe.AddByteOffset(
  182. // Using deBruijn sequence, k=2, n=5 (2^5=32) : 0b_0000_0111_1100_0100_1010_1100_1101_1101u
  183. ref MemoryMarshal.GetReference(s_Log2DeBruijn),
  184. // uint|long -> IntPtr cast on 32-bit platforms does expensive overflow checks not needed here
  185. (IntPtr)(int)((value * 0x07C4ACDDu) >> 27));
  186. }
  187. /// <summary>
  188. /// Returns the integer (floor) log of the specified value, base 2.
  189. /// Note that by convention, input value 0 returns 0 since Log(0) is undefined.
  190. /// </summary>
  191. /// <param name="value">The value.</param>
  192. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  193. public static int Log2(ulong value)
  194. {
  195. if (Lzcnt.X64.IsSupported)
  196. {
  197. // Enforce conventional contract 0->0 (Log(0) is undefined)
  198. if (value == 0)
  199. {
  200. return 0;
  201. }
  202. // LZCNT contract is 0->64
  203. return 63 - (int)Lzcnt.X64.LeadingZeroCount(value);
  204. }
  205. uint hi = (uint)(value >> 32);
  206. if (hi == 0)
  207. {
  208. return Log2((uint)value);
  209. }
  210. return 32 + Log2(hi);
  211. }
  212. /// <summary>
  213. /// Rotates the specified value left by the specified number of bits.
  214. /// Similar in behavior to the x86 instruction ROL.
  215. /// </summary>
  216. /// <param name="value">The value to rotate.</param>
  217. /// <param name="offset">The number of bits to rotate by.
  218. /// Any value outside the range [0..31] is treated as congruent mod 32.</param>
  219. /// <returns>The rotated value.</returns>
  220. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  221. public static uint RotateLeft(uint value, int offset)
  222. => (value << offset) | (value >> (32 - offset));
  223. /// <summary>
  224. /// Rotates the specified value left by the specified number of bits.
  225. /// Similar in behavior to the x86 instruction ROL.
  226. /// </summary>
  227. /// <param name="value">The value to rotate.</param>
  228. /// <param name="offset">The number of bits to rotate by.
  229. /// Any value outside the range [0..63] is treated as congruent mod 64.</param>
  230. /// <returns>The rotated value.</returns>
  231. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  232. public static ulong RotateLeft(ulong value, int offset)
  233. => (value << offset) | (value >> (64 - offset));
  234. /// <summary>
  235. /// Rotates the specified value right by the specified number of bits.
  236. /// Similar in behavior to the x86 instruction ROR.
  237. /// </summary>
  238. /// <param name="value">The value to rotate.</param>
  239. /// <param name="offset">The number of bits to rotate by.
  240. /// Any value outside the range [0..31] is treated as congruent mod 32.</param>
  241. /// <returns>The rotated value.</returns>
  242. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  243. public static uint RotateRight(uint value, int offset)
  244. => (value >> offset) | (value << (32 - offset));
  245. /// <summary>
  246. /// Rotates the specified value right by the specified number of bits.
  247. /// Similar in behavior to the x86 instruction ROR.
  248. /// </summary>
  249. /// <param name="value">The value to rotate.</param>
  250. /// <param name="offset">The number of bits to rotate by.
  251. /// Any value outside the range [0..63] is treated as congruent mod 64.</param>
  252. /// <returns>The rotated value.</returns>
  253. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  254. public static ulong RotateRight(ulong value, int offset)
  255. => (value >> offset) | (value << (64 - offset));
  256. /// <summary>
  257. /// Returns the population count (number of bits set) of a mask.
  258. /// Similar in behavior to the x86 instruction POPCNT.
  259. /// </summary>
  260. /// <param name="value">The value.</param>
  261. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  262. public static int PopCount(uint value)
  263. {
  264. if (Popcnt.IsSupported)
  265. {
  266. return (int)Popcnt.PopCount(value);
  267. }
  268. return SoftwareFallback(value);
  269. static int SoftwareFallback(uint value)
  270. {
  271. const uint c1 = 0x_55555555u;
  272. const uint c2 = 0x_33333333u;
  273. const uint c3 = 0x_0F0F0F0Fu;
  274. const uint c4 = 0x_01010101u;
  275. value = value - ((value >> 1) & c1);
  276. value = (value & c2) + ((value >> 2) & c2);
  277. value = (((value + (value >> 4)) & c3) * c4) >> 24;
  278. return (int)value;
  279. }
  280. }
  281. /// <summary>
  282. /// Returns the population count (number of bits set) of a mask.
  283. /// Similar in behavior to the x86 instruction POPCNT.
  284. /// </summary>
  285. /// <param name="value">The value.</param>
  286. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  287. public static int PopCount(ulong value)
  288. {
  289. if (Popcnt.X64.IsSupported)
  290. {
  291. return (int)Popcnt.X64.PopCount(value);
  292. }
  293. #if BIT32
  294. return PopCount((uint)value) // lo
  295. + PopCount((uint)(value >> 32)); // hi
  296. #else
  297. return SoftwareFallback(value);
  298. static int SoftwareFallback(ulong value)
  299. {
  300. const ulong c1 = 0x_55555555_55555555ul;
  301. const ulong c2 = 0x_33333333_33333333ul;
  302. const ulong c3 = 0x_0F0F0F0F_0F0F0F0Ful;
  303. const ulong c4 = 0x_01010101_01010101ul;
  304. value = value - ((value >> 1) & c1);
  305. value = (value & c2) + ((value >> 2) & c2);
  306. value = (((value + (value >> 4)) & c3) * c4) >> 56;
  307. return (int)value;
  308. }
  309. #endif
  310. }
  311. }
  312. }