1 //===- DialectResourceBlobManager.cpp - Dialect Blob Management -----------===//
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-exception
7 //===----------------------------------------------------------------------===//
9 #include "mlir/IR/DialectResourceBlobManager.h"
10 #include "llvm/ADT/SmallString.h"
15 //===----------------------------------------------------------------------===//
16 // DialectResourceBlobManager
17 //===---------------------------------------------------------------------===//
19 auto DialectResourceBlobManager::lookup(StringRef name
) -> BlobEntry
* {
20 llvm::sys::SmartScopedReader
<true> reader(blobMapLock
);
22 auto it
= blobMap
.find(name
);
23 return it
!= blobMap
.end() ? &it
->second
: nullptr;
26 void DialectResourceBlobManager::update(StringRef name
,
27 AsmResourceBlob
&&newBlob
) {
28 BlobEntry
*entry
= lookup(name
);
29 assert(entry
&& "`update` expects an existing entry for the provided name");
30 entry
->setBlob(std::move(newBlob
));
33 auto DialectResourceBlobManager::insert(StringRef name
,
34 std::optional
<AsmResourceBlob
> blob
)
36 llvm::sys::SmartScopedWriter
<true> writer(blobMapLock
);
38 // Functor used to attempt insertion with a given name.
39 auto tryInsertion
= [&](StringRef name
) -> BlobEntry
* {
40 auto it
= blobMap
.try_emplace(name
, BlobEntry());
42 it
.first
->second
.initialize(it
.first
->getKey(), std::move(blob
));
43 return &it
.first
->second
;
48 // Try inserting with the name provided by the user.
49 if (BlobEntry
*entry
= tryInsertion(name
))
52 // If an entry already exists for the user provided name, tweak the name and
53 // re-attempt insertion until we find one that is unique.
54 llvm::SmallString
<32> nameStorage(name
);
55 nameStorage
.push_back('_');
56 size_t nameCounter
= 1;
58 Twine(nameCounter
++).toVector(nameStorage
);
60 // Try inserting with the new name.
61 if (BlobEntry
*entry
= tryInsertion(nameStorage
))
63 nameStorage
.resize(name
.size() + 1);