[libc-commits] [libc] [libc] add more APIs of cmgxchg variants (PR #91208)

Schrodinger ZHU Yifan via libc-commits libc-commits at lists.llvm.org
Mon May 6 07:05:25 PDT 2024


https://github.com/SchrodingerZhu created https://github.com/llvm/llvm-project/pull/91208

Such APIs are useful in lock implementations

>From bf224ebd4df6cc60b4bc12bc064e96dcea6fffde Mon Sep 17 00:00:00 2001
From: Schrodinger ZHU Yifan <yifanzhu at rochester.edu>
Date: Mon, 6 May 2024 10:03:41 -0400
Subject: [PATCH] [libc] add more APIs of cmgxchg variants

---
 libc/src/__support/CPP/atomic.h | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)

diff --git a/libc/src/__support/CPP/atomic.h b/libc/src/__support/CPP/atomic.h
index 5e428940565b99..e273d998c07029 100644
--- a/libc/src/__support/CPP/atomic.h
+++ b/libc/src/__support/CPP/atomic.h
@@ -101,6 +101,36 @@ template <typename T> struct Atomic {
                                        int(mem_ord), int(mem_ord));
   }
 
+  // Atomic compare exchange (separate success and failure memory orders)
+  bool compare_exchange_strong(
+      T &expected, T desired, MemoryOrder success_order,
+      MemoryOrder failure_order,
+      [[maybe_unused]] MemoryScope mem_scope = MemoryScope::DEVICE) {
+    return __atomic_compare_exchange_n(&val, &expected, desired, false,
+                                       static_cast<int>(success_order),
+                                       static_cast<int>(failure_order));
+  }
+
+  // Atomic compare exchange (weak version)
+  bool compare_exchange_weak(
+      T &expected, T desired, MemoryOrder mem_ord = MemoryOrder::SEQ_CST,
+      [[maybe_unused]] MemoryScope mem_scope = MemoryScope::DEVICE) {
+    return __atomic_compare_exchange_n(&val, &expected, desired, true,
+                                       static_cast<int>(mem_ord),
+                                       static_cast<int>(mem_ord));
+  }
+
+  // Atomic compare exchange (weak version with separate success and failure
+  // memory orders)
+  bool compare_exchange_weak(
+      T &expected, T desired, MemoryOrder success_order,
+      MemoryOrder failure_order,
+      [[maybe_unused]] MemoryScope mem_scope = MemoryScope::DEVICE) {
+    return __atomic_compare_exchange_n(&val, &expected, desired, true,
+                                       static_cast<int>(success_order),
+                                       static_cast<int>(failure_order));
+  }
+
   T exchange(T desired, MemoryOrder mem_ord = MemoryOrder::SEQ_CST,
              [[maybe_unused]] MemoryScope mem_scope = MemoryScope::DEVICE) {
 #if __has_builtin(__scoped_atomic_exchange_n)



More information about the libc-commits mailing list