llvm / llvm/llvm-project

`__builtin_wmemchr` ignores `-fshort-wchar` on non-MSVC targets

Open
#195,149 50 comments 0 reactions 0 assignees View on GitHub
clang:codegen libc libc++
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

When `-fshort-wchar` is used on non-MSVC targets (macOS, Linux, etc.), `__builtin_wmemchr` produces incorrect results. The compiler lowers the builtin to a call to the system's `wmemchr`, which always operates on 4-byte `wchar_t` elements regardless of `-fshort-wchar`.

Reproducer:

```c
#include

int main() {
wchar_t arr[] = L"abc";
wchar_t *p = __builtin_wmemchr(arr, L'a', 3);
std::printf("result: %s\n", p ? "found" : "not found (BUG)");
return p ? 0 : 1;
}
```

$ clang++ -fshort-wchar test.cpp && ./a.out
result: not found (BUG)

This also breaks libc++'s `std::u16string::find` when compiled with `-fshort-wchar` as `std::__find` has an optimization that dispatches to a call to `__builtin_wmemchr` for any type where `sizeof(_Tp) == sizeof(wchar_t)`.

`__builtin_wmemcmp` likely has the same issue.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.