57 lines · c
1//===-- Shared/RefCnt.h - Helper to keep track of references --- 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-exception6//7//===----------------------------------------------------------------------===//8//9//===----------------------------------------------------------------------===//10 11#ifndef OMPTARGET_SHARED_REF_CNT_H12#define OMPTARGET_SHARED_REF_CNT_H13 14#include <atomic>15#include <cassert>16#include <limits>17#include <memory>18 19namespace llvm {20namespace omp {21namespace target {22 23/// Utility class for thread-safe reference counting. Any class that needs24/// objects' reference counting can inherit from this entity or have it as a25/// class data member.26template <typename Ty = uint32_t,27 std::memory_order MemoryOrder = std::memory_order_relaxed>28struct RefCountTy {29 /// Create a refcount object initialized to zero.30 RefCountTy() : Refs(0) {}31 32 ~RefCountTy() { assert(Refs == 0 && "Destroying with non-zero refcount"); }33 34 /// Increase the reference count atomically.35 void increase() { Refs.fetch_add(1, MemoryOrder); }36 37 /// Decrease the reference count and return whether it became zero. Decreasing38 /// the counter in more units than it was previously increased results in39 /// undefined behavior.40 bool decrease() {41 Ty Prev = Refs.fetch_sub(1, MemoryOrder);42 assert(Prev > 0 && "Invalid refcount");43 return (Prev == 1);44 }45 46 Ty get() const { return Refs.load(MemoryOrder); }47 48private:49 /// The atomic reference counter.50 std::atomic<Ty> Refs;51};52} // namespace target53} // namespace omp54} // namespace llvm55 56#endif57