Teach MSVC that elog/ereport ERROR doesn't return
authorDavid Rowley <[email protected]>
Sat, 27 Sep 2025 10:41:04 +0000 (22:41 +1200)
committerDavid Rowley <[email protected]>
Sat, 27 Sep 2025 10:41:04 +0000 (22:41 +1200)
commit59c2f03d1ece7b9b215751a508b3a84728419246
treeecdd7ea97f65d1ad5f1e7add1fc8d8e01d473d58
parent66cdef4425f3295a2cfbce3031b3c0f0b5dffc04
Teach MSVC that elog/ereport ERROR doesn't return

It had always been intended that this already works correctly as
pg_unreachable() uses __assume(0) on MSVC, and that directs the compiler
in a way so it knows that a given function won't return.  However, with
ereport_domain(), it didn't work...

It's now understood that the failure to determine that elog(ERROR) does not
return comes from the inability of the MSVC compiler to detect the "const
int elevel_" is the same as the "elevel" macro parameter.  MSVC seems to be
unable to make the "if (elevel_ >= ERROR) branch constantly-true when the
macro is used with any elevel >= ERROR, therefore the pg_unreachable() is
seen to only be present in a *conditional* branch rather than present
*unconditionally*.

While there seems to be no way to force the compiler into knowing that
elevel_ is equal to elevel within the ereport_domain() macro, there is a
way in C11 to determine if the elevel parameter is a compile-time
constant or not.  This is done via some hackery using the _Generic()
intrinsic function, which gives us functionality similar to GCC's
__builtin_constant_p(), albeit only for integers.

Here we define pg_builtin_integer_constant_p() for this purpose.
Callers can check for availability via HAVE_PG_BUILTIN_INTEGER_CONSTANT_P.
ereport_domain() has been adjusted to use
pg_builtin_integer_constant_p() instead of __builtin_constant_p().

It's not quite clear at this stage if this now allows us to forego doing
the likes of "return NULL; /* keep compiler quiet */" as there may be other
compilers in use that have similar struggles.  It's just a matter of time
before someone commits a function that does not "return" a value after
an elog(ERROR).  Let's make time and lack of complaints about said commit
be the judge of if we need to continue the "/* keep compiler quiet */"
palaver.

Author: David Rowley <[email protected]>
Reviewed-by: Peter Eisentraut <[email protected]>
Discussion: https://postgr.es/m/CAApHDvom02B_XNVSkvxznVUyZbjGAR+5myA89ZcbEd3=PA9UcA@mail.gmail.com
src/include/c.h
src/include/utils/elog.h