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