[Mlir-commits] [mlir] fa45b2f - [mlir][Python] Add `__hash__` implementation for Block.

Mike Urbach llvmlistbot at llvm.org
Tue Dec 13 11:03:08 PST 2022


Author: Mike Urbach
Date: 2022-12-13T12:03:00-07:00
New Revision: fa45b2fb2aefb5b942f022bc5a10ec97676a7868

URL: https://github.com/llvm/llvm-project/commit/fa45b2fb2aefb5b942f022bc5a10ec97676a7868
DIFF: https://github.com/llvm/llvm-project/commit/fa45b2fb2aefb5b942f022bc5a10ec97676a7868.diff

LOG: [mlir][Python] Add `__hash__` implementation for Block.

This allows us to hash Blocks and use them in sets or parts of larger
hashable objects. The implementation is the same as other core IR
constructs: the C API object's pointer is hashed.

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

Added: 
    

Modified: 
    mlir/lib/Bindings/Python/IRCore.cpp
    mlir/test/python/ir/blocks.py

Removed: 
    


################################################################################
diff  --git a/mlir/lib/Bindings/Python/IRCore.cpp b/mlir/lib/Bindings/Python/IRCore.cpp
index 8c25f6e8153d0..0a32ff598feb6 100644
--- a/mlir/lib/Bindings/Python/IRCore.cpp
+++ b/mlir/lib/Bindings/Python/IRCore.cpp
@@ -2892,6 +2892,10 @@ void mlir::python::populateIRCore(py::module &m) {
              return self.get().ptr == other.get().ptr;
            })
       .def("__eq__", [](PyBlock &self, py::object &other) { return false; })
+      .def("__hash__",
+           [](PyBlock &self) {
+             return static_cast<size_t>(llvm::hash_value(self.get().ptr));
+           })
       .def(
           "__str__",
           [](PyBlock &self) {

diff  --git a/mlir/test/python/ir/blocks.py b/mlir/test/python/ir/blocks.py
index 411b770f563b4..47aafca7e2d56 100644
--- a/mlir/test/python/ir/blocks.py
+++ b/mlir/test/python/ir/blocks.py
@@ -94,3 +94,17 @@ def testBlockMove():
       block.append_to(realop.operation.regions[0])
       dummy.operation.erase()
     print(module)
+
+
+# CHECK-LABEL: TEST: testBlockHash
+ at run
+def testBlockHash():
+  with Context() as ctx, Location.unknown():
+    ctx.allow_unregistered_dialects = True
+    module = Module.create()
+    f32 = F32Type.get()
+    with InsertionPoint(module.body):
+      dummy = Operation.create("dummy", regions=1)
+      block1 = Block.create_at_start(dummy.operation.regions[0], [f32])
+      block2 = Block.create_at_start(dummy.operation.regions[0], [f32])
+      assert hash(block1) != hash(block2)


        


More information about the Mlir-commits mailing list