[Mlir-commits] [mlir] [mlir][CAPI] Replace MlirIdentifier with MlirAttribute (PR #188222)

Tim Gymnich llvmlistbot at llvm.org
Tue Mar 24 06:08:44 PDT 2026


https://github.com/tgymnich updated https://github.com/llvm/llvm-project/pull/188222

>From c278542ec80b2eede6f794ad0076ab61dde7855f Mon Sep 17 00:00:00 2001
From: Tim Gymnich <tim at gymni.ch>
Date: Tue, 24 Mar 2026 00:09:15 +0100
Subject: [PATCH 1/3] [mlir][CAPI] Replace MlirIdentifier with MlirAttribute
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Follow up to 56f62fb / https://reviews.llvm.org/D116626

Removes the MlirIdentifier struct and replaces all uses with MlirAttribute.
Functions that previously accepted or returned MlirIdentifier now use
MlirAttribute (string kind) instead. The Identifier API
(mlirIdentifierGet, mlirIdentifierStr, etc.) is removed from the C API.

🤖 Assisted by Claude Code

Co-Authored-By: Claude Sonnet 4.6 noreply at anthropic.com
---
 mlir/include/mlir-c/Dialect/SMT.h             |  3 +-
 mlir/include/mlir-c/IR.h                      | 34 ++++----------
 .../mlir/Bindings/Python/IRInterfaces.h       |  5 +-
 mlir/include/mlir/CAPI/IR.h                   |  1 -
 mlir/lib/Bindings/Python/IRAttributes.cpp     |  4 +-
 mlir/lib/Bindings/Python/IRCore.cpp           | 36 +++++++-------
 mlir/lib/Bindings/Python/Rewrite.cpp          |  2 +-
 mlir/lib/CAPI/Dialect/SMT.cpp                 |  7 ++-
 mlir/lib/CAPI/IR/BuiltinAttributes.cpp        |  2 +-
 mlir/lib/CAPI/IR/IR.cpp                       | 37 ++++-----------
 mlir/test/CAPI/ir.c                           | 47 +++++++++----------
 mlir/test/CAPI/pass.c                         |  3 +-
 mlir/test/CAPI/smt.c                          |  3 +-
 13 files changed, 75 insertions(+), 109 deletions(-)

diff --git a/mlir/include/mlir-c/Dialect/SMT.h b/mlir/include/mlir-c/Dialect/SMT.h
index a289172b9d0f2..6a7deb29a0fea 100644
--- a/mlir/include/mlir-c/Dialect/SMT.h
+++ b/mlir/include/mlir-c/Dialect/SMT.h
@@ -83,8 +83,9 @@ MLIR_CAPI_EXPORTED MlirType mlirSMTTypeGetSMTFunc(MlirContext ctx,
 MLIR_CAPI_EXPORTED bool mlirSMTTypeIsASort(MlirType type);
 
 /// Creates a smt::SortType with the given identifier and sort parameters.
+/// The identifier must be a string attribute.
 MLIR_CAPI_EXPORTED MlirType mlirSMTTypeGetSort(MlirContext ctx,
-                                               MlirIdentifier identifier,
+                                               MlirAttribute identifier,
                                                size_t numberOfSortParams,
                                                const MlirType *sortParams);
 
diff --git a/mlir/include/mlir-c/IR.h b/mlir/include/mlir-c/IR.h
index 805f0ffaaf7ce..d79a7e69db415 100644
--- a/mlir/include/mlir-c/IR.h
+++ b/mlir/include/mlir-c/IR.h
@@ -61,7 +61,6 @@ DEFINE_C_API_STRUCT(MlirRegion, void);
 DEFINE_C_API_STRUCT(MlirSymbolTable, void);
 
 DEFINE_C_API_STRUCT(MlirAttribute, const void);
-DEFINE_C_API_STRUCT(MlirIdentifier, const void);
 DEFINE_C_API_STRUCT(MlirLocation, const void);
 DEFINE_C_API_STRUCT(MlirModule, const void);
 DEFINE_C_API_STRUCT(MlirType, const void);
@@ -72,9 +71,9 @@ DEFINE_C_API_STRUCT(MlirValue, const void);
 /// Named MLIR attribute.
 ///
 /// A named attribute is essentially a (name, attribute) pair where the name is
-/// a string.
+/// a string attribute (MlirAttribute of string kind).
 struct MlirNamedAttribute {
-  MlirIdentifier name;
+  MlirAttribute name;
   MlirAttribute attribute;
 };
 typedef struct MlirNamedAttribute MlirNamedAttribute;
@@ -271,7 +270,7 @@ MLIR_CAPI_EXPORTED MlirLocation mlirLocationFileLineColRangeGet(
     unsigned start_col, unsigned end_line, unsigned end_col);
 
 /// Getter for filename of FileLineColRange.
-MLIR_CAPI_EXPORTED MlirIdentifier
+MLIR_CAPI_EXPORTED MlirAttribute
 mlirLocationFileLineColRangeGetFilename(MlirLocation location);
 
 /// Getter for start_line of FileLineColRange.
@@ -347,7 +346,7 @@ MLIR_CAPI_EXPORTED MlirLocation mlirLocationNameGet(MlirContext context,
                                                     MlirLocation childLoc);
 
 /// Getter for name of Name.
-MLIR_CAPI_EXPORTED MlirIdentifier
+MLIR_CAPI_EXPORTED MlirAttribute
 mlirLocationNameGetName(MlirLocation location);
 
 /// Getter for childLoc of Name.
@@ -643,8 +642,8 @@ MLIR_CAPI_EXPORTED void mlirOperationSetLocation(MlirOperation op,
 /// description.
 MLIR_CAPI_EXPORTED MlirTypeID mlirOperationGetTypeID(MlirOperation op);
 
-/// Gets the name of the operation as an identifier.
-MLIR_CAPI_EXPORTED MlirIdentifier mlirOperationGetName(MlirOperation op);
+/// Gets the name of the operation as a string attribute.
+MLIR_CAPI_EXPORTED MlirAttribute mlirOperationGetName(MlirOperation op);
 
 /// Gets the block that owns this operation, returning null if the operation is
 /// not owned.
@@ -1208,27 +1207,10 @@ MLIR_CAPI_EXPORTED void mlirAttributePrint(MlirAttribute attr,
 MLIR_CAPI_EXPORTED void mlirAttributeDump(MlirAttribute attr);
 
 /// Associates an attribute with the name. Takes ownership of neither.
-MLIR_CAPI_EXPORTED MlirNamedAttribute mlirNamedAttributeGet(MlirIdentifier name,
+/// The name must be a string attribute.
+MLIR_CAPI_EXPORTED MlirNamedAttribute mlirNamedAttributeGet(MlirAttribute name,
                                                             MlirAttribute attr);
 
-//===----------------------------------------------------------------------===//
-// Identifier API.
-//===----------------------------------------------------------------------===//
-
-/// Gets an identifier with the given string value.
-MLIR_CAPI_EXPORTED MlirIdentifier mlirIdentifierGet(MlirContext context,
-                                                    MlirStringRef str);
-
-/// Returns the context associated with this identifier
-MLIR_CAPI_EXPORTED MlirContext mlirIdentifierGetContext(MlirIdentifier);
-
-/// Checks whether two identifiers are the same.
-MLIR_CAPI_EXPORTED bool mlirIdentifierEqual(MlirIdentifier ident,
-                                            MlirIdentifier other);
-
-/// Gets the string value of the identifier.
-MLIR_CAPI_EXPORTED MlirStringRef mlirIdentifierStr(MlirIdentifier ident);
-
 //===----------------------------------------------------------------------===//
 // Symbol and SymbolTable API.
 //===----------------------------------------------------------------------===//
diff --git a/mlir/include/mlir/Bindings/Python/IRInterfaces.h b/mlir/include/mlir/Bindings/Python/IRInterfaces.h
index fb30e030b6c32..bb691df76959d 100644
--- a/mlir/include/mlir/Bindings/Python/IRInterfaces.h
+++ b/mlir/include/mlir/Bindings/Python/IRInterfaces.h
@@ -9,6 +9,7 @@
 #ifndef MLIR_BINDINGS_PYTHON_IRINTERFACES_H
 #define MLIR_BINDINGS_PYTHON_IRINTERFACES_H
 
+#include "mlir-c/BuiltinAttributes.h"
 #include "mlir-c/IR.h"
 #include "mlir-c/Interfaces.h"
 #include "mlir-c/Support.h"
@@ -63,8 +64,8 @@ class PyConcreteOpInterface {
         throw nanobind::value_error((msg + ConcreteIface::pyClassName).c_str());
       }
 
-      MlirIdentifier identifier = mlirOperationGetName(*operation);
-      MlirStringRef stringRef = mlirIdentifierStr(identifier);
+      MlirAttribute nameAttr = mlirOperationGetName(*operation);
+      MlirStringRef stringRef = mlirStringAttrGetValue(nameAttr);
       opName = std::string(stringRef.data, stringRef.length);
     } else {
       if (!nanobind::try_cast<std::string>(obj.attr("OPERATION_NAME"), opName))
diff --git a/mlir/include/mlir/CAPI/IR.h b/mlir/include/mlir/CAPI/IR.h
index 1836cb0acb67e..89ad3a215c269 100644
--- a/mlir/include/mlir/CAPI/IR.h
+++ b/mlir/include/mlir/CAPI/IR.h
@@ -34,7 +34,6 @@ DEFINE_C_API_PTR_METHODS(MlirRegion, mlir::Region)
 DEFINE_C_API_PTR_METHODS(MlirSymbolTable, mlir::SymbolTable)
 
 DEFINE_C_API_METHODS(MlirAttribute, mlir::Attribute)
-DEFINE_C_API_METHODS(MlirIdentifier, mlir::StringAttr)
 DEFINE_C_API_METHODS(MlirLocation, mlir::Location)
 DEFINE_C_API_METHODS(MlirModule, mlir::ModuleOp)
 DEFINE_C_API_METHODS(MlirType, mlir::Type)
diff --git a/mlir/lib/Bindings/Python/IRAttributes.cpp b/mlir/lib/Bindings/Python/IRAttributes.cpp
index 9f5602cc61b35..5659c28e412f1 100644
--- a/mlir/lib/Bindings/Python/IRAttributes.cpp
+++ b/mlir/lib/Bindings/Python/IRAttributes.cpp
@@ -1180,7 +1180,7 @@ void PyDictAttribute::bindDerived(ClassTy &c) {
           auto &mlirAttr = nb::cast<PyAttribute &>(it.second);
           auto name = nb::cast<std::string>(it.first);
           mlirNamedAttributes.push_back(mlirNamedAttributeGet(
-              mlirIdentifierGet(mlirAttributeGetContext(mlirAttr),
+              mlirStringAttrGet(mlirAttributeGetContext(mlirAttr),
                                 toMlirStringRef(name)),
               mlirAttr));
         }
@@ -1207,7 +1207,7 @@ void PyDictAttribute::bindDerived(ClassTy &c) {
     MlirNamedAttribute namedAttr = mlirDictionaryAttrGetElement(self, index);
     return PyNamedAttribute(
         namedAttr.attribute,
-        std::string(mlirIdentifierStr(namedAttr.name).data));
+        std::string(mlirStringAttrGetValue(namedAttr.name).data));
   });
 }
 
diff --git a/mlir/lib/Bindings/Python/IRCore.cpp b/mlir/lib/Bindings/Python/IRCore.cpp
index f3f1ee4ce343f..41c53bb78a25e 100644
--- a/mlir/lib/Bindings/Python/IRCore.cpp
+++ b/mlir/lib/Bindings/Python/IRCore.cpp
@@ -1342,7 +1342,7 @@ nb::object PyOperation::create(std::string_view name,
     mlirNamedAttributes.reserve(mlirAttributes.size());
     for (const std::pair<std::string, MlirAttribute> &it : mlirAttributes)
       mlirNamedAttributes.push_back(mlirNamedAttributeGet(
-          mlirIdentifierGet(mlirAttributeGetContext(it.second),
+          mlirStringAttrGet(mlirAttributeGetContext(it.second),
                             toMlirStringRef(it.first)),
           it.second));
     mlirOperationStateAddAttributes(&state, mlirNamedAttributes.size(),
@@ -1383,10 +1383,10 @@ nb::object PyOperation::clone(const nb::object &maybeIp) {
 
 nb::object PyOperation::createOpView() {
   checkValid();
-  MlirIdentifier ident = mlirOperationGetName(get());
-  MlirStringRef identStr = mlirIdentifierStr(ident);
+  MlirAttribute nameAttr = mlirOperationGetName(get());
+  MlirStringRef nameStr = mlirStringAttrGetValue(nameAttr);
   auto operationCls = PyGlobals::get().lookupOperationClass(
-      std::string_view(identStr.data, identStr.length));
+      std::string_view(nameStr.data, nameStr.length));
   if (operationCls)
     return PyOpView::constructDerived(*operationCls, getRef().getObject());
   return nb::cast(PyOpView(getRef().getObject()));
@@ -1560,7 +1560,7 @@ static void populateResultTypes(std::string_view name, nb::list resultTypeList,
 MlirValue getUniqueResult(MlirOperation operation) {
   auto numResults = mlirOperationGetNumResults(operation);
   if (numResults != 1) {
-    auto name = mlirIdentifierStr(mlirOperationGetName(operation));
+    auto name = mlirStringAttrGetValue(mlirOperationGetName(operation));
     throw nb::value_error(
         join("Cannot call .result on operation ",
              std::string_view(name.data, name.length), " which has ",
@@ -1921,7 +1921,7 @@ nb::typed<nb::object, PyAttribute> PyAttribute::maybeDownCast() {
 PyNamedAttribute::PyNamedAttribute(MlirAttribute attr, std::string ownedName)
     : ownedName(new std::string(std::move(ownedName))) {
   namedAttr = mlirNamedAttributeGet(
-      mlirIdentifierGet(mlirAttributeGetContext(attr),
+      mlirStringAttrGet(mlirAttributeGetContext(attr),
                         toMlirStringRef(*this->ownedName)),
       attr);
 }
@@ -2431,10 +2431,9 @@ PyNamedAttribute PyOpAttributeMap::dunderGetItemIndexed(intptr_t index) {
   }
   MlirNamedAttribute namedAttr =
       mlirOperationGetAttribute(operation->get(), index);
-  return PyNamedAttribute(
-      namedAttr.attribute,
-      std::string(mlirIdentifierStr(namedAttr.name).data,
-                  mlirIdentifierStr(namedAttr.name).length));
+  MlirStringRef name = mlirStringAttrGetValue(namedAttr.name);
+  return PyNamedAttribute(namedAttr.attribute,
+                          std::string(name.data, name.length));
 }
 
 void PyOpAttributeMap::dunderSetItem(const std::string &name,
@@ -2464,7 +2463,7 @@ void PyOpAttributeMap::forEachAttr(
   intptr_t n = mlirOperationGetNumAttributes(op);
   for (intptr_t i = 0; i < n; ++i) {
     MlirNamedAttribute na = mlirOperationGetAttribute(op, i);
-    MlirStringRef name = mlirIdentifierStr(na.name);
+    MlirStringRef name = mlirStringAttrGetValue(na.name);
     fn(name, na.attribute);
   }
 }
@@ -3427,7 +3426,7 @@ void populateIRCore(nb::module_ &m) {
       .def_prop_ro(
           "filename",
           [](PyLocation loc) {
-            return mlirIdentifierStr(
+            return mlirStringAttrGetValue(
                 mlirLocationFileLineColRangeGetFilename(loc));
           },
           "Gets the filename from a FileLineColLoc.")
@@ -3491,7 +3490,7 @@ void populateIRCore(nb::module_ &m) {
       .def_prop_ro(
           "name_str",
           [](PyLocation loc) {
-            return mlirIdentifierStr(mlirLocationNameGetName(loc));
+            return mlirStringAttrGetValue(mlirLocationNameGetName(loc));
           },
           "Gets the name string from a `NameLoc`.")
       .def_prop_ro(
@@ -3710,7 +3709,7 @@ void populateIRCore(nb::module_ &m) {
             auto &concreteOperation = self.getOperation();
             concreteOperation.checkValid();
             MlirOperation operation = concreteOperation.get();
-            return mlirIdentifierStr(mlirOperationGetName(operation));
+            return mlirStringAttrGetValue(mlirOperationGetName(operation));
           },
           "Returns the fully qualified name of the operation.")
       .def_prop_ro(
@@ -4155,7 +4154,7 @@ void populateIRCore(nb::module_ &m) {
         std::string clsOpName =
             nb::cast<std::string>(cls.attr("OPERATION_NAME"));
         MlirStringRef identifier =
-            mlirIdentifierStr(mlirOperationGetName(*parsed.get()));
+            mlirStringAttrGetValue(mlirOperationGetName(*parsed.get()));
         std::string_view parsedOpName(identifier.data, identifier.length);
         if (clsOpName != parsedOpName)
           throw MLIRError(join("Expected a '", clsOpName, "' op, got: '",
@@ -4577,9 +4576,8 @@ void populateIRCore(nb::module_ &m) {
           [](PyNamedAttribute &self) {
             PyPrintAccumulator printAccum;
             printAccum.parts.append("NamedAttribute(");
-            printAccum.parts.append(
-                nb::str(mlirIdentifierStr(self.namedAttr.name).data,
-                        mlirIdentifierStr(self.namedAttr.name).length));
+            MlirStringRef name = mlirStringAttrGetValue(self.namedAttr.name);
+            printAccum.parts.append(nb::str(name.data, name.length));
             printAccum.parts.append("=");
             mlirAttributePrint(self.namedAttr.attribute,
                                printAccum.getCallback(),
@@ -4591,7 +4589,7 @@ void populateIRCore(nb::module_ &m) {
       .def_prop_ro(
           "name",
           [](PyNamedAttribute &self) {
-            return mlirIdentifierStr(self.namedAttr.name);
+            return mlirStringAttrGetValue(self.namedAttr.name);
           },
           "The name of the `NamedAttribute` binding.")
       .def_prop_ro(
diff --git a/mlir/lib/Bindings/Python/Rewrite.cpp b/mlir/lib/Bindings/Python/Rewrite.cpp
index 750c7b1e4b1d8..b37db07085720 100644
--- a/mlir/lib/Bindings/Python/Rewrite.cpp
+++ b/mlir/lib/Bindings/Python/Rewrite.cpp
@@ -247,7 +247,7 @@ void PyRewritePatternSet::addConversion(nb::handle root,
     nb::object adaptorCls =
         PyGlobals::get()
             .lookupOpAdaptorClass([&] {
-              MlirStringRef ref = mlirIdentifierStr(mlirOperationGetName(op));
+              MlirStringRef ref = mlirStringAttrGetValue(mlirOperationGetName(op));
               return std::string_view(ref.data, ref.length);
             }())
             .value_or(nb::borrow(nb::type<PyOpAdaptor>()));
diff --git a/mlir/lib/CAPI/Dialect/SMT.cpp b/mlir/lib/CAPI/Dialect/SMT.cpp
index e90ca0130e298..422e07c9148cb 100644
--- a/mlir/lib/CAPI/Dialect/SMT.cpp
+++ b/mlir/lib/CAPI/Dialect/SMT.cpp
@@ -7,6 +7,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "mlir-c/Dialect/SMT.h"
+#include "mlir/CAPI/IR.h"
 #include "mlir/CAPI/Registration.h"
 #include "mlir/Dialect/SMT/IR/SMTAttributes.h"
 #include "mlir/Dialect/SMT/IR/SMTDialect.h"
@@ -97,7 +98,7 @@ MlirType mlirSMTTypeGetSMTFunc(MlirContext ctx, size_t numberOfDomainTypes,
 
 bool mlirSMTTypeIsASort(MlirType type) { return isa<SortType>(unwrap(type)); }
 
-MlirType mlirSMTTypeGetSort(MlirContext ctx, MlirIdentifier identifier,
+MlirType mlirSMTTypeGetSort(MlirContext ctx, MlirAttribute identifier,
                             size_t numberOfSortParams,
                             const MlirType *sortParams) {
   SmallVector<Type> sortParamsVec;
@@ -106,7 +107,9 @@ MlirType mlirSMTTypeGetSort(MlirContext ctx, MlirIdentifier identifier,
   for (size_t i = 0; i < numberOfSortParams; i++)
     sortParamsVec.push_back(unwrap(sortParams[i]));
 
-  return wrap(SortType::get(unwrap(ctx), unwrap(identifier), sortParamsVec));
+  return wrap(SortType::get(unwrap(ctx),
+                            llvm::cast<StringAttr>(unwrap(identifier)),
+                            sortParamsVec));
 }
 
 //===----------------------------------------------------------------------===//
diff --git a/mlir/lib/CAPI/IR/BuiltinAttributes.cpp b/mlir/lib/CAPI/IR/BuiltinAttributes.cpp
index 4ced5fe111645..132d16c3dcf86 100644
--- a/mlir/lib/CAPI/IR/BuiltinAttributes.cpp
+++ b/mlir/lib/CAPI/IR/BuiltinAttributes.cpp
@@ -94,7 +94,7 @@ MlirAttribute mlirDictionaryAttrGet(MlirContext ctx, intptr_t numElements,
   SmallVector<NamedAttribute, 8> attributes;
   attributes.reserve(numElements);
   for (intptr_t i = 0; i < numElements; ++i)
-    attributes.emplace_back(unwrap(elements[i].name),
+    attributes.emplace_back(llvm::cast<StringAttr>(unwrap(elements[i].name)),
                             unwrap(elements[i].attribute));
   return wrap(DictionaryAttr::get(unwrap(ctx), attributes));
 }
diff --git a/mlir/lib/CAPI/IR/IR.cpp b/mlir/lib/CAPI/IR/IR.cpp
index 29f9287279b8f..03441f1619b30 100644
--- a/mlir/lib/CAPI/IR/IR.cpp
+++ b/mlir/lib/CAPI/IR/IR.cpp
@@ -285,8 +285,9 @@ mlirLocationFileLineColRangeGet(MlirContext context, MlirStringRef filename,
                                      startLine, startCol, endLine, endCol)));
 }
 
-MlirIdentifier mlirLocationFileLineColRangeGetFilename(MlirLocation location) {
-  return wrap(llvm::dyn_cast<FileLineColRange>(unwrap(location)).getFilename());
+MlirAttribute mlirLocationFileLineColRangeGetFilename(MlirLocation location) {
+  return wrap(
+      Attribute(llvm::dyn_cast<FileLineColRange>(unwrap(location)).getFilename()));
 }
 
 int mlirLocationFileLineColRangeGetStartLine(MlirLocation location) {
@@ -384,8 +385,8 @@ MlirLocation mlirLocationNameGet(MlirContext context, MlirStringRef name,
       StringAttr::get(unwrap(context), unwrap(name)), unwrap(childLoc))));
 }
 
-MlirIdentifier mlirLocationNameGetName(MlirLocation location) {
-  return wrap((llvm::dyn_cast<NameLoc>(unwrap(location)).getName()));
+MlirAttribute mlirLocationNameGetName(MlirLocation location) {
+  return wrap(Attribute(llvm::dyn_cast<NameLoc>(unwrap(location)).getName()));
 }
 
 MlirLocation mlirLocationNameGetChildLoc(MlirLocation location) {
@@ -599,7 +600,7 @@ MlirOperation mlirOperationCreate(MlirOperationState *state) {
 
   cppState.attributes.reserve(state->nAttributes);
   for (intptr_t i = 0; i < state->nAttributes; ++i)
-    cppState.addAttribute(unwrap(state->attributes[i].name),
+    cppState.addAttribute(llvm::cast<StringAttr>(unwrap(state->attributes[i].name)),
                           unwrap(state->attributes[i].attribute));
 
   for (intptr_t i = 0; i < state->nRegions; ++i)
@@ -665,8 +666,8 @@ MlirTypeID mlirOperationGetTypeID(MlirOperation op) {
   return {nullptr};
 }
 
-MlirIdentifier mlirOperationGetName(MlirOperation op) {
-  return wrap(unwrap(op)->getName().getIdentifier());
+MlirAttribute mlirOperationGetName(MlirOperation op) {
+  return wrap(Attribute(unwrap(op)->getName().getIdentifier()));
 }
 
 MlirBlock mlirOperationGetBlock(MlirOperation op) {
@@ -1312,31 +1313,11 @@ void mlirAttributePrint(MlirAttribute attr, MlirStringCallback callback,
 
 void mlirAttributeDump(MlirAttribute attr) { unwrap(attr).dump(); }
 
-MlirNamedAttribute mlirNamedAttributeGet(MlirIdentifier name,
+MlirNamedAttribute mlirNamedAttributeGet(MlirAttribute name,
                                          MlirAttribute attr) {
   return MlirNamedAttribute{name, attr};
 }
 
-//===----------------------------------------------------------------------===//
-// Identifier API.
-//===----------------------------------------------------------------------===//
-
-MlirIdentifier mlirIdentifierGet(MlirContext context, MlirStringRef str) {
-  return wrap(StringAttr::get(unwrap(context), unwrap(str)));
-}
-
-MlirContext mlirIdentifierGetContext(MlirIdentifier ident) {
-  return wrap(unwrap(ident).getContext());
-}
-
-bool mlirIdentifierEqual(MlirIdentifier ident, MlirIdentifier other) {
-  return unwrap(ident) == unwrap(other);
-}
-
-MlirStringRef mlirIdentifierStr(MlirIdentifier ident) {
-  return wrap(unwrap(ident).strref());
-}
-
 //===----------------------------------------------------------------------===//
 // Symbol and SymbolTable API.
 //===----------------------------------------------------------------------===//
diff --git a/mlir/test/CAPI/ir.c b/mlir/test/CAPI/ir.c
index 5487d1d9cf654..12483e983323e 100644
--- a/mlir/test/CAPI/ir.c
+++ b/mlir/test/CAPI/ir.c
@@ -113,11 +113,11 @@ MlirModule makeAndDumpAdd(MlirContext ctx, MlirLocation location) {
       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("\"add\""));
   MlirNamedAttribute funcAttrs[] = {
       mlirNamedAttributeGet(
-          mlirIdentifierGet(ctx,
+          mlirStringAttrGet(ctx,
                             mlirStringRefCreateFromCString("function_type")),
           funcTypeAttr),
       mlirNamedAttributeGet(
-          mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("sym_name")),
+          mlirStringAttrGet(ctx, mlirStringRefCreateFromCString("sym_name")),
           funcNameAttr)};
   MlirOperationState funcState = mlirOperationStateGet(
       mlirStringRefCreateFromCString("func.func"), location);
@@ -131,7 +131,7 @@ MlirModule makeAndDumpAdd(MlirContext ctx, MlirLocation location) {
   MlirAttribute indexZeroLiteral =
       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index"));
   MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet(
-      mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
+      mlirStringAttrGet(ctx, mlirStringRefCreateFromCString("value")),
       indexZeroLiteral);
   MlirOperationState constZeroState = mlirOperationStateGet(
       mlirStringRefCreateFromCString("arith.constant"), location);
@@ -158,7 +158,7 @@ MlirModule makeAndDumpAdd(MlirContext ctx, MlirLocation location) {
   MlirAttribute indexOneLiteral =
       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("1 : index"));
   MlirNamedAttribute indexOneValueAttr = mlirNamedAttributeGet(
-      mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
+      mlirStringAttrGet(ctx, mlirStringRefCreateFromCString("value")),
       indexOneLiteral);
   MlirOperationState constOneState = mlirOperationStateGet(
       mlirStringRefCreateFromCString("arith.constant"), location);
@@ -386,8 +386,8 @@ static void printFirstOfEach(MlirContext ctx, MlirOperation operation) {
   // clang-format on
 
   // Get the operation name and print it.
-  MlirIdentifier ident = mlirOperationGetName(operation);
-  MlirStringRef identStr = mlirIdentifierStr(ident);
+  MlirAttribute ident = mlirOperationGetName(operation);
+  MlirStringRef identStr = mlirStringAttrGetValue(ident);
   fprintf(stderr, "Operation name: '");
   for (size_t i = 0; i < identStr.length; ++i)
     fputc(identStr.data[i], stderr);
@@ -395,9 +395,10 @@ static void printFirstOfEach(MlirContext ctx, MlirOperation operation) {
   // CHECK: Operation name: 'arith.constant'
 
   // Get the identifier again and verify equal.
-  MlirIdentifier identAgain = mlirIdentifierGet(ctx, identStr);
+  MlirAttribute identAgain =
+      mlirStringAttrGet(mlirAttributeGetContext(ident), identStr);
   fprintf(stderr, "Identifier equal: %d\n",
-          mlirIdentifierEqual(ident, identAgain));
+          mlirAttributeEqual(ident, identAgain));
   // CHECK: Identifier equal: 1
 
   // Get the block terminator and print it.
@@ -637,7 +638,7 @@ static int createOperationWithTypeInference(MlirContext ctx) {
   MlirOperationState state = mlirOperationStateGet(
       mlirStringRefCreateFromCString("shape.const_size"), loc);
   MlirNamedAttribute valueAttr = mlirNamedAttributeGet(
-      mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")), iAttr);
+      mlirStringAttrGet(ctx, mlirStringRefCreateFromCString("value")), iAttr);
   mlirOperationStateAddAttributes(&state, 1, &valueAttr);
   mlirOperationStateEnableResultTypeInference(&state);
 
@@ -1823,8 +1824,8 @@ static int testBackreferences(void) {
   mlirRegionAppendOwnedBlock(region, block);
   mlirOperationStateAddOwnedRegions(&opState, 1, &region);
   MlirOperation op = mlirOperationCreate(&opState);
-  MlirIdentifier ident =
-      mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("identifier"));
+  MlirAttribute ident =
+      mlirStringAttrGet(ctx, mlirStringRefCreateFromCString("identifier"));
 
   if (!mlirContextEqual(ctx, mlirOperationGetContext(op))) {
     fprintf(stderr, "ERROR: Getting context from operation failed\n");
@@ -1834,7 +1835,7 @@ static int testBackreferences(void) {
     fprintf(stderr, "ERROR: Getting parent operation from block failed\n");
     return 2;
   }
-  if (!mlirContextEqual(ctx, mlirIdentifierGetContext(ident))) {
+  if (!mlirContextEqual(ctx, mlirAttributeGetContext(ident))) {
     fprintf(stderr, "ERROR: Getting context from identifier failed\n");
     return 3;
   }
@@ -1863,7 +1864,7 @@ int testOperands(void) {
   MlirAttribute indexZeroLiteral =
       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index"));
   MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet(
-      mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
+      mlirStringAttrGet(ctx, mlirStringRefCreateFromCString("value")),
       indexZeroLiteral);
   MlirOperationState constZeroState = mlirOperationStateGet(
       mlirStringRefCreateFromCString("arith.constant"), loc);
@@ -1875,7 +1876,7 @@ int testOperands(void) {
   MlirAttribute indexOneLiteral =
       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("1 : index"));
   MlirNamedAttribute indexOneValueAttr = mlirNamedAttributeGet(
-      mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
+      mlirStringAttrGet(ctx, mlirStringRefCreateFromCString("value")),
       indexOneLiteral);
   MlirOperationState constOneState = mlirOperationStateGet(
       mlirStringRefCreateFromCString("arith.constant"), loc);
@@ -1957,7 +1958,7 @@ int testOperands(void) {
   MlirAttribute indexTwoLiteral =
       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("2 : index"));
   MlirNamedAttribute indexTwoValueAttr = mlirNamedAttributeGet(
-      mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
+      mlirStringAttrGet(ctx, mlirStringRefCreateFromCString("value")),
       indexTwoLiteral);
   MlirOperationState constTwoState = mlirOperationStateGet(
       mlirStringRefCreateFromCString("arith.constant"), loc);
@@ -2022,7 +2023,7 @@ int testClone(void) {
   MlirAttribute indexZeroLiteral =
       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index"));
   MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet(
-      mlirIdentifierGet(ctx, valueStringRef), indexZeroLiteral);
+      mlirStringAttrGet(ctx, valueStringRef), indexZeroLiteral);
   MlirOperationState constZeroState = mlirOperationStateGet(
       mlirStringRefCreateFromCString("arith.constant"), loc);
   mlirOperationStateAddResults(&constZeroState, 1, &indexType);
@@ -2112,7 +2113,7 @@ int testTypeID(MlirContext ctx) {
   MlirAttribute indexZeroLiteral =
       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index"));
   MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet(
-      mlirIdentifierGet(ctx, valueStringRef), indexZeroLiteral);
+      mlirStringAttrGet(ctx, valueStringRef), indexZeroLiteral);
   MlirOperationState constZeroState = mlirOperationStateGet(
       mlirStringRefCreateFromCString("arith.constant"), loc);
   mlirOperationStateAddResults(&constZeroState, 1, &indexType);
@@ -2258,18 +2259,16 @@ typedef struct {
 
 MlirWalkResult walkCallBack(MlirOperation op, void *rootOpVoid) {
   fprintf(stderr, "%s: %s\n", ((callBackData *)(rootOpVoid))->x,
-          mlirIdentifierStr(mlirOperationGetName(op)).data);
+          mlirStringAttrGetValue(mlirOperationGetName(op)).data);
   return MlirWalkResultAdvance;
 }
 
 MlirWalkResult walkCallBackTestWalkResult(MlirOperation op, void *rootOpVoid) {
-  fprintf(stderr, "%s: %s\n", ((callBackData *)(rootOpVoid))->x,
-          mlirIdentifierStr(mlirOperationGetName(op)).data);
-  if (strcmp(mlirIdentifierStr(mlirOperationGetName(op)).data, "func.func") ==
-      0)
+  MlirStringRef opName = mlirStringAttrGetValue(mlirOperationGetName(op));
+  fprintf(stderr, "%s: %s\n", ((callBackData *)(rootOpVoid))->x, opName.data);
+  if (strcmp(opName.data, "func.func") == 0)
     return MlirWalkResultSkip;
-  if (strcmp(mlirIdentifierStr(mlirOperationGetName(op)).data, "arith.addi") ==
-      0)
+  if (strcmp(opName.data, "arith.addi") == 0)
     return MlirWalkResultInterrupt;
   return MlirWalkResultAdvance;
 }
diff --git a/mlir/test/CAPI/pass.c b/mlir/test/CAPI/pass.c
index 58f4d787ace63..6b7edad13fa68 100644
--- a/mlir/test/CAPI/pass.c
+++ b/mlir/test/CAPI/pass.c
@@ -11,6 +11,7 @@
  */
 
 #include "mlir-c/Pass.h"
+#include "mlir-c/BuiltinAttributes.h"
 #include "mlir-c/Dialect/Func.h"
 #include "mlir-c/IR.h"
 #include "mlir-c/RegisterEverything.h"
@@ -314,7 +315,7 @@ void testRunExternalPass(MlirOperation op, MlirExternalPass pass,
 void testRunExternalFuncPass(MlirOperation op, MlirExternalPass pass,
                              void *userData) {
   ++((TestExternalPassUserData *)userData)->runCallCount;
-  MlirStringRef opName = mlirIdentifierStr(mlirOperationGetName(op));
+  MlirStringRef opName = mlirStringAttrGetValue(mlirOperationGetName(op));
   if (!mlirStringRefEqual(opName,
                           mlirStringRefCreateFromCString("func.func"))) {
     mlirExternalPassSignalFailure(pass);
diff --git a/mlir/test/CAPI/smt.c b/mlir/test/CAPI/smt.c
index a621147c91b61..948f6aefcef10 100644
--- a/mlir/test/CAPI/smt.c
+++ b/mlir/test/CAPI/smt.c
@@ -12,6 +12,7 @@
 
 #include "mlir-c/Dialect/SMT.h"
 #include "mlir-c/Dialect/Func.h"
+#include "mlir-c/BuiltinAttributes.h"
 #include "mlir-c/IR.h"
 #include "mlir-c/Support.h"
 #include "mlir-c/Target/ExportSMTLIB.h"
@@ -57,7 +58,7 @@ void testSMTType(MlirContext ctx) {
   MlirType funcType =
       mlirSMTTypeGetSMTFunc(ctx, 2, (MlirType[]){intType, boolType}, boolType);
   MlirType sortType = mlirSMTTypeGetSort(
-      ctx, mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("sort")), 0,
+      ctx, mlirStringAttrGet(ctx, mlirStringRefCreateFromCString("sort")), 0,
       NULL);
 
   // CHECK: !smt.bool

>From 07a431588ca7d315d65ff87edff49223ad89cc43 Mon Sep 17 00:00:00 2001
From: Tim Gymnich <tim at gymni.ch>
Date: Tue, 24 Mar 2026 12:35:35 +0100
Subject: [PATCH 2/3] clang format

---
 mlir/include/mlir-c/IR.h             |  3 +--
 mlir/lib/Bindings/Python/Rewrite.cpp | 14 +++++++-------
 mlir/lib/CAPI/Dialect/SMT.cpp        |  5 ++---
 mlir/lib/CAPI/IR/IR.cpp              |  9 +++++----
 mlir/test/CAPI/smt.c                 |  2 +-
 5 files changed, 16 insertions(+), 17 deletions(-)

diff --git a/mlir/include/mlir-c/IR.h b/mlir/include/mlir-c/IR.h
index d79a7e69db415..2711ddab2f499 100644
--- a/mlir/include/mlir-c/IR.h
+++ b/mlir/include/mlir-c/IR.h
@@ -346,8 +346,7 @@ MLIR_CAPI_EXPORTED MlirLocation mlirLocationNameGet(MlirContext context,
                                                     MlirLocation childLoc);
 
 /// Getter for name of Name.
-MLIR_CAPI_EXPORTED MlirAttribute
-mlirLocationNameGetName(MlirLocation location);
+MLIR_CAPI_EXPORTED MlirAttribute mlirLocationNameGetName(MlirLocation location);
 
 /// Getter for childLoc of Name.
 MLIR_CAPI_EXPORTED MlirLocation
diff --git a/mlir/lib/Bindings/Python/Rewrite.cpp b/mlir/lib/Bindings/Python/Rewrite.cpp
index b37db07085720..7c4910e2becab 100644
--- a/mlir/lib/Bindings/Python/Rewrite.cpp
+++ b/mlir/lib/Bindings/Python/Rewrite.cpp
@@ -244,13 +244,13 @@ void PyRewritePatternSet::addConversion(nb::handle root,
     nb::object opView = PyOperation::forOperation(ctx, op)->createOpView();
 
     std::vector<MlirValue> operandsVec(operands, operands + nOperands);
-    nb::object adaptorCls =
-        PyGlobals::get()
-            .lookupOpAdaptorClass([&] {
-              MlirStringRef ref = mlirStringAttrGetValue(mlirOperationGetName(op));
-              return std::string_view(ref.data, ref.length);
-            }())
-            .value_or(nb::borrow(nb::type<PyOpAdaptor>()));
+    nb::object adaptorCls = PyGlobals::get()
+                                .lookupOpAdaptorClass([&] {
+                                  MlirStringRef ref = mlirStringAttrGetValue(
+                                      mlirOperationGetName(op));
+                                  return std::string_view(ref.data, ref.length);
+                                }())
+                                .value_or(nb::borrow(nb::type<PyOpAdaptor>()));
 
     nb::object res = f(opView, adaptorCls(operandsVec, opView),
                        PyConversionPattern(pattern).getTypeConverter(),
diff --git a/mlir/lib/CAPI/Dialect/SMT.cpp b/mlir/lib/CAPI/Dialect/SMT.cpp
index 422e07c9148cb..06867e3cafb31 100644
--- a/mlir/lib/CAPI/Dialect/SMT.cpp
+++ b/mlir/lib/CAPI/Dialect/SMT.cpp
@@ -107,9 +107,8 @@ MlirType mlirSMTTypeGetSort(MlirContext ctx, MlirAttribute identifier,
   for (size_t i = 0; i < numberOfSortParams; i++)
     sortParamsVec.push_back(unwrap(sortParams[i]));
 
-  return wrap(SortType::get(unwrap(ctx),
-                            llvm::cast<StringAttr>(unwrap(identifier)),
-                            sortParamsVec));
+  return wrap(SortType::get(
+      unwrap(ctx), llvm::cast<StringAttr>(unwrap(identifier)), sortParamsVec));
 }
 
 //===----------------------------------------------------------------------===//
diff --git a/mlir/lib/CAPI/IR/IR.cpp b/mlir/lib/CAPI/IR/IR.cpp
index 03441f1619b30..1c1bdac2d4742 100644
--- a/mlir/lib/CAPI/IR/IR.cpp
+++ b/mlir/lib/CAPI/IR/IR.cpp
@@ -286,8 +286,8 @@ mlirLocationFileLineColRangeGet(MlirContext context, MlirStringRef filename,
 }
 
 MlirAttribute mlirLocationFileLineColRangeGetFilename(MlirLocation location) {
-  return wrap(
-      Attribute(llvm::dyn_cast<FileLineColRange>(unwrap(location)).getFilename()));
+  return wrap(Attribute(
+      llvm::dyn_cast<FileLineColRange>(unwrap(location)).getFilename()));
 }
 
 int mlirLocationFileLineColRangeGetStartLine(MlirLocation location) {
@@ -600,8 +600,9 @@ MlirOperation mlirOperationCreate(MlirOperationState *state) {
 
   cppState.attributes.reserve(state->nAttributes);
   for (intptr_t i = 0; i < state->nAttributes; ++i)
-    cppState.addAttribute(llvm::cast<StringAttr>(unwrap(state->attributes[i].name)),
-                          unwrap(state->attributes[i].attribute));
+    cppState.addAttribute(
+        llvm::cast<StringAttr>(unwrap(state->attributes[i].name)),
+        unwrap(state->attributes[i].attribute));
 
   for (intptr_t i = 0; i < state->nRegions; ++i)
     cppState.addRegion(std::unique_ptr<Region>(unwrap(state->regions[i])));
diff --git a/mlir/test/CAPI/smt.c b/mlir/test/CAPI/smt.c
index 948f6aefcef10..1ae7ab8d5332f 100644
--- a/mlir/test/CAPI/smt.c
+++ b/mlir/test/CAPI/smt.c
@@ -11,8 +11,8 @@
  */
 
 #include "mlir-c/Dialect/SMT.h"
-#include "mlir-c/Dialect/Func.h"
 #include "mlir-c/BuiltinAttributes.h"
+#include "mlir-c/Dialect/Func.h"
 #include "mlir-c/IR.h"
 #include "mlir-c/Support.h"
 #include "mlir-c/Target/ExportSMTLIB.h"

>From 25c5f6e382bf86dddad7b02b6f099b9b84226a38 Mon Sep 17 00:00:00 2001
From: Tim Gymnich <tim at gymni.ch>
Date: Tue, 24 Mar 2026 13:50:44 +0100
Subject: [PATCH 3/3] [mlir][CAPI] Add string attribute assertions to functions
 accepting name attributes
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Add assert(isa<StringAttr>(...)) checks in mlirNamedAttributeGet,
mlirOperationCreate, mlirDictionaryAttrGet, and mlirSMTTypeGetSort
to catch callers passing non-string attributes where a name is expected.

🤖 Assisted by Claude Code

Co-Authored-By: Claude Sonnet 4.6 <noreply at anthropic.com>
---
 mlir/lib/CAPI/Dialect/SMT.cpp | 2 ++
 mlir/lib/CAPI/IR/IR.cpp       | 2 ++
 2 files changed, 4 insertions(+)

diff --git a/mlir/lib/CAPI/Dialect/SMT.cpp b/mlir/lib/CAPI/Dialect/SMT.cpp
index 06867e3cafb31..7edc6830a934e 100644
--- a/mlir/lib/CAPI/Dialect/SMT.cpp
+++ b/mlir/lib/CAPI/Dialect/SMT.cpp
@@ -107,6 +107,8 @@ MlirType mlirSMTTypeGetSort(MlirContext ctx, MlirAttribute identifier,
   for (size_t i = 0; i < numberOfSortParams; i++)
     sortParamsVec.push_back(unwrap(sortParams[i]));
 
+  assert(isa<StringAttr>(unwrap(identifier)) &&
+         "name attribute name must be a string attribute");
   return wrap(SortType::get(
       unwrap(ctx), llvm::cast<StringAttr>(unwrap(identifier)), sortParamsVec));
 }
diff --git a/mlir/lib/CAPI/IR/IR.cpp b/mlir/lib/CAPI/IR/IR.cpp
index 1c1bdac2d4742..c61c7c5251fc2 100644
--- a/mlir/lib/CAPI/IR/IR.cpp
+++ b/mlir/lib/CAPI/IR/IR.cpp
@@ -1316,6 +1316,8 @@ void mlirAttributeDump(MlirAttribute attr) { unwrap(attr).dump(); }
 
 MlirNamedAttribute mlirNamedAttributeGet(MlirAttribute name,
                                          MlirAttribute attr) {
+  assert(isa<StringAttr>(unwrap(name)) &&
+         "name attribute name must be a string attribute");
   return MlirNamedAttribute{name, attr};
 }
 



More information about the Mlir-commits mailing list