|
| 1 | +//===-- Transactional Ptr for ABA prevention --------------------*- C++ -*-===// |
| 2 | +// |
| 3 | +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | +// See https://llvm.org/LICENSE.txt for license information. |
| 5 | +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | +// |
| 7 | +//===----------------------------------------------------------------------===// |
| 8 | + |
| 9 | +#ifndef LLVM_LIBC_SRC___SUPPORT_TAGGED_POINTER_H |
| 10 | +#define LLVM_LIBC_SRC___SUPPORT_TAGGED_POINTER_H |
| 11 | + |
| 12 | +#include "src/__support/common.h" |
| 13 | +#include "src/__support/threads/sleep.h" |
| 14 | + |
| 15 | +#ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_16 |
| 16 | +#define LIBC_ABA_PTR_IS_ATOMIC true |
| 17 | +#else |
| 18 | +#define LIBC_ABA_PTR_IS_ATOMIC false |
| 19 | +#endif |
| 20 | + |
| 21 | +namespace LIBC_NAMESPACE_DECL { |
| 22 | + |
| 23 | +template <class T, bool IsAtomic> struct AbaPtrImpl { |
| 24 | + union Impl { |
| 25 | + struct alignas(2 * alignof(void *)) Atomic { |
| 26 | + T *ptr; |
| 27 | + __SIZE_TYPE__ tag; |
| 28 | + } atomic; |
| 29 | + struct Mutex { |
| 30 | + T *ptr; |
| 31 | + bool locked; |
| 32 | + } mutex; |
| 33 | + } impl; |
| 34 | + |
| 35 | + LIBC_INLINE constexpr AbaPtrImpl(T *ptr) |
| 36 | + : impl(IsAtomic ? Impl{.atomic{ptr, 0}} : Impl{.mutex{ptr, false}}) {} |
| 37 | + |
| 38 | + /// User must guarantee that operation is redoable. |
| 39 | + template <class Op> LIBC_INLINE void transaction(Op &&op) { |
| 40 | + if constexpr (IsAtomic) { |
| 41 | + for (;;) { |
| 42 | + typename Impl::Atomic snapshot, next; |
| 43 | + __atomic_load(&impl.atomic, &snapshot, __ATOMIC_RELAXED); |
| 44 | + next.ptr = op(snapshot.ptr); |
| 45 | + // Wrapping add for unsigned integers. |
| 46 | + next.tag = snapshot.tag + 1; |
| 47 | + if (__atomic_compare_exchange(&impl.atomic, &snapshot, &next, true, |
| 48 | + __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)) { |
| 49 | + return; |
| 50 | + } |
| 51 | + } |
| 52 | + } else { |
| 53 | + // Acquire the lock. |
| 54 | + while (__atomic_exchange_n(&impl.mutex.locked, true, __ATOMIC_ACQUIRE)) { |
| 55 | + while (__atomic_load_n(&impl.mutex.locked, __ATOMIC_RELAXED)) { |
| 56 | + LIBC_NAMESPACE::sleep_briefly(); |
| 57 | + } |
| 58 | + } |
| 59 | + impl.mutex.ptr = op(impl.mutex.ptr); |
| 60 | + // Release the lock. |
| 61 | + __atomic_store_n(&impl.mutex.locked, false, __ATOMIC_RELEASE); |
| 62 | + } |
| 63 | + } |
| 64 | +}; |
| 65 | + |
| 66 | +template <class T> using AbaPtr = AbaPtrImpl<T, LIBC_ABA_PTR_IS_ATOMIC>; |
| 67 | +} // namespace LIBC_NAMESPACE_DECL |
| 68 | + |
| 69 | +#undef LIBC_ABA_PTR_IS_ATOMIC |
| 70 | +#endif |
0 commit comments