Skip to content

Convert memref stream to loops

convert_memref_stream_to_loops

LowerGenericOpPattern

Bases: RewritePattern

Source code in xdsl/transforms/convert_memref_stream_to_loops.py
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
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
class LowerGenericOpPattern(RewritePattern):
    @op_type_rewrite_pattern
    def match_and_rewrite(
        self, op: memref_stream.GenericOp, rewriter: PatternRewriter
    ) -> None:
        if memref_stream.IteratorTypeAttr.interleaved() in op.iterator_types:
            interleave_factor = op.bounds.data[-1].value.data
            rewriter.insert_op(
                interleaved_index_ops := tuple(
                    arith.ConstantOp(IntegerAttr.from_index_int_value(i))
                    for i in range(interleave_factor)
                )
            )
            interleaved_index_vals = tuple(op.result for op in interleaved_index_ops)

            def extra_dim(source_index: int) -> tuple[SSAValue] | tuple[()]:
                return (interleaved_index_vals[source_index % interleave_factor],)

        else:
            interleave_factor = 1
            interleaved_index_vals = ()

            def extra_dim(source_index: int) -> tuple[SSAValue] | tuple[()]:
                return ()

        ins_count = len(op.inputs) * interleave_factor

        if any(not isinstance(init, UnitAttr) for init in op.inits):
            constant_vals: list[SSAValue | None] = [None] * len(op.outputs)
            for index, val in zip(op.init_indices, op.inits, strict=True):
                constant_vals[index.data] = val

            def insert_load(
                source_index: int,
                ind_vars: Sequence[SSAValue],
                rewriter: PatternRewriter,
                insertion_point: InsertPoint,
            ) -> SSAValue:
                """
                Inserts a load op or returns an initial value for a given operand of the
                generic operation being lowered.
                If the operation contains an INTERLEAVED iterator type then the body has a
                corresponding factor of duplication of arguments.
                To determine the appropriate operand and indexing map, the source_index is
                divided by the interleave factor.
                """
                source = op.operands[source_index // interleave_factor]
                affine_map_attr = op.indexing_maps.data[
                    source_index // interleave_factor
                ]
                if source_index >= ins_count:
                    constant_val = constant_vals[
                        (source_index - ins_count) // interleave_factor
                    ]
                    if constant_val is not None:
                        return constant_val

                return _insert_load(
                    source_index,
                    source,
                    affine_map_attr,
                    tuple(ind_vars) + extra_dim(source_index),
                    rewriter,
                    insertion_point,
                )

        else:

            def insert_load(
                source_index: int,
                ind_vars: Sequence[SSAValue],
                rewriter: PatternRewriter,
                insertion_point: InsertPoint,
            ) -> SSAValue:
                """
                Inserts a load op for a given operand of the generic operation being
                lowered.
                If the operation contains an INTERLEAVED iterator type then the body has a
                corresponding factor of duplication of arguments.
                To determine the appropriate operand and indexing map, the source_index is
                divided by the interleave factor.
                """
                source = op.operands[source_index // interleave_factor]
                affine_map_attr = op.indexing_maps.data[
                    source_index // interleave_factor
                ]
                return _insert_load(
                    source_index,
                    source,
                    affine_map_attr,
                    tuple(ind_vars) + extra_dim(source_index),
                    rewriter,
                    insertion_point,
                )

        def insert_store(
            source_index: int,
            value: SSAValue,
            ind_vars: Sequence[SSAValue],
            rewriter: PatternRewriter,
            insertion_point: InsertPoint,
        ) -> Operation:
            """
            Inserts a store op for a given operand of the generic operation being lowered.
            If the operation contains an INTERLEAVED iterator
            type then the body has a corresponding factor of duplication of arguments.
            To determine the appropriate operand and indexing map, the source_index is
            divided by the interleave factor.
            """
            nonlocal op
            index = (source_index + ins_count) // interleave_factor
            destination = op.operands[index]
            affine_map = op.indexing_maps.data[index].data
            if isinstance(destination.type, memref.MemRefType):
                indices = indices_for_map(
                    rewriter,
                    insertion_point,
                    affine_map,
                    tuple(ind_vars) + extra_dim(source_index),
                )
                store_op = memref.StoreOp.get(value, destination, indices)
            else:
                store_op = memref_stream.WriteOp(value, destination)
            rewriter.insert_op(store_op, insertion_point)
            return store_op

        outer_ubs, inner_ubs = op.get_static_loop_ranges()
        if inner_ubs:
            # Imperfectly nested
            rewrite_generic_to_imperfect_loops(
                rewriter,
                InsertPoint.before(op),
                outer_ubs,
                inner_ubs,
                op.indexing_maps.data[ins_count:],
                op.indexing_maps.data[:ins_count],
                op.indexing_maps.data[ins_count:],
                op.outputs,
                op.inputs,
                op.outputs,
                op.body.block.args[ins_count:],
                op.body.block.args[:ins_count],
                op.body.block,
                insert_load,
                insert_store,
            )
        else:
            rewrite_generic_to_loops(
                rewriter,
                InsertPoint.before(op),
                outer_ubs,
                op.indexing_maps.data,
                op.indexing_maps.data[-len(op.outputs) :],
                op.operands,
                op.outputs,
                op.body.block,
                insert_load,
                insert_store,
            )

match_and_rewrite(op: memref_stream.GenericOp, rewriter: PatternRewriter) -> None

Source code in xdsl/transforms/convert_memref_stream_to_loops.py
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
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
@op_type_rewrite_pattern
def match_and_rewrite(
    self, op: memref_stream.GenericOp, rewriter: PatternRewriter
) -> None:
    if memref_stream.IteratorTypeAttr.interleaved() in op.iterator_types:
        interleave_factor = op.bounds.data[-1].value.data
        rewriter.insert_op(
            interleaved_index_ops := tuple(
                arith.ConstantOp(IntegerAttr.from_index_int_value(i))
                for i in range(interleave_factor)
            )
        )
        interleaved_index_vals = tuple(op.result for op in interleaved_index_ops)

        def extra_dim(source_index: int) -> tuple[SSAValue] | tuple[()]:
            return (interleaved_index_vals[source_index % interleave_factor],)

    else:
        interleave_factor = 1
        interleaved_index_vals = ()

        def extra_dim(source_index: int) -> tuple[SSAValue] | tuple[()]:
            return ()

    ins_count = len(op.inputs) * interleave_factor

    if any(not isinstance(init, UnitAttr) for init in op.inits):
        constant_vals: list[SSAValue | None] = [None] * len(op.outputs)
        for index, val in zip(op.init_indices, op.inits, strict=True):
            constant_vals[index.data] = val

        def insert_load(
            source_index: int,
            ind_vars: Sequence[SSAValue],
            rewriter: PatternRewriter,
            insertion_point: InsertPoint,
        ) -> SSAValue:
            """
            Inserts a load op or returns an initial value for a given operand of the
            generic operation being lowered.
            If the operation contains an INTERLEAVED iterator type then the body has a
            corresponding factor of duplication of arguments.
            To determine the appropriate operand and indexing map, the source_index is
            divided by the interleave factor.
            """
            source = op.operands[source_index // interleave_factor]
            affine_map_attr = op.indexing_maps.data[
                source_index // interleave_factor
            ]
            if source_index >= ins_count:
                constant_val = constant_vals[
                    (source_index - ins_count) // interleave_factor
                ]
                if constant_val is not None:
                    return constant_val

            return _insert_load(
                source_index,
                source,
                affine_map_attr,
                tuple(ind_vars) + extra_dim(source_index),
                rewriter,
                insertion_point,
            )

    else:

        def insert_load(
            source_index: int,
            ind_vars: Sequence[SSAValue],
            rewriter: PatternRewriter,
            insertion_point: InsertPoint,
        ) -> SSAValue:
            """
            Inserts a load op for a given operand of the generic operation being
            lowered.
            If the operation contains an INTERLEAVED iterator type then the body has a
            corresponding factor of duplication of arguments.
            To determine the appropriate operand and indexing map, the source_index is
            divided by the interleave factor.
            """
            source = op.operands[source_index // interleave_factor]
            affine_map_attr = op.indexing_maps.data[
                source_index // interleave_factor
            ]
            return _insert_load(
                source_index,
                source,
                affine_map_attr,
                tuple(ind_vars) + extra_dim(source_index),
                rewriter,
                insertion_point,
            )

    def insert_store(
        source_index: int,
        value: SSAValue,
        ind_vars: Sequence[SSAValue],
        rewriter: PatternRewriter,
        insertion_point: InsertPoint,
    ) -> Operation:
        """
        Inserts a store op for a given operand of the generic operation being lowered.
        If the operation contains an INTERLEAVED iterator
        type then the body has a corresponding factor of duplication of arguments.
        To determine the appropriate operand and indexing map, the source_index is
        divided by the interleave factor.
        """
        nonlocal op
        index = (source_index + ins_count) // interleave_factor
        destination = op.operands[index]
        affine_map = op.indexing_maps.data[index].data
        if isinstance(destination.type, memref.MemRefType):
            indices = indices_for_map(
                rewriter,
                insertion_point,
                affine_map,
                tuple(ind_vars) + extra_dim(source_index),
            )
            store_op = memref.StoreOp.get(value, destination, indices)
        else:
            store_op = memref_stream.WriteOp(value, destination)
        rewriter.insert_op(store_op, insertion_point)
        return store_op

    outer_ubs, inner_ubs = op.get_static_loop_ranges()
    if inner_ubs:
        # Imperfectly nested
        rewrite_generic_to_imperfect_loops(
            rewriter,
            InsertPoint.before(op),
            outer_ubs,
            inner_ubs,
            op.indexing_maps.data[ins_count:],
            op.indexing_maps.data[:ins_count],
            op.indexing_maps.data[ins_count:],
            op.outputs,
            op.inputs,
            op.outputs,
            op.body.block.args[ins_count:],
            op.body.block.args[:ins_count],
            op.body.block,
            insert_load,
            insert_store,
        )
    else:
        rewrite_generic_to_loops(
            rewriter,
            InsertPoint.before(op),
            outer_ubs,
            op.indexing_maps.data,
            op.indexing_maps.data[-len(op.outputs) :],
            op.operands,
            op.outputs,
            op.body.block,
            insert_load,
            insert_store,
        )

ConvertMemRefStreamToLoopsPass dataclass

Bases: ModulePass

Converts a memref_stream generic to loop.

Source code in xdsl/transforms/convert_memref_stream_to_loops.py
205
206
207
208
209
210
211
212
213
214
215
216
class ConvertMemRefStreamToLoopsPass(ModulePass):
    """
    Converts a memref_stream generic to loop.
    """

    name = "convert-memref-stream-to-loops"

    def apply(self, ctx: Context, op: ModuleOp) -> None:
        PatternRewriteWalker(
            GreedyRewritePatternApplier([LowerGenericOpPattern()]),
            apply_recursively=False,
        ).rewrite_module(op)

name = 'convert-memref-stream-to-loops' class-attribute instance-attribute

apply(ctx: Context, op: ModuleOp) -> None

Source code in xdsl/transforms/convert_memref_stream_to_loops.py
212
213
214
215
216
def apply(self, ctx: Context, op: ModuleOp) -> None:
    PatternRewriteWalker(
        GreedyRewritePatternApplier([LowerGenericOpPattern()]),
        apply_recursively=False,
    ).rewrite_module(op)