[Bug middle-end/95673] missing -Wstring-compare for an impossible strncmp test

msebor at gcc dot gnu.org gcc-bugzilla@gcc.gnu.org
Wed Sep 30 17:57:39 GMT 2020


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95673

Martin Sebor <msebor at gcc dot gnu.org> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Blocks|                            |83819

--- Comment #6 from Martin Sebor <msebor at gcc dot gnu.org> ---
There warning doesn't trigger for the first strcmp call (i.e., strcmp(file,
"file123.txt")) because it's folded into a conditional expression involving
just the lengths of the strings before it reaches the stage when it would
otherwise be issued.

Here's a small test case showing how it happens:

  int f (int c)
  {
    const char *s = c ? "12345" : "12";
    return 0 == __builtin_strcmp (s, "123");
  }

and the output pf the PRE pass (-fdump-tree-pre-details) shows:

...
Found partial redundancy for expression
{call_expr<__builtin_strcmp>,iftmp.0_3,addr_expr<"123">}@.MEM_5(D) (0001)
Created phi prephitmp_7 = PHI <-1(3), 1(5)>
 in block 4 (0001)
Starting insert iteration 2
Replaced 0 with pretmp_11 in all uses of pretmp_9 = 0;
Replaced 0 with pretmp_10 in all uses of pretmp_8 = 0;
Replaced __builtin_strcmp (iftmp.0_3, "123") with prephitmp_7 in all uses of _1
= __builtin_strcmp (iftmp.0_3, "123");
...
Removing dead stmt _1 = __builtin_strcmp (iftmp.0_3, "123");
...

The PRE pass runs much earlier than the strlen pass that issues the warning so
I don't think there's going to be anything to emit the warning in this case
(involving all string literals).

The PRE optimization isn't smart enough to handle the case when at least one of
the arguments is an ordinary array and so then warning does trigger:

  extern char a[3];

  int f (int c)
  {
    const char *s = c ? "12345" : a;
    return 0 == __builtin_strcmp (s, "123");
  }

The call is then folded away by the strlen pass (by the same code that issues
the warning).

In general, the warning code doesn't necessarily know the contents of the
arrays it's based on, only their lengths and/or sizes, so it can't very well
print them.  (Printing strings is also tricky because of constraints on the
volume of output, or the question how to deal with non-printable characters.)


Referenced Bugs:

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=83819
[Bug 83819] [meta-bug] missing strlen optimizations


More information about the Gcc-bugs mailing list