[llvm] [OFFLOAD] Add support for indexed per-thread containers (PR #164263)

Kevin Sala Penades via llvm-commits llvm-commits at lists.llvm.org
Thu Nov 20 14:52:09 PST 2025


================
@@ -14,74 +14,167 @@
 #define OFFLOAD_PERTHREADTABLE_H
 
 #include <list>
+#include <llvm/ADT/SmallVector.h>
+#include <llvm/Support/Error.h>
 #include <memory>
 #include <mutex>
+#include <type_traits>
+
+template <typename ObjectType> class PerThread {
+  std::mutex Mutex;
+  llvm::SmallVector<std::shared_ptr<ObjectType>> ThreadDataList;
+
+  ObjectType &getThreadData() {
+    static thread_local std::shared_ptr<ObjectType> ThreadData = nullptr;
+    if (!ThreadData) {
+      ThreadData = std::make_shared<ObjectType>();
+      std::lock_guard<std::mutex> Lock(Mutex);
+      ThreadDataList.push_back(ThreadData);
+    }
+    return *ThreadData;
+  }
+
+public:
+  // define default constructors, disable copy and move constructors
+  PerThread() = default;
+  PerThread(const PerThread &) = delete;
+  PerThread(PerThread &&) = delete;
+  PerThread &operator=(const PerThread &) = delete;
+  PerThread &operator=(PerThread &&) = delete;
+  ~PerThread() {
+    assert(Mutex.try_lock() && (Mutex.unlock(), true) &&
+           "Cannot be deleted while other threads are adding entries");
+    ThreadDataList.clear();
+  }
+
+  ObjectType &get() { return getThreadData(); }
+
+  template <class ClearFuncTy> void clear(ClearFuncTy ClearFunc) {
+    assert(Mutex.try_lock() && (Mutex.unlock(), true) &&
+           "Clear cannot be called while other threads are adding entries");
+    for (std::shared_ptr<ObjectType> ThreadData : ThreadDataList) {
+      if (!ThreadData)
+        continue;
+      ClearFunc(*ThreadData);
+    }
+    ThreadDataList.clear();
+  }
+};
+
+template <typename ContainerTy> struct ContainerConcepts {
+  template <typename, template <typename> class, typename = std::void_t<>>
+  struct has : std::false_type {};
+  template <typename Ty, template <typename> class Op>
+  struct has<Ty, Op, std::void_t<Op<Ty>>> : std::true_type {};
+
+  template <typename Ty> using IteratorTypeCheck = typename Ty::iterator;
+  template <typename Ty> using MappedTypeCheck = typename Ty::mapped_type;
+  template <typename Ty> using ValueTypeCheck = typename Ty::value_type;
+  template <typename Ty> using KeyTypeCheck = typename Ty::key_type;
+  template <typename Ty> using SizeTyCheck = typename Ty::size_type;
----------------
kevinsala wrote:

SizeTypeCheck?

https://github.com/llvm/llvm-project/pull/164263


More information about the llvm-commits mailing list