[MLIR] Add LocationAttr to the Python API
authorAndrew Young <youngar17@gmail.com>
Thu, 19 Jan 2023 23:01:46 +0000 (15:01 -0800)
committerAndrew Young <youngar17@gmail.com>
Thu, 26 Jan 2023 00:09:29 +0000 (16:09 -0800)
This is a follow up to D142182, to expose LocationAttrs through Python.

Reviewed By: ftynse

Differential Revision: https://reviews.llvm.org/D142522

mlir/lib/Bindings/Python/IRCore.cpp
mlir/test/python/ir/location.py

index eb7d18f..2ecfc36 100644 (file)
@@ -2546,10 +2546,25 @@ void mlir::python::populateIRCore(py::module &m) {
           },
           py::arg("name"), py::arg("childLoc") = py::none(),
           py::arg("context") = py::none(), kContextGetNameLocationDocString)
+      .def_static(
+          "from_attr",
+          [](PyAttribute &attribute, DefaultingPyMlirContext context) {
+            return PyLocation(context->getRef(),
+                              mlirLocationFromAttribute(attribute));
+          },
+          py::arg("attribute"), py::arg("context") = py::none(),
+          "Gets a Location from a LocationAttr")
       .def_property_readonly(
           "context",
           [](PyLocation &self) { return self.getContext().getObject(); },
           "Context that owns the Location")
+      .def_property_readonly(
+          "attr",
+          [](PyLocation &self) {
+            return PyAttribute(self.getContext(),
+                               mlirLocationGetAttribute(self));
+          },
+          "Get the underlying LocationAttr")
       .def(
           "emit_error",
           [](PyLocation &self, std::string message) {
index ecdd02e..c1c96d0 100644 (file)
@@ -25,6 +25,21 @@ def testUnknown():
 run(testUnknown)
 
 
+# CHECK-LABEL: TEST: testLocationAttr
+def testLocationAttr():
+  with Context() as ctxt:
+    loc = Location.unknown()
+    attr = loc.get_attr()
+    clone = Location.from_attr(attr)
+  gc.collect()
+  # CHECK: loc: loc(unknown)
+  print("loc:", str(loc))
+  # CHECK: clone: loc(unknown)
+  print("clone:", str(clone))
+  assert loc == clone
+
+run(testLocationAttr)
+
 # CHECK-LABEL: TEST: testFileLineCol
 def testFileLineCol():
   with Context() as ctx: