|
| 1 | +# RUN: %PYTHON %s 2>&1 | FileCheck %s |
| 2 | + |
| 3 | +import gc, sys |
| 4 | +from mlir.ir import * |
| 5 | +from mlir.passmanager import * |
| 6 | +from mlir.dialects.builtin import ModuleOp |
| 7 | +from mlir.dialects import pdl |
| 8 | +from mlir.rewrite import * |
| 9 | + |
| 10 | +def log(*args): |
| 11 | + print(*args, file=sys.stderr) |
| 12 | + sys.stderr.flush() |
| 13 | + |
| 14 | + |
| 15 | +def run(f): |
| 16 | + log("\nTEST:", f.__name__) |
| 17 | + f() |
| 18 | + gc.collect() |
| 19 | + assert Context._get_live_count() == 0 |
| 20 | + |
| 21 | +def make_pdl_module(): |
| 22 | + with Location.unknown(): |
| 23 | + pdl_module = Module.create() |
| 24 | + with InsertionPoint(pdl_module.body): |
| 25 | + # Change all arith.addi with index types to arith.muli. |
| 26 | + @pdl.pattern(benefit=1, sym_name="addi_to_mul") |
| 27 | + def pat(): |
| 28 | + # Match arith.addi with index types. |
| 29 | + index_type = pdl.TypeOp(IndexType.get()) |
| 30 | + operand0 = pdl.OperandOp(index_type) |
| 31 | + operand1 = pdl.OperandOp(index_type) |
| 32 | + op0 = pdl.OperationOp( |
| 33 | + name="arith.addi", args=[operand0, operand1], types=[index_type] |
| 34 | + ) |
| 35 | + |
| 36 | + # Replace the matched op with arith.muli. |
| 37 | + @pdl.rewrite() |
| 38 | + def rew(): |
| 39 | + newOp = pdl.OperationOp( |
| 40 | + name="arith.muli", args=[operand0, operand1], types=[index_type] |
| 41 | + ) |
| 42 | + pdl.ReplaceOp(op0, with_op=newOp) |
| 43 | + |
| 44 | + return pdl_module |
| 45 | + |
| 46 | +# CHECK-LABEL: TEST: testCustomPass |
| 47 | +@run |
| 48 | +def testCustomPass(): |
| 49 | + with Context(): |
| 50 | + pdl_module = make_pdl_module() |
| 51 | + |
| 52 | + class CustomPass(Pass): |
| 53 | + def __init__(self): |
| 54 | + super().__init__("CustomPass", op_name="builtin.module") |
| 55 | + def run(self, m): |
| 56 | + frozen = PDLModule(pdl_module).freeze() |
| 57 | + apply_patterns_and_fold_greedily_for_op(m, frozen) |
| 58 | + |
| 59 | + module = ModuleOp.parse(r""" |
| 60 | + module { |
| 61 | + func.func @add(%a: index, %b: index) -> index { |
| 62 | + %sum = arith.addi %a, %b : index |
| 63 | + return %sum : index |
| 64 | + } |
| 65 | + } |
| 66 | + """) |
| 67 | + |
| 68 | + # CHECK-LABEL: Dump After CustomPass |
| 69 | + # CHECK: arith.muli |
| 70 | + pm = PassManager('any') |
| 71 | + pm.enable_ir_printing() |
| 72 | + pm.add(CustomPass()) |
| 73 | + pm.run(module) |
0 commit comments