xref: /third_party/mesa3d/src/util/macros.h (revision bf215546)
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 <stdio.h>
28#include <assert.h>
29#include <stdint.h>
30
31/* Compute the size of an array */
32#ifndef ARRAY_SIZE
33#  define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
34#endif
35
36/* For compatibility with Clang's __has_builtin() */
37#ifndef __has_builtin
38#  define __has_builtin(x) 0
39#endif
40
41#ifndef __has_attribute
42#  define __has_attribute(x) 0
43#endif
44
45/**
46 * __builtin_expect macros
47 */
48#if !defined(HAVE___BUILTIN_EXPECT)
49#  define __builtin_expect(x, y) (x)
50#endif
51
52#ifndef likely
53#  ifdef HAVE___BUILTIN_EXPECT
54#    define likely(x)   __builtin_expect(!!(x), 1)
55#    define unlikely(x) __builtin_expect(!!(x), 0)
56#  else
57#    define likely(x)   (x)
58#    define unlikely(x) (x)
59#  endif
60#endif
61
62/**
63 * __builtin_types_compatible_p compat
64 */
65#if defined(__cplusplus) || !defined(HAVE___BUILTIN_TYPES_COMPATIBLE_P)
66#  define __builtin_types_compatible_p(type1, type2) (1)
67#endif
68
69/**
70 * Static (compile-time) assertion.
71 */
72#define STATIC_ASSERT(cond) do { \
73   static_assert(cond, #cond); \
74} while (0)
75
76/**
77 * container_of - cast a member of a structure out to the containing structure
78 * @ptr:        the pointer to the member.
79 * @type:       the type of the container struct this is embedded in.
80 * @member:     the name of the member within the struct.
81 */
82#ifndef __GNUC__
83   /* a grown-up compiler is required for the extra type checking: */
84#  define container_of(ptr, type, member)                               \
85      (type*)((uint8_t *)ptr - offsetof(type, member))
86#else
87#  define __same_type(a, b) \
88      __builtin_types_compatible_p(__typeof__(a), __typeof__(b))
89#  define container_of(ptr, type, member) ({                            \
90         uint8_t *__mptr = (uint8_t *)(ptr);                            \
91         static_assert(__same_type(*(ptr), ((type *)0)->member) ||      \
92                       __same_type(*(ptr), void),                       \
93                       "pointer type mismatch in container_of()");      \
94         ((type *)(__mptr - offsetof(type, member)));                   \
95      })
96#endif
97
98/**
99 * Unreachable macro. Useful for suppressing "control reaches end of non-void
100 * function" warnings.
101 */
102#if defined(HAVE___BUILTIN_UNREACHABLE) || __has_builtin(__builtin_unreachable)
103#define unreachable(str)    \
104do {                        \
105   assert(!str);            \
106   __builtin_unreachable(); \
107} while (0)
108#elif defined (_MSC_VER)
109#define unreachable(str)    \
110do {                        \
111   assert(!str);            \
112   __assume(0);             \
113} while (0)
114#else
115#define unreachable(str) assert(!str)
116#endif
117
118/**
119 * Assume macro. Useful for expressing our assumptions to the compiler,
120 * typically for purposes of silencing warnings.
121 */
122#if __has_builtin(__builtin_assume)
123#define assume(expr)       \
124do {                       \
125   assert(expr);           \
126   __builtin_assume(expr); \
127} while (0)
128#elif defined HAVE___BUILTIN_UNREACHABLE
129#define assume(expr) ((expr) ? ((void) 0) \
130                             : (assert(!"assumption failed"), \
131                                __builtin_unreachable()))
132#elif defined (_MSC_VER)
133#define assume(expr) __assume(expr)
134#else
135#define assume(expr) assert(expr)
136#endif
137
138/* Attribute const is used for functions that have no effects other than their
139 * return value, and only rely on the argument values to compute the return
140 * value.  As a result, calls to it can be CSEed.  Note that using memory
141 * pointed to by the arguments is not allowed for const functions.
142 */
143#if !defined(__clang__) && defined(HAVE_FUNC_ATTRIBUTE_CONST)
144#define ATTRIBUTE_CONST __attribute__((__const__))
145#else
146#define ATTRIBUTE_CONST
147#endif
148
149#ifdef HAVE_FUNC_ATTRIBUTE_FLATTEN
150#define FLATTEN __attribute__((__flatten__))
151#else
152#define FLATTEN
153#endif
154
155#ifdef HAVE_FUNC_ATTRIBUTE_FORMAT
156#if defined (__MINGW_PRINTF_FORMAT)
157# define PRINTFLIKE(f, a) __attribute__ ((format(__MINGW_PRINTF_FORMAT, f, a)))
158#else
159# define PRINTFLIKE(f, a) __attribute__ ((format(__printf__, f, a)))
160#endif
161#else
162#define PRINTFLIKE(f, a)
163#endif
164
165#ifdef HAVE_FUNC_ATTRIBUTE_MALLOC
166#define MALLOCLIKE __attribute__((__malloc__))
167#else
168#define MALLOCLIKE
169#endif
170
171/* Forced function inlining */
172/* Note: Clang also sets __GNUC__ (see other cases below) */
173#ifndef ALWAYS_INLINE
174#  if defined(__GNUC__)
175#    define ALWAYS_INLINE inline __attribute__((always_inline))
176#  elif defined(_MSC_VER)
177#    define ALWAYS_INLINE __forceinline
178#  else
179#    define ALWAYS_INLINE inline
180#  endif
181#endif
182
183/* Used to optionally mark structures with misaligned elements or size as
184 * packed, to trade off performance for space.
185 */
186#ifdef HAVE_FUNC_ATTRIBUTE_PACKED
187#define PACKED __attribute__((__packed__))
188#else
189#define PACKED
190#endif
191
192/* Attribute pure is used for functions that have no effects other than their
193 * return value.  As a result, calls to it can be dead code eliminated.
194 */
195#ifdef HAVE_FUNC_ATTRIBUTE_PURE
196#define ATTRIBUTE_PURE __attribute__((__pure__))
197#else
198#define ATTRIBUTE_PURE
199#endif
200
201#ifdef HAVE_FUNC_ATTRIBUTE_RETURNS_NONNULL
202#define ATTRIBUTE_RETURNS_NONNULL __attribute__((__returns_nonnull__))
203#else
204#define ATTRIBUTE_RETURNS_NONNULL
205#endif
206
207#ifndef NORETURN
208#  ifdef _MSC_VER
209#    define NORETURN __declspec(noreturn)
210#  elif defined HAVE_FUNC_ATTRIBUTE_NORETURN
211#    define NORETURN __attribute__((__noreturn__))
212#  else
213#    define NORETURN
214#  endif
215#endif
216
217#ifdef _MSC_VER
218#define ALIGN16 __declspec(align(16))
219#else
220#define ALIGN16 __attribute__((aligned(16)))
221#endif
222
223#ifdef __cplusplus
224/**
225 * Macro function that evaluates to true if T is a trivially
226 * destructible type -- that is, if its (non-virtual) destructor
227 * performs no action and all member variables and base classes are
228 * trivially destructible themselves.
229 */
230#   if (defined(__clang__) && defined(__has_feature))
231#      if __has_feature(has_trivial_destructor)
232#         define HAS_TRIVIAL_DESTRUCTOR(T) __has_trivial_destructor(T)
233#      endif
234#   elif defined(__GNUC__)
235#      if ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)))
236#         define HAS_TRIVIAL_DESTRUCTOR(T) __has_trivial_destructor(T)
237#      endif
238#   elif defined(_MSC_VER) && !defined(__INTEL_COMPILER)
239#      define HAS_TRIVIAL_DESTRUCTOR(T) __has_trivial_destructor(T)
240#   endif
241#   ifndef HAS_TRIVIAL_DESTRUCTOR
242       /* It's always safe (if inefficient) to assume that a
243        * destructor is non-trivial.
244        */
245#      define HAS_TRIVIAL_DESTRUCTOR(T) (false)
246#   endif
247#endif
248
249/**
250 * PUBLIC/USED macros
251 *
252 * If we build the library with gcc's -fvisibility=hidden flag, we'll
253 * use the PUBLIC macro to mark functions that are to be exported.
254 *
255 * We also need to define a USED attribute, so the optimizer doesn't
256 * inline a static function that we later use in an alias. - ajax
257 */
258#ifndef PUBLIC
259#  if defined(_WIN32)
260#    define PUBLIC __declspec(dllexport)
261#    define USED
262#  elif defined(__GNUC__)
263#    define PUBLIC __attribute__((visibility("default")))
264#    define USED __attribute__((used))
265#  else
266#    define PUBLIC
267#    define USED
268#  endif
269#endif
270
271/**
272 * UNUSED marks variables (or sometimes functions) that have to be defined,
273 * but are sometimes (or always) unused beyond that. A common case is for
274 * a function parameter to be used in some build configurations but not others.
275 * Another case is fallback vfuncs that don't do anything with their params.
276 *
277 * Note that this should not be used for identifiers used in `assert()`;
278 * see ASSERTED below.
279 */
280#ifdef HAVE_FUNC_ATTRIBUTE_UNUSED
281#define UNUSED __attribute__((unused))
282#elif defined (_MSC_VER)
283#define UNUSED __pragma(warning(suppress:4100 4101))
284#else
285#define UNUSED
286#endif
287
288/**
289 * Use ASSERTED to indicate that an identifier is unused outside of an `assert()`,
290 * so that assert-free builds don't get "unused variable" warnings.
291 */
292#ifdef NDEBUG
293#define ASSERTED UNUSED
294#else
295#define ASSERTED
296#endif
297
298#ifdef HAVE_FUNC_ATTRIBUTE_WARN_UNUSED_RESULT
299#define MUST_CHECK __attribute__((warn_unused_result))
300#else
301#define MUST_CHECK
302#endif
303
304#if defined(__GNUC__)
305#define ATTRIBUTE_NOINLINE __attribute__((noinline))
306#elif defined(_MSC_VER)
307#define ATTRIBUTE_NOINLINE __declspec(noinline)
308#else
309#define ATTRIBUTE_NOINLINE
310#endif
311
312/* Use as: enum name { X, Y } ENUM_PACKED; */
313#if defined(__GNUC__)
314#define ENUM_PACKED __attribute__((packed))
315#else
316#define ENUM_PACKED
317#endif
318
319
320/**
321 * Check that STRUCT::FIELD can hold MAXVAL.  We use a lot of bitfields
322 * in Mesa/gallium.  We have to be sure they're of sufficient size to
323 * hold the largest expected value.
324 * Note that with MSVC, enums are signed and enum bitfields need one extra
325 * high bit (always zero) to ensure the max value is handled correctly.
326 * This macro will detect that with MSVC, but not GCC.
327 */
328#define ASSERT_BITFIELD_SIZE(STRUCT, FIELD, MAXVAL) \
329   do { \
330      ASSERTED STRUCT s; \
331      s.FIELD = (MAXVAL); \
332      assert((int) s.FIELD == (MAXVAL) && "Insufficient bitfield size!"); \
333   } while (0)
334
335
336/** Compute ceiling of integer quotient of A divided by B. */
337#define DIV_ROUND_UP( A, B )  ( ((A) + (B) - 1) / (B) )
338
339/** Clamp X to [MIN,MAX].  Turn NaN into MIN, arbitrarily. */
340#define CLAMP( X, MIN, MAX )  ( (X)>(MIN) ? ((X)>(MAX) ? (MAX) : (X)) : (MIN) )
341
342/* Syntax sugar occuring frequently in graphics code */
343#define SATURATE( X ) CLAMP(X, 0.0f, 1.0f)
344
345/** Minimum of two values: */
346#define MIN2( A, B )   ( (A)<(B) ? (A) : (B) )
347
348/** Maximum of two values: */
349#define MAX2( A, B )   ( (A)>(B) ? (A) : (B) )
350
351/** Minimum and maximum of three values: */
352#define MIN3( A, B, C ) ((A) < (B) ? MIN2(A, C) : MIN2(B, C))
353#define MAX3( A, B, C ) ((A) > (B) ? MAX2(A, C) : MAX2(B, C))
354
355/** Align a value to a power of two */
356#define ALIGN_POT(x, pot_align) (((x) + (pot_align) - 1) & ~((pot_align) - 1))
357
358/** Checks is a value is a power of two. Does not handle zero. */
359#define IS_POT(v) (((v) & ((v) - 1)) == 0)
360
361/**
362 * Macro for declaring an explicit conversion operator.  Defaults to an
363 * implicit conversion if C++11 is not supported.
364 */
365#if __cplusplus >= 201103L
366#define EXPLICIT_CONVERSION explicit
367#elif defined(__cplusplus)
368#define EXPLICIT_CONVERSION
369#endif
370
371/** Set a single bit */
372#define BITFIELD_BIT(b)      (1u << (b))
373/** Set all bits up to excluding bit b */
374#define BITFIELD_MASK(b)      \
375   ((b) == 32 ? (~0u) : BITFIELD_BIT((b) % 32) - 1)
376/** Set count bits starting from bit b  */
377#define BITFIELD_RANGE(b, count) \
378   (BITFIELD_MASK((b) + (count)) & ~BITFIELD_MASK(b))
379
380/** Set a single bit */
381#define BITFIELD64_BIT(b)      (1ull << (b))
382/** Set all bits up to excluding bit b */
383#define BITFIELD64_MASK(b)      \
384   ((b) == 64 ? (~0ull) : BITFIELD64_BIT(b) - 1)
385/** Set count bits starting from bit b  */
386#define BITFIELD64_RANGE(b, count) \
387   (BITFIELD64_MASK((b) + (count)) & ~BITFIELD64_MASK(b))
388
389static inline int64_t
390u_intN_max(unsigned bit_size)
391{
392   assert(bit_size <= 64 && bit_size > 0);
393   return INT64_MAX >> (64 - bit_size);
394}
395
396static inline int64_t
397u_intN_min(unsigned bit_size)
398{
399   /* On 2's compliment platforms, which is every platform Mesa is likely to
400    * every worry about, stdint.h generally calculated INT##_MIN in this
401    * manner.
402    */
403   return (-u_intN_max(bit_size)) - 1;
404}
405
406static inline uint64_t
407u_uintN_max(unsigned bit_size)
408{
409   assert(bit_size <= 64 && bit_size > 0);
410   return UINT64_MAX >> (64 - bit_size);
411}
412
413#ifndef __cplusplus
414#ifdef _MSC_VER
415#define alignof _Alignof
416#define alignas _Alignas
417#else
418#include <stdalign.h>
419#endif
420#endif
421
422/* Macros for static type-safety checking.
423 *
424 * https://clang.llvm.org/docs/ThreadSafetyAnalysis.html
425 */
426
427#if __has_attribute(capability)
428typedef int __attribute__((capability("mutex"))) lock_cap_t;
429
430#define guarded_by(l) __attribute__((guarded_by(l)))
431#define acquire_cap(l) __attribute((acquire_capability(l), no_thread_safety_analysis))
432#define release_cap(l) __attribute((release_capability(l), no_thread_safety_analysis))
433#define assert_cap(l) __attribute((assert_capability(l), no_thread_safety_analysis))
434#define requires_cap(l) __attribute((requires_capability(l)))
435#define disable_thread_safety_analysis __attribute((no_thread_safety_analysis))
436
437#else
438
439typedef int lock_cap_t;
440
441#define guarded_by(l)
442#define acquire_cap(l)
443#define release_cap(l)
444#define assert_cap(l)
445#define requires_cap(l)
446#define disable_thread_safety_analysis
447
448#endif
449
450/* TODO: this could be different on non-x86 architectures. */
451#define CACHE_LINE_SIZE 64
452
453#define DO_PRAGMA(X) _Pragma (#X)
454
455#if defined(__clang__)
456#define PRAGMA_DIAGNOSTIC_PUSH       _Pragma("clang diagnostic push")
457#define PRAGMA_DIAGNOSTIC_POP        _Pragma("clang diagnostic pop")
458#define PRAGMA_DIAGNOSTIC_ERROR(X)   DO_PRAGMA( clang diagnostic error #X )
459#define PRAGMA_DIAGNOSTIC_WARNING(X) DO_PRAGMA( clang diagnostic warning #X )
460#define PRAGMA_DIAGNOSTIC_IGNORED(X) DO_PRAGMA( clang diagnostic ignored #X )
461#elif defined(__GNUC__)
462#define PRAGMA_DIAGNOSTIC_PUSH       _Pragma("GCC diagnostic push")
463#define PRAGMA_DIAGNOSTIC_POP        _Pragma("GCC diagnostic pop")
464#define PRAGMA_DIAGNOSTIC_ERROR(X)   DO_PRAGMA( GCC diagnostic error #X )
465#define PRAGMA_DIAGNOSTIC_WARNING(X) DO_PRAGMA( GCC diagnostic warning #X )
466#define PRAGMA_DIAGNOSTIC_IGNORED(X) DO_PRAGMA( GCC diagnostic ignored #X )
467#else
468#define PRAGMA_DIAGNOSTIC_PUSH
469#define PRAGMA_DIAGNOSTIC_POP
470#define PRAGMA_DIAGNOSTIC_ERROR(X)
471#define PRAGMA_DIAGNOSTIC_WARNING(X)
472#define PRAGMA_DIAGNOSTIC_IGNORED(X)
473#endif
474
475#endif /* UTIL_MACROS_H */
476