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

--- Comment #18 from Wilco <wdijkstr at arm dot com> ---
(In reply to Qing Zhao from comment #17)
> (In reply to Wilco from comment #16)
> 
> >> const char s[8] = “abcd\0abc”;  // null byte in the middle of the string
> >> int f2(void) { return __builtin_strcmp(s, "abc") != 0; }
> >> int f3(void) { return __builtin_strcmp(s, “abc”); }
> >> 
> >> can either of the above f2 or f3 been optimized to memcmp? seems not.
> > 
> > You never get that to the null byte as the memcmp only compares 
> > strlen("abc"+1)
> > characters.
> 
> Yes, this is correct for memcmp, but not for strcmp.  strcmp will get to the
> null byte. 
> as a result,  
> 
> const char s[8] = “abcd\0abc”;
> strcmp (s, “abc”) != 0.       // s = “abcd", which is != “abc"
> strncmp (s, “abc”, 3) == 0
> memcmp(s, “abc”, 3) == 0
> 
> So, strcmp cannot optimized to memcmp 

No that should be:

strcmp (s, “abc”) != 0
strncmp (s, “abc”, 4) != 0
memcmp(s, “abc”, 4) != 0

You need to compare the null terminator as well.

> > However do you mean an input string which is shorter than the
> > constant string? That's fine as this will compare not-equal in the memcmp.
> 
> for the input string is shorter than the constant string, for example: 
> 
> const char s[8] = “ab\0\0abcd”;
> strcmp (s, “abc”) != 0
> strncmp (s, “abc”, 3) != 0
> memcmp (s, “abc”,3) != 0
> 
> In a summary, since it’s NOT easy for the compiler to know where is the
> “Null_terminator” 
> in the string, strcmp is NOT reasonable to be optimized to memcmp whenever
> its result is 
> used to compare with zero or not.

The compiler knows where the null terminator is in the constant string so it
can easily figure out when it is legal as well as faster than doing a byte by
byte expansion of strcmp.

strcmp (s, STR) -> memcmp (s, strlen (STR) + 1) iff max(sizeof_array(s),
alignment(s)) > strlen (STR).

> But for strncmp, if the result is to compare with zero, it might be
> reasonable to optimized it
> to the corresponding memcmp, i.e
> 
> strncmp (s, “abc”, 3) != 0
> 
> could be optimized to
> 
> memcmp (s, “abc”, 3) != 0

If the strncmp size is smaller than the strlen of the constant string (and
alignment is right), yes. But strncmp (s, "abc", C) is equivalent to strcmp (s,
"abc") if C >= 4.

Reply via email to