https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86415
Bug ID: 86415 Summary: TREE_STRING_LENGTH incorrect for constant arrays Product: gcc Version: 9.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: tree-optimization Assignee: unassigned at gcc dot gnu.org Reporter: msebor at gcc dot gnu.org Target Milestone: --- While testing a solution to bug 77357 I noticed that GCC fails to fold strlen() calls with constant char array arguments initialized by constant strings with an offset that's past the terminating NUL character unless the elements past the NUL are initialized explicitly as opposed to implicitly. I tracked it down to the c_getstr() function which normally returns a pointer to the string at the offset. The function uses TREE_STRING_LENGTH() to obtain the size of the string (i.e., the result of the sizeof(str) expression, as it should) but the macro returns the length of the string rather than its size. $ cat d.c && gcc -O2 -S -Wall -Wextra -fdump-tree-optimized=/dev/stdout d.c const char a[7] = "123\000\000\000"; int f (void) { return __builtin_strlen (a + 5); // folded } const char b[7] = "123"; int g (void) { return __builtin_strlen (b + 5); // not folded } ;; Function f (f, funcdef_no=0, decl_uid=1899, cgraph_uid=1, symbol_order=1) f () { <bb 2> [local count: 1073741825]: return 0; } ;; Function g (g, funcdef_no=1, decl_uid=1903, cgraph_uid=2, symbol_order=3) g () { long unsigned int _1; int _3; <bb 2> [local count: 1073741825]: _1 = __builtin_strlen (&MEM[(void *)&b + 5B]); _3 = (int) _1; return _3; }