llvm / llvm/llvm-project

clang-cl.exe wrong defaults for cmpxchg16

Open
#166,786 0 comments 0 reactions 0 assignees View on GitHub
clang-cl diverges-from:msvc
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

# Description

From Clang's [user manual](https://clang.llvm.org/docs/UsersManual.html#id117):
> clang-cl is an alternative command-line interface to Clang, designed for compatibility with the Visual C++ compiler, cl.exe.

Currently clang refuses to emit `lock cmpcxhg16` when calling `_InterlockedCompareExchange128`.
This behavior does not match cl.exe.

# Affected versions
At least Clang 19 and 21, I did not try older versions.

# Steps to reproduce

cmpxchg16.c:
```c
#include

#if _MSC_VER < 1930
#error "Old"
#endif

__declspec(dllexport) char test(volatile long long* dst, long long hi, long long lo, long long* result) {
return _InterlockedCompareExchange128(dst, hi, lo, result);
}
```

compile with cl.exe works:
```sh
"cl.exe" -nologo -Focmpxchg16-msvc.c.obj -c cmpxchg16.c
"link.exe" -nologo -nodefaultlib -noentry -machine:x64 -dll cmpxchg16-msvc.c.obj -out:cmpxchg16-msvc.dll
```

compile with clang-cl.exe does not work:
```sh
"D:\\LLVM\\LLVM-21.1.4\\bin\\clang-cl.exe" -nologo -Focmpxchg16-clang.c.obj -c cmpxchg16.c
"D:\\LLVM\\LLVM-21.1.4\\bin\\lld-link.exe" -nologo -nodefaultlib -noentry -machine:x64 -dll cmpxchg16-clang.c.obj -out:cmpxchg16-clang.dll
```
instead it outputs:
```sh
lld-link: error: undefined symbol: __security_cookie
>>> referenced by cmpxchg16-clang.c.obj:(test)
>>> referenced by cmpxchg16-clang.c.obj:(test)

lld-link: error: undefined symbol: __atomic_compare_exchange_16
>>> referenced by cmpxchg16-clang.c.obj:(test)

lld-link: error: undefined symbol: __security_check_cookie
>>> referenced by cmpxchg16-clang.c.obj:(test)
```

# Workaround
Adding `-mcx16` to clang-cl.exe CLI flags. This option is not supported by real cl.exe and integrating it to buildsystem conditionally might not be trivial.

# Additional notes
Required instructions for Windows 10 from [Microsoft docs](https://learn.microsoft.com/en-us/windows-server/get-started/hardware-requirements?tabs=cpu&pivots=windows-server-2016):
> Support for CMPXCHG16b, LAHF/SAHF, and PrefetchW instructions

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the issue with the payload's cmpxchg16.c using clang-cl.exe, then compare its output and linker errors with cl.exe and the -mcx16 workaround. Done means clang-cl emits lock cmpxchg16 for _InterlockedCompareExchange128 by default and the shown link succeeds without the workaround.

Written by the indexing model from the issue text.

Assessment

Tech stack
c
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.