compiler.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. /*
  2. * Copyright (c) Meta Platforms, Inc. and affiliates.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. #ifndef ZSTD_COMPILER_H
  11. #define ZSTD_COMPILER_H
  12. #include <stddef.h>
  13. #include "portability_macros.h"
  14. /*-*******************************************************
  15. * Compiler specifics
  16. *********************************************************/
  17. /* force inlining */
  18. #if !defined(ZSTD_NO_INLINE)
  19. #if (defined(__GNUC__) && !defined(__STRICT_ANSI__)) || defined(__cplusplus) || defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */
  20. # define INLINE_KEYWORD inline
  21. #else
  22. # define INLINE_KEYWORD
  23. #endif
  24. #if defined(__GNUC__) || defined(__IAR_SYSTEMS_ICC__)
  25. # define FORCE_INLINE_ATTR __attribute__((always_inline))
  26. #elif defined(_MSC_VER)
  27. # define FORCE_INLINE_ATTR __forceinline
  28. #else
  29. # define FORCE_INLINE_ATTR
  30. #endif
  31. #else
  32. #define INLINE_KEYWORD
  33. #define FORCE_INLINE_ATTR
  34. #endif
  35. /**
  36. On MSVC qsort requires that functions passed into it use the __cdecl calling conversion(CC).
  37. This explicitly marks such functions as __cdecl so that the code will still compile
  38. if a CC other than __cdecl has been made the default.
  39. */
  40. #if defined(_MSC_VER)
  41. # define WIN_CDECL __cdecl
  42. #else
  43. # define WIN_CDECL
  44. #endif
  45. /* UNUSED_ATTR tells the compiler it is okay if the function is unused. */
  46. #if defined(__GNUC__) || defined(__IAR_SYSTEMS_ICC__)
  47. # define UNUSED_ATTR __attribute__((unused))
  48. #else
  49. # define UNUSED_ATTR
  50. #endif
  51. /**
  52. * FORCE_INLINE_TEMPLATE is used to define C "templates", which take constant
  53. * parameters. They must be inlined for the compiler to eliminate the constant
  54. * branches.
  55. */
  56. #define FORCE_INLINE_TEMPLATE static INLINE_KEYWORD FORCE_INLINE_ATTR UNUSED_ATTR
  57. /**
  58. * HINT_INLINE is used to help the compiler generate better code. It is *not*
  59. * used for "templates", so it can be tweaked based on the compilers
  60. * performance.
  61. *
  62. * gcc-4.8 and gcc-4.9 have been shown to benefit from leaving off the
  63. * always_inline attribute.
  64. *
  65. * clang up to 5.0.0 (trunk) benefit tremendously from the always_inline
  66. * attribute.
  67. */
  68. #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 8 && __GNUC__ < 5
  69. # define HINT_INLINE static INLINE_KEYWORD
  70. #else
  71. # define HINT_INLINE FORCE_INLINE_TEMPLATE
  72. #endif
  73. /* "soft" inline :
  74. * The compiler is free to select if it's a good idea to inline or not.
  75. * The main objective is to silence compiler warnings
  76. * when a defined function in included but not used.
  77. *
  78. * Note : this macro is prefixed `MEM_` because it used to be provided by `mem.h` unit.
  79. * Updating the prefix is probably preferable, but requires a fairly large codemod,
  80. * since this name is used everywhere.
  81. */
  82. #ifndef MEM_STATIC /* already defined in Linux Kernel mem.h */
  83. #if defined(__GNUC__)
  84. # define MEM_STATIC static __inline UNUSED_ATTR
  85. #elif defined(__IAR_SYSTEMS_ICC__)
  86. # define MEM_STATIC static inline UNUSED_ATTR
  87. #elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  88. # define MEM_STATIC static inline
  89. #elif defined(_MSC_VER)
  90. # define MEM_STATIC static __inline
  91. #else
  92. # define MEM_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */
  93. #endif
  94. #endif
  95. /* force no inlining */
  96. #ifdef _MSC_VER
  97. # define FORCE_NOINLINE static __declspec(noinline)
  98. #else
  99. # if defined(__GNUC__) || defined(__IAR_SYSTEMS_ICC__)
  100. # define FORCE_NOINLINE static __attribute__((__noinline__))
  101. # else
  102. # define FORCE_NOINLINE static
  103. # endif
  104. #endif
  105. /* target attribute */
  106. #if defined(__GNUC__) || defined(__IAR_SYSTEMS_ICC__)
  107. # define TARGET_ATTRIBUTE(target) __attribute__((__target__(target)))
  108. #else
  109. # define TARGET_ATTRIBUTE(target)
  110. #endif
  111. /* Target attribute for BMI2 dynamic dispatch.
  112. * Enable lzcnt, bmi, and bmi2.
  113. * We test for bmi1 & bmi2. lzcnt is included in bmi1.
  114. */
  115. #define BMI2_TARGET_ATTRIBUTE TARGET_ATTRIBUTE("lzcnt,bmi,bmi2")
  116. /* prefetch
  117. * can be disabled, by declaring NO_PREFETCH build macro */
  118. #if defined(NO_PREFETCH)
  119. # define PREFETCH_L1(ptr) do { (void)(ptr); } while (0) /* disabled */
  120. # define PREFETCH_L2(ptr) do { (void)(ptr); } while (0) /* disabled */
  121. #else
  122. # if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_I86)) && !defined(_M_ARM64EC) /* _mm_prefetch() is not defined outside of x86/x64 */
  123. # include <mmintrin.h> /* https://msdn.microsoft.com/fr-fr/library/84szxsww(v=vs.90).aspx */
  124. # define PREFETCH_L1(ptr) _mm_prefetch((const char*)(ptr), _MM_HINT_T0)
  125. # define PREFETCH_L2(ptr) _mm_prefetch((const char*)(ptr), _MM_HINT_T1)
  126. # elif defined(__GNUC__) && ( (__GNUC__ >= 4) || ( (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) ) )
  127. # define PREFETCH_L1(ptr) __builtin_prefetch((ptr), 0 /* rw==read */, 3 /* locality */)
  128. # define PREFETCH_L2(ptr) __builtin_prefetch((ptr), 0 /* rw==read */, 2 /* locality */)
  129. # elif defined(__aarch64__)
  130. # define PREFETCH_L1(ptr) do { __asm__ __volatile__("prfm pldl1keep, %0" ::"Q"(*(ptr))); } while (0)
  131. # define PREFETCH_L2(ptr) do { __asm__ __volatile__("prfm pldl2keep, %0" ::"Q"(*(ptr))); } while (0)
  132. # else
  133. # define PREFETCH_L1(ptr) do { (void)(ptr); } while (0) /* disabled */
  134. # define PREFETCH_L2(ptr) do { (void)(ptr); } while (0) /* disabled */
  135. # endif
  136. #endif /* NO_PREFETCH */
  137. #define CACHELINE_SIZE 64
  138. #define PREFETCH_AREA(p, s) \
  139. do { \
  140. const char* const _ptr = (const char*)(p); \
  141. size_t const _size = (size_t)(s); \
  142. size_t _pos; \
  143. for (_pos=0; _pos<_size; _pos+=CACHELINE_SIZE) { \
  144. PREFETCH_L2(_ptr + _pos); \
  145. } \
  146. } while (0)
  147. /* vectorization
  148. * older GCC (pre gcc-4.3 picked as the cutoff) uses a different syntax,
  149. * and some compilers, like Intel ICC and MCST LCC, do not support it at all. */
  150. #if !defined(__INTEL_COMPILER) && !defined(__clang__) && defined(__GNUC__) && !defined(__LCC__)
  151. # if (__GNUC__ == 4 && __GNUC_MINOR__ > 3) || (__GNUC__ >= 5)
  152. # define DONT_VECTORIZE __attribute__((optimize("no-tree-vectorize")))
  153. # else
  154. # define DONT_VECTORIZE _Pragma("GCC optimize(\"no-tree-vectorize\")")
  155. # endif
  156. #else
  157. # define DONT_VECTORIZE
  158. #endif
  159. /* Tell the compiler that a branch is likely or unlikely.
  160. * Only use these macros if it causes the compiler to generate better code.
  161. * If you can remove a LIKELY/UNLIKELY annotation without speed changes in gcc
  162. * and clang, please do.
  163. */
  164. #if defined(__GNUC__)
  165. #define LIKELY(x) (__builtin_expect((x), 1))
  166. #define UNLIKELY(x) (__builtin_expect((x), 0))
  167. #else
  168. #define LIKELY(x) (x)
  169. #define UNLIKELY(x) (x)
  170. #endif
  171. #if __has_builtin(__builtin_unreachable) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)))
  172. # define ZSTD_UNREACHABLE do { assert(0), __builtin_unreachable(); } while (0)
  173. #else
  174. # define ZSTD_UNREACHABLE do { assert(0); } while (0)
  175. #endif
  176. /* disable warnings */
  177. #ifdef _MSC_VER /* Visual Studio */
  178. # include <intrin.h> /* For Visual 2005 */
  179. # pragma warning(disable : 4100) /* disable: C4100: unreferenced formal parameter */
  180. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  181. # pragma warning(disable : 4204) /* disable: C4204: non-constant aggregate initializer */
  182. # pragma warning(disable : 4214) /* disable: C4214: non-int bitfields */
  183. # pragma warning(disable : 4324) /* disable: C4324: padded structure */
  184. #endif
  185. /* compile time determination of SIMD support */
  186. #if !defined(ZSTD_NO_INTRINSICS)
  187. # if defined(__AVX2__)
  188. # define ZSTD_ARCH_X86_AVX2
  189. # endif
  190. # if defined(__SSE2__) || defined(_M_X64) || (defined (_M_IX86) && defined(_M_IX86_FP) && (_M_IX86_FP >= 2))
  191. # define ZSTD_ARCH_X86_SSE2
  192. # endif
  193. # if defined(__ARM_NEON) || defined(_M_ARM64)
  194. # define ZSTD_ARCH_ARM_NEON
  195. # endif
  196. #
  197. # if defined(ZSTD_ARCH_X86_AVX2)
  198. # include <immintrin.h>
  199. # endif
  200. # if defined(ZSTD_ARCH_X86_SSE2)
  201. # include <emmintrin.h>
  202. # elif defined(ZSTD_ARCH_ARM_NEON)
  203. # include <arm_neon.h>
  204. # endif
  205. #endif
  206. /* C-language Attributes are added in C23. */
  207. #if defined(__STDC_VERSION__) && (__STDC_VERSION__ > 201710L) && defined(__has_c_attribute)
  208. # define ZSTD_HAS_C_ATTRIBUTE(x) __has_c_attribute(x)
  209. #else
  210. # define ZSTD_HAS_C_ATTRIBUTE(x) 0
  211. #endif
  212. /* Only use C++ attributes in C++. Some compilers report support for C++
  213. * attributes when compiling with C.
  214. */
  215. #if defined(__cplusplus) && defined(__has_cpp_attribute)
  216. # define ZSTD_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
  217. #else
  218. # define ZSTD_HAS_CPP_ATTRIBUTE(x) 0
  219. #endif
  220. /* Define ZSTD_FALLTHROUGH macro for annotating switch case with the 'fallthrough' attribute.
  221. * - C23: https://en.cppreference.com/w/c/language/attributes/fallthrough
  222. * - CPP17: https://en.cppreference.com/w/cpp/language/attributes/fallthrough
  223. * - Else: __attribute__((__fallthrough__))
  224. */
  225. #ifndef ZSTD_FALLTHROUGH
  226. # if ZSTD_HAS_C_ATTRIBUTE(fallthrough)
  227. # define ZSTD_FALLTHROUGH [[fallthrough]]
  228. # elif ZSTD_HAS_CPP_ATTRIBUTE(fallthrough)
  229. # define ZSTD_FALLTHROUGH [[fallthrough]]
  230. # elif __has_attribute(__fallthrough__)
  231. /* Leading semicolon is to satisfy gcc-11 with -pedantic. Without the semicolon
  232. * gcc complains about: a label can only be part of a statement and a declaration is not a statement.
  233. */
  234. # define ZSTD_FALLTHROUGH ; __attribute__((__fallthrough__))
  235. # else
  236. # define ZSTD_FALLTHROUGH
  237. # endif
  238. #endif
  239. /*-**************************************************************
  240. * Alignment
  241. *****************************************************************/
  242. /* @return 1 if @u is a 2^n value, 0 otherwise
  243. * useful to check a value is valid for alignment restrictions */
  244. MEM_STATIC int ZSTD_isPower2(size_t u) {
  245. return (u & (u-1)) == 0;
  246. }
  247. /* this test was initially positioned in mem.h,
  248. * but this file is removed (or replaced) for linux kernel
  249. * so it's now hosted in compiler.h,
  250. * which remains valid for both user & kernel spaces.
  251. */
  252. #ifndef ZSTD_ALIGNOF
  253. # if defined(__GNUC__) || defined(_MSC_VER)
  254. /* covers gcc, clang & MSVC */
  255. /* note : this section must come first, before C11,
  256. * due to a limitation in the kernel source generator */
  257. # define ZSTD_ALIGNOF(T) __alignof(T)
  258. # elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  259. /* C11 support */
  260. # include <stdalign.h>
  261. # define ZSTD_ALIGNOF(T) alignof(T)
  262. # else
  263. /* No known support for alignof() - imperfect backup */
  264. # define ZSTD_ALIGNOF(T) (sizeof(void*) < sizeof(T) ? sizeof(void*) : sizeof(T))
  265. # endif
  266. #endif /* ZSTD_ALIGNOF */
  267. #ifndef ZSTD_ALIGNED
  268. /* C90-compatible alignment macro (GCC/Clang). Adjust for other compilers if needed. */
  269. # if defined(__GNUC__) || defined(__clang__)
  270. # define ZSTD_ALIGNED(a) __attribute__((aligned(a)))
  271. # elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* C11 */
  272. # define ZSTD_ALIGNED(a) _Alignas(a)
  273. #elif defined(_MSC_VER)
  274. # define ZSTD_ALIGNED(n) __declspec(align(n))
  275. # else
  276. /* this compiler will require its own alignment instruction */
  277. # define ZSTD_ALIGNED(...)
  278. # endif
  279. #endif /* ZSTD_ALIGNED */
  280. /*-**************************************************************
  281. * Sanitizer
  282. *****************************************************************/
  283. /**
  284. * Zstd relies on pointer overflow in its decompressor.
  285. * We add this attribute to functions that rely on pointer overflow.
  286. */
  287. #ifndef ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
  288. # if __has_attribute(no_sanitize)
  289. # if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 8
  290. /* gcc < 8 only has signed-integer-overlow which triggers on pointer overflow */
  291. # define ZSTD_ALLOW_POINTER_OVERFLOW_ATTR __attribute__((no_sanitize("signed-integer-overflow")))
  292. # else
  293. /* older versions of clang [3.7, 5.0) will warn that pointer-overflow is ignored. */
  294. # define ZSTD_ALLOW_POINTER_OVERFLOW_ATTR __attribute__((no_sanitize("pointer-overflow")))
  295. # endif
  296. # else
  297. # define ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
  298. # endif
  299. #endif
  300. /**
  301. * Helper function to perform a wrapped pointer difference without triggering
  302. * UBSAN.
  303. *
  304. * @returns lhs - rhs with wrapping
  305. */
  306. MEM_STATIC
  307. ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
  308. ptrdiff_t ZSTD_wrappedPtrDiff(unsigned char const* lhs, unsigned char const* rhs)
  309. {
  310. return lhs - rhs;
  311. }
  312. /**
  313. * Helper function to perform a wrapped pointer add without triggering UBSAN.
  314. *
  315. * @return ptr + add with wrapping
  316. */
  317. MEM_STATIC
  318. ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
  319. unsigned char const* ZSTD_wrappedPtrAdd(unsigned char const* ptr, ptrdiff_t add)
  320. {
  321. return ptr + add;
  322. }
  323. /**
  324. * Helper function to perform a wrapped pointer subtraction without triggering
  325. * UBSAN.
  326. *
  327. * @return ptr - sub with wrapping
  328. */
  329. MEM_STATIC
  330. ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
  331. unsigned char const* ZSTD_wrappedPtrSub(unsigned char const* ptr, ptrdiff_t sub)
  332. {
  333. return ptr - sub;
  334. }
  335. /**
  336. * Helper function to add to a pointer that works around C's undefined behavior
  337. * of adding 0 to NULL.
  338. *
  339. * @returns `ptr + add` except it defines `NULL + 0 == NULL`.
  340. */
  341. MEM_STATIC
  342. unsigned char* ZSTD_maybeNullPtrAdd(unsigned char* ptr, ptrdiff_t add)
  343. {
  344. return add > 0 ? ptr + add : ptr;
  345. }
  346. /* Issue #3240 reports an ASAN failure on an llvm-mingw build. Out of an
  347. * abundance of caution, disable our custom poisoning on mingw. */
  348. #ifdef __MINGW32__
  349. #ifndef ZSTD_ASAN_DONT_POISON_WORKSPACE
  350. #define ZSTD_ASAN_DONT_POISON_WORKSPACE 1
  351. #endif
  352. #ifndef ZSTD_MSAN_DONT_POISON_WORKSPACE
  353. #define ZSTD_MSAN_DONT_POISON_WORKSPACE 1
  354. #endif
  355. #endif
  356. #if ZSTD_MEMORY_SANITIZER && !defined(ZSTD_MSAN_DONT_POISON_WORKSPACE)
  357. /* Not all platforms that support msan provide sanitizers/msan_interface.h.
  358. * We therefore declare the functions we need ourselves, rather than trying to
  359. * include the header file... */
  360. #include <stddef.h> /* size_t */
  361. #define ZSTD_DEPS_NEED_STDINT
  362. #include "zstd_deps.h" /* intptr_t */
  363. /* Make memory region fully initialized (without changing its contents). */
  364. void __msan_unpoison(const volatile void *a, size_t size);
  365. /* Make memory region fully uninitialized (without changing its contents).
  366. This is a legacy interface that does not update origin information. Use
  367. __msan_allocated_memory() instead. */
  368. void __msan_poison(const volatile void *a, size_t size);
  369. /* Returns the offset of the first (at least partially) poisoned byte in the
  370. memory range, or -1 if the whole range is good. */
  371. intptr_t __msan_test_shadow(const volatile void *x, size_t size);
  372. /* Print shadow and origin for the memory range to stderr in a human-readable
  373. format. */
  374. void __msan_print_shadow(const volatile void *x, size_t size);
  375. #endif
  376. #if ZSTD_ADDRESS_SANITIZER && !defined(ZSTD_ASAN_DONT_POISON_WORKSPACE)
  377. /* Not all platforms that support asan provide sanitizers/asan_interface.h.
  378. * We therefore declare the functions we need ourselves, rather than trying to
  379. * include the header file... */
  380. #include <stddef.h> /* size_t */
  381. /**
  382. * Marks a memory region (<c>[addr, addr+size)</c>) as unaddressable.
  383. *
  384. * This memory must be previously allocated by your program. Instrumented
  385. * code is forbidden from accessing addresses in this region until it is
  386. * unpoisoned. This function is not guaranteed to poison the entire region -
  387. * it could poison only a subregion of <c>[addr, addr+size)</c> due to ASan
  388. * alignment restrictions.
  389. *
  390. * \note This function is not thread-safe because no two threads can poison or
  391. * unpoison memory in the same memory region simultaneously.
  392. *
  393. * \param addr Start of memory region.
  394. * \param size Size of memory region. */
  395. void __asan_poison_memory_region(void const volatile *addr, size_t size);
  396. /**
  397. * Marks a memory region (<c>[addr, addr+size)</c>) as addressable.
  398. *
  399. * This memory must be previously allocated by your program. Accessing
  400. * addresses in this region is allowed until this region is poisoned again.
  401. * This function could unpoison a super-region of <c>[addr, addr+size)</c> due
  402. * to ASan alignment restrictions.
  403. *
  404. * \note This function is not thread-safe because no two threads can
  405. * poison or unpoison memory in the same memory region simultaneously.
  406. *
  407. * \param addr Start of memory region.
  408. * \param size Size of memory region. */
  409. void __asan_unpoison_memory_region(void const volatile *addr, size_t size);
  410. #endif
  411. #endif /* ZSTD_COMPILER_H */