Skip to content

Commit d65eb5b

Browse files
committed
Add pg_assume(expr) macro
This macro can be used to avoid compiler warnings, particularly when using -O3 and not using assertions, and to get the compiler to generate better code. A subsequent commit introduces a first user. Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us> Discussion: https://postgr.es/m/3prdb6hkep3duglhsujrn52bkvnlkvhc54fzvph2emrsm4vodl@77yy6j4hkemb Discussion: https://postgr.es/m/20230316172818.x6375uvheom3ibt2%40awork3.anarazel.de Discussion: https://postgr.es/m/20240207203138.sknifhlppdtgtxnk%40awork3.anarazel.de
1 parent 4df4771 commit d65eb5b

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/include/c.h

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,36 @@
332332
#define pg_unreachable() abort()
333333
#endif
334334

335+
/*
336+
* pg_assume(expr) states that we assume `expr` to evaluate to true. In assert
337+
* enabled builds pg_assume() is turned into an assertion, in optimized builds
338+
* we try to clue the compiler into the fact that `expr` is true.
339+
*
340+
* This is useful for two purposes:
341+
*
342+
* 1) Avoid compiler warnings by telling the compiler about assumptions the
343+
* code makes. This is particularly useful when building with optimizations
344+
* and w/o assertions.
345+
*
346+
* 2) Help the compiler to generate more efficient code
347+
*
348+
* It is unspecified whether `expr` is evaluated, therefore it better be
349+
* side-effect free.
350+
*/
351+
#if defined(USE_ASSERT_CHECKING)
352+
#define pg_assume(expr) Assert(expr)
353+
#elif defined(HAVE__BUILTIN_UNREACHABLE)
354+
#define pg_assume(expr) \
355+
do { \
356+
if (!(expr)) \
357+
__builtin_unreachable(); \
358+
} while (0)
359+
#elif defined(_MSC_VER)
360+
#define pg_assume(expr) __assume(expr)
361+
#else
362+
#define pg_assume(expr) ((void) 0)
363+
#endif
364+
335365
/*
336366
* Hints to the compiler about the likelihood of a branch. Both likely() and
337367
* unlikely() return the boolean value of the contained expression.

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy