Skip to content

Memref

memref

MemRef = Dialect('memref', [LoadOp, StoreOp, AllocOp, AllocaOp, AssumeAlignmentOp, AllocaScopeOp, AllocaScopeReturnOp, AtomicRMWOp, CopyOp, CollapseShapeOp, ExpandShapeOp, DeallocOp, GetGlobalOp, GlobalOp, DimOp, ExtractStridedMetaDataOp, ExtractAlignedPointerAsIndexOp, SubviewOp, ViewOp, CastOp, MemorySpaceCastOp, ReinterpretCastOp, DmaStartOp, DmaWaitOp, RankOp], []) module-attribute

LoadOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class LoadOp(IRDLOperation):
    name = "memref.load"

    T: ClassVar = VarConstraint("T", AnyAttr())

    nontemporal = opt_prop_def(BoolAttr, default_value=BoolAttr.from_bool(False))

    memref = operand_def(MemRefType.constr(T))
    indices = var_operand_def(IndexType())
    res = result_def(T)

    traits = traits_def(MemoryReadEffect())

    irdl_options = (ParsePropInAttrDict(),)
    assembly_format = "$memref `[` $indices `]` attr-dict `:` type($memref)"

    # TODO varargs for indexing, which must match the memref dimensions
    # Problem: memref dimensions require variadic type parameters,
    # which is subject to change

    def verify_(self):
        memref_type = self.memref.type
        if not isinstance(memref_type, MemRefType):
            raise VerifyException("expected a memreftype")

        memref_type = cast(MemRefType, memref_type)

        if memref_type.get_num_dims() != len(self.indices):
            raise Exception("expected an index for each dimension")

    @classmethod
    def get(
        cls, ref: SSAValue | Operation, indices: Sequence[SSAValue | Operation]
    ) -> Self:
        ssa_value = SSAValue.get(ref, type=MemRefType)
        return cls(operands=[ref, indices], result_types=[ssa_value.type.element_type])

name = 'memref.load' class-attribute instance-attribute

T: ClassVar = VarConstraint('T', AnyAttr()) class-attribute instance-attribute

nontemporal = opt_prop_def(BoolAttr, default_value=BoolAttr.from_bool(False)) class-attribute instance-attribute

memref = operand_def(MemRefType.constr(T)) class-attribute instance-attribute

indices = var_operand_def(IndexType()) class-attribute instance-attribute

res = result_def(T) class-attribute instance-attribute

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

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

assembly_format = '$memref `[` $indices `]` attr-dict `:` type($memref)' class-attribute instance-attribute

verify_()

Source code in xdsl/dialects/memref.py
def verify_(self):
    memref_type = self.memref.type
    if not isinstance(memref_type, MemRefType):
        raise VerifyException("expected a memreftype")

    memref_type = cast(MemRefType, memref_type)

    if memref_type.get_num_dims() != len(self.indices):
        raise Exception("expected an index for each dimension")

get(ref: SSAValue | Operation, indices: Sequence[SSAValue | Operation]) -> Self classmethod

Source code in xdsl/dialects/memref.py
@classmethod
def get(
    cls, ref: SSAValue | Operation, indices: Sequence[SSAValue | Operation]
) -> Self:
    ssa_value = SSAValue.get(ref, type=MemRefType)
    return cls(operands=[ref, indices], result_types=[ssa_value.type.element_type])

StoreOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class StoreOp(IRDLOperation):
    T: ClassVar = VarConstraint("T", AnyAttr())

    name = "memref.store"

    nontemporal = opt_prop_def(BoolAttr, default_value=BoolAttr.from_bool(False))

    value = operand_def(T)
    memref = operand_def(MemRefType.constr(T))
    indices = var_operand_def(IndexType())

    traits = traits_def(MemoryWriteEffect())

    irdl_options = (ParsePropInAttrDict(),)
    assembly_format = "$value `,` $memref `[` $indices `]` attr-dict `:` type($memref)"

    def verify_(self):
        if not isinstance(memref_type := self.memref.type, MemRefType):
            raise VerifyException("expected a memreftype")

        memref_type = cast(MemRefType, memref_type)

        if memref_type.get_num_dims() != len(self.indices):
            raise Exception("Expected an index for each dimension")

    @classmethod
    def get(
        cls,
        value: Operation | SSAValue,
        ref: Operation | SSAValue,
        indices: Sequence[Operation | SSAValue],
    ) -> Self:
        return cls(operands=[value, ref, indices])

T: ClassVar = VarConstraint('T', AnyAttr()) class-attribute instance-attribute

name = 'memref.store' class-attribute instance-attribute

nontemporal = opt_prop_def(BoolAttr, default_value=BoolAttr.from_bool(False)) class-attribute instance-attribute

value = operand_def(T) class-attribute instance-attribute

memref = operand_def(MemRefType.constr(T)) class-attribute instance-attribute

indices = var_operand_def(IndexType()) class-attribute instance-attribute

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

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

assembly_format = '$value `,` $memref `[` $indices `]` attr-dict `:` type($memref)' class-attribute instance-attribute

verify_()

Source code in xdsl/dialects/memref.py
def verify_(self):
    if not isinstance(memref_type := self.memref.type, MemRefType):
        raise VerifyException("expected a memreftype")

    memref_type = cast(MemRefType, memref_type)

    if memref_type.get_num_dims() != len(self.indices):
        raise Exception("Expected an index for each dimension")

get(value: Operation | SSAValue, ref: Operation | SSAValue, indices: Sequence[Operation | SSAValue]) -> Self classmethod

Source code in xdsl/dialects/memref.py
@classmethod
def get(
    cls,
    value: Operation | SSAValue,
    ref: Operation | SSAValue,
    indices: Sequence[Operation | SSAValue],
) -> Self:
    return cls(operands=[value, ref, indices])

AllocOpHasCanonicalizationPatterns dataclass

Bases: HasCanonicalizationPatternsTrait

Source code in xdsl/dialects/memref.py
class AllocOpHasCanonicalizationPatterns(HasCanonicalizationPatternsTrait):
    @classmethod
    def get_canonicalization_patterns(cls) -> tuple[RewritePattern, ...]:
        from xdsl.transforms.canonicalization_patterns.memref import ElideUnusedAlloc

        return (ElideUnusedAlloc(),)

get_canonicalization_patterns() -> tuple[RewritePattern, ...] classmethod

Source code in xdsl/dialects/memref.py
@classmethod
def get_canonicalization_patterns(cls) -> tuple[RewritePattern, ...]:
    from xdsl.transforms.canonicalization_patterns.memref import ElideUnusedAlloc

    return (ElideUnusedAlloc(),)

AllocOp

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class AllocOp(IRDLOperation):
    name = "memref.alloc"

    dynamic_sizes = var_operand_def(IndexType)
    symbol_operands = var_operand_def(IndexType)

    memref = result_def(MemRefType)

    # TODO how to constraint the IntegerAttr type?
    alignment = opt_prop_def(IntegerAttr)

    irdl_options = (AttrSizedOperandSegments(as_property=True),)

    traits = traits_def(AllocOpHasCanonicalizationPatterns(), MemoryAllocEffect())

    def __init__(
        self,
        dynamic_sizes: Sequence[SSAValue],
        symbol_operands: Sequence[SSAValue],
        result_type: Attribute,
        alignment: Attribute | None = None,
    ):
        super().__init__(
            operands=(dynamic_sizes, symbol_operands),
            result_types=(result_type,),
            properties={"alignment": alignment},
        )

    @classmethod
    def get(
        cls,
        return_type: Attribute,
        alignment: int | IntegerAttr | None = None,
        shape: Iterable[int | IntAttr] | None = None,
        dynamic_sizes: Sequence[SSAValue | Operation] | None = None,
        layout: MemRefLayoutAttr | NoneAttr = NoneAttr(),
        memory_space: Attribute = NoneAttr(),
    ) -> Self:
        if shape is None:
            shape = [1]

        if dynamic_sizes is None:
            dynamic_sizes = []

        if isinstance(alignment, int):
            alignment = IntegerAttr(alignment, 64)

        return cls(
            tuple(SSAValue.get(ds) for ds in dynamic_sizes),
            (),
            MemRefType(return_type, shape, layout, memory_space),
            alignment,
        )

    def verify_(self) -> None:
        memref_type = self.memref.type

        dyn_dims = [x for x in memref_type.shape.data if x.data == DYNAMIC_INDEX]
        if len(dyn_dims) != len(self.dynamic_sizes):
            raise VerifyException(
                "op dimension operand count does not equal memref dynamic dimension count."
            )
        _verify_memref_alloc_alignment(self.alignment)

    def print(self, printer: Printer):
        printer.print_string("(")
        printer.print_list(self.dynamic_sizes, printer.print_ssa_value)
        printer.print_string(")")
        if self.symbol_operands:
            printer.print_string("[")
            printer.print_list(self.symbol_operands, printer.print_ssa_value)
            printer.print_string("]")

        printer.print_op_attributes(
            self.properties | self.attributes,
            print_keyword=False,
            reserved_attr_names="operandSegmentSizes",
        )

        printer.print_string(" : ")
        printer.print_attribute(self.memref.type)

    @classmethod
    def parse(cls, parser: Parser) -> Self:
        #  %alloc = memref.alloc(%a)[%s] {alignment = 64 : i64} : memref<3x2xf32>

        unresolved_dynamic_sizes = parser.parse_comma_separated_list(
            parser.Delimiter.PAREN, parser.parse_unresolved_operand
        )
        unresolved_symbol_operands = parser.parse_optional_comma_separated_list(
            parser.Delimiter.SQUARE, parser.parse_unresolved_operand
        )
        if unresolved_symbol_operands is None:
            unresolved_symbol_operands = []

        attrs = parser.parse_optional_attr_dict()

        parser.parse_punctuation(":")
        res_type = parser.parse_attribute()

        index = IndexType()
        dynamic_sizes = tuple(
            parser.resolve_operand(uop, index) for uop in unresolved_dynamic_sizes
        )
        symbol_operands = tuple(
            parser.resolve_operand(uop, index) for uop in unresolved_symbol_operands
        )

        if "alignment" in attrs:
            alignment = attrs["alignment"]
            del attrs["alignment"]
        else:
            alignment = None

        op = cls(
            dynamic_sizes,
            symbol_operands,
            res_type,
            alignment,
        )

        op.attributes |= attrs

        return op

name = 'memref.alloc' class-attribute instance-attribute

dynamic_sizes = var_operand_def(IndexType) class-attribute instance-attribute

symbol_operands = var_operand_def(IndexType) class-attribute instance-attribute

memref = result_def(MemRefType) class-attribute instance-attribute

alignment = opt_prop_def(IntegerAttr) class-attribute instance-attribute

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

traits = traits_def(AllocOpHasCanonicalizationPatterns(), MemoryAllocEffect()) class-attribute instance-attribute

__init__(dynamic_sizes: Sequence[SSAValue], symbol_operands: Sequence[SSAValue], result_type: Attribute, alignment: Attribute | None = None)

Source code in xdsl/dialects/memref.py
def __init__(
    self,
    dynamic_sizes: Sequence[SSAValue],
    symbol_operands: Sequence[SSAValue],
    result_type: Attribute,
    alignment: Attribute | None = None,
):
    super().__init__(
        operands=(dynamic_sizes, symbol_operands),
        result_types=(result_type,),
        properties={"alignment": alignment},
    )

get(return_type: Attribute, alignment: int | IntegerAttr | None = None, shape: Iterable[int | IntAttr] | None = None, dynamic_sizes: Sequence[SSAValue | Operation] | None = None, layout: MemRefLayoutAttr | NoneAttr = NoneAttr(), memory_space: Attribute = NoneAttr()) -> Self classmethod

Source code in xdsl/dialects/memref.py
@classmethod
def get(
    cls,
    return_type: Attribute,
    alignment: int | IntegerAttr | None = None,
    shape: Iterable[int | IntAttr] | None = None,
    dynamic_sizes: Sequence[SSAValue | Operation] | None = None,
    layout: MemRefLayoutAttr | NoneAttr = NoneAttr(),
    memory_space: Attribute = NoneAttr(),
) -> Self:
    if shape is None:
        shape = [1]

    if dynamic_sizes is None:
        dynamic_sizes = []

    if isinstance(alignment, int):
        alignment = IntegerAttr(alignment, 64)

    return cls(
        tuple(SSAValue.get(ds) for ds in dynamic_sizes),
        (),
        MemRefType(return_type, shape, layout, memory_space),
        alignment,
    )

verify_() -> None

Source code in xdsl/dialects/memref.py
def verify_(self) -> None:
    memref_type = self.memref.type

    dyn_dims = [x for x in memref_type.shape.data if x.data == DYNAMIC_INDEX]
    if len(dyn_dims) != len(self.dynamic_sizes):
        raise VerifyException(
            "op dimension operand count does not equal memref dynamic dimension count."
        )
    _verify_memref_alloc_alignment(self.alignment)

print(printer: Printer)

Source code in xdsl/dialects/memref.py
def print(self, printer: Printer):
    printer.print_string("(")
    printer.print_list(self.dynamic_sizes, printer.print_ssa_value)
    printer.print_string(")")
    if self.symbol_operands:
        printer.print_string("[")
        printer.print_list(self.symbol_operands, printer.print_ssa_value)
        printer.print_string("]")

    printer.print_op_attributes(
        self.properties | self.attributes,
        print_keyword=False,
        reserved_attr_names="operandSegmentSizes",
    )

    printer.print_string(" : ")
    printer.print_attribute(self.memref.type)

parse(parser: Parser) -> Self classmethod

Source code in xdsl/dialects/memref.py
@classmethod
def parse(cls, parser: Parser) -> Self:
    #  %alloc = memref.alloc(%a)[%s] {alignment = 64 : i64} : memref<3x2xf32>

    unresolved_dynamic_sizes = parser.parse_comma_separated_list(
        parser.Delimiter.PAREN, parser.parse_unresolved_operand
    )
    unresolved_symbol_operands = parser.parse_optional_comma_separated_list(
        parser.Delimiter.SQUARE, parser.parse_unresolved_operand
    )
    if unresolved_symbol_operands is None:
        unresolved_symbol_operands = []

    attrs = parser.parse_optional_attr_dict()

    parser.parse_punctuation(":")
    res_type = parser.parse_attribute()

    index = IndexType()
    dynamic_sizes = tuple(
        parser.resolve_operand(uop, index) for uop in unresolved_dynamic_sizes
    )
    symbol_operands = tuple(
        parser.resolve_operand(uop, index) for uop in unresolved_symbol_operands
    )

    if "alignment" in attrs:
        alignment = attrs["alignment"]
        del attrs["alignment"]
    else:
        alignment = None

    op = cls(
        dynamic_sizes,
        symbol_operands,
        res_type,
        alignment,
    )

    op.attributes |= attrs

    return op

AllocaScopeOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class AllocaScopeOp(IRDLOperation):
    name = "memref.alloca_scope"

    res = var_result_def()

    scope = region_def()

    traits = lazy_traits_def(
        lambda: (
            SingleBlockImplicitTerminator(AllocaScopeReturnOp),
            RecursiveMemoryEffect(),
        )
    )

    @classmethod
    def parse(cls, parser: Parser) -> Self:
        result_types: Sequence[Attribute] = ()
        if parser.parse_optional_punctuation("->"):
            types = parser.parse_optional_comma_separated_list(
                parser.Delimiter.PAREN, parser.parse_type
            )
            result_types = [parser.parse_type()] if types is None else types
        region = parser.parse_region()
        attrs = parser.parse_optional_attr_dict()
        op = cls(result_types=(result_types,), regions=(region,), attributes=attrs)
        for trait in op.get_traits_of_type(SingleBlockImplicitTerminator):
            ensure_terminator(op, trait)
        return op

    def print(self, printer: Printer):
        if self.res:
            printer.print_string(" -> (")
            printer.print_list(self.res.types, printer.print_attribute)
            printer.print_string(")")
        printer.print_string(" ")
        printer.print_region(
            self.scope,
            print_entry_block_args=False,
            print_block_terminators=bool(self.res),
        )
        printer.print_op_attributes(self.attributes)

name = 'memref.alloca_scope' class-attribute instance-attribute

res = var_result_def() class-attribute instance-attribute

scope = region_def() class-attribute instance-attribute

traits = lazy_traits_def(lambda: (SingleBlockImplicitTerminator(AllocaScopeReturnOp), RecursiveMemoryEffect())) class-attribute instance-attribute

parse(parser: Parser) -> Self classmethod

Source code in xdsl/dialects/memref.py
@classmethod
def parse(cls, parser: Parser) -> Self:
    result_types: Sequence[Attribute] = ()
    if parser.parse_optional_punctuation("->"):
        types = parser.parse_optional_comma_separated_list(
            parser.Delimiter.PAREN, parser.parse_type
        )
        result_types = [parser.parse_type()] if types is None else types
    region = parser.parse_region()
    attrs = parser.parse_optional_attr_dict()
    op = cls(result_types=(result_types,), regions=(region,), attributes=attrs)
    for trait in op.get_traits_of_type(SingleBlockImplicitTerminator):
        ensure_terminator(op, trait)
    return op

print(printer: Printer)

Source code in xdsl/dialects/memref.py
def print(self, printer: Printer):
    if self.res:
        printer.print_string(" -> (")
        printer.print_list(self.res.types, printer.print_attribute)
        printer.print_string(")")
    printer.print_string(" ")
    printer.print_region(
        self.scope,
        print_entry_block_args=False,
        print_block_terminators=bool(self.res),
    )
    printer.print_op_attributes(self.attributes)

AllocaScopeReturnOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class AllocaScopeReturnOp(IRDLOperation):
    name = "memref.alloca_scope.return"

    ops = var_operand_def()

    traits = traits_def(IsTerminator(), HasParent(AllocaScopeOp))
    assembly_format = "attr-dict ($ops^ `:` type($ops))?"

    def verify_(self) -> None:
        parent = cast(AllocaScopeOp, self.parent_op())
        if self.ops.types != parent.result_types:
            raise VerifyException(
                "Expected operand types to match parent's return types."
            )

name = 'memref.alloca_scope.return' class-attribute instance-attribute

ops = var_operand_def() class-attribute instance-attribute

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

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

verify_() -> None

Source code in xdsl/dialects/memref.py
def verify_(self) -> None:
    parent = cast(AllocaScopeOp, self.parent_op())
    if self.ops.types != parent.result_types:
        raise VerifyException(
            "Expected operand types to match parent's return types."
        )

AllocaOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class AllocaOp(IRDLOperation):
    name = "memref.alloca"

    dynamic_sizes = var_operand_def(IndexType)
    symbol_operands = var_operand_def(IndexType)

    memref = result_def(MemRefType)

    # TODO how to constraint the IntegerAttr type?
    alignment = opt_prop_def(IntegerAttr)

    traits = traits_def(MemoryAllocEffect())

    irdl_options = (AttrSizedOperandSegments(as_property=True), ParsePropInAttrDict())

    assembly_format = """
    `(`$dynamic_sizes`)` (`` `[` $symbol_operands^ `]`)? attr-dict `:` type($memref)
    """

    @staticmethod
    def get(
        return_type: Attribute,
        alignment: int | IntegerAttr | None = None,
        shape: Iterable[int | IntAttr] | None = None,
        dynamic_sizes: Sequence[SSAValue | Operation] | None = None,
        layout: MemRefLayoutAttr | NoneAttr = NoneAttr(),
        memory_space: Attribute = NoneAttr(),
    ) -> AllocaOp:
        if shape is None:
            shape = [1]

        if dynamic_sizes is None:
            dynamic_sizes = []

        if isinstance(alignment, int):
            alignment = IntegerAttr(alignment, 64)

        return AllocaOp.build(
            operands=[dynamic_sizes, []],
            result_types=[MemRefType(return_type, shape, layout, memory_space)],
            properties={
                "alignment": alignment,
            },
        )

    def verify_(self) -> None:
        memref_type = self.memref.type

        dyn_dims = [x for x in memref_type.shape.data if x.data == DYNAMIC_INDEX]
        if len(dyn_dims) != len(self.dynamic_sizes):
            raise VerifyException(
                "op dimension operand count does not equal memref dynamic dimension count."
            )
        _verify_memref_alloc_alignment(self.alignment)

name = 'memref.alloca' class-attribute instance-attribute

dynamic_sizes = var_operand_def(IndexType) class-attribute instance-attribute

symbol_operands = var_operand_def(IndexType) class-attribute instance-attribute

memref = result_def(MemRefType) class-attribute instance-attribute

alignment = opt_prop_def(IntegerAttr) class-attribute instance-attribute

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

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

assembly_format = '\n `(`$dynamic_sizes`)` (`` `[` $symbol_operands^ `]`)? attr-dict `:` type($memref)\n ' class-attribute instance-attribute

get(return_type: Attribute, alignment: int | IntegerAttr | None = None, shape: Iterable[int | IntAttr] | None = None, dynamic_sizes: Sequence[SSAValue | Operation] | None = None, layout: MemRefLayoutAttr | NoneAttr = NoneAttr(), memory_space: Attribute = NoneAttr()) -> AllocaOp staticmethod

Source code in xdsl/dialects/memref.py
@staticmethod
def get(
    return_type: Attribute,
    alignment: int | IntegerAttr | None = None,
    shape: Iterable[int | IntAttr] | None = None,
    dynamic_sizes: Sequence[SSAValue | Operation] | None = None,
    layout: MemRefLayoutAttr | NoneAttr = NoneAttr(),
    memory_space: Attribute = NoneAttr(),
) -> AllocaOp:
    if shape is None:
        shape = [1]

    if dynamic_sizes is None:
        dynamic_sizes = []

    if isinstance(alignment, int):
        alignment = IntegerAttr(alignment, 64)

    return AllocaOp.build(
        operands=[dynamic_sizes, []],
        result_types=[MemRefType(return_type, shape, layout, memory_space)],
        properties={
            "alignment": alignment,
        },
    )

verify_() -> None

Source code in xdsl/dialects/memref.py
def verify_(self) -> None:
    memref_type = self.memref.type

    dyn_dims = [x for x in memref_type.shape.data if x.data == DYNAMIC_INDEX]
    if len(dyn_dims) != len(self.dynamic_sizes):
        raise VerifyException(
            "op dimension operand count does not equal memref dynamic dimension count."
        )
    _verify_memref_alloc_alignment(self.alignment)

AssumeAlignmentOp

Bases: IRDLOperation

Assert that a memref has the given byte alignment.

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class AssumeAlignmentOp(IRDLOperation):
    """Assert that a memref has the given byte alignment."""

    name = "memref.assume_alignment"

    T: ClassVar = VarConstraint("T", base(MemRefType))

    memref = operand_def(T)
    alignment = prop_def(IntegerAttr[I32])
    result = result_def(T)

    traits = traits_def(Pure(), SameOperandsAndResultType())

    assembly_format = "$memref `,` $alignment attr-dict `:` type($memref)"

    def __init__(
        self,
        memref: SSAValue | Operation,
        alignment: int | IntegerAttr[I32],
    ) -> None:
        memref = SSAValue.get(memref)
        if isinstance(alignment, int):
            alignment = IntegerAttr(alignment, i32)
        super().__init__(
            operands=[memref],
            result_types=[memref.type],
            properties={"alignment": alignment},
        )

    def verify_(self) -> None:
        alignment = self.alignment.value.data
        if alignment <= 0:
            raise VerifyException(f"Alignment must be positive, got {alignment}")

name = 'memref.assume_alignment' class-attribute instance-attribute

T: ClassVar = VarConstraint('T', base(MemRefType)) class-attribute instance-attribute

memref = operand_def(T) class-attribute instance-attribute

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

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

traits = traits_def(Pure(), SameOperandsAndResultType()) class-attribute instance-attribute

assembly_format = '$memref `,` $alignment attr-dict `:` type($memref)' class-attribute instance-attribute

__init__(memref: SSAValue | Operation, alignment: int | IntegerAttr[I32]) -> None

Source code in xdsl/dialects/memref.py
def __init__(
    self,
    memref: SSAValue | Operation,
    alignment: int | IntegerAttr[I32],
) -> None:
    memref = SSAValue.get(memref)
    if isinstance(alignment, int):
        alignment = IntegerAttr(alignment, i32)
    super().__init__(
        operands=[memref],
        result_types=[memref.type],
        properties={"alignment": alignment},
    )

verify_() -> None

Source code in xdsl/dialects/memref.py
def verify_(self) -> None:
    alignment = self.alignment.value.data
    if alignment <= 0:
        raise VerifyException(f"Alignment must be positive, got {alignment}")

AtomicRMWOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class AtomicRMWOp(IRDLOperation):
    name = "memref.atomic_rmw"

    T: ClassVar = VarConstraint("T", AnyFloatConstr | SignlessIntegerConstraint)

    value = operand_def(T)
    memref = operand_def(MemRefType.constr(T))
    indices = var_operand_def(IndexType)

    kind = prop_def(IntegerAttr[I64])

    result = result_def(T)

    traits = traits_def(MemoryWriteEffect(), MemoryReadEffect())

name = 'memref.atomic_rmw' class-attribute instance-attribute

T: ClassVar = VarConstraint('T', AnyFloatConstr | SignlessIntegerConstraint) class-attribute instance-attribute

value = operand_def(T) class-attribute instance-attribute

memref = operand_def(MemRefType.constr(T)) class-attribute instance-attribute

indices = var_operand_def(IndexType) class-attribute instance-attribute

kind = prop_def(IntegerAttr[I64]) class-attribute instance-attribute

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

traits = traits_def(MemoryWriteEffect(), MemoryReadEffect()) class-attribute instance-attribute

DeallocOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class DeallocOp(IRDLOperation):
    name = "memref.dealloc"
    memref = operand_def(base(MemRefType) | base(UnrankedMemRefType))

    traits = traits_def(MemoryFreeEffect())

    @staticmethod
    def get(operand: Operation | SSAValue) -> DeallocOp:
        return DeallocOp.build(operands=[operand])

    assembly_format = "$memref attr-dict `:` type($memref)"

name = 'memref.dealloc' class-attribute instance-attribute

memref = operand_def(base(MemRefType) | base(UnrankedMemRefType)) class-attribute instance-attribute

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

assembly_format = '$memref attr-dict `:` type($memref)' class-attribute instance-attribute

get(operand: Operation | SSAValue) -> DeallocOp staticmethod

Source code in xdsl/dialects/memref.py
@staticmethod
def get(operand: Operation | SSAValue) -> DeallocOp:
    return DeallocOp.build(operands=[operand])

GetGlobalOp

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class GetGlobalOp(IRDLOperation):
    name = "memref.get_global"
    memref = result_def(MemRefType)
    name_ = prop_def(SymbolRefAttr, prop_name="name")

    traits = traits_def(NoMemoryEffect())

    assembly_format = "$name `:` type($memref) attr-dict"

    def __init__(self, name: str | SymbolRefAttr, return_type: Attribute):
        if isinstance(name, str):
            name = SymbolRefAttr(name)
        super().__init__(result_types=[return_type], properties={"name": name})

name = 'memref.get_global' class-attribute instance-attribute

memref = result_def(MemRefType) class-attribute instance-attribute

name_ = prop_def(SymbolRefAttr, prop_name='name') class-attribute instance-attribute

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

assembly_format = '$name `:` type($memref) attr-dict' class-attribute instance-attribute

__init__(name: str | SymbolRefAttr, return_type: Attribute)

Source code in xdsl/dialects/memref.py
def __init__(self, name: str | SymbolRefAttr, return_type: Attribute):
    if isinstance(name, str):
        name = SymbolRefAttr(name)
    super().__init__(result_types=[return_type], properties={"name": name})

GlobalOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class GlobalOp(IRDLOperation):
    name = "memref.global"

    sym_name = prop_def(SymbolNameConstraint())
    sym_visibility = prop_def(StringAttr)
    type = prop_def(MemRefType)
    initial_value = prop_def(UnitAttr | DenseIntOrFPElementsAttr)
    constant = opt_prop_def(UnitAttr)
    alignment = opt_prop_def(IntegerAttr[I64])

    traits = traits_def(SymbolOpInterface(), MemoryAllocEffect())

    def verify_(self) -> None:
        if self.alignment is not None:
            alignment_value = self.alignment.value.data
            # Alignment has to be a power of two
            if not (is_power_of_two(alignment_value)):
                raise VerifyException(
                    f"Alignment attribute {alignment_value} is not a power of 2"
                )

    @staticmethod
    def get(
        sym_name: StringAttr,
        sym_type: Attribute,
        initial_value: Attribute,
        sym_visibility: StringAttr = StringAttr("private"),
        constant: UnitAttr | None = None,
        alignment: int | IntegerAttr[IntegerType] | None = None,
    ) -> GlobalOp:
        if isinstance(alignment, int):
            alignment = IntegerAttr(alignment, 64)

        return GlobalOp.build(
            properties={
                "sym_name": sym_name,
                "type": sym_type,
                "initial_value": initial_value,
                "sym_visibility": sym_visibility,
                "constant": constant,
                "alignment": alignment,
            }
        )

name = 'memref.global' class-attribute instance-attribute

sym_name = prop_def(SymbolNameConstraint()) class-attribute instance-attribute

sym_visibility = prop_def(StringAttr) class-attribute instance-attribute

type = prop_def(MemRefType) class-attribute instance-attribute

initial_value = prop_def(UnitAttr | DenseIntOrFPElementsAttr) class-attribute instance-attribute

constant = opt_prop_def(UnitAttr) class-attribute instance-attribute

alignment = opt_prop_def(IntegerAttr[I64]) class-attribute instance-attribute

traits = traits_def(SymbolOpInterface(), MemoryAllocEffect()) class-attribute instance-attribute

verify_() -> None

Source code in xdsl/dialects/memref.py
def verify_(self) -> None:
    if self.alignment is not None:
        alignment_value = self.alignment.value.data
        # Alignment has to be a power of two
        if not (is_power_of_two(alignment_value)):
            raise VerifyException(
                f"Alignment attribute {alignment_value} is not a power of 2"
            )

get(sym_name: StringAttr, sym_type: Attribute, initial_value: Attribute, sym_visibility: StringAttr = StringAttr('private'), constant: UnitAttr | None = None, alignment: int | IntegerAttr[IntegerType] | None = None) -> GlobalOp staticmethod

Source code in xdsl/dialects/memref.py
@staticmethod
def get(
    sym_name: StringAttr,
    sym_type: Attribute,
    initial_value: Attribute,
    sym_visibility: StringAttr = StringAttr("private"),
    constant: UnitAttr | None = None,
    alignment: int | IntegerAttr[IntegerType] | None = None,
) -> GlobalOp:
    if isinstance(alignment, int):
        alignment = IntegerAttr(alignment, 64)

    return GlobalOp.build(
        properties={
            "sym_name": sym_name,
            "type": sym_type,
            "initial_value": initial_value,
            "sym_visibility": sym_visibility,
            "constant": constant,
            "alignment": alignment,
        }
    )

DimOp

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class DimOp(IRDLOperation):
    name = "memref.dim"

    source = operand_def(base(MemRefType) | base(UnrankedMemRefType))
    index = operand_def(IndexType)

    result = result_def(IndexType)

    traits = traits_def(NoMemoryEffect())

    assembly_format = "$source `,` $index attr-dict `:` type($source)"

    def __init__(
        self,
        source: SSAValue | Operation,
        index: SSAValue | Operation,
        attributes: Mapping[str, Attribute] | None = None,
    ):
        super().__init__(
            operands=(source, index), result_types=(IndexType(),), attributes=attributes
        )

    @staticmethod
    @deprecated("Use DimOp(source, index) instead")
    def from_source_and_index(
        source: SSAValue | Operation, index: SSAValue | Operation
    ) -> DimOp:
        return DimOp(source, index)

name = 'memref.dim' class-attribute instance-attribute

source = operand_def(base(MemRefType) | base(UnrankedMemRefType)) class-attribute instance-attribute

index = operand_def(IndexType) class-attribute instance-attribute

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

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

assembly_format = '$source `,` $index attr-dict `:` type($source)' class-attribute instance-attribute

__init__(source: SSAValue | Operation, index: SSAValue | Operation, attributes: Mapping[str, Attribute] | None = None)

Source code in xdsl/dialects/memref.py
def __init__(
    self,
    source: SSAValue | Operation,
    index: SSAValue | Operation,
    attributes: Mapping[str, Attribute] | None = None,
):
    super().__init__(
        operands=(source, index), result_types=(IndexType(),), attributes=attributes
    )

from_source_and_index(source: SSAValue | Operation, index: SSAValue | Operation) -> DimOp staticmethod

Source code in xdsl/dialects/memref.py
@staticmethod
@deprecated("Use DimOp(source, index) instead")
def from_source_and_index(
    source: SSAValue | Operation, index: SSAValue | Operation
) -> DimOp:
    return DimOp(source, index)

RankOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class RankOp(IRDLOperation):
    name = "memref.rank"

    source = operand_def(MemRefType)

    rank = result_def(IndexType)

    traits = traits_def(NoMemoryEffect())

    @staticmethod
    def from_memref(memref: Operation | SSAValue):
        return RankOp.build(operands=[memref], result_types=[IndexType()])

name = 'memref.rank' class-attribute instance-attribute

source = operand_def(MemRefType) class-attribute instance-attribute

rank = result_def(IndexType) class-attribute instance-attribute

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

from_memref(memref: Operation | SSAValue) staticmethod

Source code in xdsl/dialects/memref.py
@staticmethod
def from_memref(memref: Operation | SSAValue):
    return RankOp.build(operands=[memref], result_types=[IndexType()])

AlterShapeOperation dataclass

Bases: IRDLOperation, ABC

Source code in xdsl/dialects/memref.py
class AlterShapeOperation(IRDLOperation, abc.ABC):
    result = result_def(MemRefType)
    reassociation = prop_def(ContiguousArrayOfIntArray())

    traits = traits_def(NoMemoryEffect())

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

reassociation = prop_def(ContiguousArrayOfIntArray()) class-attribute instance-attribute

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

CollapseShapeOp dataclass

Bases: AlterShapeOperation

https://mlir.llvm.org/docs/Dialects/MemRef/#memrefcollapse_shape-memrefcollapseshapeop

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class CollapseShapeOp(AlterShapeOperation):
    """
    https://mlir.llvm.org/docs/Dialects/MemRef/#memrefcollapse_shape-memrefcollapseshapeop
    """

    name = "memref.collapse_shape"

    src = operand_def(MemRefType)

    assembly_format = (
        "$src $reassociation attr-dict `:` type($src) `into` type($result)"
    )

name = 'memref.collapse_shape' class-attribute instance-attribute

src = operand_def(MemRefType) class-attribute instance-attribute

assembly_format = '$src $reassociation attr-dict `:` type($src) `into` type($result)' class-attribute instance-attribute

ExpandShapeOp dataclass

Bases: AlterShapeOperation

https://mlir.llvm.org/docs/Dialects/MemRef/#memrefexpand_shape-memrefexpandshapeop

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class ExpandShapeOp(AlterShapeOperation):
    """
    https://mlir.llvm.org/docs/Dialects/MemRef/#memrefexpand_shape-memrefexpandshapeop
    """

    name = "memref.expand_shape"

    src = operand_def(MemRefType)
    output_shape = var_operand_def(IndexType)

    static_output_shape = prop_def(DenseArrayBase.constr(i64))

    assembly_format = (
        "$src $reassociation `output_shape`"
        "custom<DynamicIndexList>($output_shape, $static_output_shape) attr-dict `:`"
        "type($src) `into` type($result)"
    )

    custom_directives = (DynamicIndexList,)

name = 'memref.expand_shape' class-attribute instance-attribute

src = operand_def(MemRefType) class-attribute instance-attribute

output_shape = var_operand_def(IndexType) class-attribute instance-attribute

static_output_shape = prop_def(DenseArrayBase.constr(i64)) class-attribute instance-attribute

assembly_format = '$src $reassociation `output_shape`custom<DynamicIndexList>($output_shape, $static_output_shape) attr-dict `:`type($src) `into` type($result)' class-attribute instance-attribute

custom_directives = (DynamicIndexList,) class-attribute instance-attribute

ExtractStridedMetaDataOp

Bases: IRDLOperation

https://mlir.llvm.org/docs/Dialects/MemRef/#memrefextract_strided_metadata-memrefextractstridedmetadataop

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class ExtractStridedMetaDataOp(IRDLOperation):
    """
    https://mlir.llvm.org/docs/Dialects/MemRef/#memrefextract_strided_metadata-memrefextractstridedmetadataop
    """

    name = "memref.extract_strided_metadata"

    source = operand_def(MemRefType)

    base_buffer = result_def(MemRefType)
    offset = result_def(IndexType)
    sizes = var_result_def(IndexType)
    strides = var_result_def(IndexType)

    traits = traits_def(NoMemoryEffect())

    irdl_options = (SameVariadicResultSize(),)

    assembly_format = "$source `:` type($source) `->` type(results) attr-dict"

    def __init__(self, source: SSAValue | Operation):
        """
        Create an ExtractStridedMetaDataOp that extracts the metadata from the
        operation (source) that produces a memref.
        """
        source_type = SSAValue.get(source, type=MemRefType).type
        source_shape = source_type.get_shape()
        # Return a rank zero memref with the memref type
        base_buffer_type = MemRefType(
            source_type.element_type,
            [],
            NoneAttr(),
            source_type.memory_space,
        )
        offset_type = IndexType()
        # There are as many strides/sizes as there are shape dimensions
        strides_type = [IndexType()] * len(source_shape)
        sizes_type = [IndexType()] * len(source_shape)
        return_type = [base_buffer_type, offset_type, strides_type, sizes_type]
        super().__init__(operands=[source], result_types=return_type)

name = 'memref.extract_strided_metadata' class-attribute instance-attribute

source = operand_def(MemRefType) class-attribute instance-attribute

base_buffer = result_def(MemRefType) class-attribute instance-attribute

offset = result_def(IndexType) class-attribute instance-attribute

sizes = var_result_def(IndexType) class-attribute instance-attribute

strides = var_result_def(IndexType) class-attribute instance-attribute

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

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

assembly_format = '$source `:` type($source) `->` type(results) attr-dict' class-attribute instance-attribute

__init__(source: SSAValue | Operation)

Create an ExtractStridedMetaDataOp that extracts the metadata from the operation (source) that produces a memref.

Source code in xdsl/dialects/memref.py
def __init__(self, source: SSAValue | Operation):
    """
    Create an ExtractStridedMetaDataOp that extracts the metadata from the
    operation (source) that produces a memref.
    """
    source_type = SSAValue.get(source, type=MemRefType).type
    source_shape = source_type.get_shape()
    # Return a rank zero memref with the memref type
    base_buffer_type = MemRefType(
        source_type.element_type,
        [],
        NoneAttr(),
        source_type.memory_space,
    )
    offset_type = IndexType()
    # There are as many strides/sizes as there are shape dimensions
    strides_type = [IndexType()] * len(source_shape)
    sizes_type = [IndexType()] * len(source_shape)
    return_type = [base_buffer_type, offset_type, strides_type, sizes_type]
    super().__init__(operands=[source], result_types=return_type)

ExtractAlignedPointerAsIndexOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class ExtractAlignedPointerAsIndexOp(IRDLOperation):
    name = "memref.extract_aligned_pointer_as_index"

    source = operand_def(MemRefType)

    aligned_pointer = result_def(IndexType)

    traits = traits_def(NoMemoryEffect())

    @staticmethod
    def get(source: SSAValue | Operation):
        return ExtractAlignedPointerAsIndexOp.build(
            operands=[source], result_types=[IndexType()]
        )

name = 'memref.extract_aligned_pointer_as_index' class-attribute instance-attribute

source = operand_def(MemRefType) class-attribute instance-attribute

aligned_pointer = result_def(IndexType) class-attribute instance-attribute

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

get(source: SSAValue | Operation) staticmethod

Source code in xdsl/dialects/memref.py
@staticmethod
def get(source: SSAValue | Operation):
    return ExtractAlignedPointerAsIndexOp.build(
        operands=[source], result_types=[IndexType()]
    )

MemRefHasCanonicalizationPatternsTrait dataclass

Bases: HasCanonicalizationPatternsTrait

Source code in xdsl/dialects/memref.py
class MemRefHasCanonicalizationPatternsTrait(HasCanonicalizationPatternsTrait):
    @classmethod
    def get_canonicalization_patterns(cls) -> tuple[RewritePattern, ...]:
        from xdsl.transforms.canonicalization_patterns.memref import (
            MemRefSubviewOfSubviewFolding,
        )

        return (MemRefSubviewOfSubviewFolding(),)

get_canonicalization_patterns() -> tuple[RewritePattern, ...] classmethod

Source code in xdsl/dialects/memref.py
@classmethod
def get_canonicalization_patterns(cls) -> tuple[RewritePattern, ...]:
    from xdsl.transforms.canonicalization_patterns.memref import (
        MemRefSubviewOfSubviewFolding,
    )

    return (MemRefSubviewOfSubviewFolding(),)

SubviewOp

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class SubviewOp(IRDLOperation):
    name = "memref.subview"

    source = operand_def(MemRefType)
    offsets = var_operand_def(IndexType)
    sizes = var_operand_def(IndexType)
    strides = var_operand_def(IndexType)
    static_offsets = prop_def(DenseArrayBase.constr(i64))
    static_sizes = prop_def(DenseArrayBase.constr(i64))
    static_strides = prop_def(DenseArrayBase.constr(i64))
    result = result_def(MemRefType)

    irdl_options = (AttrSizedOperandSegments(as_property=True),)

    traits = lazy_traits_def(
        lambda: (MemRefHasCanonicalizationPatternsTrait(), NoMemoryEffect())
    )

    assembly_format = (
        "$source ``"
        "custom<DynamicIndexList>($offsets, $static_offsets)"
        "custom<DynamicIndexList>($sizes, $static_sizes)"
        "custom<DynamicIndexList>($strides, $static_strides)"
        "attr-dict `:` type($source) `to` type($result)"
    )

    custom_directives = (DynamicIndexList,)

    def verify_(self) -> None:
        static_offsets = self.static_offsets.get_values()
        static_sizes = self.static_sizes.get_values()
        static_strides = self.static_strides.get_values()
        verify_dynamic_index_list(
            static_sizes, self.sizes, DYNAMIC_INDEX, " in the size arguments"
        )
        verify_dynamic_index_list(
            static_offsets, self.offsets, DYNAMIC_INDEX, " in the offset arguments"
        )
        verify_dynamic_index_list(
            static_strides, self.strides, DYNAMIC_INDEX, " in the stride arguments"
        )

    def __init__(
        self,
        source: SSAValue | Operation,
        offsets: Sequence[SSAValue],
        sizes: Sequence[SSAValue],
        strides: Sequence[SSAValue],
        static_offsets: Sequence[int] | DenseArrayBase,
        static_sizes: Sequence[int] | DenseArrayBase,
        static_strides: Sequence[int] | DenseArrayBase,
        result_type: Attribute,
    ):
        if not isinstance(static_offsets, DenseArrayBase):
            static_offsets = DenseArrayBase.from_list(i64, static_offsets)
        if not isinstance(static_sizes, DenseArrayBase):
            static_sizes = DenseArrayBase.from_list(i64, static_sizes)
        if not isinstance(static_strides, DenseArrayBase):
            static_strides = DenseArrayBase.from_list(i64, static_strides)
        super().__init__(
            operands=[source, offsets, sizes, strides],
            result_types=[result_type],
            properties={
                "static_offsets": static_offsets,
                "static_sizes": static_sizes,
                "static_strides": static_strides,
            },
        )

    @staticmethod
    def get(
        source: SSAValue,
        offsets: Sequence[SSAValue | int],
        sizes: Sequence[SSAValue | int],
        strides: Sequence[SSAValue | int],
        result_type: Attribute,
    ) -> SubviewOp:
        static_offsets, dyn_offsets = split_dynamic_index_list(offsets, DYNAMIC_INDEX)
        static_sizes, dyn_sizes = split_dynamic_index_list(sizes, DYNAMIC_INDEX)
        static_strides, dyn_strides = split_dynamic_index_list(strides, DYNAMIC_INDEX)

        return SubviewOp(
            source,
            dyn_offsets,
            dyn_sizes,
            dyn_strides,
            static_offsets,
            static_sizes,
            static_strides,
            result_type,
        )

    @staticmethod
    def infer_result_type(
        source_type: MemRefType[Attribute],
        offsets: Sequence[SSAValue | int],
        sizes: Sequence[SSAValue | int],
        strides: Sequence[SSAValue | int],
        *,
        reduce_rank: bool = False,
    ) -> MemRefType[Attribute]:
        """
        Infer the result type of a memref.subview from its source type and
        offsets/sizes/strides.

        Raises:
            ValueError: If offsets, sizes, and strides do not match the source rank,
                if the source layout is not strided-like, or if rank reduction is
                requested with dynamic sizes.
        """
        rank = source_type.get_num_dims()
        if not (len(offsets) == len(sizes) == len(strides) == rank):
            raise ValueError(
                "expected offsets, sizes, and strides to match source rank"
            )

        static_offsets = tuple(
            value if isinstance(value, int) else None for value in offsets
        )
        static_sizes = tuple(
            value if isinstance(value, int) else None for value in sizes
        )
        static_strides = tuple(
            value if isinstance(value, int) else None for value in strides
        )

        source_strides = source_type.get_strides()
        if source_strides is None:
            raise ValueError(
                "cannot infer memref.subview result type from non-strided "
                f"source type {source_type}"
            )
        source_offset = source_type.get_offset()

        result_shape = tuple(
            DYNAMIC_INDEX if size is None else size for size in static_sizes
        )

        result_strides = tuple(
            None
            if source_stride is None or static_stride is None
            else source_stride * static_stride
            for source_stride, static_stride in zip(
                source_strides, static_strides, strict=True
            )
        )

        result_offset = source_offset
        if result_offset is not None:
            for static_offset, source_stride in zip(
                static_offsets, source_strides, strict=True
            ):
                if static_offset == 0:
                    continue
                if static_offset is None or source_stride is None:
                    result_offset = None
                    break
                result_offset += static_offset * source_stride

        if reduce_rank:
            if any(size is None for size in static_sizes):
                raise ValueError(
                    "cannot infer rank-reduced memref.subview result type with "
                    "dynamic sizes"
                )

            reduced_shape: list[int] = []
            reduced_strides: list[int | None] = []
            for size, stride in zip(static_sizes, result_strides, strict=True):
                assert size is not None
                if size == 1:
                    continue
                reduced_shape.append(size)
                reduced_strides.append(stride)
            result_shape = tuple(reduced_shape)
            result_strides = tuple(reduced_strides)

        return MemRefType(
            source_type.element_type,
            result_shape,
            StridedLayoutAttr(result_strides, result_offset),
            source_type.memory_space,
        )

    @staticmethod
    def from_static_parameters(
        source: SSAValue | Operation,
        source_type: MemRefType,
        offsets: Sequence[int],
        sizes: Sequence[int],
        strides: Sequence[int],
        reduce_rank: bool = False,
    ) -> SubviewOp:
        """
        Build a memref.subview from static offsets, sizes, and strides.

        Raises:
            ValueError: If offsets, sizes, and strides do not match the source rank,
                if the source layout is not strided-like, or if rank reduction is
                requested with dynamic sizes.
        """

        source = SSAValue.get(source)

        return_type = SubviewOp.infer_result_type(
            source_type,
            offsets,
            sizes,
            strides,
            reduce_rank=reduce_rank,
        )

        return SubviewOp.get(
            source,
            offsets,
            sizes,
            strides,
            return_type,
        )

name = 'memref.subview' class-attribute instance-attribute

source = operand_def(MemRefType) class-attribute instance-attribute

offsets = var_operand_def(IndexType) class-attribute instance-attribute

sizes = var_operand_def(IndexType) class-attribute instance-attribute

strides = var_operand_def(IndexType) class-attribute instance-attribute

static_offsets = prop_def(DenseArrayBase.constr(i64)) class-attribute instance-attribute

static_sizes = prop_def(DenseArrayBase.constr(i64)) class-attribute instance-attribute

static_strides = prop_def(DenseArrayBase.constr(i64)) class-attribute instance-attribute

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

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

traits = lazy_traits_def(lambda: (MemRefHasCanonicalizationPatternsTrait(), NoMemoryEffect())) class-attribute instance-attribute

assembly_format = '$source ``custom<DynamicIndexList>($offsets, $static_offsets)custom<DynamicIndexList>($sizes, $static_sizes)custom<DynamicIndexList>($strides, $static_strides)attr-dict `:` type($source) `to` type($result)' class-attribute instance-attribute

custom_directives = (DynamicIndexList,) class-attribute instance-attribute

verify_() -> None

Source code in xdsl/dialects/memref.py
def verify_(self) -> None:
    static_offsets = self.static_offsets.get_values()
    static_sizes = self.static_sizes.get_values()
    static_strides = self.static_strides.get_values()
    verify_dynamic_index_list(
        static_sizes, self.sizes, DYNAMIC_INDEX, " in the size arguments"
    )
    verify_dynamic_index_list(
        static_offsets, self.offsets, DYNAMIC_INDEX, " in the offset arguments"
    )
    verify_dynamic_index_list(
        static_strides, self.strides, DYNAMIC_INDEX, " in the stride arguments"
    )

__init__(source: SSAValue | Operation, offsets: Sequence[SSAValue], sizes: Sequence[SSAValue], strides: Sequence[SSAValue], static_offsets: Sequence[int] | DenseArrayBase, static_sizes: Sequence[int] | DenseArrayBase, static_strides: Sequence[int] | DenseArrayBase, result_type: Attribute)

Source code in xdsl/dialects/memref.py
def __init__(
    self,
    source: SSAValue | Operation,
    offsets: Sequence[SSAValue],
    sizes: Sequence[SSAValue],
    strides: Sequence[SSAValue],
    static_offsets: Sequence[int] | DenseArrayBase,
    static_sizes: Sequence[int] | DenseArrayBase,
    static_strides: Sequence[int] | DenseArrayBase,
    result_type: Attribute,
):
    if not isinstance(static_offsets, DenseArrayBase):
        static_offsets = DenseArrayBase.from_list(i64, static_offsets)
    if not isinstance(static_sizes, DenseArrayBase):
        static_sizes = DenseArrayBase.from_list(i64, static_sizes)
    if not isinstance(static_strides, DenseArrayBase):
        static_strides = DenseArrayBase.from_list(i64, static_strides)
    super().__init__(
        operands=[source, offsets, sizes, strides],
        result_types=[result_type],
        properties={
            "static_offsets": static_offsets,
            "static_sizes": static_sizes,
            "static_strides": static_strides,
        },
    )

get(source: SSAValue, offsets: Sequence[SSAValue | int], sizes: Sequence[SSAValue | int], strides: Sequence[SSAValue | int], result_type: Attribute) -> SubviewOp staticmethod

Source code in xdsl/dialects/memref.py
@staticmethod
def get(
    source: SSAValue,
    offsets: Sequence[SSAValue | int],
    sizes: Sequence[SSAValue | int],
    strides: Sequence[SSAValue | int],
    result_type: Attribute,
) -> SubviewOp:
    static_offsets, dyn_offsets = split_dynamic_index_list(offsets, DYNAMIC_INDEX)
    static_sizes, dyn_sizes = split_dynamic_index_list(sizes, DYNAMIC_INDEX)
    static_strides, dyn_strides = split_dynamic_index_list(strides, DYNAMIC_INDEX)

    return SubviewOp(
        source,
        dyn_offsets,
        dyn_sizes,
        dyn_strides,
        static_offsets,
        static_sizes,
        static_strides,
        result_type,
    )

infer_result_type(source_type: MemRefType[Attribute], offsets: Sequence[SSAValue | int], sizes: Sequence[SSAValue | int], strides: Sequence[SSAValue | int], *, reduce_rank: bool = False) -> MemRefType[Attribute] staticmethod

Infer the result type of a memref.subview from its source type and offsets/sizes/strides.

Raises:

Type Description
ValueError

If offsets, sizes, and strides do not match the source rank, if the source layout is not strided-like, or if rank reduction is requested with dynamic sizes.

Source code in xdsl/dialects/memref.py
@staticmethod
def infer_result_type(
    source_type: MemRefType[Attribute],
    offsets: Sequence[SSAValue | int],
    sizes: Sequence[SSAValue | int],
    strides: Sequence[SSAValue | int],
    *,
    reduce_rank: bool = False,
) -> MemRefType[Attribute]:
    """
    Infer the result type of a memref.subview from its source type and
    offsets/sizes/strides.

    Raises:
        ValueError: If offsets, sizes, and strides do not match the source rank,
            if the source layout is not strided-like, or if rank reduction is
            requested with dynamic sizes.
    """
    rank = source_type.get_num_dims()
    if not (len(offsets) == len(sizes) == len(strides) == rank):
        raise ValueError(
            "expected offsets, sizes, and strides to match source rank"
        )

    static_offsets = tuple(
        value if isinstance(value, int) else None for value in offsets
    )
    static_sizes = tuple(
        value if isinstance(value, int) else None for value in sizes
    )
    static_strides = tuple(
        value if isinstance(value, int) else None for value in strides
    )

    source_strides = source_type.get_strides()
    if source_strides is None:
        raise ValueError(
            "cannot infer memref.subview result type from non-strided "
            f"source type {source_type}"
        )
    source_offset = source_type.get_offset()

    result_shape = tuple(
        DYNAMIC_INDEX if size is None else size for size in static_sizes
    )

    result_strides = tuple(
        None
        if source_stride is None or static_stride is None
        else source_stride * static_stride
        for source_stride, static_stride in zip(
            source_strides, static_strides, strict=True
        )
    )

    result_offset = source_offset
    if result_offset is not None:
        for static_offset, source_stride in zip(
            static_offsets, source_strides, strict=True
        ):
            if static_offset == 0:
                continue
            if static_offset is None or source_stride is None:
                result_offset = None
                break
            result_offset += static_offset * source_stride

    if reduce_rank:
        if any(size is None for size in static_sizes):
            raise ValueError(
                "cannot infer rank-reduced memref.subview result type with "
                "dynamic sizes"
            )

        reduced_shape: list[int] = []
        reduced_strides: list[int | None] = []
        for size, stride in zip(static_sizes, result_strides, strict=True):
            assert size is not None
            if size == 1:
                continue
            reduced_shape.append(size)
            reduced_strides.append(stride)
        result_shape = tuple(reduced_shape)
        result_strides = tuple(reduced_strides)

    return MemRefType(
        source_type.element_type,
        result_shape,
        StridedLayoutAttr(result_strides, result_offset),
        source_type.memory_space,
    )

from_static_parameters(source: SSAValue | Operation, source_type: MemRefType, offsets: Sequence[int], sizes: Sequence[int], strides: Sequence[int], reduce_rank: bool = False) -> SubviewOp staticmethod

Build a memref.subview from static offsets, sizes, and strides.

Raises:

Type Description
ValueError

If offsets, sizes, and strides do not match the source rank, if the source layout is not strided-like, or if rank reduction is requested with dynamic sizes.

Source code in xdsl/dialects/memref.py
@staticmethod
def from_static_parameters(
    source: SSAValue | Operation,
    source_type: MemRefType,
    offsets: Sequence[int],
    sizes: Sequence[int],
    strides: Sequence[int],
    reduce_rank: bool = False,
) -> SubviewOp:
    """
    Build a memref.subview from static offsets, sizes, and strides.

    Raises:
        ValueError: If offsets, sizes, and strides do not match the source rank,
            if the source layout is not strided-like, or if rank reduction is
            requested with dynamic sizes.
    """

    source = SSAValue.get(source)

    return_type = SubviewOp.infer_result_type(
        source_type,
        offsets,
        sizes,
        strides,
        reduce_rank=reduce_rank,
    )

    return SubviewOp.get(
        source,
        offsets,
        sizes,
        strides,
        return_type,
    )

CastOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class CastOp(IRDLOperation):
    name = "memref.cast"

    source = operand_def(base(MemRefType) | base(UnrankedMemRefType))
    dest = result_def(base(MemRefType) | base(UnrankedMemRefType))

    traits = traits_def(NoMemoryEffect())

    @staticmethod
    def get(
        source: SSAValue | Operation,
        type: MemRefType | UnrankedMemRefType,
    ):
        return CastOp.build(operands=[source], result_types=[type])

name = 'memref.cast' class-attribute instance-attribute

source = operand_def(base(MemRefType) | base(UnrankedMemRefType)) class-attribute instance-attribute

dest = result_def(base(MemRefType) | base(UnrankedMemRefType)) class-attribute instance-attribute

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

get(source: SSAValue | Operation, type: MemRefType | UnrankedMemRefType) staticmethod

Source code in xdsl/dialects/memref.py
@staticmethod
def get(
    source: SSAValue | Operation,
    type: MemRefType | UnrankedMemRefType,
):
    return CastOp.build(operands=[source], result_types=[type])

MemorySpaceCastOp

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class MemorySpaceCastOp(IRDLOperation):
    name = "memref.memory_space_cast"

    source = operand_def(base(MemRefType) | base(UnrankedMemRefType))
    dest = result_def(base(MemRefType) | base(UnrankedMemRefType))

    traits = traits_def(NoMemoryEffect())

    def __init__(
        self,
        source: SSAValue | Operation,
        dest: MemRefType | UnrankedMemRefType,
    ):
        super().__init__(operands=[source], result_types=[dest])

    @staticmethod
    def from_type_and_target_space(
        source: SSAValue | Operation,
        type: MemRefType,
        dest_memory_space: Attribute,
    ) -> MemorySpaceCastOp:
        dest = MemRefType(
            type.get_element_type(),
            shape=type.get_shape(),
            layout=type.layout,
            memory_space=dest_memory_space,
        )
        return MemorySpaceCastOp(source, dest)

    def verify_(self) -> None:
        source = cast(MemRefType, self.source.type)
        dest = cast(MemRefType, self.dest.type)
        if source.get_shape() != dest.get_shape():
            raise VerifyException(
                "Expected source and destination to have the same shape."
            )
        if source.get_element_type() != dest.get_element_type():
            raise VerifyException(
                "Expected source and destination to have the same element type."
            )

name = 'memref.memory_space_cast' class-attribute instance-attribute

source = operand_def(base(MemRefType) | base(UnrankedMemRefType)) class-attribute instance-attribute

dest = result_def(base(MemRefType) | base(UnrankedMemRefType)) class-attribute instance-attribute

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

__init__(source: SSAValue | Operation, dest: MemRefType | UnrankedMemRefType)

Source code in xdsl/dialects/memref.py
def __init__(
    self,
    source: SSAValue | Operation,
    dest: MemRefType | UnrankedMemRefType,
):
    super().__init__(operands=[source], result_types=[dest])

from_type_and_target_space(source: SSAValue | Operation, type: MemRefType, dest_memory_space: Attribute) -> MemorySpaceCastOp staticmethod

Source code in xdsl/dialects/memref.py
@staticmethod
def from_type_and_target_space(
    source: SSAValue | Operation,
    type: MemRefType,
    dest_memory_space: Attribute,
) -> MemorySpaceCastOp:
    dest = MemRefType(
        type.get_element_type(),
        shape=type.get_shape(),
        layout=type.layout,
        memory_space=dest_memory_space,
    )
    return MemorySpaceCastOp(source, dest)

verify_() -> None

Source code in xdsl/dialects/memref.py
def verify_(self) -> None:
    source = cast(MemRefType, self.source.type)
    dest = cast(MemRefType, self.dest.type)
    if source.get_shape() != dest.get_shape():
        raise VerifyException(
            "Expected source and destination to have the same shape."
        )
    if source.get_element_type() != dest.get_element_type():
        raise VerifyException(
            "Expected source and destination to have the same element type."
        )

ReinterpretCastOp

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class ReinterpretCastOp(IRDLOperation):
    name = "memref.reinterpret_cast"

    source = operand_def(MemRefType)

    offsets = var_operand_def(IndexType)
    sizes = var_operand_def(IndexType)
    strides = var_operand_def(IndexType)

    static_offsets = prop_def(DenseArrayBase.constr(i64))
    static_sizes = prop_def(DenseArrayBase.constr(i64))
    static_strides = prop_def(DenseArrayBase.constr(i64))

    result = result_def(MemRefType)

    traits = traits_def(NoMemoryEffect())

    irdl_options = (AttrSizedOperandSegments(as_property=True),)

    assembly_format = (
        "$source `to` `offset` `` `:`"
        "custom<DynamicIndexList>($offsets, $static_offsets)"
        "`` `,` `sizes` `` `:`"
        "custom<DynamicIndexList>($sizes, $static_sizes)"
        "`` `,` `strides` `` `:`"
        "custom<DynamicIndexList>($strides, $static_strides)"
        "attr-dict `:` type($source) `to` type($result)"
    )

    custom_directives = (DynamicIndexList,)

    def __init__(
        self,
        source: SSAValue | Operation,
        offsets: Sequence[SSAValue],
        sizes: Sequence[SSAValue],
        strides: Sequence[SSAValue],
        static_offsets: Sequence[int] | DenseArrayBase,
        static_sizes: Sequence[int] | DenseArrayBase,
        static_strides: Sequence[int] | DenseArrayBase,
        result_type: Attribute,
    ):
        if not isinstance(static_offsets, DenseArrayBase):
            static_offsets = DenseArrayBase.from_list(i64, static_offsets)
        if not isinstance(static_sizes, DenseArrayBase):
            static_sizes = DenseArrayBase.from_list(i64, static_sizes)
        if not isinstance(static_strides, DenseArrayBase):
            static_strides = DenseArrayBase.from_list(i64, static_strides)
        super().__init__(
            operands=[source, offsets, sizes, strides],
            result_types=[result_type],
            properties={
                "static_offsets": static_offsets,
                "static_sizes": static_sizes,
                "static_strides": static_strides,
            },
        )

    @staticmethod
    def from_dynamic(
        source: SSAValue,
        offsets: Sequence[SSAValue | int],
        sizes: Sequence[SSAValue | int],
        strides: Sequence[SSAValue | int],
        result_type: Attribute,
    ):
        """
        Construct a `ReinterpretCastOp` from dynamic offsets, sizes, and strides.
        """
        static_offsets, dyn_offsets = split_dynamic_index_list(offsets, DYNAMIC_INDEX)
        static_sizes, dyn_sizes = split_dynamic_index_list(sizes, DYNAMIC_INDEX)
        static_strides, dyn_strides = split_dynamic_index_list(strides, DYNAMIC_INDEX)

        return ReinterpretCastOp(
            source,
            dyn_offsets,
            dyn_sizes,
            dyn_strides,
            static_offsets,
            static_sizes,
            static_strides,
            result_type,
        )

    def verify_(self):
        static_offsets = self.static_offsets.get_values()
        static_sizes = self.static_sizes.get_values()
        static_strides = self.static_strides.get_values()

        verify_dynamic_index_list(
            static_sizes, self.sizes, DYNAMIC_INDEX, " in the size arguments"
        )
        verify_dynamic_index_list(
            static_offsets, self.offsets, DYNAMIC_INDEX, " in the offset arguments"
        )
        verify_dynamic_index_list(
            static_strides, self.strides, DYNAMIC_INDEX, " in the stride arguments"
        )

        assert isa(self.source.type, MemRefType)
        assert isa(self.result.type, MemRefType)

        if len(self.result.type.shape) != len(self.static_sizes):
            raise VerifyException(
                f"Expected {len(self.source.type.shape)} size values but got {len(self.static_sizes)}"
            )

        # validate sizes
        for dim, (actual, expected) in enumerate(
            zip(
                self.result.type.get_shape(),
                self.static_sizes.get_values(),
                strict=True,
            )
        ):
            if expected == DYNAMIC_INDEX and actual != DYNAMIC_INDEX:
                raise VerifyException(
                    f"Expected result type with dynamic size instead of {actual} in dim = {dim}"
                )
            elif expected != DYNAMIC_INDEX and expected != actual:
                raise VerifyException(
                    f"Expected result type with size = {expected} instead of {actual} in dim = {dim}"
                )

name = 'memref.reinterpret_cast' class-attribute instance-attribute

source = operand_def(MemRefType) class-attribute instance-attribute

offsets = var_operand_def(IndexType) class-attribute instance-attribute

sizes = var_operand_def(IndexType) class-attribute instance-attribute

strides = var_operand_def(IndexType) class-attribute instance-attribute

static_offsets = prop_def(DenseArrayBase.constr(i64)) class-attribute instance-attribute

static_sizes = prop_def(DenseArrayBase.constr(i64)) class-attribute instance-attribute

static_strides = prop_def(DenseArrayBase.constr(i64)) class-attribute instance-attribute

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

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

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

assembly_format = '$source `to` `offset` `` `:`custom<DynamicIndexList>($offsets, $static_offsets)`` `,` `sizes` `` `:`custom<DynamicIndexList>($sizes, $static_sizes)`` `,` `strides` `` `:`custom<DynamicIndexList>($strides, $static_strides)attr-dict `:` type($source) `to` type($result)' class-attribute instance-attribute

custom_directives = (DynamicIndexList,) class-attribute instance-attribute

__init__(source: SSAValue | Operation, offsets: Sequence[SSAValue], sizes: Sequence[SSAValue], strides: Sequence[SSAValue], static_offsets: Sequence[int] | DenseArrayBase, static_sizes: Sequence[int] | DenseArrayBase, static_strides: Sequence[int] | DenseArrayBase, result_type: Attribute)

Source code in xdsl/dialects/memref.py
def __init__(
    self,
    source: SSAValue | Operation,
    offsets: Sequence[SSAValue],
    sizes: Sequence[SSAValue],
    strides: Sequence[SSAValue],
    static_offsets: Sequence[int] | DenseArrayBase,
    static_sizes: Sequence[int] | DenseArrayBase,
    static_strides: Sequence[int] | DenseArrayBase,
    result_type: Attribute,
):
    if not isinstance(static_offsets, DenseArrayBase):
        static_offsets = DenseArrayBase.from_list(i64, static_offsets)
    if not isinstance(static_sizes, DenseArrayBase):
        static_sizes = DenseArrayBase.from_list(i64, static_sizes)
    if not isinstance(static_strides, DenseArrayBase):
        static_strides = DenseArrayBase.from_list(i64, static_strides)
    super().__init__(
        operands=[source, offsets, sizes, strides],
        result_types=[result_type],
        properties={
            "static_offsets": static_offsets,
            "static_sizes": static_sizes,
            "static_strides": static_strides,
        },
    )

from_dynamic(source: SSAValue, offsets: Sequence[SSAValue | int], sizes: Sequence[SSAValue | int], strides: Sequence[SSAValue | int], result_type: Attribute) staticmethod

Construct a ReinterpretCastOp from dynamic offsets, sizes, and strides.

Source code in xdsl/dialects/memref.py
@staticmethod
def from_dynamic(
    source: SSAValue,
    offsets: Sequence[SSAValue | int],
    sizes: Sequence[SSAValue | int],
    strides: Sequence[SSAValue | int],
    result_type: Attribute,
):
    """
    Construct a `ReinterpretCastOp` from dynamic offsets, sizes, and strides.
    """
    static_offsets, dyn_offsets = split_dynamic_index_list(offsets, DYNAMIC_INDEX)
    static_sizes, dyn_sizes = split_dynamic_index_list(sizes, DYNAMIC_INDEX)
    static_strides, dyn_strides = split_dynamic_index_list(strides, DYNAMIC_INDEX)

    return ReinterpretCastOp(
        source,
        dyn_offsets,
        dyn_sizes,
        dyn_strides,
        static_offsets,
        static_sizes,
        static_strides,
        result_type,
    )

verify_()

Source code in xdsl/dialects/memref.py
def verify_(self):
    static_offsets = self.static_offsets.get_values()
    static_sizes = self.static_sizes.get_values()
    static_strides = self.static_strides.get_values()

    verify_dynamic_index_list(
        static_sizes, self.sizes, DYNAMIC_INDEX, " in the size arguments"
    )
    verify_dynamic_index_list(
        static_offsets, self.offsets, DYNAMIC_INDEX, " in the offset arguments"
    )
    verify_dynamic_index_list(
        static_strides, self.strides, DYNAMIC_INDEX, " in the stride arguments"
    )

    assert isa(self.source.type, MemRefType)
    assert isa(self.result.type, MemRefType)

    if len(self.result.type.shape) != len(self.static_sizes):
        raise VerifyException(
            f"Expected {len(self.source.type.shape)} size values but got {len(self.static_sizes)}"
        )

    # validate sizes
    for dim, (actual, expected) in enumerate(
        zip(
            self.result.type.get_shape(),
            self.static_sizes.get_values(),
            strict=True,
        )
    ):
        if expected == DYNAMIC_INDEX and actual != DYNAMIC_INDEX:
            raise VerifyException(
                f"Expected result type with dynamic size instead of {actual} in dim = {dim}"
            )
        elif expected != DYNAMIC_INDEX and expected != actual:
            raise VerifyException(
                f"Expected result type with size = {expected} instead of {actual} in dim = {dim}"
            )

ViewOp

Bases: IRDLOperation

memref view operation.

See external documentation.

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class ViewOp(IRDLOperation):
    """
    memref view operation.

    See external [documentation](https://mlir.llvm.org/docs/Dialects/MemRef/#memrefview-memrefviewop).
    """

    name = "memref.view"

    source = operand_def(MemRefType[i8])
    byte_shift = operand_def(IndexType)
    sizes = var_operand_def(IndexType)

    result = result_def(MemRefType)

    traits = traits_def(NoMemoryEffect())

    assembly_format = (
        "$source `[` $byte_shift `]` `` `[` $sizes `]` attr-dict "
        "`:` type($source) `to` type($result)"
    )

    def __init__(
        self,
        source: SSAValue | Operation,
        byte_shift: SSAValue | Operation,
        sizes: Sequence[SSAValue | Operation],
        result_type: MemRefType,
    ):
        super().__init__(
            operands=[source, byte_shift, sizes], result_types=[result_type]
        )

    def verify_(self) -> None:
        # Source must be a 1-D memref of i8.
        src_type = cast(MemRefType[IntegerType], self.source.type)

        if len(src_type.shape.data) != 1:
            raise VerifyException("memref.view source must be a 1-D memref of i8")

        # Enforce empty layout map on source and result (identity layout, offset 0).
        if not isinstance(src_type.layout, NoneAttr):
            raise VerifyException(
                "memref.view source must have identity layout (no layout map)"
            )

        res_type = cast(MemRefType[IntegerType], self.result.type)

        if not isinstance(res_type.layout, NoneAttr):
            raise VerifyException(
                "memref.view result must have identity layout (no layout map)"
            )

        # Memory spaces must match between source and result.
        if src_type.memory_space != res_type.memory_space:
            raise VerifyException(
                "different memory spaces specified for base memref type "
                f"'{src_type}' and view memref type '{res_type}'"
            )

        # A dynamic size operand must be provided for each dynamic dim in result.
        dyn_dims = sum(1 for d in res_type.shape.data if d.data == DYNAMIC_INDEX)
        if dyn_dims != len(self.sizes):
            raise VerifyException(
                "number of size operands must match number of dynamic dims in result type"
            )

name = 'memref.view' class-attribute instance-attribute

source = operand_def(MemRefType[i8]) class-attribute instance-attribute

byte_shift = operand_def(IndexType) class-attribute instance-attribute

sizes = var_operand_def(IndexType) class-attribute instance-attribute

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

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

assembly_format = '$source `[` $byte_shift `]` `` `[` $sizes `]` attr-dict `:` type($source) `to` type($result)' class-attribute instance-attribute

__init__(source: SSAValue | Operation, byte_shift: SSAValue | Operation, sizes: Sequence[SSAValue | Operation], result_type: MemRefType)

Source code in xdsl/dialects/memref.py
def __init__(
    self,
    source: SSAValue | Operation,
    byte_shift: SSAValue | Operation,
    sizes: Sequence[SSAValue | Operation],
    result_type: MemRefType,
):
    super().__init__(
        operands=[source, byte_shift, sizes], result_types=[result_type]
    )

verify_() -> None

Source code in xdsl/dialects/memref.py
def verify_(self) -> None:
    # Source must be a 1-D memref of i8.
    src_type = cast(MemRefType[IntegerType], self.source.type)

    if len(src_type.shape.data) != 1:
        raise VerifyException("memref.view source must be a 1-D memref of i8")

    # Enforce empty layout map on source and result (identity layout, offset 0).
    if not isinstance(src_type.layout, NoneAttr):
        raise VerifyException(
            "memref.view source must have identity layout (no layout map)"
        )

    res_type = cast(MemRefType[IntegerType], self.result.type)

    if not isinstance(res_type.layout, NoneAttr):
        raise VerifyException(
            "memref.view result must have identity layout (no layout map)"
        )

    # Memory spaces must match between source and result.
    if src_type.memory_space != res_type.memory_space:
        raise VerifyException(
            "different memory spaces specified for base memref type "
            f"'{src_type}' and view memref type '{res_type}'"
        )

    # A dynamic size operand must be provided for each dynamic dim in result.
    dyn_dims = sum(1 for d in res_type.shape.data if d.data == DYNAMIC_INDEX)
    if dyn_dims != len(self.sizes):
        raise VerifyException(
            "number of size operands must match number of dynamic dims in result type"
        )

DmaStartOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class DmaStartOp(IRDLOperation):
    name = "memref.dma_start"

    src = operand_def(MemRefType)
    src_indices = var_operand_def(IndexType)

    dest = operand_def(MemRefType)
    dest_indices = var_operand_def(IndexType)

    num_elements = operand_def(IndexType)

    tag = operand_def(MemRefType[IntegerType])
    tag_indices = var_operand_def(IndexType)

    traits = traits_def(MemoryWriteEffect(), MemoryReadEffect())

    irdl_options = (AttrSizedOperandSegments(),)

    @staticmethod
    def get(
        src: SSAValue | Operation,
        src_indices: Sequence[SSAValue | Operation],
        dest: SSAValue | Operation,
        dest_indices: Sequence[SSAValue | Operation],
        num_elements: SSAValue | Operation,
        tag: SSAValue | Operation,
        tag_indices: Sequence[SSAValue | Operation],
    ):
        return DmaStartOp.build(
            operands=[
                src,
                src_indices,
                dest,
                dest_indices,
                num_elements,
                tag,
                tag_indices,
            ]
        )

    def verify_(self) -> None:
        assert isa(self.src.type, MemRefType)
        assert isa(self.dest.type, MemRefType)
        assert isa(self.tag.type, MemRefType[IntegerType])

        if len(self.src.type.shape) != len(self.src_indices):
            raise VerifyException(
                f"Expected {len(self.src.type.shape)} source indices (because of shape of src memref)"
            )

        if len(self.dest.type.shape) != len(self.dest_indices):
            raise VerifyException(
                f"Expected {len(self.dest.type.shape)} dest indices (because of shape of dest memref)"
            )

        if len(self.tag.type.shape) != len(self.tag_indices):
            raise VerifyException(
                f"Expected {len(self.tag.type.shape)} tag indices (because of shape of tag memref)"
            )

        if self.tag.type.element_type != i32:
            raise VerifyException("Expected tag to be a memref of i32")

        if self.dest.type.memory_space == self.src.type.memory_space:
            raise VerifyException("Source and dest must have different memory spaces!")

name = 'memref.dma_start' class-attribute instance-attribute

src = operand_def(MemRefType) class-attribute instance-attribute

src_indices = var_operand_def(IndexType) class-attribute instance-attribute

dest = operand_def(MemRefType) class-attribute instance-attribute

dest_indices = var_operand_def(IndexType) class-attribute instance-attribute

num_elements = operand_def(IndexType) class-attribute instance-attribute

tag = operand_def(MemRefType[IntegerType]) class-attribute instance-attribute

tag_indices = var_operand_def(IndexType) class-attribute instance-attribute

traits = traits_def(MemoryWriteEffect(), MemoryReadEffect()) class-attribute instance-attribute

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

get(src: SSAValue | Operation, src_indices: Sequence[SSAValue | Operation], dest: SSAValue | Operation, dest_indices: Sequence[SSAValue | Operation], num_elements: SSAValue | Operation, tag: SSAValue | Operation, tag_indices: Sequence[SSAValue | Operation]) staticmethod

Source code in xdsl/dialects/memref.py
@staticmethod
def get(
    src: SSAValue | Operation,
    src_indices: Sequence[SSAValue | Operation],
    dest: SSAValue | Operation,
    dest_indices: Sequence[SSAValue | Operation],
    num_elements: SSAValue | Operation,
    tag: SSAValue | Operation,
    tag_indices: Sequence[SSAValue | Operation],
):
    return DmaStartOp.build(
        operands=[
            src,
            src_indices,
            dest,
            dest_indices,
            num_elements,
            tag,
            tag_indices,
        ]
    )

verify_() -> None

Source code in xdsl/dialects/memref.py
def verify_(self) -> None:
    assert isa(self.src.type, MemRefType)
    assert isa(self.dest.type, MemRefType)
    assert isa(self.tag.type, MemRefType[IntegerType])

    if len(self.src.type.shape) != len(self.src_indices):
        raise VerifyException(
            f"Expected {len(self.src.type.shape)} source indices (because of shape of src memref)"
        )

    if len(self.dest.type.shape) != len(self.dest_indices):
        raise VerifyException(
            f"Expected {len(self.dest.type.shape)} dest indices (because of shape of dest memref)"
        )

    if len(self.tag.type.shape) != len(self.tag_indices):
        raise VerifyException(
            f"Expected {len(self.tag.type.shape)} tag indices (because of shape of tag memref)"
        )

    if self.tag.type.element_type != i32:
        raise VerifyException("Expected tag to be a memref of i32")

    if self.dest.type.memory_space == self.src.type.memory_space:
        raise VerifyException("Source and dest must have different memory spaces!")

DmaWaitOp dataclass

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class DmaWaitOp(IRDLOperation):
    name = "memref.dma_wait"

    tag = operand_def(MemRefType)
    tag_indices = var_operand_def(IndexType)

    num_elements = operand_def(IndexType)

    traits = traits_def(MemoryWriteEffect(), MemoryReadEffect())

    assembly_format = (
        "$tag `[` $tag_indices `]` `,` $num_elements attr-dict `:` type($tag)"
    )

    @staticmethod
    def get(
        tag: SSAValue | Operation,
        tag_indices: Sequence[SSAValue | Operation],
        num_elements: SSAValue | Operation,
    ):
        return DmaWaitOp.build(
            operands=[
                tag,
                tag_indices,
                num_elements,
            ]
        )

    def verify_(self) -> None:
        assert isa(self.tag.type, MemRefType)

        if len(self.tag.type.shape) != len(self.tag_indices):
            raise VerifyException(
                f"Expected {len(self.tag.type.shape)} tag indices because of shape of tag memref"
            )

        if self.tag.type.element_type != i32:
            raise VerifyException("Expected tag to be a memref of i32")

name = 'memref.dma_wait' class-attribute instance-attribute

tag = operand_def(MemRefType) class-attribute instance-attribute

tag_indices = var_operand_def(IndexType) class-attribute instance-attribute

num_elements = operand_def(IndexType) class-attribute instance-attribute

traits = traits_def(MemoryWriteEffect(), MemoryReadEffect()) class-attribute instance-attribute

assembly_format = '$tag `[` $tag_indices `]` `,` $num_elements attr-dict `:` type($tag)' class-attribute instance-attribute

get(tag: SSAValue | Operation, tag_indices: Sequence[SSAValue | Operation], num_elements: SSAValue | Operation) staticmethod

Source code in xdsl/dialects/memref.py
@staticmethod
def get(
    tag: SSAValue | Operation,
    tag_indices: Sequence[SSAValue | Operation],
    num_elements: SSAValue | Operation,
):
    return DmaWaitOp.build(
        operands=[
            tag,
            tag_indices,
            num_elements,
        ]
    )

verify_() -> None

Source code in xdsl/dialects/memref.py
def verify_(self) -> None:
    assert isa(self.tag.type, MemRefType)

    if len(self.tag.type.shape) != len(self.tag_indices):
        raise VerifyException(
            f"Expected {len(self.tag.type.shape)} tag indices because of shape of tag memref"
        )

    if self.tag.type.element_type != i32:
        raise VerifyException("Expected tag to be a memref of i32")

CopyOp

Bases: IRDLOperation

Source code in xdsl/dialects/memref.py
@irdl_op_definition
class CopyOp(IRDLOperation):
    name = "memref.copy"
    source = operand_def(MemRefType)
    destination = operand_def(MemRefType)

    traits = traits_def(MemoryWriteEffect(), MemoryReadEffect())

    def __init__(self, source: SSAValue | Operation, destination: SSAValue | Operation):
        super().__init__(operands=[source, destination])

    def verify_(self) -> None:
        source = cast(MemRefType, self.source.type)
        destination = cast(MemRefType, self.destination.type)
        if source.get_shape() != destination.get_shape():
            raise VerifyException(
                "Expected source and destination to have the same shape."
            )
        if source.get_element_type() != destination.get_element_type():
            raise VerifyException(
                "Expected source and destination to have the same element type."
            )

name = 'memref.copy' class-attribute instance-attribute

source = operand_def(MemRefType) class-attribute instance-attribute

destination = operand_def(MemRefType) class-attribute instance-attribute

traits = traits_def(MemoryWriteEffect(), MemoryReadEffect()) class-attribute instance-attribute

__init__(source: SSAValue | Operation, destination: SSAValue | Operation)

Source code in xdsl/dialects/memref.py
def __init__(self, source: SSAValue | Operation, destination: SSAValue | Operation):
    super().__init__(operands=[source, destination])

verify_() -> None

Source code in xdsl/dialects/memref.py
def verify_(self) -> None:
    source = cast(MemRefType, self.source.type)
    destination = cast(MemRefType, self.destination.type)
    if source.get_shape() != destination.get_shape():
        raise VerifyException(
            "Expected source and destination to have the same shape."
        )
    if source.get_element_type() != destination.get_element_type():
        raise VerifyException(
            "Expected source and destination to have the same element type."
        )