#include "mlir/Support/StorageUniquer.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Support/ThreadLocalCache.h"
#include "mlir/Support/TypeID.h"
#include "llvm/Support/RWMutex.h"
using namespace mlir;
using namespace mlir::detail;
namespace {
class ParametricStorageUniquer {
public:
using BaseStorage = StorageUniquer::BaseStorage;
using StorageAllocator = StorageUniquer::StorageAllocator;
struct LookupKey {
unsigned hashValue;
function_ref<bool(const BaseStorage *)> isEqual;
};
private:
struct HashedStorage {
HashedStorage(unsigned hashValue = 0, BaseStorage *storage = nullptr)
: hashValue(hashValue), storage(storage) {}
unsigned hashValue;
BaseStorage *storage;
};
struct StorageKeyInfo {
static inline HashedStorage getEmptyKey() {
return HashedStorage(0, DenseMapInfo<BaseStorage *>::getEmptyKey());
}
static inline HashedStorage getTombstoneKey() {
return HashedStorage(0, DenseMapInfo<BaseStorage *>::getTombstoneKey());
}
static inline unsigned getHashValue(const HashedStorage &key) {
return key.hashValue;
}
static inline unsigned getHashValue(const LookupKey &key) {
return key.hashValue;
}
static inline bool isEqual(const HashedStorage &lhs,
const HashedStorage &rhs) {
return lhs.storage == rhs.storage;
}
static inline bool isEqual(const LookupKey &lhs, const HashedStorage &rhs) {
if (isEqual(rhs, getEmptyKey()) || isEqual(rhs, getTombstoneKey()))
return false;
return lhs.isEqual(rhs.storage);
}
};
using StorageTypeSet = DenseSet<HashedStorage, StorageKeyInfo>;
struct Shard {
StorageTypeSet instances;
#if LLVM_ENABLE_THREADS != 0
llvm::sys::SmartRWMutex<true> mutex;
#endif
};
BaseStorage *getOrCreateUnsafe(Shard &shard, LookupKey &key,
function_ref<BaseStorage *()> ctorFn) {
auto existing = shard.instances.insert_as({key.hashValue}, key);
BaseStorage *&storage = existing.first->storage;
if (existing.second)
storage = ctorFn();
return storage;
}
void destroyShardInstances(Shard &shard) {
if (!destructorFn)
return;
for (HashedStorage &instance : shard.instances)
destructorFn(instance.storage);
}
public:
#if LLVM_ENABLE_THREADS != 0
ParametricStorageUniquer(function_ref<void(BaseStorage *)> destructorFn,
size_t numShards = 8)
: shards(new std::atomic<Shard *>[numShards]), numShards(numShards),
destructorFn(destructorFn) {
assert(llvm::isPowerOf2_64(numShards) &&
"the number of shards is required to be a power of 2");
for (size_t i = 0; i < numShards; i++)
shards[i].store(nullptr, std::memory_order_relaxed);
}
~ParametricStorageUniquer() {
for (size_t i = 0; i != numShards; ++i) {
if (Shard *shard = shards[i].load()) {
destroyShardInstances(*shard);
delete shard;
}
}
}
BaseStorage *getOrCreate(bool threadingIsEnabled, unsigned hashValue,
function_ref<bool(const BaseStorage *)> isEqual,
function_ref<BaseStorage *()> ctorFn) {
Shard &shard = getShard(hashValue);
ParametricStorageUniquer::LookupKey lookupKey{hashValue, isEqual};
if (!threadingIsEnabled)
return getOrCreateUnsafe(shard, lookupKey, ctorFn);
auto localIt = localCache->insert_as({hashValue}, lookupKey);
BaseStorage *&localInst = localIt.first->storage;
if (localInst)
return localInst;
{
llvm::sys::SmartScopedReader<true> typeLock(shard.mutex);
auto it = shard.instances.find_as(lookupKey);
if (it != shard.instances.end())
return localInst = it->storage;
}
llvm::sys::SmartScopedWriter<true> typeLock(shard.mutex);
return localInst = getOrCreateUnsafe(shard, lookupKey, ctorFn);
}
LogicalResult mutate(bool threadingIsEnabled, BaseStorage *storage,
function_ref<LogicalResult()> mutationFn) {
if (!threadingIsEnabled)
return mutationFn();
Shard &shard = getShard(llvm::hash_value(storage));
llvm::sys::SmartScopedWriter<true> lock(shard.mutex);
return mutationFn();
}
private:
Shard &getShard(unsigned hashValue) {
unsigned shardNum = hashValue & (numShards - 1);
Shard *shard = shards[shardNum].load(std::memory_order_acquire);
if (shard)
return *shard;
Shard *newShard = new Shard();
if (shards[shardNum].compare_exchange_strong(shard, newShard))
return *newShard;
delete newShard;
return *shard;
}
ThreadLocalCache<StorageTypeSet> localCache;
std::unique_ptr<std::atomic<Shard *>[]> shards;
size_t numShards;
function_ref<void(BaseStorage *)> destructorFn;
#else
ParametricStorageUniquer(function_ref<void(BaseStorage *)> destructorFn,
size_t numShards = 0)
: destructorFn(destructorFn) {}
~ParametricStorageUniquer() { destroyShardInstances(shard); }
BaseStorage *
getOrCreate(bool threadingIsEnabled, unsigned hashValue,
function_ref<bool(const BaseStorage *)> isEqual,
function_ref<BaseStorage *()> ctorFn) {
ParametricStorageUniquer::LookupKey lookupKey{hashValue, isEqual};
return getOrCreateUnsafe(shard, lookupKey, ctorFn);
}
LogicalResult
mutate(bool threadingIsEnabled, BaseStorage *storage,
function_ref<LogicalResult()> mutationFn) {
return mutationFn();
}
private:
Shard shard;
function_ref<void(BaseStorage *)> destructorFn;
#endif
};
}
namespace mlir {
namespace detail {
struct StorageUniquerImpl {
using BaseStorage = StorageUniquer::BaseStorage;
using StorageAllocator = StorageUniquer::StorageAllocator;
bool hasParametricStorage(TypeID id) { return parametricUniquers.count(id); }
BaseStorage *
getOrCreate(TypeID id, unsigned hashValue,
function_ref<bool(const BaseStorage *)> isEqual,
function_ref<BaseStorage *(StorageAllocator &)> ctorFn) {
assert(parametricUniquers.count(id) &&
"creating unregistered storage instance");
ParametricStorageUniquer &storageUniquer = *parametricUniquers[id];
return storageUniquer.getOrCreate(
threadingIsEnabled, hashValue, isEqual,
[&] { return ctorFn(getThreadSafeAllocator()); });
}
LogicalResult
mutate(TypeID id, BaseStorage *storage,
function_ref<LogicalResult(StorageAllocator &)> mutationFn) {
assert(parametricUniquers.count(id) &&
"mutating unregistered storage instance");
ParametricStorageUniquer &storageUniquer = *parametricUniquers[id];
return storageUniquer.mutate(threadingIsEnabled, storage, [&] {
return mutationFn(getThreadSafeAllocator());
});
}
StorageAllocator &getThreadSafeAllocator() {
#if LLVM_ENABLE_THREADS != 0
if (!threadingIsEnabled)
return allocator;
StorageAllocator *&threadAllocator = threadSafeAllocator.get();
if (!threadAllocator) {
threadAllocator = new StorageAllocator();
llvm::sys::SmartScopedLock<true> lock(threadAllocatorMutex);
threadAllocators.push_back(
std::unique_ptr<StorageAllocator>(threadAllocator));
}
return *threadAllocator;
#else
return allocator;
#endif
}
BaseStorage *getSingleton(TypeID id) {
BaseStorage *singletonInstance = singletonInstances[id];
assert(singletonInstance && "expected singleton instance to exist");
return singletonInstance;
}
bool hasSingleton(TypeID id) const { return singletonInstances.count(id); }
#if LLVM_ENABLE_THREADS != 0
ThreadLocalCache<StorageAllocator *> threadSafeAllocator;
std::vector<std::unique_ptr<StorageAllocator>> threadAllocators;
llvm::sys::SmartMutex<true> threadAllocatorMutex;
#endif
StorageAllocator allocator;
DenseMap<TypeID, std::unique_ptr<ParametricStorageUniquer>>
parametricUniquers;
DenseMap<TypeID, BaseStorage *> singletonInstances;
bool threadingIsEnabled = true;
};
}
}
StorageUniquer::StorageUniquer() : impl(new StorageUniquerImpl()) {}
StorageUniquer::~StorageUniquer() = default;
void StorageUniquer::disableMultithreading(bool disable) {
impl->threadingIsEnabled = !disable;
}
auto StorageUniquer::getParametricStorageTypeImpl(
TypeID id, unsigned hashValue,
function_ref<bool(const BaseStorage *)> isEqual,
function_ref<BaseStorage *(StorageAllocator &)> ctorFn) -> BaseStorage * {
return impl->getOrCreate(id, hashValue, isEqual, ctorFn);
}
void StorageUniquer::registerParametricStorageTypeImpl(
TypeID id, function_ref<void(BaseStorage *)> destructorFn) {
impl->parametricUniquers.try_emplace(
id, std::make_unique<ParametricStorageUniquer>(destructorFn));
}
auto StorageUniquer::getSingletonImpl(TypeID id) -> BaseStorage * {
return impl->getSingleton(id);
}
bool StorageUniquer::isSingletonStorageInitialized(TypeID id) {
return impl->hasSingleton(id);
}
bool StorageUniquer::isParametricStorageInitialized(TypeID id) {
return impl->hasParametricStorage(id);
}
void StorageUniquer::registerSingletonImpl(
TypeID id, function_ref<BaseStorage *(StorageAllocator &)> ctorFn) {
assert(!impl->singletonInstances.count(id) &&
"storage class already registered");
impl->singletonInstances.try_emplace(id, ctorFn(impl->allocator));
}
LogicalResult StorageUniquer::mutateImpl(
TypeID id, BaseStorage *storage,
function_ref<LogicalResult(StorageAllocator &)> mutationFn) {
return impl->mutate(id, storage, mutationFn);
}