https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109071
Bug ID: 109071
Summary: -Warray-bounds warning when array index checked via
inline
Product: gcc
Version: 13.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c
Assignee: unassigned at gcc dot gnu.org
Reporter: kees at outflux dot net
Target Milestone: ---
Created attachment 54611
--> https://gcc.gnu.org/bugzilla/attachment.cgi?id=54611&action=edit
PoC for -Warray-bounds false positive
The Linux kernel is seeing -Warray-bounds warnings when array indexes are being
checked via inlines. This appears to be in the overly noisy/false positive
territory, but I don't actually know what's going on.
The upstream report is here:
https://lore.kernel.org/lkml/[email protected]/
Originally I thought this was another -fsanitizer=shift issue, but after
reducing the test-case, it seems to be related to inlining or some other aspect
of optimization passes.
If the "assign" function is open-coded in the caller, the warning goes away.
If the index checks are moved before the "assign" calls, the warning goes away.
If there is only 1 call to "assign", the warning goes away.
Fundamentally there should be no warning at all since the value of "index" is
entirely unknown _except_ when it makes the call to "warn".
$ cat test.c
extern void warn(void);
#define MAX_ENTRIES 4
static inline void assign(int val, int *regs, int index)
{
if (index >= MAX_ENTRIES)
warn();
*regs = val;
}
struct nums {
int vals[MAX_ENTRIES];
};
void sparx5_psfp_sg_set(int *ptr, struct nums *sg, int index)
{
int *val;
val = &sg->vals[index];
assign(0, ptr, index);
assign(*val, ptr, index);
}
$ gcc -Wall -O2 -c -o test.o test.c
test.c: In function 'sparx5_psfp_sg_set':
test.c:20:24: warning: array subscript 4 is above array bounds of 'int[4]'
[-Warray-bounds=]
20 | val = &sg->vals[index];
| ~~~~~~~~^~~~~~~
test.c:13:13: note: while referencing 'vals'
13 | int vals[MAX_ENTRIES];
| ^~~~