c, c++: Implement -Wsizeof-array-div [PR91741]
This patch implements a new warning, -Wsizeof-array-div. It warns about
code like
int arr[10];
sizeof (arr) / sizeof (short);
where we have a division of two sizeof expressions, where the first
argument is an array, and the second sizeof does not equal the size
of the array element. See e.g. <https://www.viva64.com/en/examples/v706/>.
Clang makes it possible to suppress the warning by parenthesizing the
second sizeof like this:
sizeof (arr) / (sizeof (short));
so I followed suit. In the C++ FE this was rather easy, because
finish_parenthesized_expr already set TREE_NO_WARNING. In the C FE
I've added a new tree code, PAREN_SIZEOF_EXPR, to discern between the
non-() and () versions.
This warning is enabled by -Wall. An example of the output:
x.c:5:23: warning: expression does not compute the number of elements in this array; element type is ‘int’, not ‘short int’ [-Wsizeof-array-div]
5 | return sizeof (arr) / sizeof (short);
| ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~
x.c:5:25: note: add parentheses around ‘sizeof (short int)’ to silence this warning
5 | return sizeof (arr) / sizeof (short);
| ^~~~~~~~~~~~~~
| ( )
x.c:4:7: note: array ‘arr’ declared here
4 | int arr[10];
| ^~~
gcc/c-family/ChangeLog:
PR c++/91741
* c-common.c (verify_tree): Handle PAREN_SIZEOF_EXPR.
(c_common_init_ts): Likewise.
* c-common.def (PAREN_SIZEOF_EXPR): New tree code.
* c-common.h (maybe_warn_sizeof_array_div): Declare.
* c-warn.c (sizeof_pointer_memaccess_warning): Unwrap NOP_EXPRs.
(maybe_warn_sizeof_array_div): New function.
* c.opt (Wsizeof-array-div): New option.
gcc/c/ChangeLog:
PR c++/91741
* c-parser.c (c_parser_binary_expression): Implement -Wsizeof-array-div.
(c_parser_postfix_expression): Set PAREN_SIZEOF_EXPR.
(c_parser_expr_list): Handle PAREN_SIZEOF_EXPR like SIZEOF_EXPR.
* c-tree.h (char_type_p): Declare.
* c-typeck.c (char_type_p): No longer static.
gcc/cp/ChangeLog:
PR c++/91741
* typeck.c (cp_build_binary_op): Implement -Wsizeof-array-div.
gcc/ChangeLog:
PR c++/91741
* doc/invoke.texi: Document -Wsizeof-array-div.
gcc/testsuite/ChangeLog:
PR c++/91741
* c-c++-common/Wsizeof-pointer-div.c: Add dg-warning.
* c-c++-common/Wsizeof-array-div1.c: New test.
* g++.dg/warn/Wsizeof-array-div1.C: New test.
* g++.dg/warn/Wsizeof-array-div2.C: New test.
14 files changed: