Skip to content

Builtin

builtin

DYNAMIC_INDEX = -2 ** 63 module-attribute

A constant value denoting a dynamic index in a shape. Equal to -(2 ** 63) which is used in C++ MLIR.

FlatSymbolRefAttrConstr = MessageConstraint(ParamAttrConstraint.get(SymbolRefAttr, AnyAttr(), EmptyArrayAttrConstraint()), 'Expected SymbolRefAttr with no nested symbols.') module-attribute

Constrain SymbolRef to be FlatSymbolRef

FlatSymbolRefAttr = Annotated[SymbolRefAttr, FlatSymbolRefAttrConstr] module-attribute

SymbolRef constrained to have an empty nested_references property.

StaticDimensionConstr = MessageConstraint(IntAttrConstraint(NotEqualIntConstraint(DYNAMIC_INDEX)), f'expected static dimension, but got {DYNAMIC_INDEX}') module-attribute

Constrain a dimension to be static (not equal to DYNAMIC_INDEX).

StaticShapeArrayConstr = MessageConstraint(ArrayOfConstraint(StaticDimensionConstr), 'expected static shape, but got dynamic dimension') module-attribute

Constrain an array to be a static shape (all dimensions static).

I128: TypeAlias = IntegerType[Literal[128], Literal[Signedness.SIGNLESS]] module-attribute

I64: TypeAlias = IntegerType[Literal[64], Literal[Signedness.SIGNLESS]] module-attribute

I32: TypeAlias = IntegerType[Literal[32], Literal[Signedness.SIGNLESS]] module-attribute

I16: TypeAlias = IntegerType[Literal[16], Literal[Signedness.SIGNLESS]] module-attribute

I8: TypeAlias = IntegerType[Literal[8], Literal[Signedness.SIGNLESS]] module-attribute

I1: TypeAlias = IntegerType[Literal[1], Literal[Signedness.SIGNLESS]] module-attribute

i128: I128 = IntegerType(128) module-attribute

i64: I64 = IntegerType(64) module-attribute

i32: I32 = IntegerType(32) module-attribute

i16: I16 = IntegerType(16) module-attribute

i8: I8 = IntegerType(8) module-attribute

i1: I1 = IntegerType(1) module-attribute

AnySignlessIntegerType: TypeAlias = IntegerType[int, Literal[Signedness.SIGNLESS]] module-attribute

Type alias constrained to signless IntegerType.

SignlessIntegerConstraint = irdl_to_attr_constraint(AnySignlessIntegerType) module-attribute

Type constraint for signless IntegerType.

LocationAttr: TypeAlias = UnknownLoc | FileLineColLoc | CallSiteLoc | NameLoc | FusedLoc module-attribute

Union of all MLIR location attribute types. Represents source location information that can be attached to operations, covering unknown locations, file/line/column positions, call-site chains, named locations, and fused (multi-location) aggregates.

UNKNOWN_LOC: LocationAttr = UnknownLoc() module-attribute

IndexTypeConstr = BaseAttr(IndexType) module-attribute

IntegerAttrTypeConstr = IndexTypeConstr | BaseAttr(IntegerType) module-attribute

BoolAttr: TypeAlias = IntegerAttr[Annotated[IntegerType, IntegerType(1)]] module-attribute

AnyFloat: TypeAlias = BFloat16Type | Float16Type | Float32Type | Float64Type | Float80Type | Float128Type | FloatTF32Type | Float8E5M2Type | Float8E4M3Type | Float8E4M3FNType | Float8E5M2FNUZType | Float8E4M3FNUZType | Float8E4M3B11FNUZType | Float8E3M4Type | Float8E8M0FNUType | Float6E2M3FNType | Float6E3M2FNType | Float4E2M1FNType module-attribute

AnyFloatConstr = BaseAttr(BFloat16Type) | BaseAttr(Float16Type) | BaseAttr(Float32Type) | BaseAttr(Float64Type) | BaseAttr(Float80Type) | BaseAttr(Float128Type) | BaseAttr(FloatTF32Type) | BaseAttr(Float8E5M2Type) | BaseAttr(Float8E4M3Type) | BaseAttr(Float8E4M3FNType) | BaseAttr(Float8E5M2FNUZType) | BaseAttr(Float8E4M3FNUZType) | BaseAttr(Float8E4M3B11FNUZType) | BaseAttr(Float8E3M4Type) | BaseAttr(Float8E8M0FNUType) | BaseAttr(Float6E2M3FNType) | BaseAttr(Float6E3M2FNType) | BaseAttr(Float4E2M1FNType) module-attribute

AnyVectorType: TypeAlias = VectorType[Attribute] module-attribute

AnyTensorType: TypeAlias = TensorType[Attribute] module-attribute

AnyTensorTypeConstr = BaseAttr[TensorType[Attribute]](TensorType) module-attribute

AnyUnrankedTensorType: TypeAlias = UnrankedTensorType[Attribute] module-attribute

AnyUnrankedTensorTypeConstr = BaseAttr[AnyUnrankedTensorType](UnrankedTensorType) module-attribute

VectorOrTensorOf: TypeAlias = VectorType[AttributeCovT] | TensorType[AttributeCovT] | UnrankedTensorType[AttributeCovT] module-attribute

bf16 = BFloat16Type() module-attribute

f16 = Float16Type() module-attribute

f32 = Float32Type() module-attribute

f64 = Float64Type() module-attribute

f80 = Float80Type() module-attribute

f128 = Float128Type() module-attribute

tf32 = FloatTF32Type() module-attribute

f8E5M2 = Float8E5M2Type() module-attribute

f8E4M3 = Float8E4M3Type() module-attribute

f8E4M3FN = Float8E4M3FNType() module-attribute

f8E5M2FNUZ = Float8E5M2FNUZType() module-attribute

f8E4M3FNUZ = Float8E4M3FNUZType() module-attribute

f8E4M3B11FNUZ = Float8E4M3B11FNUZType() module-attribute

f8E3M4 = Float8E3M4Type() module-attribute

f8E8M0FNU = Float8E8M0FNUType() module-attribute

f6E2M3FN = Float6E2M3FNType() module-attribute

f6E3M2FN = Float6E3M2FNType() module-attribute

f4E2M1FN = Float4E2M1FNType() module-attribute

AnyUnrankedMemRefTypeConstr = BaseAttr[UnrankedMemRefType](UnrankedMemRefType) module-attribute

RankedStructure: TypeAlias = VectorType[AttributeCovT] | TensorType[AttributeCovT] | MemRefType[AttributeCovT] module-attribute

AnyDenseElement: TypeAlias = IntegerType | IndexType | AnyFloat | ComplexType module-attribute

DenseIntElementsAttr: TypeAlias = DenseIntOrFPElementsAttr[IndexType | IntegerType] module-attribute

Builtin = Dialect('builtin', [ModuleOp, UnregisteredOp, UnrealizedConversionCastOp], [UnregisteredAttr, StringAttr, SymbolRefAttr, IntAttr, IntegerAttr, ArrayAttr, DictionaryAttr, DenseIntOrFPElementsAttr, DenseResourceAttr, UnitAttr, FloatData, UnknownLoc, FileLineColLoc, NoneAttr, OpaqueAttr, ComplexType, FunctionType, BFloat16Type, Float16Type, Float32Type, Float64Type, Float80Type, Float128Type, FloatTF32Type, Float8E5M2Type, Float8E4M3Type, Float8E4M3FNType, Float8E5M2FNUZType, Float8E4M3FNUZType, Float8E4M3B11FNUZType, Float8E3M4Type, Float8E8M0FNUType, Float6E2M3FNType, Float6E3M2FNType, Float4E2M1FNType, FloatAttr, SignednessAttr, TupleType, IntegerType, IndexType, NoneType, VectorType, TensorType, UnrankedTensorType, AffineMapAttr, AffineSetAttr, MemRefType, UnrankedMemRefType], [OpAsmDialectInterface()]) module-attribute

ShapedType dataclass

Bases: Attribute, ABC

Source code in xdsl/dialects/builtin.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
class ShapedType(Attribute, ABC):
    @abstractmethod
    def get_num_dims(self) -> int: ...

    @abstractmethod
    def get_shape(self) -> tuple[int, ...]: ...

    def element_count(self) -> int:
        return prod(self.get_shape())

    def has_static_shape(self) -> bool:
        """
        Check if all dimensions have static (non-dynamic) shapes.
        """
        return all(dim != DYNAMIC_INDEX for dim in self.get_shape())

    @staticmethod
    def strides_for_shape(
        shape: Sequence[int], factor: int = 1
    ) -> tuple[int | None, ...]:
        """
        Returns a tuple of strides for a given shape, with row-major layout.
        Strides that depend on a dynamic index are returned as `None`.
        The optional `factor` parameter specifies the stride for the innermost
        dimension, defaulting to 1.
        """
        rev_strides: list[int | None] = []
        stride: int | None = factor
        for dim in reversed(shape):
            rev_strides.append(stride)
            if stride is None or dim == DYNAMIC_INDEX:
                stride = None
            else:
                stride *= dim
        return tuple(reversed(rev_strides))

get_num_dims() -> int abstractmethod

Source code in xdsl/dialects/builtin.py
115
116
@abstractmethod
def get_num_dims(self) -> int: ...

get_shape() -> tuple[int, ...] abstractmethod

Source code in xdsl/dialects/builtin.py
118
119
@abstractmethod
def get_shape(self) -> tuple[int, ...]: ...

element_count() -> int

Source code in xdsl/dialects/builtin.py
121
122
def element_count(self) -> int:
    return prod(self.get_shape())

has_static_shape() -> bool

Check if all dimensions have static (non-dynamic) shapes.

Source code in xdsl/dialects/builtin.py
124
125
126
127
128
def has_static_shape(self) -> bool:
    """
    Check if all dimensions have static (non-dynamic) shapes.
    """
    return all(dim != DYNAMIC_INDEX for dim in self.get_shape())

strides_for_shape(shape: Sequence[int], factor: int = 1) -> tuple[int | None, ...] staticmethod

Returns a tuple of strides for a given shape, with row-major layout. Strides that depend on a dynamic index are returned as None. The optional factor parameter specifies the stride for the innermost dimension, defaulting to 1.

Source code in xdsl/dialects/builtin.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
@staticmethod
def strides_for_shape(
    shape: Sequence[int], factor: int = 1
) -> tuple[int | None, ...]:
    """
    Returns a tuple of strides for a given shape, with row-major layout.
    Strides that depend on a dynamic index are returned as `None`.
    The optional `factor` parameter specifies the stride for the innermost
    dimension, defaulting to 1.
    """
    rev_strides: list[int | None] = []
    stride: int | None = factor
    for dim in reversed(shape):
        rev_strides.append(stride)
        if stride is None or dim == DYNAMIC_INDEX:
            stride = None
        else:
            stride *= dim
    return tuple(reversed(rev_strides))

ContainerType

Bases: ABC, Generic[_ContainerElementTypeT]

Source code in xdsl/dialects/builtin.py
156
157
158
159
class ContainerType(ABC, Generic[_ContainerElementTypeT]):
    @abstractmethod
    def get_element_type(self) -> _ContainerElementTypeT:
        pass

get_element_type() -> _ContainerElementTypeT abstractmethod

Source code in xdsl/dialects/builtin.py
157
158
159
@abstractmethod
def get_element_type(self) -> _ContainerElementTypeT:
    pass

NoneAttr dataclass

Bases: ParametrizedAttribute, BuiltinAttribute

An attribute representing the absence of an attribute.

Source code in xdsl/dialects/builtin.py
185
186
187
188
189
190
191
192
@irdl_attr_definition
class NoneAttr(ParametrizedAttribute, BuiltinAttribute):
    """An attribute representing the absence of an attribute."""

    name = "none"

    def print_builtin(self, printer: Printer):
        printer.print_string("none")

name = 'none' class-attribute instance-attribute

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
191
192
def print_builtin(self, printer: Printer):
    printer.print_string("none")

ArrayAttr

Bases: _BuiltinGenericData[tuple[AttributeCovT, ...]], Iterable[AttributeCovT], Generic[AttributeCovT]

Source code in xdsl/dialects/builtin.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
@irdl_attr_definition
class ArrayAttr(
    _BuiltinGenericData[tuple[AttributeCovT, ...]],
    Iterable[AttributeCovT],
    Generic[AttributeCovT],
):
    name = "array"

    def __init__(self, param: Iterable[AttributeCovT]) -> None:
        super().__init__(tuple(param))

    def print_builtin(self, printer: Printer):
        with printer.in_square_brackets():
            printer.print_list(self.data, printer.print_attribute)

    @staticmethod
    @override
    def constr(
        constr: IRDLAttrConstraint[AttributeInvT]
        | RangeConstraint[AttributeInvT]
        | None = None,
    ) -> ArrayOfConstraint[AttributeInvT]:
        return ArrayOfConstraint[AttributeInvT](
            cast(
                AttrConstraint[AttributeInvT],
                TypeVarConstraint(AttributeCovT, AnyAttr()),
            )
            if constr is None
            else constr
        )

    def __len__(self):
        return len(self.data)

    def __iter__(self) -> Iterator[AttributeCovT]:
        return iter(self.data)

name = 'array' class-attribute instance-attribute

__init__(param: Iterable[AttributeCovT]) -> None

Source code in xdsl/dialects/builtin.py
203
204
def __init__(self, param: Iterable[AttributeCovT]) -> None:
    super().__init__(tuple(param))

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
206
207
208
def print_builtin(self, printer: Printer):
    with printer.in_square_brackets():
        printer.print_list(self.data, printer.print_attribute)

constr(constr: IRDLAttrConstraint[AttributeInvT] | RangeConstraint[AttributeInvT] | None = None) -> ArrayOfConstraint[AttributeInvT] staticmethod

Source code in xdsl/dialects/builtin.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
@staticmethod
@override
def constr(
    constr: IRDLAttrConstraint[AttributeInvT]
    | RangeConstraint[AttributeInvT]
    | None = None,
) -> ArrayOfConstraint[AttributeInvT]:
    return ArrayOfConstraint[AttributeInvT](
        cast(
            AttrConstraint[AttributeInvT],
            TypeVarConstraint(AttributeCovT, AnyAttr()),
        )
        if constr is None
        else constr
    )

__len__()

Source code in xdsl/dialects/builtin.py
226
227
def __len__(self):
    return len(self.data)

__iter__() -> Iterator[AttributeCovT]

Source code in xdsl/dialects/builtin.py
229
230
def __iter__(self) -> Iterator[AttributeCovT]:
    return iter(self.data)

ArrayOfConstraint dataclass

Bases: AttrConstraint[ArrayAttr[AttributeCovT]]

Source code in xdsl/dialects/builtin.py
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
@dataclass(frozen=True)
class ArrayOfConstraint(AttrConstraint[ArrayAttr[AttributeCovT]]):
    elem_range_constraint: RangeConstraint[AttributeCovT]
    """
    A constraint that enforces an ArrayData whose elements satisfy
    the underlying range constraint.
    """

    def __init__(
        self,
        constr: (IRDLAttrConstraint[AttributeCovT] | RangeConstraint[AttributeCovT]),
    ):
        if isinstance(constr, RangeConstraint):
            object.__setattr__(self, "elem_range_constraint", constr)
        else:
            object.__setattr__(
                self, "elem_range_constraint", RangeOf(irdl_to_attr_constraint(constr))
            )

    def verify(
        self,
        attr: Attribute,
        constraint_context: ConstraintContext,
    ) -> None:
        if not isa(attr, ArrayAttr):
            raise VerifyException(
                f"expected ArrayAttr attribute, but got '{type(attr)}'"
            )
        self.elem_range_constraint.verify(attr.data, constraint_context)

    def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
        return self.elem_range_constraint.can_infer(
            var_constraint_names, length_known=False
        )

    def infer(self, context: ConstraintContext) -> ArrayAttr[AttributeCovT]:
        return ArrayAttr(self.elem_range_constraint.infer(context, length=None))

    def get_bases(self) -> set[type[Attribute]] | None:
        return {ArrayAttr}

    def variables(self) -> set[str]:
        return self.elem_range_constraint.variables()

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> AttrConstraint[ArrayAttr[AttributeCovT]]:
        return ArrayOfConstraint(
            self.elem_range_constraint.mapping_type_vars(type_var_mapping)
        )

elem_range_constraint: RangeConstraint[AttributeCovT] instance-attribute

A constraint that enforces an ArrayData whose elements satisfy the underlying range constraint.

__init__(constr: IRDLAttrConstraint[AttributeCovT] | RangeConstraint[AttributeCovT])

Source code in xdsl/dialects/builtin.py
241
242
243
244
245
246
247
248
249
250
def __init__(
    self,
    constr: (IRDLAttrConstraint[AttributeCovT] | RangeConstraint[AttributeCovT]),
):
    if isinstance(constr, RangeConstraint):
        object.__setattr__(self, "elem_range_constraint", constr)
    else:
        object.__setattr__(
            self, "elem_range_constraint", RangeOf(irdl_to_attr_constraint(constr))
        )

verify(attr: Attribute, constraint_context: ConstraintContext) -> None

Source code in xdsl/dialects/builtin.py
252
253
254
255
256
257
258
259
260
261
def verify(
    self,
    attr: Attribute,
    constraint_context: ConstraintContext,
) -> None:
    if not isa(attr, ArrayAttr):
        raise VerifyException(
            f"expected ArrayAttr attribute, but got '{type(attr)}'"
        )
    self.elem_range_constraint.verify(attr.data, constraint_context)

can_infer(var_constraint_names: AbstractSet[str]) -> bool

Source code in xdsl/dialects/builtin.py
263
264
265
266
def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
    return self.elem_range_constraint.can_infer(
        var_constraint_names, length_known=False
    )

infer(context: ConstraintContext) -> ArrayAttr[AttributeCovT]

Source code in xdsl/dialects/builtin.py
268
269
def infer(self, context: ConstraintContext) -> ArrayAttr[AttributeCovT]:
    return ArrayAttr(self.elem_range_constraint.infer(context, length=None))

get_bases() -> set[type[Attribute]] | None

Source code in xdsl/dialects/builtin.py
271
272
def get_bases(self) -> set[type[Attribute]] | None:
    return {ArrayAttr}

variables() -> set[str]

Source code in xdsl/dialects/builtin.py
274
275
def variables(self) -> set[str]:
    return self.elem_range_constraint.variables()

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> AttrConstraint[ArrayAttr[AttributeCovT]]

Source code in xdsl/dialects/builtin.py
277
278
279
280
281
282
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> AttrConstraint[ArrayAttr[AttributeCovT]]:
    return ArrayOfConstraint(
        self.elem_range_constraint.mapping_type_vars(type_var_mapping)
    )

StringAttr dataclass

Bases: _BuiltinData[str]

Source code in xdsl/dialects/builtin.py
285
286
287
288
289
290
@irdl_attr_definition
class StringAttr(_BuiltinData[str]):
    name = "string"

    def print_builtin(self, printer: Printer):
        printer.print_string_literal(self.data)

name = 'string' class-attribute instance-attribute

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
289
290
def print_builtin(self, printer: Printer):
    printer.print_string_literal(self.data)

SymbolNameConstraint dataclass

Bases: AttrConstraint[StringAttr]

Constrain an attribute to be a StringAttr. This constraint has special assembly format support.

Source code in xdsl/dialects/builtin.py
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
@dataclass(frozen=True)
class SymbolNameConstraint(AttrConstraint[StringAttr]):
    """
    Constrain an attribute to be a StringAttr.
    This constraint has special assembly format support.
    """

    def verify(
        self,
        attr: Attribute,
        constraint_context: ConstraintContext,
    ) -> None:
        if not isinstance(attr, StringAttr):
            raise VerifyException(f"{attr} should be a string")

    def get_bases(self) -> set[type[Attribute]] | None:
        return {StringAttr}

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> AttrConstraint[StringAttr]:
        return self

__init__() -> None

verify(attr: Attribute, constraint_context: ConstraintContext) -> None

Source code in xdsl/dialects/builtin.py
300
301
302
303
304
305
306
def verify(
    self,
    attr: Attribute,
    constraint_context: ConstraintContext,
) -> None:
    if not isinstance(attr, StringAttr):
        raise VerifyException(f"{attr} should be a string")

get_bases() -> set[type[Attribute]] | None

Source code in xdsl/dialects/builtin.py
308
309
def get_bases(self) -> set[type[Attribute]] | None:
    return {StringAttr}

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> AttrConstraint[StringAttr]

Source code in xdsl/dialects/builtin.py
311
312
313
314
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> AttrConstraint[StringAttr]:
    return self

BytesAttr dataclass

Bases: _BuiltinData[bytes]

Source code in xdsl/dialects/builtin.py
317
318
319
320
321
322
@irdl_attr_definition
class BytesAttr(_BuiltinData[bytes]):
    name = "bytes"

    def print_builtin(self, printer: Printer):
        printer.print_bytes_literal(self.data)

name = 'bytes' class-attribute instance-attribute

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
321
322
def print_builtin(self, printer: Printer):
    printer.print_bytes_literal(self.data)

SymbolRefAttr

Bases: ParametrizedAttribute, BuiltinAttribute

Source code in xdsl/dialects/builtin.py
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
@irdl_attr_definition
class SymbolRefAttr(ParametrizedAttribute, BuiltinAttribute):
    name = "symbol_ref"
    root_reference: StringAttr
    nested_references: ArrayAttr[StringAttr]

    def __init__(
        self,
        root: str | StringAttr,
        nested: Sequence[str] | Sequence[StringAttr] | ArrayAttr[StringAttr] = [],
    ) -> None:
        if isinstance(root, str):
            root = StringAttr(root)
        if not isinstance(nested, ArrayAttr):
            nested = ArrayAttr(
                [StringAttr(x) if isinstance(x, str) else x for x in nested]
            )
        super().__init__(root, nested)

    @staticmethod
    def get(value: str | SymbolRefAttr) -> SymbolRefAttr:
        if isinstance(value, str):
            return SymbolRefAttr(value)
        return value

    def string_value(self):
        root = self.root_reference.data
        for ref in self.nested_references.data:
            root += "." + ref.data
        return root

    def print_builtin(self, printer: Printer):
        printer.print_symbol_name(self.root_reference.data)
        for ref in self.nested_references.data:
            printer.print_string("::")
            printer.print_symbol_name(ref.data)

name = 'symbol_ref' class-attribute instance-attribute

root_reference: StringAttr instance-attribute

nested_references: ArrayAttr[StringAttr] instance-attribute

__init__(root: str | StringAttr, nested: Sequence[str] | Sequence[StringAttr] | ArrayAttr[StringAttr] = []) -> None

Source code in xdsl/dialects/builtin.py
331
332
333
334
335
336
337
338
339
340
341
342
def __init__(
    self,
    root: str | StringAttr,
    nested: Sequence[str] | Sequence[StringAttr] | ArrayAttr[StringAttr] = [],
) -> None:
    if isinstance(root, str):
        root = StringAttr(root)
    if not isinstance(nested, ArrayAttr):
        nested = ArrayAttr(
            [StringAttr(x) if isinstance(x, str) else x for x in nested]
        )
    super().__init__(root, nested)

get(value: str | SymbolRefAttr) -> SymbolRefAttr staticmethod

Source code in xdsl/dialects/builtin.py
344
345
346
347
348
@staticmethod
def get(value: str | SymbolRefAttr) -> SymbolRefAttr:
    if isinstance(value, str):
        return SymbolRefAttr(value)
    return value

string_value()

Source code in xdsl/dialects/builtin.py
350
351
352
353
354
def string_value(self):
    root = self.root_reference.data
    for ref in self.nested_references.data:
        root += "." + ref.data
    return root

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
356
357
358
359
360
def print_builtin(self, printer: Printer):
    printer.print_symbol_name(self.root_reference.data)
    for ref in self.nested_references.data:
        printer.print_string("::")
        printer.print_symbol_name(ref.data)

EmptyArrayAttrConstraint dataclass

Bases: AttrConstraint

Constrain attribute to be empty ArrayData

Source code in xdsl/dialects/builtin.py
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
class EmptyArrayAttrConstraint(AttrConstraint):
    """
    Constrain attribute to be empty ArrayData
    """

    def verify(self, attr: Attribute, constraint_context: ConstraintContext) -> None:
        if not isa(attr, ArrayAttr):
            raise VerifyException(f"expected ArrayData attribute, but got {attr}")
        if attr.data:
            raise VerifyException(f"expected empty array, but got {attr}")

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> EmptyArrayAttrConstraint:
        return self

verify(attr: Attribute, constraint_context: ConstraintContext) -> None

Source code in xdsl/dialects/builtin.py
368
369
370
371
372
def verify(self, attr: Attribute, constraint_context: ConstraintContext) -> None:
    if not isa(attr, ArrayAttr):
        raise VerifyException(f"expected ArrayData attribute, but got {attr}")
    if attr.data:
        raise VerifyException(f"expected empty array, but got {attr}")

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> EmptyArrayAttrConstraint

Source code in xdsl/dialects/builtin.py
374
375
376
377
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> EmptyArrayAttrConstraint:
    return self

IntAttr dataclass

Bases: GenericData[_IntCovT], Generic[_IntCovT]

Source code in xdsl/dialects/builtin.py
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
@irdl_attr_definition
class IntAttr(GenericData[_IntCovT], Generic[_IntCovT]):
    name = "builtin.int"

    @classmethod
    def parse_parameter(cls, parser: AttrParser) -> _IntCovT:
        with parser.in_angle_brackets():
            data = parser.parse_integer()
            return cast(_IntCovT, data)

    def print_parameter(self, printer: Printer) -> None:
        with printer.in_angle_brackets():
            printer.print_string(f"{self.data}")

    def __bool__(self) -> bool:
        """Returns True if value is non-zero."""
        return bool(self.data)

    @staticmethod
    @override
    def constr(
        constr: IntConstraint | int | TypeForm[int] | None = None,
    ) -> AttrConstraint[IntAttr]:
        return IntAttrConstraint.get(
            IntTypeVarConstraint(_IntCovT, AnyInt()) if constr is None else constr
        )

name = 'builtin.int' class-attribute instance-attribute

parse_parameter(parser: AttrParser) -> _IntCovT classmethod

Source code in xdsl/dialects/builtin.py
396
397
398
399
400
@classmethod
def parse_parameter(cls, parser: AttrParser) -> _IntCovT:
    with parser.in_angle_brackets():
        data = parser.parse_integer()
        return cast(_IntCovT, data)

print_parameter(printer: Printer) -> None

Source code in xdsl/dialects/builtin.py
402
403
404
def print_parameter(self, printer: Printer) -> None:
    with printer.in_angle_brackets():
        printer.print_string(f"{self.data}")

__bool__() -> bool

Returns True if value is non-zero.

Source code in xdsl/dialects/builtin.py
406
407
408
def __bool__(self) -> bool:
    """Returns True if value is non-zero."""
    return bool(self.data)

constr(constr: IntConstraint | int | TypeForm[int] | None = None) -> AttrConstraint[IntAttr] staticmethod

Source code in xdsl/dialects/builtin.py
410
411
412
413
414
415
416
417
@staticmethod
@override
def constr(
    constr: IntConstraint | int | TypeForm[int] | None = None,
) -> AttrConstraint[IntAttr]:
    return IntAttrConstraint.get(
        IntTypeVarConstraint(_IntCovT, AnyInt()) if constr is None else constr
    )

IntAttrConstraint dataclass

Bases: AttrConstraint[IntAttr]

Constrains the value of an IntAttr.

Source code in xdsl/dialects/builtin.py
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
@dataclass(frozen=True)
class IntAttrConstraint(AttrConstraint[IntAttr]):
    """
    Constrains the value of an IntAttr.
    """

    @staticmethod
    def get(
        int_constraint: IntConstraint | int | TypeForm[int] | None = None,
    ) -> AttrConstraint[IntAttr]:
        if int_constraint is None:
            return BaseAttr(IntAttr)
        if not isinstance(int_constraint, IntConstraint):
            int_constraint = get_int_constraint(int_constraint)
        if int_constraint == AnyInt():
            return BaseAttr(IntAttr)
        if isinstance(int_constraint, EqIntConstraint):
            return EqAttrConstraint(IntAttr(int_constraint.value))
        return IntAttrConstraint(int_constraint)

    int_constraint: IntConstraint

    def verify(self, attr: Attribute, constraint_context: ConstraintContext) -> None:
        if not isa(attr, IntAttr):
            raise VerifyException(f"attribute {attr} expected to be an IntAttr")
        self.int_constraint.verify(attr.data, constraint_context)

    def variables(self) -> set[str]:
        return self.int_constraint.variables()

    def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
        return self.int_constraint.can_infer(var_constraint_names)

    def infer(self, context: ConstraintContext) -> IntAttr:
        return IntAttr(self.int_constraint.infer(context))

    def get_bases(self) -> set[type[Attribute]] | None:
        return {IntAttr}

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ):
        return IntAttrConstraint.get(
            self.int_constraint.mapping_type_vars(type_var_mapping)
        )

int_constraint: IntConstraint instance-attribute

__init__(int_constraint: IntConstraint) -> None

get(int_constraint: IntConstraint | int | TypeForm[int] | None = None) -> AttrConstraint[IntAttr] staticmethod

Source code in xdsl/dialects/builtin.py
426
427
428
429
430
431
432
433
434
435
436
437
438
@staticmethod
def get(
    int_constraint: IntConstraint | int | TypeForm[int] | None = None,
) -> AttrConstraint[IntAttr]:
    if int_constraint is None:
        return BaseAttr(IntAttr)
    if not isinstance(int_constraint, IntConstraint):
        int_constraint = get_int_constraint(int_constraint)
    if int_constraint == AnyInt():
        return BaseAttr(IntAttr)
    if isinstance(int_constraint, EqIntConstraint):
        return EqAttrConstraint(IntAttr(int_constraint.value))
    return IntAttrConstraint(int_constraint)

verify(attr: Attribute, constraint_context: ConstraintContext) -> None

Source code in xdsl/dialects/builtin.py
442
443
444
445
def verify(self, attr: Attribute, constraint_context: ConstraintContext) -> None:
    if not isa(attr, IntAttr):
        raise VerifyException(f"attribute {attr} expected to be an IntAttr")
    self.int_constraint.verify(attr.data, constraint_context)

variables() -> set[str]

Source code in xdsl/dialects/builtin.py
447
448
def variables(self) -> set[str]:
    return self.int_constraint.variables()

can_infer(var_constraint_names: AbstractSet[str]) -> bool

Source code in xdsl/dialects/builtin.py
450
451
def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
    return self.int_constraint.can_infer(var_constraint_names)

infer(context: ConstraintContext) -> IntAttr

Source code in xdsl/dialects/builtin.py
453
454
def infer(self, context: ConstraintContext) -> IntAttr:
    return IntAttr(self.int_constraint.infer(context))

get_bases() -> set[type[Attribute]] | None

Source code in xdsl/dialects/builtin.py
456
457
def get_bases(self) -> set[type[Attribute]] | None:
    return {IntAttr}

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint])

Source code in xdsl/dialects/builtin.py
459
460
461
462
463
464
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
):
    return IntAttrConstraint.get(
        self.int_constraint.mapping_type_vars(type_var_mapping)
    )

Signedness

Bases: ConstraintConvertible, Enum

Signedness semantics for integer

Source code in xdsl/dialects/builtin.py
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
class Signedness(ConstraintConvertible, Enum):
    "Signedness semantics for integer"

    SIGNLESS = 0
    "No signedness semantics"

    SIGNED = 1
    UNSIGNED = 2

    def value_range(self, bitwidth: int) -> tuple[int, int]:
        """
        For a given bitwidth, returns (min, max+1), where min and max are the smallest and
        largest representable values.

        Signless integers are bit patterns, so the representable range is the union of the
        signed and unsigned representable ranges.
        """
        match self:
            case Signedness.SIGNLESS:
                return signless_value_range(bitwidth)
            case Signedness.SIGNED:
                return signed_value_range(bitwidth)
            case Signedness.UNSIGNED:
                return unsigned_value_range(bitwidth)

    @staticmethod
    def base_constr() -> AttrConstraint[SignednessAttr]:
        """The constraint for this class."""
        return BaseAttr(SignednessAttr)

    def constr(self) -> AttrConstraint[SignednessAttr]:
        return EqAttrConstraint(SignednessAttr(self))

SIGNLESS = 0 class-attribute instance-attribute

No signedness semantics

SIGNED = 1 class-attribute instance-attribute

UNSIGNED = 2 class-attribute instance-attribute

value_range(bitwidth: int) -> tuple[int, int]

For a given bitwidth, returns (min, max+1), where min and max are the smallest and largest representable values.

Signless integers are bit patterns, so the representable range is the union of the signed and unsigned representable ranges.

Source code in xdsl/dialects/builtin.py
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
def value_range(self, bitwidth: int) -> tuple[int, int]:
    """
    For a given bitwidth, returns (min, max+1), where min and max are the smallest and
    largest representable values.

    Signless integers are bit patterns, so the representable range is the union of the
    signed and unsigned representable ranges.
    """
    match self:
        case Signedness.SIGNLESS:
            return signless_value_range(bitwidth)
        case Signedness.SIGNED:
            return signed_value_range(bitwidth)
        case Signedness.UNSIGNED:
            return unsigned_value_range(bitwidth)

base_constr() -> AttrConstraint[SignednessAttr] staticmethod

The constraint for this class.

Source code in xdsl/dialects/builtin.py
510
511
512
513
@staticmethod
def base_constr() -> AttrConstraint[SignednessAttr]:
    """The constraint for this class."""
    return BaseAttr(SignednessAttr)

constr() -> AttrConstraint[SignednessAttr]

Source code in xdsl/dialects/builtin.py
515
516
def constr(self) -> AttrConstraint[SignednessAttr]:
    return EqAttrConstraint(SignednessAttr(self))

SignednessAttr dataclass

Bases: GenericData[_SignednessCovT], Generic[_SignednessCovT]

Source code in xdsl/dialects/builtin.py
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
@irdl_attr_definition
class SignednessAttr(GenericData[_SignednessCovT], Generic[_SignednessCovT]):
    name = "builtin.signedness"

    @classmethod
    def parse_parameter(cls, parser: AttrParser) -> _SignednessCovT:
        with parser.in_angle_brackets():
            if parser.parse_optional_keyword("signless") is not None:
                return Signedness.SIGNLESS  # pyright: ignore[reportReturnType]
            if parser.parse_optional_keyword("signed") is not None:
                return Signedness.SIGNED  # pyright: ignore[reportReturnType]
            if parser.parse_optional_keyword("unsigned") is not None:
                return Signedness.UNSIGNED  # pyright: ignore[reportReturnType]
            parser.raise_error("`signless`, `signed`, or `unsigned` expected")

    def print_parameter(self, printer: Printer) -> None:
        with printer.in_angle_brackets():
            data = self.data
            if data == Signedness.SIGNLESS:
                printer.print_string("signless")
            elif data == Signedness.SIGNED:
                printer.print_string("signed")
            elif data == Signedness.UNSIGNED:
                printer.print_string("unsigned")
            else:
                raise ValueError(f"Invalid signedness {data}")

    @staticmethod
    def constr() -> AttrConstraint:
        return TypeVarConstraint(_SignednessCovT, BaseAttr(SignednessAttr))

name = 'builtin.signedness' class-attribute instance-attribute

parse_parameter(parser: AttrParser) -> _SignednessCovT classmethod

Source code in xdsl/dialects/builtin.py
528
529
530
531
532
533
534
535
536
537
@classmethod
def parse_parameter(cls, parser: AttrParser) -> _SignednessCovT:
    with parser.in_angle_brackets():
        if parser.parse_optional_keyword("signless") is not None:
            return Signedness.SIGNLESS  # pyright: ignore[reportReturnType]
        if parser.parse_optional_keyword("signed") is not None:
            return Signedness.SIGNED  # pyright: ignore[reportReturnType]
        if parser.parse_optional_keyword("unsigned") is not None:
            return Signedness.UNSIGNED  # pyright: ignore[reportReturnType]
        parser.raise_error("`signless`, `signed`, or `unsigned` expected")

print_parameter(printer: Printer) -> None

Source code in xdsl/dialects/builtin.py
539
540
541
542
543
544
545
546
547
548
549
def print_parameter(self, printer: Printer) -> None:
    with printer.in_angle_brackets():
        data = self.data
        if data == Signedness.SIGNLESS:
            printer.print_string("signless")
        elif data == Signedness.SIGNED:
            printer.print_string("signed")
        elif data == Signedness.UNSIGNED:
            printer.print_string("unsigned")
        else:
            raise ValueError(f"Invalid signedness {data}")

constr() -> AttrConstraint staticmethod

Source code in xdsl/dialects/builtin.py
551
552
553
@staticmethod
def constr() -> AttrConstraint:
    return TypeVarConstraint(_SignednessCovT, BaseAttr(SignednessAttr))

CompileTimeFixedBitwidthType dataclass

Bases: TypeAttribute, ABC

A type attribute whose runtime bitwidth is fixed, but may be target-dependent.

Source code in xdsl/dialects/builtin.py
556
557
558
559
560
561
562
563
564
565
566
567
568
569
class CompileTimeFixedBitwidthType(TypeAttribute, ABC):
    """
    A type attribute whose runtime bitwidth is fixed, but may be target-dependent.
    """

    name = "abstract.compile_time_fixed_bitwidth_type"

    @property
    @abstractmethod
    def compile_time_size(self) -> int:
        """
        Contiguous memory footprint in bytes of the value during compilation.
        """
        raise NotImplementedError()

name = 'abstract.compile_time_fixed_bitwidth_type' class-attribute instance-attribute

compile_time_size: int abstractmethod property

Contiguous memory footprint in bytes of the value during compilation.

FixedBitwidthType dataclass

Bases: CompileTimeFixedBitwidthType, ABC

A type attribute whose runtime bitwidth is target-independent.

Source code in xdsl/dialects/builtin.py
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
class FixedBitwidthType(CompileTimeFixedBitwidthType, ABC):
    """
    A type attribute whose runtime bitwidth is target-independent.
    """

    name = "abstract.fixed_bitwidth_type"

    @property
    @abstractmethod
    def bitwidth(self) -> int:
        """
        Contiguous memory footprint in bits
        """
        raise NotImplementedError()

    @property
    def size(self) -> int:
        """
        Contiguous memory footprint in bytes, defaults to `ceil(bitwidth / 8)`
        """
        return (self.bitwidth + 7) >> 3

name = 'abstract.fixed_bitwidth_type' class-attribute instance-attribute

bitwidth: int abstractmethod property

Contiguous memory footprint in bits

size: int property

Contiguous memory footprint in bytes, defaults to ceil(bitwidth / 8)

PackableType dataclass

Bases: CompileTimeFixedBitwidthType, ABC, Generic[_PyT]

Abstract base class for xDSL types whose values can be encoded and decoded as bytes.

Source code in xdsl/dialects/builtin.py
598
599
600
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
class PackableType(CompileTimeFixedBitwidthType, ABC, Generic[_PyT]):
    """
    Abstract base class for xDSL types whose values can be encoded and decoded as bytes.
    """

    @abstractmethod
    def iter_unpack(self, buffer: ReadableBuffer, /) -> Iterator[_PyT]:
        """
        Yields unpacked values one at a time, starting at the beginning of the buffer.

        Raises `ValueError` if `len(buffer)` is not divisible by
        `self.compile_time_size`.
        """
        raise NotImplementedError()

    @abstractmethod
    def unpack(self, buffer: ReadableBuffer, num: int, /) -> tuple[_PyT, ...]:
        """
        Unpack `num` values from the beginning of the buffer.

        Raises `ValueError` if `len(buffer) != num * self.compile_time_size`.
        """
        raise NotImplementedError()

    @abstractmethod
    def pack_into(self, buffer: WriteableBuffer, offset: int, value: _PyT) -> None:
        """
        Pack a value at a given offset into a buffer.

        Raises `ValueError` if `len(buffer) < offset + self.compile_time_size`.
        """
        raise NotImplementedError()

    @abstractmethod
    def pack(self, values: Sequence[_PyT]) -> bytes:
        """
        Create a new buffer containing the input `values`.
        """
        raise NotImplementedError()

iter_unpack(buffer: ReadableBuffer) -> Iterator[_PyT] abstractmethod

Yields unpacked values one at a time, starting at the beginning of the buffer.

Raises ValueError if len(buffer) is not divisible by self.compile_time_size.

Source code in xdsl/dialects/builtin.py
603
604
605
606
607
608
609
610
611
@abstractmethod
def iter_unpack(self, buffer: ReadableBuffer, /) -> Iterator[_PyT]:
    """
    Yields unpacked values one at a time, starting at the beginning of the buffer.

    Raises `ValueError` if `len(buffer)` is not divisible by
    `self.compile_time_size`.
    """
    raise NotImplementedError()

unpack(buffer: ReadableBuffer, num: int) -> tuple[_PyT, ...] abstractmethod

Unpack num values from the beginning of the buffer.

Raises ValueError if len(buffer) != num * self.compile_time_size.

Source code in xdsl/dialects/builtin.py
613
614
615
616
617
618
619
620
@abstractmethod
def unpack(self, buffer: ReadableBuffer, num: int, /) -> tuple[_PyT, ...]:
    """
    Unpack `num` values from the beginning of the buffer.

    Raises `ValueError` if `len(buffer) != num * self.compile_time_size`.
    """
    raise NotImplementedError()

pack_into(buffer: WriteableBuffer, offset: int, value: _PyT) -> None abstractmethod

Pack a value at a given offset into a buffer.

Raises ValueError if len(buffer) < offset + self.compile_time_size.

Source code in xdsl/dialects/builtin.py
622
623
624
625
626
627
628
629
@abstractmethod
def pack_into(self, buffer: WriteableBuffer, offset: int, value: _PyT) -> None:
    """
    Pack a value at a given offset into a buffer.

    Raises `ValueError` if `len(buffer) < offset + self.compile_time_size`.
    """
    raise NotImplementedError()

pack(values: Sequence[_PyT]) -> bytes abstractmethod

Create a new buffer containing the input values.

Source code in xdsl/dialects/builtin.py
631
632
633
634
635
636
@abstractmethod
def pack(self, values: Sequence[_PyT]) -> bytes:
    """
    Create a new buffer containing the input `values`.
    """
    raise NotImplementedError()

StructPackableType dataclass

Bases: PackableType[_PyT], ABC, Generic[_PyT]

Abstract base class for xDSL types that can be packed and unpacked using Python's struct package, using a format string.

Source code in xdsl/dialects/builtin.py
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
666
667
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
class StructPackableType(PackableType[_PyT], ABC, Generic[_PyT]):
    """
    Abstract base class for xDSL types that can be packed and unpacked using Python's
    `struct` package, using a format string.
    """

    @property
    @abstractmethod
    def format(self) -> str:
        """
        Format to be used when decoding and encoding bytes.

        See external [documentation](https://docs.python.org/3/library/struct.html).
        """
        raise NotImplementedError()

    def iter_unpack(self, buffer: ReadableBuffer, /) -> Iterator[_PyT]:
        try:
            return (values[0] for values in struct.iter_unpack(self.format, buffer))
        except struct.error:
            buffer_size = len(memoryview(buffer))
            compile_time_size = self.compile_time_size
            if buffer_size % compile_time_size:
                raise ValueError(
                    f"Buffer length {buffer_size} not multiple of {self.name} element "
                    f"size {compile_time_size}."
                )
            # Re-raise unexpected struct.error
            raise

    def unpack(self, buffer: ReadableBuffer, num: int, /) -> tuple[_PyT, ...]:
        fmt = self.format[0] + str(num) + self.format[1:]
        try:
            return struct.unpack(fmt, buffer)
        except struct.error:
            buffer_size = len(memoryview(buffer))
            compile_time_size = self.compile_time_size
            if buffer_size != num * compile_time_size:
                raise ValueError(
                    f"Buffer length {buffer_size} not product of {self.name} element "
                    f"size {compile_time_size} and num {num}."
                )
            # Re-raise unexpected struct.error
            raise

    def pack_into(self, buffer: WriteableBuffer, offset: int, value: _PyT) -> None:
        try:
            struct.pack_into(self.format, buffer, offset, value)
        except struct.error:
            buffer_size = len(memoryview(buffer))
            compile_time_size = self.compile_time_size
            if buffer_size < offset + compile_time_size:
                raise ValueError(
                    f"Buffer length {buffer_size} too small for packing "
                    f"{compile_time_size} bytes at offset {offset}, expected at least "
                    f"{offset + compile_time_size}."
                )
            # Re-raise unexpected struct.error
            raise

    def pack(self, values: Sequence[_PyT]) -> bytes:
        fmt = self.format[0] + str(len(values)) + self.format[1:]
        return struct.pack(fmt, *values)

    @property
    def compile_time_size(self) -> int:
        return struct.calcsize(self.format)

format: str abstractmethod property

Format to be used when decoding and encoding bytes.

See external documentation.

compile_time_size: int property

iter_unpack(buffer: ReadableBuffer) -> Iterator[_PyT]

Source code in xdsl/dialects/builtin.py
655
656
657
658
659
660
661
662
663
664
665
666
667
def iter_unpack(self, buffer: ReadableBuffer, /) -> Iterator[_PyT]:
    try:
        return (values[0] for values in struct.iter_unpack(self.format, buffer))
    except struct.error:
        buffer_size = len(memoryview(buffer))
        compile_time_size = self.compile_time_size
        if buffer_size % compile_time_size:
            raise ValueError(
                f"Buffer length {buffer_size} not multiple of {self.name} element "
                f"size {compile_time_size}."
            )
        # Re-raise unexpected struct.error
        raise

unpack(buffer: ReadableBuffer, num: int) -> tuple[_PyT, ...]

Source code in xdsl/dialects/builtin.py
669
670
671
672
673
674
675
676
677
678
679
680
681
682
def unpack(self, buffer: ReadableBuffer, num: int, /) -> tuple[_PyT, ...]:
    fmt = self.format[0] + str(num) + self.format[1:]
    try:
        return struct.unpack(fmt, buffer)
    except struct.error:
        buffer_size = len(memoryview(buffer))
        compile_time_size = self.compile_time_size
        if buffer_size != num * compile_time_size:
            raise ValueError(
                f"Buffer length {buffer_size} not product of {self.name} element "
                f"size {compile_time_size} and num {num}."
            )
        # Re-raise unexpected struct.error
        raise

pack_into(buffer: WriteableBuffer, offset: int, value: _PyT) -> None

Source code in xdsl/dialects/builtin.py
684
685
686
687
688
689
690
691
692
693
694
695
696
697
def pack_into(self, buffer: WriteableBuffer, offset: int, value: _PyT) -> None:
    try:
        struct.pack_into(self.format, buffer, offset, value)
    except struct.error:
        buffer_size = len(memoryview(buffer))
        compile_time_size = self.compile_time_size
        if buffer_size < offset + compile_time_size:
            raise ValueError(
                f"Buffer length {buffer_size} too small for packing "
                f"{compile_time_size} bytes at offset {offset}, expected at least "
                f"{offset + compile_time_size}."
            )
        # Re-raise unexpected struct.error
        raise

pack(values: Sequence[_PyT]) -> bytes

Source code in xdsl/dialects/builtin.py
699
700
701
def pack(self, values: Sequence[_PyT]) -> bytes:
    fmt = self.format[0] + str(len(values)) + self.format[1:]
    return struct.pack(fmt, *values)

IntegerType

Bases: ParametrizedAttribute, StructPackableType[int], FixedBitwidthType, BuiltinAttribute, Generic[_IntCovT, _SignednessCovT]

Source code in xdsl/dialects/builtin.py
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
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
791
792
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
@irdl_attr_definition
class IntegerType(
    ParametrizedAttribute,
    StructPackableType[int],
    FixedBitwidthType,
    BuiltinAttribute,
    Generic[_IntCovT, _SignednessCovT],
):
    name = "integer_type"
    width: IntAttr[_IntCovT]
    signedness: SignednessAttr[_SignednessCovT]

    def __init__(
        self,
        data: _IntCovT | IntAttr[_IntCovT],
        signedness: _SignednessCovT
        | SignednessAttr[_SignednessCovT] = Signedness.SIGNLESS,
    ) -> None:
        if isinstance(data, int):
            data = IntAttr(data)
        if isinstance(signedness, Signedness):
            signedness = SignednessAttr(signedness)
        super().__init__(data, signedness)

    def print_builtin(self, printer: Printer) -> None:
        if self.signedness.data == Signedness.SIGNLESS:
            printer.print_string("i")
        elif self.signedness.data == Signedness.SIGNED:
            printer.print_string("si")
        elif self.signedness.data == Signedness.UNSIGNED:
            printer.print_string("ui")
        printer.print_int(self.width.data)

    def __repr__(self):
        width = self.width.data
        signedness = self.signedness.data
        if signedness == Signedness.SIGNLESS:
            return f"IntegerType({width})"
        else:
            return f"IntegerType({width}, {signedness})"

    def verify(self):
        if self.width.data < 0:
            raise VerifyException(
                f"integer type bitwidth should be nonnegative (got {self.width.data})"
            )

    def value_range(self) -> tuple[int, int]:
        return self.signedness.data.value_range(self.width.data)

    def verify_value(self, value: int):
        min_value, max_value = self.value_range()

        if not (min_value <= value < max_value):
            raise VerifyException(
                f"Integer value {value} is out of range for type {self} which supports "
                f"values in the range [{min_value}, {max_value})"
            )

    def normalized_value(
        self, value: int, *, truncate_bits: bool = False
    ) -> int | None:
        """
        Signless values can represent integers from both the signed and unsigned ranges
        for a given bitwidth.
        We choose to normalize values that are not in the intersection of the two ranges
        to the signed version (meaning ambiguous values will always be negative).
        For example, the bitpattern of all ones will always be represented as `-1` at
        runtime.
        If the input value is outside of the valid range, return `None` if `truncate_bits`
        is false, otherwise returns a value in range by truncating the bits of the input.
        """
        min_value, max_value = self.value_range()
        if not (min_value <= value < max_value):
            if not truncate_bits:
                return None
            value = value % (2**self.bitwidth)

        if self.signedness.data != Signedness.UNSIGNED:
            signed_ub = signed_upper_bound(self.bitwidth)
            unsigned_ub = unsigned_upper_bound(self.bitwidth)
            if signed_ub <= value:
                return value - unsigned_ub

        return value

    def get_normalized_value(self, value: int) -> int:
        """
        Normalises an integer value similarly to the `normalized_value` function,
        but throws a ValueError when the value falls outside the type's range.
        """
        v = self.normalized_value(value)
        if v is None:
            min_value, max_value = self.value_range()
            raise ValueError(
                f"Integer value {value} is out of range for type {self} which supports "
                f"values in the range [{min_value}, {max_value})"
            )
        return v

    @property
    def bitwidth(self) -> int:
        return self.width.data

    @property
    def format(self) -> str:
        format_index = ((self.bitwidth + 7) >> 3) - 1  #  = ceil(bw / 8) - 1
        if format_index >= 8:
            raise NotImplementedError(f"Format not implemented for {self}")

        unsigned = self.signedness.data == Signedness.UNSIGNED
        f = _UNSIGNED_INTEGER_FORMATS if unsigned else _SIGNED_INTEGER_FORMATS
        return f[format_index]

name = 'integer_type' class-attribute instance-attribute

width: IntAttr[_IntCovT] instance-attribute

signedness: SignednessAttr[_SignednessCovT] instance-attribute

bitwidth: int property

format: str property

__init__(data: _IntCovT | IntAttr[_IntCovT], signedness: _SignednessCovT | SignednessAttr[_SignednessCovT] = Signedness.SIGNLESS) -> None

Source code in xdsl/dialects/builtin.py
732
733
734
735
736
737
738
739
740
741
742
def __init__(
    self,
    data: _IntCovT | IntAttr[_IntCovT],
    signedness: _SignednessCovT
    | SignednessAttr[_SignednessCovT] = Signedness.SIGNLESS,
) -> None:
    if isinstance(data, int):
        data = IntAttr(data)
    if isinstance(signedness, Signedness):
        signedness = SignednessAttr(signedness)
    super().__init__(data, signedness)

print_builtin(printer: Printer) -> None

Source code in xdsl/dialects/builtin.py
744
745
746
747
748
749
750
751
def print_builtin(self, printer: Printer) -> None:
    if self.signedness.data == Signedness.SIGNLESS:
        printer.print_string("i")
    elif self.signedness.data == Signedness.SIGNED:
        printer.print_string("si")
    elif self.signedness.data == Signedness.UNSIGNED:
        printer.print_string("ui")
    printer.print_int(self.width.data)

__repr__()

Source code in xdsl/dialects/builtin.py
753
754
755
756
757
758
759
def __repr__(self):
    width = self.width.data
    signedness = self.signedness.data
    if signedness == Signedness.SIGNLESS:
        return f"IntegerType({width})"
    else:
        return f"IntegerType({width}, {signedness})"

verify()

Source code in xdsl/dialects/builtin.py
761
762
763
764
765
def verify(self):
    if self.width.data < 0:
        raise VerifyException(
            f"integer type bitwidth should be nonnegative (got {self.width.data})"
        )

value_range() -> tuple[int, int]

Source code in xdsl/dialects/builtin.py
767
768
def value_range(self) -> tuple[int, int]:
    return self.signedness.data.value_range(self.width.data)

verify_value(value: int)

Source code in xdsl/dialects/builtin.py
770
771
772
773
774
775
776
777
def verify_value(self, value: int):
    min_value, max_value = self.value_range()

    if not (min_value <= value < max_value):
        raise VerifyException(
            f"Integer value {value} is out of range for type {self} which supports "
            f"values in the range [{min_value}, {max_value})"
        )

normalized_value(value: int, *, truncate_bits: bool = False) -> int | None

Signless values can represent integers from both the signed and unsigned ranges for a given bitwidth. We choose to normalize values that are not in the intersection of the two ranges to the signed version (meaning ambiguous values will always be negative). For example, the bitpattern of all ones will always be represented as -1 at runtime. If the input value is outside of the valid range, return None if truncate_bits is false, otherwise returns a value in range by truncating the bits of the input.

Source code in xdsl/dialects/builtin.py
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
def normalized_value(
    self, value: int, *, truncate_bits: bool = False
) -> int | None:
    """
    Signless values can represent integers from both the signed and unsigned ranges
    for a given bitwidth.
    We choose to normalize values that are not in the intersection of the two ranges
    to the signed version (meaning ambiguous values will always be negative).
    For example, the bitpattern of all ones will always be represented as `-1` at
    runtime.
    If the input value is outside of the valid range, return `None` if `truncate_bits`
    is false, otherwise returns a value in range by truncating the bits of the input.
    """
    min_value, max_value = self.value_range()
    if not (min_value <= value < max_value):
        if not truncate_bits:
            return None
        value = value % (2**self.bitwidth)

    if self.signedness.data != Signedness.UNSIGNED:
        signed_ub = signed_upper_bound(self.bitwidth)
        unsigned_ub = unsigned_upper_bound(self.bitwidth)
        if signed_ub <= value:
            return value - unsigned_ub

    return value

get_normalized_value(value: int) -> int

Normalises an integer value similarly to the normalized_value function, but throws a ValueError when the value falls outside the type's range.

Source code in xdsl/dialects/builtin.py
806
807
808
809
810
811
812
813
814
815
816
817
818
def get_normalized_value(self, value: int) -> int:
    """
    Normalises an integer value similarly to the `normalized_value` function,
    but throws a ValueError when the value falls outside the type's range.
    """
    v = self.normalized_value(value)
    if v is None:
        min_value, max_value = self.value_range()
        raise ValueError(
            f"Integer value {value} is out of range for type {self} which supports "
            f"values in the range [{min_value}, {max_value})"
        )
    return v

UnitAttr dataclass

Bases: ParametrizedAttribute, BuiltinAttribute

Source code in xdsl/dialects/builtin.py
857
858
859
860
861
862
@irdl_attr_definition
class UnitAttr(ParametrizedAttribute, BuiltinAttribute):
    name = "unit"

    def print_builtin(self, printer: Printer) -> None:
        printer.print_string("unit")

name = 'unit' class-attribute instance-attribute

print_builtin(printer: Printer) -> None

Source code in xdsl/dialects/builtin.py
861
862
def print_builtin(self, printer: Printer) -> None:
    printer.print_string("unit")

LocationConstraint dataclass

Bases: AttrConstraint

Check if an attribute is one of the supported location types.

Source code in xdsl/dialects/builtin.py
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
class LocationConstraint(AttrConstraint):
    """
    Check if an attribute is one of the supported location types.
    """

    def verify(self, attr: Attribute, constraint_context: ConstraintContext) -> None:
        if isinstance(attr, LocationAttr) or isinstance(attr, NoneAttr):
            return
        raise VerifyException(f"{attr} is not a location attribute")

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> AttrConstraint:
        # No type variables to map in this constraint
        return self

verify(attr: Attribute, constraint_context: ConstraintContext) -> None

Source code in xdsl/dialects/builtin.py
870
871
872
873
def verify(self, attr: Attribute, constraint_context: ConstraintContext) -> None:
    if isinstance(attr, LocationAttr) or isinstance(attr, NoneAttr):
        return
    raise VerifyException(f"{attr} is not a location attribute")

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> AttrConstraint

Source code in xdsl/dialects/builtin.py
875
876
877
878
879
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> AttrConstraint:
    # No type variables to map in this constraint
    return self

LocationsArrayConstraint

Bases: AttrConstraint

Check if an attribute is one of the supported location types.

Source code in xdsl/dialects/builtin.py
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
class LocationsArrayConstraint(AttrConstraint):
    """
    Check if an attribute is one of the supported location types.
    """

    def __init__(self):
        self.location_constraint = LocationConstraint()

    def verify(self, attr: Attribute, constraint_context: ConstraintContext) -> None:
        array = cast(ArrayAttr[Attribute], attr)
        element: Attribute
        for element in array:
            self.location_constraint.verify(element, constraint_context)

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> AttrConstraint:
        # No type variables to map in this constraint
        return self

location_constraint = LocationConstraint() instance-attribute

__init__()

Source code in xdsl/dialects/builtin.py
887
888
def __init__(self):
    self.location_constraint = LocationConstraint()

verify(attr: Attribute, constraint_context: ConstraintContext) -> None

Source code in xdsl/dialects/builtin.py
890
891
892
893
894
def verify(self, attr: Attribute, constraint_context: ConstraintContext) -> None:
    array = cast(ArrayAttr[Attribute], attr)
    element: Attribute
    for element in array:
        self.location_constraint.verify(element, constraint_context)

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> AttrConstraint

Source code in xdsl/dialects/builtin.py
896
897
898
899
900
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> AttrConstraint:
    # No type variables to map in this constraint
    return self

UnknownLoc dataclass

Bases: ParametrizedAttribute, BuiltinAttribute

Syntax:

unknown-location ::= `unknown`

Source location information is an extremely integral part of the MLIR infrastructure. As such, location information is always present in the IR, and must explicitly be set to unknown. Thus, an instance of the unknown location represents an unspecified source location.

Example:

loc(unknown)
Source code in xdsl/dialects/builtin.py
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
@irdl_attr_definition
class UnknownLoc(ParametrizedAttribute, BuiltinAttribute):
    """
    Syntax:

    ```
    unknown-location ::= `unknown`
    ```

    Source location information is an extremely integral part of the MLIR
    infrastructure. As such, location information is always present in the IR,
    and must explicitly be set to unknown. Thus, an instance of the `unknown`
    location represents an unspecified source location.

    Example:

    ```mlir
    loc(unknown)
    ```
    """

    name = "unknown_loc"

    def print_builtin(self, printer: Printer) -> None:
        with printer.in_location():
            printer.print_string("unknown")

name = 'unknown_loc' class-attribute instance-attribute

print_builtin(printer: Printer) -> None

Source code in xdsl/dialects/builtin.py
926
927
928
def print_builtin(self, printer: Printer) -> None:
    with printer.in_location():
        printer.print_string("unknown")

FileLineColLoc dataclass

Bases: ParametrizedAttribute, BuiltinAttribute

Syntax:

filelinecol-location ::= string-literal `:` integer-literal `:`
                         integer-literal

An instance of this location represents a tuple of file, line number, and column number. This is similar to the type of location that you get from most source languages.

Example:

loc("mysource.cc":10:8)
Source code in xdsl/dialects/builtin.py
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
@irdl_attr_definition
class FileLineColLoc(ParametrizedAttribute, BuiltinAttribute):
    """
    Syntax:

    ```
    filelinecol-location ::= string-literal `:` integer-literal `:`
                             integer-literal
    ```

    An instance of this location represents a tuple of file, line number, and
    column number. This is similar to the type of location that you get from
    most source languages.

    Example:

    ```mlir
    loc("mysource.cc":10:8)
    ```
    """

    name = "file_line_loc"

    filename: StringAttr = param_def()
    line: IntAttr = param_def()
    column: IntAttr = param_def()

    def print_builtin(self, printer: Printer) -> None:
        with printer.in_location():
            printer.print_string_literal(self.filename.data)
            printer.print_string(":")
            printer.print_int(self.line.data)
            printer.print_string(":")
            printer.print_int(self.column.data)

name = 'file_line_loc' class-attribute instance-attribute

filename: StringAttr = param_def() class-attribute instance-attribute

line: IntAttr = param_def() class-attribute instance-attribute

column: IntAttr = param_def() class-attribute instance-attribute

print_builtin(printer: Printer) -> None

Source code in xdsl/dialects/builtin.py
958
959
960
961
962
963
964
def print_builtin(self, printer: Printer) -> None:
    with printer.in_location():
        printer.print_string_literal(self.filename.data)
        printer.print_string(":")
        printer.print_int(self.line.data)
        printer.print_string(":")
        printer.print_int(self.column.data)

CallSiteLoc dataclass

Bases: ParametrizedAttribute, BuiltinAttribute

Source code in xdsl/dialects/builtin.py
967
968
969
970
971
972
973
974
975
976
977
978
979
980
@irdl_attr_definition
class CallSiteLoc(ParametrizedAttribute, BuiltinAttribute):
    name = "builtin.callsite_loc"

    callee: Attribute = param_def(LocationConstraint())
    caller: Attribute = param_def(LocationConstraint())

    def print_builtin(self, printer: Printer) -> None:
        with printer.in_location():
            printer.print_string("callsite(")
            printer.print_attribute(self.callee)
            printer.print_string(" at ")
            printer.print_attribute(self.caller)
            printer.print_string(")")

name = 'builtin.callsite_loc' class-attribute instance-attribute

callee: Attribute = param_def(LocationConstraint()) class-attribute instance-attribute

caller: Attribute = param_def(LocationConstraint()) class-attribute instance-attribute

print_builtin(printer: Printer) -> None

Source code in xdsl/dialects/builtin.py
974
975
976
977
978
979
980
def print_builtin(self, printer: Printer) -> None:
    with printer.in_location():
        printer.print_string("callsite(")
        printer.print_attribute(self.callee)
        printer.print_string(" at ")
        printer.print_attribute(self.caller)
        printer.print_string(")")

FusedLoc dataclass

Bases: ParametrizedAttribute, BuiltinAttribute

Source code in xdsl/dialects/builtin.py
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
@irdl_attr_definition
class FusedLoc(ParametrizedAttribute, BuiltinAttribute):
    name = "builtin.fused_loc"

    locations: Attribute = param_def(
        constraint=LocationsArrayConstraint(), converter=ArrayAttr[Attribute].get
    )
    metadata: Attribute = param_def()

    def print_builtin(self, printer: Printer) -> None:
        with printer.in_location():
            printer.print_string("fused")
            if not isinstance(self.metadata, NoneAttr):
                printer.print_string("<")
                printer.print_attribute(self.metadata)
                printer.print_string(">")
            printer.print_attribute(self.locations)

name = 'builtin.fused_loc' class-attribute instance-attribute

locations: Attribute = param_def(constraint=(LocationsArrayConstraint()), converter=(ArrayAttr[Attribute].get)) class-attribute instance-attribute

metadata: Attribute = param_def() class-attribute instance-attribute

print_builtin(printer: Printer) -> None

Source code in xdsl/dialects/builtin.py
992
993
994
995
996
997
998
999
def print_builtin(self, printer: Printer) -> None:
    with printer.in_location():
        printer.print_string("fused")
        if not isinstance(self.metadata, NoneAttr):
            printer.print_string("<")
            printer.print_attribute(self.metadata)
            printer.print_string(">")
        printer.print_attribute(self.locations)

NameLoc dataclass

Bases: ParametrizedAttribute, BuiltinAttribute

Source code in xdsl/dialects/builtin.py
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
@irdl_attr_definition
class NameLoc(ParametrizedAttribute, BuiltinAttribute):
    name = "builtin.name_loc"

    desc: StringAttr = param_def()
    location: Attribute = param_def(LocationConstraint())

    def print_builtin(self, printer: Printer) -> None:
        with printer.in_location():
            printer.print_attribute(self.desc)
            if not isinstance(self.location, NoneAttr):
                printer.print_string("(")
                printer.print_attribute(self.location)
                printer.print_string(")")

name = 'builtin.name_loc' class-attribute instance-attribute

desc: StringAttr = param_def() class-attribute instance-attribute

location: Attribute = param_def(LocationConstraint()) class-attribute instance-attribute

print_builtin(printer: Printer) -> None

Source code in xdsl/dialects/builtin.py
1009
1010
1011
1012
1013
1014
1015
def print_builtin(self, printer: Printer) -> None:
    with printer.in_location():
        printer.print_attribute(self.desc)
        if not isinstance(self.location, NoneAttr):
            printer.print_string("(")
            printer.print_attribute(self.location)
            printer.print_string(")")

IndexType dataclass

Bases: ParametrizedAttribute, BuiltinAttribute, StructPackableType[int]

Source code in xdsl/dialects/builtin.py
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
@irdl_attr_definition
class IndexType(ParametrizedAttribute, BuiltinAttribute, StructPackableType[int]):
    name = "index"

    def print_builtin(self, printer: Printer):
        printer.print_string("index")

    @property
    def format(self) -> str:
        # index types are always packable as int64
        return "<q"

name = 'index' class-attribute instance-attribute

format: str property

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
1032
1033
def print_builtin(self, printer: Printer):
    printer.print_string("index")

IntegerAttr

Bases: BuiltinAttribute, TypedAttribute, Generic[_IntegerAttrTypeCovT]

Source code in xdsl/dialects/builtin.py
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
@irdl_attr_definition
class IntegerAttr(
    BuiltinAttribute,
    TypedAttribute,
    Generic[_IntegerAttrTypeCovT],
):
    name = "integer"
    value: IntAttr
    type: _IntegerAttrTypeCovT

    @overload
    def __init__(
        self,
        value: int | IntAttr,
        value_type: _IntegerAttrTypeCovT,
        *,
        truncate_bits: bool = False,
    ) -> None: ...

    @overload
    def __init__(
        self: IntegerAttr[IntegerType[_IntCovT, Literal[Signedness.SIGNLESS]]],
        value: int | IntAttr,
        value_type: _IntCovT,
        *,
        truncate_bits: bool = False,
    ) -> None: ...

    def __init__(
        self,
        value: int | IntAttr,
        value_type: _IntCovT | IntegerType[_IntCovT] | IndexType,
        *,
        truncate_bits: bool = False,
    ) -> None:
        if isinstance(value_type, int):
            value_type = IntegerType(value_type)
        if not isinstance(value, int):
            value = value.data
        if not isinstance(value_type, IndexType):
            normalized_value = value_type.normalized_value(
                value, truncate_bits=truncate_bits
            )
            if normalized_value is not None:
                value = normalized_value
        super().__init__(IntAttr(value), value_type)

    @staticmethod
    def from_index_int_value(value: int) -> IntegerAttr[IndexType]:
        return IntegerAttr(value, IndexType())

    @staticmethod
    def from_bool(value: bool) -> BoolAttr:
        return IntegerAttr(value, 1)

    def print_builtin(self, printer: Printer) -> None:
        ty = self.type
        printer.print_int(self.value.data, ty)
        if ty != i1:
            printer.print_string(" : ")
            printer.print_attribute(ty)

    def verify(self) -> None:
        if isinstance(int_type := self.type, IndexType):
            return

        int_type.verify_value(self.value.data)

    @staticmethod
    def parse_with_type(
        parser: AttrParser,
        type: Attribute,
    ) -> TypedAttribute:
        assert isa(type, IntegerType | IndexType)
        return IntegerAttr(parser.parse_integer(allow_boolean=(type == i1)), type)

    def print_without_type(self, printer: Printer):
        printer.print_int(self.value.data, self.type)

    def get_type(self) -> Attribute:
        return self.type

    @staticmethod
    def constr(
        type: IRDLAttrConstraint[_IntegerAttrTypeCovT] = IntegerAttrTypeConstr,
        *,
        value: AttrConstraint | IntConstraint | None = None,
    ) -> AttrConstraint[IntegerAttr[_IntegerAttrTypeCovT]]:
        if isinstance(value, IntConstraint):
            value = IntAttrConstraint.get(value)
        return cast(
            AttrConstraint[IntegerAttr[_IntegerAttrTypeCovT]],
            ParamAttrConstraint.get(IntegerAttr, value, type),
        )

    def __bool__(self) -> bool:
        """Returns True if value is non-zero."""
        return bool(self.value)

    @staticmethod
    def iter_unpack(
        type: _IntegerAttrTypeInvT, buffer: ReadableBuffer, /
    ) -> Iterator[IntegerAttr[_IntegerAttrTypeInvT]]:
        """
        Yields unpacked values one at a time, starting at the beginning of the buffer.
        """
        for value in type.iter_unpack(buffer):
            yield IntegerAttr(value, type)

    @staticmethod
    def unpack(
        type: _IntegerAttrTypeInvT, buffer: ReadableBuffer, num: int, /
    ) -> tuple[IntegerAttr[_IntegerAttrTypeInvT], ...]:
        """
        Unpack `num` values from the beginning of the buffer.
        """
        return tuple(IntegerAttr(value, type) for value in type.unpack(buffer, num))

name = 'integer' class-attribute instance-attribute

value: IntAttr instance-attribute

type: _IntegerAttrTypeCovT instance-attribute

__init__(value: int | IntAttr, value_type: _IntCovT | IntegerType[_IntCovT] | IndexType, *, truncate_bits: bool = False) -> None

__init__(
    value: int | IntAttr,
    value_type: _IntegerAttrTypeCovT,
    *,
    truncate_bits: bool = False,
) -> None
__init__(
    value: int | IntAttr,
    value_type: _IntCovT,
    *,
    truncate_bits: bool = False,
) -> None
Source code in xdsl/dialects/builtin.py
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
def __init__(
    self,
    value: int | IntAttr,
    value_type: _IntCovT | IntegerType[_IntCovT] | IndexType,
    *,
    truncate_bits: bool = False,
) -> None:
    if isinstance(value_type, int):
        value_type = IntegerType(value_type)
    if not isinstance(value, int):
        value = value.data
    if not isinstance(value_type, IndexType):
        normalized_value = value_type.normalized_value(
            value, truncate_bits=truncate_bits
        )
        if normalized_value is not None:
            value = normalized_value
    super().__init__(IntAttr(value), value_type)

from_index_int_value(value: int) -> IntegerAttr[IndexType] staticmethod

Source code in xdsl/dialects/builtin.py
1100
1101
1102
@staticmethod
def from_index_int_value(value: int) -> IntegerAttr[IndexType]:
    return IntegerAttr(value, IndexType())

from_bool(value: bool) -> BoolAttr staticmethod

Source code in xdsl/dialects/builtin.py
1104
1105
1106
@staticmethod
def from_bool(value: bool) -> BoolAttr:
    return IntegerAttr(value, 1)

print_builtin(printer: Printer) -> None

Source code in xdsl/dialects/builtin.py
1108
1109
1110
1111
1112
1113
def print_builtin(self, printer: Printer) -> None:
    ty = self.type
    printer.print_int(self.value.data, ty)
    if ty != i1:
        printer.print_string(" : ")
        printer.print_attribute(ty)

verify() -> None

Source code in xdsl/dialects/builtin.py
1115
1116
1117
1118
1119
def verify(self) -> None:
    if isinstance(int_type := self.type, IndexType):
        return

    int_type.verify_value(self.value.data)

parse_with_type(parser: AttrParser, type: Attribute) -> TypedAttribute staticmethod

Source code in xdsl/dialects/builtin.py
1121
1122
1123
1124
1125
1126
1127
@staticmethod
def parse_with_type(
    parser: AttrParser,
    type: Attribute,
) -> TypedAttribute:
    assert isa(type, IntegerType | IndexType)
    return IntegerAttr(parser.parse_integer(allow_boolean=(type == i1)), type)

print_without_type(printer: Printer)

Source code in xdsl/dialects/builtin.py
1129
1130
def print_without_type(self, printer: Printer):
    printer.print_int(self.value.data, self.type)

get_type() -> Attribute

Source code in xdsl/dialects/builtin.py
1132
1133
def get_type(self) -> Attribute:
    return self.type

constr(type: IRDLAttrConstraint[_IntegerAttrTypeCovT] = IntegerAttrTypeConstr, *, value: AttrConstraint | IntConstraint | None = None) -> AttrConstraint[IntegerAttr[_IntegerAttrTypeCovT]] staticmethod

Source code in xdsl/dialects/builtin.py
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
@staticmethod
def constr(
    type: IRDLAttrConstraint[_IntegerAttrTypeCovT] = IntegerAttrTypeConstr,
    *,
    value: AttrConstraint | IntConstraint | None = None,
) -> AttrConstraint[IntegerAttr[_IntegerAttrTypeCovT]]:
    if isinstance(value, IntConstraint):
        value = IntAttrConstraint.get(value)
    return cast(
        AttrConstraint[IntegerAttr[_IntegerAttrTypeCovT]],
        ParamAttrConstraint.get(IntegerAttr, value, type),
    )

__bool__() -> bool

Returns True if value is non-zero.

Source code in xdsl/dialects/builtin.py
1148
1149
1150
def __bool__(self) -> bool:
    """Returns True if value is non-zero."""
    return bool(self.value)

iter_unpack(type: _IntegerAttrTypeInvT, buffer: ReadableBuffer) -> Iterator[IntegerAttr[_IntegerAttrTypeInvT]] staticmethod

Yields unpacked values one at a time, starting at the beginning of the buffer.

Source code in xdsl/dialects/builtin.py
1152
1153
1154
1155
1156
1157
1158
1159
1160
@staticmethod
def iter_unpack(
    type: _IntegerAttrTypeInvT, buffer: ReadableBuffer, /
) -> Iterator[IntegerAttr[_IntegerAttrTypeInvT]]:
    """
    Yields unpacked values one at a time, starting at the beginning of the buffer.
    """
    for value in type.iter_unpack(buffer):
        yield IntegerAttr(value, type)

unpack(type: _IntegerAttrTypeInvT, buffer: ReadableBuffer, num: int) -> tuple[IntegerAttr[_IntegerAttrTypeInvT], ...] staticmethod

Unpack num values from the beginning of the buffer.

Source code in xdsl/dialects/builtin.py
1162
1163
1164
1165
1166
1167
1168
1169
@staticmethod
def unpack(
    type: _IntegerAttrTypeInvT, buffer: ReadableBuffer, num: int, /
) -> tuple[IntegerAttr[_IntegerAttrTypeInvT], ...]:
    """
    Unpack `num` values from the beginning of the buffer.
    """
    return tuple(IntegerAttr(value, type) for value in type.unpack(buffer, num))

FloatNonfiniteBehavior

Bases: Enum

How a reduced-precision float format represents infinities and NaNs.

Mirrors LLVM APFloat's fltNonfiniteBehavior.

Source code in xdsl/dialects/builtin.py
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
class FloatNonfiniteBehavior(Enum):
    """
    How a reduced-precision float format represents infinities and NaNs.

    Mirrors LLVM APFloat's `fltNonfiniteBehavior`.
    """

    IEEE = auto()
    """The all-ones exponent encodes infinities (zero mantissa) and NaNs."""
    NAN_ONLY = auto()
    """No infinities; a NaN is present (see `FloatNanEncoding`)."""
    FINITE_ONLY = auto()
    """No infinities or NaNs; overflow saturates to the largest finite value."""

IEEE = auto() class-attribute instance-attribute

The all-ones exponent encodes infinities (zero mantissa) and NaNs.

NAN_ONLY = auto() class-attribute instance-attribute

No infinities; a NaN is present (see FloatNanEncoding).

FINITE_ONLY = auto() class-attribute instance-attribute

No infinities or NaNs; overflow saturates to the largest finite value.

FloatNanEncoding

Bases: Enum

Which bit pattern encodes NaN. Mirrors LLVM APFloat's fltNanEncoding.

Source code in xdsl/dialects/builtin.py
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
class FloatNanEncoding(Enum):
    """
    Which bit pattern encodes NaN. Mirrors LLVM APFloat's `fltNanEncoding`.
    """

    IEEE = auto()
    """All-ones exponent with a non-zero mantissa."""
    ALL_ONES = auto()
    """All-ones exponent and mantissa."""
    NEGATIVE_ZERO = auto()
    """The sign-bit-only pattern; the format has no negative zero."""

IEEE = auto() class-attribute instance-attribute

All-ones exponent with a non-zero mantissa.

ALL_ONES = auto() class-attribute instance-attribute

All-ones exponent and mantissa.

NEGATIVE_ZERO = auto() class-attribute instance-attribute

The sign-bit-only pattern; the format has no negative zero.

FloatSemantics dataclass

The parameters that fully define a reduced-precision float format.

Modelled on LLVM's fltSemantics.

Source code in xdsl/dialects/builtin.py
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
@dataclass(frozen=True)
class FloatSemantics:
    """
    The parameters that fully define a reduced-precision float format.

    Modelled on LLVM's `fltSemantics`.
    """

    exponent_bits: int
    mantissa_bits: int
    exponent_bias: int
    nonfinite: FloatNonfiniteBehavior = FloatNonfiniteBehavior.IEEE
    nan_encoding: FloatNanEncoding = FloatNanEncoding.IEEE
    has_zero: bool = True
    has_sign: bool = True

    @property
    def bitwidth(self) -> int:
        return int(self.has_sign) + self.exponent_bits + self.mantissa_bits

    @property
    def max_exponent(self) -> int:
        """The all-ones exponent field."""
        return (1 << self.exponent_bits) - 1

    @property
    def max_mantissa(self) -> int:
        """The all-ones mantissa field."""
        return (1 << self.mantissa_bits) - 1

    @property
    def sign_shift(self) -> int:
        """Bit position of the sign bit."""
        return self.exponent_bits + self.mantissa_bits

    @staticmethod
    def round_half_even(significand: int, shift: int) -> int:
        """Round `significand >> shift` to nearest, ties to even, with exact integer math."""
        if shift <= 0:
            return significand << (-shift)
        quotient = significand >> shift
        dropped = significand & ((1 << shift) - 1)
        halfway = 1 << (shift - 1)
        if dropped > halfway or (dropped == halfway and quotient & 1):
            quotient += 1
        return quotient

exponent_bits: int instance-attribute

mantissa_bits: int instance-attribute

exponent_bias: int instance-attribute

nonfinite: FloatNonfiniteBehavior = FloatNonfiniteBehavior.IEEE class-attribute instance-attribute

nan_encoding: FloatNanEncoding = FloatNanEncoding.IEEE class-attribute instance-attribute

has_zero: bool = True class-attribute instance-attribute

has_sign: bool = True class-attribute instance-attribute

bitwidth: int property

max_exponent: int property

The all-ones exponent field.

max_mantissa: int property

The all-ones mantissa field.

sign_shift: int property

Bit position of the sign bit.

__init__(exponent_bits: int, mantissa_bits: int, exponent_bias: int, nonfinite: FloatNonfiniteBehavior = FloatNonfiniteBehavior.IEEE, nan_encoding: FloatNanEncoding = FloatNanEncoding.IEEE, has_zero: bool = True, has_sign: bool = True) -> None

round_half_even(significand: int, shift: int) -> int staticmethod

Round significand >> shift to nearest, ties to even, with exact integer math.

Source code in xdsl/dialects/builtin.py
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
@staticmethod
def round_half_even(significand: int, shift: int) -> int:
    """Round `significand >> shift` to nearest, ties to even, with exact integer math."""
    if shift <= 0:
        return significand << (-shift)
    quotient = significand >> shift
    dropped = significand & ((1 << shift) - 1)
    halfway = 1 << (shift - 1)
    if dropped > halfway or (dropped == halfway and quotient & 1):
        quotient += 1
    return quotient

ReducedPrecisionFloatType dataclass

Bases: _FloatType, PackableType[float], ABC

Base for reduced-precision float types, described by a FloatSemantics.

Concrete subclasses set only SEMANTICS; all encoding, decoding, rounding and special-value handling is shared here and parameterised by that FloatSemantics.

Source code in xdsl/dialects/builtin.py
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
class ReducedPrecisionFloatType(_FloatType, PackableType[float], ABC):
    """
    Base for reduced-precision float types, described by a `FloatSemantics`.

    Concrete subclasses set only `SEMANTICS`; all encoding, decoding, rounding and
    special-value handling is shared here and parameterised by that `FloatSemantics`.
    """

    SEMANTICS: ClassVar[FloatSemantics]

    @property
    def bitwidth(self) -> int:
        return self.SEMANTICS.bitwidth

    @property
    def compile_time_size(self) -> int:
        return self.size

    @staticmethod
    def decode_significand_power(magnitude: float) -> tuple[int, int]:
        """Return `(significand, power)` with `magnitude == significand * 2**power`, exact for positive finite floats."""
        bits = struct.unpack("<Q", struct.pack("<d", magnitude))[0]
        biased_exponent = (bits >> 52) & 0x7FF
        fraction = bits & ((1 << 52) - 1)
        if biased_exponent:
            return fraction | (1 << 52), biased_exponent - 1075
        return fraction, -1074

    def _decode_special(
        self, negative: bool, biased_exponent: int, mantissa: int
    ) -> float | None:
        """Value of a reserved infinity/NaN pattern, or None if the pattern is finite."""
        semantics = self.SEMANTICS
        match semantics:
            case FloatSemantics(nonfinite=FloatNonfiniteBehavior.FINITE_ONLY):
                return None
            case FloatSemantics(nonfinite=FloatNonfiniteBehavior.IEEE) if (
                biased_exponent != semantics.max_exponent
            ):
                return None
            case FloatSemantics(nonfinite=FloatNonfiniteBehavior.IEEE) if mantissa:
                return math.nan
            case FloatSemantics(nonfinite=FloatNonfiniteBehavior.IEEE) if negative:
                return -math.inf
            case FloatSemantics(nonfinite=FloatNonfiniteBehavior.IEEE):
                return math.inf
            case FloatSemantics(nan_encoding=FloatNanEncoding.ALL_ONES) if (
                biased_exponent == semantics.max_exponent
                and mantissa == semantics.max_mantissa
            ):
                return math.nan
            case FloatSemantics(nan_encoding=FloatNanEncoding.ALL_ONES):
                return None
            case _ if negative and biased_exponent == 0 and mantissa == 0:
                return math.nan
            case _:
                return None

    def decode_bits(self, bits: int) -> float:
        semantics = self.SEMANTICS
        mantissa_bits = semantics.mantissa_bits
        bias = semantics.exponent_bias
        negative = bool(semantics.has_sign and (bits >> semantics.sign_shift) & 1)
        biased_exponent = (bits >> mantissa_bits) & semantics.max_exponent
        mantissa = bits & semantics.max_mantissa
        special = self._decode_special(negative, biased_exponent, mantissa)
        if special is not None:
            return special
        sign = -1.0 if negative else 1.0
        if semantics.has_zero and biased_exponent == 0:
            return sign * mantissa * 2.0 ** (1 - bias - mantissa_bits)
        return (
            sign * (1 + mantissa / 2.0**mantissa_bits) * 2.0 ** (biased_exponent - bias)
        )

    def _encode_overflow(self, sign: int) -> int:
        """Bits a too-large magnitude maps to: infinity, NaN, or the largest finite value."""
        semantics = self.SEMANTICS
        match semantics.nonfinite:
            case FloatNonfiniteBehavior.IEEE:
                return (sign << semantics.sign_shift) | (
                    semantics.max_exponent << semantics.mantissa_bits
                )
            case FloatNonfiniteBehavior.NAN_ONLY:
                return self._encode_nan(sign)
            case FloatNonfiniteBehavior.FINITE_ONLY:
                return (
                    (sign << semantics.sign_shift)
                    | (semantics.max_exponent << semantics.mantissa_bits)
                    | semantics.max_mantissa
                )

    def _encode_nan(self, sign: int) -> int:
        semantics = self.SEMANTICS
        mantissa_bits = semantics.mantissa_bits
        if semantics.nonfinite is FloatNonfiniteBehavior.FINITE_ONLY:
            return self._encode_overflow(sign)
        match semantics.nan_encoding:
            case FloatNanEncoding.IEEE:
                return (semantics.max_exponent << mantissa_bits) | (
                    1 << (mantissa_bits - 1)
                )
            case FloatNanEncoding.ALL_ONES:
                return (
                    (sign << semantics.sign_shift)
                    | (semantics.max_exponent << mantissa_bits)
                    | semantics.max_mantissa
                )
            case FloatNanEncoding.NEGATIVE_ZERO:
                return 1 << semantics.sign_shift

    def _encode_zero(self, sign: int) -> int:
        if self.SEMANTICS.nan_encoding is FloatNanEncoding.NEGATIVE_ZERO:
            return 0  # no negative zero
        return sign << self.SEMANTICS.sign_shift

    def _overflows(self, biased_exponent: int, mantissa: int) -> bool:
        semantics = self.SEMANTICS
        if semantics.nonfinite is FloatNonfiniteBehavior.IEEE:
            return biased_exponent >= semantics.max_exponent
        if semantics.nan_encoding is FloatNanEncoding.ALL_ONES:
            return biased_exponent > semantics.max_exponent or (
                biased_exponent == semantics.max_exponent
                and mantissa == semantics.max_mantissa
            )
        return biased_exponent > semantics.max_exponent

    def _rounded_exponent_mantissa(self, magnitude: float) -> tuple[int, int] | None:
        """
        Round a positive, finite magnitude to `(biased_exponent, mantissa)`.

        Returns `(0, 0)` on underflow to the smallest value and `None` on overflow.
        """
        semantics = self.SEMANTICS
        mantissa_bits = semantics.mantissa_bits
        bias = semantics.exponent_bias
        implicit_bit = 1 << mantissa_bits
        significand, power = self.decode_significand_power(magnitude)
        exponent = math.frexp(magnitude)[1] - 1
        smallest_normal_exponent = 1 - bias if semantics.has_zero else -bias
        if exponent < smallest_normal_exponent:
            if not semantics.has_zero:
                return 0, 0  # no subnormals: underflow to the smallest value
            quotient = semantics.round_half_even(
                significand, (1 - bias - mantissa_bits) - power
            )
            if quotient < implicit_bit:
                return 0, quotient
            return 1, 0  # rounded up into the smallest normal
        quotient = semantics.round_half_even(
            significand, (exponent - mantissa_bits) - power
        )
        if quotient == implicit_bit << 1:
            exponent += 1
            quotient = implicit_bit
        biased_exponent = exponent + bias
        mantissa = quotient - implicit_bit
        if self._overflows(biased_exponent, mantissa):
            return None
        return biased_exponent, mantissa

    def encode_bits(self, value: float) -> int:
        semantics = self.SEMANTICS
        sign = 1 if semantics.has_sign and math.copysign(1.0, value) < 0 else 0
        if math.isinf(value):
            return self._encode_overflow(sign)
        if math.isnan(value):
            return self._encode_nan(sign)
        if value == 0.0:
            return self._encode_zero(sign)
        if not semantics.has_sign and value < 0:
            # Unsigned formats (e.g. f8E8M0FNU) reject signed finite values, as LLVM does,
            # rather than silently dropping the sign. -0.0 is handled by the zero case above.
            raise ValueError(f"{self.name} does not support signed values")
        fields = self._rounded_exponent_mantissa(abs(value))
        if fields is None:
            return self._encode_overflow(sign)
        biased_exponent, mantissa = fields
        if semantics.has_zero and not biased_exponent and not mantissa:
            return self._encode_zero(sign)
        return (
            (sign << semantics.sign_shift)
            | (biased_exponent << semantics.mantissa_bits)
            | mantissa
        )

    def iter_unpack(self, buffer: ReadableBuffer, /) -> Iterator[float]:
        # `int` handles the odd byte widths `struct` can't (tf32's 19 bits -> 3 bytes).
        size = self.size
        mv = memoryview(buffer)
        buffer_size = len(mv)
        if buffer_size % size:
            raise ValueError(
                f"Buffer length {buffer_size} not multiple of {self.name} element "
                f"size {size}."
            )
        return (
            self.decode_bits(int.from_bytes(mv[i : i + size], "little"))
            for i in range(0, buffer_size, size)
        )

    def unpack(self, buffer: ReadableBuffer, num: int, /) -> tuple[float, ...]:
        size = self.size
        mv = memoryview(buffer)
        buffer_size = len(mv)
        if buffer_size != num * size:
            raise ValueError(
                f"Buffer length {buffer_size} not product of {self.name} element "
                f"size {size} and num {num}."
            )
        return tuple(
            self.decode_bits(int.from_bytes(mv[i : i + size], "little"))
            for i in range(0, buffer_size, size)
        )

    def pack_into(self, buffer: WriteableBuffer, offset: int, value: float) -> None:
        size = self.size
        buffer_size = len(memoryview(buffer))
        if buffer_size < offset + size:
            raise ValueError(
                f"Buffer length {buffer_size} too small for packing "
                f"{size} bytes at offset {offset}, expected at least "
                f"{offset + size}."
            )
        memoryview(buffer)[offset : offset + size] = self.encode_bits(value).to_bytes(
            size, "little"
        )

    def pack(self, values: Sequence[float]) -> bytes:
        size = self.size
        buffer = bytearray(size * len(values))
        for index, value in enumerate(values):
            self.pack_into(buffer, index * size, value)
        return bytes(buffer)

SEMANTICS: FloatSemantics class-attribute

bitwidth: int property

compile_time_size: int property

decode_significand_power(magnitude: float) -> tuple[int, int] staticmethod

Return (significand, power) with magnitude == significand * 2**power, exact for positive finite floats.

Source code in xdsl/dialects/builtin.py
1280
1281
1282
1283
1284
1285
1286
1287
1288
@staticmethod
def decode_significand_power(magnitude: float) -> tuple[int, int]:
    """Return `(significand, power)` with `magnitude == significand * 2**power`, exact for positive finite floats."""
    bits = struct.unpack("<Q", struct.pack("<d", magnitude))[0]
    biased_exponent = (bits >> 52) & 0x7FF
    fraction = bits & ((1 << 52) - 1)
    if biased_exponent:
        return fraction | (1 << 52), biased_exponent - 1075
    return fraction, -1074

decode_bits(bits: int) -> float

Source code in xdsl/dialects/builtin.py
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
def decode_bits(self, bits: int) -> float:
    semantics = self.SEMANTICS
    mantissa_bits = semantics.mantissa_bits
    bias = semantics.exponent_bias
    negative = bool(semantics.has_sign and (bits >> semantics.sign_shift) & 1)
    biased_exponent = (bits >> mantissa_bits) & semantics.max_exponent
    mantissa = bits & semantics.max_mantissa
    special = self._decode_special(negative, biased_exponent, mantissa)
    if special is not None:
        return special
    sign = -1.0 if negative else 1.0
    if semantics.has_zero and biased_exponent == 0:
        return sign * mantissa * 2.0 ** (1 - bias - mantissa_bits)
    return (
        sign * (1 + mantissa / 2.0**mantissa_bits) * 2.0 ** (biased_exponent - bias)
    )

encode_bits(value: float) -> int

Source code in xdsl/dialects/builtin.py
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
def encode_bits(self, value: float) -> int:
    semantics = self.SEMANTICS
    sign = 1 if semantics.has_sign and math.copysign(1.0, value) < 0 else 0
    if math.isinf(value):
        return self._encode_overflow(sign)
    if math.isnan(value):
        return self._encode_nan(sign)
    if value == 0.0:
        return self._encode_zero(sign)
    if not semantics.has_sign and value < 0:
        # Unsigned formats (e.g. f8E8M0FNU) reject signed finite values, as LLVM does,
        # rather than silently dropping the sign. -0.0 is handled by the zero case above.
        raise ValueError(f"{self.name} does not support signed values")
    fields = self._rounded_exponent_mantissa(abs(value))
    if fields is None:
        return self._encode_overflow(sign)
    biased_exponent, mantissa = fields
    if semantics.has_zero and not biased_exponent and not mantissa:
        return self._encode_zero(sign)
    return (
        (sign << semantics.sign_shift)
        | (biased_exponent << semantics.mantissa_bits)
        | mantissa
    )

iter_unpack(buffer: ReadableBuffer) -> Iterator[float]

Source code in xdsl/dialects/builtin.py
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
def iter_unpack(self, buffer: ReadableBuffer, /) -> Iterator[float]:
    # `int` handles the odd byte widths `struct` can't (tf32's 19 bits -> 3 bytes).
    size = self.size
    mv = memoryview(buffer)
    buffer_size = len(mv)
    if buffer_size % size:
        raise ValueError(
            f"Buffer length {buffer_size} not multiple of {self.name} element "
            f"size {size}."
        )
    return (
        self.decode_bits(int.from_bytes(mv[i : i + size], "little"))
        for i in range(0, buffer_size, size)
    )

unpack(buffer: ReadableBuffer, num: int) -> tuple[float, ...]

Source code in xdsl/dialects/builtin.py
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
def unpack(self, buffer: ReadableBuffer, num: int, /) -> tuple[float, ...]:
    size = self.size
    mv = memoryview(buffer)
    buffer_size = len(mv)
    if buffer_size != num * size:
        raise ValueError(
            f"Buffer length {buffer_size} not product of {self.name} element "
            f"size {size} and num {num}."
        )
    return tuple(
        self.decode_bits(int.from_bytes(mv[i : i + size], "little"))
        for i in range(0, buffer_size, size)
    )

pack_into(buffer: WriteableBuffer, offset: int, value: float) -> None

Source code in xdsl/dialects/builtin.py
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
def pack_into(self, buffer: WriteableBuffer, offset: int, value: float) -> None:
    size = self.size
    buffer_size = len(memoryview(buffer))
    if buffer_size < offset + size:
        raise ValueError(
            f"Buffer length {buffer_size} too small for packing "
            f"{size} bytes at offset {offset}, expected at least "
            f"{offset + size}."
        )
    memoryview(buffer)[offset : offset + size] = self.encode_bits(value).to_bytes(
        size, "little"
    )

pack(values: Sequence[float]) -> bytes

Source code in xdsl/dialects/builtin.py
1490
1491
1492
1493
1494
1495
def pack(self, values: Sequence[float]) -> bytes:
    size = self.size
    buffer = bytearray(size * len(values))
    for index, value in enumerate(values):
        self.pack_into(buffer, index * size, value)
    return bytes(buffer)

BFloat16Type dataclass

Bases: ParametrizedAttribute, _FloatType

Source code in xdsl/dialects/builtin.py
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
@irdl_attr_definition
class BFloat16Type(ParametrizedAttribute, _FloatType):
    name = "bf16"

    @property
    def bitwidth(self) -> int:
        return 16

    @property
    def compile_time_size(self) -> int:
        return 2

    @staticmethod
    def _encode(value: float) -> bytes:
        """
        Encode a Python float (IEEE 754 binary32 after Python's f64 -> f32
        narrowing) as bf16 bytes, little-endian. Round-to-nearest-even,
        quiet-NaN preservation; matches LLVM APFloat semantics.
        """
        f32_bits = struct.unpack("<I", struct.pack("<f", value))[0]
        # NaN must remain a NaN after truncation; force the quiet bit on so a
        # signaling NaN with mantissa entirely in the truncated bits doesn't
        # become inf.
        if (f32_bits & 0x7FFFFFFF) > 0x7F800000:
            bits = ((f32_bits >> 16) | 0x0040) & 0xFFFF
        else:
            rounding_bias = 0x7FFF + ((f32_bits >> 16) & 1)
            bits = ((f32_bits + rounding_bias) >> 16) & 0xFFFF
        return bits.to_bytes(2, "little")

    @staticmethod
    def _decode(raw: ReadableBuffer) -> float:
        # bf16 is the high 16 bits of an f32 with the low 16 truncated; the
        # inverse is to zero-extend with two low bytes in little-endian.
        return struct.unpack("<f", b"\x00\x00" + raw)[0]

    def iter_unpack(self, buffer: ReadableBuffer, /) -> Iterator[float]:
        mv = memoryview(buffer)
        buffer_size = len(mv)
        if buffer_size % 2:
            raise ValueError(
                f"Buffer length {buffer_size} not multiple of {self.name} element "
                f"size 2."
            )
        return (self._decode(mv[i : i + 2]) for i in range(0, len(mv), 2))

    def unpack(self, buffer: ReadableBuffer, num: int, /) -> tuple[float, ...]:
        mv = memoryview(buffer)
        buffer_size = len(mv)
        compile_time_size = self.compile_time_size
        if buffer_size != num * compile_time_size:
            raise ValueError(
                f"Buffer length {buffer_size} not product of {self.name} element "
                f"size {compile_time_size} and num {num}."
            )

        return tuple(self._decode(mv[i : i + 2]) for i in range(0, buffer_size, 2))

    def pack_into(self, buffer: WriteableBuffer, offset: int, value: float) -> None:
        buffer_size = len(memoryview(buffer))
        compile_time_size = self.compile_time_size
        if buffer_size < offset + compile_time_size:
            raise ValueError(
                f"Buffer length {buffer_size} too small for packing "
                f"{compile_time_size} bytes at offset {offset}, expected at least "
                f"{offset + compile_time_size}."
            )

        memoryview(buffer)[offset : offset + 2] = self._encode(value)

    def pack(self, values: Sequence[float]) -> bytes:
        return b"".join(self._encode(v) for v in values)

name = 'bf16' class-attribute instance-attribute

bitwidth: int property

compile_time_size: int property

iter_unpack(buffer: ReadableBuffer) -> Iterator[float]

Source code in xdsl/dialects/builtin.py
1534
1535
1536
1537
1538
1539
1540
1541
1542
def iter_unpack(self, buffer: ReadableBuffer, /) -> Iterator[float]:
    mv = memoryview(buffer)
    buffer_size = len(mv)
    if buffer_size % 2:
        raise ValueError(
            f"Buffer length {buffer_size} not multiple of {self.name} element "
            f"size 2."
        )
    return (self._decode(mv[i : i + 2]) for i in range(0, len(mv), 2))

unpack(buffer: ReadableBuffer, num: int) -> tuple[float, ...]

Source code in xdsl/dialects/builtin.py
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
def unpack(self, buffer: ReadableBuffer, num: int, /) -> tuple[float, ...]:
    mv = memoryview(buffer)
    buffer_size = len(mv)
    compile_time_size = self.compile_time_size
    if buffer_size != num * compile_time_size:
        raise ValueError(
            f"Buffer length {buffer_size} not product of {self.name} element "
            f"size {compile_time_size} and num {num}."
        )

    return tuple(self._decode(mv[i : i + 2]) for i in range(0, buffer_size, 2))

pack_into(buffer: WriteableBuffer, offset: int, value: float) -> None

Source code in xdsl/dialects/builtin.py
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
def pack_into(self, buffer: WriteableBuffer, offset: int, value: float) -> None:
    buffer_size = len(memoryview(buffer))
    compile_time_size = self.compile_time_size
    if buffer_size < offset + compile_time_size:
        raise ValueError(
            f"Buffer length {buffer_size} too small for packing "
            f"{compile_time_size} bytes at offset {offset}, expected at least "
            f"{offset + compile_time_size}."
        )

    memoryview(buffer)[offset : offset + 2] = self._encode(value)

pack(values: Sequence[float]) -> bytes

Source code in xdsl/dialects/builtin.py
1568
1569
def pack(self, values: Sequence[float]) -> bytes:
    return b"".join(self._encode(v) for v in values)

Float16Type dataclass

Bases: ParametrizedAttribute, _FloatType, StructPackableType[float]

Source code in xdsl/dialects/builtin.py
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
@irdl_attr_definition
class Float16Type(ParametrizedAttribute, _FloatType, StructPackableType[float]):
    name = "f16"

    @property
    def bitwidth(self) -> int:
        return 16

    @property
    def format(self) -> str:
        return "<e"

name = 'f16' class-attribute instance-attribute

bitwidth: int property

format: str property

Float32Type dataclass

Bases: ParametrizedAttribute, _FloatType, StructPackableType[float]

Source code in xdsl/dialects/builtin.py
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
@irdl_attr_definition
class Float32Type(ParametrizedAttribute, _FloatType, StructPackableType[float]):
    name = "f32"

    @property
    def bitwidth(self) -> int:
        return 32

    @property
    def format(self) -> str:
        return "<f"

name = 'f32' class-attribute instance-attribute

bitwidth: int property

format: str property

Float64Type dataclass

Bases: ParametrizedAttribute, _FloatType, StructPackableType[float]

Source code in xdsl/dialects/builtin.py
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
@irdl_attr_definition
class Float64Type(ParametrizedAttribute, _FloatType, StructPackableType[float]):
    name = "f64"

    @property
    def bitwidth(self) -> int:
        return 64

    @property
    def format(self) -> str:
        return "<d"

name = 'f64' class-attribute instance-attribute

bitwidth: int property

format: str property

Float80Type dataclass

Bases: ParametrizedAttribute, _FloatType, StructPackableType[float]

Source code in xdsl/dialects/builtin.py
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
@irdl_attr_definition
class Float80Type(ParametrizedAttribute, _FloatType, StructPackableType[float]):
    name = "f80"

    @property
    def bitwidth(self) -> int:
        return 80

    @property
    def format(self) -> str:
        raise NotImplementedError()

name = 'f80' class-attribute instance-attribute

bitwidth: int property

format: str property

Float128Type dataclass

Bases: ParametrizedAttribute, _FloatType, StructPackableType[float]

Source code in xdsl/dialects/builtin.py
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
@irdl_attr_definition
class Float128Type(ParametrizedAttribute, _FloatType, StructPackableType[float]):
    name = "f128"

    @property
    def bitwidth(self) -> int:
        return 128

    @property
    def format(self) -> str:
        raise NotImplementedError()

name = 'f128' class-attribute instance-attribute

bitwidth: int property

format: str property

FloatTF32Type dataclass

Bases: ParametrizedAttribute, ReducedPrecisionFloatType

Source code in xdsl/dialects/builtin.py
1637
1638
1639
1640
1641
1642
1643
1644
@irdl_attr_definition
class FloatTF32Type(ParametrizedAttribute, ReducedPrecisionFloatType):
    name = "tf32"
    SEMANTICS = FloatSemantics(
        exponent_bits=8,
        mantissa_bits=10,
        exponent_bias=127,
    )

name = 'tf32' class-attribute instance-attribute

SEMANTICS = FloatSemantics(exponent_bits=8, mantissa_bits=10, exponent_bias=127) class-attribute instance-attribute

Float8E5M2Type dataclass

Bases: ParametrizedAttribute, ReducedPrecisionFloatType

Source code in xdsl/dialects/builtin.py
1647
1648
1649
1650
1651
1652
1653
1654
@irdl_attr_definition
class Float8E5M2Type(ParametrizedAttribute, ReducedPrecisionFloatType):
    name = "f8E5M2"
    SEMANTICS = FloatSemantics(
        exponent_bits=5,
        mantissa_bits=2,
        exponent_bias=15,
    )

name = 'f8E5M2' class-attribute instance-attribute

SEMANTICS = FloatSemantics(exponent_bits=5, mantissa_bits=2, exponent_bias=15) class-attribute instance-attribute

Float8E4M3Type dataclass

Bases: ParametrizedAttribute, ReducedPrecisionFloatType

Source code in xdsl/dialects/builtin.py
1657
1658
1659
1660
1661
1662
1663
1664
@irdl_attr_definition
class Float8E4M3Type(ParametrizedAttribute, ReducedPrecisionFloatType):
    name = "f8E4M3"
    SEMANTICS = FloatSemantics(
        exponent_bits=4,
        mantissa_bits=3,
        exponent_bias=7,
    )

name = 'f8E4M3' class-attribute instance-attribute

SEMANTICS = FloatSemantics(exponent_bits=4, mantissa_bits=3, exponent_bias=7) class-attribute instance-attribute

Float8E4M3FNType dataclass

Bases: ParametrizedAttribute, ReducedPrecisionFloatType

Source code in xdsl/dialects/builtin.py
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
@irdl_attr_definition
class Float8E4M3FNType(ParametrizedAttribute, ReducedPrecisionFloatType):
    name = "f8E4M3FN"
    SEMANTICS = FloatSemantics(
        exponent_bits=4,
        mantissa_bits=3,
        exponent_bias=7,
        nonfinite=FloatNonfiniteBehavior.NAN_ONLY,
        nan_encoding=FloatNanEncoding.ALL_ONES,
    )

name = 'f8E4M3FN' class-attribute instance-attribute

SEMANTICS = FloatSemantics(exponent_bits=4, mantissa_bits=3, exponent_bias=7, nonfinite=(FloatNonfiniteBehavior.NAN_ONLY), nan_encoding=(FloatNanEncoding.ALL_ONES)) class-attribute instance-attribute

Float8E5M2FNUZType dataclass

Bases: ParametrizedAttribute, ReducedPrecisionFloatType

Source code in xdsl/dialects/builtin.py
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
@irdl_attr_definition
class Float8E5M2FNUZType(ParametrizedAttribute, ReducedPrecisionFloatType):
    name = "f8E5M2FNUZ"
    SEMANTICS = FloatSemantics(
        exponent_bits=5,
        mantissa_bits=2,
        exponent_bias=16,
        nonfinite=FloatNonfiniteBehavior.NAN_ONLY,
        nan_encoding=FloatNanEncoding.NEGATIVE_ZERO,
    )

name = 'f8E5M2FNUZ' class-attribute instance-attribute

SEMANTICS = FloatSemantics(exponent_bits=5, mantissa_bits=2, exponent_bias=16, nonfinite=(FloatNonfiniteBehavior.NAN_ONLY), nan_encoding=(FloatNanEncoding.NEGATIVE_ZERO)) class-attribute instance-attribute

Float8E4M3FNUZType dataclass

Bases: ParametrizedAttribute, ReducedPrecisionFloatType

Source code in xdsl/dialects/builtin.py
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
@irdl_attr_definition
class Float8E4M3FNUZType(ParametrizedAttribute, ReducedPrecisionFloatType):
    name = "f8E4M3FNUZ"
    SEMANTICS = FloatSemantics(
        exponent_bits=4,
        mantissa_bits=3,
        exponent_bias=8,
        nonfinite=FloatNonfiniteBehavior.NAN_ONLY,
        nan_encoding=FloatNanEncoding.NEGATIVE_ZERO,
    )

name = 'f8E4M3FNUZ' class-attribute instance-attribute

SEMANTICS = FloatSemantics(exponent_bits=4, mantissa_bits=3, exponent_bias=8, nonfinite=(FloatNonfiniteBehavior.NAN_ONLY), nan_encoding=(FloatNanEncoding.NEGATIVE_ZERO)) class-attribute instance-attribute

Float8E4M3B11FNUZType dataclass

Bases: ParametrizedAttribute, ReducedPrecisionFloatType

Source code in xdsl/dialects/builtin.py
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
@irdl_attr_definition
class Float8E4M3B11FNUZType(ParametrizedAttribute, ReducedPrecisionFloatType):
    name = "f8E4M3B11FNUZ"
    SEMANTICS = FloatSemantics(
        exponent_bits=4,
        mantissa_bits=3,
        exponent_bias=11,
        nonfinite=FloatNonfiniteBehavior.NAN_ONLY,
        nan_encoding=FloatNanEncoding.NEGATIVE_ZERO,
    )

name = 'f8E4M3B11FNUZ' class-attribute instance-attribute

SEMANTICS = FloatSemantics(exponent_bits=4, mantissa_bits=3, exponent_bias=11, nonfinite=(FloatNonfiniteBehavior.NAN_ONLY), nan_encoding=(FloatNanEncoding.NEGATIVE_ZERO)) class-attribute instance-attribute

Float8E3M4Type dataclass

Bases: ParametrizedAttribute, ReducedPrecisionFloatType

Source code in xdsl/dialects/builtin.py
1715
1716
1717
1718
1719
1720
1721
1722
@irdl_attr_definition
class Float8E3M4Type(ParametrizedAttribute, ReducedPrecisionFloatType):
    name = "f8E3M4"
    SEMANTICS = FloatSemantics(
        exponent_bits=3,
        mantissa_bits=4,
        exponent_bias=3,
    )

name = 'f8E3M4' class-attribute instance-attribute

SEMANTICS = FloatSemantics(exponent_bits=3, mantissa_bits=4, exponent_bias=3) class-attribute instance-attribute

Float8E8M0FNUType dataclass

Bases: ParametrizedAttribute, ReducedPrecisionFloatType

Source code in xdsl/dialects/builtin.py
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
@irdl_attr_definition
class Float8E8M0FNUType(ParametrizedAttribute, ReducedPrecisionFloatType):
    name = "f8E8M0FNU"
    SEMANTICS = FloatSemantics(
        exponent_bits=8,
        mantissa_bits=0,
        exponent_bias=127,
        nonfinite=FloatNonfiniteBehavior.NAN_ONLY,
        nan_encoding=FloatNanEncoding.ALL_ONES,
        has_zero=False,
        has_sign=False,
    )

name = 'f8E8M0FNU' class-attribute instance-attribute

SEMANTICS = FloatSemantics(exponent_bits=8, mantissa_bits=0, exponent_bias=127, nonfinite=(FloatNonfiniteBehavior.NAN_ONLY), nan_encoding=(FloatNanEncoding.ALL_ONES), has_zero=False, has_sign=False) class-attribute instance-attribute

Float6E2M3FNType dataclass

Bases: ParametrizedAttribute, ReducedPrecisionFloatType

Source code in xdsl/dialects/builtin.py
1739
1740
1741
1742
1743
1744
1745
1746
1747
@irdl_attr_definition
class Float6E2M3FNType(ParametrizedAttribute, ReducedPrecisionFloatType):
    name = "f6E2M3FN"
    SEMANTICS = FloatSemantics(
        exponent_bits=2,
        mantissa_bits=3,
        exponent_bias=1,
        nonfinite=FloatNonfiniteBehavior.FINITE_ONLY,
    )

name = 'f6E2M3FN' class-attribute instance-attribute

SEMANTICS = FloatSemantics(exponent_bits=2, mantissa_bits=3, exponent_bias=1, nonfinite=(FloatNonfiniteBehavior.FINITE_ONLY)) class-attribute instance-attribute

Float6E3M2FNType dataclass

Bases: ParametrizedAttribute, ReducedPrecisionFloatType

Source code in xdsl/dialects/builtin.py
1750
1751
1752
1753
1754
1755
1756
1757
1758
@irdl_attr_definition
class Float6E3M2FNType(ParametrizedAttribute, ReducedPrecisionFloatType):
    name = "f6E3M2FN"
    SEMANTICS = FloatSemantics(
        exponent_bits=3,
        mantissa_bits=2,
        exponent_bias=3,
        nonfinite=FloatNonfiniteBehavior.FINITE_ONLY,
    )

name = 'f6E3M2FN' class-attribute instance-attribute

SEMANTICS = FloatSemantics(exponent_bits=3, mantissa_bits=2, exponent_bias=3, nonfinite=(FloatNonfiniteBehavior.FINITE_ONLY)) class-attribute instance-attribute

Float4E2M1FNType dataclass

Bases: ParametrizedAttribute, ReducedPrecisionFloatType

Source code in xdsl/dialects/builtin.py
1761
1762
1763
1764
1765
1766
1767
1768
1769
@irdl_attr_definition
class Float4E2M1FNType(ParametrizedAttribute, ReducedPrecisionFloatType):
    name = "f4E2M1FN"
    SEMANTICS = FloatSemantics(
        exponent_bits=2,
        mantissa_bits=1,
        exponent_bias=1,
        nonfinite=FloatNonfiniteBehavior.FINITE_ONLY,
    )

name = 'f4E2M1FN' class-attribute instance-attribute

SEMANTICS = FloatSemantics(exponent_bits=2, mantissa_bits=1, exponent_bias=1, nonfinite=(FloatNonfiniteBehavior.FINITE_ONLY)) class-attribute instance-attribute

FloatData dataclass

Bases: Data[float]

Source code in xdsl/dialects/builtin.py
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
@irdl_attr_definition
class FloatData(Data[float]):
    name = "builtin.float_data"

    @classmethod
    def parse_parameter(cls, parser: AttrParser) -> float:
        with parser.in_angle_brackets():
            return float(parser.parse_number())

    def print_parameter(self, printer: Printer) -> None:
        with printer.in_angle_brackets():
            printer.print_string(f"{self.data}")

    def __eq__(self, other: object):
        # avoid triggering `float('nan') != float('nan')` inequality
        return isinstance(other, FloatData) and (
            (math.isnan(self.data) and math.isnan(other.data))
            or self.data == other.data
        )

    def __hash__(self):
        return hash(self.data)

name = 'builtin.float_data' class-attribute instance-attribute

parse_parameter(parser: AttrParser) -> float classmethod

Source code in xdsl/dialects/builtin.py
1818
1819
1820
1821
@classmethod
def parse_parameter(cls, parser: AttrParser) -> float:
    with parser.in_angle_brackets():
        return float(parser.parse_number())

print_parameter(printer: Printer) -> None

Source code in xdsl/dialects/builtin.py
1823
1824
1825
def print_parameter(self, printer: Printer) -> None:
    with printer.in_angle_brackets():
        printer.print_string(f"{self.data}")

__eq__(other: object)

Source code in xdsl/dialects/builtin.py
1827
1828
1829
1830
1831
1832
def __eq__(self, other: object):
    # avoid triggering `float('nan') != float('nan')` inequality
    return isinstance(other, FloatData) and (
        (math.isnan(self.data) and math.isnan(other.data))
        or self.data == other.data
    )

__hash__()

Source code in xdsl/dialects/builtin.py
1834
1835
def __hash__(self):
    return hash(self.data)

FloatAttr

Bases: BuiltinAttribute, TypedAttribute, Generic[_FloatAttrTypeCovT]

Source code in xdsl/dialects/builtin.py
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
@irdl_attr_definition
class FloatAttr(BuiltinAttribute, TypedAttribute, Generic[_FloatAttrTypeCovT]):
    name = "float"

    value: FloatData
    type: _FloatAttrTypeCovT

    @overload
    def __init__(self, data: float | FloatData, type: _FloatAttrTypeCovT) -> None: ...

    @overload
    def __init__(self, data: float | FloatData, type: int) -> None: ...

    def __init__(
        self, data: float | FloatData, type: int | _FloatAttrTypeCovT | AnyFloat
    ) -> None:
        if isinstance(type, int):
            if type == 16:
                type = f16
            elif type == 32:
                type = f32
            elif type == 64:
                type = f64
            elif type == 80:
                type = f80
            elif type == 128:
                type = f128
            else:
                raise ValueError(f"Invalid bitwidth: {type}")

        value: float = data.data if isinstance(data, FloatData) else data
        # for supported types, constrain value to precision of floating point type
        # else, allow full python float precision
        if isinstance(
            type,
            Float64Type
            | Float32Type
            | Float16Type
            | BFloat16Type
            | ReducedPrecisionFloatType,
        ):
            value = type.unpack(type.pack((value,)), 1)[0]

        data_attr = FloatData(value)

        super().__init__(data_attr, type)

    @staticmethod
    def parse_with_type(
        parser: AttrParser,
        type: Attribute,
    ) -> TypedAttribute:
        assert isinstance(type, AnyFloat)
        return FloatAttr(parser.parse_float(), type)

    def print_without_type(self, printer: Printer):
        return printer.print_float(self.value.data, self.type)

    def print_builtin(self, printer: Printer):
        self.print_without_type(printer)
        printer.print_string(" : ")
        printer.print_attribute(self.get_type())

    @staticmethod
    def iter_unpack(
        type: _FloatAttrTypeInvT, buffer: ReadableBuffer, /
    ) -> Iterator[FloatAttr[_FloatAttrTypeInvT]]:
        """
        Yields unpacked values one at a time, starting at the beginning of the buffer.
        """
        for value in type.iter_unpack(buffer):
            yield FloatAttr(value, type)

    @staticmethod
    def unpack(
        type: _FloatAttrTypeInvT, buffer: ReadableBuffer, num: int, /
    ) -> tuple[FloatAttr[_FloatAttrTypeInvT], ...]:
        """
        Unpack `num` values from the beginning of the buffer.
        """
        return tuple(FloatAttr(value, type) for value in type.unpack(buffer, num))

    @staticmethod
    def constr(
        type: IRDLAttrConstraint[_FloatAttrTypeCovT] = AnyFloatConstr,
    ) -> AttrConstraint[FloatAttr[_FloatAttrTypeCovT]]:
        return cast(
            AttrConstraint[FloatAttr[_FloatAttrTypeCovT]],
            ParamAttrConstraint.get(
                FloatAttr,
                None,
                type,
            ),
        )

name = 'float' class-attribute instance-attribute

value: FloatData instance-attribute

type: _FloatAttrTypeCovT instance-attribute

__init__(data: float | FloatData, type: int | _FloatAttrTypeCovT | AnyFloat) -> None

__init__(
    data: float | FloatData, type: _FloatAttrTypeCovT
) -> None
__init__(data: float | FloatData, type: int) -> None
Source code in xdsl/dialects/builtin.py
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
def __init__(
    self, data: float | FloatData, type: int | _FloatAttrTypeCovT | AnyFloat
) -> None:
    if isinstance(type, int):
        if type == 16:
            type = f16
        elif type == 32:
            type = f32
        elif type == 64:
            type = f64
        elif type == 80:
            type = f80
        elif type == 128:
            type = f128
        else:
            raise ValueError(f"Invalid bitwidth: {type}")

    value: float = data.data if isinstance(data, FloatData) else data
    # for supported types, constrain value to precision of floating point type
    # else, allow full python float precision
    if isinstance(
        type,
        Float64Type
        | Float32Type
        | Float16Type
        | BFloat16Type
        | ReducedPrecisionFloatType,
    ):
        value = type.unpack(type.pack((value,)), 1)[0]

    data_attr = FloatData(value)

    super().__init__(data_attr, type)

parse_with_type(parser: AttrParser, type: Attribute) -> TypedAttribute staticmethod

Source code in xdsl/dialects/builtin.py
1891
1892
1893
1894
1895
1896
1897
@staticmethod
def parse_with_type(
    parser: AttrParser,
    type: Attribute,
) -> TypedAttribute:
    assert isinstance(type, AnyFloat)
    return FloatAttr(parser.parse_float(), type)

print_without_type(printer: Printer)

Source code in xdsl/dialects/builtin.py
1899
1900
def print_without_type(self, printer: Printer):
    return printer.print_float(self.value.data, self.type)

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
1902
1903
1904
1905
def print_builtin(self, printer: Printer):
    self.print_without_type(printer)
    printer.print_string(" : ")
    printer.print_attribute(self.get_type())

iter_unpack(type: _FloatAttrTypeInvT, buffer: ReadableBuffer) -> Iterator[FloatAttr[_FloatAttrTypeInvT]] staticmethod

Yields unpacked values one at a time, starting at the beginning of the buffer.

Source code in xdsl/dialects/builtin.py
1907
1908
1909
1910
1911
1912
1913
1914
1915
@staticmethod
def iter_unpack(
    type: _FloatAttrTypeInvT, buffer: ReadableBuffer, /
) -> Iterator[FloatAttr[_FloatAttrTypeInvT]]:
    """
    Yields unpacked values one at a time, starting at the beginning of the buffer.
    """
    for value in type.iter_unpack(buffer):
        yield FloatAttr(value, type)

unpack(type: _FloatAttrTypeInvT, buffer: ReadableBuffer, num: int) -> tuple[FloatAttr[_FloatAttrTypeInvT], ...] staticmethod

Unpack num values from the beginning of the buffer.

Source code in xdsl/dialects/builtin.py
1917
1918
1919
1920
1921
1922
1923
1924
@staticmethod
def unpack(
    type: _FloatAttrTypeInvT, buffer: ReadableBuffer, num: int, /
) -> tuple[FloatAttr[_FloatAttrTypeInvT], ...]:
    """
    Unpack `num` values from the beginning of the buffer.
    """
    return tuple(FloatAttr(value, type) for value in type.unpack(buffer, num))

constr(type: IRDLAttrConstraint[_FloatAttrTypeCovT] = AnyFloatConstr) -> AttrConstraint[FloatAttr[_FloatAttrTypeCovT]] staticmethod

Source code in xdsl/dialects/builtin.py
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
@staticmethod
def constr(
    type: IRDLAttrConstraint[_FloatAttrTypeCovT] = AnyFloatConstr,
) -> AttrConstraint[FloatAttr[_FloatAttrTypeCovT]]:
    return cast(
        AttrConstraint[FloatAttr[_FloatAttrTypeCovT]],
        ParamAttrConstraint.get(
            FloatAttr,
            None,
            type,
        ),
    )

ComplexType dataclass

Bases: PackableType[tuple[float, float] | tuple[int, int]], ParametrizedAttribute, BuiltinAttribute, ContainerType[_ComplexElementCovT], TypeAttribute, Generic[_ComplexElementCovT]

Source code in xdsl/dialects/builtin.py
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
@irdl_attr_definition
class ComplexType(
    PackableType[tuple[float, float] | tuple[int, int]],
    ParametrizedAttribute,
    BuiltinAttribute,
    ContainerType[_ComplexElementCovT],
    TypeAttribute,
    Generic[_ComplexElementCovT],
):
    name = "complex"
    element_type: _ComplexElementCovT

    def print_builtin(self, printer: Printer):
        printer.print_string("complex")
        with printer.in_angle_brackets():
            printer.print_attribute(self.element_type)

    def get_element_type(self) -> _ComplexElementCovT:
        return self.element_type

    @property
    def compile_time_size(self) -> int:
        return 2 * self.element_type.compile_time_size

    @property
    def size(self) -> int:
        return 2 * self.element_type.size

    def iter_unpack(self, buffer: ReadableBuffer, /):
        values = (value for value in self.element_type.iter_unpack(buffer))
        return ((real, imag) for real, imag in zip(values, values))

    def unpack(self, buffer: ReadableBuffer, num: int, /):
        values = (value for value in self.element_type.unpack(buffer, 2 * num))
        return tuple((real, imag) for real, imag in zip(values, values))

    @overload
    def pack_into(
        self: ComplexType[IntegerType],
        buffer: WriteableBuffer,
        offset: int,
        value: tuple[int, int],
    ) -> None: ...

    @overload
    def pack_into(
        self: ComplexType[AnyFloat],
        buffer: WriteableBuffer,
        offset: int,
        value: tuple[float, float],
    ) -> None: ...

    def pack_into(
        self,
        buffer: WriteableBuffer,
        offset: int,
        value: tuple[float, float] | tuple[int, int],
    ) -> None:
        self.element_type.pack_into(buffer, 2 * offset, value[0])  # pyright: ignore[reportArgumentType]
        self.element_type.pack_into(buffer, 2 * offset + 1, value[1])  # pyright: ignore[reportArgumentType]
        return

    @overload
    def pack(
        self: ComplexType[AnyFloat], values: Sequence[tuple[float, float]]
    ) -> bytes: ...

    @overload
    def pack(
        self: ComplexType[IntegerType], values: Sequence[tuple[int, int]]
    ) -> bytes: ...

    def pack(self, values: Sequence[tuple[float, float] | tuple[int, int]]) -> bytes:
        return self.element_type.pack(tuple(val for vals in values for val in vals))  # pyright: ignore[reportArgumentType]

    @staticmethod
    def constr(
        element_type: IRDLAttrConstraint[_ComplexElementCovT] | None = None,
    ) -> AttrConstraint[ComplexType[_ComplexElementCovT]]:
        return cast(
            AttrConstraint[ComplexType[_ComplexElementCovT]],
            ParamAttrConstraint.get(
                ComplexType,
                element_type,
            ),
        )

name = 'complex' class-attribute instance-attribute

element_type: _ComplexElementCovT instance-attribute

compile_time_size: int property

size: int property

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
1960
1961
1962
1963
def print_builtin(self, printer: Printer):
    printer.print_string("complex")
    with printer.in_angle_brackets():
        printer.print_attribute(self.element_type)

get_element_type() -> _ComplexElementCovT

Source code in xdsl/dialects/builtin.py
1965
1966
def get_element_type(self) -> _ComplexElementCovT:
    return self.element_type

iter_unpack(buffer: ReadableBuffer)

Source code in xdsl/dialects/builtin.py
1976
1977
1978
def iter_unpack(self, buffer: ReadableBuffer, /):
    values = (value for value in self.element_type.iter_unpack(buffer))
    return ((real, imag) for real, imag in zip(values, values))

unpack(buffer: ReadableBuffer, num: int)

Source code in xdsl/dialects/builtin.py
1980
1981
1982
def unpack(self, buffer: ReadableBuffer, num: int, /):
    values = (value for value in self.element_type.unpack(buffer, 2 * num))
    return tuple((real, imag) for real, imag in zip(values, values))

pack_into(buffer: WriteableBuffer, offset: int, value: tuple[float, float] | tuple[int, int]) -> None

pack_into(
    buffer: WriteableBuffer,
    offset: int,
    value: tuple[int, int],
) -> None
pack_into(
    buffer: WriteableBuffer,
    offset: int,
    value: tuple[float, float],
) -> None
Source code in xdsl/dialects/builtin.py
2000
2001
2002
2003
2004
2005
2006
2007
2008
def pack_into(
    self,
    buffer: WriteableBuffer,
    offset: int,
    value: tuple[float, float] | tuple[int, int],
) -> None:
    self.element_type.pack_into(buffer, 2 * offset, value[0])  # pyright: ignore[reportArgumentType]
    self.element_type.pack_into(buffer, 2 * offset + 1, value[1])  # pyright: ignore[reportArgumentType]
    return

pack(values: Sequence[tuple[float, float] | tuple[int, int]]) -> bytes

pack(values: Sequence[tuple[float, float]]) -> bytes
pack(values: Sequence[tuple[int, int]]) -> bytes
Source code in xdsl/dialects/builtin.py
2020
2021
def pack(self, values: Sequence[tuple[float, float] | tuple[int, int]]) -> bytes:
    return self.element_type.pack(tuple(val for vals in values for val in vals))  # pyright: ignore[reportArgumentType]

constr(element_type: IRDLAttrConstraint[_ComplexElementCovT] | None = None) -> AttrConstraint[ComplexType[_ComplexElementCovT]] staticmethod

Source code in xdsl/dialects/builtin.py
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
@staticmethod
def constr(
    element_type: IRDLAttrConstraint[_ComplexElementCovT] | None = None,
) -> AttrConstraint[ComplexType[_ComplexElementCovT]]:
    return cast(
        AttrConstraint[ComplexType[_ComplexElementCovT]],
        ParamAttrConstraint.get(
            ComplexType,
            element_type,
        ),
    )

DictionaryAttr

Bases: _BuiltinData[immutabledict[str, Attribute]]

Source code in xdsl/dialects/builtin.py
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
@irdl_attr_definition
class DictionaryAttr(_BuiltinData[immutabledict[str, Attribute]]):
    name = "dictionary"

    def __init__(self, value: Mapping[str, Attribute]):
        if not isinstance(value, immutabledict):
            value = immutabledict(value)
        super().__init__(value)

    def print_builtin(self, printer: Printer):
        printer.print_attr_dict(self.data)

    def verify(self) -> None:
        return super().verify()

name = 'dictionary' class-attribute instance-attribute

__init__(value: Mapping[str, Attribute])

Source code in xdsl/dialects/builtin.py
2040
2041
2042
2043
def __init__(self, value: Mapping[str, Attribute]):
    if not isinstance(value, immutabledict):
        value = immutabledict(value)
    super().__init__(value)

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
2045
2046
def print_builtin(self, printer: Printer):
    printer.print_attr_dict(self.data)

verify() -> None

Source code in xdsl/dialects/builtin.py
2048
2049
def verify(self) -> None:
    return super().verify()

TupleType dataclass

Bases: ParametrizedAttribute, BuiltinAttribute, TypeAttribute

Source code in xdsl/dialects/builtin.py
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
@irdl_attr_definition
class TupleType(ParametrizedAttribute, BuiltinAttribute, TypeAttribute):
    name = "tuple"

    types: ArrayAttr[TypeAttribute] = param_def(converter=ArrayAttr[TypeAttribute].get)

    def print_builtin(self, printer: Printer):
        printer.print_string("tuple")
        with printer.in_angle_brackets():
            printer.print_list(self.types, printer.print_attribute)

name = 'tuple' class-attribute instance-attribute

types: ArrayAttr[TypeAttribute] = param_def(converter=(ArrayAttr[TypeAttribute].get)) class-attribute instance-attribute

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
2058
2059
2060
2061
def print_builtin(self, printer: Printer):
    printer.print_string("tuple")
    with printer.in_angle_brackets():
        printer.print_list(self.types, printer.print_attribute)

VectorType

Bases: BuiltinAttribute, ParametrizedAttribute, TypeAttribute, ShapedType, ContainerType[AttributeCovT], Generic[AttributeCovT]

Source code in xdsl/dialects/builtin.py
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
@irdl_attr_definition
class VectorType(
    BuiltinAttribute,
    ParametrizedAttribute,
    TypeAttribute,
    ShapedType,
    ContainerType[AttributeCovT],
    Generic[AttributeCovT],
):
    name = "vector"

    element_type: AttributeCovT
    shape: ArrayAttr[IntAttr]
    scalable_dims: ArrayAttr[BoolAttr]

    def __init__(
        self,
        element_type: AttributeCovT,
        shape: Iterable[int | IntAttr],
        scalable_dims: ArrayAttr[BoolAttr] | None = None,
    ) -> None:
        shape = ArrayAttr(
            [IntAttr(dim) if isinstance(dim, int) else dim for dim in shape]
        )
        if scalable_dims is None:
            false = BoolAttr(False, i1)
            scalable_dims = ArrayAttr(false for _ in shape)
        super().__init__(element_type, shape, scalable_dims)

    @staticmethod
    def _print_vector_dim(printer: Printer, pair: tuple[IntAttr, BoolAttr]):
        """
        Helper method to print a vector dimension either as static (`4`) or scalable
        (`[4]`).
        """
        dim, scalable = pair
        if scalable:
            printer.print_string(f"[{dim.data}]")
        else:
            printer.print_string(f"{dim.data}")

    def print_builtin(self, printer: Printer):
        printer.print_string("vector")
        with printer.in_angle_brackets():
            printer.print_list(
                zip(self.shape, self.scalable_dims, strict=True),
                lambda pair: self._print_vector_dim(printer, pair),
                delimiter="x",
            )
            if self.shape.data:
                printer.print_string("x")

            printer.print_attribute(self.element_type)

    def get_num_dims(self) -> int:
        return len(self.shape.data)

    def get_num_scalable_dims(self) -> int:
        return sum(bool(d.value) for d in self.scalable_dims)

    def get_shape(self) -> tuple[int, ...]:
        return tuple(i.data for i in self.shape)

    def get_element_type(self) -> AttributeCovT:
        return self.element_type

    def get_scalable_dims(self) -> tuple[bool, ...]:
        return tuple(bool(i) for i in self.scalable_dims)

    def verify(self):
        num_dims = len(self.shape)
        num_scalable_dims = len(self.scalable_dims)
        if num_dims != num_scalable_dims:
            raise VerifyException(
                f"Number of scalable dimension specifiers {num_scalable_dims} must "
                f"equal to number of dimensions {num_dims}."
            )

    @staticmethod
    def constr(
        element_type: IRDLAttrConstraint[AttributeInvT] | None = None,
        *,
        shape: IRDLAttrConstraint[ArrayAttr[IntAttr]] | None = None,
        scalable_dims: IRDLAttrConstraint[ArrayAttr[BoolAttr]] | None = None,
    ) -> AttrConstraint[VectorType[AttributeInvT]]:
        shape_constr = AnyAttr() if shape is None else shape
        scalable_dims_constr = AnyAttr() if scalable_dims is None else scalable_dims
        return cast(
            AttrConstraint[VectorType[AttributeInvT]],
            ParamAttrConstraint.get(
                VectorType,
                element_type,
                shape_constr,
                scalable_dims_constr,
            ),
        )

name = 'vector' class-attribute instance-attribute

element_type: AttributeCovT instance-attribute

shape: ArrayAttr[IntAttr] instance-attribute

scalable_dims: ArrayAttr[BoolAttr] instance-attribute

__init__(element_type: AttributeCovT, shape: Iterable[int | IntAttr], scalable_dims: ArrayAttr[BoolAttr] | None = None) -> None

Source code in xdsl/dialects/builtin.py
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
def __init__(
    self,
    element_type: AttributeCovT,
    shape: Iterable[int | IntAttr],
    scalable_dims: ArrayAttr[BoolAttr] | None = None,
) -> None:
    shape = ArrayAttr(
        [IntAttr(dim) if isinstance(dim, int) else dim for dim in shape]
    )
    if scalable_dims is None:
        false = BoolAttr(False, i1)
        scalable_dims = ArrayAttr(false for _ in shape)
    super().__init__(element_type, shape, scalable_dims)

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
def print_builtin(self, printer: Printer):
    printer.print_string("vector")
    with printer.in_angle_brackets():
        printer.print_list(
            zip(self.shape, self.scalable_dims, strict=True),
            lambda pair: self._print_vector_dim(printer, pair),
            delimiter="x",
        )
        if self.shape.data:
            printer.print_string("x")

        printer.print_attribute(self.element_type)

get_num_dims() -> int

Source code in xdsl/dialects/builtin.py
2118
2119
def get_num_dims(self) -> int:
    return len(self.shape.data)

get_num_scalable_dims() -> int

Source code in xdsl/dialects/builtin.py
2121
2122
def get_num_scalable_dims(self) -> int:
    return sum(bool(d.value) for d in self.scalable_dims)

get_shape() -> tuple[int, ...]

Source code in xdsl/dialects/builtin.py
2124
2125
def get_shape(self) -> tuple[int, ...]:
    return tuple(i.data for i in self.shape)

get_element_type() -> AttributeCovT

Source code in xdsl/dialects/builtin.py
2127
2128
def get_element_type(self) -> AttributeCovT:
    return self.element_type

get_scalable_dims() -> tuple[bool, ...]

Source code in xdsl/dialects/builtin.py
2130
2131
def get_scalable_dims(self) -> tuple[bool, ...]:
    return tuple(bool(i) for i in self.scalable_dims)

verify()

Source code in xdsl/dialects/builtin.py
2133
2134
2135
2136
2137
2138
2139
2140
def verify(self):
    num_dims = len(self.shape)
    num_scalable_dims = len(self.scalable_dims)
    if num_dims != num_scalable_dims:
        raise VerifyException(
            f"Number of scalable dimension specifiers {num_scalable_dims} must "
            f"equal to number of dimensions {num_dims}."
        )

constr(element_type: IRDLAttrConstraint[AttributeInvT] | None = None, *, shape: IRDLAttrConstraint[ArrayAttr[IntAttr]] | None = None, scalable_dims: IRDLAttrConstraint[ArrayAttr[BoolAttr]] | None = None) -> AttrConstraint[VectorType[AttributeInvT]] staticmethod

Source code in xdsl/dialects/builtin.py
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
@staticmethod
def constr(
    element_type: IRDLAttrConstraint[AttributeInvT] | None = None,
    *,
    shape: IRDLAttrConstraint[ArrayAttr[IntAttr]] | None = None,
    scalable_dims: IRDLAttrConstraint[ArrayAttr[BoolAttr]] | None = None,
) -> AttrConstraint[VectorType[AttributeInvT]]:
    shape_constr = AnyAttr() if shape is None else shape
    scalable_dims_constr = AnyAttr() if scalable_dims is None else scalable_dims
    return cast(
        AttrConstraint[VectorType[AttributeInvT]],
        ParamAttrConstraint.get(
            VectorType,
            element_type,
            shape_constr,
            scalable_dims_constr,
        ),
    )

TensorType

Bases: ParametrizedAttribute, BuiltinAttribute, TypeAttribute, ShapedType, ContainerType[AttributeCovT], Generic[AttributeCovT]

Source code in xdsl/dialects/builtin.py
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
@irdl_attr_definition
class TensorType(
    ParametrizedAttribute,
    BuiltinAttribute,
    TypeAttribute,
    ShapedType,
    ContainerType[AttributeCovT],
    Generic[AttributeCovT],
):
    name = "tensor"

    shape: ArrayAttr[IntAttr]
    element_type: AttributeCovT
    encoding: Attribute

    def __init__(
        self,
        element_type: AttributeCovT,
        shape: Iterable[int | IntAttr],
        encoding: Attribute = NoneAttr(),
    ):
        shape = ArrayAttr(
            [IntAttr(dim) if isinstance(dim, int) else dim for dim in shape]
        )
        super().__init__(shape, element_type, encoding)

    def print_builtin(self, printer: Printer):
        printer.print_string("tensor")
        with printer.in_angle_brackets():
            printer.print_dimension_list(self.get_shape())
            if len(self.shape.data) != 0:
                printer.print_string("x")
            printer.print_attribute(self.element_type)
            if self.encoding != NoneAttr():
                printer.print_string(", ")
                printer.print_attribute(self.encoding)

    def get_num_dims(self) -> int:
        return len(self.shape.data)

    def get_shape(self) -> tuple[int, ...]:
        return tuple(i.data for i in self.shape.data)

    def get_element_type(self) -> AttributeCovT:
        return self.element_type

    @staticmethod
    def constr(
        element_type: IRDLAttrConstraint[AttributeInvT] | None = None,
        shape: IRDLAttrConstraint | None = None,
    ) -> AttrConstraint[TensorType[AttributeInvT]]:
        return cast(
            AttrConstraint[TensorType[AttributeInvT]],
            ParamAttrConstraint.get(TensorType, shape, element_type, AnyAttr()),
        )

name = 'tensor' class-attribute instance-attribute

shape: ArrayAttr[IntAttr] instance-attribute

element_type: AttributeCovT instance-attribute

encoding: Attribute instance-attribute

__init__(element_type: AttributeCovT, shape: Iterable[int | IntAttr], encoding: Attribute = NoneAttr())

Source code in xdsl/dialects/builtin.py
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
def __init__(
    self,
    element_type: AttributeCovT,
    shape: Iterable[int | IntAttr],
    encoding: Attribute = NoneAttr(),
):
    shape = ArrayAttr(
        [IntAttr(dim) if isinstance(dim, int) else dim for dim in shape]
    )
    super().__init__(shape, element_type, encoding)

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
def print_builtin(self, printer: Printer):
    printer.print_string("tensor")
    with printer.in_angle_brackets():
        printer.print_dimension_list(self.get_shape())
        if len(self.shape.data) != 0:
            printer.print_string("x")
        printer.print_attribute(self.element_type)
        if self.encoding != NoneAttr():
            printer.print_string(", ")
            printer.print_attribute(self.encoding)

get_num_dims() -> int

Source code in xdsl/dialects/builtin.py
2202
2203
def get_num_dims(self) -> int:
    return len(self.shape.data)

get_shape() -> tuple[int, ...]

Source code in xdsl/dialects/builtin.py
2205
2206
def get_shape(self) -> tuple[int, ...]:
    return tuple(i.data for i in self.shape.data)

get_element_type() -> AttributeCovT

Source code in xdsl/dialects/builtin.py
2208
2209
def get_element_type(self) -> AttributeCovT:
    return self.element_type

constr(element_type: IRDLAttrConstraint[AttributeInvT] | None = None, shape: IRDLAttrConstraint | None = None) -> AttrConstraint[TensorType[AttributeInvT]] staticmethod

Source code in xdsl/dialects/builtin.py
2211
2212
2213
2214
2215
2216
2217
2218
2219
@staticmethod
def constr(
    element_type: IRDLAttrConstraint[AttributeInvT] | None = None,
    shape: IRDLAttrConstraint | None = None,
) -> AttrConstraint[TensorType[AttributeInvT]]:
    return cast(
        AttrConstraint[TensorType[AttributeInvT]],
        ParamAttrConstraint.get(TensorType, shape, element_type, AnyAttr()),
    )

UnrankedTensorType dataclass

Bases: ParametrizedAttribute, BuiltinAttribute, TypeAttribute, ContainerType[AttributeCovT], Generic[AttributeCovT]

Source code in xdsl/dialects/builtin.py
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
@irdl_attr_definition
class UnrankedTensorType(
    ParametrizedAttribute,
    BuiltinAttribute,
    TypeAttribute,
    ContainerType[AttributeCovT],
    Generic[AttributeCovT],
):
    name = "unranked_tensor"

    element_type: AttributeCovT

    def get_element_type(self) -> AttributeCovT:
        return self.element_type

    def print_builtin(self, printer: Printer):
        with printer.delimited("tensor<*x", ">"):
            printer.print_attribute(self.element_type)

name = 'unranked_tensor' class-attribute instance-attribute

element_type: AttributeCovT instance-attribute

get_element_type() -> AttributeCovT

Source code in xdsl/dialects/builtin.py
2238
2239
def get_element_type(self) -> AttributeCovT:
    return self.element_type

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
2241
2242
2243
def print_builtin(self, printer: Printer):
    with printer.delimited("tensor<*x", ">"):
        printer.print_attribute(self.element_type)

VectorRankConstraint dataclass

Bases: AttrConstraint

Constrain a vector to be of a given rank.

Source code in xdsl/dialects/builtin.py
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
@dataclass(frozen=True)
class VectorRankConstraint(AttrConstraint):
    """
    Constrain a vector to be of a given rank.
    """

    expected_rank: int
    """The expected vector rank."""

    def verify(self, attr: Attribute, constraint_context: ConstraintContext) -> None:
        if not isinstance(attr, VectorType):
            raise VerifyException(f"{attr} should be of type VectorType.")
        if attr.get_num_dims() != self.expected_rank:
            raise VerifyException(
                f"Expected vector rank to be {self.expected_rank}, got {attr.get_num_dims()}."
            )

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> VectorRankConstraint:
        return self

expected_rank: int instance-attribute

The expected vector rank.

__init__(expected_rank: int) -> None

verify(attr: Attribute, constraint_context: ConstraintContext) -> None

Source code in xdsl/dialects/builtin.py
2281
2282
2283
2284
2285
2286
2287
def verify(self, attr: Attribute, constraint_context: ConstraintContext) -> None:
    if not isinstance(attr, VectorType):
        raise VerifyException(f"{attr} should be of type VectorType.")
    if attr.get_num_dims() != self.expected_rank:
        raise VerifyException(
            f"Expected vector rank to be {self.expected_rank}, got {attr.get_num_dims()}."
        )

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> VectorRankConstraint

Source code in xdsl/dialects/builtin.py
2289
2290
2291
2292
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> VectorRankConstraint:
    return self

VectorBaseTypeConstraint dataclass

Bases: AttrConstraint

Constrain a vector to be of a given base type.

Source code in xdsl/dialects/builtin.py
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
@dataclass(frozen=True)
class VectorBaseTypeConstraint(AttrConstraint):
    """
    Constrain a vector to be of a given base type.
    """

    expected_type: Attribute
    """The expected vector base type."""

    def verify(self, attr: Attribute, constraint_context: ConstraintContext) -> None:
        if not isa(attr, VectorType):
            raise VerifyException(f"{attr} should be of type VectorType.")
        if attr.element_type != self.expected_type:
            raise VerifyException(
                f"Expected vector type to be {self.expected_type}, got {attr.element_type}."
            )

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> VectorBaseTypeConstraint:
        return self

expected_type: Attribute instance-attribute

The expected vector base type.

__init__(expected_type: Attribute) -> None

verify(attr: Attribute, constraint_context: ConstraintContext) -> None

Source code in xdsl/dialects/builtin.py
2304
2305
2306
2307
2308
2309
2310
def verify(self, attr: Attribute, constraint_context: ConstraintContext) -> None:
    if not isa(attr, VectorType):
        raise VerifyException(f"{attr} should be of type VectorType.")
    if attr.element_type != self.expected_type:
        raise VerifyException(
            f"Expected vector type to be {self.expected_type}, got {attr.element_type}."
        )

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> VectorBaseTypeConstraint

Source code in xdsl/dialects/builtin.py
2312
2313
2314
2315
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> VectorBaseTypeConstraint:
    return self

VectorBaseTypeAndRankConstraint dataclass

Bases: AttrConstraint

Constrain a vector to be of a given rank and base type.

Source code in xdsl/dialects/builtin.py
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
@dataclass(frozen=True)
class VectorBaseTypeAndRankConstraint(AttrConstraint):
    """
    Constrain a vector to be of a given rank and base type.
    """

    expected_type: Attribute
    """The expected vector base type."""

    expected_rank: int
    """The expected vector rank."""

    def verify(self, attr: Attribute, constraint_context: ConstraintContext) -> None:
        constraint = VectorBaseTypeConstraint(
            self.expected_type
        ) & VectorRankConstraint(self.expected_rank)
        constraint.verify(attr, constraint_context)

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> VectorBaseTypeAndRankConstraint:
        return self

expected_type: Attribute instance-attribute

The expected vector base type.

expected_rank: int instance-attribute

The expected vector rank.

__init__(expected_type: Attribute, expected_rank: int) -> None

verify(attr: Attribute, constraint_context: ConstraintContext) -> None

Source code in xdsl/dialects/builtin.py
2330
2331
2332
2333
2334
def verify(self, attr: Attribute, constraint_context: ConstraintContext) -> None:
    constraint = VectorBaseTypeConstraint(
        self.expected_type
    ) & VectorRankConstraint(self.expected_rank)
    constraint.verify(attr, constraint_context)

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> VectorBaseTypeAndRankConstraint

Source code in xdsl/dialects/builtin.py
2336
2337
2338
2339
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> VectorBaseTypeAndRankConstraint:
    return self

DenseResourceAttr dataclass

Bases: BuiltinAttribute, TypedAttribute

Source code in xdsl/dialects/builtin.py
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
@irdl_attr_definition
class DenseResourceAttr(BuiltinAttribute, TypedAttribute):
    name = "dense_resource"

    resource_handle: StringAttr
    type: ShapedType

    def print_without_type(self, printer: Printer):
        printer.print_string("dense_resource")
        with printer.in_angle_brackets():
            printer.print_resource_handle("builtin", self.resource_handle.data)

    def print_builtin(self, printer: Printer):
        self.print_without_type(printer)
        printer.print_string(" : ")
        printer.print_attribute(self.get_type())

    @staticmethod
    def from_params(handle: str | StringAttr, type: ShapedType) -> DenseResourceAttr:
        if isinstance(handle, str):
            handle = StringAttr(handle)
        return DenseResourceAttr(handle, type)

name = 'dense_resource' class-attribute instance-attribute

resource_handle: StringAttr instance-attribute

type: ShapedType instance-attribute

print_without_type(printer: Printer)

Source code in xdsl/dialects/builtin.py
2349
2350
2351
2352
def print_without_type(self, printer: Printer):
    printer.print_string("dense_resource")
    with printer.in_angle_brackets():
        printer.print_resource_handle("builtin", self.resource_handle.data)

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
2354
2355
2356
2357
def print_builtin(self, printer: Printer):
    self.print_without_type(printer)
    printer.print_string(" : ")
    printer.print_attribute(self.get_type())

from_params(handle: str | StringAttr, type: ShapedType) -> DenseResourceAttr staticmethod

Source code in xdsl/dialects/builtin.py
2359
2360
2361
2362
2363
@staticmethod
def from_params(handle: str | StringAttr, type: ShapedType) -> DenseResourceAttr:
    if isinstance(handle, str):
        handle = StringAttr(handle)
    return DenseResourceAttr(handle, type)

DenseArrayBase dataclass

Bases: ContainerType[_DenseArrayElementCovT], ParametrizedAttribute, BuiltinAttribute, Generic[_DenseArrayElementCovT]

Source code in xdsl/dialects/builtin.py
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
@irdl_attr_definition
class DenseArrayBase(
    ContainerType[_DenseArrayElementCovT],
    ParametrizedAttribute,
    BuiltinAttribute,
    Generic[_DenseArrayElementCovT],
):
    name = "array"

    elt_type: _DenseArrayElementCovT
    data: BytesAttr

    def print_builtin(self, printer: Printer):
        printer.print_string("array")
        with printer.in_angle_brackets():
            printer.print_attribute(self.elt_type)
            if len(self) == 0:
                return
            printer.print_string(": ")
            elt_type = self.elt_type
            if isinstance(elt_type, IntegerType):
                int_self: DenseArrayBase[IntegerType] = self  # pyright: ignore[reportAssignmentType]
                printer.print_list(
                    int_self.iter_values(),
                    lambda x: printer.print_int(x, elt_type),
                )
            else:
                float_self: DenseArrayBase[AnyFloat] = self  # pyright: ignore[reportAssignmentType]
                printer.print_list(
                    float_self.iter_values(), lambda x: printer.print_float(x, elt_type)
                )

    def verify(self):
        data_len = len(self.data.data)
        elt_size = self.elt_type.size
        if data_len % elt_size:
            raise VerifyException(
                f"Data length of {self.name} ({data_len}) not divisible by element "
                f"size {elt_size}"
            )

    def get_element_type(self) -> _DenseArrayElementCovT:
        return self.elt_type

    @overload
    @staticmethod
    def from_list(
        data_type: _IntegerTypeInvT, data: Sequence[int]
    ) -> DenseArrayBase[_IntegerTypeInvT]: ...

    @overload
    @staticmethod
    def from_list(
        data_type: _FloatAttrTypeInvT, data: Sequence[float]
    ) -> DenseArrayBase[_FloatAttrTypeInvT]: ...

    @staticmethod
    def from_list(
        data_type: IntegerType | AnyFloat,
        data: (Sequence[int] | Sequence[float]),
    ) -> DenseArrayBase:
        if isinstance(data_type, IntegerType):
            data = tuple(
                data_type.get_normalized_value(value)  # pyright: ignore[reportArgumentType]
                for value in data
            )
        bytes_data = data_type.pack(data)  # pyright: ignore[reportArgumentType]
        return DenseArrayBase(data_type, BytesAttr(bytes_data))

    @overload
    def iter_values(self: DenseArrayBase[IntegerType]) -> Iterator[int]: ...

    @overload
    def iter_values(self: DenseArrayBase[AnyFloat]) -> Iterator[float]: ...

    def iter_values(self) -> Iterator[float] | Iterator[int]:
        """
        Returns an iterator of `int` or `float` values, depending on whether
        `self.elt_type` is an integer type or a floating point type.
        """
        return self.elt_type.iter_unpack(self.data.data)

    @overload
    def get_values(self: DenseArrayBase[IntegerType]) -> tuple[int, ...]: ...

    @overload
    def get_values(self: DenseArrayBase[AnyFloat]) -> tuple[float, ...]: ...

    def get_values(self) -> tuple[int, ...] | tuple[float, ...]:
        """
        Get a tuple of `int` or `float` values, depending on whether `self.elt_type` is
        an integer type or a floating point type.
        """
        return self.elt_type.unpack(self.data.data, len(self))

    def iter_attrs(self) -> Iterator[IntegerAttr] | Iterator[FloatAttr]:
        if isinstance(self.elt_type, IntegerType):
            return IntegerAttr.iter_unpack(self.elt_type, self.data.data)
        else:
            return FloatAttr.iter_unpack(self.elt_type, self.data.data)

    def get_attrs(self) -> tuple[IntegerAttr, ...] | tuple[FloatAttr, ...]:
        if isinstance(self.elt_type, IntegerType):
            return IntegerAttr.unpack(self.elt_type, self.data.data, len(self))
        else:
            return FloatAttr.unpack(self.elt_type, self.data.data, len(self))

    def __len__(self) -> int:
        return len(self.data.data) // self.elt_type.size

    @staticmethod
    def constr(
        element_type: IRDLAttrConstraint[_DenseArrayElementInvT] | None = None,
    ) -> AttrConstraint[DenseArrayBase[_DenseArrayElementInvT]]:
        return cast(
            AttrConstraint[DenseArrayBase[_DenseArrayElementInvT]],
            ParamAttrConstraint.get(DenseArrayBase, element_type, AnyAttr()),
        )

name = 'array' class-attribute instance-attribute

elt_type: _DenseArrayElementCovT instance-attribute

data: BytesAttr instance-attribute

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
def print_builtin(self, printer: Printer):
    printer.print_string("array")
    with printer.in_angle_brackets():
        printer.print_attribute(self.elt_type)
        if len(self) == 0:
            return
        printer.print_string(": ")
        elt_type = self.elt_type
        if isinstance(elt_type, IntegerType):
            int_self: DenseArrayBase[IntegerType] = self  # pyright: ignore[reportAssignmentType]
            printer.print_list(
                int_self.iter_values(),
                lambda x: printer.print_int(x, elt_type),
            )
        else:
            float_self: DenseArrayBase[AnyFloat] = self  # pyright: ignore[reportAssignmentType]
            printer.print_list(
                float_self.iter_values(), lambda x: printer.print_float(x, elt_type)
            )

verify()

Source code in xdsl/dialects/builtin.py
2412
2413
2414
2415
2416
2417
2418
2419
def verify(self):
    data_len = len(self.data.data)
    elt_size = self.elt_type.size
    if data_len % elt_size:
        raise VerifyException(
            f"Data length of {self.name} ({data_len}) not divisible by element "
            f"size {elt_size}"
        )

get_element_type() -> _DenseArrayElementCovT

Source code in xdsl/dialects/builtin.py
2421
2422
def get_element_type(self) -> _DenseArrayElementCovT:
    return self.elt_type

from_list(data_type: IntegerType | AnyFloat, data: Sequence[int] | Sequence[float]) -> DenseArrayBase staticmethod

from_list(
    data_type: _IntegerTypeInvT, data: Sequence[int]
) -> DenseArrayBase[_IntegerTypeInvT]
from_list(
    data_type: _FloatAttrTypeInvT, data: Sequence[float]
) -> DenseArrayBase[_FloatAttrTypeInvT]
Source code in xdsl/dialects/builtin.py
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
@staticmethod
def from_list(
    data_type: IntegerType | AnyFloat,
    data: (Sequence[int] | Sequence[float]),
) -> DenseArrayBase:
    if isinstance(data_type, IntegerType):
        data = tuple(
            data_type.get_normalized_value(value)  # pyright: ignore[reportArgumentType]
            for value in data
        )
    bytes_data = data_type.pack(data)  # pyright: ignore[reportArgumentType]
    return DenseArrayBase(data_type, BytesAttr(bytes_data))

iter_values() -> Iterator[float] | Iterator[int]

iter_values() -> Iterator[int]
iter_values() -> Iterator[float]

Returns an iterator of int or float values, depending on whether self.elt_type is an integer type or a floating point type.

Source code in xdsl/dialects/builtin.py
2455
2456
2457
2458
2459
2460
def iter_values(self) -> Iterator[float] | Iterator[int]:
    """
    Returns an iterator of `int` or `float` values, depending on whether
    `self.elt_type` is an integer type or a floating point type.
    """
    return self.elt_type.iter_unpack(self.data.data)

get_values() -> tuple[int, ...] | tuple[float, ...]

get_values() -> tuple[int, ...]
get_values() -> tuple[float, ...]

Get a tuple of int or float values, depending on whether self.elt_type is an integer type or a floating point type.

Source code in xdsl/dialects/builtin.py
2468
2469
2470
2471
2472
2473
def get_values(self) -> tuple[int, ...] | tuple[float, ...]:
    """
    Get a tuple of `int` or `float` values, depending on whether `self.elt_type` is
    an integer type or a floating point type.
    """
    return self.elt_type.unpack(self.data.data, len(self))

iter_attrs() -> Iterator[IntegerAttr] | Iterator[FloatAttr]

Source code in xdsl/dialects/builtin.py
2475
2476
2477
2478
2479
def iter_attrs(self) -> Iterator[IntegerAttr] | Iterator[FloatAttr]:
    if isinstance(self.elt_type, IntegerType):
        return IntegerAttr.iter_unpack(self.elt_type, self.data.data)
    else:
        return FloatAttr.iter_unpack(self.elt_type, self.data.data)

get_attrs() -> tuple[IntegerAttr, ...] | tuple[FloatAttr, ...]

Source code in xdsl/dialects/builtin.py
2481
2482
2483
2484
2485
def get_attrs(self) -> tuple[IntegerAttr, ...] | tuple[FloatAttr, ...]:
    if isinstance(self.elt_type, IntegerType):
        return IntegerAttr.unpack(self.elt_type, self.data.data, len(self))
    else:
        return FloatAttr.unpack(self.elt_type, self.data.data, len(self))

__len__() -> int

Source code in xdsl/dialects/builtin.py
2487
2488
def __len__(self) -> int:
    return len(self.data.data) // self.elt_type.size

constr(element_type: IRDLAttrConstraint[_DenseArrayElementInvT] | None = None) -> AttrConstraint[DenseArrayBase[_DenseArrayElementInvT]] staticmethod

Source code in xdsl/dialects/builtin.py
2490
2491
2492
2493
2494
2495
2496
2497
@staticmethod
def constr(
    element_type: IRDLAttrConstraint[_DenseArrayElementInvT] | None = None,
) -> AttrConstraint[DenseArrayBase[_DenseArrayElementInvT]]:
    return cast(
        AttrConstraint[DenseArrayBase[_DenseArrayElementInvT]],
        ParamAttrConstraint.get(DenseArrayBase, element_type, AnyAttr()),
    )

FunctionType dataclass

Bases: ParametrizedAttribute, BuiltinAttribute, TypeAttribute

Source code in xdsl/dialects/builtin.py
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
@irdl_attr_definition
class FunctionType(ParametrizedAttribute, BuiltinAttribute, TypeAttribute):
    name = "fun"

    inputs: ArrayAttr[Attribute]
    outputs: ArrayAttr[Attribute]

    def print_builtin(self, printer: Printer):
        with printer.in_parens():
            printer.print_list(self.inputs.data, printer.print_attribute)
        printer.print_string(" -> ")
        outputs = self.outputs.data
        if len(outputs) == 1 and not isinstance(outputs[0], FunctionType):
            printer.print_attribute(outputs[0])
        else:
            with printer.in_parens():
                printer.print_list(outputs, printer.print_attribute)

    @staticmethod
    def from_lists(
        inputs: Sequence[Attribute], outputs: Sequence[Attribute]
    ) -> FunctionType:
        return FunctionType(ArrayAttr(inputs), ArrayAttr(outputs))

    @staticmethod
    def from_attrs(
        inputs: ArrayAttr[Attribute], outputs: ArrayAttr[Attribute]
    ) -> FunctionType:
        return FunctionType(inputs, outputs)

name = 'fun' class-attribute instance-attribute

inputs: ArrayAttr[Attribute] instance-attribute

outputs: ArrayAttr[Attribute] instance-attribute

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
def print_builtin(self, printer: Printer):
    with printer.in_parens():
        printer.print_list(self.inputs.data, printer.print_attribute)
    printer.print_string(" -> ")
    outputs = self.outputs.data
    if len(outputs) == 1 and not isinstance(outputs[0], FunctionType):
        printer.print_attribute(outputs[0])
    else:
        with printer.in_parens():
            printer.print_list(outputs, printer.print_attribute)

from_lists(inputs: Sequence[Attribute], outputs: Sequence[Attribute]) -> FunctionType staticmethod

Source code in xdsl/dialects/builtin.py
2518
2519
2520
2521
2522
@staticmethod
def from_lists(
    inputs: Sequence[Attribute], outputs: Sequence[Attribute]
) -> FunctionType:
    return FunctionType(ArrayAttr(inputs), ArrayAttr(outputs))

from_attrs(inputs: ArrayAttr[Attribute], outputs: ArrayAttr[Attribute]) -> FunctionType staticmethod

Source code in xdsl/dialects/builtin.py
2524
2525
2526
2527
2528
@staticmethod
def from_attrs(
    inputs: ArrayAttr[Attribute], outputs: ArrayAttr[Attribute]
) -> FunctionType:
    return FunctionType(inputs, outputs)

OpaqueAttr dataclass

Bases: ParametrizedAttribute, BuiltinAttribute

Source code in xdsl/dialects/builtin.py
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
@irdl_attr_definition
class OpaqueAttr(ParametrizedAttribute, BuiltinAttribute):
    name = "opaque"

    ident: StringAttr
    value: StringAttr
    type: Attribute

    def print_builtin(self, printer: Printer):
        printer.print_string("opaque")
        with printer.in_angle_brackets():
            printer.print_attribute(self.ident)
            printer.print_string(", ")
            printer.print_attribute(self.value)

        if not isinstance(self.type, NoneAttr):
            printer.print_string(" : ")
            printer.print_attribute(self.type)

    @staticmethod
    def from_strings(name: str, value: str, type: Attribute = NoneAttr()) -> OpaqueAttr:
        return OpaqueAttr(StringAttr(name), StringAttr(value), type)

name = 'opaque' class-attribute instance-attribute

ident: StringAttr instance-attribute

value: StringAttr instance-attribute

type: Attribute instance-attribute

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
def print_builtin(self, printer: Printer):
    printer.print_string("opaque")
    with printer.in_angle_brackets():
        printer.print_attribute(self.ident)
        printer.print_string(", ")
        printer.print_attribute(self.value)

    if not isinstance(self.type, NoneAttr):
        printer.print_string(" : ")
        printer.print_attribute(self.type)

from_strings(name: str, value: str, type: Attribute = NoneAttr()) -> OpaqueAttr staticmethod

Source code in xdsl/dialects/builtin.py
2550
2551
2552
@staticmethod
def from_strings(name: str, value: str, type: Attribute = NoneAttr()) -> OpaqueAttr:
    return OpaqueAttr(StringAttr(name), StringAttr(value), type)

MemRefLayoutAttr dataclass

Bases: Attribute, ABC

Interface for any attribute acceptable as a memref layout.

Source code in xdsl/dialects/builtin.py
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
class MemRefLayoutAttr(Attribute, ABC):
    """
    Interface for any attribute acceptable as a memref layout.
    """

    @abstractmethod
    def get_affine_map(self) -> AffineMap:
        """
        Return the affine mapping from the iteration space of this
        layout to the element offset in linear memory. The resulting
        affine map thus has only one result.
        """
        raise NotImplementedError()

    def get_strides(self) -> Sequence[int | None] | None:
        """
        (optional) Return the list of strides, representing the element offset
        in linear memory for every dimension in the iteration space of
        this memref layout attribute.

        Note: The dimension of the iteration space may differ from the dimension
        of the data it represents. For instance, this can occur in a tiled layout.

        This is only applicable to hyper-rectangular layouts.
        If this is not applicable for a given layout, returns None
        """
        return None

    def get_offset(self) -> int | None:
        """
        (optional) Return the static offset of this memref layout, if available.

        Returns `None` when the offset is dynamic or when this layout does not
        expose a strided offset.
        """
        return None

get_affine_map() -> AffineMap abstractmethod

Return the affine mapping from the iteration space of this layout to the element offset in linear memory. The resulting affine map thus has only one result.

Source code in xdsl/dialects/builtin.py
2560
2561
2562
2563
2564
2565
2566
2567
@abstractmethod
def get_affine_map(self) -> AffineMap:
    """
    Return the affine mapping from the iteration space of this
    layout to the element offset in linear memory. The resulting
    affine map thus has only one result.
    """
    raise NotImplementedError()

get_strides() -> Sequence[int | None] | None

(optional) Return the list of strides, representing the element offset in linear memory for every dimension in the iteration space of this memref layout attribute.

Note: The dimension of the iteration space may differ from the dimension of the data it represents. For instance, this can occur in a tiled layout.

This is only applicable to hyper-rectangular layouts. If this is not applicable for a given layout, returns None

Source code in xdsl/dialects/builtin.py
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
def get_strides(self) -> Sequence[int | None] | None:
    """
    (optional) Return the list of strides, representing the element offset
    in linear memory for every dimension in the iteration space of
    this memref layout attribute.

    Note: The dimension of the iteration space may differ from the dimension
    of the data it represents. For instance, this can occur in a tiled layout.

    This is only applicable to hyper-rectangular layouts.
    If this is not applicable for a given layout, returns None
    """
    return None

get_offset() -> int | None

(optional) Return the static offset of this memref layout, if available.

Returns None when the offset is dynamic or when this layout does not expose a strided offset.

Source code in xdsl/dialects/builtin.py
2583
2584
2585
2586
2587
2588
2589
2590
def get_offset(self) -> int | None:
    """
    (optional) Return the static offset of this memref layout, if available.

    Returns `None` when the offset is dynamic or when this layout does not
    expose a strided offset.
    """
    return None

StridedLayoutAttr

Bases: MemRefLayoutAttr, BuiltinAttribute, ParametrizedAttribute

An attribute representing a strided layout of a shaped type. See external documentation.

Contrary to MLIR, we represent dynamic offsets and strides with NoneAttr, and we do not restrict offsets and strides to 64-bits integers.

Source code in xdsl/dialects/builtin.py
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
@irdl_attr_definition
class StridedLayoutAttr(MemRefLayoutAttr, BuiltinAttribute, ParametrizedAttribute):
    """
    An attribute representing a strided layout of a shaped type.
    See external [documentation](https://mlir.llvm.org/docs/Dialects/Builtin/#stridedlayoutattr).

    Contrary to MLIR, we represent dynamic offsets and strides with
    `NoneAttr`, and we do not restrict offsets and strides to 64-bits
    integers.
    """

    name = "strided"

    strides: ArrayAttr[IntAttr | NoneAttr]
    offset: IntAttr | NoneAttr

    def __init__(
        self,
        strides: (
            ArrayAttr[IntAttr | NoneAttr] | Sequence[int | IntAttr | NoneAttr | None]
        ),
        offset: int | IntAttr | NoneAttr | None = 0,
    ) -> None:
        if not isinstance(strides, ArrayAttr):
            strides_values: list[IntAttr | NoneAttr] = []
            for stride in strides:
                if isinstance(stride, int):
                    strides_values.append(IntAttr(stride))
                elif stride is None:
                    strides_values.append(NoneAttr())
                else:
                    strides_values.append(stride)
            strides = ArrayAttr(strides_values)

        if isinstance(offset, int):
            offset = IntAttr(offset)
        if offset is None:
            offset = NoneAttr()

        super().__init__(strides, offset)

    @staticmethod
    def _print_int_or_question(printer: Printer, value: IntAttr | NoneAttr) -> None:
        printer.print_string(f"{value.data}" if isinstance(value, IntAttr) else "?")

    def print_builtin(self, printer: Printer):
        printer.print_string("strided")
        with printer.in_angle_brackets():
            with printer.in_square_brackets():
                printer.print_list(
                    self.strides.data,
                    lambda value: self._print_int_or_question(printer, value),
                )
            if self.offset != IntAttr(0):
                printer.print_string(", offset: ")
                self._print_int_or_question(printer, self.offset)

    def get_strides(self) -> Sequence[int | None]:
        return tuple(
            None if isinstance(stride, NoneAttr) else stride.data
            for stride in self.strides
        )

    def get_offset(self) -> int | None:
        if isinstance(self.offset, NoneAttr):
            return None
        else:
            return self.offset.data

    def get_affine_map(self) -> AffineMap:
        """
        Return the affine mapping from the iteration space of this
        layout to the element offset in linear memory. The resulting
        affine map thus has only one result.

        For dynamic strides, this results in an affinemap with a number
        of symbols, ordered in the following manner:
            (1) Symbol for the dynamic offset of the layout
            (2) Symbols for every dynamic stride of the layout
        """

        # keep track of number of symbols
        nb_symbols = 0

        result = AffineConstantExpr(0)

        # add offset
        if isinstance(self.offset, IntAttr):
            result += AffineConstantExpr(self.offset.data)
        else:  # NoneAttr
            result += AffineSymExpr(nb_symbols)
            nb_symbols += 1

        for dim, stride in enumerate(self.strides.data):
            if isinstance(stride, IntAttr):
                stride_expr = AffineConstantExpr(stride.data)
            else:  # NoneAttr
                stride_expr = AffineSymExpr(nb_symbols)
                nb_symbols += 1
            result += AffineDimExpr(dim) * stride_expr

        return AffineMap(len(self.strides), nb_symbols, (result,))

name = 'strided' class-attribute instance-attribute

strides: ArrayAttr[IntAttr | NoneAttr] instance-attribute

offset: IntAttr | NoneAttr instance-attribute

__init__(strides: ArrayAttr[IntAttr | NoneAttr] | Sequence[int | IntAttr | NoneAttr | None], offset: int | IntAttr | NoneAttr | None = 0) -> None

Source code in xdsl/dialects/builtin.py
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
def __init__(
    self,
    strides: (
        ArrayAttr[IntAttr | NoneAttr] | Sequence[int | IntAttr | NoneAttr | None]
    ),
    offset: int | IntAttr | NoneAttr | None = 0,
) -> None:
    if not isinstance(strides, ArrayAttr):
        strides_values: list[IntAttr | NoneAttr] = []
        for stride in strides:
            if isinstance(stride, int):
                strides_values.append(IntAttr(stride))
            elif stride is None:
                strides_values.append(NoneAttr())
            else:
                strides_values.append(stride)
        strides = ArrayAttr(strides_values)

    if isinstance(offset, int):
        offset = IntAttr(offset)
    if offset is None:
        offset = NoneAttr()

    super().__init__(strides, offset)

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
def print_builtin(self, printer: Printer):
    printer.print_string("strided")
    with printer.in_angle_brackets():
        with printer.in_square_brackets():
            printer.print_list(
                self.strides.data,
                lambda value: self._print_int_or_question(printer, value),
            )
        if self.offset != IntAttr(0):
            printer.print_string(", offset: ")
            self._print_int_or_question(printer, self.offset)

get_strides() -> Sequence[int | None]

Source code in xdsl/dialects/builtin.py
2650
2651
2652
2653
2654
def get_strides(self) -> Sequence[int | None]:
    return tuple(
        None if isinstance(stride, NoneAttr) else stride.data
        for stride in self.strides
    )

get_offset() -> int | None

Source code in xdsl/dialects/builtin.py
2656
2657
2658
2659
2660
def get_offset(self) -> int | None:
    if isinstance(self.offset, NoneAttr):
        return None
    else:
        return self.offset.data

get_affine_map() -> AffineMap

Return the affine mapping from the iteration space of this layout to the element offset in linear memory. The resulting affine map thus has only one result.

For dynamic strides, this results in an affinemap with a number of symbols, ordered in the following manner: (1) Symbol for the dynamic offset of the layout (2) Symbols for every dynamic stride of the layout

Source code in xdsl/dialects/builtin.py
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
def get_affine_map(self) -> AffineMap:
    """
    Return the affine mapping from the iteration space of this
    layout to the element offset in linear memory. The resulting
    affine map thus has only one result.

    For dynamic strides, this results in an affinemap with a number
    of symbols, ordered in the following manner:
        (1) Symbol for the dynamic offset of the layout
        (2) Symbols for every dynamic stride of the layout
    """

    # keep track of number of symbols
    nb_symbols = 0

    result = AffineConstantExpr(0)

    # add offset
    if isinstance(self.offset, IntAttr):
        result += AffineConstantExpr(self.offset.data)
    else:  # NoneAttr
        result += AffineSymExpr(nb_symbols)
        nb_symbols += 1

    for dim, stride in enumerate(self.strides.data):
        if isinstance(stride, IntAttr):
            stride_expr = AffineConstantExpr(stride.data)
        else:  # NoneAttr
            stride_expr = AffineSymExpr(nb_symbols)
            nb_symbols += 1
        result += AffineDimExpr(dim) * stride_expr

    return AffineMap(len(self.strides), nb_symbols, (result,))

AffineMapAttr dataclass

Bases: MemRefLayoutAttr, _BuiltinData[AffineMap]

An Attribute containing an AffineMap object.

Source code in xdsl/dialects/builtin.py
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
@irdl_attr_definition
class AffineMapAttr(MemRefLayoutAttr, _BuiltinData[AffineMap]):
    """An Attribute containing an AffineMap object."""

    name = "affine_map"

    def print_builtin(self, printer: Printer):
        printer.print_string(f"affine_map<{self.data}>")

    @staticmethod
    def constant_map(value: int) -> AffineMapAttr:
        return AffineMapAttr(AffineMap.constant_map(value))

    def get_affine_map(self) -> AffineMap:
        return self.data

name = 'affine_map' class-attribute instance-attribute

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
2703
2704
def print_builtin(self, printer: Printer):
    printer.print_string(f"affine_map<{self.data}>")

constant_map(value: int) -> AffineMapAttr staticmethod

Source code in xdsl/dialects/builtin.py
2706
2707
2708
@staticmethod
def constant_map(value: int) -> AffineMapAttr:
    return AffineMapAttr(AffineMap.constant_map(value))

get_affine_map() -> AffineMap

Source code in xdsl/dialects/builtin.py
2710
2711
def get_affine_map(self) -> AffineMap:
    return self.data

AffineSetAttr dataclass

Bases: _BuiltinData[AffineSet]

An attribute containing an AffineSet object.

Source code in xdsl/dialects/builtin.py
2714
2715
2716
2717
2718
2719
2720
2721
@irdl_attr_definition
class AffineSetAttr(_BuiltinData[AffineSet]):
    """An attribute containing an AffineSet object."""

    name = "affine_set"

    def print_builtin(self, printer: Printer):
        printer.print_string(f"affine_set<{self.data}>")

name = 'affine_set' class-attribute instance-attribute

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
2720
2721
def print_builtin(self, printer: Printer):
    printer.print_string(f"affine_set<{self.data}>")

UnrealizedConversionCastOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/builtin.py
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
@irdl_op_definition
class UnrealizedConversionCastOp(IRDLOperation):
    name = "builtin.unrealized_conversion_cast"

    inputs = var_operand_def()
    outputs = var_result_def()

    traits = traits_def(NoMemoryEffect())

    @staticmethod
    def get(inputs: Sequence[SSAValue | Operation], result_type: Sequence[Attribute]):
        return UnrealizedConversionCastOp.build(
            operands=[inputs],
            result_types=[result_type],
        )

    @staticmethod
    def cast_one(
        input: SSAValue, result_type: AttributeInvT
    ) -> tuple[UnrealizedConversionCastOp, SSAValue[AttributeInvT]]:
        op = UnrealizedConversionCastOp(operands=(input,), result_types=(result_type,))
        res: SSAValue[AttributeInvT] = op.results[0]  # pyright: ignore[reportAssignmentType]
        if input.name_hint is not None:
            res.name_hint = input.name_hint
        return op, res

    @classmethod
    def parse(cls, parser: Parser) -> Self:
        if parser.parse_optional_characters("to") is None:
            args = parser.parse_comma_separated_list(
                parser.Delimiter.NONE,
                parser.parse_unresolved_operand,
            )
            parser.parse_punctuation(":")
            input_types = parser.parse_comma_separated_list(
                parser.Delimiter.NONE,
                parser.parse_type,
            )
            parser.parse_characters("to")
            inputs = parser.resolve_operands(args, input_types, parser.pos)
        else:
            inputs = list[SSAValue]()
        output_types = parser.parse_comma_separated_list(
            parser.Delimiter.NONE,
            parser.parse_type,
        )
        attributes = parser.parse_optional_attr_dict()
        return cls(
            operands=[inputs], result_types=[output_types], attributes=attributes
        )

    def print(self, printer: Printer):
        def print_fn(operand: SSAValue) -> None:
            return printer.print_attribute(operand.type)

        if self.inputs:
            printer.print_string(" ")
            printer.print_list(self.inputs, printer.print_operand)
            printer.print_string(" : ")
            printer.print_list(self.inputs, print_fn)
        printer.print_string(" to ")
        printer.print_list(self.outputs, print_fn)
        printer.print_op_attributes(self.attributes)

name = 'builtin.unrealized_conversion_cast' class-attribute instance-attribute

inputs = var_operand_def() class-attribute instance-attribute

outputs = var_result_def() class-attribute instance-attribute

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

get(inputs: Sequence[SSAValue | Operation], result_type: Sequence[Attribute]) staticmethod

Source code in xdsl/dialects/builtin.py
2733
2734
2735
2736
2737
2738
@staticmethod
def get(inputs: Sequence[SSAValue | Operation], result_type: Sequence[Attribute]):
    return UnrealizedConversionCastOp.build(
        operands=[inputs],
        result_types=[result_type],
    )

cast_one(input: SSAValue, result_type: AttributeInvT) -> tuple[UnrealizedConversionCastOp, SSAValue[AttributeInvT]] staticmethod

Source code in xdsl/dialects/builtin.py
2740
2741
2742
2743
2744
2745
2746
2747
2748
@staticmethod
def cast_one(
    input: SSAValue, result_type: AttributeInvT
) -> tuple[UnrealizedConversionCastOp, SSAValue[AttributeInvT]]:
    op = UnrealizedConversionCastOp(operands=(input,), result_types=(result_type,))
    res: SSAValue[AttributeInvT] = op.results[0]  # pyright: ignore[reportAssignmentType]
    if input.name_hint is not None:
        res.name_hint = input.name_hint
    return op, res

parse(parser: Parser) -> Self classmethod

Source code in xdsl/dialects/builtin.py
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
@classmethod
def parse(cls, parser: Parser) -> Self:
    if parser.parse_optional_characters("to") is None:
        args = parser.parse_comma_separated_list(
            parser.Delimiter.NONE,
            parser.parse_unresolved_operand,
        )
        parser.parse_punctuation(":")
        input_types = parser.parse_comma_separated_list(
            parser.Delimiter.NONE,
            parser.parse_type,
        )
        parser.parse_characters("to")
        inputs = parser.resolve_operands(args, input_types, parser.pos)
    else:
        inputs = list[SSAValue]()
    output_types = parser.parse_comma_separated_list(
        parser.Delimiter.NONE,
        parser.parse_type,
    )
    attributes = parser.parse_optional_attr_dict()
    return cls(
        operands=[inputs], result_types=[output_types], attributes=attributes
    )

print(printer: Printer)

Source code in xdsl/dialects/builtin.py
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
def print(self, printer: Printer):
    def print_fn(operand: SSAValue) -> None:
        return printer.print_attribute(operand.type)

    if self.inputs:
        printer.print_string(" ")
        printer.print_list(self.inputs, printer.print_operand)
        printer.print_string(" : ")
        printer.print_list(self.inputs, print_fn)
    printer.print_string(" to ")
    printer.print_list(self.outputs, print_fn)
    printer.print_op_attributes(self.attributes)

UnregisteredOp dataclass

Bases: Operation, ABC

An unregistered operation.

Each unregistered op is registered as a subclass of UnregisteredOp, and op with different names have distinct subclasses.

Source code in xdsl/dialects/builtin.py
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
class UnregisteredOp(Operation, ABC):
    """
    An unregistered operation.

    Each unregistered op is registered as a subclass of `UnregisteredOp`,
    and op with different names have distinct subclasses.
    """

    name = "builtin.unregistered"
    traits = traits_def()

    @property
    def op_name(self) -> StringAttr:
        if "op_name__" not in self.attributes:
            raise ValueError("missing 'op_name__' attribute")
        op_name = self.attributes["op_name__"]
        if not isinstance(op_name, StringAttr):
            raise ValueError(
                f"'op_name__' is expected to have 'StringAttr' type, got {op_name}"
            )
        return op_name

    @classmethod
    def with_name(cls, name: str) -> type[Operation]:
        """
        Return a new unregistered operation type given a name.
        This function should not be called directly. Use methods from
        `Context` to get an `UnregisteredOp` type.
        """

        class UnregisteredOpWithNameOp(UnregisteredOp):
            @classmethod
            def create(
                cls,
                *,
                operands: Sequence[SSAValue] = (),
                result_types: Sequence[Attribute] = (),
                properties: Mapping[str, Attribute] = {},
                attributes: Mapping[str, Attribute] = {},
                location: LocationAttr | None = None,
                successors: Sequence[Block] = (),
                regions: Sequence[Region] = (),
            ):
                op = super().create(
                    operands=operands,
                    result_types=result_types,
                    properties=properties,
                    attributes=attributes,
                    location=location,
                    successors=successors,
                    regions=regions,
                )
                op.attributes["op_name__"] = StringAttr(name)
                return op

        return UnregisteredOpWithNameOp

    @classmethod
    def has_trait(
        cls,
        trait: type[OpTrait] | OpTrait,
        *,
        value_if_unregistered: bool = True,
    ) -> bool:
        return value_if_unregistered

name = 'builtin.unregistered' class-attribute instance-attribute

traits = traits_def() class-attribute instance-attribute

op_name: StringAttr property

with_name(name: str) -> type[Operation] classmethod

Return a new unregistered operation type given a name. This function should not be called directly. Use methods from Context to get an UnregisteredOp type.

Source code in xdsl/dialects/builtin.py
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
@classmethod
def with_name(cls, name: str) -> type[Operation]:
    """
    Return a new unregistered operation type given a name.
    This function should not be called directly. Use methods from
    `Context` to get an `UnregisteredOp` type.
    """

    class UnregisteredOpWithNameOp(UnregisteredOp):
        @classmethod
        def create(
            cls,
            *,
            operands: Sequence[SSAValue] = (),
            result_types: Sequence[Attribute] = (),
            properties: Mapping[str, Attribute] = {},
            attributes: Mapping[str, Attribute] = {},
            location: LocationAttr | None = None,
            successors: Sequence[Block] = (),
            regions: Sequence[Region] = (),
        ):
            op = super().create(
                operands=operands,
                result_types=result_types,
                properties=properties,
                attributes=attributes,
                location=location,
                successors=successors,
                regions=regions,
            )
            op.attributes["op_name__"] = StringAttr(name)
            return op

    return UnregisteredOpWithNameOp

has_trait(trait: type[OpTrait] | OpTrait, *, value_if_unregistered: bool = True) -> bool classmethod

Source code in xdsl/dialects/builtin.py
2846
2847
2848
2849
2850
2851
2852
2853
@classmethod
def has_trait(
    cls,
    trait: type[OpTrait] | OpTrait,
    *,
    value_if_unregistered: bool = True,
) -> bool:
    return value_if_unregistered

UnregisteredAttr dataclass

Bases: ParametrizedAttribute, BuiltinAttribute, ABC

An unregistered attribute or type.

Each unregistered attribute is registered as a subclass of UnregisteredAttr, and attribute with different names have distinct subclasses.

Since attributes do not have a generic format, unregistered attributes represent their original parameters as a string, which is exactly the content parsed from the textual representation.

Source code in xdsl/dialects/builtin.py
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
@dataclass(frozen=True, init=False)
class UnregisteredAttr(ParametrizedAttribute, BuiltinAttribute, ABC):
    """
    An unregistered attribute or type.

    Each unregistered attribute is registered as a subclass of
    `UnregisteredAttr`, and attribute with different names have
    distinct subclasses.

    Since attributes do not have a generic format, unregistered
    attributes represent their original parameters as a string,
    which is exactly the content parsed from the textual
    representation.
    """

    name = "builtin.unregistered"

    attr_name: StringAttr
    is_type: IntAttr
    is_opaque: IntAttr
    value: StringAttr
    """
    This parameter is non-null is the attribute is a type, and null otherwise.
    """

    def __init__(
        self,
        attr_name: str | StringAttr,
        is_type: bool | IntAttr,
        is_opaque: bool | IntAttr,
        value: str | StringAttr,
    ):
        if isinstance(attr_name, str):
            attr_name = StringAttr(attr_name)
        if isinstance(is_type, bool):
            is_type = IntAttr(int(is_type))
        if isinstance(is_opaque, bool):
            is_opaque = IntAttr(int(is_opaque))
        if isinstance(value, str):
            value = StringAttr(value)
        super().__init__(attr_name, is_type, is_opaque, value)

    def print_builtin(self, printer: Printer):
        # Do not print `!` or `#` for unregistered builtin attributes
        printer.print_string("!" if self.is_type.data else "#")
        if self.is_opaque.data:
            printer.print_string(
                f"{self.attr_name.data.replace('.', '<', 1)}{self.value.data}>"
            )
        else:
            printer.print_string(self.attr_name.data)
            if self.value.data:
                printer.print_string(f"<{self.value.data}>")

    @classmethod
    def with_name_and_type(cls, name: str, is_type: bool) -> type[UnregisteredAttr]:
        """
        Return a new unregistered attribute type given a name and a
        boolean indicating if the attribute can be a type.
        This function should not be called directly. Use methods from
        `Context` to get an `UnregisteredAttr` type.
        """

        @irdl_attr_definition(init=False)
        class UnregisteredAttrWithName(UnregisteredAttr):
            def verify(self):
                if self.attr_name.data != name:
                    raise VerifyException("Unregistered attribute name mismatch")
                if self.is_type.data != int(is_type):
                    raise VerifyException("Unregistered attribute is_type mismatch")

        @irdl_attr_definition(init=False)
        class UnregisteredAttrTypeWithName(UnregisteredAttr, TypeAttribute):
            def verify(self):
                if self.attr_name.data != name:
                    raise VerifyException("Unregistered attribute name mismatch")
                if self.is_type.data != int(is_type):
                    raise VerifyException("Unregistered attribute is_type mismatch")

        if is_type:
            return UnregisteredAttrTypeWithName
        else:
            return UnregisteredAttrWithName

name = 'builtin.unregistered' class-attribute instance-attribute

attr_name: StringAttr instance-attribute

is_type: IntAttr instance-attribute

is_opaque: IntAttr instance-attribute

value: StringAttr instance-attribute

This parameter is non-null is the attribute is a type, and null otherwise.

__init__(attr_name: str | StringAttr, is_type: bool | IntAttr, is_opaque: bool | IntAttr, value: str | StringAttr)

Source code in xdsl/dialects/builtin.py
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
def __init__(
    self,
    attr_name: str | StringAttr,
    is_type: bool | IntAttr,
    is_opaque: bool | IntAttr,
    value: str | StringAttr,
):
    if isinstance(attr_name, str):
        attr_name = StringAttr(attr_name)
    if isinstance(is_type, bool):
        is_type = IntAttr(int(is_type))
    if isinstance(is_opaque, bool):
        is_opaque = IntAttr(int(is_opaque))
    if isinstance(value, str):
        value = StringAttr(value)
    super().__init__(attr_name, is_type, is_opaque, value)

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
def print_builtin(self, printer: Printer):
    # Do not print `!` or `#` for unregistered builtin attributes
    printer.print_string("!" if self.is_type.data else "#")
    if self.is_opaque.data:
        printer.print_string(
            f"{self.attr_name.data.replace('.', '<', 1)}{self.value.data}>"
        )
    else:
        printer.print_string(self.attr_name.data)
        if self.value.data:
            printer.print_string(f"<{self.value.data}>")

with_name_and_type(name: str, is_type: bool) -> type[UnregisteredAttr] classmethod

Return a new unregistered attribute type given a name and a boolean indicating if the attribute can be a type. This function should not be called directly. Use methods from Context to get an UnregisteredAttr type.

Source code in xdsl/dialects/builtin.py
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
@classmethod
def with_name_and_type(cls, name: str, is_type: bool) -> type[UnregisteredAttr]:
    """
    Return a new unregistered attribute type given a name and a
    boolean indicating if the attribute can be a type.
    This function should not be called directly. Use methods from
    `Context` to get an `UnregisteredAttr` type.
    """

    @irdl_attr_definition(init=False)
    class UnregisteredAttrWithName(UnregisteredAttr):
        def verify(self):
            if self.attr_name.data != name:
                raise VerifyException("Unregistered attribute name mismatch")
            if self.is_type.data != int(is_type):
                raise VerifyException("Unregistered attribute is_type mismatch")

    @irdl_attr_definition(init=False)
    class UnregisteredAttrTypeWithName(UnregisteredAttr, TypeAttribute):
        def verify(self):
            if self.attr_name.data != name:
                raise VerifyException("Unregistered attribute name mismatch")
            if self.is_type.data != int(is_type):
                raise VerifyException("Unregistered attribute is_type mismatch")

    if is_type:
        return UnregisteredAttrTypeWithName
    else:
        return UnregisteredAttrWithName

ModuleOp

Bases: IRDLOperation

Source code in xdsl/dialects/builtin.py
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
@irdl_op_definition
class ModuleOp(IRDLOperation):
    name = "builtin.module"

    sym_name = opt_prop_def(StringAttr)

    body = region_def("single_block")

    traits = traits_def(
        IsolatedFromAbove(),
        NoTerminator(),
        OptionalSymbolOpInterface(),
        SymbolTable(),
    )

    def __init__(
        self,
        ops: Iterable[Operation] | Region,
        attributes: Mapping[str, Attribute] | None = None,
        sym_name: StringAttr | None = None,
    ):
        if attributes is None:
            attributes = {}
        if isinstance(ops, Region):
            region = ops
        else:
            region = Region(Block(ops))
        properties: dict[str, Attribute | None] = {"sym_name": sym_name}
        super().__init__(regions=[region], attributes=attributes, properties=properties)

    @property
    def ops(self) -> BlockOps:
        return self.body.ops

    @classmethod
    def parse(cls, parser: Parser) -> ModuleOp:
        module_name = parser.parse_optional_symbol_name()

        attributes = parser.parse_optional_attr_dict_with_keyword()
        if attributes is not None:
            attributes = attributes.data
        region = parser.parse_region()

        # Add a block if the region is empty
        if not region.blocks:
            region.add_block(Block())

        return ModuleOp(region, attributes, module_name)

    def print(self, printer: Printer) -> None:
        if self.sym_name is not None:
            printer.print_string(" ")
            printer.print_symbol_name(self.sym_name.data)

        if self.attributes:
            printer.print_op_attributes(self.attributes, print_keyword=True)

        if not self.body.block.ops:
            # Do not print the entry block if the region has an empty block
            printer.print_string(" {\n")
            printer.print_string("}")
        else:
            printer.print_string(" ")
            printer.print_region(self.body)

name = 'builtin.module' 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(IsolatedFromAbove(), NoTerminator(), OptionalSymbolOpInterface(), SymbolTable()) class-attribute instance-attribute

ops: BlockOps property

__init__(ops: Iterable[Operation] | Region, attributes: Mapping[str, Attribute] | None = None, sym_name: StringAttr | None = None)

Source code in xdsl/dialects/builtin.py
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
def __init__(
    self,
    ops: Iterable[Operation] | Region,
    attributes: Mapping[str, Attribute] | None = None,
    sym_name: StringAttr | None = None,
):
    if attributes is None:
        attributes = {}
    if isinstance(ops, Region):
        region = ops
    else:
        region = Region(Block(ops))
    properties: dict[str, Attribute | None] = {"sym_name": sym_name}
    super().__init__(regions=[region], attributes=attributes, properties=properties)

parse(parser: Parser) -> ModuleOp classmethod

Source code in xdsl/dialects/builtin.py
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
@classmethod
def parse(cls, parser: Parser) -> ModuleOp:
    module_name = parser.parse_optional_symbol_name()

    attributes = parser.parse_optional_attr_dict_with_keyword()
    if attributes is not None:
        attributes = attributes.data
    region = parser.parse_region()

    # Add a block if the region is empty
    if not region.blocks:
        region.add_block(Block())

    return ModuleOp(region, attributes, module_name)

print(printer: Printer) -> None

Source code in xdsl/dialects/builtin.py
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
def print(self, printer: Printer) -> None:
    if self.sym_name is not None:
        printer.print_string(" ")
        printer.print_symbol_name(self.sym_name.data)

    if self.attributes:
        printer.print_op_attributes(self.attributes, print_keyword=True)

    if not self.body.block.ops:
        # Do not print the entry block if the region has an empty block
        printer.print_string(" {\n")
        printer.print_string("}")
    else:
        printer.print_string(" ")
        printer.print_region(self.body)

NoneType dataclass

Bases: ParametrizedAttribute, BuiltinAttribute, TypeAttribute

Source code in xdsl/dialects/builtin.py
3028
3029
3030
3031
3032
3033
@irdl_attr_definition
class NoneType(ParametrizedAttribute, BuiltinAttribute, TypeAttribute):
    name = "none_type"

    def print_builtin(self, printer: Printer):
        printer.print_string("none")

name = 'none_type' class-attribute instance-attribute

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
3032
3033
def print_builtin(self, printer: Printer):
    printer.print_string("none")

MemRefType

Bases: ParametrizedAttribute, BuiltinAttribute, TypeAttribute, ShapedType, ContainerType[AttributeCovT], Generic[AttributeCovT]

Source code in xdsl/dialects/builtin.py
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
@irdl_attr_definition
class MemRefType(
    ParametrizedAttribute,
    BuiltinAttribute,
    TypeAttribute,
    ShapedType,
    ContainerType[AttributeCovT],
    Generic[AttributeCovT],
):
    name = "memref"

    shape: ArrayAttr[IntAttr]
    element_type: AttributeCovT
    layout: MemRefLayoutAttr | NoneAttr
    memory_space: Attribute

    def __init__(
        self,
        element_type: AttributeCovT,
        shape: ArrayAttr[IntAttr] | Iterable[int | IntAttr],
        layout: MemRefLayoutAttr | NoneAttr = NoneAttr(),
        memory_space: Attribute = NoneAttr(),
    ):
        if not isa(shape, ArrayAttr[IntAttr]):
            shape = ArrayAttr(
                [IntAttr(dim) if isinstance(dim, int) else dim for dim in shape]
            )
        super().__init__(
            shape,
            element_type,
            layout,
            memory_space,
        )

    def get_num_dims(self) -> int:
        return len(self.shape.data)

    def get_shape(self) -> tuple[int, ...]:
        return tuple(i.data for i in self.shape.data)

    def get_element_type(self) -> AttributeCovT:
        return self.element_type

    @classmethod
    def parse_parameters(cls, parser: AttrParser) -> list[Attribute]:
        parser.parse_punctuation("<", " in memref attribute")
        shape = parser.parse_attribute()
        parser.parse_punctuation(",", " between shape and element type parameters")
        type = parser.parse_attribute()
        # If we have a layout or a memory space, parse both of them.
        if parser.parse_optional_punctuation(",") is None:
            parser.parse_punctuation(">", " at end of memref attribute")
            return [shape, type, NoneAttr(), NoneAttr()]
        layout = parser.parse_attribute()
        parser.parse_punctuation(",", " between layout and memory space")
        memory_space = parser.parse_attribute()
        parser.parse_punctuation(">", " at end of memref attribute")

        return [shape, type, layout, memory_space]

    def print_parameters(self, printer: Printer) -> None:
        with printer.in_angle_brackets():
            printer.print_attribute(self.shape)
            printer.print_string(", ")
            printer.print_attribute(self.element_type)
            if self.layout != NoneAttr() or self.memory_space != NoneAttr():
                printer.print_string(", ")
                printer.print_attribute(self.layout)
                printer.print_string(", ")
                printer.print_attribute(self.memory_space)

    def print_builtin(self, printer: Printer):
        printer.print_string("memref")
        with printer.in_angle_brackets():
            if self.shape.data:
                printer.print_dimension_list(self.get_shape())
                printer.print_string("x")
            printer.print_attribute(self.element_type)
            if not isinstance(self.layout, NoneAttr):
                printer.print_string(", ")
                printer.print_attribute(self.layout)
            if not isinstance(self.memory_space, NoneAttr):
                printer.print_string(", ")
                printer.print_attribute(self.memory_space)

    def get_affine_map(self) -> AffineMap:
        """
        Return the affine mapping from the iteration space of this
        memref's layout to the element offset in linear memory.
        """
        if isinstance(self.layout, NoneAttr):
            # empty shape not supported
            if self.get_shape() == ():
                raise DiagnosticException(
                    f"Unsupported empty shape in memref of type {self}"
                )

            strides = self.strides_for_shape(self.get_shape())
            map = StridedLayoutAttr(strides).get_affine_map()
        else:
            map = self.layout.get_affine_map()

        return map

    def get_affine_map_in_bytes(self) -> AffineMap:
        """
        Return the affine mapping from the iteration space of this
        memref's layout to the byte offset in linear memory.

        Unlike the get_affine_map, this function accounts for element width.
        """

        map = self.get_affine_map()

        # account for element width
        assert isinstance(self.element_type, FixedBitwidthType)

        return AffineMap(
            map.num_dims,
            map.num_symbols,
            tuple(result * self.element_type.size for result in map.results),
        )

    def get_strides(self) -> Sequence[int | None] | None:
        """
        Yields the strides of the memref for each dimension.
        The stride of a dimension is the number of elements that are skipped when
        incrementing the corresponding index by one.
        """
        match self.layout:
            case NoneAttr():
                return ShapedType.strides_for_shape(self.get_shape())
            case _:
                return self.layout.get_strides()

    def get_offset(self) -> int | None:
        """
        Return the static offset of the memref layout.

        Returns `0` for the default layout, and `None` when the offset is dynamic or
        when the layout does not expose a strided offset.
        """
        match self.layout:
            case NoneAttr():
                return 0
            case _:
                return self.layout.get_offset()

    @staticmethod
    def constr(
        element_type: IRDLAttrConstraint[AttributeCovT] = AnyAttr(),
        *,
        shape: IRDLAttrConstraint | None = None,
        layout: IRDLAttrConstraint | None = None,
        memory_space: IRDLAttrConstraint | None = None,
    ) -> AttrConstraint[MemRefType[AttributeCovT]]:
        return cast(
            AttrConstraint[MemRefType[AttributeCovT]],
            ParamAttrConstraint.get(
                MemRefType, shape, element_type, layout, memory_space
            ),
        )

name = 'memref' class-attribute instance-attribute

shape: ArrayAttr[IntAttr] instance-attribute

element_type: AttributeCovT instance-attribute

layout: MemRefLayoutAttr | NoneAttr instance-attribute

memory_space: Attribute instance-attribute

__init__(element_type: AttributeCovT, shape: ArrayAttr[IntAttr] | Iterable[int | IntAttr], layout: MemRefLayoutAttr | NoneAttr = NoneAttr(), memory_space: Attribute = NoneAttr())

Source code in xdsl/dialects/builtin.py
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
def __init__(
    self,
    element_type: AttributeCovT,
    shape: ArrayAttr[IntAttr] | Iterable[int | IntAttr],
    layout: MemRefLayoutAttr | NoneAttr = NoneAttr(),
    memory_space: Attribute = NoneAttr(),
):
    if not isa(shape, ArrayAttr[IntAttr]):
        shape = ArrayAttr(
            [IntAttr(dim) if isinstance(dim, int) else dim for dim in shape]
        )
    super().__init__(
        shape,
        element_type,
        layout,
        memory_space,
    )

get_num_dims() -> int

Source code in xdsl/dialects/builtin.py
3070
3071
def get_num_dims(self) -> int:
    return len(self.shape.data)

get_shape() -> tuple[int, ...]

Source code in xdsl/dialects/builtin.py
3073
3074
def get_shape(self) -> tuple[int, ...]:
    return tuple(i.data for i in self.shape.data)

get_element_type() -> AttributeCovT

Source code in xdsl/dialects/builtin.py
3076
3077
def get_element_type(self) -> AttributeCovT:
    return self.element_type

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

Source code in xdsl/dialects/builtin.py
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
@classmethod
def parse_parameters(cls, parser: AttrParser) -> list[Attribute]:
    parser.parse_punctuation("<", " in memref attribute")
    shape = parser.parse_attribute()
    parser.parse_punctuation(",", " between shape and element type parameters")
    type = parser.parse_attribute()
    # If we have a layout or a memory space, parse both of them.
    if parser.parse_optional_punctuation(",") is None:
        parser.parse_punctuation(">", " at end of memref attribute")
        return [shape, type, NoneAttr(), NoneAttr()]
    layout = parser.parse_attribute()
    parser.parse_punctuation(",", " between layout and memory space")
    memory_space = parser.parse_attribute()
    parser.parse_punctuation(">", " at end of memref attribute")

    return [shape, type, layout, memory_space]

print_parameters(printer: Printer) -> None

Source code in xdsl/dialects/builtin.py
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
def print_parameters(self, printer: Printer) -> None:
    with printer.in_angle_brackets():
        printer.print_attribute(self.shape)
        printer.print_string(", ")
        printer.print_attribute(self.element_type)
        if self.layout != NoneAttr() or self.memory_space != NoneAttr():
            printer.print_string(", ")
            printer.print_attribute(self.layout)
            printer.print_string(", ")
            printer.print_attribute(self.memory_space)

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
def print_builtin(self, printer: Printer):
    printer.print_string("memref")
    with printer.in_angle_brackets():
        if self.shape.data:
            printer.print_dimension_list(self.get_shape())
            printer.print_string("x")
        printer.print_attribute(self.element_type)
        if not isinstance(self.layout, NoneAttr):
            printer.print_string(", ")
            printer.print_attribute(self.layout)
        if not isinstance(self.memory_space, NoneAttr):
            printer.print_string(", ")
            printer.print_attribute(self.memory_space)

get_affine_map() -> AffineMap

Return the affine mapping from the iteration space of this memref's layout to the element offset in linear memory.

Source code in xdsl/dialects/builtin.py
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
def get_affine_map(self) -> AffineMap:
    """
    Return the affine mapping from the iteration space of this
    memref's layout to the element offset in linear memory.
    """
    if isinstance(self.layout, NoneAttr):
        # empty shape not supported
        if self.get_shape() == ():
            raise DiagnosticException(
                f"Unsupported empty shape in memref of type {self}"
            )

        strides = self.strides_for_shape(self.get_shape())
        map = StridedLayoutAttr(strides).get_affine_map()
    else:
        map = self.layout.get_affine_map()

    return map

get_affine_map_in_bytes() -> AffineMap

Return the affine mapping from the iteration space of this memref's layout to the byte offset in linear memory.

Unlike the get_affine_map, this function accounts for element width.

Source code in xdsl/dialects/builtin.py
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
def get_affine_map_in_bytes(self) -> AffineMap:
    """
    Return the affine mapping from the iteration space of this
    memref's layout to the byte offset in linear memory.

    Unlike the get_affine_map, this function accounts for element width.
    """

    map = self.get_affine_map()

    # account for element width
    assert isinstance(self.element_type, FixedBitwidthType)

    return AffineMap(
        map.num_dims,
        map.num_symbols,
        tuple(result * self.element_type.size for result in map.results),
    )

get_strides() -> Sequence[int | None] | None

Yields the strides of the memref for each dimension. The stride of a dimension is the number of elements that are skipped when incrementing the corresponding index by one.

Source code in xdsl/dialects/builtin.py
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
def get_strides(self) -> Sequence[int | None] | None:
    """
    Yields the strides of the memref for each dimension.
    The stride of a dimension is the number of elements that are skipped when
    incrementing the corresponding index by one.
    """
    match self.layout:
        case NoneAttr():
            return ShapedType.strides_for_shape(self.get_shape())
        case _:
            return self.layout.get_strides()

get_offset() -> int | None

Return the static offset of the memref layout.

Returns 0 for the default layout, and None when the offset is dynamic or when the layout does not expose a strided offset.

Source code in xdsl/dialects/builtin.py
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
def get_offset(self) -> int | None:
    """
    Return the static offset of the memref layout.

    Returns `0` for the default layout, and `None` when the offset is dynamic or
    when the layout does not expose a strided offset.
    """
    match self.layout:
        case NoneAttr():
            return 0
        case _:
            return self.layout.get_offset()

constr(element_type: IRDLAttrConstraint[AttributeCovT] = AnyAttr(), *, shape: IRDLAttrConstraint | None = None, layout: IRDLAttrConstraint | None = None, memory_space: IRDLAttrConstraint | None = None) -> AttrConstraint[MemRefType[AttributeCovT]] staticmethod

Source code in xdsl/dialects/builtin.py
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
@staticmethod
def constr(
    element_type: IRDLAttrConstraint[AttributeCovT] = AnyAttr(),
    *,
    shape: IRDLAttrConstraint | None = None,
    layout: IRDLAttrConstraint | None = None,
    memory_space: IRDLAttrConstraint | None = None,
) -> AttrConstraint[MemRefType[AttributeCovT]]:
    return cast(
        AttrConstraint[MemRefType[AttributeCovT]],
        ParamAttrConstraint.get(
            MemRefType, shape, element_type, layout, memory_space
        ),
    )

UnrankedMemRefType dataclass

Bases: ParametrizedAttribute, BuiltinAttribute, TypeAttribute, ContainerType[AttributeCovT], Generic[AttributeCovT]

Source code in xdsl/dialects/builtin.py
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
@irdl_attr_definition
class UnrankedMemRefType(
    ParametrizedAttribute,
    BuiltinAttribute,
    TypeAttribute,
    ContainerType[AttributeCovT],
    Generic[AttributeCovT],
):
    name = "unranked_memref"

    element_type: AttributeCovT
    memory_space: Attribute

    def print_builtin(self, printer: Printer):
        printer.print_string("memref<*x")
        printer.print_attribute(self.element_type)
        if not isinstance(self.memory_space, NoneAttr):
            printer.print_string(", ")
            printer.print_attribute(self.memory_space)
        printer.print_string(">")

    @staticmethod
    def from_type(
        referenced_type: AttributeInvT,
        memory_space: Attribute = NoneAttr(),
    ) -> UnrankedMemRefType[AttributeInvT]:
        return UnrankedMemRefType(referenced_type, memory_space)

    def get_element_type(self) -> AttributeCovT:
        return self.element_type

name = 'unranked_memref' class-attribute instance-attribute

element_type: AttributeCovT instance-attribute

memory_space: Attribute instance-attribute

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
3213
3214
3215
3216
3217
3218
3219
def print_builtin(self, printer: Printer):
    printer.print_string("memref<*x")
    printer.print_attribute(self.element_type)
    if not isinstance(self.memory_space, NoneAttr):
        printer.print_string(", ")
        printer.print_attribute(self.memory_space)
    printer.print_string(">")

from_type(referenced_type: AttributeInvT, memory_space: Attribute = NoneAttr()) -> UnrankedMemRefType[AttributeInvT] staticmethod

Source code in xdsl/dialects/builtin.py
3221
3222
3223
3224
3225
3226
@staticmethod
def from_type(
    referenced_type: AttributeInvT,
    memory_space: Attribute = NoneAttr(),
) -> UnrankedMemRefType[AttributeInvT]:
    return UnrankedMemRefType(referenced_type, memory_space)

get_element_type() -> AttributeCovT

Source code in xdsl/dialects/builtin.py
3228
3229
def get_element_type(self) -> AttributeCovT:
    return self.element_type

DenseIntOrFPElementsAttr dataclass

Bases: TypedAttribute, BuiltinAttribute, ContainerType[_DenseElementCovT], Generic[_DenseElementCovT]

Source code in xdsl/dialects/builtin.py
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
@irdl_attr_definition
class DenseIntOrFPElementsAttr(
    TypedAttribute,
    BuiltinAttribute,
    ContainerType[_DenseElementCovT],
    Generic[_DenseElementCovT],
):
    name = "dense"
    type: RankedStructure[_DenseElementCovT]
    data: BytesAttr

    # The type stores the shape data
    def get_shape(self) -> tuple[int, ...]:
        return self.type.get_shape()

    def get_element_type(self) -> _DenseElementCovT:
        return self.type.get_element_type()

    def __len__(self) -> int:
        return len(self.data.data) // self.type.element_type.compile_time_size

    @property
    def shape_is_complete(self) -> bool:
        shape = self.get_shape()

        n = 1
        for dim in shape:
            if dim < 1:
                # Dimensions need to be greater or equal to one
                return False
            n *= dim

        # Product of dimensions needs to equal length
        return n == len(self)

    def verify(self) -> None:
        # zero rank type should only hold 1 value
        data_len = len(self)
        if not self.type.get_shape() and data_len != 1:
            raise VerifyException(
                f"A zero-rank {self.type.name} can only hold 1 value but {data_len} were given."
            )

    @overload
    @staticmethod
    def from_list(
        type: RankedStructure[_FloatAttrTypeInvT],
        data: Sequence[float],
    ) -> DenseIntOrFPElementsAttr[_FloatAttrTypeInvT]: ...

    @overload
    @staticmethod
    def from_list(
        type: RankedStructure[_IntegerAttrTypeInvT],
        data: Sequence[int],
    ) -> DenseIntOrFPElementsAttr[_IntegerAttrTypeInvT]: ...

    @overload
    @staticmethod
    def from_list(
        type: RankedStructure[ComplexType[_IntegerTypeInvT]],
        data: Sequence[tuple[int, int]],
    ) -> DenseIntOrFPElementsAttr[ComplexType[_IntegerTypeInvT]]: ...

    @overload
    @staticmethod
    def from_list(
        type: RankedStructure[ComplexType[_FloatAttrTypeInvT]],
        data: Sequence[tuple[float, float]],
    ) -> DenseIntOrFPElementsAttr[ComplexType[_FloatAttrTypeInvT]]: ...

    @staticmethod
    def from_list(
        type: (
            RankedStructure[
                AnyFloat
                | IntegerType
                | IndexType
                | ComplexType[IntegerType]
                | ComplexType[AnyFloat]
            ]
        ),
        data: Sequence[int]
        | Sequence[float]
        | Sequence[tuple[int, int]]
        | Sequence[tuple[float, float]],
    ) -> DenseIntOrFPElementsAttr:
        # Normalise ints
        if isinstance(t := type.get_element_type(), IntegerType):
            data = tuple(t.get_normalized_value(x) for x in data)  # pyright: ignore[reportArgumentType]

        b = type.element_type.pack(data)  # pyright: ignore[reportArgumentType]

        # Splat case
        if len(data) == 1 and (p := prod(type.get_shape())) != 1:
            b *= p

        return DenseIntOrFPElementsAttr(type, BytesAttr(b))

    def iter_values(
        self,
    ) -> (
        Iterator[int]
        | Iterator[float]
        | Iterator[tuple[int, int]]
        | Iterator[tuple[float, float]]
    ):
        """
        Return an iterator over all the values of the elements in this DenseIntOrFPElementsAttr
        """
        return self.get_element_type().iter_unpack(self.data.data)

    @overload
    def get_values(
        self: DenseIntOrFPElementsAttr[IntegerType | IndexType],
    ) -> tuple[int, ...]: ...

    @overload
    def get_values(self: DenseIntOrFPElementsAttr[AnyFloat]) -> tuple[float, ...]: ...

    @overload
    def get_values(
        self: DenseIntOrFPElementsAttr[ComplexType[IntegerType]],
    ) -> tuple[tuple[int, int], ...]: ...

    @overload
    def get_values(
        self: DenseIntOrFPElementsAttr[ComplexType[AnyFloat]],
    ) -> tuple[tuple[float, float], ...]: ...

    @overload
    def get_values(
        self,
    ) -> (
        tuple[int, ...]
        | tuple[float, ...]
        | tuple[tuple[int, int], ...]
        | tuple[tuple[float, float], ...]
    ): ...

    def get_values(
        self,
    ) -> (
        tuple[int, ...]
        | tuple[float, ...]
        | tuple[tuple[int, int], ...]
        | tuple[tuple[float, float], ...]
    ):
        """
        Return all the values of the elements in this DenseIntOrFPElementsAttr
        """
        return self.get_element_type().unpack(self.data.data, len(self))

    def iter_attrs(self) -> Iterator[IntegerAttr] | Iterator[FloatAttr]:
        """
        Return an iterator over all elements of the dense attribute in their relevant
        attribute representation (IntegerAttr / FloatAttr)
        """
        if isinstance(eltype := self.get_element_type(), IntegerType | IndexType):
            return IntegerAttr.iter_unpack(eltype, self.data.data)
        elif isinstance(eltype, AnyFloat):
            return FloatAttr.iter_unpack(eltype, self.data.data)
        raise NotImplementedError()

    def get_attrs(self) -> Sequence[IntegerAttr] | Sequence[FloatAttr]:
        """
        Return all elements of the dense attribute in their relevant
        attribute representation (IntegerAttr / FloatAttr)
        """
        if isinstance(eltype := self.get_element_type(), IntegerType | IndexType):
            return IntegerAttr.unpack(eltype, self.data.data, len(self))
        elif isinstance(eltype, AnyFloat):
            return FloatAttr.unpack(eltype, self.data.data, len(self))
        raise NotImplementedError()

    def is_splat(self) -> bool:
        """
        Return whether or not this dense attribute is defined entirely
        by a single value (splat).
        """
        values = self.get_values()
        return values.count(values[0]) == len(values)

    @staticmethod
    def parse_with_type(parser: AttrParser, type: Attribute) -> TypedAttribute:
        assert isa(type, RankedStructure[AnyDenseElement])
        return parser.parse_dense_int_or_fp_elements_attr(type)

    def _print_one_elem(
        self, val: float | tuple[int, int] | tuple[float, float], printer: Printer
    ):
        if isinstance(val, int):
            element_type = self.get_element_type()
            assert isinstance(element_type, IntegerType | IndexType)
            printer.print_int(val, element_type)
        elif isinstance(val, float):
            element_type = self.get_element_type()
            assert isinstance(element_type, AnyFloat)
            printer.print_float(val, element_type)
        else:  # complex
            element_type = self.get_element_type()
            assert isinstance(element_type, ComplexType)
            printer.print_complex(val, element_type)

    def _print_dense_list(
        self,
        array: Sequence[int]
        | Sequence[float]
        | Sequence[tuple[int, int]]
        | Sequence[tuple[float, float]],
        shape: Sequence[int],
        printer: Printer,
    ):
        printer.print_string("[")
        if len(shape) > 1:
            k = len(array) // shape[0]
            printer.print_list(
                (array[i : i + k] for i in range(0, len(array), k)),
                lambda subarray: self._print_dense_list(subarray, shape[1:], printer),
            )
        else:
            printer.print_list(
                array,
                lambda val: self._print_one_elem(val, printer),
            )
        printer.print_string("]")

    def print_without_type(self, printer: Printer):
        printer.print_string("dense")
        length = len(self)
        data = self.get_values()
        shape = self.get_shape() if self.shape_is_complete else (length,)
        assert shape is not None, "If shape is complete, then it cannot be None"
        with printer.in_angle_brackets():
            if length == 0:
                pass
            elif self.is_splat():
                self._print_one_elem(data[0], printer)
            elif length > 100:
                printer.print_string(f'"0x{self.data.data.hex().upper()}"')
            else:
                self._print_dense_list(data, shape, printer)

    def print_builtin(self, printer: Printer):
        self.print_without_type(printer)
        printer.print_string(" : ")
        printer.print_attribute(self.get_type())

name = 'dense' class-attribute instance-attribute

type: RankedStructure[_DenseElementCovT] instance-attribute

data: BytesAttr instance-attribute

shape_is_complete: bool property

get_shape() -> tuple[int, ...]

Source code in xdsl/dialects/builtin.py
3256
3257
def get_shape(self) -> tuple[int, ...]:
    return self.type.get_shape()

get_element_type() -> _DenseElementCovT

Source code in xdsl/dialects/builtin.py
3259
3260
def get_element_type(self) -> _DenseElementCovT:
    return self.type.get_element_type()

__len__() -> int

Source code in xdsl/dialects/builtin.py
3262
3263
def __len__(self) -> int:
    return len(self.data.data) // self.type.element_type.compile_time_size

verify() -> None

Source code in xdsl/dialects/builtin.py
3279
3280
3281
3282
3283
3284
3285
def verify(self) -> None:
    # zero rank type should only hold 1 value
    data_len = len(self)
    if not self.type.get_shape() and data_len != 1:
        raise VerifyException(
            f"A zero-rank {self.type.name} can only hold 1 value but {data_len} were given."
        )

from_list(type: RankedStructure[AnyFloat | IntegerType | IndexType | ComplexType[IntegerType] | ComplexType[AnyFloat]], data: Sequence[int] | Sequence[float] | Sequence[tuple[int, int]] | Sequence[tuple[float, float]]) -> DenseIntOrFPElementsAttr staticmethod

from_list(
    type: RankedStructure[_FloatAttrTypeInvT],
    data: Sequence[float],
) -> DenseIntOrFPElementsAttr[_FloatAttrTypeInvT]
from_list(
    type: RankedStructure[_IntegerAttrTypeInvT],
    data: Sequence[int],
) -> DenseIntOrFPElementsAttr[_IntegerAttrTypeInvT]
from_list(
    type: RankedStructure[ComplexType[_IntegerTypeInvT]],
    data: Sequence[tuple[int, int]],
) -> DenseIntOrFPElementsAttr[
    ComplexType[_IntegerTypeInvT]
]
from_list(
    type: RankedStructure[ComplexType[_FloatAttrTypeInvT]],
    data: Sequence[tuple[float, float]],
) -> DenseIntOrFPElementsAttr[
    ComplexType[_FloatAttrTypeInvT]
]
Source code in xdsl/dialects/builtin.py
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
@staticmethod
def from_list(
    type: (
        RankedStructure[
            AnyFloat
            | IntegerType
            | IndexType
            | ComplexType[IntegerType]
            | ComplexType[AnyFloat]
        ]
    ),
    data: Sequence[int]
    | Sequence[float]
    | Sequence[tuple[int, int]]
    | Sequence[tuple[float, float]],
) -> DenseIntOrFPElementsAttr:
    # Normalise ints
    if isinstance(t := type.get_element_type(), IntegerType):
        data = tuple(t.get_normalized_value(x) for x in data)  # pyright: ignore[reportArgumentType]

    b = type.element_type.pack(data)  # pyright: ignore[reportArgumentType]

    # Splat case
    if len(data) == 1 and (p := prod(type.get_shape())) != 1:
        b *= p

    return DenseIntOrFPElementsAttr(type, BytesAttr(b))

iter_values() -> Iterator[int] | Iterator[float] | Iterator[tuple[int, int]] | Iterator[tuple[float, float]]

Return an iterator over all the values of the elements in this DenseIntOrFPElementsAttr

Source code in xdsl/dialects/builtin.py
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
def iter_values(
    self,
) -> (
    Iterator[int]
    | Iterator[float]
    | Iterator[tuple[int, int]]
    | Iterator[tuple[float, float]]
):
    """
    Return an iterator over all the values of the elements in this DenseIntOrFPElementsAttr
    """
    return self.get_element_type().iter_unpack(self.data.data)

get_values() -> tuple[int, ...] | tuple[float, ...] | tuple[tuple[int, int], ...] | tuple[tuple[float, float], ...]

get_values() -> tuple[int, ...]
get_values() -> tuple[float, ...]
get_values() -> tuple[tuple[int, int], ...]
get_values() -> tuple[tuple[float, float], ...]
get_values() -> (
    tuple[int, ...]
    | tuple[float, ...]
    | tuple[tuple[int, int], ...]
    | tuple[tuple[float, float], ...]
)

Return all the values of the elements in this DenseIntOrFPElementsAttr

Source code in xdsl/dialects/builtin.py
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
def get_values(
    self,
) -> (
    tuple[int, ...]
    | tuple[float, ...]
    | tuple[tuple[int, int], ...]
    | tuple[tuple[float, float], ...]
):
    """
    Return all the values of the elements in this DenseIntOrFPElementsAttr
    """
    return self.get_element_type().unpack(self.data.data, len(self))

iter_attrs() -> Iterator[IntegerAttr] | Iterator[FloatAttr]

Return an iterator over all elements of the dense attribute in their relevant attribute representation (IntegerAttr / FloatAttr)

Source code in xdsl/dialects/builtin.py
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
def iter_attrs(self) -> Iterator[IntegerAttr] | Iterator[FloatAttr]:
    """
    Return an iterator over all elements of the dense attribute in their relevant
    attribute representation (IntegerAttr / FloatAttr)
    """
    if isinstance(eltype := self.get_element_type(), IntegerType | IndexType):
        return IntegerAttr.iter_unpack(eltype, self.data.data)
    elif isinstance(eltype, AnyFloat):
        return FloatAttr.iter_unpack(eltype, self.data.data)
    raise NotImplementedError()

get_attrs() -> Sequence[IntegerAttr] | Sequence[FloatAttr]

Return all elements of the dense attribute in their relevant attribute representation (IntegerAttr / FloatAttr)

Source code in xdsl/dialects/builtin.py
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
def get_attrs(self) -> Sequence[IntegerAttr] | Sequence[FloatAttr]:
    """
    Return all elements of the dense attribute in their relevant
    attribute representation (IntegerAttr / FloatAttr)
    """
    if isinstance(eltype := self.get_element_type(), IntegerType | IndexType):
        return IntegerAttr.unpack(eltype, self.data.data, len(self))
    elif isinstance(eltype, AnyFloat):
        return FloatAttr.unpack(eltype, self.data.data, len(self))
    raise NotImplementedError()

is_splat() -> bool

Return whether or not this dense attribute is defined entirely by a single value (splat).

Source code in xdsl/dialects/builtin.py
3419
3420
3421
3422
3423
3424
3425
def is_splat(self) -> bool:
    """
    Return whether or not this dense attribute is defined entirely
    by a single value (splat).
    """
    values = self.get_values()
    return values.count(values[0]) == len(values)

parse_with_type(parser: AttrParser, type: Attribute) -> TypedAttribute staticmethod

Source code in xdsl/dialects/builtin.py
3427
3428
3429
3430
@staticmethod
def parse_with_type(parser: AttrParser, type: Attribute) -> TypedAttribute:
    assert isa(type, RankedStructure[AnyDenseElement])
    return parser.parse_dense_int_or_fp_elements_attr(type)

print_without_type(printer: Printer)

Source code in xdsl/dialects/builtin.py
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
def print_without_type(self, printer: Printer):
    printer.print_string("dense")
    length = len(self)
    data = self.get_values()
    shape = self.get_shape() if self.shape_is_complete else (length,)
    assert shape is not None, "If shape is complete, then it cannot be None"
    with printer.in_angle_brackets():
        if length == 0:
            pass
        elif self.is_splat():
            self._print_one_elem(data[0], printer)
        elif length > 100:
            printer.print_string(f'"0x{self.data.data.hex().upper()}"')
        else:
            self._print_dense_list(data, shape, printer)

print_builtin(printer: Printer)

Source code in xdsl/dialects/builtin.py
3487
3488
3489
3490
def print_builtin(self, printer: Printer):
    self.print_without_type(printer)
    printer.print_string(" : ")
    printer.print_attribute(self.get_type())

container_of(constr: IRDLAttrConstraint[AttributeInvT]) -> AttrConstraint[AttributeInvT | VectorType[AttributeInvT] | TensorType[AttributeInvT]]

Source code in xdsl/dialects/builtin.py
2250
2251
2252
2253
2254
2255
def container_of(
    constr: IRDLAttrConstraint[AttributeInvT],
) -> AttrConstraint[
    AttributeInvT | VectorType[AttributeInvT] | TensorType[AttributeInvT]
]:
    return AnyOf.get(constr, VectorType.constr(constr), TensorType.constr(constr))

ContainerOf(constr: IRDLAttrConstraint[AttributeInvT])

Source code in xdsl/dialects/builtin.py
2258
2259
2260
2261
2262
@deprecated("Please use `container_of` instead")
def ContainerOf(
    constr: IRDLAttrConstraint[AttributeInvT],
):
    container_of(constr)