crc_x86_clmul.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. // SPDX-License-Identifier: 0BSD
  2. ///////////////////////////////////////////////////////////////////////////////
  3. //
  4. /// \file crc_x86_clmul.h
  5. /// \brief CRC32 and CRC64 implementations using CLMUL instructions.
  6. ///
  7. /// The CRC32 and CRC64 implementations use 32/64-bit x86 SSSE3, SSE4.1, and
  8. /// CLMUL instructions. This is compatible with Elbrus 2000 (E2K) too.
  9. ///
  10. /// They were derived from
  11. /// https://www.researchgate.net/publication/263424619_Fast_CRC_computation
  12. /// and the public domain code from https://github.com/rawrunprotected/crc
  13. /// (URLs were checked on 2023-10-14).
  14. ///
  15. /// While this file has both CRC32 and CRC64 implementations, only one
  16. /// should be built at a time to ensure that crc_simd_body() is inlined
  17. /// even with compilers with which lzma_always_inline expands to plain inline.
  18. /// The version to build is selected by defining BUILDING_CRC32_CLMUL or
  19. /// BUILDING_CRC64_CLMUL before including this file.
  20. ///
  21. /// FIXME: Builds for 32-bit x86 use the assembly .S files by default
  22. /// unless configured with --disable-assembler. Even then the lookup table
  23. /// isn't omitted in crc64_table.c since it doesn't know that assembly
  24. /// code has been disabled.
  25. //
  26. // Authors: Ilya Kurdyukov
  27. // Hans Jansen
  28. // Lasse Collin
  29. // Jia Tan
  30. //
  31. ///////////////////////////////////////////////////////////////////////////////
  32. // This file must not be included more than once.
  33. #ifdef LZMA_CRC_X86_CLMUL_H
  34. # error crc_x86_clmul.h was included twice.
  35. #endif
  36. #define LZMA_CRC_X86_CLMUL_H
  37. #include <immintrin.h>
  38. #if defined(_MSC_VER)
  39. # include <intrin.h>
  40. #elif defined(HAVE_CPUID_H)
  41. # include <cpuid.h>
  42. #endif
  43. // EDG-based compilers (Intel's classic compiler and compiler for E2K) can
  44. // define __GNUC__ but the attribute must not be used with them.
  45. // The new Clang-based ICX needs the attribute.
  46. //
  47. // NOTE: Build systems check for this too, keep them in sync with this.
  48. #if (defined(__GNUC__) || defined(__clang__)) && !defined(__EDG__)
  49. # define crc_attr_target \
  50. __attribute__((__target__("ssse3,sse4.1,pclmul")))
  51. #else
  52. # define crc_attr_target
  53. #endif
  54. #define MASK_L(in, mask, r) r = _mm_shuffle_epi8(in, mask)
  55. #define MASK_H(in, mask, r) \
  56. r = _mm_shuffle_epi8(in, _mm_xor_si128(mask, vsign))
  57. #define MASK_LH(in, mask, low, high) \
  58. MASK_L(in, mask, low); \
  59. MASK_H(in, mask, high)
  60. crc_attr_target
  61. crc_attr_no_sanitize_address
  62. static lzma_always_inline void
  63. crc_simd_body(const uint8_t *buf, const size_t size, __m128i *v0, __m128i *v1,
  64. const __m128i vfold16, const __m128i initial_crc)
  65. {
  66. // Create a vector with 8-bit values 0 to 15. This is used to
  67. // construct control masks for _mm_blendv_epi8 and _mm_shuffle_epi8.
  68. const __m128i vramp = _mm_setr_epi32(
  69. 0x03020100, 0x07060504, 0x0b0a0908, 0x0f0e0d0c);
  70. // This is used to inverse the control mask of _mm_shuffle_epi8
  71. // so that bytes that wouldn't be picked with the original mask
  72. // will be picked and vice versa.
  73. const __m128i vsign = _mm_set1_epi8(-0x80);
  74. // Memory addresses A to D and the distances between them:
  75. //
  76. // A B C D
  77. // [skip_start][size][skip_end]
  78. // [ size2 ]
  79. //
  80. // A and D are 16-byte aligned. B and C are 1-byte aligned.
  81. // skip_start and skip_end are 0-15 bytes. size is at least 1 byte.
  82. //
  83. // A = aligned_buf will initially point to this address.
  84. // B = The address pointed by the caller-supplied buf.
  85. // C = buf + size == aligned_buf + size2
  86. // D = buf + size + skip_end == aligned_buf + size2 + skip_end
  87. const size_t skip_start = (size_t)((uintptr_t)buf & 15);
  88. const size_t skip_end = (size_t)((0U - (uintptr_t)(buf + size)) & 15);
  89. const __m128i *aligned_buf = (const __m128i *)(
  90. (uintptr_t)buf & ~(uintptr_t)15);
  91. // If size2 <= 16 then the whole input fits into a single 16-byte
  92. // vector. If size2 > 16 then at least two 16-byte vectors must
  93. // be processed. If size2 > 16 && size <= 16 then there is only
  94. // one 16-byte vector's worth of input but it is unaligned in memory.
  95. //
  96. // NOTE: There is no integer overflow here if the arguments
  97. // are valid. If this overflowed, buf + size would too.
  98. const size_t size2 = skip_start + size;
  99. // Masks to be used with _mm_blendv_epi8 and _mm_shuffle_epi8:
  100. // The first skip_start or skip_end bytes in the vectors will have
  101. // the high bit (0x80) set. _mm_blendv_epi8 and _mm_shuffle_epi8
  102. // will produce zeros for these positions. (Bitwise-xor of these
  103. // masks with vsign will produce the opposite behavior.)
  104. const __m128i mask_start
  105. = _mm_sub_epi8(vramp, _mm_set1_epi8((char)skip_start));
  106. const __m128i mask_end
  107. = _mm_sub_epi8(vramp, _mm_set1_epi8((char)skip_end));
  108. // Get the first 1-16 bytes into data0. If loading less than 16
  109. // bytes, the bytes are loaded to the high bits of the vector and
  110. // the least significant positions are filled with zeros.
  111. const __m128i data0 = _mm_blendv_epi8(_mm_load_si128(aligned_buf),
  112. _mm_setzero_si128(), mask_start);
  113. aligned_buf++;
  114. __m128i v2, v3;
  115. #ifndef CRC_USE_GENERIC_FOR_SMALL_INPUTS
  116. if (size <= 16) {
  117. // Right-shift initial_crc by 1-16 bytes based on "size"
  118. // and store the result in v1 (high bytes) and v0 (low bytes).
  119. //
  120. // NOTE: The highest 8 bytes of initial_crc are zeros so
  121. // v1 will be filled with zeros if size >= 8. The highest
  122. // 8 bytes of v1 will always become zeros.
  123. //
  124. // [ v1 ][ v0 ]
  125. // [ initial_crc ] size == 1
  126. // [ initial_crc ] size == 2
  127. // [ initial_crc ] size == 15
  128. // [ initial_crc ] size == 16 (all in v0)
  129. const __m128i mask_low = _mm_add_epi8(
  130. vramp, _mm_set1_epi8((char)(size - 16)));
  131. MASK_LH(initial_crc, mask_low, *v0, *v1);
  132. if (size2 <= 16) {
  133. // There are 1-16 bytes of input and it is all
  134. // in data0. Copy the input bytes to v3. If there
  135. // are fewer than 16 bytes, the low bytes in v3
  136. // will be filled with zeros. That is, the input
  137. // bytes are stored to the same position as
  138. // (part of) initial_crc is in v0.
  139. MASK_L(data0, mask_end, v3);
  140. } else {
  141. // There are 2-16 bytes of input but not all bytes
  142. // are in data0.
  143. const __m128i data1 = _mm_load_si128(aligned_buf);
  144. // Collect the 2-16 input bytes from data0 and data1
  145. // to v2 and v3, and bitwise-xor them with the
  146. // low bits of initial_crc in v0. Note that the
  147. // the second xor is below this else-block as it
  148. // is shared with the other branch.
  149. MASK_H(data0, mask_end, v2);
  150. MASK_L(data1, mask_end, v3);
  151. *v0 = _mm_xor_si128(*v0, v2);
  152. }
  153. *v0 = _mm_xor_si128(*v0, v3);
  154. *v1 = _mm_alignr_epi8(*v1, *v0, 8);
  155. } else
  156. #endif
  157. {
  158. // There is more than 16 bytes of input.
  159. const __m128i data1 = _mm_load_si128(aligned_buf);
  160. const __m128i *end = (const __m128i*)(
  161. (const char *)aligned_buf - 16 + size2);
  162. aligned_buf++;
  163. MASK_LH(initial_crc, mask_start, *v0, *v1);
  164. *v0 = _mm_xor_si128(*v0, data0);
  165. *v1 = _mm_xor_si128(*v1, data1);
  166. while (aligned_buf < end) {
  167. *v1 = _mm_xor_si128(*v1, _mm_clmulepi64_si128(
  168. *v0, vfold16, 0x00));
  169. *v0 = _mm_xor_si128(*v1, _mm_clmulepi64_si128(
  170. *v0, vfold16, 0x11));
  171. *v1 = _mm_load_si128(aligned_buf++);
  172. }
  173. if (aligned_buf != end) {
  174. MASK_H(*v0, mask_end, v2);
  175. MASK_L(*v0, mask_end, *v0);
  176. MASK_L(*v1, mask_end, v3);
  177. *v1 = _mm_or_si128(v2, v3);
  178. }
  179. *v1 = _mm_xor_si128(*v1, _mm_clmulepi64_si128(
  180. *v0, vfold16, 0x00));
  181. *v0 = _mm_xor_si128(*v1, _mm_clmulepi64_si128(
  182. *v0, vfold16, 0x11));
  183. *v1 = _mm_srli_si128(*v0, 8);
  184. }
  185. }
  186. /////////////////////
  187. // x86 CLMUL CRC32 //
  188. /////////////////////
  189. /*
  190. // These functions were used to generate the constants
  191. // at the top of crc32_arch_optimized().
  192. static uint64_t
  193. calc_lo(uint64_t p, uint64_t a, int n)
  194. {
  195. uint64_t b = 0; int i;
  196. for (i = 0; i < n; i++) {
  197. b = b >> 1 | (a & 1) << (n - 1);
  198. a = (a >> 1) ^ ((0 - (a & 1)) & p);
  199. }
  200. return b;
  201. }
  202. // same as ~crc(&a, sizeof(a), ~0)
  203. static uint64_t
  204. calc_hi(uint64_t p, uint64_t a, int n)
  205. {
  206. int i;
  207. for (i = 0; i < n; i++)
  208. a = (a >> 1) ^ ((0 - (a & 1)) & p);
  209. return a;
  210. }
  211. */
  212. #ifdef BUILDING_CRC32_CLMUL
  213. crc_attr_target
  214. crc_attr_no_sanitize_address
  215. static uint32_t
  216. crc32_arch_optimized(const uint8_t *buf, size_t size, uint32_t crc)
  217. {
  218. #ifndef CRC_USE_GENERIC_FOR_SMALL_INPUTS
  219. // The code assumes that there is at least one byte of input.
  220. if (size == 0)
  221. return crc;
  222. #endif
  223. // uint32_t poly = 0xedb88320;
  224. const int64_t p = 0x1db710640; // p << 1
  225. const int64_t mu = 0x1f7011641; // calc_lo(p, p, 32) << 1 | 1
  226. const int64_t k5 = 0x163cd6124; // calc_hi(p, p, 32) << 1
  227. const int64_t k4 = 0x0ccaa009e; // calc_hi(p, p, 64) << 1
  228. const int64_t k3 = 0x1751997d0; // calc_hi(p, p, 128) << 1
  229. const __m128i vfold4 = _mm_set_epi64x(mu, p);
  230. const __m128i vfold8 = _mm_set_epi64x(0, k5);
  231. const __m128i vfold16 = _mm_set_epi64x(k4, k3);
  232. __m128i v0, v1, v2;
  233. crc_simd_body(buf, size, &v0, &v1, vfold16,
  234. _mm_cvtsi32_si128((int32_t)~crc));
  235. v1 = _mm_xor_si128(
  236. _mm_clmulepi64_si128(v0, vfold16, 0x10), v1); // xxx0
  237. v2 = _mm_shuffle_epi32(v1, 0xe7); // 0xx0
  238. v0 = _mm_slli_epi64(v1, 32); // [0]
  239. v0 = _mm_clmulepi64_si128(v0, vfold8, 0x00);
  240. v0 = _mm_xor_si128(v0, v2); // [1] [2]
  241. v2 = _mm_clmulepi64_si128(v0, vfold4, 0x10);
  242. v2 = _mm_clmulepi64_si128(v2, vfold4, 0x00);
  243. v0 = _mm_xor_si128(v0, v2); // [2]
  244. return ~(uint32_t)_mm_extract_epi32(v0, 2);
  245. }
  246. #endif // BUILDING_CRC32_CLMUL
  247. /////////////////////
  248. // x86 CLMUL CRC64 //
  249. /////////////////////
  250. /*
  251. // These functions were used to generate the constants
  252. // at the top of crc64_arch_optimized().
  253. static uint64_t
  254. calc_lo(uint64_t poly)
  255. {
  256. uint64_t a = poly;
  257. uint64_t b = 0;
  258. for (unsigned i = 0; i < 64; ++i) {
  259. b = (b >> 1) | (a << 63);
  260. a = (a >> 1) ^ (a & 1 ? poly : 0);
  261. }
  262. return b;
  263. }
  264. static uint64_t
  265. calc_hi(uint64_t poly, uint64_t a)
  266. {
  267. for (unsigned i = 0; i < 64; ++i)
  268. a = (a >> 1) ^ (a & 1 ? poly : 0);
  269. return a;
  270. }
  271. */
  272. #ifdef BUILDING_CRC64_CLMUL
  273. // MSVC (VS2015 - VS2022) produces bad 32-bit x86 code from the CLMUL CRC
  274. // code when optimizations are enabled (release build). According to the bug
  275. // report, the ebx register is corrupted and the calculated result is wrong.
  276. // Trying to workaround the problem with "__asm mov ebx, ebx" didn't help.
  277. // The following pragma works and performance is still good. x86-64 builds
  278. // and CRC32 CLMUL aren't affected by this problem. The problem does not
  279. // happen in crc_simd_body() either (which is shared with CRC32 CLMUL anyway).
  280. //
  281. // NOTE: Another pragma after crc64_arch_optimized() restores
  282. // the optimizations. If the #if condition here is updated,
  283. // the other one must be updated too.
  284. #if defined(_MSC_VER) && !defined(__INTEL_COMPILER) && !defined(__clang__) \
  285. && defined(_M_IX86)
  286. # pragma optimize("g", off)
  287. #endif
  288. crc_attr_target
  289. crc_attr_no_sanitize_address
  290. static uint64_t
  291. crc64_arch_optimized(const uint8_t *buf, size_t size, uint64_t crc)
  292. {
  293. #ifndef CRC_USE_GENERIC_FOR_SMALL_INPUTS
  294. // The code assumes that there is at least one byte of input.
  295. if (size == 0)
  296. return crc;
  297. #endif
  298. // const uint64_t poly = 0xc96c5795d7870f42; // CRC polynomial
  299. const uint64_t p = 0x92d8af2baf0e1e85; // (poly << 1) | 1
  300. const uint64_t mu = 0x9c3e466c172963d5; // (calc_lo(poly) << 1) | 1
  301. const uint64_t k2 = 0xdabe95afc7875f40; // calc_hi(poly, 1)
  302. const uint64_t k1 = 0xe05dd497ca393ae4; // calc_hi(poly, k2)
  303. const __m128i vfold8 = _mm_set_epi64x((int64_t)p, (int64_t)mu);
  304. const __m128i vfold16 = _mm_set_epi64x((int64_t)k2, (int64_t)k1);
  305. __m128i v0, v1, v2;
  306. #if defined(__i386__) || defined(_M_IX86)
  307. crc_simd_body(buf, size, &v0, &v1, vfold16,
  308. _mm_set_epi64x(0, (int64_t)~crc));
  309. #else
  310. // GCC and Clang would produce good code with _mm_set_epi64x
  311. // but MSVC needs _mm_cvtsi64_si128 on x86-64.
  312. crc_simd_body(buf, size, &v0, &v1, vfold16,
  313. _mm_cvtsi64_si128((int64_t)~crc));
  314. #endif
  315. v1 = _mm_xor_si128(_mm_clmulepi64_si128(v0, vfold16, 0x10), v1);
  316. v0 = _mm_clmulepi64_si128(v1, vfold8, 0x00);
  317. v2 = _mm_clmulepi64_si128(v0, vfold8, 0x10);
  318. v0 = _mm_xor_si128(_mm_xor_si128(v1, _mm_slli_si128(v0, 8)), v2);
  319. #if defined(__i386__) || defined(_M_IX86)
  320. return ~(((uint64_t)(uint32_t)_mm_extract_epi32(v0, 3) << 32) |
  321. (uint64_t)(uint32_t)_mm_extract_epi32(v0, 2));
  322. #else
  323. return ~(uint64_t)_mm_extract_epi64(v0, 1);
  324. #endif
  325. }
  326. #if defined(_MSC_VER) && !defined(__INTEL_COMPILER) && !defined(__clang__) \
  327. && defined(_M_IX86)
  328. # pragma optimize("", on)
  329. #endif
  330. #endif // BUILDING_CRC64_CLMUL
  331. // Inlining this function duplicates the function body in crc32_resolve() and
  332. // crc64_resolve(), but this is acceptable because this is a tiny function.
  333. static inline bool
  334. is_arch_extension_supported(void)
  335. {
  336. int success = 1;
  337. uint32_t r[4]; // eax, ebx, ecx, edx
  338. #if defined(_MSC_VER)
  339. // This needs <intrin.h> with MSVC. ICC has it as a built-in
  340. // on all platforms.
  341. __cpuid(r, 1);
  342. #elif defined(HAVE_CPUID_H)
  343. // Compared to just using __asm__ to run CPUID, this also checks
  344. // that CPUID is supported and saves and restores ebx as that is
  345. // needed with GCC < 5 with position-independent code (PIC).
  346. success = __get_cpuid(1, &r[0], &r[1], &r[2], &r[3]);
  347. #else
  348. // Just a fallback that shouldn't be needed.
  349. __asm__("cpuid\n\t"
  350. : "=a"(r[0]), "=b"(r[1]), "=c"(r[2]), "=d"(r[3])
  351. : "a"(1), "c"(0));
  352. #endif
  353. // Returns true if these are supported:
  354. // CLMUL (bit 1 in ecx)
  355. // SSSE3 (bit 9 in ecx)
  356. // SSE4.1 (bit 19 in ecx)
  357. const uint32_t ecx_mask = (1 << 1) | (1 << 9) | (1 << 19);
  358. return success && (r[2] & ecx_mask) == ecx_mask;
  359. // Alternative methods that weren't used:
  360. // - ICC's _may_i_use_cpu_feature: the other methods should work too.
  361. // - GCC >= 6 / Clang / ICX __builtin_cpu_supports("pclmul")
  362. //
  363. // CPUID decding is needed with MSVC anyway and older GCC. This keeps
  364. // the feature checks in the build system simpler too. The nice thing
  365. // about __builtin_cpu_supports would be that it generates very short
  366. // code as is it only reads a variable set at startup but a few bytes
  367. // doesn't matter here.
  368. }