14 #ifndef MLIR_SUPPORT_THREADLOCALCACHE_H
15 #define MLIR_SUPPORT_THREADLOCALCACHE_H
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/Support/ManagedStatic.h"
20 #include "llvm/Support/Mutex.h"
26 template <
typename ValueT>
32 struct PerInstanceState {
35 void remove(ValueT *value) {
38 llvm::sys::SmartScopedLock<true> threadInstanceLock(instanceMutex);
40 llvm::find_if(instances, [&](std::unique_ptr<ValueT> &instance) {
41 return instance.get() == value;
43 assert(it != instances.end() &&
"expected value to exist in cache");
61 :
public llvm::SmallDenseMap<PerInstanceState *, std::weak_ptr<ValueT>> {
64 for (
auto &it : *
this)
65 if (std::shared_ptr<ValueT> value = it.second.lock())
66 it.first->remove(value.get());
71 void clearExpiredEntries() {
72 for (
auto it = this->begin(), e = this->end(); it != e;) {
74 if (curIt->second.expired())
90 CacheType &staticCache = getStaticCache();
91 std::weak_ptr<ValueT> &threadInstance = staticCache[perInstanceState.get()];
92 if (std::shared_ptr<ValueT> value = threadInstance.lock())
96 llvm::sys::SmartScopedLock<true> threadInstanceLock(
97 perInstanceState->instanceMutex);
98 perInstanceState->instances.push_back(std::make_unique<ValueT>());
99 ValueT *instance = perInstanceState->instances.back().get();
100 threadInstance = std::shared_ptr<ValueT>(perInstanceState, instance);
105 staticCache.clearExpiredEntries();
117 static CacheType &getStaticCache() {
118 static LLVM_THREAD_LOCAL CacheType cache;
122 std::shared_ptr<PerInstanceState> perInstanceState =
123 std::make_shared<PerInstanceState>();
This class provides support for defining a thread local object with non static storage duration.
ThreadLocalCache()=default
ValueT & get()
Return an instance of the value type for the current thread.
This header declares functions that assist transformations in the MemRef dialect.