https://gcc.gnu.org/bugzilla/show_bug.cgi?id=98503
Bug ID: 98503 Summary: [11 regression] -Warray-bounds false positive with global variables at -O2 Product: gcc Version: 11.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c Assignee: unassigned at gcc dot gnu.org Reporter: w at 1wt dot eu Target Milestone: --- First, please note that I saw a handful of related reports but couldn't judge if this one might be merged with another one; if you think it can, feel free to do so! We've had build errors reported on haproxy with gcc-11 due to walking over a list whose head is in a global variable. We could simplify the reproducer to this and confirm it on godbolt.org: #include <stddef.h> struct list { struct list *n; struct list *p; }; struct list head; struct ref { struct list list; char *filename; }; struct list *first(void) { struct ref *tmp; /*tmp = (struct ref *)((char *)&head - (size_t)&((struct ref *)0)->list);*/ tmp = (struct ref *)&head; //asm("" : "+rm"(tmp)); // hide tmp's origin to shut the warning. //asm("" : "=rm"(tmp) : "0"(&head)); // discretely assign tmp from head return tmp->list.n; } Note that only the "ref->list" part is accessed here, hence it exactly matches "head" (both of type struct list). But since gcc 11 (and only this one, 1.27 to 10.2 are OK), we're getting this: <source>: In function 'first': <source>:22:19: warning: array subscript 'struct ref[0]' is partly outside array bounds of 'struct list[1]' [-Warray-bounds] 22 | return tmp->list.n; | ^~ <source>:8:13: note: while referencing 'head' 8 | struct list head; | ^~~~ Compiler returned: 0 Changing "head" to a function argument makes the warning disappear, building at -O1 as well, and obviously, cheating with the asm statement to hide "tmp" solves it (though it degrades the code quality). Removing the unused "filename" from struct "ref" removes the warning. It looks to me as if the compiler doesn't know what part of a structure is being dereferenced when we access any member, making the warning systematically bogus for embedded members accessed via container_of() and friends when the list's head is global. For now we can disable the warning, I've confirmed the generated code is correct, but since it's the first time we have a false positive on this one, I'd prefer if we can keep it as much as possible as it's one which can definitely help spot real bugs. I've just verified the version used on godbolt.org, it's "gcc version 11.0.0 20210101 (experimental) (Compiler-Explorer-Build)". I haven't rebuilt the trunk locally so it might be possible this bug got solved since as part of one of the few related ones. Thanks! Willy