1 /*
2 * Copyright © 2014 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24 #ifndef UTIL_MACROS_H
25 #define UTIL_MACROS_H
26
27 #include <assert.h>
28 #if defined(__HAIKU__) && !defined(__cplusplus)
29 #define static_assert _Static_assert
30 #endif
31 #include <stddef.h>
32 #include <stdint.h>
33 #include <stdio.h>
34
35 #ifdef _GAMING_XBOX
36 #define strdup _strdup
37 #define stricmp _stricmp
38 #define unlink _unlink
39 #define access(a, b) _access(a, b)
40 #endif
41
42 /* Compute the size of an array */
43 #ifndef ARRAY_SIZE
44 # define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
45 #endif
46
47 /* For compatibility with Clang's __has_builtin() */
48 #ifndef __has_builtin
49 # define __has_builtin(x) 0
50 #endif
51
52 #ifndef __has_attribute
53 # define __has_attribute(x) 0
54 #endif
55
56 /**
57 * __builtin_expect macros
58 */
59 #if !defined(HAVE___BUILTIN_EXPECT)
60 # define __builtin_expect(x, y) (x)
61 #endif
62
63 #ifndef likely
64 # ifdef HAVE___BUILTIN_EXPECT
65 # define likely(x) __builtin_expect(!!(x), 1)
66 # define unlikely(x) __builtin_expect(!!(x), 0)
67 # else
68 # define likely(x) (x)
69 # define unlikely(x) (x)
70 # endif
71 #endif
72
73 /**
74 * __builtin_types_compatible_p compat
75 */
76 #if defined(__cplusplus) || !defined(HAVE___BUILTIN_TYPES_COMPATIBLE_P)
77 # define __builtin_types_compatible_p(type1, type2) (1)
78 #endif
79
80 /* This should match linux gcc cdecl semantics everywhere, so that we
81 * just codegen one calling convention on all platforms.
82 */
83 #ifdef _MSC_VER
84 #define UTIL_CDECL __cdecl
85 #else
86 #define UTIL_CDECL
87 #endif
88
89 /**
90 * Static (compile-time) assertion.
91 */
92 #define STATIC_ASSERT(cond) do { \
93 static_assert(cond, #cond); \
94 } while (0)
95
96 /**
97 * container_of - cast a member of a structure out to the containing structure
98 * @ptr: the pointer to the member.
99 * @type: the type of the container struct this is embedded in.
100 * @member: the name of the member within the struct.
101 */
102 #ifndef __GNUC__
103 /* a grown-up compiler is required for the extra type checking: */
104 # define container_of(ptr, type, member) \
105 (type*)((uint8_t *)ptr - offsetof(type, member))
106 #else
107 # define __same_type(a, b) \
108 __builtin_types_compatible_p(__typeof__(a), __typeof__(b))
109 # define container_of(ptr, type, member) ({ \
110 uint8_t *__mptr = (uint8_t *)(ptr); \
111 static_assert(__same_type(*(ptr), ((type *)0)->member) || \
112 __same_type(*(ptr), void), \
113 "pointer type mismatch in container_of()"); \
114 ((type *)(__mptr - offsetof(type, member))); \
115 })
116 #endif
117
118 /**
119 * Unreachable macro. Useful for suppressing "control reaches end of non-void
120 * function" warnings.
121 */
122 #if defined(HAVE___BUILTIN_UNREACHABLE) || __has_builtin(__builtin_unreachable)
123 #define unreachable(str) \
124 do { \
125 assert(!"" str); \
126 __builtin_unreachable(); \
127 } while (0)
128 #elif defined (_MSC_VER)
129 #define unreachable(str) \
130 do { \
131 assert(!"" str); \
132 __assume(0); \
133 } while (0)
134 #else
135 #define unreachable(str) assert(!"" str)
136 #endif
137
138 /**
139 * Assume macro. Useful for expressing our assumptions to the compiler,
140 * typically for purposes of silencing warnings.
141 */
142 #if __has_builtin(__builtin_assume)
143 #define assume(expr) \
144 do { \
145 assert(expr); \
146 __builtin_assume(expr); \
147 } while (0)
148 #elif defined HAVE___BUILTIN_UNREACHABLE
149 #define assume(expr) ((expr) ? ((void) 0) \
150 : (assert(!"assumption failed"), \
151 __builtin_unreachable()))
152 #elif defined (_MSC_VER)
153 #define assume(expr) __assume(expr)
154 #else
155 #define assume(expr) assert(expr)
156 #endif
157
158 /* Attribute const is used for functions that have no effects other than their
159 * return value, and only rely on the argument values to compute the return
160 * value. As a result, calls to it can be CSEed. Note that using memory
161 * pointed to by the arguments is not allowed for const functions.
162 */
163 #if !defined(__clang__) && defined(HAVE_FUNC_ATTRIBUTE_CONST)
164 #define ATTRIBUTE_CONST __attribute__((__const__))
165 #else
166 #define ATTRIBUTE_CONST
167 #endif
168
169 #ifdef HAVE_FUNC_ATTRIBUTE_FLATTEN
170 #define FLATTEN __attribute__((__flatten__))
171 #else
172 #define FLATTEN
173 #endif
174
175 #ifdef HAVE_FUNC_ATTRIBUTE_FORMAT
176 #if defined (__MINGW_PRINTF_FORMAT)
177 # define PRINTFLIKE(f, a) __attribute__ ((format(__MINGW_PRINTF_FORMAT, f, a)))
178 #else
179 # define PRINTFLIKE(f, a) __attribute__ ((format(__printf__, f, a)))
180 #endif
181 #else
182 #define PRINTFLIKE(f, a)
183 #endif
184
185 #ifdef HAVE_FUNC_ATTRIBUTE_MALLOC
186 #define MALLOCLIKE __attribute__((__malloc__))
187 #else
188 #define MALLOCLIKE
189 #endif
190
191 /* Forced function inlining */
192 /* Note: Clang also sets __GNUC__ (see other cases below) */
193 #ifndef ALWAYS_INLINE
194 # if defined(__GNUC__)
195 # define ALWAYS_INLINE inline __attribute__((always_inline))
196 # elif defined(_MSC_VER)
197 # define ALWAYS_INLINE __forceinline
198 # else
199 # define ALWAYS_INLINE inline
200 # endif
201 #endif
202
203 /* Used to optionally mark structures with misaligned elements or size as
204 * packed, to trade off performance for space.
205 */
206 #ifdef HAVE_FUNC_ATTRIBUTE_PACKED
207 # if defined(__MINGW32__) || defined(__MINGW64__)
208 # define PACKED __attribute__((gcc_struct,__packed__))
209 # else
210 # define PACKED __attribute__((__packed__))
211 # endif
212 # define ENUM_PACKED __attribute__((packed))
213 #else
214 #define PACKED
215 #define ENUM_PACKED
216 #endif
217
218 /* Attribute pure is used for functions that have no effects other than their
219 * return value. As a result, calls to it can be dead code eliminated.
220 */
221 #ifdef HAVE_FUNC_ATTRIBUTE_PURE
222 #define ATTRIBUTE_PURE __attribute__((__pure__))
223 #else
224 #define ATTRIBUTE_PURE
225 #endif
226
227 #ifdef HAVE_FUNC_ATTRIBUTE_RETURNS_NONNULL
228 #define ATTRIBUTE_RETURNS_NONNULL __attribute__((__returns_nonnull__))
229 #else
230 #define ATTRIBUTE_RETURNS_NONNULL
231 #endif
232
233 #ifndef NORETURN
234 # ifdef _MSC_VER
235 # define NORETURN __declspec(noreturn)
236 # elif defined HAVE_FUNC_ATTRIBUTE_NORETURN
237 # define NORETURN __attribute__((__noreturn__))
238 # else
239 # define NORETURN
240 # endif
241 #endif
242
243 #ifdef HAVE_FUNC_ATTRIBUTE_OPTIMIZE
244 #define ATTRIBUTE_OPTIMIZE(flags) __attribute__((__optimize__((flags))))
245 #else
246 #define ATTRIBUTE_OPTIMIZE(flags)
247 #endif
248
249 #ifdef __cplusplus
250 /**
251 * Macro function that evaluates to true if T is a trivially
252 * destructible type -- that is, if its (non-virtual) destructor
253 * performs no action and all member variables and base classes are
254 * trivially destructible themselves.
255 */
256 # if defined(__clang__)
257 # if __has_builtin(__is_trivially_destructible)
258 # define HAS_TRIVIAL_DESTRUCTOR(T) __is_trivially_destructible(T)
259 # elif (defined(__has_feature) && __has_feature(has_trivial_destructor))
260 # define HAS_TRIVIAL_DESTRUCTOR(T) __has_trivial_destructor(T)
261 # endif
262 # elif defined(__GNUC__)
263 # if ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)))
264 # define HAS_TRIVIAL_DESTRUCTOR(T) __has_trivial_destructor(T)
265 # endif
266 # elif defined(_MSC_VER) && !defined(__INTEL_COMPILER)
267 # define HAS_TRIVIAL_DESTRUCTOR(T) __has_trivial_destructor(T)
268 # endif
269 # ifndef HAS_TRIVIAL_DESTRUCTOR
270 /* It's always safe (if inefficient) to assume that a
271 * destructor is non-trivial.
272 */
273 # define HAS_TRIVIAL_DESTRUCTOR(T) (false)
274 # endif
275 #endif
276
277 /**
278 * PUBLIC/USED macros
279 *
280 * If we build the library with gcc's -fvisibility=hidden flag, we'll
281 * use the PUBLIC macro to mark functions that are to be exported.
282 *
283 * We also need to define a USED attribute, so the optimizer doesn't
284 * inline a static function that we later use in an alias. - ajax
285 */
286 #ifndef PUBLIC
287 # if defined(_WIN32)
288 # define PUBLIC __declspec(dllexport)
289 # define USED
290 # elif defined(__GNUC__)
291 # define PUBLIC __attribute__((visibility("default")))
292 # define USED __attribute__((used))
293 # else
294 # define PUBLIC
295 # define USED
296 # endif
297 #endif
298
299 /**
300 * UNUSED marks variables (or sometimes functions) that have to be defined,
301 * but are sometimes (or always) unused beyond that. A common case is for
302 * a function parameter to be used in some build configurations but not others.
303 * Another case is fallback vfuncs that don't do anything with their params.
304 *
305 * Note that this should not be used for identifiers used in `assert()`;
306 * see ASSERTED below.
307 */
308 #ifdef HAVE_FUNC_ATTRIBUTE_UNUSED
309 #define UNUSED __attribute__((unused))
310 #elif defined (_MSC_VER)
311 #define UNUSED __pragma(warning(suppress:4100 4101 4189))
312 #else
313 #define UNUSED
314 #endif
315
316 /**
317 * Use ASSERTED to indicate that an identifier is unused outside of an `assert()`,
318 * so that assert-free builds don't get "unused variable" warnings.
319 */
320 #ifdef NDEBUG
321 #define ASSERTED UNUSED
322 #else
323 #define ASSERTED
324 #endif
325
326 #ifdef HAVE_FUNC_ATTRIBUTE_WARN_UNUSED_RESULT
327 #define MUST_CHECK __attribute__((warn_unused_result))
328 #else
329 #define MUST_CHECK
330 #endif
331
332 #if defined(__GNUC__)
333 #define ATTRIBUTE_NOINLINE __attribute__((noinline))
334 #elif defined(_MSC_VER)
335 #define ATTRIBUTE_NOINLINE __declspec(noinline)
336 #else
337 #define ATTRIBUTE_NOINLINE
338 #endif
339
340 /**
341 * Check that STRUCT::FIELD can hold MAXVAL. We use a lot of bitfields
342 * in Mesa/gallium. We have to be sure they're of sufficient size to
343 * hold the largest expected value.
344 * Note that with MSVC, enums are signed and enum bitfields need one extra
345 * high bit (always zero) to ensure the max value is handled correctly.
346 * This macro will detect that with MSVC, but not GCC.
347 */
348 #define ASSERT_BITFIELD_SIZE(STRUCT, FIELD, MAXVAL) \
349 do { \
350 ASSERTED STRUCT s; \
351 s.FIELD = (MAXVAL); \
352 assert((int) s.FIELD == (MAXVAL) && "Insufficient bitfield size!"); \
353 } while (0)
354
355
356 /** Compute ceiling of integer quotient of A divided by B. */
357 #define DIV_ROUND_UP( A, B ) ( ((A) + (B) - 1) / (B) )
358
359 /**
360 * Clamp X to [MIN, MAX].
361 * This is a macro to allow float, int, unsigned, etc. types.
362 * We arbitrarily turn NaN into MIN.
363 */
364 #define CLAMP( X, MIN, MAX ) ( (X)>(MIN) ? ((X)>(MAX) ? (MAX) : (X)) : (MIN) )
365
366 /* Syntax sugar occuring frequently in graphics code */
367 #define SATURATE( X ) CLAMP(X, 0.0f, 1.0f)
368
369 /** Minimum of two values: */
370 #define MIN2( A, B ) ( (A)<(B) ? (A) : (B) )
371
372 /** Maximum of two values: */
373 #define MAX2( A, B ) ( (A)>(B) ? (A) : (B) )
374
375 /** Minimum of three values: */
376 #define MIN3( A, B, C ) ((A) < (B) ? MIN2(A, C) : MIN2(B, C))
377
378 /** Maximum of three values: */
379 #define MAX3( A, B, C ) ((A) > (B) ? MAX2(A, C) : MAX2(B, C))
380
381 /** Minimum of four values: */
382 #define MIN4( A, B, C, D ) ((A) < (B) ? MIN3(A, C, D) : MIN3(B, C, D))
383
384 /** Maximum of four values: */
385 #define MAX4( A, B, C, D ) ((A) > (B) ? MAX3(A, C, D) : MAX3(B, C, D))
386
387 /** Align a value to a power of two */
388 #define ALIGN_POT(x, pot_align) (((x) + (pot_align) - 1) & ~((pot_align) - 1))
389
390 /** Checks is a value is a power of two. Does not handle zero. */
391 #define IS_POT(v) (((v) & ((v) - 1)) == 0)
392
393 /** Checks is a value is a power of two. Zero handled. */
394 #define IS_POT_NONZERO(v) ((v) != 0 && IS_POT(v))
395
396 /** Set a single bit */
397 #define BITFIELD_BIT(b) (1u << (b))
398 /** Set all bits up to excluding bit b */
399 #define BITFIELD_MASK(b) \
400 ((b) == 32 ? (~0u) : BITFIELD_BIT((b) & 31) - 1)
401 /** Set count bits starting from bit b */
402 #define BITFIELD_RANGE(b, count) \
403 (BITFIELD_MASK((b) + (count)) & ~BITFIELD_MASK(b))
404
405 /** Set a single bit */
406 #define BITFIELD64_BIT(b) (1ull << (b))
407 /** Set all bits up to excluding bit b */
408 #define BITFIELD64_MASK(b) \
409 ((b) == 64 ? (~0ull) : BITFIELD64_BIT((b) & 63) - 1)
410 /** Set count bits starting from bit b */
411 #define BITFIELD64_RANGE(b, count) \
412 (BITFIELD64_MASK((b) + (count)) & ~BITFIELD64_MASK(b))
413
414 static inline int64_t
u_intN_max(unsigned bit_size)415 u_intN_max(unsigned bit_size)
416 {
417 assert(bit_size <= 64 && bit_size > 0);
418 return INT64_MAX >> (64 - bit_size);
419 }
420
421 static inline int64_t
u_intN_min(unsigned bit_size)422 u_intN_min(unsigned bit_size)
423 {
424 /* On 2's compliment platforms, which is every platform Mesa is likely to
425 * every worry about, stdint.h generally calculated INT##_MIN in this
426 * manner.
427 */
428 return (-u_intN_max(bit_size)) - 1;
429 }
430
431 static inline uint64_t
u_uintN_max(unsigned bit_size)432 u_uintN_max(unsigned bit_size)
433 {
434 assert(bit_size <= 64 && bit_size > 0);
435 return UINT64_MAX >> (64 - bit_size);
436 }
437
438 /* alignas usage
439 * For struct or union, use alignas(align_size) on any member
440 * of it will make it aligned to align_size.
441 * See https://en.cppreference.com/w/c/language/_Alignas for
442 * details. We can use static_assert and alignof to check if
443 * the alignment result of alignas(align_size) on struct or
444 * union is valid.
445 * For example:
446 * static_assert(alignof(struct tgsi_exec_machine) == 16, "")
447 * Also, we can use special code to see the size of the aligned
448 * struct or union at the compile time with GCC, Clang or MSVC.
449 * So we can see if the size of union or struct are as expected
450 * when using alignas(align_size) on its member.
451 * For example:
452 * char (*__kaboom)[sizeof(struct tgsi_exec_machine)] = 1;
453 * can show us the size of struct tgsi_exec_machine at compile
454 * time.
455 */
456 #ifndef __cplusplus
457 #ifdef _MSC_VER
458 #define alignof _Alignof
459 #define alignas _Alignas
460 #else
461 #include <stdalign.h>
462 #endif
463 #endif
464
465 /* Macros for static type-safety checking.
466 *
467 * https://clang.llvm.org/docs/ThreadSafetyAnalysis.html
468 */
469
470 #if __has_attribute(capability)
471 typedef int __attribute__((capability("mutex"))) lock_cap_t;
472
473 #define guarded_by(l) __attribute__((guarded_by(l)))
474 #define acquire_cap(l) __attribute((acquire_capability(l), no_thread_safety_analysis))
475 #define release_cap(l) __attribute((release_capability(l), no_thread_safety_analysis))
476 #define assert_cap(l) __attribute((assert_capability(l), no_thread_safety_analysis))
477 #define requires_cap(l) __attribute((requires_capability(l)))
478 #define disable_thread_safety_analysis __attribute((no_thread_safety_analysis))
479
480 #else
481
482 typedef int lock_cap_t;
483
484 #define guarded_by(l)
485 #define acquire_cap(l)
486 #define release_cap(l)
487 #define assert_cap(l)
488 #define requires_cap(l)
489 #define disable_thread_safety_analysis
490
491 #endif
492
493 #define DO_PRAGMA(X) _Pragma (#X)
494
495 #if defined(__clang__)
496 #define PRAGMA_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push")
497 #define PRAGMA_DIAGNOSTIC_POP _Pragma("clang diagnostic pop")
498 #define PRAGMA_DIAGNOSTIC_ERROR(X) DO_PRAGMA( clang diagnostic error #X )
499 #define PRAGMA_DIAGNOSTIC_WARNING(X) DO_PRAGMA( clang diagnostic warning #X )
500 #define PRAGMA_DIAGNOSTIC_IGNORED(X) DO_PRAGMA( clang diagnostic ignored #X )
501 #elif defined(__GNUC__)
502 #define PRAGMA_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push")
503 #define PRAGMA_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
504 #define PRAGMA_DIAGNOSTIC_ERROR(X) DO_PRAGMA( GCC diagnostic error #X )
505 #define PRAGMA_DIAGNOSTIC_WARNING(X) DO_PRAGMA( GCC diagnostic warning #X )
506 #define PRAGMA_DIAGNOSTIC_IGNORED(X) DO_PRAGMA( GCC diagnostic ignored #X )
507 #else
508 #define PRAGMA_DIAGNOSTIC_PUSH
509 #define PRAGMA_DIAGNOSTIC_POP
510 #define PRAGMA_DIAGNOSTIC_ERROR(X)
511 #define PRAGMA_DIAGNOSTIC_WARNING(X)
512 #define PRAGMA_DIAGNOSTIC_IGNORED(X)
513 #endif
514
515 #define PASTE2(a, b) a ## b
516 #define PASTE3(a, b, c) a ## b ## c
517 #define PASTE4(a, b, c, d) a ## b ## c ## d
518
519 #define CONCAT2(a, b) PASTE2(a, b)
520 #define CONCAT3(a, b, c) PASTE3(a, b, c)
521 #define CONCAT4(a, b, c, d) PASTE4(a, b, c, d)
522
523 #if defined(__GNUC__)
524 #define PRAGMA_POISON(X) DO_PRAGMA( GCC poison X )
525 #elif defined(__clang__)
526 #define PRAGMA_POISON(X) DO_PRAGMA( clang poison X )
527 #else
528 #define PRAGMA_POISON
529 #endif
530
531 #endif /* UTIL_MACROS_H */
532