[Mlir-commits] [mlir] [MLIR][Python] Call `notifyOperationInserted` while constructing new op in rewrite patterns (PR #163694)
llvmlistbot at llvm.org
llvmlistbot at llvm.org
Thu Oct 16 20:29:30 PDT 2025
================
@@ -202,7 +207,15 @@ class PyRewritePatternSet {
PyMlirContext::forContext(mlirOperationGetContext(op));
nb::object opView = PyOperation::forOperation(ctx, op)->createOpView();
- nb::object res = f(opView, PyPatternRewriter(rewriter));
+ PyPatternRewriter pyRewriter(rewriter);
+ nb::object listener = nb::cast(pyRewriter.getListener());
+
+ listener.attr("__enter__")();
+ auto exit = llvm::make_scope_exit([listener] {
+ listener.attr("__exit__")(nb::none(), nb::none(), nb::none());
+ });
----------------
PragmaTwice wrote:
ahhh I think I've got some clue about the inconsistency between our understanding.
I want to explain in a gradual way why we need a global state (or stack). Firstly, we can just throw these stack/state things if we write code like this:
```python
def match_and_rewrite(op, rewriter):
new_op = arith.add(op.lhs, op.rhs, listener=rewriter.listener)
# or just: new_op = arith.add(op.lhs, op.rhs, rewriter=rewriter)
...
```
Here we pass the listener (or the rewriter) into the op constructor so we don't need any global state, and then we can use this listener to call `notify..` methods. But in the initial I want to avoid such passing, so some code like this:
```python
def match_and_rewrite(op, rewriter):
new_op = arith.add(op.lhs, op.rhs) # no listener/rewriter passing, so we need to retrieve it from some global state!
...
```
And then, obviously, we need some global state to know which is the current listener that we need to obtain in the op constructor to call notify methods.
https://github.com/llvm/llvm-project/pull/163694
More information about the Mlir-commits
mailing list