Skip to content

Memref stream

memref_stream

A target-independent representation of streams of buffers over time.

Currently a higher-level representation of the snitch_stream dialect, operating on memrefs instead of registers storing pointers.

MemRefStream = Dialect('memref_stream', [ReadOp, WriteOp, StreamingRegionOp, GenericOp, YieldOp, FillOp], [ReadableStreamType, WritableStreamType, IteratorTypeAttr, StridePattern]) module-attribute

ReadableStreamType dataclass

Bases: ParametrizedAttribute, TypeAttribute, ContainerType[_StreamTypeElement], Generic[_StreamTypeElement]

Source code in xdsl/dialects/memref_stream.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
@irdl_attr_definition
class ReadableStreamType(
    ParametrizedAttribute,
    TypeAttribute,
    ContainerType[_StreamTypeElement],
    Generic[_StreamTypeElement],
):
    name = "memref_stream.readable"

    element_type: _StreamTypeElement

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

    @staticmethod
    def constr(
        element_type: AttrConstraint[_StreamTypeElement] = AnyAttr(),
    ) -> ParamAttrConstraint[ReadableStreamType[_StreamTypeElement]]:
        return ParamAttrConstraint[ReadableStreamType[_StreamTypeElement]](
            ReadableStreamType, (element_type,)
        )

name = 'memref_stream.readable' class-attribute instance-attribute

element_type: _StreamTypeElement instance-attribute

get_element_type() -> _StreamTypeElement

Source code in xdsl/dialects/memref_stream.py
83
84
def get_element_type(self) -> _StreamTypeElement:
    return self.element_type

constr(element_type: AttrConstraint[_StreamTypeElement] = AnyAttr()) -> ParamAttrConstraint[ReadableStreamType[_StreamTypeElement]] staticmethod

Source code in xdsl/dialects/memref_stream.py
86
87
88
89
90
91
92
@staticmethod
def constr(
    element_type: AttrConstraint[_StreamTypeElement] = AnyAttr(),
) -> ParamAttrConstraint[ReadableStreamType[_StreamTypeElement]]:
    return ParamAttrConstraint[ReadableStreamType[_StreamTypeElement]](
        ReadableStreamType, (element_type,)
    )

WritableStreamType dataclass

Bases: ParametrizedAttribute, TypeAttribute, ContainerType[_StreamTypeElement], Generic[_StreamTypeElement]

Source code in xdsl/dialects/memref_stream.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
@irdl_attr_definition
class WritableStreamType(
    ParametrizedAttribute,
    TypeAttribute,
    ContainerType[_StreamTypeElement],
    Generic[_StreamTypeElement],
):
    name = "memref_stream.writable"

    element_type: _StreamTypeElement

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

    @staticmethod
    def constr(
        element_type: AttrConstraint[_StreamTypeElement] = AnyAttr(),
    ) -> ParamAttrConstraint[WritableStreamType[_StreamTypeElement]]:
        return ParamAttrConstraint[WritableStreamType[_StreamTypeElement]](
            WritableStreamType, (element_type,)
        )

name = 'memref_stream.writable' class-attribute instance-attribute

element_type: _StreamTypeElement instance-attribute

get_element_type() -> _StreamTypeElement

Source code in xdsl/dialects/memref_stream.py
106
107
def get_element_type(self) -> _StreamTypeElement:
    return self.element_type

constr(element_type: AttrConstraint[_StreamTypeElement] = AnyAttr()) -> ParamAttrConstraint[WritableStreamType[_StreamTypeElement]] staticmethod

Source code in xdsl/dialects/memref_stream.py
109
110
111
112
113
114
115
@staticmethod
def constr(
    element_type: AttrConstraint[_StreamTypeElement] = AnyAttr(),
) -> ParamAttrConstraint[WritableStreamType[_StreamTypeElement]]:
    return ParamAttrConstraint[WritableStreamType[_StreamTypeElement]](
        WritableStreamType, (element_type,)
    )

IteratorType

Bases: StrEnum

Iterator type for memref_stream Attribute

Source code in xdsl/dialects/memref_stream.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
class IteratorType(StrEnum):
    "Iterator type for memref_stream Attribute"

    PARALLEL = auto()
    """
    The corresponding iterators appear in the output.
    """
    REDUCTION = auto()
    """
    The corresponding iterators do not appear in the output.
    """
    INTERLEAVED = auto()
    """
    All inputs and outputs of the operation will be operated this many times in parallel.
    This is helpful to circumvent the latency in the loop.
    For example, if the ALU of the target has a pipeline of length 4, and the operation
    accumulates its innermost dimension, there will be stalls waiting fof the pipeline to
    clear in each iteration.
    By interleaving the loop with a factor of 4, four dimensions can be processed in
    parallel, removing the stalls.
    The corresponding iterators may appear in the output.
    """

PARALLEL = auto() class-attribute instance-attribute

The corresponding iterators appear in the output.

REDUCTION = auto() class-attribute instance-attribute

The corresponding iterators do not appear in the output.

INTERLEAVED = auto() class-attribute instance-attribute

All inputs and outputs of the operation will be operated this many times in parallel. This is helpful to circumvent the latency in the loop. For example, if the ALU of the target has a pipeline of length 4, and the operation accumulates its innermost dimension, there will be stalls waiting fof the pipeline to clear in each iteration. By interleaving the loop with a factor of 4, four dimensions can be processed in parallel, removing the stalls. The corresponding iterators may appear in the output.

IteratorTypeAttr dataclass

Bases: EnumAttribute[IteratorType]

Source code in xdsl/dialects/memref_stream.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
@irdl_attr_definition
class IteratorTypeAttr(EnumAttribute[IteratorType]):
    name = "memref_stream.iterator_type"

    @classmethod
    def parallel(cls) -> IteratorTypeAttr:
        return IteratorTypeAttr(IteratorType.PARALLEL)

    @classmethod
    def reduction(cls) -> IteratorTypeAttr:
        return IteratorTypeAttr(IteratorType.REDUCTION)

    @classmethod
    def interleaved(cls) -> IteratorTypeAttr:
        return IteratorTypeAttr(IteratorType.INTERLEAVED)

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

    def print_parameter(self, printer: Printer) -> None:
        with printer.in_angle_brackets():
            super().print_parameter(printer)

name = 'memref_stream.iterator_type' class-attribute instance-attribute

parallel() -> IteratorTypeAttr classmethod

Source code in xdsl/dialects/memref_stream.py
146
147
148
@classmethod
def parallel(cls) -> IteratorTypeAttr:
    return IteratorTypeAttr(IteratorType.PARALLEL)

reduction() -> IteratorTypeAttr classmethod

Source code in xdsl/dialects/memref_stream.py
150
151
152
@classmethod
def reduction(cls) -> IteratorTypeAttr:
    return IteratorTypeAttr(IteratorType.REDUCTION)

interleaved() -> IteratorTypeAttr classmethod

Source code in xdsl/dialects/memref_stream.py
154
155
156
@classmethod
def interleaved(cls) -> IteratorTypeAttr:
    return IteratorTypeAttr(IteratorType.INTERLEAVED)

parse_parameter(parser: AttrParser) -> IteratorType classmethod

Source code in xdsl/dialects/memref_stream.py
158
159
160
161
@classmethod
def parse_parameter(cls, parser: AttrParser) -> IteratorType:
    with parser.in_angle_brackets():
        return super().parse_parameter(parser)

print_parameter(printer: Printer) -> None

Source code in xdsl/dialects/memref_stream.py
163
164
165
def print_parameter(self, printer: Printer) -> None:
    with printer.in_angle_brackets():
        super().print_parameter(printer)

StridePattern dataclass

Bases: ParametrizedAttribute

Attribute representing the order and offsets in which elements will be read from or written to a stream.

// 2D access pattern
#pat = #memref_stream.stride_pattern<ub = [16, 8], strides = (d0, d1) -> (d0 + 1, d1 + 2)>
// Corresponds to the following locations
// for i in range(16):
//   for j in range(8):
//     yield (i + 1, j + 2)
// Note that the upper bounds and strides go from the outermost loop inwards
Source code in xdsl/dialects/memref_stream.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
@irdl_attr_definition
class StridePattern(ParametrizedAttribute):
    """
    Attribute representing the order and offsets in which elements will be read from or
    written to a stream.

    ```
    // 2D access pattern
    #pat = #memref_stream.stride_pattern<ub = [16, 8], strides = (d0, d1) -> (d0 + 1, d1 + 2)>
    // Corresponds to the following locations
    // for i in range(16):
    //   for j in range(8):
    //     yield (i + 1, j + 2)
    // Note that the upper bounds and strides go from the outermost loop inwards
    ```
    """

    name = "memref_stream.stride_pattern"

    ub: ArrayAttr[IntegerAttr[IndexType]]
    index_map: AffineMapAttr

    @classmethod
    def parse_parameters(cls, parser: AttrParser) -> Sequence[Attribute]:
        with parser.in_angle_brackets():
            parser.parse_identifier("ub")
            parser.parse_punctuation("=")
            index = IndexType()
            ub = ArrayAttr(
                IntegerAttr(i, index)
                for i in parser.parse_comma_separated_list(
                    parser.Delimiter.SQUARE, parser.parse_integer
                )
            )
            parser.parse_punctuation(",")
            parser.parse_identifier("index_map")
            parser.parse_punctuation("=")
            index_map = AffineMapAttr(parser.parse_affine_map())
            return (ub, index_map)

    def print_parameters(self, printer: Printer) -> None:
        with printer.in_angle_brackets():
            printer.print_string("ub = ")
            with printer.in_square_brackets():
                printer.print_list(
                    self.ub, lambda attr: attr.print_without_type(printer)
                )
            printer.print_string(f", index_map = {self.index_map.data}")

    def rank(self):
        return len(self.ub)

    def verify(self) -> None:
        if len(self.ub) != self.index_map.data.num_dims:
            raise VerifyException(
                f"Expect stride pattern upper bounds {self.ub} to be equal in length to dimensions of {self.index_map}"
            )
        if self.index_map.data.num_symbols:
            raise VerifyException(
                f"Expect stride pattern map to not contain symbols: {self.index_map}"
            )

    def index_iter(self) -> Iterator[tuple[int, ...]]:
        for indices in product(*(range(bound.value.data) for bound in self.ub.data)):
            indices: tuple[int, ...] = indices
            yield self.index_map.data.eval(indices, ())

    def offsets(self) -> tuple[tuple[int, ...], ...]:
        return tuple(self.index_iter())

name = 'memref_stream.stride_pattern' class-attribute instance-attribute

ub: ArrayAttr[IntegerAttr[IndexType]] instance-attribute

index_map: AffineMapAttr instance-attribute

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

Source code in xdsl/dialects/memref_stream.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
@classmethod
def parse_parameters(cls, parser: AttrParser) -> Sequence[Attribute]:
    with parser.in_angle_brackets():
        parser.parse_identifier("ub")
        parser.parse_punctuation("=")
        index = IndexType()
        ub = ArrayAttr(
            IntegerAttr(i, index)
            for i in parser.parse_comma_separated_list(
                parser.Delimiter.SQUARE, parser.parse_integer
            )
        )
        parser.parse_punctuation(",")
        parser.parse_identifier("index_map")
        parser.parse_punctuation("=")
        index_map = AffineMapAttr(parser.parse_affine_map())
        return (ub, index_map)

print_parameters(printer: Printer) -> None

Source code in xdsl/dialects/memref_stream.py
208
209
210
211
212
213
214
215
def print_parameters(self, printer: Printer) -> None:
    with printer.in_angle_brackets():
        printer.print_string("ub = ")
        with printer.in_square_brackets():
            printer.print_list(
                self.ub, lambda attr: attr.print_without_type(printer)
            )
        printer.print_string(f", index_map = {self.index_map.data}")

rank()

Source code in xdsl/dialects/memref_stream.py
217
218
def rank(self):
    return len(self.ub)

verify() -> None

Source code in xdsl/dialects/memref_stream.py
220
221
222
223
224
225
226
227
228
def verify(self) -> None:
    if len(self.ub) != self.index_map.data.num_dims:
        raise VerifyException(
            f"Expect stride pattern upper bounds {self.ub} to be equal in length to dimensions of {self.index_map}"
        )
    if self.index_map.data.num_symbols:
        raise VerifyException(
            f"Expect stride pattern map to not contain symbols: {self.index_map}"
        )

index_iter() -> Iterator[tuple[int, ...]]

Source code in xdsl/dialects/memref_stream.py
230
231
232
233
def index_iter(self) -> Iterator[tuple[int, ...]]:
    for indices in product(*(range(bound.value.data) for bound in self.ub.data)):
        indices: tuple[int, ...] = indices
        yield self.index_map.data.eval(indices, ())

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

Source code in xdsl/dialects/memref_stream.py
235
236
def offsets(self) -> tuple[tuple[int, ...], ...]:
    return tuple(self.index_iter())

ReadOp

Bases: IRDLOperation

Source code in xdsl/dialects/memref_stream.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
@irdl_op_definition
class ReadOp(IRDLOperation):
    name = "memref_stream.read"

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

    stream = operand_def(ReadableStreamType.constr(T))
    res = result_def(T)

    assembly_format = "`from` $stream attr-dict `:` type($res)"

    def __init__(self, stream_val: SSAValue, result_type: Attribute | None = None):
        if result_type is None:
            assert isinstance(stream_type := stream_val.type, ReadableStreamType)
            stream_type = cast(ReadableStreamType[Attribute], stream_type)
            result_type = stream_type.element_type
        super().__init__(operands=[stream_val], result_types=[result_type])

    def assembly_line(self) -> str | None:
        return None

name = 'memref_stream.read' class-attribute instance-attribute

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

stream = operand_def(ReadableStreamType.constr(T)) class-attribute instance-attribute

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

assembly_format = '`from` $stream attr-dict `:` type($res)' class-attribute instance-attribute

__init__(stream_val: SSAValue, result_type: Attribute | None = None)

Source code in xdsl/dialects/memref_stream.py
250
251
252
253
254
255
def __init__(self, stream_val: SSAValue, result_type: Attribute | None = None):
    if result_type is None:
        assert isinstance(stream_type := stream_val.type, ReadableStreamType)
        stream_type = cast(ReadableStreamType[Attribute], stream_type)
        result_type = stream_type.element_type
    super().__init__(operands=[stream_val], result_types=[result_type])

assembly_line() -> str | None

Source code in xdsl/dialects/memref_stream.py
257
258
def assembly_line(self) -> str | None:
    return None

WriteOp

Bases: IRDLOperation

Source code in xdsl/dialects/memref_stream.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
@irdl_op_definition
class WriteOp(IRDLOperation):
    name = "memref_stream.write"

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

    value = operand_def(T)
    stream = operand_def(WritableStreamType.constr(T))

    assembly_format = "$value `to` $stream attr-dict `:` type($value)"

    def __init__(self, value: SSAValue, stream: SSAValue):
        super().__init__(operands=[value, stream])

    def assembly_line(self) -> str | None:
        return None

name = 'memref_stream.write' class-attribute instance-attribute

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

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

stream = operand_def(WritableStreamType.constr(T)) class-attribute instance-attribute

assembly_format = '$value `to` $stream attr-dict `:` type($value)' class-attribute instance-attribute

__init__(value: SSAValue, stream: SSAValue)

Source code in xdsl/dialects/memref_stream.py
272
273
def __init__(self, value: SSAValue, stream: SSAValue):
    super().__init__(operands=[value, stream])

assembly_line() -> str | None

Source code in xdsl/dialects/memref_stream.py
275
276
def assembly_line(self) -> str | None:
    return None

StreamingRegionOp

Bases: IRDLOperation

An operation that creates streams from access patterns, which are only available to read from and write to within the body of the operation.

Within the loop body, memrefs that are streamed must not be otherwise accessed via memref.load, memref.store or any other access means, including extraction (e.g.: memref.view).

Source code in xdsl/dialects/memref_stream.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
@irdl_op_definition
class StreamingRegionOp(IRDLOperation):
    """
    An operation that creates streams from access patterns, which are only available to
    read from and write to within the body of the operation.

    Within the loop body, memrefs that are streamed must not be otherwise accessed
    via memref.load, memref.store or any other access means, including extraction (e.g.: memref.view).
    """

    name = "memref_stream.streaming_region"

    inputs = var_operand_def(memref.MemRefType)
    """
    Pointers to memory buffers that will be streamed. The corresponding stride pattern
    defines the order in which the elements of the input buffers will be read.
    """
    outputs = var_operand_def(memref.MemRefType)
    """
    Pointers to memory buffers that will be streamed. The corresponding stride pattern
    defines the order in which the elements of the input buffers will be written to.
    """
    patterns = prop_def(ArrayAttr[StridePattern])
    """
    Stride patterns that define the order of the input and output streams.
    Like in linalg.generic, the indexing maps corresponding to inputs are followed by the
    indexing maps for the outputs.
    """

    body = region_def("single_block")

    irdl_options = (AttrSizedOperandSegments(as_property=True),)

    traits = traits_def(NoTerminator())

    def __init__(
        self,
        inputs: Sequence[SSAValue],
        outputs: Sequence[SSAValue],
        patterns: ArrayAttr[StridePattern],
        body: Region,
    ) -> None:
        super().__init__(
            operands=[inputs, outputs],
            regions=[body],
            properties={
                "patterns": patterns,
            },
        )

    def print(self, printer: Printer):
        with printer.indented():
            printer.print_string(" {")
            if self.patterns.data:
                printer.print_string("\npatterns = [")
                with printer.indented():
                    if self.patterns.data:
                        printer.print_string("\n")
                        printer.print_list(
                            self.patterns.data,
                            printer.print_attribute,
                            delimiter=",\n",
                        )
                printer.print_string("\n]")
            else:
                printer.print_string("\npatterns = []")
        printer.print_string("\n}")

        if self.inputs:
            printer.print_string(" ins(")
            printer.print_list(self.inputs, printer.print_ssa_value)
            printer.print_string(" : ")
            printer.print_list(self.inputs.types, printer.print_attribute)
            printer.print_string(")")

        if self.outputs:
            printer.print_string(" outs(")
            printer.print_list(self.outputs, printer.print_ssa_value)
            printer.print_string(" : ")
            printer.print_list(self.outputs.types, printer.print_attribute)
            printer.print_string(")")

        if self.attributes:
            printer.print_string(" attrs = ")
            printer.print_op_attributes(self.attributes)

        printer.print_string(" ")
        printer.print_region(self.body)

    @classmethod
    def parse(cls, parser: Parser) -> Self:
        parser.parse_punctuation("{")
        parser.parse_identifier("patterns")
        parser.parse_punctuation("=")

        patterns = parser.parse_attribute()
        if not isinstance(patterns, ArrayAttr):
            parser.raise_error(f"Expected ArrayAttr {patterns}")
        patterns = cast(ArrayAttr[Any], patterns)
        for pattern in patterns:
            if not isinstance(pattern, StridePattern):
                parser.raise_error(f"Expected StridePattern {pattern}")
        patterns = cast(ArrayAttr[StridePattern], patterns)

        parser.parse_punctuation("}")

        pos = parser.pos
        if parser.parse_optional_characters("ins"):
            parser.parse_punctuation("(")
            unresolved_ins = parser.parse_comma_separated_list(
                Parser.Delimiter.NONE, parser.parse_unresolved_operand
            )
            parser.parse_punctuation(":")
            ins_types = parser.parse_comma_separated_list(
                Parser.Delimiter.NONE, parser.parse_type
            )
            parser.parse_punctuation(")")
            ins = parser.resolve_operands(unresolved_ins, ins_types, pos)
        else:
            ins = ()

        pos = parser.pos
        if parser.parse_optional_characters("outs"):
            parser.parse_punctuation("(")
            unresolved_outs = parser.parse_comma_separated_list(
                Parser.Delimiter.NONE, parser.parse_unresolved_operand
            )
            parser.parse_punctuation(":")
            outs_types = parser.parse_comma_separated_list(
                Parser.Delimiter.NONE, parser.parse_type
            )
            parser.parse_punctuation(")")
            outs = parser.resolve_operands(unresolved_outs, outs_types, pos)
        else:
            outs = ()

        if parser.parse_optional_keyword("attrs"):
            parser.parse_punctuation("=")
            extra_attrs = parser.expect(
                parser.parse_optional_attr_dict, "expect extra attributes"
            )
        else:
            extra_attrs = {}

        body = parser.parse_region()

        generic = cls(
            ins,
            outs,
            patterns,
            body,
        )
        generic.attributes |= extra_attrs

        return generic

name = 'memref_stream.streaming_region' class-attribute instance-attribute

inputs = var_operand_def(memref.MemRefType) class-attribute instance-attribute

Pointers to memory buffers that will be streamed. The corresponding stride pattern defines the order in which the elements of the input buffers will be read.

outputs = var_operand_def(memref.MemRefType) class-attribute instance-attribute

Pointers to memory buffers that will be streamed. The corresponding stride pattern defines the order in which the elements of the input buffers will be written to.

patterns = prop_def(ArrayAttr[StridePattern]) class-attribute instance-attribute

Stride patterns that define the order of the input and output streams. Like in linalg.generic, the indexing maps corresponding to inputs are followed by the indexing maps for the outputs.

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

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

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

__init__(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue], patterns: ArrayAttr[StridePattern], body: Region) -> None

Source code in xdsl/dialects/memref_stream.py
314
315
316
317
318
319
320
321
322
323
324
325
326
327
def __init__(
    self,
    inputs: Sequence[SSAValue],
    outputs: Sequence[SSAValue],
    patterns: ArrayAttr[StridePattern],
    body: Region,
) -> None:
    super().__init__(
        operands=[inputs, outputs],
        regions=[body],
        properties={
            "patterns": patterns,
        },
    )

print(printer: Printer)

Source code in xdsl/dialects/memref_stream.py
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
361
362
363
364
365
366
def print(self, printer: Printer):
    with printer.indented():
        printer.print_string(" {")
        if self.patterns.data:
            printer.print_string("\npatterns = [")
            with printer.indented():
                if self.patterns.data:
                    printer.print_string("\n")
                    printer.print_list(
                        self.patterns.data,
                        printer.print_attribute,
                        delimiter=",\n",
                    )
            printer.print_string("\n]")
        else:
            printer.print_string("\npatterns = []")
    printer.print_string("\n}")

    if self.inputs:
        printer.print_string(" ins(")
        printer.print_list(self.inputs, printer.print_ssa_value)
        printer.print_string(" : ")
        printer.print_list(self.inputs.types, printer.print_attribute)
        printer.print_string(")")

    if self.outputs:
        printer.print_string(" outs(")
        printer.print_list(self.outputs, printer.print_ssa_value)
        printer.print_string(" : ")
        printer.print_list(self.outputs.types, printer.print_attribute)
        printer.print_string(")")

    if self.attributes:
        printer.print_string(" attrs = ")
        printer.print_op_attributes(self.attributes)

    printer.print_string(" ")
    printer.print_region(self.body)

parse(parser: Parser) -> Self classmethod

Source code in xdsl/dialects/memref_stream.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
@classmethod
def parse(cls, parser: Parser) -> Self:
    parser.parse_punctuation("{")
    parser.parse_identifier("patterns")
    parser.parse_punctuation("=")

    patterns = parser.parse_attribute()
    if not isinstance(patterns, ArrayAttr):
        parser.raise_error(f"Expected ArrayAttr {patterns}")
    patterns = cast(ArrayAttr[Any], patterns)
    for pattern in patterns:
        if not isinstance(pattern, StridePattern):
            parser.raise_error(f"Expected StridePattern {pattern}")
    patterns = cast(ArrayAttr[StridePattern], patterns)

    parser.parse_punctuation("}")

    pos = parser.pos
    if parser.parse_optional_characters("ins"):
        parser.parse_punctuation("(")
        unresolved_ins = parser.parse_comma_separated_list(
            Parser.Delimiter.NONE, parser.parse_unresolved_operand
        )
        parser.parse_punctuation(":")
        ins_types = parser.parse_comma_separated_list(
            Parser.Delimiter.NONE, parser.parse_type
        )
        parser.parse_punctuation(")")
        ins = parser.resolve_operands(unresolved_ins, ins_types, pos)
    else:
        ins = ()

    pos = parser.pos
    if parser.parse_optional_characters("outs"):
        parser.parse_punctuation("(")
        unresolved_outs = parser.parse_comma_separated_list(
            Parser.Delimiter.NONE, parser.parse_unresolved_operand
        )
        parser.parse_punctuation(":")
        outs_types = parser.parse_comma_separated_list(
            Parser.Delimiter.NONE, parser.parse_type
        )
        parser.parse_punctuation(")")
        outs = parser.resolve_operands(unresolved_outs, outs_types, pos)
    else:
        outs = ()

    if parser.parse_optional_keyword("attrs"):
        parser.parse_punctuation("=")
        extra_attrs = parser.expect(
            parser.parse_optional_attr_dict, "expect extra attributes"
        )
    else:
        extra_attrs = {}

    body = parser.parse_region()

    generic = cls(
        ins,
        outs,
        patterns,
        body,
    )
    generic.attributes |= extra_attrs

    return generic

GenericOpHasCanonicalizationPatternsTrait dataclass

Bases: HasCanonicalizationPatternsTrait

Source code in xdsl/dialects/memref_stream.py
436
437
438
439
440
441
442
443
class GenericOpHasCanonicalizationPatternsTrait(HasCanonicalizationPatternsTrait):
    @classmethod
    def get_canonicalization_patterns(cls):
        from xdsl.transforms.canonicalization_patterns.memref_stream import (
            RemoveUnusedInitOperandPattern,
        )

        return (RemoveUnusedInitOperandPattern(),)

get_canonicalization_patterns() classmethod

Source code in xdsl/dialects/memref_stream.py
437
438
439
440
441
442
443
@classmethod
def get_canonicalization_patterns(cls):
    from xdsl.transforms.canonicalization_patterns.memref_stream import (
        RemoveUnusedInitOperandPattern,
    )

    return (RemoveUnusedInitOperandPattern(),)

GenericOp

Bases: IRDLOperation

Source code in xdsl/dialects/memref_stream.py
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
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
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
@irdl_op_definition
class GenericOp(IRDLOperation):
    name = "memref_stream.generic"

    inputs = var_operand_def()
    """
    Pointers to memory buffers or streams to be operated on. The corresponding stride
    pattern defines the order in which the elements of the input buffers will be read.
    """
    outputs = var_operand_def(MemRefType.constr() | WritableStreamType.constr())
    """
    Pointers to memory buffers or streams to be operated on. The corresponding stride
    pattern defines the order in which the elements of the input buffers will be written
    to.
    """
    inits = var_operand_def()
    """
    Initial values for outputs. The outputs are at corresponding `init_indices`. The
    inits may be set only for the imperfectly nested form.
    """
    indexing_maps = prop_def(ArrayAttr[AffineMapAttr])
    """
    Stride patterns that define the order of the input and output streams.
    Like in linalg.generic, the indexing maps corresponding to inputs are followed by
    the indexing maps for the outputs.
    """
    bounds = prop_def(ArrayAttr[IntegerAttr[IndexType]])
    """
    The bounds of the iteration space, from the outermost loop inwards.
    All indexing maps must have the same number of dimensions as the length of `bounds`.
    """

    iterator_types = prop_def(ArrayAttr[IteratorTypeAttr])
    init_indices = prop_def(ArrayAttr[IntAttr])
    """
    Indices into the `outputs` that correspond to the initial values in `inits`.
    """

    doc = opt_prop_def(StringAttr)
    library_call = opt_prop_def(StringAttr)

    body = region_def("single_block")

    traits = traits_def(GenericOpHasCanonicalizationPatternsTrait())

    irdl_options = (AttrSizedOperandSegments(as_property=True),)

    def __init__(
        self,
        inputs: Sequence[SSAValue],
        outputs: Sequence[SSAValue],
        inits: Sequence[SSAValue],
        body: Region,
        indexing_maps: ArrayAttr[AffineMapAttr],
        iterator_types: ArrayAttr[Attribute],
        bounds: ArrayAttr[IntegerAttr[IndexType]],
        init_indices: ArrayAttr[IntAttr],
        doc: StringAttr | None = None,
        library_call: StringAttr | None = None,
    ) -> None:
        for m in indexing_maps:
            if m.data.num_symbols:
                raise NotImplementedError(
                    f"Symbols currently not implemented in {self.name} indexing maps"
                )
        super().__init__(
            operands=[inputs, outputs, inits],
            properties={
                "bounds": bounds,
                "init_indices": init_indices,
                "indexing_maps": indexing_maps,
                "iterator_types": iterator_types,
                "doc": doc,
                "library_call": library_call,
            },
            regions=[body],
        )

    def get_static_loop_ranges(
        self,
    ) -> tuple[tuple[int, ...], tuple[int, ...]]:
        """
        This operation can represent two sets of perfectly nested loops, or one.
        If it is one, then the first element of the returned tuple has all the loop
        bounds, and the second is empty.
        If there are two, then the first element of the returned tuple has the outer
        bounds, and the second the inner.
        Interleaved iterators are not returned in either tuple.
        """
        output_maps = self.indexing_maps.data[len(self.inputs) :]
        # min_dims will equal len(self.iterator_types) in the perfect nest case
        min_dims = min(m.data.num_dims for m in output_maps)
        num_interleaved = sum(
            it.data == IteratorType.INTERLEAVED for it in self.iterator_types
        )
        if num_interleaved:
            res = (
                tuple(
                    bound.value.data
                    for bound in self.bounds.data[: min_dims - num_interleaved]
                ),
                tuple(
                    bound.value.data
                    for bound in self.bounds.data[
                        min_dims - num_interleaved : -num_interleaved
                    ]
                ),
            )
        else:
            res = (
                tuple(bound.value.data for bound in self.bounds.data[:min_dims]),
                tuple(
                    bound.value.data
                    for bound in self.bounds.data[min_dims - num_interleaved :]
                ),
            )
        return res

    @property
    def is_imperfectly_nested(self) -> bool:
        return bool(self.get_static_loop_ranges()[1])

    def _print_init(self, printer: Printer, init: SSAValue | None):
        if init is None:
            printer.print_string("None")
        else:
            printer.print_ssa_value(init)
            printer.print_string(" : ")
            printer.print_attribute(init.type)

    def print(self, printer: Printer):
        printer.print_string(" {")
        with printer.indented():
            if self.bounds:
                printer.print_string("\nbounds = [")
                with printer.indented():
                    printer.print_list(
                        self.bounds.data,
                        lambda bound: printer.print_string(f"{bound.value.data}"),
                    )
                printer.print_string("],")
            else:
                printer.print_string("\nbounds = [],")

            if self.indexing_maps:
                printer.print_string("\nindexing_maps = [")
                with printer.indented():
                    printer.print_list(
                        self.indexing_maps.data,
                        lambda m: printer.print_string(f"\n{m}"),
                        delimiter=",",
                    )
                printer.print_string("\n],")
            else:
                printer.print_string("\nindexing_maps = [].")
            printer.print_string("\niterator_types = [")
            printer.print_list(
                self.iterator_types,
                lambda iterator_type: printer.print_string_literal(iterator_type.data),
            )
            printer.print_string("]")
            if self.doc:
                printer.print_string(",\ndoc = ")
                printer.print_attribute(self.doc)
            if self.library_call:
                printer.print_string(",\nlibrary_call = ")
                printer.print_attribute(self.library_call)
        printer.print_string("\n}")

        if self.inputs:
            printer.print_string(" ins(")
            printer.print_list(self.inputs, printer.print_ssa_value)
            printer.print_string(" : ")
            printer.print_list(self.inputs.types, printer.print_attribute)
            printer.print_string(")")

        if self.outputs:
            printer.print_string(" outs(")
            printer.print_list(self.outputs, printer.print_ssa_value)
            printer.print_string(" : ")
            printer.print_list(self.outputs.types, printer.print_attribute)
            printer.print_string(")")

        if self.inits:
            printer.print_string(" inits(")
            inits: list[SSAValue | None] = [None] * len(self.outputs)
            for i, val in zip(self.init_indices, self.inits):
                inits[i.data] = val
            printer.print_list(
                inits,
                lambda val: self._print_init(printer, val),
            )
            printer.print_string(")")

        extra_attrs = self.attributes.copy()
        if "indexing_maps" in extra_attrs:
            del extra_attrs["indexing_maps"]
        if "iterator_types" in extra_attrs:
            del extra_attrs["iterator_types"]
        if "doc" in extra_attrs:
            del extra_attrs["doc"]
        if "library_call" in extra_attrs:
            del extra_attrs["library_call"]

        if extra_attrs:
            printer.print_string(" attrs = ")
            printer.print_op_attributes(extra_attrs)

        printer.print_string(" ")
        printer.print_region(self.body)

    @classmethod
    def _parse_init(cls, parser: Parser) -> SSAValue | None:
        if parser.parse_optional_characters("None"):
            return None
        unresolved = parser.parse_unresolved_operand()
        parser.parse_punctuation(":")
        type = parser.parse_type()
        return parser.resolve_operand(unresolved, type)

    @classmethod
    def _parse_inits(
        cls, parser: Parser
    ) -> tuple[tuple[SSAValue, ...], tuple[int, ...]]:
        if not parser.parse_optional_characters("inits"):
            return ((), ())

        parser.parse_punctuation("(")
        optional_inits = parser.parse_comma_separated_list(
            Parser.Delimiter.NONE, lambda: cls._parse_init(parser)
        )
        parser.parse_punctuation(")")
        enumerated_inits = tuple(
            (i, val) for i, val in enumerate(optional_inits) if val is not None
        )
        inits = tuple(init for _, init in enumerated_inits)
        init_indices = tuple(i for i, _ in enumerated_inits)

        return (tuple(inits), init_indices)

    @classmethod
    def parse(cls, parser: Parser) -> Self:
        attrs_start_pos = parser.pos
        attrs = parser.parse_optional_attr_dict()
        attrs_end_pos = parser.pos

        if "bounds" in attrs:
            bounds = attrs["bounds"]
            assert isa(bounds, ArrayAttr[IntegerAttr[IntegerType | IndexType]]), bounds
            index = IndexType()
            bounds = ArrayAttr(
                tuple(IntegerAttr(attr.value, index) for attr in bounds.data)
            )
            del attrs["bounds"]
        else:
            parser.raise_error(
                "Expected bounds for memref_stream.generic",
                attrs_start_pos,
                attrs_end_pos,
            )

        if "indexing_maps" in attrs:
            indexing_maps = attrs["indexing_maps"]
            assert isinstance(indexing_maps, ArrayAttr)
            indexing_maps = cast(ArrayAttr[AffineMapAttr], indexing_maps)
            del attrs["indexing_maps"]
        else:
            parser.raise_error(
                "Expected indexing_maps for memref_stream.generic",
                attrs_start_pos,
                attrs_end_pos,
            )

        if "iterator_types" in attrs:
            # Get iterator types and make sure they're an ArrayAttr
            parsed_iterator_types = attrs["iterator_types"]
            assert isinstance(parsed_iterator_types, ArrayAttr)
            parsed_iterator_types = cast(ArrayAttr[Attribute], parsed_iterator_types)
            del attrs["iterator_types"]

            # Make sure they're iterator types
            iterator_types: list[IteratorTypeAttr] = []
            for iterator_type in parsed_iterator_types:
                match iterator_type:
                    case IteratorTypeAttr():
                        iterator_types.append(iterator_type)
                    case StringAttr():
                        iterator_type = IteratorTypeAttr(
                            IteratorType(iterator_type.data)
                        )
                        iterator_types.append(iterator_type)
                    case _:
                        parser.raise_error(
                            f"Unknown iterator type {iterator_type}",
                            attrs_start_pos,
                            attrs_end_pos,
                        )
        else:
            parser.raise_error(
                "Expected iterator_types for memref_stream.generic",
                attrs_start_pos,
                attrs_end_pos,
            )

        if "doc" in attrs:
            doc = attrs["doc"]
            assert isinstance(doc, StringAttr)
            del attrs["doc"]
        else:
            doc = None

        if "library_call" in attrs:
            library_call = attrs["library_call"]
            assert isinstance(library_call, StringAttr)
            del attrs["library_call"]
        else:
            library_call = None

        pos = parser.pos
        if parser.parse_optional_characters("ins"):
            parser.parse_punctuation("(")
            unresolved_ins = parser.parse_comma_separated_list(
                Parser.Delimiter.NONE, parser.parse_unresolved_operand
            )
            parser.parse_punctuation(":")
            ins_types = parser.parse_comma_separated_list(
                Parser.Delimiter.NONE, parser.parse_type
            )
            parser.parse_punctuation(")")
            ins = parser.resolve_operands(unresolved_ins, ins_types, pos)
        else:
            ins = ()

        pos = parser.pos
        if parser.parse_optional_characters("outs"):
            parser.parse_punctuation("(")
            unresolved_outs = parser.parse_comma_separated_list(
                Parser.Delimiter.NONE, parser.parse_unresolved_operand
            )
            parser.parse_punctuation(":")
            outs_types = parser.parse_comma_separated_list(
                Parser.Delimiter.NONE, parser.parse_type
            )
            parser.parse_punctuation(")")
            outs = parser.resolve_operands(unresolved_outs, outs_types, pos)
        else:
            outs_types = ()
            outs = ()

        inits, init_indices = cls._parse_inits(parser)

        if parser.parse_optional_keyword("attrs"):
            parser.parse_punctuation("=")
            extra_attrs = parser.expect(
                parser.parse_optional_attr_dict, "expect extra attributes"
            )
        else:
            extra_attrs = {}

        body = parser.parse_region()

        generic = cls(
            ins,
            outs,
            inits,
            body,
            indexing_maps,
            ArrayAttr(iterator_types),
            bounds,
            ArrayAttr(IntAttr(index) for index in init_indices),
            doc,
            library_call,
        )
        generic.attributes |= attrs
        generic.attributes |= extra_attrs

        return generic

    def verify_(self) -> None:
        if len(self.inits) != len(self.init_indices):
            raise VerifyException(
                f"Mismatching number of inits and init indices: {len(self.inits)} != {self.init_indices}"
            )

        # Parallel iterator types must preceed reduction iterators
        iterator_types = self.iterator_types.data
        num_parallel = iterator_types.count(IteratorTypeAttr.parallel())
        num_reduction = iterator_types.count(IteratorTypeAttr.reduction())
        num_interleaved = iterator_types.count(IteratorTypeAttr.interleaved())

        if IteratorTypeAttr.parallel() in iterator_types[num_parallel:]:
            raise VerifyException(
                f"Unexpected order of iterator types: {[it.data.value for it in iterator_types]}"
            )
        if (
            IteratorTypeAttr.reduction()
            in iterator_types[num_parallel + num_reduction :]
        ):
            raise VerifyException(
                f"Unexpected order of iterator types: {[it.data.value for it in iterator_types]}"
            )
        if num_interleaved > 1:
            raise VerifyException(f"Too many interleaved bounds: {num_interleaved}")
        assert num_parallel + num_reduction + num_interleaved == len(iterator_types)

        if len(self.inputs) + len(self.outputs) != len(self.indexing_maps):
            raise VerifyException(
                "The number of affine maps must match the number of inputs and outputs"
            )

        # Whether or not the operation represents an imperfect loop nest, verify that the
        # bounds of the outer + inner nests match the domain of the input affine maps
        input_count = len(self.inputs)
        input_maps = self.indexing_maps.data[:input_count]

        for i, m in enumerate(input_maps):
            if len(iterator_types) != m.data.num_dims:
                raise VerifyException(f"Invalid number of dims in indexing map {i}")

        # If the operation represents an imperfect loop nest, the bounds must match the
        # number of parallel iterators; otherwise they must match the total number of
        # iterators. In either case, they must all be the same.
        output_count = len(self.outputs)
        output_maps = self.indexing_maps.data[input_count:]

        min_dims = min(m.data.num_dims for m in output_maps)
        max_dims = max(m.data.num_dims for m in output_maps)

        if min_dims != max_dims:
            raise VerifyException(
                "The number of dims in output indexing maps must all be the same"
            )

        if min_dims not in (len(iterator_types), num_parallel + num_interleaved):
            # To signify that the output is imperfectly nested, the output affine map has
            # as many dims as parallel iterators. Otherwise, it has as many dims as
            # the total number of iterators.
            raise VerifyException(
                "The number of dims in output indexing maps must be "
                f"{len(iterator_types)} or {num_parallel + num_interleaved}"
            )

        if len(self.init_indices) != len(self.inits):
            raise VerifyException(
                "The number of inits and init_indices must be the same"
            )

        # The values of the inits must correspond to outputs where the domain of the
        # affine map has the same number of dimensions as the number of parallel
        # iterators.
        num_outputs = len(self.outputs)
        output_maps = self.indexing_maps.data[-num_outputs:]
        for index in self.init_indices:
            if not (0 <= index.data <= num_outputs):
                raise VerifyException(f"Init index out of bounds: {index.data}")
            m = output_maps[index.data]
            if m.data.num_dims != (num_parallel + num_interleaved):
                raise VerifyException(
                    "Incompatible affine map and initial value for output at index "
                    f"{index}"
                )

        interleave_factor = self.bounds.data[-1].value.data if num_interleaved else 1

        # If the operation is interleaved, use the interleaving factor to check
        # the number of arguments
        init_count = len(self.inits)
        # Outputs with initial values correspond to accumulators in the presence of
        # reduction
        acc_count = output_count if num_reduction else (output_count - init_count)
        expected_block_arg_count = (input_count + acc_count) * interleave_factor

        if expected_block_arg_count != len(self.body.block.args):
            raise VerifyException(
                f"Invalid number of arguments in block ({len(self.body.block.args)}), expected {expected_block_arg_count}"
            )

name = 'memref_stream.generic' class-attribute instance-attribute

inputs = var_operand_def() class-attribute instance-attribute

Pointers to memory buffers or streams to be operated on. The corresponding stride pattern defines the order in which the elements of the input buffers will be read.

outputs = var_operand_def(MemRefType.constr() | WritableStreamType.constr()) class-attribute instance-attribute

Pointers to memory buffers or streams to be operated on. The corresponding stride pattern defines the order in which the elements of the input buffers will be written to.

inits = var_operand_def() class-attribute instance-attribute

Initial values for outputs. The outputs are at corresponding init_indices. The inits may be set only for the imperfectly nested form.

indexing_maps = prop_def(ArrayAttr[AffineMapAttr]) class-attribute instance-attribute

Stride patterns that define the order of the input and output streams. Like in linalg.generic, the indexing maps corresponding to inputs are followed by the indexing maps for the outputs.

bounds = prop_def(ArrayAttr[IntegerAttr[IndexType]]) class-attribute instance-attribute

The bounds of the iteration space, from the outermost loop inwards. All indexing maps must have the same number of dimensions as the length of bounds.

iterator_types = prop_def(ArrayAttr[IteratorTypeAttr]) class-attribute instance-attribute

init_indices = prop_def(ArrayAttr[IntAttr]) class-attribute instance-attribute

Indices into the outputs that correspond to the initial values in inits.

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

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

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

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

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

is_imperfectly_nested: bool property

__init__(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue], inits: Sequence[SSAValue], body: Region, indexing_maps: ArrayAttr[AffineMapAttr], iterator_types: ArrayAttr[Attribute], bounds: ArrayAttr[IntegerAttr[IndexType]], init_indices: ArrayAttr[IntAttr], doc: StringAttr | None = None, library_call: StringAttr | None = None) -> None

Source code in xdsl/dialects/memref_stream.py
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
def __init__(
    self,
    inputs: Sequence[SSAValue],
    outputs: Sequence[SSAValue],
    inits: Sequence[SSAValue],
    body: Region,
    indexing_maps: ArrayAttr[AffineMapAttr],
    iterator_types: ArrayAttr[Attribute],
    bounds: ArrayAttr[IntegerAttr[IndexType]],
    init_indices: ArrayAttr[IntAttr],
    doc: StringAttr | None = None,
    library_call: StringAttr | None = None,
) -> None:
    for m in indexing_maps:
        if m.data.num_symbols:
            raise NotImplementedError(
                f"Symbols currently not implemented in {self.name} indexing maps"
            )
    super().__init__(
        operands=[inputs, outputs, inits],
        properties={
            "bounds": bounds,
            "init_indices": init_indices,
            "indexing_maps": indexing_maps,
            "iterator_types": iterator_types,
            "doc": doc,
            "library_call": library_call,
        },
        regions=[body],
    )

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

This operation can represent two sets of perfectly nested loops, or one. If it is one, then the first element of the returned tuple has all the loop bounds, and the second is empty. If there are two, then the first element of the returned tuple has the outer bounds, and the second the inner. Interleaved iterators are not returned in either tuple.

Source code in xdsl/dialects/memref_stream.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
554
555
556
557
558
559
560
561
562
def get_static_loop_ranges(
    self,
) -> tuple[tuple[int, ...], tuple[int, ...]]:
    """
    This operation can represent two sets of perfectly nested loops, or one.
    If it is one, then the first element of the returned tuple has all the loop
    bounds, and the second is empty.
    If there are two, then the first element of the returned tuple has the outer
    bounds, and the second the inner.
    Interleaved iterators are not returned in either tuple.
    """
    output_maps = self.indexing_maps.data[len(self.inputs) :]
    # min_dims will equal len(self.iterator_types) in the perfect nest case
    min_dims = min(m.data.num_dims for m in output_maps)
    num_interleaved = sum(
        it.data == IteratorType.INTERLEAVED for it in self.iterator_types
    )
    if num_interleaved:
        res = (
            tuple(
                bound.value.data
                for bound in self.bounds.data[: min_dims - num_interleaved]
            ),
            tuple(
                bound.value.data
                for bound in self.bounds.data[
                    min_dims - num_interleaved : -num_interleaved
                ]
            ),
        )
    else:
        res = (
            tuple(bound.value.data for bound in self.bounds.data[:min_dims]),
            tuple(
                bound.value.data
                for bound in self.bounds.data[min_dims - num_interleaved :]
            ),
        )
    return res

print(printer: Printer)

Source code in xdsl/dialects/memref_stream.py
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
def print(self, printer: Printer):
    printer.print_string(" {")
    with printer.indented():
        if self.bounds:
            printer.print_string("\nbounds = [")
            with printer.indented():
                printer.print_list(
                    self.bounds.data,
                    lambda bound: printer.print_string(f"{bound.value.data}"),
                )
            printer.print_string("],")
        else:
            printer.print_string("\nbounds = [],")

        if self.indexing_maps:
            printer.print_string("\nindexing_maps = [")
            with printer.indented():
                printer.print_list(
                    self.indexing_maps.data,
                    lambda m: printer.print_string(f"\n{m}"),
                    delimiter=",",
                )
            printer.print_string("\n],")
        else:
            printer.print_string("\nindexing_maps = [].")
        printer.print_string("\niterator_types = [")
        printer.print_list(
            self.iterator_types,
            lambda iterator_type: printer.print_string_literal(iterator_type.data),
        )
        printer.print_string("]")
        if self.doc:
            printer.print_string(",\ndoc = ")
            printer.print_attribute(self.doc)
        if self.library_call:
            printer.print_string(",\nlibrary_call = ")
            printer.print_attribute(self.library_call)
    printer.print_string("\n}")

    if self.inputs:
        printer.print_string(" ins(")
        printer.print_list(self.inputs, printer.print_ssa_value)
        printer.print_string(" : ")
        printer.print_list(self.inputs.types, printer.print_attribute)
        printer.print_string(")")

    if self.outputs:
        printer.print_string(" outs(")
        printer.print_list(self.outputs, printer.print_ssa_value)
        printer.print_string(" : ")
        printer.print_list(self.outputs.types, printer.print_attribute)
        printer.print_string(")")

    if self.inits:
        printer.print_string(" inits(")
        inits: list[SSAValue | None] = [None] * len(self.outputs)
        for i, val in zip(self.init_indices, self.inits):
            inits[i.data] = val
        printer.print_list(
            inits,
            lambda val: self._print_init(printer, val),
        )
        printer.print_string(")")

    extra_attrs = self.attributes.copy()
    if "indexing_maps" in extra_attrs:
        del extra_attrs["indexing_maps"]
    if "iterator_types" in extra_attrs:
        del extra_attrs["iterator_types"]
    if "doc" in extra_attrs:
        del extra_attrs["doc"]
    if "library_call" in extra_attrs:
        del extra_attrs["library_call"]

    if extra_attrs:
        printer.print_string(" attrs = ")
        printer.print_op_attributes(extra_attrs)

    printer.print_string(" ")
    printer.print_region(self.body)

parse(parser: Parser) -> Self classmethod

Source code in xdsl/dialects/memref_stream.py
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
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
@classmethod
def parse(cls, parser: Parser) -> Self:
    attrs_start_pos = parser.pos
    attrs = parser.parse_optional_attr_dict()
    attrs_end_pos = parser.pos

    if "bounds" in attrs:
        bounds = attrs["bounds"]
        assert isa(bounds, ArrayAttr[IntegerAttr[IntegerType | IndexType]]), bounds
        index = IndexType()
        bounds = ArrayAttr(
            tuple(IntegerAttr(attr.value, index) for attr in bounds.data)
        )
        del attrs["bounds"]
    else:
        parser.raise_error(
            "Expected bounds for memref_stream.generic",
            attrs_start_pos,
            attrs_end_pos,
        )

    if "indexing_maps" in attrs:
        indexing_maps = attrs["indexing_maps"]
        assert isinstance(indexing_maps, ArrayAttr)
        indexing_maps = cast(ArrayAttr[AffineMapAttr], indexing_maps)
        del attrs["indexing_maps"]
    else:
        parser.raise_error(
            "Expected indexing_maps for memref_stream.generic",
            attrs_start_pos,
            attrs_end_pos,
        )

    if "iterator_types" in attrs:
        # Get iterator types and make sure they're an ArrayAttr
        parsed_iterator_types = attrs["iterator_types"]
        assert isinstance(parsed_iterator_types, ArrayAttr)
        parsed_iterator_types = cast(ArrayAttr[Attribute], parsed_iterator_types)
        del attrs["iterator_types"]

        # Make sure they're iterator types
        iterator_types: list[IteratorTypeAttr] = []
        for iterator_type in parsed_iterator_types:
            match iterator_type:
                case IteratorTypeAttr():
                    iterator_types.append(iterator_type)
                case StringAttr():
                    iterator_type = IteratorTypeAttr(
                        IteratorType(iterator_type.data)
                    )
                    iterator_types.append(iterator_type)
                case _:
                    parser.raise_error(
                        f"Unknown iterator type {iterator_type}",
                        attrs_start_pos,
                        attrs_end_pos,
                    )
    else:
        parser.raise_error(
            "Expected iterator_types for memref_stream.generic",
            attrs_start_pos,
            attrs_end_pos,
        )

    if "doc" in attrs:
        doc = attrs["doc"]
        assert isinstance(doc, StringAttr)
        del attrs["doc"]
    else:
        doc = None

    if "library_call" in attrs:
        library_call = attrs["library_call"]
        assert isinstance(library_call, StringAttr)
        del attrs["library_call"]
    else:
        library_call = None

    pos = parser.pos
    if parser.parse_optional_characters("ins"):
        parser.parse_punctuation("(")
        unresolved_ins = parser.parse_comma_separated_list(
            Parser.Delimiter.NONE, parser.parse_unresolved_operand
        )
        parser.parse_punctuation(":")
        ins_types = parser.parse_comma_separated_list(
            Parser.Delimiter.NONE, parser.parse_type
        )
        parser.parse_punctuation(")")
        ins = parser.resolve_operands(unresolved_ins, ins_types, pos)
    else:
        ins = ()

    pos = parser.pos
    if parser.parse_optional_characters("outs"):
        parser.parse_punctuation("(")
        unresolved_outs = parser.parse_comma_separated_list(
            Parser.Delimiter.NONE, parser.parse_unresolved_operand
        )
        parser.parse_punctuation(":")
        outs_types = parser.parse_comma_separated_list(
            Parser.Delimiter.NONE, parser.parse_type
        )
        parser.parse_punctuation(")")
        outs = parser.resolve_operands(unresolved_outs, outs_types, pos)
    else:
        outs_types = ()
        outs = ()

    inits, init_indices = cls._parse_inits(parser)

    if parser.parse_optional_keyword("attrs"):
        parser.parse_punctuation("=")
        extra_attrs = parser.expect(
            parser.parse_optional_attr_dict, "expect extra attributes"
        )
    else:
        extra_attrs = {}

    body = parser.parse_region()

    generic = cls(
        ins,
        outs,
        inits,
        body,
        indexing_maps,
        ArrayAttr(iterator_types),
        bounds,
        ArrayAttr(IntAttr(index) for index in init_indices),
        doc,
        library_call,
    )
    generic.attributes |= attrs
    generic.attributes |= extra_attrs

    return generic

verify_() -> None

Source code in xdsl/dialects/memref_stream.py
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
def verify_(self) -> None:
    if len(self.inits) != len(self.init_indices):
        raise VerifyException(
            f"Mismatching number of inits and init indices: {len(self.inits)} != {self.init_indices}"
        )

    # Parallel iterator types must preceed reduction iterators
    iterator_types = self.iterator_types.data
    num_parallel = iterator_types.count(IteratorTypeAttr.parallel())
    num_reduction = iterator_types.count(IteratorTypeAttr.reduction())
    num_interleaved = iterator_types.count(IteratorTypeAttr.interleaved())

    if IteratorTypeAttr.parallel() in iterator_types[num_parallel:]:
        raise VerifyException(
            f"Unexpected order of iterator types: {[it.data.value for it in iterator_types]}"
        )
    if (
        IteratorTypeAttr.reduction()
        in iterator_types[num_parallel + num_reduction :]
    ):
        raise VerifyException(
            f"Unexpected order of iterator types: {[it.data.value for it in iterator_types]}"
        )
    if num_interleaved > 1:
        raise VerifyException(f"Too many interleaved bounds: {num_interleaved}")
    assert num_parallel + num_reduction + num_interleaved == len(iterator_types)

    if len(self.inputs) + len(self.outputs) != len(self.indexing_maps):
        raise VerifyException(
            "The number of affine maps must match the number of inputs and outputs"
        )

    # Whether or not the operation represents an imperfect loop nest, verify that the
    # bounds of the outer + inner nests match the domain of the input affine maps
    input_count = len(self.inputs)
    input_maps = self.indexing_maps.data[:input_count]

    for i, m in enumerate(input_maps):
        if len(iterator_types) != m.data.num_dims:
            raise VerifyException(f"Invalid number of dims in indexing map {i}")

    # If the operation represents an imperfect loop nest, the bounds must match the
    # number of parallel iterators; otherwise they must match the total number of
    # iterators. In either case, they must all be the same.
    output_count = len(self.outputs)
    output_maps = self.indexing_maps.data[input_count:]

    min_dims = min(m.data.num_dims for m in output_maps)
    max_dims = max(m.data.num_dims for m in output_maps)

    if min_dims != max_dims:
        raise VerifyException(
            "The number of dims in output indexing maps must all be the same"
        )

    if min_dims not in (len(iterator_types), num_parallel + num_interleaved):
        # To signify that the output is imperfectly nested, the output affine map has
        # as many dims as parallel iterators. Otherwise, it has as many dims as
        # the total number of iterators.
        raise VerifyException(
            "The number of dims in output indexing maps must be "
            f"{len(iterator_types)} or {num_parallel + num_interleaved}"
        )

    if len(self.init_indices) != len(self.inits):
        raise VerifyException(
            "The number of inits and init_indices must be the same"
        )

    # The values of the inits must correspond to outputs where the domain of the
    # affine map has the same number of dimensions as the number of parallel
    # iterators.
    num_outputs = len(self.outputs)
    output_maps = self.indexing_maps.data[-num_outputs:]
    for index in self.init_indices:
        if not (0 <= index.data <= num_outputs):
            raise VerifyException(f"Init index out of bounds: {index.data}")
        m = output_maps[index.data]
        if m.data.num_dims != (num_parallel + num_interleaved):
            raise VerifyException(
                "Incompatible affine map and initial value for output at index "
                f"{index}"
            )

    interleave_factor = self.bounds.data[-1].value.data if num_interleaved else 1

    # If the operation is interleaved, use the interleaving factor to check
    # the number of arguments
    init_count = len(self.inits)
    # Outputs with initial values correspond to accumulators in the presence of
    # reduction
    acc_count = output_count if num_reduction else (output_count - init_count)
    expected_block_arg_count = (input_count + acc_count) * interleave_factor

    if expected_block_arg_count != len(self.body.block.args):
        raise VerifyException(
            f"Invalid number of arguments in block ({len(self.body.block.args)}), expected {expected_block_arg_count}"
        )

YieldOp dataclass

Bases: AbstractYieldOperation[Attribute]

Source code in xdsl/dialects/memref_stream.py
924
925
926
927
928
@irdl_op_definition
class YieldOp(AbstractYieldOperation[Attribute]):
    name = "memref_stream.yield"

    traits = traits_def(IsTerminator())

name = 'memref_stream.yield' class-attribute instance-attribute

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

FillOp

Bases: IRDLOperation

Source code in xdsl/dialects/memref_stream.py
931
932
933
934
935
936
937
938
939
940
941
942
943
@irdl_op_definition
class FillOp(IRDLOperation):
    name = "memref_stream.fill"

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

    memref = operand_def(memref.MemRefType.constr(T))
    value = operand_def(T)

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

    def __init__(self, memref: SSAValue, value: SSAValue):
        super().__init__(operands=(memref, value))

name = 'memref_stream.fill' class-attribute instance-attribute

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

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

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

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

__init__(memref: SSAValue, value: SSAValue)

Source code in xdsl/dialects/memref_stream.py
942
943
def __init__(self, memref: SSAValue, value: SSAValue):
    super().__init__(operands=(memref, value))