|
| 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 | + |
| 11 | +def run(f): |
| 12 | + # Note, everything in this file is dumped to stderr because that's where |
| 13 | + # `IR Dump After` dumps too (so we can't cross the "streams") |
| 14 | + print("\nTEST:", f.__name__, file=sys.stderr) |
| 15 | + f() |
| 16 | + gc.collect() |
| 17 | + assert Context._get_live_count() == 0 |
| 18 | + |
| 19 | + |
| 20 | +def make_pdl_module(): |
| 21 | + with Location.unknown(): |
| 22 | + pdl_module = Module.create() |
| 23 | + with InsertionPoint(pdl_module.body): |
| 24 | + # Change all arith.addi with index types to arith.muli. |
| 25 | + @pdl.pattern(benefit=1, sym_name="addi_to_mul") |
| 26 | + def pat(): |
| 27 | + # Match arith.addi with index types. |
| 28 | + i64_type = pdl.TypeOp(IntegerType.get_signless(64)) |
| 29 | + operand0 = pdl.OperandOp(i64_type) |
| 30 | + operand1 = pdl.OperandOp(i64_type) |
| 31 | + op0 = pdl.OperationOp( |
| 32 | + name="arith.addi", args=[operand0, operand1], types=[i64_type] |
| 33 | + ) |
| 34 | + |
| 35 | + # Replace the matched op with arith.muli. |
| 36 | + @pdl.rewrite() |
| 37 | + def rew(): |
| 38 | + newOp = pdl.OperationOp( |
| 39 | + name="arith.muli", args=[operand0, operand1], types=[i64_type] |
| 40 | + ) |
| 41 | + pdl.ReplaceOp(op0, with_op=newOp) |
| 42 | + |
| 43 | + return pdl_module |
| 44 | + |
| 45 | + |
| 46 | +# CHECK-LABEL: TEST: testCustomPass |
| 47 | +@run |
| 48 | +def testCustomPass(): |
| 49 | + with Context(): |
| 50 | + pdl_module = make_pdl_module() |
| 51 | + frozen = PDLModule(pdl_module).freeze() |
| 52 | + |
| 53 | + module = ModuleOp.parse( |
| 54 | + r""" |
| 55 | + module { |
| 56 | + func.func @add(%a: i64, %b: i64) -> i64 { |
| 57 | + %sum = arith.addi %a, %b : i64 |
| 58 | + return %sum : i64 |
| 59 | + } |
| 60 | + } |
| 61 | + """ |
| 62 | + ) |
| 63 | + |
| 64 | + def run1(op): |
| 65 | + print("hello from pass 1!!!", file=sys.stderr) |
| 66 | + |
| 67 | + def run2(op): |
| 68 | + apply_patterns_and_fold_greedily_with_op(op, frozen) |
| 69 | + |
| 70 | + pm = PassManager("any") |
| 71 | + pm.enable_ir_printing() |
| 72 | + |
| 73 | + # CHECK: hello from pass 1!!! |
| 74 | + # CHECK-LABEL: Dump After CustomPass |
| 75 | + # CHECK: arith.muli |
| 76 | + pm.add_python_pass("CustomPass1", "", "", "", run1) |
| 77 | + pm.add_python_pass("CustomPass2", "", "", "", run2) |
| 78 | + # # CHECK-LABEL: Dump After ArithToLLVMConversionPass |
| 79 | + # # CHECK: llvm.mul |
| 80 | + pm.add("convert-arith-to-llvm") |
| 81 | + pm.run(module) |
0 commit comments