RE: [PATCH] compiler.h: Explain how __is_constexpr() works

From: David Laight
Date: Fri Mar 01 2024 - 04:32:34 EST


From: Kees Cook
> Sent: 01 March 2024 04:45
> To: Rasmus Villemoes <linux@xxxxxxxxxxxxxxxxxx>
>
> The __is_constexpr() macro is dark magic. Shed some light on it with
> a comment to explain how and why it works.

All the 8s don't help...

I don't think you need that much explanation.

Perhaps just saying that the type of ?: depends on the types
of the values and is independent of the condition.
The type of (0 ? (void *)p : (foo *)q) is normally 'void *'
(so that both values can be assigned to it).
But if 'p' is 'an integer constant expression with value 0'
then (void *)p is NULL and the type is 'foo *'.

The type can then be checked to find out it 'p' is constant 0.
A non-zero constant 'p' can be multiples by 0.

I need to replace the definition with (the more portable):
#define __if_constexpr(cond, if_const, if_not_const) \
_Generic(0 ? (void *)((long)(cond) * 0) : (char *)0, \
char *: (if_const), \
void *: (if_not_const))
which is arguably less cryptic.

#define __is_constexpr(cond) __if_constexpr(cond, 1, 0)

So that I can write:
#define is_non_neg_const(x) (__if_constexpr(x, x , -1) >= 0)
and avoid the compiler bleating about some comparisons
in unreachable code.

David

-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK
Registration No: 1397386 (Wales)