https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86937
Bug ID: 86937 Summary: strnlen() of a conditional expression with constant operands not folded 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: --- GCC folds the strlen() call below with a conditional expression involving constant operands but it fails to do the same for the equivalent strnlen() call. Besides missing this optimization opportunity it also prevents it from diagnosing strnlen() calls with unterminated character arrays where the bound is greater than the size of the array. $ cat f.c && gcc -O2 -S -Wall -Wextra -Wnull-dereference -fdump-tree-optimized=/dev/stdout f.c const char a[4] = "123"; int f (int i) { return __builtin_strlen (i ? a : ""); } int g (int i) { return __builtin_strnlen (i ? a : "", 4); } ;; Function f (f, funcdef_no=0, decl_uid=1906, cgraph_uid=1, symbol_order=1) Removing basic block 3 f (int i) { int prephitmp_7; <bb 2> [local count: 1073741825]: if (i_3(D) != 0) goto <bb 4>; [50.00%] else goto <bb 3>; [50.00%] <bb 3> [local count: 536870913]: <bb 4> [local count: 1073741825]: # prephitmp_7 = PHI <3(2), i_3(D)(3)> return prephitmp_7; } ;; Function g (g, funcdef_no=1, decl_uid=1909, cgraph_uid=2, symbol_order=2) Removing basic block 3 g (int i) { long unsigned int _1; const char * iftmp.1_2; int _5; <bb 2> [local count: 1073741825]: if (i_3(D) != 0) goto <bb 4>; [50.00%] else goto <bb 3>; [50.00%] <bb 3> [local count: 536870913]: <bb 4> [local count: 1073741825]: # iftmp.1_2 = PHI <&a(2), ""(3)> _1 = __builtin_strnlen (iftmp.1_2, 4); _5 = (int) _1; return _5; }