160f443bbSAlex Zinenko //===- ParallelLoopTiling.cpp - Tiles scf.parallel ---------------===//
2c25b20c0SAlex Zinenko //
3c25b20c0SAlex Zinenko // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4c25b20c0SAlex Zinenko // See https://llvm.org/LICENSE.txt for license information.
5c25b20c0SAlex Zinenko // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6c25b20c0SAlex Zinenko //
7c25b20c0SAlex Zinenko //===----------------------------------------------------------------------===//
8c25b20c0SAlex Zinenko //
9c25b20c0SAlex Zinenko // This file implements loop tiling on parallel loops.
10c25b20c0SAlex Zinenko //
11c25b20c0SAlex Zinenko //===----------------------------------------------------------------------===//
12c25b20c0SAlex Zinenko 
13c25b20c0SAlex Zinenko #include "PassDetail.h"
14c25b20c0SAlex Zinenko #include "mlir/Dialect/Affine/IR/AffineOps.h"
15c25b20c0SAlex Zinenko #include "mlir/Dialect/SCF/Passes.h"
16c25b20c0SAlex Zinenko #include "mlir/Dialect/SCF/SCF.h"
17c25b20c0SAlex Zinenko #include "mlir/Dialect/SCF/Transforms.h"
1880966447SAlexander Belyaev #include "mlir/Dialect/SCF/Utils.h"
19c25b20c0SAlex Zinenko #include "mlir/Dialect/StandardOps/IR/Ops.h"
20c25b20c0SAlex Zinenko 
21c25b20c0SAlex Zinenko using namespace mlir;
22c25b20c0SAlex Zinenko using namespace mlir::scf;
23c25b20c0SAlex Zinenko 
24c25b20c0SAlex Zinenko /// Tile a parallel loop of the form
2560f443bbSAlex Zinenko ///   scf.parallel (%i0, %i1) = (%arg0, %arg1) to (%arg2, %arg3)
26c25b20c0SAlex Zinenko ///                                            step (%arg4, %arg5)
27c25b20c0SAlex Zinenko ///
28c25b20c0SAlex Zinenko /// into
2960f443bbSAlex Zinenko ///   scf.parallel (%i0, %i1) = (%arg0, %arg1) to (%arg2, %arg3)
30c25b20c0SAlex Zinenko ///                                            step (%arg4*tileSize[0],
31c25b20c0SAlex Zinenko ///                                                  %arg5*tileSize[1])
32cd730816STobias Gysi ///     scf.parallel (%j0, %j1) = (0, 0) to (min(%arg4*tileSize[0], %arg2-%i0)
33cd730816STobias Gysi ///                                          min(%arg5*tileSize[1], %arg3-%i1))
34c25b20c0SAlex Zinenko ///                                      step (%arg4, %arg5)
351e60678cSStephan Herhut ///
361e60678cSStephan Herhut /// where the uses of %i0 and %i1 in the loop body are replaced by
371e60678cSStephan Herhut /// %i0 + j0 and %i1 + %j1.
381e60678cSStephan Herhut //
39c25b20c0SAlex Zinenko /// The old loop is replaced with the new one.
40*09c18a66SAlexander Belyaev std::pair<ParallelOp, ParallelOp>
41*09c18a66SAlexander Belyaev mlir::scf::tileParallelLoop(ParallelOp op, ArrayRef<int64_t> tileSizes) {
42c25b20c0SAlex Zinenko   OpBuilder b(op);
43c25b20c0SAlex Zinenko   auto zero = b.create<ConstantIndexOp>(op.getLoc(), 0);
44c25b20c0SAlex Zinenko   SmallVector<Value, 2> tileSizeConstants;
45c25b20c0SAlex Zinenko   tileSizeConstants.reserve(op.upperBound().size());
46c25b20c0SAlex Zinenko   for (size_t i = 0, end = op.upperBound().size(); i != end; ++i) {
47c25b20c0SAlex Zinenko     if (i < tileSizes.size())
48c25b20c0SAlex Zinenko       tileSizeConstants.push_back(
49c25b20c0SAlex Zinenko           b.create<ConstantIndexOp>(op.getLoc(), tileSizes[i]));
50c25b20c0SAlex Zinenko     else
51c25b20c0SAlex Zinenko       // Just pick 1 for the remaining dimensions.
52c25b20c0SAlex Zinenko       tileSizeConstants.push_back(b.create<ConstantIndexOp>(op.getLoc(), 1));
53c25b20c0SAlex Zinenko   }
54c25b20c0SAlex Zinenko 
55c25b20c0SAlex Zinenko   // Create the outer loop with adjusted steps.
56c25b20c0SAlex Zinenko   SmallVector<Value, 2> newSteps;
57c25b20c0SAlex Zinenko   newSteps.reserve(op.step().size());
58c25b20c0SAlex Zinenko   for (auto step : llvm::zip(op.step(), tileSizeConstants)) {
59c25b20c0SAlex Zinenko     newSteps.push_back(
60c25b20c0SAlex Zinenko         b.create<MulIOp>(op.getLoc(), std::get<0>(step), std::get<1>(step)));
61c25b20c0SAlex Zinenko   }
62c25b20c0SAlex Zinenko   auto outerLoop = b.create<ParallelOp>(op.getLoc(), op.lowerBound(),
63c25b20c0SAlex Zinenko                                         op.upperBound(), newSteps);
64c25b20c0SAlex Zinenko   b.setInsertionPointToStart(outerLoop.getBody());
65c25b20c0SAlex Zinenko 
66c25b20c0SAlex Zinenko   // Compute min(size, dim - offset) to avoid out-of-bounds accesses.
67c25b20c0SAlex Zinenko   // FIXME: Instead of using min, we want to replicate the tail. This would give
68c25b20c0SAlex Zinenko   // the inner loop constant bounds for easy vectorization.
69c25b20c0SAlex Zinenko   auto minMap = AffineMap::get(
70c25b20c0SAlex Zinenko       /*dimCount=*/3, /*symbolCount=*/0,
71c25b20c0SAlex Zinenko       {getAffineDimExpr(/*position=*/0, b.getContext()),
72c25b20c0SAlex Zinenko        getAffineDimExpr(/*position=*/1, b.getContext()) -
73c25b20c0SAlex Zinenko            getAffineDimExpr(/*position=*/2, b.getContext())},
74c25b20c0SAlex Zinenko       b.getContext());
75c25b20c0SAlex Zinenko 
76c25b20c0SAlex Zinenko   // Create the inner loop with adjusted bounds.
77c25b20c0SAlex Zinenko   SmallVector<Value, 2> newBounds;
78c25b20c0SAlex Zinenko   newBounds.reserve(op.upperBound().size());
79cd730816STobias Gysi   for (auto dim : llvm::zip(outerLoop.lowerBound(), outerLoop.upperBound(),
80cd730816STobias Gysi                             outerLoop.step(), outerLoop.getInductionVars(),
81cd730816STobias Gysi                             op.step(), tileSizeConstants)) {
82cd730816STobias Gysi     Value lowerBound, upperBound, newStep, iv, step, tileSizeConstant;
83cd730816STobias Gysi     std::tie(lowerBound, upperBound, newStep, iv, step, tileSizeConstant) = dim;
84cd730816STobias Gysi     // Collect the statically known loop bounds
85cd730816STobias Gysi     auto lowerBoundConstant =
86cd730816STobias Gysi         dyn_cast_or_null<ConstantIndexOp>(lowerBound.getDefiningOp());
87cd730816STobias Gysi     auto upperBoundConstant =
88cd730816STobias Gysi         dyn_cast_or_null<ConstantIndexOp>(upperBound.getDefiningOp());
89cd730816STobias Gysi     auto stepConstant = dyn_cast_or_null<ConstantIndexOp>(step.getDefiningOp());
90cd730816STobias Gysi     auto tileSize =
91cd730816STobias Gysi         cast<ConstantIndexOp>(tileSizeConstant.getDefiningOp()).getValue();
92cd730816STobias Gysi     // If the loop bounds and the loop step are constant and if the number of
93cd730816STobias Gysi     // loop iterations is an integer multiple of the tile size, we use a static
94cd730816STobias Gysi     // bound for the inner loop.
95cd730816STobias Gysi     if (lowerBoundConstant && upperBoundConstant && stepConstant) {
96cd730816STobias Gysi       auto numIterations = llvm::divideCeil(upperBoundConstant.getValue() -
97cd730816STobias Gysi                                                 lowerBoundConstant.getValue(),
98cd730816STobias Gysi                                             stepConstant.getValue());
99cd730816STobias Gysi       if (numIterations % tileSize == 0) {
100cd730816STobias Gysi         newBounds.push_back(newStep);
101cd730816STobias Gysi         continue;
102cd730816STobias Gysi       }
103cd730816STobias Gysi     }
104cd730816STobias Gysi     // Otherwise, we dynamically compute the bound for
105cd730816STobias Gysi     // each iteration of the outer loop.
106cd730816STobias Gysi     newBounds.push_back(
107cd730816STobias Gysi         b.create<AffineMinOp>(op.getLoc(), b.getIndexType(), minMap,
108cd730816STobias Gysi                               ValueRange{newStep, upperBound, iv}));
109c25b20c0SAlex Zinenko   }
110c25b20c0SAlex Zinenko   auto innerLoop = b.create<ParallelOp>(
111c25b20c0SAlex Zinenko       op.getLoc(), SmallVector<Value, 2>(newBounds.size(), zero), newBounds,
112c25b20c0SAlex Zinenko       op.step());
113c25b20c0SAlex Zinenko 
114c25b20c0SAlex Zinenko   // Steal the body of the old parallel loop and erase it.
115c25b20c0SAlex Zinenko   innerLoop.region().takeBody(op.region());
1161e60678cSStephan Herhut 
1171e60678cSStephan Herhut   // Insert computation for new index vectors and replace uses.
1181e60678cSStephan Herhut   b.setInsertionPointToStart(innerLoop.getBody());
1191e60678cSStephan Herhut   for (auto ivs :
1201e60678cSStephan Herhut        llvm::zip(innerLoop.getInductionVars(), outerLoop.getInductionVars())) {
1211e60678cSStephan Herhut     Value inner_index = std::get<0>(ivs);
1221e60678cSStephan Herhut     AddIOp newIndex =
1231e60678cSStephan Herhut         b.create<AddIOp>(op.getLoc(), std::get<0>(ivs), std::get<1>(ivs));
1241e60678cSStephan Herhut     inner_index.replaceAllUsesExcept(
1251e60678cSStephan Herhut         newIndex, SmallPtrSet<Operation *, 1>{newIndex.getOperation()});
1261e60678cSStephan Herhut   }
1271e60678cSStephan Herhut 
128c25b20c0SAlex Zinenko   op.erase();
129*09c18a66SAlexander Belyaev   return std::make_pair(outerLoop, innerLoop);
130c25b20c0SAlex Zinenko }
131c25b20c0SAlex Zinenko 
132c25b20c0SAlex Zinenko namespace {
133c25b20c0SAlex Zinenko struct ParallelLoopTiling
1344bcd08ebSStephan Herhut     : public SCFParallelLoopTilingBase<ParallelLoopTiling> {
135c25b20c0SAlex Zinenko   ParallelLoopTiling() = default;
136c25b20c0SAlex Zinenko   explicit ParallelLoopTiling(ArrayRef<int64_t> tileSizes) {
137c25b20c0SAlex Zinenko     this->tileSizes = tileSizes;
138c25b20c0SAlex Zinenko   }
139c25b20c0SAlex Zinenko 
140c25b20c0SAlex Zinenko   void runOnFunction() override {
1416484567fSFrederik Gossen     SmallVector<ParallelOp, 2> innermostPloops;
14280966447SAlexander Belyaev     getInnermostParallelLoops(getFunction().getOperation(), innermostPloops);
1436484567fSFrederik Gossen     for (ParallelOp ploop : innermostPloops) {
144cd730816STobias Gysi       // FIXME: Add reduction support.
1456484567fSFrederik Gossen       if (ploop.getNumReductions() == 0)
1466484567fSFrederik Gossen         tileParallelLoop(ploop, tileSizes);
147c25b20c0SAlex Zinenko     }
148c25b20c0SAlex Zinenko   }
149c25b20c0SAlex Zinenko };
150c25b20c0SAlex Zinenko } // namespace
151c25b20c0SAlex Zinenko 
152c25b20c0SAlex Zinenko std::unique_ptr<Pass>
153c25b20c0SAlex Zinenko mlir::createParallelLoopTilingPass(ArrayRef<int64_t> tileSizes) {
154c25b20c0SAlex Zinenko   return std::make_unique<ParallelLoopTiling>(tileSizes);
155c25b20c0SAlex Zinenko }
156