Skip to content

LLVM cannot constant fold memchr with local buffer #114668

@philnik777

Description

@philnik777

LLVM is currently unable to constant fold calls memchr when a local buffer is passed. I noticed this while looking into libc++'s std::find optimizations.

This is a simple example where Clang doesn't constant fold the function even though it should be able to do that trivially: (Godbolt)

auto test() {
  char buffer[] = "Banane";
  return __builtin_memchr(buffer, 'a', __builtin_strlen(buffer)) == nullptr;
}

I think the problem is that __builtin_memchr can escape the pointer, so the buffer isn't recognized as immutable, resulting in the constant folder failing.

I'm in no way an expert in compiler optimizations, but I think it would be possible to check whether the pointer actually escapes, and if not, mark the pointer as noescape to at least partially solve this problem.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions