diff --git a/mlir/include/mlir-c/IR.h b/mlir/include/mlir-c/IR.h --- a/mlir/include/mlir-c/IR.h +++ b/mlir/include/mlir-c/IR.h @@ -357,6 +357,9 @@ /// Gets the context this operation is associated with MLIR_CAPI_EXPORTED MlirContext mlirOperationGetContext(MlirOperation op); +/// Gets the location of the operation. +MLIR_CAPI_EXPORTED MlirLocation mlirOperationGetLoc(MlirOperation op); + /// Gets the type id of the operation. /// Returns null if the operation does not have a registered operation /// description. diff --git a/mlir/lib/Bindings/Python/IRCore.cpp b/mlir/lib/Bindings/Python/IRCore.cpp --- a/mlir/lib/Bindings/Python/IRCore.cpp +++ b/mlir/lib/Bindings/Python/IRCore.cpp @@ -2143,6 +2143,15 @@ }, "Shortcut to get an op result if it has only one (throws an error " "otherwise).") + .def_property_readonly( + "loc", + [](PyOperationBase &self) { + auto &operation = self.getOperation(); + return PyLocation(operation.getContext(), + mlirOperationGetLoc(operation.get())); + }, + "Returns the source location the operation was defined or derived " + "from.") .def("__iter__", [](PyOperationBase &self) { return PyRegionIterator(self.getOperation().getRef()); diff --git a/mlir/lib/CAPI/IR/IR.cpp b/mlir/lib/CAPI/IR/IR.cpp --- a/mlir/lib/CAPI/IR/IR.cpp +++ b/mlir/lib/CAPI/IR/IR.cpp @@ -346,6 +346,10 @@ return wrap(unwrap(op)->getContext()); } +MlirLocation mlirOperationGetLoc(MlirOperation op) { + return wrap(unwrap(op)->getLoc()); +} + MlirTypeID mlirOperationGetTypeID(MlirOperation op) { if (const auto *abstractOp = unwrap(op)->getAbstractOperation()) { return wrap(abstractOp->typeID); diff --git a/mlir/test/python/ir/operation.py b/mlir/test/python/ir/operation.py --- a/mlir/test/python/ir/operation.py +++ b/mlir/test/python/ir/operation.py @@ -728,3 +728,15 @@ # Ensure we can create another operation Operation.create("custom.op2") + + +# CHECK-LABEL: TEST: testOperationLoc +@run +def testOperationLoc(): + ctx = Context() + ctx.allow_unregistered_dialects = True + with ctx: + loc = Location.name("loc") + op = Operation.create("custom.op", loc=loc) + assert op.loc == loc + assert op.operation.loc == loc