[Mlir-commits] [mlir] ad9dc60 - [mlir][IR][Rewrite] Use split inherent/discardable attribute APIs (#218907)

llvmlistbot at llvm.org llvmlistbot at llvm.org
Wed Aug 26 05:19:14 PDT 2026


Author: Mehdi Amini
Date: 2026-08-26T12:19:09Z
New Revision: ad9dc60252ed6c43fb0667dc0fad7df995651235

URL: https://github.com/llvm/llvm-project/commit/ad9dc60252ed6c43fb0667dc0fad7df995651235
DIFF: https://github.com/llvm/llvm-project/commit/ad9dc60252ed6c43fb0667dc0fad7df995651235.diff

LOG: [mlir][IR][Rewrite] Use split inherent/discardable attribute APIs (#218907)

Migrate core IR implementation, interfaces, rewriting, pass printing,
and focused tests to explicit discardable or inherent attribute access.

Assisted-by: Codex

Added: 
    

Modified: 
    mlir/lib/IR/AsmPrinter.cpp
    mlir/lib/IR/BuiltinDialect.cpp
    mlir/lib/IR/Operation.cpp
    mlir/lib/IR/OperationSupport.cpp
    mlir/lib/IR/PatternMatch.cpp
    mlir/lib/Interfaces/FunctionImplementation.cpp
    mlir/lib/Interfaces/Utils/MemorySlotUtils.cpp
    mlir/lib/Rewrite/ByteCode.cpp
    mlir/lib/Transforms/Utils/DialectConversion.cpp
    mlir/lib/Transforms/ViewOpGraph.cpp
    mlir/test/lib/IR/TestAffineWalk.cpp
    mlir/test/lib/IR/TestBuiltinAttributeInterfaces.cpp
    mlir/test/lib/IR/TestBuiltinDistinctAttributes.cpp
    mlir/test/lib/IR/TestDiagnostics.cpp
    mlir/test/lib/IR/TestDiagnosticsMetadata.cpp
    mlir/test/lib/IR/TestDominance.cpp
    mlir/test/lib/IR/TestFunc.cpp
    mlir/test/lib/IR/TestOperationEquals.cpp
    mlir/test/lib/IR/TestPrintNesting.cpp
    mlir/test/lib/IR/TestSymbolUses.cpp
    mlir/test/lib/IR/TestVisitors.cpp
    mlir/test/lib/IR/TestVisitorsGeneric.cpp
    mlir/test/lib/Transforms/TestControlFlowSink.cpp
    mlir/unittests/IR/BlobManagerTest.cpp
    mlir/unittests/IR/OpPropertiesTest.cpp
    mlir/unittests/IR/OperationSupportTest.cpp
    mlir/unittests/Interfaces/DataLayoutInterfacesTest.cpp
    mlir/unittests/Pass/PassManagerTest.cpp

Removed: 
    


################################################################################
diff  --git a/mlir/lib/IR/AsmPrinter.cpp b/mlir/lib/IR/AsmPrinter.cpp
index 4f3fb609189a0..f7e269867c9be 100644
--- a/mlir/lib/IR/AsmPrinter.cpp
+++ b/mlir/lib/IR/AsmPrinter.cpp
@@ -3858,9 +3858,7 @@ void OperationPrinter::printGenericOp(Operation *op, bool printOpName) {
     os << ')';
   }
 
-  printOptionalAttrDict(op->getPropertiesStorage()
-                            ? llvm::to_vector(op->getDiscardableAttrs())
-                            : op->getAttrs());
+  printOptionalAttrDict(op->getRawDictionaryAttrs().getValue());
 
   // Print the type signature of the operation.
   os << " : ";

diff  --git a/mlir/lib/IR/BuiltinDialect.cpp b/mlir/lib/IR/BuiltinDialect.cpp
index c88b328282275..f2a84134616e5 100644
--- a/mlir/lib/IR/BuiltinDialect.cpp
+++ b/mlir/lib/IR/BuiltinDialect.cpp
@@ -139,7 +139,8 @@ DataLayoutSpecInterface ModuleOp::getDataLayoutSpec() {
   // Take the first and only (if present) attribute that implements the
   // interface. This needs a linear search, but is called only once per data
   // layout object construction that is used for repeated queries.
-  for (NamedAttribute attr : getOperation()->getAttrs())
+  for (NamedAttribute attr :
+       getOperation()->getDiscardableAttrDictionary().getValue())
     if (auto spec = llvm::dyn_cast<DataLayoutSpecInterface>(attr.getValue()))
       return spec;
   return {};
@@ -149,7 +150,8 @@ TargetSystemSpecInterface ModuleOp::getTargetSystemSpec() {
   // Take the first and only (if present) attribute that implements the
   // interface. This needs a linear search, but is called only once per data
   // layout object construction that is used for repeated queries.
-  for (NamedAttribute attr : getOperation()->getAttrs())
+  for (NamedAttribute attr :
+       getOperation()->getDiscardableAttrDictionary().getValue())
     if (auto spec = llvm::dyn_cast<TargetSystemSpecInterface>(attr.getValue()))
       return spec;
   return {};
@@ -158,7 +160,7 @@ TargetSystemSpecInterface ModuleOp::getTargetSystemSpec() {
 LogicalResult ModuleOp::verify() {
   // Check that none of the attributes are non-dialect attributes, except for
   // the symbol related attributes.
-  for (auto attr : (*this)->getAttrs()) {
+  for (auto attr : (*this)->getDiscardableAttrDictionary().getValue()) {
     if (!attr.getName().strref().contains('.') &&
         !llvm::is_contained(
             ArrayRef<StringRef>{mlir::SymbolTable::getSymbolAttrName(),
@@ -172,7 +174,8 @@ LogicalResult ModuleOp::verify() {
   // Check that there is at most one data layout spec attribute.
   StringRef layoutSpecAttrName;
   DataLayoutSpecInterface layoutSpec;
-  for (const NamedAttribute &na : (*this)->getAttrs()) {
+  for (const NamedAttribute &na :
+       (*this)->getDiscardableAttrDictionary().getValue()) {
     if (auto spec = llvm::dyn_cast<DataLayoutSpecInterface>(na.getValue())) {
       if (layoutSpec) {
         InFlightDiagnostic diag =

diff  --git a/mlir/lib/IR/Operation.cpp b/mlir/lib/IR/Operation.cpp
index ee93b97dc2508..d262e844603a1 100644
--- a/mlir/lib/IR/Operation.cpp
+++ b/mlir/lib/IR/Operation.cpp
@@ -1270,7 +1270,8 @@ LogicalResult OpTrait::impl::verifyValueSizeAttr(Operation *op,
                                                  StringRef attrName,
                                                  StringRef valueGroupName,
                                                  size_t expectedCount) {
-  auto sizeAttr = op->getAttrOfType<DenseI32ArrayAttr>(attrName);
+  auto sizeAttr = dyn_cast_or_null<DenseI32ArrayAttr>(
+      op->getInherentAttr(attrName).value_or(Attribute{}));
   if (!sizeAttr)
     return op->emitOpError("requires dense i32 array attribute '")
            << attrName << "'";

diff  --git a/mlir/lib/IR/OperationSupport.cpp b/mlir/lib/IR/OperationSupport.cpp
index 32c6426429ae8..4ecb73398aa77 100644
--- a/mlir/lib/IR/OperationSupport.cpp
+++ b/mlir/lib/IR/OperationSupport.cpp
@@ -523,7 +523,7 @@ void MutableOperandRange::updateLength(unsigned newLength) {
     segments[segment.first] += 
diff ;
     segment.second.setValue(
         DenseI32ArrayAttr::get(attr.getContext(), segments));
-    owner->setAttr(segment.second.getName(), segment.second.getValue());
+    owner->setInherentAttr(segment.second.getName(), segment.second.getValue());
   }
 }
 

diff  --git a/mlir/lib/IR/PatternMatch.cpp b/mlir/lib/IR/PatternMatch.cpp
index cd067f2cc25b3..0b080d2920230 100644
--- a/mlir/lib/IR/PatternMatch.cpp
+++ b/mlir/lib/IR/PatternMatch.cpp
@@ -260,7 +260,9 @@ Operation *RewriterBase::eraseOpResults(Operation *op,
   InsertionGuard g(*this);
   setInsertionPoint(op);
   OperationState state(op->getLoc(), op->getName().getStringRef(),
-                       op->getOperands(), newResultTypes, op->getAttrs());
+                       op->getOperands(), newResultTypes,
+                       op->getDiscardableAttrDictionary().getValue());
+  state.propertiesAttr = op->getPropertiesAsAttribute();
   for ([[maybe_unused]] auto i : llvm::seq<unsigned>(0, op->getNumRegions()))
     state.addRegion();
   Operation *newOp = create(state);

diff  --git a/mlir/lib/Interfaces/FunctionImplementation.cpp b/mlir/lib/Interfaces/FunctionImplementation.cpp
index 90f32896e8181..d40d5e6230cf7 100644
--- a/mlir/lib/Interfaces/FunctionImplementation.cpp
+++ b/mlir/lib/Interfaces/FunctionImplementation.cpp
@@ -169,7 +169,10 @@ void function_interface_impl::printFunctionAttributes(
   SmallVector<StringRef, 8> ignoredAttrs = {SymbolTable::getSymbolAttrName()};
   ignoredAttrs.append(elided.begin(), elided.end());
 
-  p.printOptionalAttrDictWithKeyword(op->getAttrs(), ignoredAttrs);
+  NamedAttrList attrs(op->getDiscardableAttrDictionary().getValue());
+  op->getName().walkInherentAttrs(
+      op, [&](StringRef name, Attribute &attr) { attrs.append(name, attr); });
+  p.printOptionalAttrDictWithKeyword(attrs, ignoredAttrs);
 }
 
 void function_interface_impl::printFunctionOp(

diff  --git a/mlir/lib/Interfaces/Utils/MemorySlotUtils.cpp b/mlir/lib/Interfaces/Utils/MemorySlotUtils.cpp
index c497970b8b188..9beadc1a13c4a 100644
--- a/mlir/lib/Interfaces/Utils/MemorySlotUtils.cpp
+++ b/mlir/lib/Interfaces/Utils/MemorySlotUtils.cpp
@@ -31,7 +31,8 @@ Operation *mlir::memoryslot::replaceWithNewResults(RewriterBase &rewriter,
   RewriterBase::InsertionGuard guard(rewriter);
   rewriter.setInsertionPoint(op);
   OperationState state(op->getLoc(), op->getName(), op->getOperands(),
-                       resultTypes, op->getAttrs());
+                       resultTypes,
+                       op->getDiscardableAttrDictionary().getValue());
   state.propertiesAttr = op->getPropertiesAsAttribute();
   unsigned numRegions = op->getNumRegions();
   for (unsigned i = 0; i < numRegions; ++i)

diff  --git a/mlir/lib/Rewrite/ByteCode.cpp b/mlir/lib/Rewrite/ByteCode.cpp
index 2daf2635d96d5..d6239c7ba82d8 100644
--- a/mlir/lib/Rewrite/ByteCode.cpp
+++ b/mlir/lib/Rewrite/ByteCode.cpp
@@ -1788,7 +1788,9 @@ void ByteCodeExecutor::executeGetAttribute() {
   unsigned memIndex = read();
   Operation *op = read<Operation *>();
   StringAttr attrName = read<StringAttr>();
-  Attribute attr = op->getAttr(attrName);
+  Attribute attr = op->getDiscardableAttr(attrName);
+  if (op->getPropertiesStorageSize())
+    attr = op->getInherentAttr(attrName).value_or(attr);
 
   LDBG() << "  * Operation: " << *op << "\n  * Attribute: " << attrName
          << "\n  * Result: " << attr;
@@ -1857,7 +1859,8 @@ executeGetOperandsResults(RangeT values, Operation *op, unsigned index,
   } else if (op->hasTrait<AttrSizedSegmentsT>()) {
     LDBG() << "  * Extracting values from `" << attrSizedSegments << "`";
 
-    auto segmentAttr = op->getAttrOfType<DenseI32ArrayAttr>(attrSizedSegments);
+    auto segmentAttr = dyn_cast_or_null<DenseI32ArrayAttr>(
+        op->getInherentAttr(attrSizedSegments).value_or(Attribute{}));
     if (!segmentAttr || segmentAttr.asArrayRef().size() <= index)
       return nullptr;
 

diff  --git a/mlir/lib/Transforms/Utils/DialectConversion.cpp b/mlir/lib/Transforms/Utils/DialectConversion.cpp
index 75d5620f0f298..507f0650169ca 100644
--- a/mlir/lib/Transforms/Utils/DialectConversion.cpp
+++ b/mlir/lib/Transforms/Utils/DialectConversion.cpp
@@ -217,7 +217,7 @@ static Operation *getCommonDefiningOp(const ValueVector &values) {
 static bool isPureTypeConversion(const ValueVector &values) {
   assert(!values.empty() && "expected non-empty value vector");
   Operation *op = getCommonDefiningOp(values);
-  return op && op->hasAttr(kPureTypeConversionMarker);
+  return op && op->hasDiscardableAttr(kPureTypeConversionMarker);
 }
 
 ValueVector ConversionValueMapping::lookup(const ValueVector &from) const {
@@ -683,7 +683,8 @@ class ModifyOperationRewrite : public OperationRewrite {
   ModifyOperationRewrite(ConversionPatternRewriterImpl &rewriterImpl,
                          Operation *op)
       : OperationRewrite(Kind::ModifyOperation, rewriterImpl, op),
-        name(op->getName()), loc(op->getLoc()), attrs(op->getAttrDictionary()),
+        name(op->getName()), loc(op->getLoc()),
+        attrs(op->getDiscardableAttrDictionary()),
         operands(op->operand_begin(), op->operand_end()),
         successors(op->successor_begin(), op->successor_end()) {
     if (PropertyRef prop = op->getPropertiesStorage()) {
@@ -721,7 +722,7 @@ class ModifyOperationRewrite : public OperationRewrite {
 
   void rollback() override {
     op->setLoc(loc);
-    op->setAttrs(attrs);
+    op->setDiscardableAttrs(attrs);
     op->setOperands(operands);
     for (const auto &it : llvm::enumerate(successors))
       op->setSuccessor(it.value(), it.index());
@@ -1723,10 +1724,11 @@ ValueRange ConversionPatternRewriterImpl::buildUnresolvedMaterialization(
   if (config.attachDebugMaterializationKind) {
     StringRef kindStr =
         kind == MaterializationKind::Source ? "source" : "target";
-    convertOp->setAttr("__kind__", builder.getStringAttr(kindStr));
+    convertOp->setDiscardableAttr("__kind__", builder.getStringAttr(kindStr));
   }
   if (isPureTypeConversion)
-    convertOp->setAttr(kPureTypeConversionMarker, builder.getUnitAttr());
+    convertOp->setDiscardableAttr(kPureTypeConversionMarker,
+                                  builder.getUnitAttr());
 
   // Register the materialization.
   unresolvedMaterializations[convertOp] =
@@ -3503,7 +3505,7 @@ LogicalResult OperationConverter::applyConversion(ArrayRef<Operation *> ops) {
 
   // Drop markers.
   for (UnrealizedConversionCastOp castOp : remainingCastOps)
-    castOp->removeAttr(kPureTypeConversionMarker);
+    castOp->removeDiscardableAttr(kPureTypeConversionMarker);
 
   // Try to legalize all unresolved materializations.
   if (rewriter.getConfig().buildMaterializations) {
@@ -3947,7 +3949,8 @@ mlir::convertOpResultTypes(Operation *op, ValueRange operands,
     return rewriter.notifyMatchFailure(loc, "couldn't convert return types");
 
   newOp.addTypes(newResultTypes);
-  newOp.addAttributes(op->getAttrs());
+  newOp.addAttributes(op->getDiscardableAttrDictionary().getValue());
+  newOp.propertiesAttr = op->getPropertiesAsAttribute();
   return rewriter.create(newOp);
 }
 

diff  --git a/mlir/lib/Transforms/ViewOpGraph.cpp b/mlir/lib/Transforms/ViewOpGraph.cpp
index 2d7e40d18efca..7b786f4936358 100644
--- a/mlir/lib/Transforms/ViewOpGraph.cpp
+++ b/mlir/lib/Transforms/ViewOpGraph.cpp
@@ -316,7 +316,11 @@ class PrintOpPass : public impl::ViewOpGraphPassBase<PrintOpPass> {
       // Print attributes.
       if (printAttrs) {
         os << "\\l";
-        for (const NamedAttribute &attr : op->getAttrs()) {
+        NamedAttrList attrs(op->getDiscardableAttrDictionary());
+        op->getName().walkInherentAttrs(
+            op,
+            [&](StringRef name, Attribute &attr) { attrs.append(name, attr); });
+        for (const NamedAttribute &attr : attrs) {
           os << escapeLabelString(attr.getName().getValue().str()) << ": ";
           emitMlirAttr(os, attr.getValue());
           os << "\\l";
@@ -344,10 +348,14 @@ class PrintOpPass : public impl::ViewOpGraphPassBase<PrintOpPass> {
       os << op->getName() << "\\l";
 
       // Print attributes.
-      if (printAttrs && !op->getAttrs().empty()) {
+      NamedAttrList attrs(op->getDiscardableAttrDictionary());
+      op->getName().walkInherentAttrs(op, [&](StringRef name, Attribute &attr) {
+        attrs.append(name, attr);
+      });
+      if (printAttrs && !attrs.empty()) {
         // Extra line break to separate attributes from the operation name.
         os << "\\l";
-        for (const NamedAttribute &attr : op->getAttrs()) {
+        for (const NamedAttribute &attr : attrs) {
           os << attr.getName().getValue() << ": ";
           emitMlirAttr(os, attr.getValue());
           os << "\\l";

diff  --git a/mlir/test/lib/IR/TestAffineWalk.cpp b/mlir/test/lib/IR/TestAffineWalk.cpp
index e8b836888b459..68806567ad9bb 100644
--- a/mlir/test/lib/IR/TestAffineWalk.cpp
+++ b/mlir/test/lib/IR/TestAffineWalk.cpp
@@ -43,7 +43,7 @@ void TestAffineWalk::runOnOperation() {
   auto m = getOperation();
   // Test whether the walk is being correctly interrupted.
   m.walk([](Operation *op) {
-    for (NamedAttribute attr : op->getAttrs()) {
+    for (NamedAttribute attr : op->getDiscardableAttrDictionary().getValue()) {
       auto mapAttr = dyn_cast<AffineMapAttr>(attr.getValue());
       if (!mapAttr)
         return;

diff  --git a/mlir/test/lib/IR/TestBuiltinAttributeInterfaces.cpp b/mlir/test/lib/IR/TestBuiltinAttributeInterfaces.cpp
index f44b78673ec5f..d055642bc550a 100644
--- a/mlir/test/lib/IR/TestBuiltinAttributeInterfaces.cpp
+++ b/mlir/test/lib/IR/TestBuiltinAttributeInterfaces.cpp
@@ -35,7 +35,12 @@ struct TestElementsAttrInterface
   }
   void runOnOperation() override {
     getOperation().walk([&](Operation *op) {
-      for (NamedAttribute attr : op->getAttrs()) {
+      NamedAttrList attrs(op->getDiscardableAttrDictionary());
+      if (op->getPropertiesStorageSize())
+        op->getName().walkInherentAttrs(
+            op,
+            [&](StringRef name, Attribute &attr) { attrs.append(name, attr); });
+      for (NamedAttribute attr : attrs) {
         auto elementsAttr = dyn_cast<ElementsAttr>(attr.getValue());
         if (!elementsAttr)
           continue;

diff  --git a/mlir/test/lib/IR/TestBuiltinDistinctAttributes.cpp b/mlir/test/lib/IR/TestBuiltinDistinctAttributes.cpp
index 4717ce345fc1f..924a8a91e3903 100644
--- a/mlir/test/lib/IR/TestBuiltinDistinctAttributes.cpp
+++ b/mlir/test/lib/IR/TestBuiltinDistinctAttributes.cpp
@@ -30,11 +30,13 @@ struct DistinctAttributesPass
     /// Walk all operations and create a distinct output attribute given a
     /// distinct input attribute.
     funcOp->walk([](Operation *op) {
-      auto distinctAttr = op->getAttrOfType<DistinctAttr>("distinct.input");
+      auto distinctAttr =
+          op->getDiscardableAttrOfType<DistinctAttr>("distinct.input");
       if (!distinctAttr)
         return;
-      op->setAttr("distinct.output",
-                  DistinctAttr::create(distinctAttr.getReferencedAttr()));
+      op->setDiscardableAttr(
+          "distinct.output",
+          DistinctAttr::create(distinctAttr.getReferencedAttr()));
     });
   }
 };

diff  --git a/mlir/test/lib/IR/TestDiagnostics.cpp b/mlir/test/lib/IR/TestDiagnostics.cpp
index 578486c0a3b14..38126b48ea90f 100644
--- a/mlir/test/lib/IR/TestDiagnostics.cpp
+++ b/mlir/test/lib/IR/TestDiagnostics.cpp
@@ -51,7 +51,8 @@ struct TestDiagnosticFilterPass
 
     // Emit a diagnostic for every operation with a valid loc.
     getOperation()->walk([&](Operation *op) {
-      if (LocationAttr locAttr = op->getAttrOfType<LocationAttr>("test.loc"))
+      if (LocationAttr locAttr =
+              op->getDiscardableAttrOfType<LocationAttr>("test.loc"))
         emitError(locAttr, "test diagnostic");
     });
   }

diff  --git a/mlir/test/lib/IR/TestDiagnosticsMetadata.cpp b/mlir/test/lib/IR/TestDiagnosticsMetadata.cpp
index 5cb0193baa171..07dc9cb430128 100644
--- a/mlir/test/lib/IR/TestDiagnosticsMetadata.cpp
+++ b/mlir/test/lib/IR/TestDiagnosticsMetadata.cpp
@@ -43,7 +43,8 @@ struct TestDiagnosticMetadataPass
 
     // Emit a diagnostic for every operation with a valid loc.
     getOperation()->walk([&](Operation *op) {
-      if (StringAttr strAttr = op->getAttrOfType<StringAttr>("attr")) {
+      if (StringAttr strAttr =
+              op->getDiscardableAttrOfType<StringAttr>("attr")) {
         if (strAttr.getValue() == "emit_error")
           emitError(op->getLoc(), "test diagnostic metadata")
               .getUnderlyingDiagnostic()

diff  --git a/mlir/test/lib/IR/TestDominance.cpp b/mlir/test/lib/IR/TestDominance.cpp
index b34149b3e2cbd..60d37476b5bf9 100644
--- a/mlir/test/lib/IR/TestDominance.cpp
+++ b/mlir/test/lib/IR/TestDominance.cpp
@@ -51,12 +51,13 @@ class DominanceTest {
 
     // Helper function that annotates the IR with block IDs.
     auto annotateBlockId = [&](Operation *op, int64_t blockId) {
-      auto idAttr = op->getAttrOfType<DenseI64ArrayAttr>(kBlockIdsAttrName);
+      auto idAttr =
+          op->getDiscardableAttrOfType<DenseI64ArrayAttr>(kBlockIdsAttrName);
       SmallVector<int64_t> ids;
       if (idAttr)
         ids = llvm::to_vector(idAttr.asArrayRef());
       ids.push_back(blockId);
-      op->setAttr(kBlockIdsAttrName, b.getDenseI64ArrayAttr(ids));
+      op->setDiscardableAttr(kBlockIdsAttrName, b.getDenseI64ArrayAttr(ids));
     };
 
     // Create unique IDs for each block.

diff  --git a/mlir/test/lib/IR/TestFunc.cpp b/mlir/test/lib/IR/TestFunc.cpp
index 2d4050d3484d0..7597f06db42f5 100644
--- a/mlir/test/lib/IR/TestFunc.cpp
+++ b/mlir/test/lib/IR/TestFunc.cpp
@@ -26,7 +26,8 @@ struct TestFuncInsertArg
 
     UnknownLoc unknownLoc = UnknownLoc::get(module.getContext());
     for (auto func : module.getOps<FunctionOpInterface>()) {
-      auto inserts = func->getAttrOfType<ArrayAttr>("test.insert_args");
+      auto inserts =
+          func->getDiscardableAttrOfType<ArrayAttr>("test.insert_args");
       if (!inserts || inserts.empty())
         continue;
       SmallVector<unsigned, 4> indicesToInsert;
@@ -44,7 +45,7 @@ struct TestFuncInsertArg
                                    ? Location(cast<LocationAttr>(insert[3]))
                                    : unknownLoc);
       }
-      func->removeAttr("test.insert_args");
+      func->removeDiscardableAttr("test.insert_args");
       if (succeeded(func.insertArguments(indicesToInsert, typesToInsert,
                                          attrsToInsert, locsToInsert)))
         continue;
@@ -68,7 +69,8 @@ struct TestFuncInsertResult
     auto module = getOperation();
 
     for (auto func : module.getOps<FunctionOpInterface>()) {
-      auto inserts = func->getAttrOfType<ArrayAttr>("test.insert_results");
+      auto inserts =
+          func->getDiscardableAttrOfType<ArrayAttr>("test.insert_results");
       if (!inserts || inserts.empty())
         continue;
       SmallVector<unsigned, 4> indicesToInsert;
@@ -82,7 +84,7 @@ struct TestFuncInsertResult
                                     ? cast<DictionaryAttr>(insert[2])
                                     : DictionaryAttr::get(&getContext()));
       }
-      func->removeAttr("test.insert_results");
+      func->removeDiscardableAttr("test.insert_results");
       if (succeeded(func.insertResults(indicesToInsert, typesToInsert,
                                        attrsToInsert)))
         continue;
@@ -166,7 +168,8 @@ struct TestFuncSetType
     SymbolTable symbolTable(module);
 
     for (auto func : module.getOps<FunctionOpInterface>()) {
-      auto sym = func->getAttrOfType<FlatSymbolRefAttr>("test.set_type_from");
+      auto sym = func->getDiscardableAttrOfType<FlatSymbolRefAttr>(
+          "test.set_type_from");
       if (!sym)
         continue;
       func.setType(symbolTable.lookup<FunctionOpInterface>(sym.getValue())

diff  --git a/mlir/test/lib/IR/TestOperationEquals.cpp b/mlir/test/lib/IR/TestOperationEquals.cpp
index 7cef2e5bd4bfe..6e765e58b1f26 100644
--- a/mlir/test/lib/IR/TestOperationEquals.cpp
+++ b/mlir/test/lib/IR/TestOperationEquals.cpp
@@ -23,7 +23,7 @@ struct TestOperationEqualPass
     ModuleOp module = getOperation();
     // Expects two operations at the top-level:
     int opCount = module.getBody()->getOperations().size();
-    if (module->hasAttr("test.includes_setup")) {
+    if (module->hasDiscardableAttr("test.includes_setup")) {
       if (opCount < 2) {
         module.emitError()
             << "expected at least 2 top-level ops in the module, got "
@@ -41,9 +41,9 @@ struct TestOperationEqualPass
     llvm::outs() << first->getName().getStringRef() << " with attr "
                  << first->getDiscardableAttrDictionary();
     OperationEquivalence::Flags flags{};
-    if (!first->hasAttr("strict_loc_check"))
+    if (!first->hasDiscardableAttr("strict_loc_check"))
       flags |= OperationEquivalence::IgnoreLocations;
-    if (first->hasAttr("ignore_commutativity"))
+    if (first->hasDiscardableAttr("ignore_commutativity"))
       flags |= OperationEquivalence::IgnoreCommutativity;
     if (OperationEquivalence::isEquivalentTo(first, &module.getBody()->back(),
                                              flags))

diff  --git a/mlir/test/lib/IR/TestPrintNesting.cpp b/mlir/test/lib/IR/TestPrintNesting.cpp
index c66149b33371d..b1e878964c49c 100644
--- a/mlir/test/lib/IR/TestPrintNesting.cpp
+++ b/mlir/test/lib/IR/TestPrintNesting.cpp
@@ -35,9 +35,10 @@ struct TestPrintNestingPass
                   << op->getNumOperands() << " operands and "
                   << op->getNumResults() << " results\n";
     // Print the operation attributes
-    if (!op->getAttrs().empty()) {
-      printIndent() << op->getAttrs().size() << " attributes:\n";
-      for (NamedAttribute attr : op->getAttrs())
+    if (!op->getDiscardableAttrDictionary().getValue().empty()) {
+      printIndent() << op->getDiscardableAttrDictionary().getValue().size()
+                    << " attributes:\n";
+      for (NamedAttribute attr : op->getDiscardableAttrDictionary().getValue())
         printIndent() << " - '" << attr.getName().getValue() << "' : '"
                       << attr.getValue() << "'\n";
     }

diff  --git a/mlir/test/lib/IR/TestSymbolUses.cpp b/mlir/test/lib/IR/TestSymbolUses.cpp
index 6aac9bfc8baa4..e8170b8531d1d 100644
--- a/mlir/test/lib/IR/TestSymbolUses.cpp
+++ b/mlir/test/lib/IR/TestSymbolUses.cpp
@@ -118,7 +118,8 @@ struct SymbolReplacementPass
     SymbolTableCollection symbolTable;
     SymbolUserMap symbolUsers(symbolTable, module);
     module.getBodyRegion().walk([&](Operation *nestedOp) {
-      StringAttr newName = nestedOp->getAttrOfType<StringAttr>("sym.new_name");
+      StringAttr newName =
+          nestedOp->getDiscardableAttrOfType<StringAttr>("sym.new_name");
       if (!newName)
         return;
       symbolUsers.replaceAllUsesWith(nestedOp, newName);

diff  --git a/mlir/test/lib/IR/TestVisitors.cpp b/mlir/test/lib/IR/TestVisitors.cpp
index 148a57f2a739b..603ee12a1aa46 100644
--- a/mlir/test/lib/IR/TestVisitors.cpp
+++ b/mlir/test/lib/IR/TestVisitors.cpp
@@ -251,7 +251,7 @@ static void testBlockAndRegionWalkers(Operation *op) {
 
   llvm::outs() << "Invoke block pre-order visits on blocks\n";
   op->walk([&](Operation *op) {
-    if (!op->hasAttr("walk_blocks"))
+    if (!op->hasDiscardableAttr("walk_blocks"))
       return;
     for (Region &region : op->getRegions()) {
       for (Block &block : region.getBlocks()) {
@@ -262,7 +262,7 @@ static void testBlockAndRegionWalkers(Operation *op) {
 
   llvm::outs() << "Invoke block post-order visits on blocks\n";
   op->walk([&](Operation *op) {
-    if (!op->hasAttr("walk_blocks"))
+    if (!op->hasDiscardableAttr("walk_blocks"))
       return;
     for (Region &region : op->getRegions()) {
       for (Block &block : region.getBlocks()) {
@@ -273,7 +273,7 @@ static void testBlockAndRegionWalkers(Operation *op) {
 
   llvm::outs() << "Invoke region pre-order visits on region\n";
   op->walk([&](Operation *op) {
-    if (!op->hasAttr("walk_regions"))
+    if (!op->hasDiscardableAttr("walk_regions"))
       return;
     for (Region &region : op->getRegions()) {
       region.walk<WalkOrder::PreOrder>(regionPure);
@@ -282,7 +282,7 @@ static void testBlockAndRegionWalkers(Operation *op) {
 
   llvm::outs() << "Invoke region post-order visits on region\n";
   op->walk([&](Operation *op) {
-    if (!op->hasAttr("walk_regions"))
+    if (!op->hasDiscardableAttr("walk_regions"))
       return;
     for (Region &region : op->getRegions()) {
       region.walk<WalkOrder::PostOrder>(regionPure);

diff  --git a/mlir/test/lib/IR/TestVisitorsGeneric.cpp b/mlir/test/lib/IR/TestVisitorsGeneric.cpp
index 4556671df0ba0..20193bd71a6f5 100644
--- a/mlir/test/lib/IR/TestVisitorsGeneric.cpp
+++ b/mlir/test/lib/IR/TestVisitorsGeneric.cpp
@@ -64,31 +64,33 @@ struct TestGenericIRVisitorInterruptPass
 
     auto walker = [&](Operation *op, const WalkStage &stage) {
       if (auto interruptBeforeAall =
-              op->getAttrOfType<BoolAttr>("interrupt_before_all"))
+              op->getDiscardableAttrOfType<BoolAttr>("interrupt_before_all"))
         if (interruptBeforeAall.getValue() && stage.isBeforeAllRegions())
           return WalkResult::interrupt();
 
       if (auto interruptAfterAll =
-              op->getAttrOfType<BoolAttr>("interrupt_after_all"))
+              op->getDiscardableAttrOfType<BoolAttr>("interrupt_after_all"))
         if (interruptAfterAll.getValue() && stage.isAfterAllRegions())
           return WalkResult::interrupt();
 
-      if (auto interruptAfterRegion =
-              op->getAttrOfType<IntegerAttr>("interrupt_after_region"))
+      if (auto interruptAfterRegion = op->getDiscardableAttrOfType<IntegerAttr>(
+              "interrupt_after_region"))
         if (stage.isAfterRegion(
                 static_cast<int>(interruptAfterRegion.getInt())))
           return WalkResult::interrupt();
 
-      if (auto skipBeforeAall = op->getAttrOfType<BoolAttr>("skip_before_all"))
+      if (auto skipBeforeAall =
+              op->getDiscardableAttrOfType<BoolAttr>("skip_before_all"))
         if (skipBeforeAall.getValue() && stage.isBeforeAllRegions())
           return WalkResult::skip();
 
-      if (auto skipAfterAll = op->getAttrOfType<BoolAttr>("skip_after_all"))
+      if (auto skipAfterAll =
+              op->getDiscardableAttrOfType<BoolAttr>("skip_after_all"))
         if (skipAfterAll.getValue() && stage.isAfterAllRegions())
           return WalkResult::skip();
 
       if (auto skipAfterRegion =
-              op->getAttrOfType<IntegerAttr>("skip_after_region"))
+              op->getDiscardableAttrOfType<IntegerAttr>("skip_after_region"))
         if (stage.isAfterRegion(static_cast<int>(skipAfterRegion.getInt())))
           return WalkResult::skip();
 
@@ -131,7 +133,7 @@ struct TestGenericIRBlockVisitorInterruptPass
 
     auto walker = [&](Block *block) {
       for (Operation &op : *block)
-        if (op.getAttrOfType<BoolAttr>("interrupt"))
+        if (op.getDiscardableAttrOfType<BoolAttr>("interrupt"))
           return WalkResult::interrupt();
 
       llvm::outs() << "step " << stepNo++ << "\n";
@@ -162,7 +164,7 @@ struct TestGenericIRRegionVisitorInterruptPass
 
     auto walker = [&](Region *region) {
       for (Operation &op : region->getOps())
-        if (op.getAttrOfType<BoolAttr>("interrupt"))
+        if (op.getDiscardableAttrOfType<BoolAttr>("interrupt"))
           return WalkResult::interrupt();
 
       llvm::outs() << "step " << stepNo++ << "\n";

diff  --git a/mlir/test/lib/Transforms/TestControlFlowSink.cpp b/mlir/test/lib/Transforms/TestControlFlowSink.cpp
index ad34b6c2ffdf8..7e4decabb0832 100644
--- a/mlir/test/lib/Transforms/TestControlFlowSink.cpp
+++ b/mlir/test/lib/Transforms/TestControlFlowSink.cpp
@@ -43,8 +43,8 @@ struct TestControlFlowSinkPass
     auto moveIntoRegion = [](Operation *op, Region *region) {
       Block &entry = region->front();
       op->moveBefore(&entry, entry.begin());
-      op->setAttr("was_sunk",
-                  Builder(op).getI32IntegerAttr(region->getRegionNumber()));
+      op->setDiscardableAttr(
+          "was_sunk", Builder(op).getI32IntegerAttr(region->getRegionNumber()));
     };
 
     getOperation()->walk([&](Operation *op) {

diff  --git a/mlir/unittests/IR/BlobManagerTest.cpp b/mlir/unittests/IR/BlobManagerTest.cpp
index d82482ddb7936..b32dc5a59bac4 100644
--- a/mlir/unittests/IR/BlobManagerTest.cpp
+++ b/mlir/unittests/IR/BlobManagerTest.cpp
@@ -49,7 +49,8 @@ TEST(DialectResourceBlobManagerTest, GetBlobMap) {
 
   Block *block = m->getBody();
   auto &op = block->getOperations().front();
-  auto resourceAttr = op.getAttrOfType<DenseResourceElementsAttr>("attr");
+  auto resourceAttr =
+      op.getDiscardableAttrOfType<DenseResourceElementsAttr>("attr");
   ASSERT_NE(resourceAttr, nullptr);
 
   const auto &dialectManager =

diff  --git a/mlir/unittests/IR/OpPropertiesTest.cpp b/mlir/unittests/IR/OpPropertiesTest.cpp
index 492b7a345e394..ba966bfdc28ca 100644
--- a/mlir/unittests/IR/OpPropertiesTest.cpp
+++ b/mlir/unittests/IR/OpPropertiesTest.cpp
@@ -393,11 +393,15 @@ TEST(OpPropertiesTest, withoutPropertiesDiscardableAttrs) {
   ParserConfig config(&context);
   OwningOpRef<Operation *> op =
       parseSourceString(withoutPropertiesAttrsSrc, config);
-  ASSERT_EQ(llvm::range_size(op->getDiscardableAttrs()), 1u);
-  EXPECT_EQ(op->getDiscardableAttrs().begin()->getName().getValue(),
+  ASSERT_EQ(llvm::range_size(op->getDiscardableAttrDictionary().getValue()),
+            1u);
+  EXPECT_EQ(op->getDiscardableAttrDictionary()
+                .getValue()
+                .begin()
+                ->getName()
+                .getValue(),
             "other_attr");
 
-  EXPECT_EQ(op->getAttrs().size(), 2u);
   EXPECT_EQ(op->getInherentAttr("inherent_attr"), std::nullopt);
   EXPECT_NE(op->getDiscardableAttr("inherent_attr"), Attribute());
   EXPECT_NE(op->getDiscardableAttr("other_attr"), Attribute());

diff  --git a/mlir/unittests/IR/OperationSupportTest.cpp b/mlir/unittests/IR/OperationSupportTest.cpp
index 90e59808c984a..fa5fdfe16fde0 100644
--- a/mlir/unittests/IR/OperationSupportTest.cpp
+++ b/mlir/unittests/IR/OperationSupportTest.cpp
@@ -334,7 +334,7 @@ TEST(OperationEquivalenceTest, HashWorksWithFlags) {
   // Check ignore discardable dictionary attributes.
   SmallVector<NamedAttribute> newAttrs = {
       b.getNamedAttr("foo", b.getStringAttr("f"))};
-  op1->setAttrs(newAttrs);
+  op1->setDiscardableAttrs(newAttrs);
   EXPECT_EQ(getHash(op1, OperationEquivalence::IgnoreDiscardableAttrs),
             getHash(op2, OperationEquivalence::IgnoreDiscardableAttrs));
   EXPECT_NE(getHash(op1, OperationEquivalence::None),

diff  --git a/mlir/unittests/Interfaces/DataLayoutInterfacesTest.cpp b/mlir/unittests/Interfaces/DataLayoutInterfacesTest.cpp
index 3067cf103590c..f72c00070bd01 100644
--- a/mlir/unittests/Interfaces/DataLayoutInterfacesTest.cpp
+++ b/mlir/unittests/Interfaces/DataLayoutInterfacesTest.cpp
@@ -280,11 +280,12 @@ struct OpWithLayout : public Op<OpWithLayout, DataLayoutOpInterface::Trait> {
   static StringRef getOperationName() { return "dltest.op_with_layout"; }
 
   DataLayoutSpecInterface getDataLayoutSpec() {
-    return getOperation()->getAttrOfType<DataLayoutSpecInterface>(kAttrName);
+    return getOperation()->getDiscardableAttrOfType<DataLayoutSpecInterface>(
+        kAttrName);
   }
 
   TargetSystemSpecInterface getTargetSystemSpec() {
-    return getOperation()->getAttrOfType<TargetSystemSpecInterface>(
+    return getOperation()->getDiscardableAttrOfType<TargetSystemSpecInterface>(
         kTargetSystemDescAttrName);
   }
 
@@ -332,11 +333,12 @@ struct OpWith7BitByte
   static StringRef getOperationName() { return "dltest.op_with_7bit_byte"; }
 
   DataLayoutSpecInterface getDataLayoutSpec() {
-    return getOperation()->getAttrOfType<DataLayoutSpecInterface>(kAttrName);
+    return getOperation()->getDiscardableAttrOfType<DataLayoutSpecInterface>(
+        kAttrName);
   }
 
   TargetSystemSpecInterface getTargetSystemSpec() {
-    return getOperation()->getAttrOfType<TargetSystemSpecInterface>(
+    return getOperation()->getDiscardableAttrOfType<TargetSystemSpecInterface>(
         kTargetSystemDescAttrName);
   }
 
@@ -732,7 +734,7 @@ TEST(DataLayout, CacheInvalidation) {
   EXPECT_EQ(layout.getTypeSize(Float16Type::get(&ctx)), 6u);
 
   // Replace the data layout spec with a new, empty spec.
-  op->setAttr(kAttrName, CustomDataLayoutSpec::get(&ctx, {}));
+  op->setDiscardableAttr(kAttrName, CustomDataLayoutSpec::get(&ctx, {}));
 
   // Data layout is no longer valid and should trigger assertion when queried.
 #ifndef NDEBUG

diff  --git a/mlir/unittests/Pass/PassManagerTest.cpp b/mlir/unittests/Pass/PassManagerTest.cpp
index 3f5db8ebcbb6d..c0b7dcbb7eaed 100644
--- a/mlir/unittests/Pass/PassManagerTest.cpp
+++ b/mlir/unittests/Pass/PassManagerTest.cpp
@@ -51,8 +51,8 @@ struct AnnotateFunctionPass
     auto &ga = getAnalysis<GenericAnalysis>();
     auto &sa = getAnalysis<OpSpecificAnalysis>();
 
-    op->setAttr("isFunc", builder.getBoolAttr(ga.isFunc));
-    op->setAttr("isSecret", builder.getBoolAttr(sa.isSecret));
+    op->setDiscardableAttr("isFunc", builder.getBoolAttr(ga.isFunc));
+    op->setDiscardableAttr("isSecret", builder.getBoolAttr(sa.isSecret));
   }
 };
 
@@ -96,11 +96,11 @@ struct AddAttrFunctionPass
   void runOnOperation() override {
     func::FuncOp op = getOperation();
     Builder builder(op->getParentOfType<ModuleOp>());
-    if (op->hasAttr("didProcess"))
-      op->setAttr("didProcessAgain", builder.getUnitAttr());
+    if (op->hasDiscardableAttr("didProcess"))
+      op->setDiscardableAttr("didProcessAgain", builder.getUnitAttr());
 
     // We always want to set this one.
-    op->setAttr("didProcess", builder.getUnitAttr());
+    op->setDiscardableAttr("didProcess", builder.getUnitAttr());
   }
 };
 
@@ -114,7 +114,7 @@ struct AddSecondAttrFunctionPass
   void runOnOperation() override {
     func::FuncOp op = getOperation();
     Builder builder(op->getParentOfType<ModuleOp>());
-    op->setAttr("didProcess2", builder.getUnitAttr());
+    op->setDiscardableAttr("didProcess2", builder.getUnitAttr());
   }
 };
 


        


More information about the Mlir-commits mailing list