https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94699
Bug ID: 94699 Summary: enhance -Wstring-compare to detect tautological or mutually exclusive strcmp expressions Product: gcc Version: 10.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: middle-end Assignee: unassigned at gcc dot gnu.org Reporter: msebor at gcc dot gnu.org Target Milestone: --- The article referenced in pr94629 (https://habr.com/en/company/pvs-studio/blog/497640/) points out the following suspicious-looking code in GCC: static bool dw_val_equal_p (dw_val_node *a, dw_val_node *b) { .... case dw_val_class_vms_delta: return (!strcmp (a->v.val_vms_delta.lbl1, b->v.val_vms_delta.lbl1) && !strcmp (a->v.val_vms_delta.lbl1, b->v.val_vms_delta.lbl1)); .... } and goes on to say: PVS-Studio warning: V501 There are identical sub-expressions '!strcmp(a->v.val_vms_delta.lbl1, b->v.val_vms_delta.lbl1)' to the left and to the right of the '&&' operator. dwarf2out.c 1481 Two strcmp functions compare the same pointers. That is, a clearly redundant check is performed. The -Wstring-compare warning introduced in GCC 10 is designed to detect likely erroneous uses of strcmp and strncmp that evaluate to a constant result due to the sizes of the pointed-to arrays. Detecting also this pattern seems like a natural and useful extension. (The warning is implemented in the strlen pass while these issues might perhaps be better diagnosed earlier.) A simple test case: int f0 (const char *a, const char *b) { // second strcmp call is redundant and can be eliminated; should // be diagnosed by -Wstring-compare (ditto with ||) return 0 == __builtin_strcmp (a, b) && 0 == __builtin_strcmp (b, a); } int f1 (const char *a) { // results of calls are mutually exclusive and the whole expression // can be folded to zero; should be diagnosed by -Wstring-compare return 0 == __builtin_strcmp (a, "123") && 0 == __builtin_strcmp (a, "456"); } Another similar warning designed to catch some of these likely bugs is -Wtautological-compare (see also pr70181).