diff --git a/mlir/lib/Bindings/Python/IRAttributes.cpp b/mlir/lib/Bindings/Python/IRAttributes.cpp index bef3b95a2487a2..1093d50c88698e 100644 --- a/mlir/lib/Bindings/Python/IRAttributes.cpp +++ b/mlir/lib/Bindings/Python/IRAttributes.cpp @@ -320,6 +320,43 @@ class PyFlatSymbolRefAttribute } }; +class PyOpaqueAttribute : public PyConcreteAttribute { +public: + static constexpr IsAFunctionTy isaFunction = mlirAttributeIsAOpaque; + static constexpr const char *pyClassName = "OpaqueAttr"; + using PyConcreteAttribute::PyConcreteAttribute; + + static void bindDerived(ClassTy &c) { + c.def_static( + "get", + [](std::string dialectNamespace, py::buffer buffer, PyType &type, + DefaultingPyMlirContext context) { + const py::buffer_info bufferInfo = buffer.request(); + intptr_t bufferSize = bufferInfo.size; + MlirAttribute attr = mlirOpaqueAttrGet( + context->get(), toMlirStringRef(dialectNamespace), bufferSize, + static_cast(bufferInfo.ptr), type); + return PyOpaqueAttribute(context->getRef(), attr); + }, + py::arg("dialect_namespace"), py::arg("buffer"), py::arg("type"), + py::arg("context") = py::none(), "Gets an Opaque attribute."); + c.def_property_readonly( + "dialect_namespace", + [](PyOpaqueAttribute &self) { + MlirStringRef stringRef = mlirOpaqueAttrGetDialectNamespace(self); + return py::str(stringRef.data, stringRef.length); + }, + "Returns the dialect namespace for the Opaque attribute as a string"); + c.def_property_readonly( + "data", + [](PyOpaqueAttribute &self) { + MlirStringRef stringRef = mlirOpaqueAttrGetData(self); + return py::str(stringRef.data, stringRef.length); + }, + "Returns the data for the Opaqued attributes as a string"); + } +}; + class PyStringAttribute : public PyConcreteAttribute { public: static constexpr IsAFunctionTy isaFunction = mlirAttributeIsAString; @@ -862,6 +899,7 @@ void mlir::python::populateIRAttributes(py::module &m) { PyDenseIntElementsAttribute::bind(m); PyDictAttribute::bind(m); PyFlatSymbolRefAttribute::bind(m); + PyOpaqueAttribute::bind(m); PyFloatAttribute::bind(m); PyIntegerAttribute::bind(m); PyStringAttribute::bind(m); diff --git a/mlir/test/python/ir/attributes.py b/mlir/test/python/ir/attributes.py index 53d246b3975284..f5efdf3880bb23 100644 --- a/mlir/test/python/ir/attributes.py +++ b/mlir/test/python/ir/attributes.py @@ -236,6 +236,24 @@ def testFlatSymbolRefAttr(): print("default_get:", FlatSymbolRefAttr.get("foobar")) +# CHECK-LABEL: TEST: testOpaqueAttr +@run +def testOpaqueAttr(): + with Context() as ctx: + ctx.allow_unregistered_dialects = True + oattr = OpaqueAttr(Attribute.parse("#pytest_dummy.dummyattr<>")) + # CHECK: oattr value: pytest_dummy + print("oattr value:", oattr.dialect_namespace) + # CHECK: oattr value: dummyattr<> + print("oattr value:", oattr.data) + + # Test factory methods. + # CHECK: default_get: #foobar<"123"> + print( + "default_get:", + OpaqueAttr.get("foobar", bytes("123", "utf-8"), NoneType.get())) + + # CHECK-LABEL: TEST: testStringAttr @run def testStringAttr():