Skip to content

Pdl

pdl

AnyPDLType = AttributeType | OperationType | TypeType | ValueType module-attribute

AnyPDLTypeConstr = base(AttributeType) | base(OperationType) | base(TypeType) | base(ValueType) module-attribute

PDL = Dialect('pdl', [ApplyNativeConstraintOp, ApplyNativeRewriteOp, AttributeOp, OperandOp, EraseOp, OperandsOp, OperationOp, PatternOp, RangeOp, ReplaceOp, ResultOp, ResultsOp, RewriteOp, TypeOp, TypesOp], [AttributeType, OperationType, TypeType, ValueType, RangeType]) module-attribute

AttributeType dataclass

Bases: ParametrizedAttribute, TypeAttribute

Source code in xdsl/dialects/pdl.py
113
114
115
@irdl_attr_definition
class AttributeType(ParametrizedAttribute, TypeAttribute):
    name = "pdl.attribute"

name = 'pdl.attribute' class-attribute instance-attribute

OperationType dataclass

Bases: ParametrizedAttribute, TypeAttribute

Source code in xdsl/dialects/pdl.py
118
119
120
@irdl_attr_definition
class OperationType(ParametrizedAttribute, TypeAttribute):
    name = "pdl.operation"

name = 'pdl.operation' class-attribute instance-attribute

TypeType dataclass

Bases: ParametrizedAttribute, TypeAttribute

Source code in xdsl/dialects/pdl.py
123
124
125
@irdl_attr_definition
class TypeType(ParametrizedAttribute, TypeAttribute):
    name = "pdl.type"

name = 'pdl.type' class-attribute instance-attribute

ValueType dataclass

Bases: ParametrizedAttribute, TypeAttribute

Source code in xdsl/dialects/pdl.py
128
129
130
@irdl_attr_definition
class ValueType(ParametrizedAttribute, TypeAttribute):
    name = "pdl.value"

name = 'pdl.value' class-attribute instance-attribute

RangeType dataclass

Bases: ParametrizedAttribute, TypeAttribute, Generic[_RangeT]

Source code in xdsl/dialects/pdl.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
@irdl_attr_definition
class RangeType(ParametrizedAttribute, TypeAttribute, Generic[_RangeT]):
    name = "pdl.range"
    element_type: _RangeT

    @classmethod
    def parse_parameters(cls, parser: AttrParser) -> Sequence[Attribute]:
        parser.parse_punctuation("<")
        if parser.parse_optional_keyword("attribute") is not None:
            element_type = AttributeType()
        elif parser.parse_optional_keyword("operation") is not None:
            element_type = OperationType()
        elif parser.parse_optional_keyword("type") is not None:
            element_type = TypeType()
        elif parser.parse_optional_keyword("value") is not None:
            element_type = ValueType()
        else:
            parser.raise_error("expected PDL element type for range")
        parser.parse_punctuation(">")
        return [element_type]

    def print_parameters(self, printer: Printer) -> None:
        match self.element_type:
            case AttributeType():
                printer.print_string("<attribute>")
            case OperationType():
                printer.print_string("<operation>")
            case TypeType():
                printer.print_string("<type>")
            case ValueType():
                printer.print_string("<value>")

name = 'pdl.range' class-attribute instance-attribute

element_type: _RangeT instance-attribute

parse_parameters(parser: AttrParser) -> Sequence[Attribute] classmethod

Source code in xdsl/dialects/pdl.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
@classmethod
def parse_parameters(cls, parser: AttrParser) -> Sequence[Attribute]:
    parser.parse_punctuation("<")
    if parser.parse_optional_keyword("attribute") is not None:
        element_type = AttributeType()
    elif parser.parse_optional_keyword("operation") is not None:
        element_type = OperationType()
    elif parser.parse_optional_keyword("type") is not None:
        element_type = TypeType()
    elif parser.parse_optional_keyword("value") is not None:
        element_type = ValueType()
    else:
        parser.raise_error("expected PDL element type for range")
    parser.parse_punctuation(">")
    return [element_type]

print_parameters(printer: Printer) -> None

Source code in xdsl/dialects/pdl.py
166
167
168
169
170
171
172
173
174
175
def print_parameters(self, printer: Printer) -> None:
    match self.element_type:
        case AttributeType():
            printer.print_string("<attribute>")
        case OperationType():
            printer.print_string("<operation>")
        case TypeType():
            printer.print_string("<type>")
        case ValueType():
            printer.print_string("<value>")

ApplyNativeConstraintOp

Bases: IRDLOperation

See external documentation.

Source code in xdsl/dialects/pdl.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
@irdl_op_definition
class ApplyNativeConstraintOp(IRDLOperation):
    """
    See external [documentation](https://mlir.llvm.org/docs/Dialects/PDLOps/#pdlapply_native_constraint-pdlapplynativeconstraintop).
    """

    name = "pdl.apply_native_constraint"
    constraint_name = prop_def(StringAttr, prop_name="name")
    is_negated = prop_def(
        BoolAttr, prop_name="isNegated", default_value=BoolAttr.from_bool(False)
    )
    args = var_operand_def(AnyPDLTypeConstr | base(RangeType[AnyPDLType]))
    res = var_result_def(AnyPDLTypeConstr | base(RangeType[AnyPDLType]))

    irdl_options = (ParsePropInAttrDict(),)

    assembly_format = "$name `(` $args `:` type($args) `)` (`:` type($res)^)? attr-dict"

    def __init__(
        self,
        name: str | StringAttr,
        args: Sequence[SSAValue],
        result_types: Sequence[Attribute],
        is_negated: bool = False,
    ) -> None:
        if isinstance(name, str):
            name = StringAttr(name)
        super().__init__(
            result_types=[result_types],
            operands=[args],
            properties={"name": name, "isNegated": BoolAttr.from_bool(is_negated)},
        )

name = 'pdl.apply_native_constraint' class-attribute instance-attribute

constraint_name = prop_def(StringAttr, prop_name='name') class-attribute instance-attribute

is_negated = prop_def(BoolAttr, prop_name='isNegated', default_value=(BoolAttr.from_bool(False))) class-attribute instance-attribute

args = var_operand_def(AnyPDLTypeConstr | base(RangeType[AnyPDLType])) class-attribute instance-attribute

res = var_result_def(AnyPDLTypeConstr | base(RangeType[AnyPDLType])) class-attribute instance-attribute

irdl_options = (ParsePropInAttrDict(),) class-attribute instance-attribute

assembly_format = '$name `(` $args `:` type($args) `)` (`:` type($res)^)? attr-dict' class-attribute instance-attribute

__init__(name: str | StringAttr, args: Sequence[SSAValue], result_types: Sequence[Attribute], is_negated: bool = False) -> None

Source code in xdsl/dialects/pdl.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def __init__(
    self,
    name: str | StringAttr,
    args: Sequence[SSAValue],
    result_types: Sequence[Attribute],
    is_negated: bool = False,
) -> None:
    if isinstance(name, str):
        name = StringAttr(name)
    super().__init__(
        result_types=[result_types],
        operands=[args],
        properties={"name": name, "isNegated": BoolAttr.from_bool(is_negated)},
    )

ApplyNativeRewriteOp

Bases: IRDLOperation

See external documentation.

Source code in xdsl/dialects/pdl.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
@irdl_op_definition
class ApplyNativeRewriteOp(IRDLOperation):
    """
    See external [documentation](https://mlir.llvm.org/docs/Dialects/PDLOps/#pdlapply_native_rewrite-pdlapplynativerewriteop).
    """

    name = "pdl.apply_native_rewrite"
    constraint_name = prop_def(StringAttr, prop_name="name")
    args = var_operand_def(AnyPDLTypeConstr | base(RangeType[AnyPDLType]))
    res = var_result_def(AnyPDLTypeConstr | base(RangeType[AnyPDLType]))

    def __init__(
        self,
        name: str | StringAttr,
        args: Sequence[SSAValue],
        result_types: Sequence[Attribute],
    ) -> None:
        if isinstance(name, str):
            name = StringAttr(name)
        super().__init__(
            result_types=[result_types],
            operands=[args],
            properties={"name": name},
        )

    @classmethod
    def parse(cls, parser: Parser) -> ApplyNativeRewriteOp:
        name = parser.parse_str_literal()
        parser.parse_punctuation("(")
        operands = parse_operands_with_types(parser)
        parser.parse_punctuation(")")
        result_types = []
        if parser.parse_optional_punctuation(":") is not None:
            result_types = parser.parse_comma_separated_list(
                Parser.Delimiter.NONE, parser.parse_attribute
            )
        return ApplyNativeRewriteOp(name, operands, result_types)

    def print(self, printer: Printer) -> None:
        printer.print_string(" ")
        printer.print_string_literal(self.constraint_name.data)
        with printer.in_parens():
            print_operands_with_types(printer, self.operands)
        if len(self.results) != 0:
            printer.print_string(" : ")
            printer.print_list(self.result_types, printer.print_attribute)

name = 'pdl.apply_native_rewrite' class-attribute instance-attribute

constraint_name = prop_def(StringAttr, prop_name='name') class-attribute instance-attribute

args = var_operand_def(AnyPDLTypeConstr | base(RangeType[AnyPDLType])) class-attribute instance-attribute

res = var_result_def(AnyPDLTypeConstr | base(RangeType[AnyPDLType])) class-attribute instance-attribute

__init__(name: str | StringAttr, args: Sequence[SSAValue], result_types: Sequence[Attribute]) -> None

Source code in xdsl/dialects/pdl.py
223
224
225
226
227
228
229
230
231
232
233
234
235
def __init__(
    self,
    name: str | StringAttr,
    args: Sequence[SSAValue],
    result_types: Sequence[Attribute],
) -> None:
    if isinstance(name, str):
        name = StringAttr(name)
    super().__init__(
        result_types=[result_types],
        operands=[args],
        properties={"name": name},
    )

parse(parser: Parser) -> ApplyNativeRewriteOp classmethod

Source code in xdsl/dialects/pdl.py
237
238
239
240
241
242
243
244
245
246
247
248
@classmethod
def parse(cls, parser: Parser) -> ApplyNativeRewriteOp:
    name = parser.parse_str_literal()
    parser.parse_punctuation("(")
    operands = parse_operands_with_types(parser)
    parser.parse_punctuation(")")
    result_types = []
    if parser.parse_optional_punctuation(":") is not None:
        result_types = parser.parse_comma_separated_list(
            Parser.Delimiter.NONE, parser.parse_attribute
        )
    return ApplyNativeRewriteOp(name, operands, result_types)

print(printer: Printer) -> None

Source code in xdsl/dialects/pdl.py
250
251
252
253
254
255
256
257
def print(self, printer: Printer) -> None:
    printer.print_string(" ")
    printer.print_string_literal(self.constraint_name.data)
    with printer.in_parens():
        print_operands_with_types(printer, self.operands)
    if len(self.results) != 0:
        printer.print_string(" : ")
        printer.print_list(self.result_types, printer.print_attribute)

AttributeOp

Bases: IRDLOperation

See external documentation. https://mlir.llvm.org/docs/Dialects/PDLOps/#pdlattribute-pdlattributeop

Source code in xdsl/dialects/pdl.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
@irdl_op_definition
class AttributeOp(IRDLOperation):
    """
    See external [documentation](https://mlir.llvm.org/docs/Dialects/PDLOps/#pdlattribute-pdlattributeop).
    https://mlir.llvm.org/docs/Dialects/PDLOps/#pdlattribute-pdlattributeop
    """

    name = "pdl.attribute"
    value = opt_prop_def()
    value_type = opt_operand_def(TypeType)
    output = result_def(AttributeType)

    assembly_format = "(`:` $value_type^)? (`=` $value^)? attr-dict-with-keyword"

    def verify_(self):
        if self.value is not None and self.value_type is not None:
            raise VerifyException(
                f"{self.name} cannot both specify an expected attribute "
                "via a constant value and an expected type."
            )
        if self.value is None and isinstance(self.parent_op(), RewriteOp):
            raise VerifyException(
                "expected constant value when specified within a `pdl.rewrite`"
            )
        verify_has_binding_use(self)

    def __init__(self, value: Attribute | SSAValue | None = None) -> None:
        """
        The given value is either the expected attribute, if given an attribute, or the
        expected attribute type, if given an SSAValue.
        """
        properties: dict[str, Attribute] = {}
        operands: list[SSAValue | None] = [None]
        if isinstance(value, Attribute):
            properties["value"] = value
        elif isinstance(value, SSAValue):
            operands = [value]

        super().__init__(
            operands=operands, properties=properties, result_types=[AttributeType()]
        )

name = 'pdl.attribute' class-attribute instance-attribute

value = opt_prop_def() class-attribute instance-attribute

value_type = opt_operand_def(TypeType) class-attribute instance-attribute

output = result_def(AttributeType) class-attribute instance-attribute

assembly_format = '(`:` $value_type^)? (`=` $value^)? attr-dict-with-keyword' class-attribute instance-attribute

verify_()

Source code in xdsl/dialects/pdl.py
274
275
276
277
278
279
280
281
282
283
284
def verify_(self):
    if self.value is not None and self.value_type is not None:
        raise VerifyException(
            f"{self.name} cannot both specify an expected attribute "
            "via a constant value and an expected type."
        )
    if self.value is None and isinstance(self.parent_op(), RewriteOp):
        raise VerifyException(
            "expected constant value when specified within a `pdl.rewrite`"
        )
    verify_has_binding_use(self)

__init__(value: Attribute | SSAValue | None = None) -> None

The given value is either the expected attribute, if given an attribute, or the expected attribute type, if given an SSAValue.

Source code in xdsl/dialects/pdl.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
def __init__(self, value: Attribute | SSAValue | None = None) -> None:
    """
    The given value is either the expected attribute, if given an attribute, or the
    expected attribute type, if given an SSAValue.
    """
    properties: dict[str, Attribute] = {}
    operands: list[SSAValue | None] = [None]
    if isinstance(value, Attribute):
        properties["value"] = value
    elif isinstance(value, SSAValue):
        operands = [value]

    super().__init__(
        operands=operands, properties=properties, result_types=[AttributeType()]
    )

EraseOp

Bases: IRDLOperation

See external documentation.

Source code in xdsl/dialects/pdl.py
303
304
305
306
307
308
309
310
311
312
313
314
315
@irdl_op_definition
class EraseOp(IRDLOperation):
    """
    See external [documentation](https://mlir.llvm.org/docs/Dialects/PDLOps/#pdlerase-pdleraseop).
    """

    name = "pdl.erase"
    op_value = operand_def(OperationType)

    assembly_format = "$op_value attr-dict"

    def __init__(self, op_value: SSAValue) -> None:
        super().__init__(operands=[op_value])

name = 'pdl.erase' class-attribute instance-attribute

op_value = operand_def(OperationType) class-attribute instance-attribute

assembly_format = '$op_value attr-dict' class-attribute instance-attribute

__init__(op_value: SSAValue) -> None

Source code in xdsl/dialects/pdl.py
314
315
def __init__(self, op_value: SSAValue) -> None:
    super().__init__(operands=[op_value])

OperandOp

Bases: IRDLOperation

See external documentation.

Source code in xdsl/dialects/pdl.py
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
@irdl_op_definition
class OperandOp(IRDLOperation):
    """
    See external [documentation](https://mlir.llvm.org/docs/Dialects/PDLOps/#pdloperand-pdloperandop).
    """

    name = "pdl.operand"
    value_type = opt_operand_def(TypeType)
    value = result_def(ValueType)

    assembly_format = "(`:` $value_type^)? attr-dict"

    def __init__(self, value_type: SSAValue | None = None) -> None:
        super().__init__(operands=[value_type], result_types=[ValueType()])

    def verify_(self):
        verify_has_binding_use(self)

name = 'pdl.operand' class-attribute instance-attribute

value_type = opt_operand_def(TypeType) class-attribute instance-attribute

value = result_def(ValueType) class-attribute instance-attribute

assembly_format = '(`:` $value_type^)? attr-dict' class-attribute instance-attribute

__init__(value_type: SSAValue | None = None) -> None

Source code in xdsl/dialects/pdl.py
330
331
def __init__(self, value_type: SSAValue | None = None) -> None:
    super().__init__(operands=[value_type], result_types=[ValueType()])

verify_()

Source code in xdsl/dialects/pdl.py
333
334
def verify_(self):
    verify_has_binding_use(self)

OperandsOp

Bases: IRDLOperation

See external documentation.

Source code in xdsl/dialects/pdl.py
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
@irdl_op_definition
class OperandsOp(IRDLOperation):
    """
    See external [documentation](https://mlir.llvm.org/docs/Dialects/PDLOps/#pdloperands-pdloperandsop).
    """

    name = "pdl.operands"
    value_type = opt_operand_def(RangeType[TypeType])
    value = result_def(RangeType[ValueType])

    assembly_format = "(`:` $value_type^)? attr-dict"

    def __init__(self, value_type: SSAValue | None) -> None:
        super().__init__(operands=[value_type], result_types=[RangeType(ValueType())])

    def verify_(self):
        verify_has_binding_use(self)

name = 'pdl.operands' class-attribute instance-attribute

value_type = opt_operand_def(RangeType[TypeType]) class-attribute instance-attribute

value = result_def(RangeType[ValueType]) class-attribute instance-attribute

assembly_format = '(`:` $value_type^)? attr-dict' class-attribute instance-attribute

__init__(value_type: SSAValue | None) -> None

Source code in xdsl/dialects/pdl.py
349
350
def __init__(self, value_type: SSAValue | None) -> None:
    super().__init__(operands=[value_type], result_types=[RangeType(ValueType())])

verify_()

Source code in xdsl/dialects/pdl.py
352
353
def verify_(self):
    verify_has_binding_use(self)

OperationOp

Bases: IRDLOperation

See external documentation.

Source code in xdsl/dialects/pdl.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
@irdl_op_definition
class OperationOp(IRDLOperation):
    """
    See external [documentation](https://mlir.llvm.org/docs/Dialects/PDLOps/#pdloperation-pdloperationop).
    """

    name = "pdl.operation"
    opName = opt_prop_def(StringAttr)
    attributeValueNames = prop_def(ArrayAttr[StringAttr])

    operand_values = var_operand_def(base(ValueType) | base(RangeType[ValueType]))
    attribute_values = var_operand_def(AttributeType)
    type_values = var_operand_def(base(TypeType) | base(RangeType[TypeType]))
    op = result_def(OperationType)

    irdl_options = (AttrSizedOperandSegments(as_property=True),)

    def __init__(
        self,
        op_name: str | StringAttr | None,
        attribute_value_names: Iterable[StringAttr] | None = None,
        operand_values: Sequence[SSAValue] | None = None,
        attribute_values: Sequence[SSAValue] | None = None,
        type_values: Sequence[SSAValue] | None = None,
    ):
        if isinstance(op_name, str):
            op_name = StringAttr(op_name)
        if attribute_value_names is not None:
            attribute_value_names = ArrayAttr(attribute_value_names)
        if attribute_value_names is None:
            attribute_value_names = ArrayAttr([])

        if operand_values is None:
            operand_values = []
        if attribute_values is None:
            attribute_values = []
        if type_values is None:
            type_values = []

        super().__init__(
            operands=[operand_values, attribute_values, type_values],
            result_types=[OperationType()],
            properties={
                "attributeValueNames": attribute_value_names,
                "opName": op_name,
            },
        )

    def verify_(self):
        is_within_rewrite: bool = isinstance(self.parent_op(), RewriteOp)
        if is_within_rewrite and self.opName is None:
            raise VerifyException(
                "must have an operation name when nested within a `pdl.rewrite`"
            )
        if len(self.attributeValueNames) != len(self.attribute_values):
            raise VerifyException(
                "expected the same number of attribute values and attribute "
                f"names, got {len(self.attributeValueNames)} names and "
                f"{len(self.attribute_values)} values"
            )
        verify_has_binding_use(self)

    @classmethod
    def parse(cls, parser: Parser) -> OperationOp:
        name = parser.parse_optional_str_literal()
        operands = []
        if parser.parse_optional_punctuation("(") is not None:
            operands = parse_operands_with_types(parser)
            parser.parse_punctuation(")")

        def parse_attribute_entry() -> tuple[str, SSAValue]:
            name = parser.parse_str_literal()
            parser.parse_punctuation("=")
            type = parser.parse_operand()
            return (name, type)

        attributes = parser.parse_optional_comma_separated_list(
            Parser.Delimiter.BRACES, parse_attribute_entry
        )
        if attributes is None:
            attributes = []
        attribute_names = [StringAttr(attr[0]) for attr in attributes]
        attribute_values = [attr[1] for attr in attributes]

        results = []
        if parser.parse_optional_punctuation("->"):
            parser.parse_punctuation("(")
            results = parse_operands_with_types(parser)
            parser.parse_punctuation(")")

        return OperationOp(name, attribute_names, operands, attribute_values, results)

    def print(self, printer: Printer) -> None:
        if self.opName is not None:
            printer.print_string(" ")
            printer.print_attribute(self.opName)

        if len(self.operand_values) != 0:
            printer.print_string(" ")
            with printer.in_parens():
                print_operands_with_types(printer, self.operand_values)

        def print_attribute_entry(entry: tuple[StringAttr, SSAValue]):
            printer.print_attribute(entry[0])
            printer.print_string(" = ")
            printer.print_ssa_value(entry[1])

        if len(self.attributeValueNames) != 0:
            printer.print_string(" ")
            with printer.in_braces():
                printer.print_list(
                    zip(self.attributeValueNames, self.attribute_values),
                    print_attribute_entry,
                )

        if len(self.type_values) != 0:
            printer.print_string(" -> ")
            with printer.in_parens():
                print_operands_with_types(printer, self.type_values)

name = 'pdl.operation' class-attribute instance-attribute

opName = opt_prop_def(StringAttr) class-attribute instance-attribute

attributeValueNames = prop_def(ArrayAttr[StringAttr]) class-attribute instance-attribute

operand_values = var_operand_def(base(ValueType) | base(RangeType[ValueType])) class-attribute instance-attribute

attribute_values = var_operand_def(AttributeType) class-attribute instance-attribute

type_values = var_operand_def(base(TypeType) | base(RangeType[TypeType])) class-attribute instance-attribute

op = result_def(OperationType) class-attribute instance-attribute

irdl_options = (AttrSizedOperandSegments(as_property=True),) class-attribute instance-attribute

__init__(op_name: str | StringAttr | None, attribute_value_names: Iterable[StringAttr] | None = None, operand_values: Sequence[SSAValue] | None = None, attribute_values: Sequence[SSAValue] | None = None, type_values: Sequence[SSAValue] | None = None)

Source code in xdsl/dialects/pdl.py
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
def __init__(
    self,
    op_name: str | StringAttr | None,
    attribute_value_names: Iterable[StringAttr] | None = None,
    operand_values: Sequence[SSAValue] | None = None,
    attribute_values: Sequence[SSAValue] | None = None,
    type_values: Sequence[SSAValue] | None = None,
):
    if isinstance(op_name, str):
        op_name = StringAttr(op_name)
    if attribute_value_names is not None:
        attribute_value_names = ArrayAttr(attribute_value_names)
    if attribute_value_names is None:
        attribute_value_names = ArrayAttr([])

    if operand_values is None:
        operand_values = []
    if attribute_values is None:
        attribute_values = []
    if type_values is None:
        type_values = []

    super().__init__(
        operands=[operand_values, attribute_values, type_values],
        result_types=[OperationType()],
        properties={
            "attributeValueNames": attribute_value_names,
            "opName": op_name,
        },
    )

verify_()

Source code in xdsl/dialects/pdl.py
404
405
406
407
408
409
410
411
412
413
414
415
416
def verify_(self):
    is_within_rewrite: bool = isinstance(self.parent_op(), RewriteOp)
    if is_within_rewrite and self.opName is None:
        raise VerifyException(
            "must have an operation name when nested within a `pdl.rewrite`"
        )
    if len(self.attributeValueNames) != len(self.attribute_values):
        raise VerifyException(
            "expected the same number of attribute values and attribute "
            f"names, got {len(self.attributeValueNames)} names and "
            f"{len(self.attribute_values)} values"
        )
    verify_has_binding_use(self)

parse(parser: Parser) -> OperationOp classmethod

Source code in xdsl/dialects/pdl.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
@classmethod
def parse(cls, parser: Parser) -> OperationOp:
    name = parser.parse_optional_str_literal()
    operands = []
    if parser.parse_optional_punctuation("(") is not None:
        operands = parse_operands_with_types(parser)
        parser.parse_punctuation(")")

    def parse_attribute_entry() -> tuple[str, SSAValue]:
        name = parser.parse_str_literal()
        parser.parse_punctuation("=")
        type = parser.parse_operand()
        return (name, type)

    attributes = parser.parse_optional_comma_separated_list(
        Parser.Delimiter.BRACES, parse_attribute_entry
    )
    if attributes is None:
        attributes = []
    attribute_names = [StringAttr(attr[0]) for attr in attributes]
    attribute_values = [attr[1] for attr in attributes]

    results = []
    if parser.parse_optional_punctuation("->"):
        parser.parse_punctuation("(")
        results = parse_operands_with_types(parser)
        parser.parse_punctuation(")")

    return OperationOp(name, attribute_names, operands, attribute_values, results)

print(printer: Printer) -> None

Source code in xdsl/dialects/pdl.py
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
def print(self, printer: Printer) -> None:
    if self.opName is not None:
        printer.print_string(" ")
        printer.print_attribute(self.opName)

    if len(self.operand_values) != 0:
        printer.print_string(" ")
        with printer.in_parens():
            print_operands_with_types(printer, self.operand_values)

    def print_attribute_entry(entry: tuple[StringAttr, SSAValue]):
        printer.print_attribute(entry[0])
        printer.print_string(" = ")
        printer.print_ssa_value(entry[1])

    if len(self.attributeValueNames) != 0:
        printer.print_string(" ")
        with printer.in_braces():
            printer.print_list(
                zip(self.attributeValueNames, self.attribute_values),
                print_attribute_entry,
            )

    if len(self.type_values) != 0:
        printer.print_string(" -> ")
        with printer.in_parens():
            print_operands_with_types(printer, self.type_values)

PatternOp

Bases: IRDLOperation

See external documentation.

Source code in xdsl/dialects/pdl.py
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
@irdl_op_definition
class PatternOp(IRDLOperation):
    """
    See external [documentation](https://mlir.llvm.org/docs/Dialects/PDLOps/#pdlpattern-pdlpatternop).
    """

    name = "pdl.pattern"
    benefit = prop_def(IntegerAttr[I16])
    sym_name = opt_prop_def(StringAttr)
    body = region_def("single_block")

    traits = traits_def(OptionalSymbolOpInterface())

    def __init__(
        self,
        benefit: int | IntegerAttr[IntegerType],
        sym_name: str | StringAttr | None,
        body: Region | None = None,
    ):
        if isinstance(benefit, int):
            benefit = IntegerAttr(benefit, 16)
        if isinstance(sym_name, str):
            sym_name = StringAttr(sym_name)
        if body is None:
            body = Region(Block())
        super().__init__(
            properties={
                "benefit": benefit,
                "sym_name": sym_name,
            },
            regions=[body],
            result_types=[],
        )

    def verify_(self):
        # Check for the correct terminator.
        if not isinstance(self.body.block.last_op, RewriteOp):
            raise VerifyException("expected body to terminate with a `pdl.rewrite`")

        # Check that there is at least one `pdl.operation`.
        if not any(isinstance(op, OperationOp) for op in self.body.block.ops):
            raise VerifyException(
                "the pattern must contain at least one `pdl.operation`"
            )

        # Get the connected component by traversing the graph in the first
        # PDL operation, operand, or result used in a `pdl.rewrite`. The other
        # operations will be detected via other means with a better error handling
        # (expected bindable user).
        first = True
        visited: set[Operation] = set()
        for op in self.body.block.ops:
            if not isinstance(
                op, OperandOp | OperandsOp | ResultOp | ResultsOp | OperationOp
            ):
                continue
            if not _has_user_in_rewrite(op):
                continue

            if first:
                first = False
                _visit_pdl_ops(op, visited)
            if op not in visited:
                raise VerifyException(
                    "Operations in a `pdl.pattern` must form a connected component"
                )

    @classmethod
    def parse(cls, parser: Parser) -> PatternOp:
        name = parser.parse_optional_symbol_name()
        parser.parse_punctuation(":")
        parser.parse_keyword("benefit")
        parser.parse_punctuation("(")
        benefit = parser.parse_integer()
        parser.parse_punctuation(")")
        body = parser.parse_region()
        return PatternOp(benefit, name, body)

    def print(self, printer: Printer) -> None:
        if self.sym_name is not None:
            printer.print_string(" @")
            printer.print_string(self.sym_name.data)
        printer.print_string(f" : benefit({self.benefit.value.data}) ")
        printer.print_region(self.body)

name = 'pdl.pattern' class-attribute instance-attribute

benefit = prop_def(IntegerAttr[I16]) class-attribute instance-attribute

sym_name = opt_prop_def(StringAttr) class-attribute instance-attribute

body = region_def('single_block') class-attribute instance-attribute

traits = traits_def(OptionalSymbolOpInterface()) class-attribute instance-attribute

__init__(benefit: int | IntegerAttr[IntegerType], sym_name: str | StringAttr | None, body: Region | None = None)

Source code in xdsl/dialects/pdl.py
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
def __init__(
    self,
    benefit: int | IntegerAttr[IntegerType],
    sym_name: str | StringAttr | None,
    body: Region | None = None,
):
    if isinstance(benefit, int):
        benefit = IntegerAttr(benefit, 16)
    if isinstance(sym_name, str):
        sym_name = StringAttr(sym_name)
    if body is None:
        body = Region(Block())
    super().__init__(
        properties={
            "benefit": benefit,
            "sym_name": sym_name,
        },
        regions=[body],
        result_types=[],
    )

verify_()

Source code in xdsl/dialects/pdl.py
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
def verify_(self):
    # Check for the correct terminator.
    if not isinstance(self.body.block.last_op, RewriteOp):
        raise VerifyException("expected body to terminate with a `pdl.rewrite`")

    # Check that there is at least one `pdl.operation`.
    if not any(isinstance(op, OperationOp) for op in self.body.block.ops):
        raise VerifyException(
            "the pattern must contain at least one `pdl.operation`"
        )

    # Get the connected component by traversing the graph in the first
    # PDL operation, operand, or result used in a `pdl.rewrite`. The other
    # operations will be detected via other means with a better error handling
    # (expected bindable user).
    first = True
    visited: set[Operation] = set()
    for op in self.body.block.ops:
        if not isinstance(
            op, OperandOp | OperandsOp | ResultOp | ResultsOp | OperationOp
        ):
            continue
        if not _has_user_in_rewrite(op):
            continue

        if first:
            first = False
            _visit_pdl_ops(op, visited)
        if op not in visited:
            raise VerifyException(
                "Operations in a `pdl.pattern` must form a connected component"
            )

parse(parser: Parser) -> PatternOp classmethod

Source code in xdsl/dialects/pdl.py
582
583
584
585
586
587
588
589
590
591
@classmethod
def parse(cls, parser: Parser) -> PatternOp:
    name = parser.parse_optional_symbol_name()
    parser.parse_punctuation(":")
    parser.parse_keyword("benefit")
    parser.parse_punctuation("(")
    benefit = parser.parse_integer()
    parser.parse_punctuation(")")
    body = parser.parse_region()
    return PatternOp(benefit, name, body)

print(printer: Printer) -> None

Source code in xdsl/dialects/pdl.py
593
594
595
596
597
598
def print(self, printer: Printer) -> None:
    if self.sym_name is not None:
        printer.print_string(" @")
        printer.print_string(self.sym_name.data)
    printer.print_string(f" : benefit({self.benefit.value.data}) ")
    printer.print_region(self.body)

RangeOp

Bases: IRDLOperation

See external documentation.

Source code in xdsl/dialects/pdl.py
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
@irdl_op_definition
class RangeOp(IRDLOperation):
    """
    See external [documentation](https://mlir.llvm.org/docs/Dialects/PDLOps/#pdlrange-pdlrangeop).
    """

    name = "pdl.range"
    arguments = var_operand_def(AnyPDLTypeConstr | base(RangeType[AnyPDLType]))
    result = result_def(RangeType[AnyPDLType])

    traits = lazy_traits_def(lambda: (HasParent(RewriteOp),))

    def verify_(self) -> None:
        def get_type_or_elem_type(arg: SSAValue) -> Attribute:
            if isa(arg.type, RangeType[AnyPDLType]):
                return arg.type.element_type
            else:
                return arg.type

        if len(self.arguments) > 0:
            elem_type = get_type_or_elem_type(self.result)

            for arg in self.arguments:
                if cur_elem_type := get_type_or_elem_type(arg) != elem_type:
                    raise VerifyException(
                        "All arguments must have the same type or be an array of the "
                        f"corresponding element type. First element type: {elem_type}"
                        f", current element type: {cur_elem_type}"
                    )

    def __init__(
        self,
        arguments: Sequence[SSAValue],
        result_type: Attribute | None = None,
    ) -> None:
        if result_type is None:
            if len(arguments) == 0:
                raise ValueError("Empty range constructions require a return type.")

            if isa(arguments[0].type, RangeType[AnyPDLType]):
                result_type = RangeType(arguments[0].type.element_type)
            elif AnyPDLTypeConstr.verifies(arguments[0].type):
                result_type = RangeType(arguments[0].type)
            else:
                raise ValueError(
                    f"Arguments of {self.name} are expected to be PDL types"
                )

        super().__init__(operands=[arguments], result_types=[result_type])

    @classmethod
    def parse(cls, parser: Parser) -> RangeOp:
        if parser.parse_optional_punctuation(":") is not None:
            return RangeOp([], parser.parse_attribute())

        arguments = parse_operands_with_types(parser)
        return RangeOp(arguments)

    def print(self, printer: Printer) -> None:
        if len(self.arguments) == 0:
            printer.print_string(" : ")
            printer.print_attribute(self.result.type)
            return
        printer.print_string(" ")
        print_operands_with_types(printer, self.arguments)

name = 'pdl.range' class-attribute instance-attribute

arguments = var_operand_def(AnyPDLTypeConstr | base(RangeType[AnyPDLType])) class-attribute instance-attribute

result = result_def(RangeType[AnyPDLType]) class-attribute instance-attribute

traits = lazy_traits_def(lambda: (HasParent(RewriteOp),)) class-attribute instance-attribute

verify_() -> None

Source code in xdsl/dialects/pdl.py
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
def verify_(self) -> None:
    def get_type_or_elem_type(arg: SSAValue) -> Attribute:
        if isa(arg.type, RangeType[AnyPDLType]):
            return arg.type.element_type
        else:
            return arg.type

    if len(self.arguments) > 0:
        elem_type = get_type_or_elem_type(self.result)

        for arg in self.arguments:
            if cur_elem_type := get_type_or_elem_type(arg) != elem_type:
                raise VerifyException(
                    "All arguments must have the same type or be an array of the "
                    f"corresponding element type. First element type: {elem_type}"
                    f", current element type: {cur_elem_type}"
                )

__init__(arguments: Sequence[SSAValue], result_type: Attribute | None = None) -> None

Source code in xdsl/dialects/pdl.py
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
def __init__(
    self,
    arguments: Sequence[SSAValue],
    result_type: Attribute | None = None,
) -> None:
    if result_type is None:
        if len(arguments) == 0:
            raise ValueError("Empty range constructions require a return type.")

        if isa(arguments[0].type, RangeType[AnyPDLType]):
            result_type = RangeType(arguments[0].type.element_type)
        elif AnyPDLTypeConstr.verifies(arguments[0].type):
            result_type = RangeType(arguments[0].type)
        else:
            raise ValueError(
                f"Arguments of {self.name} are expected to be PDL types"
            )

    super().__init__(operands=[arguments], result_types=[result_type])

parse(parser: Parser) -> RangeOp classmethod

Source code in xdsl/dialects/pdl.py
651
652
653
654
655
656
657
@classmethod
def parse(cls, parser: Parser) -> RangeOp:
    if parser.parse_optional_punctuation(":") is not None:
        return RangeOp([], parser.parse_attribute())

    arguments = parse_operands_with_types(parser)
    return RangeOp(arguments)

print(printer: Printer) -> None

Source code in xdsl/dialects/pdl.py
659
660
661
662
663
664
665
def print(self, printer: Printer) -> None:
    if len(self.arguments) == 0:
        printer.print_string(" : ")
        printer.print_attribute(self.result.type)
        return
    printer.print_string(" ")
    print_operands_with_types(printer, self.arguments)

ReplaceOp

Bases: IRDLOperation

See external documentation.

pdl.replace operations are used within pdl.rewrite regions to specify that an input operation should be marked as replaced. The semantics of this operation correspond with the replaceOp method on a PatternRewriter. The set of replacement values can be either: * a single Operation (replOperation should be populated) - The operation will be replaced with the results of this operation. * a set of Values (replValues should be populated) - The operation will be replaced with these values.

Source code in xdsl/dialects/pdl.py
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
@irdl_op_definition
class ReplaceOp(IRDLOperation):
    """
    See external [documentation](https://mlir.llvm.org/docs/Dialects/PDLOps/#pdlreplace-pdlreplaceop).

    `pdl.replace` operations are used within `pdl.rewrite` regions to specify
    that an input operation should be marked as replaced. The semantics of this
    operation correspond with the `replaceOp` method on a `PatternRewriter`. The
    set of replacement values can be either:
    * a single `Operation` (`replOperation` should be populated)
      - The operation will be replaced with the results of this operation.
    * a set of `Value`s (`replValues` should be populated)
      - The operation will be replaced with these values.
    """

    name = "pdl.replace"
    op_value = operand_def(OperationType)
    repl_operation = opt_operand_def(OperationType)
    repl_values = var_operand_def(base(ValueType) | base(RangeType[ValueType]))

    irdl_options = (AttrSizedOperandSegments(as_property=True),)

    assembly_format = (
        "$op_value `with` ` ` "
        "(`(` $repl_values^ `:` type($repl_values) `)`)? $repl_operation attr-dict"
    )

    def __init__(
        self,
        op_value: SSAValue,
        repl_operation: SSAValue | None = None,
        repl_values: Sequence[SSAValue] | None = None,
    ) -> None:
        operands: list[SSAValue | Sequence[SSAValue]] = [op_value]
        if repl_operation is None:
            operands.append([])
        else:
            operands.append([repl_operation])
        if repl_values is None:
            repl_values = []
        operands.append(repl_values)
        super().__init__(operands=operands)

    def verify_(self) -> None:
        if self.repl_operation is None:
            if not len(self.repl_values):
                raise VerifyException(
                    "Exactly one of `replOperation` or "
                    "`replValues` must be set in `ReplaceOp`"
                    ", both are empty"
                )
        elif len(self.repl_values):
            raise VerifyException(
                "Exactly one of `replOperation` or `replValues` must be set in "
                "`ReplaceOp`, both are set"
            )

name = 'pdl.replace' class-attribute instance-attribute

op_value = operand_def(OperationType) class-attribute instance-attribute

repl_operation = opt_operand_def(OperationType) class-attribute instance-attribute

repl_values = var_operand_def(base(ValueType) | base(RangeType[ValueType])) class-attribute instance-attribute

irdl_options = (AttrSizedOperandSegments(as_property=True),) class-attribute instance-attribute

assembly_format = '$op_value `with` ` ` (`(` $repl_values^ `:` type($repl_values) `)`)? $repl_operation attr-dict' class-attribute instance-attribute

__init__(op_value: SSAValue, repl_operation: SSAValue | None = None, repl_values: Sequence[SSAValue] | None = None) -> None

Source code in xdsl/dialects/pdl.py
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
def __init__(
    self,
    op_value: SSAValue,
    repl_operation: SSAValue | None = None,
    repl_values: Sequence[SSAValue] | None = None,
) -> None:
    operands: list[SSAValue | Sequence[SSAValue]] = [op_value]
    if repl_operation is None:
        operands.append([])
    else:
        operands.append([repl_operation])
    if repl_values is None:
        repl_values = []
    operands.append(repl_values)
    super().__init__(operands=operands)

verify_() -> None

Source code in xdsl/dialects/pdl.py
711
712
713
714
715
716
717
718
719
720
721
722
723
def verify_(self) -> None:
    if self.repl_operation is None:
        if not len(self.repl_values):
            raise VerifyException(
                "Exactly one of `replOperation` or "
                "`replValues` must be set in `ReplaceOp`"
                ", both are empty"
            )
    elif len(self.repl_values):
        raise VerifyException(
            "Exactly one of `replOperation` or `replValues` must be set in "
            "`ReplaceOp`, both are set"
        )

ResultOp

Bases: IRDLOperation

See external documentation.

Source code in xdsl/dialects/pdl.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
@irdl_op_definition
class ResultOp(IRDLOperation):
    """
    See external [documentation](https://mlir.llvm.org/docs/Dialects/PDLOps/#pdlresult-pdlresultop).
    """

    name = "pdl.result"
    index = prop_def(IntegerAttr[I32])
    parent_ = operand_def(OperationType)
    val = result_def(ValueType)

    assembly_format = "$index `of` $parent_ attr-dict"

    def __init__(self, index: int | IntegerAttr[IntegerType], parent: SSAValue) -> None:
        if isinstance(index, int):
            index = IntegerAttr(index, 32)
        super().__init__(
            operands=[parent], properties={"index": index}, result_types=[ValueType()]
        )

name = 'pdl.result' class-attribute instance-attribute

index = prop_def(IntegerAttr[I32]) class-attribute instance-attribute

parent_ = operand_def(OperationType) class-attribute instance-attribute

val = result_def(ValueType) class-attribute instance-attribute

assembly_format = '$index `of` $parent_ attr-dict' class-attribute instance-attribute

__init__(index: int | IntegerAttr[IntegerType], parent: SSAValue) -> None

Source code in xdsl/dialects/pdl.py
739
740
741
742
743
744
def __init__(self, index: int | IntegerAttr[IntegerType], parent: SSAValue) -> None:
    if isinstance(index, int):
        index = IntegerAttr(index, 32)
    super().__init__(
        operands=[parent], properties={"index": index}, result_types=[ValueType()]
    )

ResultsOp

Bases: IRDLOperation

See external documentation.

Source code in xdsl/dialects/pdl.py
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
@irdl_op_definition
class ResultsOp(IRDLOperation):
    """
    See external [documentation](https://mlir.llvm.org/docs/Dialects/PDLOps/#pdlresults-pdlresultsop).
    """

    name = "pdl.results"
    index = opt_prop_def(IntegerAttr[I32])
    parent_ = operand_def(OperationType)
    val = result_def(base(ValueType) | base(RangeType[ValueType]))

    def __init__(
        self,
        parent: SSAValue,
        index: int | IntegerAttr[IntegerType] | None = None,
        result_type: Attribute = RangeType(ValueType()),
    ) -> None:
        if isinstance(index, int):
            index = IntegerAttr(index, 32)
        super().__init__(
            operands=[parent], result_types=[result_type], properties={"index": index}
        )

    @classmethod
    def parse(cls, parser: Parser) -> ResultsOp:
        if parser.parse_optional_keyword("of") is not None:
            parent = parser.parse_operand()
            return ResultsOp(parent)
        index = parser.parse_integer()
        parser.parse_keyword("of")
        parent = parser.parse_operand()
        parser.parse_punctuation("->")
        result_type = parser.parse_attribute()
        return ResultsOp(parent, index, result_type)

    def print(self, printer: Printer) -> None:
        if self.index is None:
            printer.print_string(" of ")
            printer.print_ssa_value(self.parent_)
        else:
            printer.print_string(f" {self.index.value.data} of ")
            printer.print_ssa_value(self.parent_)
            printer.print_string(" -> ")
            printer.print_attribute(self.val.type)

name = 'pdl.results' class-attribute instance-attribute

index = opt_prop_def(IntegerAttr[I32]) class-attribute instance-attribute

parent_ = operand_def(OperationType) class-attribute instance-attribute

val = result_def(base(ValueType) | base(RangeType[ValueType])) class-attribute instance-attribute

__init__(parent: SSAValue, index: int | IntegerAttr[IntegerType] | None = None, result_type: Attribute = RangeType(ValueType())) -> None

Source code in xdsl/dialects/pdl.py
758
759
760
761
762
763
764
765
766
767
768
def __init__(
    self,
    parent: SSAValue,
    index: int | IntegerAttr[IntegerType] | None = None,
    result_type: Attribute = RangeType(ValueType()),
) -> None:
    if isinstance(index, int):
        index = IntegerAttr(index, 32)
    super().__init__(
        operands=[parent], result_types=[result_type], properties={"index": index}
    )

parse(parser: Parser) -> ResultsOp classmethod

Source code in xdsl/dialects/pdl.py
770
771
772
773
774
775
776
777
778
779
780
@classmethod
def parse(cls, parser: Parser) -> ResultsOp:
    if parser.parse_optional_keyword("of") is not None:
        parent = parser.parse_operand()
        return ResultsOp(parent)
    index = parser.parse_integer()
    parser.parse_keyword("of")
    parent = parser.parse_operand()
    parser.parse_punctuation("->")
    result_type = parser.parse_attribute()
    return ResultsOp(parent, index, result_type)

print(printer: Printer) -> None

Source code in xdsl/dialects/pdl.py
782
783
784
785
786
787
788
789
790
def print(self, printer: Printer) -> None:
    if self.index is None:
        printer.print_string(" of ")
        printer.print_ssa_value(self.parent_)
    else:
        printer.print_string(f" {self.index.value.data} of ")
        printer.print_ssa_value(self.parent_)
        printer.print_string(" -> ")
        printer.print_attribute(self.val.type)

RewriteOp

Bases: IRDLOperation

See external documentation.

Source code in xdsl/dialects/pdl.py
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
@irdl_op_definition
class RewriteOp(IRDLOperation):
    """
    See external [documentation](https://mlir.llvm.org/docs/Dialects/PDLOps/#pdlrewrite-pdlrewriteop).
    """

    name = "pdl.rewrite"
    root = opt_operand_def(OperationType)
    # name of external rewriter function
    name_ = opt_prop_def(StringAttr, prop_name="name")
    # parameters of external rewriter function
    external_args = var_operand_def(AnyPDLTypeConstr)
    # body of inline rewriter function
    body = region_def()

    irdl_options = (AttrSizedOperandSegments(as_property=True),)

    traits = traits_def(HasParent(PatternOp), NoTerminator(), IsTerminator())

    assembly_format = (
        "($root^)? "
        "(`with` $name^ (`(` $external_args^ `:` type($external_args) `)`)?)?"
        "($body^)? attr-dict-with-keyword"
    )

    def __init__(
        self,
        root: SSAValue | None,
        body: Region | type[Region.DEFAULT] = Region.DEFAULT,
        name: str | StringAttr | None = None,
        external_args: Sequence[SSAValue] = (),
    ) -> None:
        if isinstance(name, str):
            name = StringAttr(name)

        operands: list[SSAValue | Sequence[SSAValue]] = []
        if root is not None:
            operands.append([root])
        else:
            operands.append([])
        operands.append(external_args)

        regions: list[Region | list[Region]] = []
        if body is Region.DEFAULT:
            regions.append(Region(Block()))
        elif isinstance(body, Region):
            regions.append(body)

        properties: dict[str, Attribute] = {}
        if name is not None:
            properties["name"] = name

        super().__init__(
            result_types=[],
            operands=operands,
            properties=properties,
            regions=regions,
        )

name = 'pdl.rewrite' class-attribute instance-attribute

root = opt_operand_def(OperationType) class-attribute instance-attribute

name_ = opt_prop_def(StringAttr, prop_name='name') class-attribute instance-attribute

external_args = var_operand_def(AnyPDLTypeConstr) class-attribute instance-attribute

body = region_def() class-attribute instance-attribute

irdl_options = (AttrSizedOperandSegments(as_property=True),) class-attribute instance-attribute

traits = traits_def(HasParent(PatternOp), NoTerminator(), IsTerminator()) class-attribute instance-attribute

assembly_format = '($root^)? (`with` $name^ (`(` $external_args^ `:` type($external_args) `)`)?)?($body^)? attr-dict-with-keyword' class-attribute instance-attribute

__init__(root: SSAValue | None, body: Region | type[Region.DEFAULT] = Region.DEFAULT, name: str | StringAttr | None = None, external_args: Sequence[SSAValue] = ()) -> None

Source code in xdsl/dialects/pdl.py
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
def __init__(
    self,
    root: SSAValue | None,
    body: Region | type[Region.DEFAULT] = Region.DEFAULT,
    name: str | StringAttr | None = None,
    external_args: Sequence[SSAValue] = (),
) -> None:
    if isinstance(name, str):
        name = StringAttr(name)

    operands: list[SSAValue | Sequence[SSAValue]] = []
    if root is not None:
        operands.append([root])
    else:
        operands.append([])
    operands.append(external_args)

    regions: list[Region | list[Region]] = []
    if body is Region.DEFAULT:
        regions.append(Region(Block()))
    elif isinstance(body, Region):
        regions.append(body)

    properties: dict[str, Attribute] = {}
    if name is not None:
        properties["name"] = name

    super().__init__(
        result_types=[],
        operands=operands,
        properties=properties,
        regions=regions,
    )

TypeOp

Bases: IRDLOperation

See external documentation.

Source code in xdsl/dialects/pdl.py
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
@irdl_op_definition
class TypeOp(IRDLOperation):
    """
    See external [documentation](https://mlir.llvm.org/docs/Dialects/PDLOps/#pdltype-pdltypeop).
    """

    name = "pdl.type"
    constantType = opt_prop_def(TypeAttribute)
    result = result_def(TypeType)

    assembly_format = "attr-dict (`:` $constantType^)?"

    def __init__(self, constant_type: Attribute | None = None) -> None:
        super().__init__(
            properties={"constantType": constant_type}, result_types=[TypeType()]
        )

    def verify_(self):
        verify_has_binding_use(self)

name = 'pdl.type' class-attribute instance-attribute

constantType = opt_prop_def(TypeAttribute) class-attribute instance-attribute

result = result_def(TypeType) class-attribute instance-attribute

assembly_format = 'attr-dict (`:` $constantType^)?' class-attribute instance-attribute

__init__(constant_type: Attribute | None = None) -> None

Source code in xdsl/dialects/pdl.py
865
866
867
868
def __init__(self, constant_type: Attribute | None = None) -> None:
    super().__init__(
        properties={"constantType": constant_type}, result_types=[TypeType()]
    )

verify_()

Source code in xdsl/dialects/pdl.py
870
871
def verify_(self):
    verify_has_binding_use(self)

TypesOp

Bases: IRDLOperation

See external documentation.

Source code in xdsl/dialects/pdl.py
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
@irdl_op_definition
class TypesOp(IRDLOperation):
    """
    See external [documentation](https://mlir.llvm.org/docs/Dialects/PDLOps/#pdltypes-pdltypesop).
    """

    name = "pdl.types"
    constantTypes = opt_prop_def(ArrayAttr[TypeAttribute])
    result = result_def(RangeType[TypeType])

    assembly_format = "attr-dict (`:` $constantTypes^)?"

    def __init__(self, constant_types: Iterable[Attribute] | None = None) -> None:
        if constant_types is not None:
            properties = {"constantTypes": ArrayAttr(constant_types)}
        else:
            properties = {}
        super().__init__(
            properties=properties,
            result_types=[RangeType(TypeType())],
        )

    def verify_(self):
        verify_has_binding_use(self)

name = 'pdl.types' class-attribute instance-attribute

constantTypes = opt_prop_def(ArrayAttr[TypeAttribute]) class-attribute instance-attribute

result = result_def(RangeType[TypeType]) class-attribute instance-attribute

assembly_format = 'attr-dict (`:` $constantTypes^)?' class-attribute instance-attribute

__init__(constant_types: Iterable[Attribute] | None = None) -> None

Source code in xdsl/dialects/pdl.py
886
887
888
889
890
891
892
893
894
def __init__(self, constant_types: Iterable[Attribute] | None = None) -> None:
    if constant_types is not None:
        properties = {"constantTypes": ArrayAttr(constant_types)}
    else:
        properties = {}
    super().__init__(
        properties=properties,
        result_types=[RangeType(TypeType())],
    )

verify_()

Source code in xdsl/dialects/pdl.py
896
897
def verify_(self):
    verify_has_binding_use(self)

parse_operands_with_types(parser: Parser) -> list[SSAValue]

Parse a list of operands with types of the following format: operand1, operand2 : type1, type2 At least one operand is expected.

Source code in xdsl/dialects/pdl.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def parse_operands_with_types(parser: Parser) -> list[SSAValue]:
    """
    Parse a list of operands with types of the following format:
    `operand1, operand2 : type1, type2`
    At least one operand is expected.
    """
    pos = parser.pos
    operands = parser.parse_comma_separated_list(
        Parser.Delimiter.NONE, parser.parse_operand
    )
    parser.parse_punctuation(":")
    types = parser.parse_comma_separated_list(
        Parser.Delimiter.NONE, parser.parse_attribute
    )
    end_pos = parser.pos
    if len(operands) != len(types):
        parser.raise_error(
            "Mismatched between the numbers of operands and types", pos, end_pos
        )
    for operand, type in zip(operands, types):
        if operand.type != type:
            parser.raise_error(
                "Mismatched between operands and their types", pos, end_pos
            )

    return operands

print_operands_with_types(printer: Printer, operands: Iterable[SSAValue]) -> None

Source code in xdsl/dialects/pdl.py
80
81
82
83
def print_operands_with_types(printer: Printer, operands: Iterable[SSAValue]) -> None:
    printer.print_list(operands, printer.print_ssa_value)
    printer.print_string(" : ")
    printer.print_list(operands, lambda o: printer.print_attribute(o.type))

has_binding_use(op: Operation) -> bool

Returns true if the given operation is used by a "binding" pdl operation.

Source code in xdsl/dialects/pdl.py
86
87
88
89
90
91
92
93
94
95
96
def has_binding_use(op: Operation) -> bool:
    """
    Returns true if the given operation is used by a "binding" pdl operation.
    """
    for result in op.results:
        for use in result.uses:
            if not isinstance(use.operation, ResultOp | ResultsOp) or has_binding_use(
                use.operation
            ):
                return True
    return False

verify_has_binding_use(op: Operation) -> None

Raise an exception if the operation is in the main matcher body and is not used by a "binding" pdl operation.

Source code in xdsl/dialects/pdl.py
 99
100
101
102
103
104
105
106
107
108
109
110
def verify_has_binding_use(op: Operation) -> None:
    """
    Raise an exception if the operation is in the main matcher body and is
    not used by a "binding" pdl operation.
    """
    if not isinstance(op.parent_op(), PatternOp):
        return
    if not has_binding_use(op):
        raise VerifyException(
            "expected a bindable user when defined in the matcher body of a "
            "`pdl.pattern`"
        )