c: Add _Countof operator [PR117025]
This operator is similar to sizeof but can only be applied to an array,
and returns its number of elements.
FUTURE DIRECTIONS:
- We should make it work with array parameters to functions,
and somehow magically return the number of elements of the array,
regardless of it being really a pointer.
Link: <https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3550.pdf>
Link: <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=117025>
Link: <https://inbox.sourceware.org/gcc/M8S4oQy--3-2@tutanota.com/T/>
Link: <https://inbox.sourceware.org/gcc-patches/
20240728141547.302478-1-alx@kernel.org/T/#t>
Link: <https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3313.pdf>
Link: <https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3325.pdf>
Link: <https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3369.pdf>
Link: <https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3469.htm>
Link: <https://github.com/llvm/llvm-project/issues/102836>
Link: <https://thephd.dev/the-big-array-size-survey-for-c>
Link: <https://thephd.dev/the-big-array-size-survey-for-c-results>
Link: <https://stackoverflow.com/questions/37538/#
57537491>
PR c/117025
gcc/ChangeLog:
* doc/extend.texi: Document _Countof operator.
gcc/c-family/ChangeLog:
* c-common.h (enum rid): Add RID_COUNTOF.
(c_countof_type): New function prototype.
* c-common.def (COUNTOF_EXPR): New tree.
* c-common.cc (c_common_reswords): Add RID_COUNTOF entry.
(c_countof_type): New function.
gcc/c/ChangeLog:
* c-tree.h (in_countof): Add global variable declaration.
(c_expr_countof_expr): Add function prototype.
(c_expr_countof_type): Add function prototype.
* c-decl.cc (start_struct, finish_struct): Add support for
_Countof.
(start_enum, finish_enum): Add support for _Countof.
* c-parser.cc (c_parser_sizeof_expression): New macro.
(c_parser_countof_expression): New macro.
(c_parser_sizeof_or_countof_expression): Rename function and add
support for _Countof.
(c_parser_unary_expression): Add RID_COUNTOF entry.
* c-typeck.cc (in_countof): Add global variable.
(build_external_ref): Add support for _Countof.
(record_maybe_used_decl): Add support for _Countof.
(pop_maybe_used): Add support for _Countof.
(is_top_array_vla): New function.
(c_expr_countof_expr, c_expr_countof_type): New functions.
gcc/testsuite/ChangeLog:
* gcc.dg/countof-compile.c: New test.
* gcc.dg/countof-vla.c: New test.
* gcc.dg/countof-vmt.c: New test.
* gcc.dg/countof-zero-compile.c: New test.
* gcc.dg/countof-zero.c: New test.
* gcc.dg/countof.c: New test.
Suggested-by: Xavier Del Campo Romero <xavi.dcr@tutanota.com>
Co-authored-by: Martin Uecker <uecker@tugraz.at>
Acked-by: "James K. Lowden" <jklowden@schemamania.org>
Signed-off-by: Alejandro Colomar <alx@kernel.org>