Skip to content

Loop nest lowering utils

loop_nest_lowering_utils

INSERT_LOAD: TypeAlias = Callable[[int, Sequence[SSAValue], PatternRewriter, InsertPoint], SSAValue] module-attribute

INSERT_STORE: TypeAlias = Callable[[int, SSAValue, Sequence[SSAValue], PatternRewriter, InsertPoint], Operation] module-attribute

indices_for_map(rewriter: PatternRewriter, insertion_point: InsertPoint, affine_map: AffineMap, input_index_vals: Sequence[SSAValue]) -> Sequence[SSAValue]

Given an affine map mapping iteration indices to indices to a memref, return the indices into the corresponding memref. The number of returned SSA values corresponds to the number of results of the affine map. If the result is an affine dimension expression, then return the corresponding input index. Otherwise, add an affine.apply operation that calculates the indices, reducing the expression to only the relevant dimensions.

For example, the map (d0, d1, d2, d3) -> (d0 + d2) when applied to indices (a, b, c, d) is transformed to the map (d0, d1) -> (d0 + d1) when applied to indices (a, c).

The affine.apply operations are inserted before target_op.

Source code in xdsl/transforms/loop_nest_lowering_utils.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def indices_for_map(
    rewriter: PatternRewriter,
    insertion_point: InsertPoint,
    affine_map: AffineMap,
    input_index_vals: Sequence[SSAValue],
) -> Sequence[SSAValue]:
    """
    Given an affine map mapping iteration indices to indices to a memref, return the
    indices into the corresponding memref. The number of returned SSA values corresponds
    to the number of results of the affine map. If the result is an affine dimension
    expression, then return the corresponding input index. Otherwise, add an
    `affine.apply` operation that calculates the indices, reducing the expression to only
    the relevant dimensions.

    For example, the map `(d0, d1, d2, d3) -> (d0 + d2)` when applied to indices
    `(a, b, c, d)` is transformed to the map `(d0, d1) -> (d0 + d1)` when applied to
    indices `(a, c)`.

    The `affine.apply` operations are inserted before `target_op`.
    """
    if affine_map.num_symbols:
        raise NotImplementedError("Cannot create indices for affine map with symbols")
    output_indices: list[SSAValue] = []
    for expr in affine_map.results:
        if isinstance(expr, AffineDimExpr):
            output_indices.append(input_index_vals[expr.position])
        else:
            used_dims = expr.used_dims()
            new_index_vals = input_index_vals
            new_affine_map = AffineMap(
                affine_map.num_dims, affine_map.num_symbols, (expr,)
            )
            if len(used_dims) != affine_map.num_dims:
                # Remove unused dims
                # used_dims = affine_map.used_dims_bit_vector()
                used_dims_vector = tuple(
                    dim in used_dims for dim in range(affine_map.num_dims)
                )
                unused_dims_vector = tuple(
                    not used_dim for used_dim in used_dims_vector
                )
                new_index_vals = tuple(compress(new_index_vals, used_dims_vector))
                new_affine_map = new_affine_map.drop_dims(unused_dims_vector)

            rewriter.insert_op(
                apply_op := affine.ApplyOp(
                    new_index_vals,
                    AffineMapAttr(new_affine_map),
                ),
                insertion_point,
            )

            output_indices.append(apply_op.result)

    return output_indices

rewrite_generic_to_loops(rewriter: PatternRewriter, insertion_point: InsertPoint, ubs: Sequence[int], load_indexing_maps: Sequence[AffineMapAttr], store_indexing_maps: Sequence[AffineMapAttr], load_operands: Sequence[SSAValue], store_operands: Sequence[SSAValue], block: Block, insert_load: INSERT_LOAD, insert_store: INSERT_STORE) -> None

Source code in xdsl/transforms/loop_nest_lowering_utils.py
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
def rewrite_generic_to_loops(
    rewriter: PatternRewriter,
    insertion_point: InsertPoint,
    ubs: Sequence[int],
    load_indexing_maps: Sequence[AffineMapAttr],
    store_indexing_maps: Sequence[AffineMapAttr],
    load_operands: Sequence[SSAValue],
    store_operands: Sequence[SSAValue],
    block: Block,
    insert_load: INSERT_LOAD,
    insert_store: INSERT_STORE,
) -> None:
    # Create loop nest lb (0), step (1), and ubs
    # ubs are calculated from affine maps and memref dimensions

    bound_constant_ops = tuple(
        arith.ConstantOp(IntegerAttr.from_index_int_value(ub)) for ub in ubs
    )
    rewriter.insert_op(bound_constant_ops)
    bound_constant_values = tuple(op.result for op in bound_constant_ops)

    zero_op = arith.ConstantOp(IntegerAttr.from_index_int_value(0))
    one_op = arith.ConstantOp(IntegerAttr.from_index_int_value(1))
    if bound_constant_values:
        rewriter.insert_op((zero_op, one_op))

    def make_body(
        rewriter: PatternRewriter,
        insertion_point: InsertPoint,
        ind_vars: Sequence[BlockArgument],
        iter_args: Sequence[SSAValue],
    ) -> Sequence[SSAValue]:
        assert not iter_args

        loaded_values = _insert_load_ops(
            rewriter,
            insertion_point,
            ind_vars,
            load_indexing_maps,
            load_operands,
            block.args,
            insert_load,
        )

        for i, val in loaded_values:
            block.args[i].replace_all_uses_with(val)

        yield_op = block.last_op
        assert yield_op is not None

        # Erase the yield op, we still have access to its operands
        rewriter.erase_op(yield_op)

        while block.args:
            rewriter.erase_block_argument(block.args[0])

        rewriter.inline_block(block, insertion_point)

        _insert_store_ops(
            rewriter,
            insertion_point,
            ind_vars,
            yield_op.operands,
            insert_store,
        )

        return ()

    _insert_loop_nest(
        rewriter,
        insertion_point,
        zero_op,
        one_op,
        bound_constant_values,
        (),
        make_body,
    )

    rewriter.erase_op(rewriter.current_operation)

rewrite_generic_to_imperfect_loops(rewriter: PatternRewriter, insertion_point: InsertPoint, outer_ubs: Sequence[int], inner_ubs: Sequence[int], outer_load_indexing_maps: Sequence[AffineMapAttr], inner_load_indexing_maps: Sequence[AffineMapAttr], store_indexing_maps: Sequence[AffineMapAttr], outer_load_operands: Sequence[SSAValue], inner_load_operands: Sequence[SSAValue], store_operands: Sequence[SSAValue], outer_load_block_args: Sequence[BlockArgument], inner_load_block_args: Sequence[BlockArgument], block: Block, insert_load: INSERT_LOAD, insert_store: INSERT_STORE) -> None

Source code in xdsl/transforms/loop_nest_lowering_utils.py
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
def rewrite_generic_to_imperfect_loops(
    rewriter: PatternRewriter,
    insertion_point: InsertPoint,
    outer_ubs: Sequence[int],
    inner_ubs: Sequence[int],
    outer_load_indexing_maps: Sequence[AffineMapAttr],
    inner_load_indexing_maps: Sequence[AffineMapAttr],
    store_indexing_maps: Sequence[AffineMapAttr],
    outer_load_operands: Sequence[SSAValue],
    inner_load_operands: Sequence[SSAValue],
    store_operands: Sequence[SSAValue],
    outer_load_block_args: Sequence[BlockArgument],
    inner_load_block_args: Sequence[BlockArgument],
    block: Block,
    insert_load: INSERT_LOAD,
    insert_store: INSERT_STORE,
) -> None:
    # Create loop nest lb (0), step (1), and ubs
    # ubs are calculated from affine maps and memref dimensions

    outer_bound_constant_ops = tuple(
        arith.ConstantOp(IntegerAttr.from_index_int_value(ub)) for ub in outer_ubs
    )
    inner_bound_constant_ops = tuple(
        arith.ConstantOp(IntegerAttr.from_index_int_value(ub)) for ub in inner_ubs
    )
    rewriter.insert_op(outer_bound_constant_ops, insertion_point)
    rewriter.insert_op(inner_bound_constant_ops, insertion_point)
    outer_bound_constant_values = tuple(op.result for op in outer_bound_constant_ops)
    inner_bound_constant_values = tuple(op.result for op in inner_bound_constant_ops)

    zero_op = arith.ConstantOp(IntegerAttr.from_index_int_value(0))
    one_op = arith.ConstantOp(IntegerAttr.from_index_int_value(1))
    if outer_bound_constant_values or inner_bound_constant_values:
        rewriter.insert_op((zero_op, one_op))

    def outer_make_body(
        rewriter: PatternRewriter,
        insertion_point: InsertPoint,
        outer_ind_vars: Sequence[BlockArgument],
        outer_iter_args: Sequence[SSAValue],
    ) -> Sequence[SSAValue]:
        assert not outer_iter_args

        # Add load ops
        outer_loaded_values = _insert_load_ops(
            rewriter,
            insertion_point,
            outer_ind_vars,
            outer_load_indexing_maps,
            outer_load_operands,
            outer_load_block_args,
            insert_load,
            index_increment=len(inner_load_block_args),
        )

        def inner_make_body(
            rewriter: PatternRewriter,
            insertion_point: InsertPoint,
            inner_ind_vars: Sequence[BlockArgument],
            inner_iter_args: Sequence[SSAValue],
        ):
            # Add load ops
            inner_loaded_values = _insert_load_ops(
                rewriter,
                insertion_point,
                (*outer_ind_vars, *inner_ind_vars),
                inner_load_indexing_maps,
                inner_load_operands,
                inner_load_block_args,
                insert_load,
            )

            # Replace block argument use with iter args
            for (i, _), arg in zip(
                outer_loaded_values,
                inner_iter_args,
                strict=True,
            ):
                block.args[i].replace_all_uses_with(arg)

            # Replace block argument use with load op results
            for i, val in inner_loaded_values:
                block.args[i].replace_all_uses_with(val)

            yield_op = block.last_op
            assert yield_op is not None

            # Erase the yield op, we still have access to its operands
            rewriter.erase_op(yield_op)

            # Inline generic body into innermost scf loop
            # The operands have already been remapped

            while block.args:
                rewriter.erase_block_argument(block.args[0])

            rewriter.inline_block(block, insertion_point)

            return yield_op.operands

        # Insert inner loop nest, from the outtermost loop inwards
        inner_loop_nest_results = _insert_loop_nest(
            rewriter,
            insertion_point,
            zero_op,
            one_op,
            inner_bound_constant_values,
            tuple(val for _, val in outer_loaded_values),
            inner_make_body,
        )

        # Finally, add store ops
        _insert_store_ops(
            rewriter,
            insertion_point,
            outer_ind_vars,
            inner_loop_nest_results,
            insert_store,
        )

        return ()

    # Insert outer loop nest, from the outtermost loop inwards
    _insert_loop_nest(
        rewriter,
        insertion_point,
        zero_op,
        one_op,
        outer_bound_constant_values,
        (),
        outer_make_body,
    )

    rewriter.erase_op(rewriter.current_operation)