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 @@ -386,6 +386,9 @@ /// Prints an operation to stderr. MLIR_CAPI_EXPORTED void mlirOperationDump(MlirOperation op); +/// Verify the operation and return true if it passes, false if it fails. +MLIR_CAPI_EXPORTED bool mlirOperationVerify(MlirOperation op); + //===----------------------------------------------------------------------===// // Region API. //===----------------------------------------------------------------------===// diff --git a/mlir/lib/Bindings/Python/IRModules.cpp b/mlir/lib/Bindings/Python/IRModules.cpp --- a/mlir/lib/Bindings/Python/IRModules.cpp +++ b/mlir/lib/Bindings/Python/IRModules.cpp @@ -809,6 +809,12 @@ operation.checkValid(); if (fileObject.is_none()) fileObject = py::module::import("sys").attr("stdout"); + + if (!printGenericOpForm && !mlirOperationVerify(operation)) { + fileObject.attr("write")("// Verification failed, printing generic form\n"); + printGenericOpForm = true; + } + MlirOpPrintingFlags flags = mlirOpPrintingFlagsCreate(); if (largeElementsLimit) mlirOpPrintingFlagsElideLargeElementsAttrs(flags, *largeElementsLimit); 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 @@ -17,6 +17,7 @@ #include "mlir/IR/Dialect.h" #include "mlir/IR/Operation.h" #include "mlir/IR/Types.h" +#include "mlir/IR/Verifier.h" #include "mlir/Parser.h" using namespace mlir; @@ -339,6 +340,10 @@ void mlirOperationDump(MlirOperation op) { return unwrap(op)->dump(); } +bool mlirOperationVerify(MlirOperation op) { + return succeeded(verify(unwrap(op))); +} + //===----------------------------------------------------------------------===// // Region API. //===----------------------------------------------------------------------===// diff --git a/mlir/test/Bindings/Python/ir_operation.py b/mlir/test/Bindings/Python/ir_operation.py --- a/mlir/test/Bindings/Python/ir_operation.py +++ b/mlir/test/Bindings/Python/ir_operation.py @@ -537,3 +537,17 @@ print(module.body.operations[2]) run(testSingleResultProperty) + +# CHECK-LABEL: TEST: testPrintInvalidOperation +def testPrintInvalidOperation(): + ctx = Context() + with Location.unknown(ctx): + module = Operation.create("module", regions=1) + # This block does not have a terminator, it may crash the custom printer. + # Verify that we fallback to the generic printer for safety. + block = module.regions[0].blocks.append() + print(module) + # CHECK: // Verification failed, printing generic form + # CHECK: "module"() ( { + # CHECK: }) : () -> () +run(testPrintInvalidOperation)