This is an archive of the discontinued LLVM Phabricator instance.

[InstCombine] Expand strcmp(s, "x") to memcmp
AbandonedPublic

Authored by xbolva00 on Jul 30 2018, 3:22 PM.

Details

Reviewers
efriedma
Summary

strcmp(s, y) -> memcmp(s,y,2) where y is string with single char, e.g. "x")

Diff Detail

Event Timeline

xbolva00 created this revision.Jul 30 2018, 3:22 PM

This is not correct: consider, for example, strcmp("xx", "x").

xbolva00 updated this revision to Diff 158109.Jul 30 2018, 3:33 PM
This comment was removed by xbolva00.

Ah yes, sure. I updated patch to compare two chars

xbolva00 edited the summary of this revision. (Show Details)Jul 30 2018, 3:37 PM
xbolva00 retitled this revision from [InstCombine] Expand strcmp(s, "x") to char comparision to [InstCombine] Expand strcmp(s, "x") to memcmp.
xbolva00 edited the summary of this revision. (Show Details)

Oh, okay, that makes more sense.

Unfortunately, this transform is still illegal: if the unknown operand is the empty string, memcmp can read past the end of the string, which is undefined behavior (and may crash in practice).

xbolva00 abandoned this revision.Jul 30 2018, 3:45 PM

Oh, okay, that makes more sense.

Unfortunately, this transform is still illegal: if the unknown operand is the empty string, memcmp can read past the end of the string, which is undefined behavior (and may crash in practice).

Ah yes :/ I wanted to do similar transformation as GCC does. But with memcmp this is not possible.

If you want to expand strcmp inline, probably the best way to do that is to extend the existing ExpandMemCmpPass pass.

What about

char buf[10];
if (strcmp(buf, "key") eq / ne 0)

?

We can promote it to memcmp now, no?

Not sure how often that shows up, but yes, if you can prove the the pointer is dereferenceable, it's okay to transform to memcmp.

Not sure how often that shows up, but yes, if you can prove the the pointer is dereferenceable, it's okay to transform to memcmp.

It is not so rare, I see it in many code bases.

Motivating example;
https://searchcode.com/file/71153892/src/resmom/linux/mom_mach.c