4444#include < charconv>
4545#include < cstdlib>
4646#include < memory>
47+ #include < mutex>
4748#include < optional>
4849#include < system_error>
4950
@@ -504,32 +505,44 @@ llvm::StringRef getVarAnnotationIntrinsicName(const llvm::CallInst *CallInst) {
504505 return Data->getAsCString ();
505506}
506507
508+ struct PhasarModuleSlotTrackerWrapper {
509+ PhasarModuleSlotTrackerWrapper (const llvm::Module *M) : MST(M) {}
510+
511+ llvm::ModuleSlotTracker MST;
512+ size_t RefCount = 0 ;
513+ };
514+
507515static llvm::SmallDenseMap<const llvm::Module *,
508- std::unique_ptr<llvm::ModuleSlotTracker >, 2 >
516+ std::unique_ptr<PhasarModuleSlotTrackerWrapper >, 2 >
509517 MToST{};
510518
519+ static std::mutex MSTMx;
520+
511521llvm::ModuleSlotTracker &
512522ModulesToSlotTracker::getSlotTrackerForModule (const llvm::Module *M) {
523+ std::lock_guard Lck (MSTMx);
524+
513525 auto &Ret = MToST[M];
514526 if (M == nullptr && Ret == nullptr ) {
515- Ret = std::make_unique<llvm::ModuleSlotTracker>(M);
527+ Ret = std::make_unique<PhasarModuleSlotTrackerWrapper>(M);
528+ Ret->RefCount ++;
516529 }
517530 assert (Ret != nullptr && " no ModuleSlotTracker instance for module cached" );
518- return * Ret;
531+ return Ret-> MST ;
519532}
520533
521534void ModulesToSlotTracker::setMSTForModule (const llvm::Module *M) {
535+ std::lock_guard Lck (MSTMx);
536+
522537 auto [It, Inserted] = MToST.try_emplace (M, nullptr );
523- if (!Inserted) {
524- llvm::report_fatal_error (
525- " Cannot register the same module twice in the ModulesToSlotTracker! "
526- " Probably you have managed the same LLVM Module with multiple "
527- " ProjectIRDB instances at the same time. Don't do that!" );
538+ if (Inserted) {
539+ It->second = std::make_unique<PhasarModuleSlotTrackerWrapper>(M);
528540 }
529- It->second = std::make_unique<llvm::ModuleSlotTracker>(M) ;
541+ It->second -> RefCount ++ ;
530542}
531543
532544void ModulesToSlotTracker::updateMSTForModule (const llvm::Module *Module) {
545+ std::lock_guard Lck (MSTMx);
533546 auto It = MToST.find (Module);
534547 if (It == MToST.end ()) {
535548 llvm::report_fatal_error (
@@ -541,7 +554,16 @@ void ModulesToSlotTracker::updateMSTForModule(const llvm::Module *Module) {
541554}
542555
543556void ModulesToSlotTracker::deleteMSTForModule (const llvm::Module *M) {
544- MToST.erase (M);
557+ std::lock_guard Lck (MSTMx);
558+
559+ auto It = MToST.find (M);
560+ if (It == MToST.end ()) {
561+ return ;
562+ }
563+
564+ if (--It->second ->RefCount == 0 ) {
565+ MToST.erase (It);
566+ }
545567}
546568
547569} // namespace psr
0 commit comments