[Mlir-commits] [mlir] [MLIR][Python] Make the TypeID allocator global defined in `PassManager.add` (PR #162594)

llvmlistbot at llvm.org llvmlistbot at llvm.org
Wed Oct 8 20:57:51 PDT 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-mlir

Author: Twice (PragmaTwice)

<details>
<summary>Changes</summary>

Previously, each time we called `PassManager.add(python_pass_callable)`, a new `TypeID` allocator was created and never released afterward. This approach could potentially lead to some issues. In this PR, we introduce a global `TypeIDAllocator` that is shared across all `add` calls to allocate IDs.


---
Full diff: https://github.com/llvm/llvm-project/pull/162594.diff


1 Files Affected:

- (modified) mlir/lib/Bindings/Python/Pass.cpp (+18-3) 


``````````diff
diff --git a/mlir/lib/Bindings/Python/Pass.cpp b/mlir/lib/Bindings/Python/Pass.cpp
index e489585fd5f50..e371a8cf76a9d 100644
--- a/mlir/lib/Bindings/Python/Pass.cpp
+++ b/mlir/lib/Bindings/Python/Pass.cpp
@@ -52,6 +52,23 @@ class PyPassManager {
   MlirPassManager passManager;
 };
 
+class PyTypeIDAllocator {
+public:
+  PyTypeIDAllocator() : allocator(mlirTypeIDAllocatorCreate()) {}
+  ~PyTypeIDAllocator() {
+    if (!allocator.ptr)
+      mlirTypeIDAllocatorDestroy(allocator);
+  }
+
+  MlirTypeIDAllocator get() { return allocator; }
+  MlirTypeID allocate() { return mlirTypeIDAllocatorAllocateTypeID(allocator); }
+
+private:
+  MlirTypeIDAllocator allocator;
+};
+
+PyTypeIDAllocator globalTypeIDAllocator;
+
 } // namespace
 
 /// Create the `mlir.passmanager` here.
@@ -181,9 +198,7 @@ void mlir::python::populatePassManagerSubmodule(nb::module_ &m) {
               name = nb::cast<std::string>(
                   nb::borrow<nb::str>(run.attr("__name__")));
             }
-            MlirTypeIDAllocator typeIDAllocator = mlirTypeIDAllocatorCreate();
-            MlirTypeID passID =
-                mlirTypeIDAllocatorAllocateTypeID(typeIDAllocator);
+            MlirTypeID passID = globalTypeIDAllocator.allocate();
             MlirExternalPassCallbacks callbacks;
             callbacks.construct = [](void *obj) {
               (void)nb::handle(static_cast<PyObject *>(obj)).inc_ref();

``````````

</details>


https://github.com/llvm/llvm-project/pull/162594


More information about the Mlir-commits mailing list