|
| 1 | +from mlir import rewrite, ir |
| 2 | +from mlir.dialects import ext, transform |
| 3 | + |
| 4 | + |
| 5 | +def register_and_load(context=None): |
| 6 | + TransformExtensionDialect.load() |
| 7 | + |
| 8 | + |
| 9 | +class TransformExtensionDialect(ext.Dialect, name="transform_ext"): |
| 10 | + @classmethod |
| 11 | + def load(cls, *args, **kwargs): |
| 12 | + super().load(*args, **kwargs) |
| 13 | + for op_cls in cls.operations: |
| 14 | + if hasattr(op_cls, "attach_interface_impls"): |
| 15 | + op_cls.attach_interface_impls() |
| 16 | + |
| 17 | + |
| 18 | +class PopulatePatternOp(TransformExtensionDialect.Operation, name="populate_pattern"): |
| 19 | + """An operation to populate a pattern set with a specific pattern. |
| 20 | +
|
| 21 | + To be used in the region of `transform.apply_patterns`.""" |
| 22 | + |
| 23 | + op_kind: ir.StringAttr |
| 24 | + pattern_name: ir.StringAttr |
| 25 | + priority: ir.IntegerAttr |
| 26 | + |
| 27 | + # A mapping from pattern names to their corresponding rewrite functions. |
| 28 | + # This should be populated by the users of this operation. In effect serves |
| 29 | + # as a registry for rewrite patterns that can be applied by this operation. |
| 30 | + name_to_rewrite_pattern = {} |
| 31 | + |
| 32 | + @classmethod |
| 33 | + def attach_interface_impls(cls, context=None): |
| 34 | + cls.PatternDescriptorOpInterfaceModel.attach( |
| 35 | + cls.OPERATION_NAME, context=context |
| 36 | + ) |
| 37 | + |
| 38 | + class PatternDescriptorOpInterfaceModel(transform.PatternDescriptorOpInterface): |
| 39 | + @staticmethod |
| 40 | + def populate_patterns( |
| 41 | + op: "PopulatePatternOp", |
| 42 | + patternset: rewrite.RewritePatternSet, |
| 43 | + ) -> None: |
| 44 | + patternset.add( |
| 45 | + op.op_kind.value, |
| 46 | + op.name_to_rewrite_pattern[op.pattern_name.value], |
| 47 | + benefit=op.priority.value, |
| 48 | + ) |
| 49 | + |
| 50 | + |
| 51 | +def populate_pattern( |
| 52 | + op_kind: str, pattern_name: str, priority: int |
| 53 | +) -> PopulatePatternOp: |
| 54 | + """Camelcase constructor for PopulatePatternOp.""" |
| 55 | + priority_attr = ir.IntegerAttr.get(ir.IntegerType.get_signless(32), priority) |
| 56 | + return PopulatePatternOp( |
| 57 | + op_kind=ir.StringAttr.get(op_kind), |
| 58 | + pattern_name=ir.StringAttr.get(pattern_name), |
| 59 | + priority=priority_attr, |
| 60 | + ) |
0 commit comments