You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Consider adding a LOCK CMPXCHG16B intrinsic method #28711
The CMPXCHG16B instruction is required to do CAS or atomic read of 128-bits values in memory. Currently, atomic 64-bits read and CAS is supported on .NET with the Interlocked.CompareExchange and Interlocked.Read, however the same operations are not support for 128-bits values.
I believe that the main problem is that the required instruction (CMPXCHG16B) is not supported on all CPUs, for example, it is not supported by some very old AMD CPUs, however it is a requirement to run Windows 8.1 and 10, so I beleive that the amount of CPUs were this instruction is not supported is very small.
Due to the above limitation, I beleive that the best way to support it is through an intrinsic, and the user can check if the instruction is supported on the current CPU, much like the other IsSupported properties that are exposed on the other ISA classes. The API would be something like this:
namespaceSystem.Runtime.Intrinsics.X86;publicstaticclassCmpxchg16B{// Cx16 flag check using the CPUID instruction (cached).publicstaticboolIsSupported{get;}// Returns the old value at destination.publicstatic(ulongLower,ulongUpper)InterlockedCompareExchange(void*destination,(ulongLower,ulongUpper)value,(ulongLower,ulongUpper)comparand);}
The CMPXCHG16B sets the zero flag, if the values at destination and the comparand are equal, and clears it otherwise. It sets the ZF flag if the values were equal and leaves it clear otherwise. The address is required to be 16 byte aligned.
Reacted by jduncanator, Domenico V., BaronKiko, AlgorithmsAreCool, Clinton Ingram, Abel Braaksma, Viktor Svub, Gregory Bell, moon-chilled, bysdxt and 14 more
This would consolidate both InterlockedCompareExchange16Bytes and InterlockedCompareExchange16BytesEqual into a single method that covered both use cases.
This would be fairly trivial to implement, as both the comparand and the "old value" (read from destination on failure) are stored in RDX:RAX, so an unconditional copy from RDX:RAX to oldValue at the end of the function call would be enough to handle setting oldValue.
Reacted by gdkchan, ちーず(・8・)けーき, Cole Tobin and Daniel Collingwood
But you are right that there are still problems with alignment with #31911
There is also the consideration that while CMPXCHG8B is a "baseline" instruction, CMPXCHG16B is a newer instruction and not guaranteed to be available (similar for Arm64 since Atomics aren't required).
We'd end up needing some IsSupported API to avoid any issues with tearing.
couldn't BitwiseAtomic have its alignment set to 16?
The GC has no support for such alignment today. If it did, then Int128, Vector128<T>, and some other types (which are ABI primitives and have a natural alignment of 16) would all be sufficient. Today, we only pack these types correctly (thus, struct S { byte x; Int128 y; } has a size of 32, but is only 8-byte aligned on a typical 64-bit computer).
The GC adding such support is complex and is tracked by various other issues, all of which have been indicated by the GC team to be very complex and potentially not "pay for play". To my knowledge the GC is also not in a position to be able to even test the benefit vs drawbacks of supporting new alignments or changing the default alignment.
If I'm understanding correctly, a "simple" alignment attribute like below would be very difficult to implement, especially considering GC interactions like compaction?
While we have an Int128 type now, we still can't do this without the requisite alignment guarantees and so it'd have to be updated to be a signature taking void*
I do believe that is reasonable and there's enough interest overall that it might be worth explicitly exposing this as a platform specific intrinsics or perhaps some explicit general-purpose API with a corresponding IsSupported check that can be queried about whether it even works.
@jkotas, any objections to exposing this as a platform specific intrinsic, given that we're unlikely to get GC support or other features that allow such a general purpose API?
namespaceSystem.Runtime.Intrinsics.X86;publicstaticclassCmpxchg16B{// Cx16 flag check using the CPUID instruction (cached).publicstaticboolIsSupported{get;}// Returns the old value at destination.publicstatic(ulongLower,ulongUpper)InterlockedCompareExchange(void*destination,(ulongLower,ulongUpper)value,(ulongLower,ulongUpper)comparand);}
CMPXCHG16B is the official CPUID name, so using this matches our existing conventions.
The JIT currently has no special understanding of Int128/UInt128 like it does for tuples and there are strict requirements to the registers used here, so this should simplify the JIT implementation. We could add that support, but it's then a bit "unique" compared to the rest of the intrinsics.
The instruction technically has both LOCK# and non-locked versions, but the non-locked isn't super optimized on most hardware and can be added in the future if we really need some weaker 16 byte compare exchange.
The ZF flag is written, but we really shouldn't have an issue with recognizing result == comparand after like we use for all the other cases.
Could it still be under System.Runtime.Intrinsics but not arch specific, keeping the 16B alignment semantics? That way all archs could share the intrinsic.
EDIT: If that'll be the case, it might make more sense to make it pairwise and use nuint so that its usable for 32bit too.
Added the missing "unsafe", otherwise looks good as proposed.
namespaceSystem.Runtime.Intrinsics.X86;publicstaticclassCmpxchg16B{// Cx16 flag check using the CPUID instruction (cached).publicstaticboolIsSupported{get;}// Returns the old value at destination.publicstaticunsafe(ulongLower,ulongUpper)InterlockedCompareExchange(void*destination,(ulongLower,ulongUpper)value,(ulongLower,ulongUpper)comparand);}
Reacted by OmariO, Hamish Arblaster, Cole Tobin and samsosa
While we have an Int128 type now, we still can't do this without the requisite alignment guarantees and so it'd have to be updated to be a signature taking void*
I do believe that is reasonable and there's enough interest overall that it might be worth explicitly exposing this as a platform specific intrinsics or perhaps some explicit general-purpose API with a corresponding IsSupported check that can be queried about whether it even works.
@jkotas, any objections to exposing this as a platform specific intrinsic, given that we're unlikely to get GC support or other features that allow such a general purpose API?
Possibly Dumb/dangerous question...
Given how long this has been wanted (Won't quote all the other cases, but I think some issues are 10ish years old,) would it be worth having some sort of either Variant of or Attribute for Int128/UInt128 to hint at alignment in a way that fits well with how the GC aligns things today? Or would that still be just too much work to make happen without touching the GC?
Activity
jduncanator commentedon Feb 17, 2019
Thinking about this a little, a more appropriate signature might be one using an out parameter for the old value, something like:
This would consolidate both
InterlockedCompareExchange16BytesandInterlockedCompareExchange16BytesEqualinto a single method that covered both use cases.This would be fairly trivial to implement, as both the comparand and the "old value" (read from destination on failure) are stored in
RDX:RAX, so an unconditional copy fromRDX:RAXtooldValueat the end of the function call would be enough to handle settingoldValue.tannergooding commentedon Mar 25, 2020
We can't support this without either taking in a set of
void*or exposing a newInt128typejkotas commentedon Mar 25, 2020
This is related/duplicate of #31911 . #31911 is a more general proposal.
tannergooding commentedon Mar 25, 2020
I thought we couldn't support
CMPXCHG16Bon 32-bit systems due to tearing and so it needed to be an intrinsic?jkotas commentedon Mar 25, 2020
#31911 avoids that problem by targeting pairs of pointer-sized items only.
jkotas commentedon Mar 25, 2020
But you are right that there are still problems with alignment with #31911 that would need to be solved (on both 32-bit and 64-bit platforms).
omariom commentedon Apr 30, 2021
@jkotas
Then may be it should go Unsafe?
Or a special unsafe subset of intrinsics.
ayende commentedon Jul 22, 2021
How about handling it with:
bool InterlockedCompareDCAS(Span<nint> destination, ReadOnly<nint>value, ReadOnlySpan<nint>comparand, Span<nint>oldValue);With the idea that
nintwill sort it out?This can be really useful for many scenarios, and the other options is:
https://gist.github.com/jduncanator/ab17e4e476300d3eb0b7c19f6f38429a
tannergooding commentedon Jul 30, 2022
There is also the consideration that while
CMPXCHG8Bis a "baseline" instruction,CMPXCHG16Bis a newer instruction and not guaranteed to be available (similar for Arm64 sinceAtomicsaren't required).We'd end up needing some
IsSupportedAPI to avoid any issues with tearing.13 remaining items
tannergooding commentedon Feb 18, 2025
The GC has no support for such alignment today. If it did, then
Int128,Vector128<T>, and some other types (which are ABI primitives and have a natural alignment of 16) would all be sufficient. Today, we only pack these types correctly (thus,struct S { byte x; Int128 y; }has a size of 32, but is only 8-byte aligned on a typical 64-bit computer).The GC adding such support is complex and is tracked by various other issues, all of which have been indicated by the GC team to be very complex and potentially not "pay for play". To my knowledge the GC is also not in a position to be able to even test the benefit vs drawbacks of supporting new alignments or changing the default alignment.
colejohnson66 commentedon Feb 19, 2025
If I'm understanding correctly, a "simple" alignment attribute like below would be very difficult to implement, especially considering GC interactions like compaction?
jkotas commentedon Feb 19, 2025
#22990 (comment) is a discussion about what it would take.
tannergooding commentedon Jul 11, 2026
While we have an
Int128type now, we still can't do this without the requisite alignment guarantees and so it'd have to be updated to be a signature takingvoid*I do believe that is reasonable and there's enough interest overall that it might be worth explicitly exposing this as a platform specific intrinsics or perhaps some explicit general-purpose API with a corresponding
IsSupportedcheck that can be queried about whether it even works.@jkotas, any objections to exposing this as a platform specific intrinsic, given that we're unlikely to get GC support or other features that allow such a general purpose API?
jkotas commentedon Jul 12, 2026
fine with me
tannergooding commentedon Jul 12, 2026
Updated to be:
CMPXCHG16Bis the official CPUID name, so using this matches our existing conventions.The JIT currently has no special understanding of
Int128/UInt128like it does for tuples and there are strict requirements to the registers used here, so this should simplify the JIT implementation. We could add that support, but it's then a bit "unique" compared to the rest of the intrinsics.The instruction technically has both
LOCK#and non-locked versions, but the non-locked isn't super optimized on most hardware and can be added in the future if we really need some weaker 16 byte compare exchange.The ZF flag is written, but we really shouldn't have an issue with recognizing
result == comparandafter like we use for all the other cases.MichalPetryka commentedon Jul 12, 2026
Could it still be under
System.Runtime.Intrinsicsbut not arch specific, keeping the 16B alignment semantics? That way all archs could share the intrinsic.EDIT: If that'll be the case, it might make more sense to make it pairwise and use nuint so that its usable for 32bit too.
tannergooding commentedon Jul 12, 2026
That'd be a net new design, but not impossible. I'm willing to consider it if there's no pushback.
bartonjs commentedon Aug 11, 2026
Video
Added the missing "unsafe", otherwise looks good as proposed.
to11mtm commentedon Aug 26, 2026
Possibly Dumb/dangerous question...
Given how long this has been wanted (Won't quote all the other cases, but I think some issues are 10ish years old,) would it be worth having some sort of either Variant of or Attribute for
Int128/UInt128to hint at alignment in a way that fits well with how the GC aligns things today? Or would that still be just too much work to make happen without touching the GC?