https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78450
Bug ID: 78450 Summary: strlen(s) return value can be assumed to be less than the size of s Product: gcc Version: 7.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: --- In a call to strlen(p) where p points to two or more constant strings of known lengths GCC determines the length of the longest string and uses that as the upper bound of the range of values returned by the call. Similarly, in a call to strlen(q) where the length of one or more of the strings pointed to by q is not known but where q points to arrays of known size, GCC could use the size of the largest array as the upper bound (modulo flexible array members and such). However, the test case below shows that GCC does not take advantage of this possible optimization opportunity. $ (set -x && cat x.c && gcc -O2 -S -Wall -Wextra -Wpedantic -fdump-tree-optimized=/dev/stdout x.c | grep -e "^[fg] (" -e abort) + cat x.c const char a[] = "123"; const char b[] = "1234"; void f (int i) { const char *s = i < 0 ? a : b; unsigned n = __builtin_strlen (s); if (4 < n) __builtin_abort (); } char a3[3]; char b4[4]; void g (int i) { const char *s = i < 0 ? a3 : b4; unsigned n = __builtin_strlen (s); if (3 < n) __builtin_abort (); } + gcc -O2 -S -Wall -Wextra -Wpedantic -fdump-tree-optimized=/dev/stdout x.c + grep --color=auto -e '^[fg] (' -e abort f (int i) g (int i) __builtin_abort ();