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 __cplusplus
244 /**
245 * Macro function that evaluates to true if T is a trivially
246 * destructible type -- that is, if its (non-virtual) destructor
247 * performs no action and all member variables and base classes are
248 * trivially destructible themselves.
249 */
250 # if defined(__clang__)
251 # if __has_builtin(__is_trivially_destructible)
252 # define HAS_TRIVIAL_DESTRUCTOR(T) __is_trivially_destructible(T)
253 # elif (defined(__has_feature) && __has_feature(has_trivial_destructor))
254 # define HAS_TRIVIAL_DESTRUCTOR(T) __has_trivial_destructor(T)
255 # endif
256 # elif defined(__GNUC__)
257 # if ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)))
258 # define HAS_TRIVIAL_DESTRUCTOR(T) __has_trivial_destructor(T)
259 # endif
260 # elif defined(_MSC_VER) && !defined(__INTEL_COMPILER)
261 # define HAS_TRIVIAL_DESTRUCTOR(T) __has_trivial_destructor(T)
262 # endif
263 # ifndef HAS_TRIVIAL_DESTRUCTOR
264 /* It's always safe (if inefficient) to assume that a
265 * destructor is non-trivial.
266 */
267 # define HAS_TRIVIAL_DESTRUCTOR(T) (false)
268 # endif
269 #endif
270
271 /**
272 * PUBLIC/USED macros
273 *
274 * If we build the library with gcc's -fvisibility=hidden flag, we'll
275 * use the PUBLIC macro to mark functions that are to be exported.
276 *
277 * We also need to define a USED attribute, so the optimizer doesn't
278 * inline a static function that we later use in an alias. - ajax
279 */
280 #ifndef PUBLIC
281 # if defined(_WIN32)
282 # define PUBLIC __declspec(dllexport)
283 # define USED
284 # elif defined(__GNUC__)
285 # define PUBLIC __attribute__((visibility("default")))
286 # define USED __attribute__((used))
287 # else
288 # define PUBLIC
289 # define USED
290 # endif
291 #endif
292
293 /**
294 * UNUSED marks variables (or sometimes functions) that have to be defined,
295 * but are sometimes (or always) unused beyond that. A common case is for
296 * a function parameter to be used in some build configurations but not others.
297 * Another case is fallback vfuncs that don't do anything with their params.
298 *
299 * Note that this should not be used for identifiers used in `assert()`;
300 * see ASSERTED below.
301 */
302 #ifdef HAVE_FUNC_ATTRIBUTE_UNUSED
303 #define UNUSED __attribute__((unused))
304 #elif defined (_MSC_VER)
305 #define UNUSED __pragma(warning(suppress:4100 4101 4189))
306 #else
307 #define UNUSED
308 #endif
309
310 /**
311 * Use ASSERTED to indicate that an identifier is unused outside of an `assert()`,
312 * so that assert-free builds don't get "unused variable" warnings.
313 */
314 #ifdef NDEBUG
315 #define ASSERTED UNUSED
316 #else
317 #define ASSERTED
318 #endif
319
320 #ifdef HAVE_FUNC_ATTRIBUTE_WARN_UNUSED_RESULT
321 #define MUST_CHECK __attribute__((warn_unused_result))
322 #else
323 #define MUST_CHECK
324 #endif
325
326 #if defined(__GNUC__)
327 #define ATTRIBUTE_NOINLINE __attribute__((noinline))
328 #elif defined(_MSC_VER)
329 #define ATTRIBUTE_NOINLINE __declspec(noinline)
330 #else
331 #define ATTRIBUTE_NOINLINE
332 #endif
333
334 /**
335 * Check that STRUCT::FIELD can hold MAXVAL. We use a lot of bitfields
336 * in Mesa/gallium. We have to be sure they're of sufficient size to
337 * hold the largest expected value.
338 * Note that with MSVC, enums are signed and enum bitfields need one extra
339 * high bit (always zero) to ensure the max value is handled correctly.
340 * This macro will detect that with MSVC, but not GCC.
341 */
342 #define ASSERT_BITFIELD_SIZE(STRUCT, FIELD, MAXVAL) \
343 do { \
344 ASSERTED STRUCT s; \
345 s.FIELD = (MAXVAL); \
346 assert((int) s.FIELD == (MAXVAL) && "Insufficient bitfield size!"); \
347 } while (0)
348
349
350 /** Compute ceiling of integer quotient of A divided by B. */
351 #define DIV_ROUND_UP( A, B ) ( ((A) + (B) - 1) / (B) )
352
353 /**
354 * Clamp X to [MIN, MAX].
355 * This is a macro to allow float, int, unsigned, etc. types.
356 * We arbitrarily turn NaN into MIN.
357 */
358 #define CLAMP( X, MIN, MAX ) ( (X)>(MIN) ? ((X)>(MAX) ? (MAX) : (X)) : (MIN) )
359
360 /* Syntax sugar occuring frequently in graphics code */
361 #define SATURATE( X ) CLAMP(X, 0.0f, 1.0f)
362
363 /** Minimum of two values: */
364 #define MIN2( A, B ) ( (A)<(B) ? (A) : (B) )
365
366 /** Maximum of two values: */
367 #define MAX2( A, B ) ( (A)>(B) ? (A) : (B) )
368
369 /** Minimum of three values: */
370 #define MIN3( A, B, C ) ((A) < (B) ? MIN2(A, C) : MIN2(B, C))
371
372 /** Maximum of three values: */
373 #define MAX3( A, B, C ) ((A) > (B) ? MAX2(A, C) : MAX2(B, C))
374
375 /** Minimum of four values: */
376 #define MIN4( A, B, C, D ) ((A) < (B) ? MIN3(A, C, D) : MIN3(B, C, D))
377
378 /** Maximum of four values: */
379 #define MAX4( A, B, C, D ) ((A) > (B) ? MAX3(A, C, D) : MAX3(B, C, D))
380
381 /** Align a value to a power of two */
382 #define ALIGN_POT(x, pot_align) (((x) + (pot_align) - 1) & ~((pot_align) - 1))
383
384 /** Checks is a value is a power of two. Does not handle zero. */
385 #define IS_POT(v) (((v) & ((v) - 1)) == 0)
386
387 /** Checks is a value is a power of two. Zero handled. */
388 #define IS_POT_NONZERO(v) ((v) != 0 && IS_POT(v))
389
390 /** Set a single bit */
391 #define BITFIELD_BIT(b) (1u << (b))
392 /** Set all bits up to excluding bit b */
393 #define BITFIELD_MASK(b) \
394 ((b) == 32 ? (~0u) : BITFIELD_BIT((b) & 31) - 1)
395 /** Set count bits starting from bit b */
396 #define BITFIELD_RANGE(b, count) \
397 (BITFIELD_MASK((b) + (count)) & ~BITFIELD_MASK(b))
398
399 /** Set a single bit */
400 #define BITFIELD64_BIT(b) (1ull << (b))
401 /** Set all bits up to excluding bit b */
402 #define BITFIELD64_MASK(b) \
403 ((b) == 64 ? (~0ull) : BITFIELD64_BIT((b) & 63) - 1)
404 /** Set count bits starting from bit b */
405 #define BITFIELD64_RANGE(b, count) \
406 (BITFIELD64_MASK((b) + (count)) & ~BITFIELD64_MASK(b))
407
408 static inline int64_t
u_intN_max(unsigned bit_size)409 u_intN_max(unsigned bit_size)
410 {
411 assert(bit_size <= 64 && bit_size > 0);
412 return INT64_MAX >> (64 - bit_size);
413 }
414
415 static inline int64_t
u_intN_min(unsigned bit_size)416 u_intN_min(unsigned bit_size)
417 {
418 /* On 2's compliment platforms, which is every platform Mesa is likely to
419 * every worry about, stdint.h generally calculated INT##_MIN in this
420 * manner.
421 */
422 return (-u_intN_max(bit_size)) - 1;
423 }
424
425 static inline uint64_t
u_uintN_max(unsigned bit_size)426 u_uintN_max(unsigned bit_size)
427 {
428 assert(bit_size <= 64 && bit_size > 0);
429 return UINT64_MAX >> (64 - bit_size);
430 }
431
432 /* alignas usage
433 * For struct or union, use alignas(align_size) on any member
434 * of it will make it aligned to align_size.
435 * See https://en.cppreference.com/w/c/language/_Alignas for
436 * details. We can use static_assert and alignof to check if
437 * the alignment result of alignas(align_size) on struct or
438 * union is valid.
439 * For example:
440 * static_assert(alignof(struct tgsi_exec_machine) == 16, "")
441 * Also, we can use special code to see the size of the aligned
442 * struct or union at the compile time with GCC, Clang or MSVC.
443 * So we can see if the size of union or struct are as expected
444 * when using alignas(align_size) on its member.
445 * For example:
446 * char (*__kaboom)[sizeof(struct tgsi_exec_machine)] = 1;
447 * can show us the size of struct tgsi_exec_machine at compile
448 * time.
449 */
450 #ifndef __cplusplus
451 #ifdef _MSC_VER
452 #define alignof _Alignof
453 #define alignas _Alignas
454 #else
455 #include <stdalign.h>
456 #endif
457 #endif
458
459 /* Macros for static type-safety checking.
460 *
461 * https://clang.llvm.org/docs/ThreadSafetyAnalysis.html
462 */
463
464 #if __has_attribute(capability)
465 typedef int __attribute__((capability("mutex"))) lock_cap_t;
466
467 #define guarded_by(l) __attribute__((guarded_by(l)))
468 #define acquire_cap(l) __attribute((acquire_capability(l), no_thread_safety_analysis))
469 #define release_cap(l) __attribute((release_capability(l), no_thread_safety_analysis))
470 #define assert_cap(l) __attribute((assert_capability(l), no_thread_safety_analysis))
471 #define requires_cap(l) __attribute((requires_capability(l)))
472 #define disable_thread_safety_analysis __attribute((no_thread_safety_analysis))
473
474 #else
475
476 typedef int lock_cap_t;
477
478 #define guarded_by(l)
479 #define acquire_cap(l)
480 #define release_cap(l)
481 #define assert_cap(l)
482 #define requires_cap(l)
483 #define disable_thread_safety_analysis
484
485 #endif
486
487 #define DO_PRAGMA(X) _Pragma (#X)
488
489 #if defined(__clang__)
490 #define PRAGMA_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push")
491 #define PRAGMA_DIAGNOSTIC_POP _Pragma("clang diagnostic pop")
492 #define PRAGMA_DIAGNOSTIC_ERROR(X) DO_PRAGMA( clang diagnostic error #X )
493 #define PRAGMA_DIAGNOSTIC_WARNING(X) DO_PRAGMA( clang diagnostic warning #X )
494 #define PRAGMA_DIAGNOSTIC_IGNORED(X) DO_PRAGMA( clang diagnostic ignored #X )
495 #elif defined(__GNUC__)
496 #define PRAGMA_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push")
497 #define PRAGMA_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
498 #define PRAGMA_DIAGNOSTIC_ERROR(X) DO_PRAGMA( GCC diagnostic error #X )
499 #define PRAGMA_DIAGNOSTIC_WARNING(X) DO_PRAGMA( GCC diagnostic warning #X )
500 #define PRAGMA_DIAGNOSTIC_IGNORED(X) DO_PRAGMA( GCC diagnostic ignored #X )
501 #else
502 #define PRAGMA_DIAGNOSTIC_PUSH
503 #define PRAGMA_DIAGNOSTIC_POP
504 #define PRAGMA_DIAGNOSTIC_ERROR(X)
505 #define PRAGMA_DIAGNOSTIC_WARNING(X)
506 #define PRAGMA_DIAGNOSTIC_IGNORED(X)
507 #endif
508
509 #define PASTE2(a, b) a ## b
510 #define PASTE3(a, b, c) a ## b ## c
511 #define PASTE4(a, b, c, d) a ## b ## c ## d
512
513 #define CONCAT2(a, b) PASTE2(a, b)
514 #define CONCAT3(a, b, c) PASTE3(a, b, c)
515 #define CONCAT4(a, b, c, d) PASTE4(a, b, c, d)
516
517 #if defined(__GNUC__)
518 #define PRAGMA_POISON(X) DO_PRAGMA( GCC poison X )
519 #elif defined(__clang__)
520 #define PRAGMA_POISON(X) DO_PRAGMA( clang poison X )
521 #else
522 #define PRAGMA_POISON
523 #endif
524
525 #endif /* UTIL_MACROS_H */
526