On Wed, Aug 04, 2021 at 03:20:45PM +0530, Prathamesh Kulkarni wrote:
> On Wed, 4 Aug 2021 at 03:27, Segher Boessenkool
> <seg...@kernel.crashing.org> wrote:
> > The Linux kernel has a macro __is_constexpr to test if something is an
> > integer constant expression, see <linux/const.h> .  That is a much
> > better idea imo.  There could be a builtin for that of course, but an
> > attribute is less powerful, less usable, less useful.
> Hi Segher,
> Thanks for the suggestions. I am not sure tho if we could use a macro
> similar to __is_constexpr
> to check if parameter is constant inside an inline function (which is
> the case for intrinsics) ?

I said we can make a builtin that returns if its arg is an ICE -- we do
not have to do tricky tricks :-)

The macro would work fine in an inline function though, or, where do you
see potential problems?

> For eg:
> #define __is_constexpr(x) \
>         (sizeof(int) == sizeof(*(8 ? ((void *)((long)(x) * 0l)) : (int *)8)))
> 
> inline int foo(const int x)
> {
>   _Static_assert (__is_constexpr (x));
>   return x;
> }
> 
> int main()
> {
>   return foo (1);
> }
> 
> results in:
> foo.c: In function ‘foo’:
> foo.c:8:3: error: static assertion failed
>     8 |   _Static_assert (__is_constexpr (x));

And that is correct, x is *not* an integer constant expression here.
Because it is a variable, instead :-)

If you do this in a macro it should work though?

> Initially we tried to use __Static_assert (__builtin_constant_p (arg))
> for the same purpose but that did not work
> because while parsing the intrinsic function, the FE cannot determine
> if the arg is indeed a constant.

Yes.  If you want something like that you need to test very late during
compilation whether something is a constant then: it will not be earlier.

> I guess the static assertion or __is_constexpr would work only if the
> intrinsic were defined as a macro instead of an inline function ?
> Or am I misunderstanding ?

Both __builtin_constant_p and __is_constexpr will not work in your use
case (since a function argument is not a constant, let alone an ICE).
It only becomes a constant value later on.  The manual (for the former)
says:
  You may use this built-in function in either a macro or an inline
  function. However, if you use it in an inlined function and pass an
  argument of the function as the argument to the built-in, GCC never
  returns 1 when you call the inline function with a string constant or
  compound literal (see Compound Literals) and does not return 1 when you
  pass a constant numeric value to the inline function unless you specify
  the -O option.
An integer constant expression is well-defined whatever the optimisation
level is, it is a feature of the language.

If some x is an ICE you can do
  asm ("" :: "n"(x));
and if it is a constant you can do
  asm ("" :: "i"(x));
(not that that gets you much further, but it might help explorng this).


Segher

Reply via email to