Skip to content

Commit b96ebee

Browse files
authored
[mlir] Fix allocateAndCopyWithAlign for immutable (#108679)
Previously this would assert when attempting to getMutableData.
1 parent 089227f commit b96ebee

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

mlir/include/mlir/IR/AsmState.h

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,8 @@ class AsmStateImpl;
8282
//===----------------------------------------------------------------------===//
8383
// Resource Entry
8484

85+
class HeapAsmResourceBlob;
86+
8587
/// This class represents a processed binary blob of data. A resource blob is
8688
/// essentially a collection of data, potentially mutable, with an associated
8789
/// deleter function (used if the data needs to be destroyed).
@@ -177,6 +179,8 @@ class AsmResourceBlob {
177179

178180
/// Whether the data is mutable.
179181
bool dataIsMutable;
182+
183+
friend class HeapAsmResourceBlob;
180184
};
181185

182186
/// This class provides a simple utility wrapper for creating heap allocated
@@ -196,8 +200,11 @@ class HeapAsmResourceBlob {
196200
static AsmResourceBlob allocateAndCopyWithAlign(ArrayRef<char> data,
197201
size_t align,
198202
bool dataIsMutable = true) {
199-
AsmResourceBlob blob = allocate(data.size(), align, dataIsMutable);
203+
// This sets the blob to be mutable initially to allow writing
204+
// (getMutableData) below.
205+
AsmResourceBlob blob = allocate(data.size(), align, /*dataIsMutable=*/true);
200206
std::memcpy(blob.getMutableData().data(), data.data(), data.size());
207+
blob.dataIsMutable = dataIsMutable;
201208
return blob;
202209
}
203210
template <typename T>

mlir/unittests/IR/AttributeTest.cpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,21 @@ TEST(DenseResourceElementsAttrTest, CheckNoCast) {
351351
EXPECT_FALSE(isa<DenseBoolResourceElementsAttr>(i32ResourceAttr));
352352
}
353353

354+
TEST(DenseResourceElementsAttrTest, CheckNotMutableAllocateAndCopy) {
355+
MLIRContext context;
356+
Builder builder(&context);
357+
358+
// Create a i32 attribute.
359+
std::vector<int32_t> data = {10, 20, 30};
360+
auto type = RankedTensorType::get(data.size(), builder.getI32Type());
361+
Attribute i32ResourceAttr = DenseI32ResourceElementsAttr::get(
362+
type, "resource",
363+
HeapAsmResourceBlob::allocateAndCopyInferAlign<int32_t>(
364+
data, /*is_mutable=*/false));
365+
366+
EXPECT_TRUE(isa<DenseI32ResourceElementsAttr>(i32ResourceAttr));
367+
}
368+
354369
TEST(DenseResourceElementsAttrTest, CheckInvalidData) {
355370
MLIRContext context;
356371
Builder builder(&context);

0 commit comments

Comments
 (0)