• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
30 #include "c99_compat.h"
31 #include "c11_compat.h"
32 
33 #include <stdint.h>
34 
35 /* Compute the size of an array */
36 #ifndef ARRAY_SIZE
37 #  define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
38 #endif
39 
40 /* For compatibility with Clang's __has_builtin() */
41 #ifndef __has_builtin
42 #  define __has_builtin(x) 0
43 #endif
44 
45 #ifndef __has_attribute
46 #  define __has_attribute(x) 0
47 #endif
48 
49 /**
50  * __builtin_expect macros
51  */
52 #if !defined(HAVE___BUILTIN_EXPECT)
53 #  define __builtin_expect(x, y) (x)
54 #endif
55 
56 #ifndef likely
57 #  ifdef HAVE___BUILTIN_EXPECT
58 #    define likely(x)   __builtin_expect(!!(x), 1)
59 #    define unlikely(x) __builtin_expect(!!(x), 0)
60 #  else
61 #    define likely(x)   (x)
62 #    define unlikely(x) (x)
63 #  endif
64 #endif
65 
66 /**
67  * __builtin_types_compatible_p compat
68  */
69 #if defined(__cplusplus) || !defined(HAVE___BUILTIN_TYPES_COMPATIBLE_P)
70 #  define __builtin_types_compatible_p(type1, type2) (1)
71 #endif
72 
73 /**
74  * Static (compile-time) assertion.
75  */
76 #if defined(_MSC_VER)
77    /* MSVC doesn't like VLA's, but it also dislikes zero length arrays
78     * (which gcc is happy with), so we have to define STATIC_ASSERT()
79     * slightly differently.
80     */
81 #  define STATIC_ASSERT(COND) do {         \
82       (void) sizeof(char [(COND) != 0]);   \
83    } while (0)
84 #elif defined(__GNUC__)
85    /* This version of STATIC_ASSERT() relies on VLAs.  If COND is
86     * false/zero, the array size will be -1 and we'll get a compile
87     * error
88     */
89 #  define STATIC_ASSERT(COND) do {         \
90       (void) sizeof(char [1 - 2*!(COND)]); \
91    } while (0)
92 #else
93 #  define STATIC_ASSERT(COND) do { } while (0)
94 #endif
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 #ifdef 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 #define PACKED __attribute__((__packed__))
208 #else
209 #define PACKED
210 #endif
211 
212 /* Attribute pure is used for functions that have no effects other than their
213  * return value.  As a result, calls to it can be dead code eliminated.
214  */
215 #ifdef HAVE_FUNC_ATTRIBUTE_PURE
216 #define ATTRIBUTE_PURE __attribute__((__pure__))
217 #else
218 #define ATTRIBUTE_PURE
219 #endif
220 
221 #ifdef HAVE_FUNC_ATTRIBUTE_RETURNS_NONNULL
222 #define ATTRIBUTE_RETURNS_NONNULL __attribute__((__returns_nonnull__))
223 #else
224 #define ATTRIBUTE_RETURNS_NONNULL
225 #endif
226 
227 #ifndef NORETURN
228 #  ifdef _MSC_VER
229 #    define NORETURN __declspec(noreturn)
230 #  elif defined HAVE_FUNC_ATTRIBUTE_NORETURN
231 #    define NORETURN __attribute__((__noreturn__))
232 #  else
233 #    define NORETURN
234 #  endif
235 #endif
236 
237 #ifdef _MSC_VER
238 #define ALIGN16 __declspec(align(16))
239 #else
240 #define ALIGN16 __attribute__((aligned(16)))
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__) && defined(__has_feature))
251 #      if __has_feature(has_trivial_destructor)
252 #         define HAS_TRIVIAL_DESTRUCTOR(T) __has_trivial_destructor(T)
253 #      endif
254 #   elif defined(__GNUC__)
255 #      if ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)))
256 #         define HAS_TRIVIAL_DESTRUCTOR(T) __has_trivial_destructor(T)
257 #      endif
258 #   elif defined(_MSC_VER) && !defined(__INTEL_COMPILER)
259 #      define HAS_TRIVIAL_DESTRUCTOR(T) __has_trivial_destructor(T)
260 #   endif
261 #   ifndef HAS_TRIVIAL_DESTRUCTOR
262        /* It's always safe (if inefficient) to assume that a
263         * destructor is non-trivial.
264         */
265 #      define HAS_TRIVIAL_DESTRUCTOR(T) (false)
266 #   endif
267 #endif
268 
269 /**
270  * PUBLIC/USED macros
271  *
272  * If we build the library with gcc's -fvisibility=hidden flag, we'll
273  * use the PUBLIC macro to mark functions that are to be exported.
274  *
275  * We also need to define a USED attribute, so the optimizer doesn't
276  * inline a static function that we later use in an alias. - ajax
277  */
278 #ifndef PUBLIC
279 #  if defined(_WIN32)
280 #    define PUBLIC __declspec(dllexport)
281 #    define USED
282 #  elif defined(__GNUC__)
283 #    define PUBLIC __attribute__((visibility("default")))
284 #    define USED __attribute__((used))
285 #  else
286 #    define PUBLIC
287 #    define USED
288 #  endif
289 #endif
290 
291 /**
292  * UNUSED marks variables (or sometimes functions) that have to be defined,
293  * but are sometimes (or always) unused beyond that. A common case is for
294  * a function parameter to be used in some build configurations but not others.
295  * Another case is fallback vfuncs that don't do anything with their params.
296  *
297  * Note that this should not be used for identifiers used in `assert()`;
298  * see ASSERTED below.
299  */
300 #ifdef HAVE_FUNC_ATTRIBUTE_UNUSED
301 #define UNUSED __attribute__((unused))
302 #else
303 #define UNUSED
304 #endif
305 
306 /**
307  * Use ASSERTED to indicate that an identifier is unused outside of an `assert()`,
308  * so that assert-free builds don't get "unused variable" warnings.
309  */
310 #ifdef NDEBUG
311 #define ASSERTED UNUSED
312 #else
313 #define ASSERTED
314 #endif
315 
316 #ifdef HAVE_FUNC_ATTRIBUTE_WARN_UNUSED_RESULT
317 #define MUST_CHECK __attribute__((warn_unused_result))
318 #else
319 #define MUST_CHECK
320 #endif
321 
322 #if defined(__GNUC__)
323 #define ATTRIBUTE_NOINLINE __attribute__((noinline))
324 #elif defined(_MSC_VER)
325 #define ATTRIBUTE_NOINLINE __declspec(noinline)
326 #else
327 #define ATTRIBUTE_NOINLINE
328 #endif
329 
330 /* Use as: enum name { X, Y } ENUM_PACKED; */
331 #if defined(__GNUC__)
332 #define ENUM_PACKED __attribute__((packed))
333 #else
334 #define ENUM_PACKED
335 #endif
336 
337 
338 /**
339  * Check that STRUCT::FIELD can hold MAXVAL.  We use a lot of bitfields
340  * in Mesa/gallium.  We have to be sure they're of sufficient size to
341  * hold the largest expected value.
342  * Note that with MSVC, enums are signed and enum bitfields need one extra
343  * high bit (always zero) to ensure the max value is handled correctly.
344  * This macro will detect that with MSVC, but not GCC.
345  */
346 #define ASSERT_BITFIELD_SIZE(STRUCT, FIELD, MAXVAL) \
347    do { \
348       ASSERTED STRUCT s; \
349       s.FIELD = (MAXVAL); \
350       assert((int) s.FIELD == (MAXVAL) && "Insufficient bitfield size!"); \
351    } while (0)
352 
353 
354 /** Compute ceiling of integer quotient of A divided by B. */
355 #define DIV_ROUND_UP( A, B )  ( ((A) + (B) - 1) / (B) )
356 
357 /** Clamp X to [MIN,MAX].  Turn NaN into MIN, arbitrarily. */
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 and maximum of three values: */
370 #define MIN3( A, B, C ) ((A) < (B) ? MIN2(A, C) : MIN2(B, C))
371 #define MAX3( A, B, C ) ((A) > (B) ? MAX2(A, C) : MAX2(B, C))
372 
373 /** Align a value to a power of two */
374 #define ALIGN_POT(x, pot_align) (((x) + (pot_align) - 1) & ~((pot_align) - 1))
375 
376 /**
377  * Macro for declaring an explicit conversion operator.  Defaults to an
378  * implicit conversion if C++11 is not supported.
379  */
380 #if __cplusplus >= 201103L
381 #define EXPLICIT_CONVERSION explicit
382 #elif defined(__cplusplus)
383 #define EXPLICIT_CONVERSION
384 #endif
385 
386 /** Set a single bit */
387 #define BITFIELD_BIT(b)      (1u << (b))
388 /** Set all bits up to excluding bit b */
389 #define BITFIELD_MASK(b)      \
390    ((b) == 32 ? (~0u) : BITFIELD_BIT((b) % 32) - 1)
391 /** Set count bits starting from bit b  */
392 #define BITFIELD_RANGE(b, count) \
393    (BITFIELD_MASK((b) + (count)) & ~BITFIELD_MASK(b))
394 
395 /** Set a single bit */
396 #define BITFIELD64_BIT(b)      (1ull << (b))
397 /** Set all bits up to excluding bit b */
398 #define BITFIELD64_MASK(b)      \
399    ((b) == 64 ? (~0ull) : BITFIELD64_BIT(b) - 1)
400 /** Set count bits starting from bit b  */
401 #define BITFIELD64_RANGE(b, count) \
402    (BITFIELD64_MASK((b) + (count)) & ~BITFIELD64_MASK(b))
403 
404 static inline int64_t
u_intN_max(unsigned bit_size)405 u_intN_max(unsigned bit_size)
406 {
407    assert(bit_size <= 64 && bit_size > 0);
408    return INT64_MAX >> (64 - bit_size);
409 }
410 
411 static inline int64_t
u_intN_min(unsigned bit_size)412 u_intN_min(unsigned bit_size)
413 {
414    /* On 2's compliment platforms, which is every platform Mesa is likely to
415     * every worry about, stdint.h generally calculated INT##_MIN in this
416     * manner.
417     */
418    return (-u_intN_max(bit_size)) - 1;
419 }
420 
421 static inline uint64_t
u_uintN_max(unsigned bit_size)422 u_uintN_max(unsigned bit_size)
423 {
424    assert(bit_size <= 64 && bit_size > 0);
425    return UINT64_MAX >> (64 - bit_size);
426 }
427 
428 /* TODO: In future we should try to move this to u_debug.h once header
429  * dependencies are reorganised to allow this.
430  */
431 enum pipe_debug_type
432 {
433    PIPE_DEBUG_TYPE_OUT_OF_MEMORY = 1,
434    PIPE_DEBUG_TYPE_ERROR,
435    PIPE_DEBUG_TYPE_SHADER_INFO,
436    PIPE_DEBUG_TYPE_PERF_INFO,
437    PIPE_DEBUG_TYPE_INFO,
438    PIPE_DEBUG_TYPE_FALLBACK,
439    PIPE_DEBUG_TYPE_CONFORMANCE,
440 };
441 
442 #if !defined(alignof) && !defined(__cplusplus)
443 #if __STDC_VERSION__ >= 201112L
444 #define alignof(t) _Alignof(t)
445 #elif defined(_MSC_VER)
446 #define alignof(t) __alignof(t)
447 #else
448 #define alignof(t) __alignof__(t)
449 #endif
450 #endif
451 
452 /* Macros for static type-safety checking.
453  *
454  * https://clang.llvm.org/docs/ThreadSafetyAnalysis.html
455  */
456 
457 #if __has_attribute(capability)
458 typedef int __attribute__((capability("mutex"))) lock_cap_t;
459 
460 #define guarded_by(l) __attribute__((guarded_by(l)))
461 #define acquire_cap(l) __attribute((acquire_capability(l), no_thread_safety_analysis))
462 #define release_cap(l) __attribute((release_capability(l), no_thread_safety_analysis))
463 #define assert_cap(l) __attribute((assert_capability(l), no_thread_safety_analysis))
464 #define requires_cap(l) __attribute((requires_capability(l)))
465 #define disable_thread_safety_analysis __attribute((no_thread_safety_analysis))
466 
467 #else
468 
469 typedef int lock_cap_t;
470 
471 #define guarded_by(l)
472 #define acquire_cap(l)
473 #define release_cap(l)
474 #define assert_cap(l)
475 #define requires_cap(l)
476 #define disable_thread_safety_analysis
477 
478 #endif
479 
480 #endif /* UTIL_MACROS_H */
481