xref: /llvm-project/mlir/lib/Dialect/Async/Transforms/AsyncParallelFor.cpp (revision 09dfc5713d7e2342bea4c8447d1ed76c85eb8225)
1c30ab6c2SEugene Zhulenev //===- AsyncParallelFor.cpp - Implementation of Async Parallel For --------===//
2c30ab6c2SEugene Zhulenev //
3c30ab6c2SEugene Zhulenev // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4c30ab6c2SEugene Zhulenev // See https://llvm.org/LICENSE.txt for license information.
5c30ab6c2SEugene Zhulenev // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6c30ab6c2SEugene Zhulenev //
7c30ab6c2SEugene Zhulenev //===----------------------------------------------------------------------===//
8c30ab6c2SEugene Zhulenev //
986ad0af8SEugene Zhulenev // This file implements scf.parallel to scf.for + async.execute conversion pass.
10c30ab6c2SEugene Zhulenev //
11c30ab6c2SEugene Zhulenev //===----------------------------------------------------------------------===//
12c30ab6c2SEugene Zhulenev 
1367d0d7acSMichele Scuttari #include "mlir/Dialect/Async/Passes.h"
141fc096afSMehdi Amini 
15c30ab6c2SEugene Zhulenev #include "PassDetail.h"
16abc362a1SJakub Kuderski #include "mlir/Dialect/Arith/IR/Arith.h"
17c30ab6c2SEugene Zhulenev #include "mlir/Dialect/Async/IR/Async.h"
18ec0e4545Sbakhtiyar #include "mlir/Dialect/Async/Transforms.h"
1923aa5a74SRiver Riddle #include "mlir/Dialect/Func/IR/FuncOps.h"
208b68da2cSAlex Zinenko #include "mlir/Dialect/SCF/IR/SCF.h"
214d67b278SJeff Niu #include "mlir/IR/IRMapping.h"
2286ad0af8SEugene Zhulenev #include "mlir/IR/ImplicitLocOpBuilder.h"
239f151b78SEugene Zhulenev #include "mlir/IR/Matchers.h"
24c30ab6c2SEugene Zhulenev #include "mlir/IR/PatternMatch.h"
25149311b4Sbakhtiyar #include "mlir/Support/LLVM.h"
26c30ab6c2SEugene Zhulenev #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
2786ad0af8SEugene Zhulenev #include "mlir/Transforms/RegionUtils.h"
2867d0d7acSMichele Scuttari #include <utility>
2967d0d7acSMichele Scuttari 
3067d0d7acSMichele Scuttari namespace mlir {
3167d0d7acSMichele Scuttari #define GEN_PASS_DEF_ASYNCPARALLELFOR
3267d0d7acSMichele Scuttari #include "mlir/Dialect/Async/Passes.h.inc"
3367d0d7acSMichele Scuttari } // namespace mlir
34c30ab6c2SEugene Zhulenev 
35c30ab6c2SEugene Zhulenev using namespace mlir;
36c30ab6c2SEugene Zhulenev using namespace mlir::async;
37c30ab6c2SEugene Zhulenev 
38c30ab6c2SEugene Zhulenev #define DEBUG_TYPE "async-parallel-for"
39c30ab6c2SEugene Zhulenev 
40c30ab6c2SEugene Zhulenev namespace {
41c30ab6c2SEugene Zhulenev 
42c30ab6c2SEugene Zhulenev // Rewrite scf.parallel operation into multiple concurrent async.execute
43c30ab6c2SEugene Zhulenev // operations over non overlapping subranges of the original loop.
44c30ab6c2SEugene Zhulenev //
45c30ab6c2SEugene Zhulenev // Example:
46c30ab6c2SEugene Zhulenev //
4786ad0af8SEugene Zhulenev //   scf.parallel (%i, %j) = (%lbi, %lbj) to (%ubi, %ubj) step (%si, %sj) {
48c30ab6c2SEugene Zhulenev //     "do_some_compute"(%i, %j): () -> ()
49c30ab6c2SEugene Zhulenev //   }
50c30ab6c2SEugene Zhulenev //
51c30ab6c2SEugene Zhulenev // Converted to:
52c30ab6c2SEugene Zhulenev //
5386ad0af8SEugene Zhulenev //   // Parallel compute function that executes the parallel body region for
5486ad0af8SEugene Zhulenev //   // a subset of the parallel iteration space defined by the one-dimensional
5586ad0af8SEugene Zhulenev //   // compute block index.
5686ad0af8SEugene Zhulenev //   func parallel_compute_function(%block_index : index, %block_size : index,
5786ad0af8SEugene Zhulenev //                                  <parallel operation properties>, ...) {
5886ad0af8SEugene Zhulenev //     // Compute multi-dimensional loop bounds for %block_index.
5986ad0af8SEugene Zhulenev //     %block_lbi, %block_lbj = ...
6086ad0af8SEugene Zhulenev //     %block_ubi, %block_ubj = ...
61c30ab6c2SEugene Zhulenev //
6286ad0af8SEugene Zhulenev //     // Clone parallel operation body into the scf.for loop nest.
6386ad0af8SEugene Zhulenev //     scf.for %i = %blockLbi to %blockUbi {
6486ad0af8SEugene Zhulenev //       scf.for %j = block_lbj to %block_ubj {
65c30ab6c2SEugene Zhulenev //         "do_some_compute"(%i, %j): () -> ()
66c30ab6c2SEugene Zhulenev //       }
67c30ab6c2SEugene Zhulenev //     }
68c30ab6c2SEugene Zhulenev //   }
69c30ab6c2SEugene Zhulenev //
7086ad0af8SEugene Zhulenev // And a dispatch function depending on the `asyncDispatch` option.
7186ad0af8SEugene Zhulenev //
7286ad0af8SEugene Zhulenev // When async dispatch is on: (pseudocode)
7386ad0af8SEugene Zhulenev //
7486ad0af8SEugene Zhulenev //   %block_size = ... compute parallel compute block size
7586ad0af8SEugene Zhulenev //   %block_count = ... compute the number of compute blocks
7686ad0af8SEugene Zhulenev //
7786ad0af8SEugene Zhulenev //   func @async_dispatch(%block_start : index, %block_end : index, ...) {
7886ad0af8SEugene Zhulenev //     // Keep splitting block range until we reached a range of size 1.
7986ad0af8SEugene Zhulenev //     while (%block_end - %block_start > 1) {
8086ad0af8SEugene Zhulenev //       %mid_index = block_start + (block_end - block_start) / 2;
8186ad0af8SEugene Zhulenev //       async.execute { call @async_dispatch(%mid_index, %block_end); }
8286ad0af8SEugene Zhulenev //       %block_end = %mid_index
83c30ab6c2SEugene Zhulenev //     }
84c30ab6c2SEugene Zhulenev //
8586ad0af8SEugene Zhulenev //     // Call parallel compute function for a single block.
8686ad0af8SEugene Zhulenev //     call @parallel_compute_fn(%block_start, %block_size, ...);
8786ad0af8SEugene Zhulenev //   }
88c30ab6c2SEugene Zhulenev //
8986ad0af8SEugene Zhulenev //   // Launch async dispatch for [0, block_count) range.
9086ad0af8SEugene Zhulenev //   call @async_dispatch(%c0, %block_count);
91c30ab6c2SEugene Zhulenev //
9286ad0af8SEugene Zhulenev // When async dispatch is off:
93c30ab6c2SEugene Zhulenev //
9486ad0af8SEugene Zhulenev //   %block_size = ... compute parallel compute block size
9586ad0af8SEugene Zhulenev //   %block_count = ... compute the number of compute blocks
9686ad0af8SEugene Zhulenev //
9786ad0af8SEugene Zhulenev //   scf.for %block_index = %c0 to %block_count {
9886ad0af8SEugene Zhulenev //      call @parallel_compute_fn(%block_index, %block_size, ...)
9986ad0af8SEugene Zhulenev //   }
10086ad0af8SEugene Zhulenev //
10186ad0af8SEugene Zhulenev struct AsyncParallelForPass
10267d0d7acSMichele Scuttari     : public impl::AsyncParallelForBase<AsyncParallelForPass> {
10386ad0af8SEugene Zhulenev   AsyncParallelForPass() = default;
10434a164c9SEugene Zhulenev 
10534a164c9SEugene Zhulenev   AsyncParallelForPass(bool asyncDispatch, int32_t numWorkerThreads,
10655dfab39Sbakhtiyar                        int32_t minTaskSize) {
10734a164c9SEugene Zhulenev     this->asyncDispatch = asyncDispatch;
10834a164c9SEugene Zhulenev     this->numWorkerThreads = numWorkerThreads;
10955dfab39Sbakhtiyar     this->minTaskSize = minTaskSize;
11034a164c9SEugene Zhulenev   }
11134a164c9SEugene Zhulenev 
11286ad0af8SEugene Zhulenev   void runOnOperation() override;
11386ad0af8SEugene Zhulenev };
11486ad0af8SEugene Zhulenev 
115c30ab6c2SEugene Zhulenev struct AsyncParallelForRewrite : public OpRewritePattern<scf::ParallelOp> {
116c30ab6c2SEugene Zhulenev public:
117ec0e4545Sbakhtiyar   AsyncParallelForRewrite(
118ec0e4545Sbakhtiyar       MLIRContext *ctx, bool asyncDispatch, int32_t numWorkerThreads,
119ec0e4545Sbakhtiyar       AsyncMinTaskSizeComputationFunction computeMinTaskSize)
12086ad0af8SEugene Zhulenev       : OpRewritePattern(ctx), asyncDispatch(asyncDispatch),
121ec0e4545Sbakhtiyar         numWorkerThreads(numWorkerThreads),
1221fc096afSMehdi Amini         computeMinTaskSize(std::move(computeMinTaskSize)) {}
123c30ab6c2SEugene Zhulenev 
124c30ab6c2SEugene Zhulenev   LogicalResult matchAndRewrite(scf::ParallelOp op,
125c30ab6c2SEugene Zhulenev                                 PatternRewriter &rewriter) const override;
126c30ab6c2SEugene Zhulenev 
127c30ab6c2SEugene Zhulenev private:
12886ad0af8SEugene Zhulenev   bool asyncDispatch;
12986ad0af8SEugene Zhulenev   int32_t numWorkerThreads;
130ec0e4545Sbakhtiyar   AsyncMinTaskSizeComputationFunction computeMinTaskSize;
131c30ab6c2SEugene Zhulenev };
132c30ab6c2SEugene Zhulenev 
13386ad0af8SEugene Zhulenev struct ParallelComputeFunctionType {
13486ad0af8SEugene Zhulenev   FunctionType type;
1359f151b78SEugene Zhulenev   SmallVector<Value> captures;
1369f151b78SEugene Zhulenev };
1379f151b78SEugene Zhulenev 
1389f151b78SEugene Zhulenev // Helper struct to parse parallel compute function argument list.
1399f151b78SEugene Zhulenev struct ParallelComputeFunctionArgs {
1409f151b78SEugene Zhulenev   BlockArgument blockIndex();
1419f151b78SEugene Zhulenev   BlockArgument blockSize();
1429f151b78SEugene Zhulenev   ArrayRef<BlockArgument> tripCounts();
1439f151b78SEugene Zhulenev   ArrayRef<BlockArgument> lowerBounds();
1449f151b78SEugene Zhulenev   ArrayRef<BlockArgument> steps();
1459f151b78SEugene Zhulenev   ArrayRef<BlockArgument> captures();
1469f151b78SEugene Zhulenev 
1479f151b78SEugene Zhulenev   unsigned numLoops;
1489f151b78SEugene Zhulenev   ArrayRef<BlockArgument> args;
1499f151b78SEugene Zhulenev };
1509f151b78SEugene Zhulenev 
1519f151b78SEugene Zhulenev struct ParallelComputeFunctionBounds {
1529f151b78SEugene Zhulenev   SmallVector<IntegerAttr> tripCounts;
1539f151b78SEugene Zhulenev   SmallVector<IntegerAttr> lowerBounds;
1549f151b78SEugene Zhulenev   SmallVector<IntegerAttr> upperBounds;
1559f151b78SEugene Zhulenev   SmallVector<IntegerAttr> steps;
15686ad0af8SEugene Zhulenev };
15786ad0af8SEugene Zhulenev 
15886ad0af8SEugene Zhulenev struct ParallelComputeFunction {
1599f151b78SEugene Zhulenev   unsigned numLoops;
16058ceae95SRiver Riddle   func::FuncOp func;
16186ad0af8SEugene Zhulenev   llvm::SmallVector<Value> captures;
162c30ab6c2SEugene Zhulenev };
163c30ab6c2SEugene Zhulenev 
164c30ab6c2SEugene Zhulenev } // namespace
165c30ab6c2SEugene Zhulenev 
1669f151b78SEugene Zhulenev BlockArgument ParallelComputeFunctionArgs::blockIndex() { return args[0]; }
1679f151b78SEugene Zhulenev BlockArgument ParallelComputeFunctionArgs::blockSize() { return args[1]; }
1689f151b78SEugene Zhulenev 
1699f151b78SEugene Zhulenev ArrayRef<BlockArgument> ParallelComputeFunctionArgs::tripCounts() {
1709f151b78SEugene Zhulenev   return args.drop_front(2).take_front(numLoops);
1719f151b78SEugene Zhulenev }
1729f151b78SEugene Zhulenev 
1739f151b78SEugene Zhulenev ArrayRef<BlockArgument> ParallelComputeFunctionArgs::lowerBounds() {
1749f151b78SEugene Zhulenev   return args.drop_front(2 + 1 * numLoops).take_front(numLoops);
1759f151b78SEugene Zhulenev }
1769f151b78SEugene Zhulenev 
1779f151b78SEugene Zhulenev ArrayRef<BlockArgument> ParallelComputeFunctionArgs::steps() {
1789f151b78SEugene Zhulenev   return args.drop_front(2 + 3 * numLoops).take_front(numLoops);
1799f151b78SEugene Zhulenev }
1809f151b78SEugene Zhulenev 
1819f151b78SEugene Zhulenev ArrayRef<BlockArgument> ParallelComputeFunctionArgs::captures() {
1829f151b78SEugene Zhulenev   return args.drop_front(2 + 4 * numLoops);
1839f151b78SEugene Zhulenev }
1849f151b78SEugene Zhulenev 
1859f151b78SEugene Zhulenev template <typename ValueRange>
1869f151b78SEugene Zhulenev static SmallVector<IntegerAttr> integerConstants(ValueRange values) {
1879f151b78SEugene Zhulenev   SmallVector<IntegerAttr> attrs(values.size());
1889f151b78SEugene Zhulenev   for (unsigned i = 0; i < values.size(); ++i)
1899f151b78SEugene Zhulenev     matchPattern(values[i], m_Constant(&attrs[i]));
1909f151b78SEugene Zhulenev   return attrs;
1919f151b78SEugene Zhulenev }
1929f151b78SEugene Zhulenev 
19386ad0af8SEugene Zhulenev // Converts one-dimensional iteration index in the [0, tripCount) interval
19486ad0af8SEugene Zhulenev // into multidimensional iteration coordinate.
19586ad0af8SEugene Zhulenev static SmallVector<Value> delinearize(ImplicitLocOpBuilder &b, Value index,
19634a164c9SEugene Zhulenev                                       ArrayRef<Value> tripCounts) {
19786ad0af8SEugene Zhulenev   SmallVector<Value> coords(tripCounts.size());
19886ad0af8SEugene Zhulenev   assert(!tripCounts.empty() && "tripCounts must be not empty");
19986ad0af8SEugene Zhulenev 
20086ad0af8SEugene Zhulenev   for (ssize_t i = tripCounts.size() - 1; i >= 0; --i) {
201a54f4eaeSMogball     coords[i] = b.create<arith::RemSIOp>(index, tripCounts[i]);
202a54f4eaeSMogball     index = b.create<arith::DivSIOp>(index, tripCounts[i]);
20386ad0af8SEugene Zhulenev   }
20486ad0af8SEugene Zhulenev 
20586ad0af8SEugene Zhulenev   return coords;
20686ad0af8SEugene Zhulenev }
20786ad0af8SEugene Zhulenev 
20886ad0af8SEugene Zhulenev // Returns a function type and implicit captures for a parallel compute
20986ad0af8SEugene Zhulenev // function. We'll need a list of implicit captures to setup block and value
21086ad0af8SEugene Zhulenev // mapping when we'll clone the body of the parallel operation.
21186ad0af8SEugene Zhulenev static ParallelComputeFunctionType
21286ad0af8SEugene Zhulenev getParallelComputeFunctionType(scf::ParallelOp op, PatternRewriter &rewriter) {
21386ad0af8SEugene Zhulenev   // Values implicitly captured by the parallel operation.
21486ad0af8SEugene Zhulenev   llvm::SetVector<Value> captures;
215c0342a2dSJacques Pienaar   getUsedValuesDefinedAbove(op.getRegion(), op.getRegion(), captures);
21686ad0af8SEugene Zhulenev 
2179f151b78SEugene Zhulenev   SmallVector<Type> inputs;
21886ad0af8SEugene Zhulenev   inputs.reserve(2 + 4 * op.getNumLoops() + captures.size());
21986ad0af8SEugene Zhulenev 
22086ad0af8SEugene Zhulenev   Type indexTy = rewriter.getIndexType();
22186ad0af8SEugene Zhulenev 
22286ad0af8SEugene Zhulenev   // One-dimensional iteration space defined by the block index and size.
22386ad0af8SEugene Zhulenev   inputs.push_back(indexTy); // blockIndex
22486ad0af8SEugene Zhulenev   inputs.push_back(indexTy); // blockSize
22586ad0af8SEugene Zhulenev 
22686ad0af8SEugene Zhulenev   // Multi-dimensional parallel iteration space defined by the loop trip counts.
22786ad0af8SEugene Zhulenev   for (unsigned i = 0; i < op.getNumLoops(); ++i)
22886ad0af8SEugene Zhulenev     inputs.push_back(indexTy); // loop tripCount
22986ad0af8SEugene Zhulenev 
2309f151b78SEugene Zhulenev   // Parallel operation lower bound, upper bound and step. Lower bound, upper
2319f151b78SEugene Zhulenev   // bound and step passed as contiguous arguments:
2329f151b78SEugene Zhulenev   //   call @compute(%lb0, %lb1, ..., %ub0, %ub1, ..., %step0, %step1, ...)
23386ad0af8SEugene Zhulenev   for (unsigned i = 0; i < op.getNumLoops(); ++i) {
23486ad0af8SEugene Zhulenev     inputs.push_back(indexTy); // lower bound
23586ad0af8SEugene Zhulenev     inputs.push_back(indexTy); // upper bound
23686ad0af8SEugene Zhulenev     inputs.push_back(indexTy); // step
23786ad0af8SEugene Zhulenev   }
23886ad0af8SEugene Zhulenev 
23986ad0af8SEugene Zhulenev   // Types of the implicit captures.
24086ad0af8SEugene Zhulenev   for (Value capture : captures)
24186ad0af8SEugene Zhulenev     inputs.push_back(capture.getType());
24286ad0af8SEugene Zhulenev 
24386ad0af8SEugene Zhulenev   // Convert captures to vector for later convenience.
24486ad0af8SEugene Zhulenev   SmallVector<Value> capturesVector(captures.begin(), captures.end());
24586ad0af8SEugene Zhulenev   return {rewriter.getFunctionType(inputs, TypeRange()), capturesVector};
24686ad0af8SEugene Zhulenev }
24786ad0af8SEugene Zhulenev 
24886ad0af8SEugene Zhulenev // Create a parallel compute fuction from the parallel operation.
24949ce40e9SEugene Zhulenev static ParallelComputeFunction createParallelComputeFunction(
2501fc096afSMehdi Amini     scf::ParallelOp op, const ParallelComputeFunctionBounds &bounds,
25149ce40e9SEugene Zhulenev     unsigned numBlockAlignedInnerLoops, PatternRewriter &rewriter) {
25286ad0af8SEugene Zhulenev   OpBuilder::InsertionGuard guard(rewriter);
25386ad0af8SEugene Zhulenev   ImplicitLocOpBuilder b(op.getLoc(), rewriter);
25486ad0af8SEugene Zhulenev 
25586ad0af8SEugene Zhulenev   ModuleOp module = op->getParentOfType<ModuleOp>();
25686ad0af8SEugene Zhulenev 
25786ad0af8SEugene Zhulenev   ParallelComputeFunctionType computeFuncType =
25886ad0af8SEugene Zhulenev       getParallelComputeFunctionType(op, rewriter);
25986ad0af8SEugene Zhulenev 
26086ad0af8SEugene Zhulenev   FunctionType type = computeFuncType.type;
26158ceae95SRiver Riddle   func::FuncOp func = func::FuncOp::create(
26258ceae95SRiver Riddle       op.getLoc(),
26358ceae95SRiver Riddle       numBlockAlignedInnerLoops > 0 ? "parallel_compute_fn_with_aligned_loops"
264ec0e4545Sbakhtiyar                                     : "parallel_compute_fn",
265ec0e4545Sbakhtiyar       type);
26686ad0af8SEugene Zhulenev   func.setPrivate();
26786ad0af8SEugene Zhulenev 
26886ad0af8SEugene Zhulenev   // Insert function into the module symbol table and assign it unique name.
26986ad0af8SEugene Zhulenev   SymbolTable symbolTable(module);
27086ad0af8SEugene Zhulenev   symbolTable.insert(func);
2715cc0f76dSMatthias Springer   rewriter.getListener()->notifyOperationInserted(func, /*previous=*/{});
27286ad0af8SEugene Zhulenev 
27386ad0af8SEugene Zhulenev   // Create function entry block.
274e084679fSRiver Riddle   Block *block =
275e084679fSRiver Riddle       b.createBlock(&func.getBody(), func.begin(), type.getInputs(),
276e084679fSRiver Riddle                     SmallVector<Location>(type.getNumInputs(), op.getLoc()));
27786ad0af8SEugene Zhulenev   b.setInsertionPointToEnd(block);
27886ad0af8SEugene Zhulenev 
2799f151b78SEugene Zhulenev   ParallelComputeFunctionArgs args = {op.getNumLoops(), func.getArguments()};
28086ad0af8SEugene Zhulenev 
28186ad0af8SEugene Zhulenev   // Block iteration position defined by the block index and size.
2829f151b78SEugene Zhulenev   BlockArgument blockIndex = args.blockIndex();
2839f151b78SEugene Zhulenev   BlockArgument blockSize = args.blockSize();
28486ad0af8SEugene Zhulenev 
28586ad0af8SEugene Zhulenev   // Constants used below.
286a54f4eaeSMogball   Value c0 = b.create<arith::ConstantIndexOp>(0);
287a54f4eaeSMogball   Value c1 = b.create<arith::ConstantIndexOp>(1);
28886ad0af8SEugene Zhulenev 
2899f151b78SEugene Zhulenev   // Materialize known constants as constant operation in the function body.
2909f151b78SEugene Zhulenev   auto values = [&](ArrayRef<BlockArgument> args, ArrayRef<IntegerAttr> attrs) {
2919f151b78SEugene Zhulenev     return llvm::to_vector(
2929f151b78SEugene Zhulenev         llvm::map_range(llvm::zip(args, attrs), [&](auto tuple) -> Value {
2939f151b78SEugene Zhulenev           if (IntegerAttr attr = std::get<1>(tuple))
2948e123ca6SRiver Riddle             return b.create<arith::ConstantOp>(attr);
2959f151b78SEugene Zhulenev           return std::get<0>(tuple);
2969f151b78SEugene Zhulenev         }));
2979f151b78SEugene Zhulenev   };
2989f151b78SEugene Zhulenev 
29986ad0af8SEugene Zhulenev   // Multi-dimensional parallel iteration space defined by the loop trip counts.
3009f151b78SEugene Zhulenev   auto tripCounts = values(args.tripCounts(), bounds.tripCounts);
3019f151b78SEugene Zhulenev 
3029f151b78SEugene Zhulenev   // Parallel operation lower bound and step.
3039f151b78SEugene Zhulenev   auto lowerBounds = values(args.lowerBounds(), bounds.lowerBounds);
3049f151b78SEugene Zhulenev   auto steps = values(args.steps(), bounds.steps);
3059f151b78SEugene Zhulenev 
3069f151b78SEugene Zhulenev   // Remaining arguments are implicit captures of the parallel operation.
3079f151b78SEugene Zhulenev   ArrayRef<BlockArgument> captures = args.captures();
30886ad0af8SEugene Zhulenev 
30986ad0af8SEugene Zhulenev   // Compute a product of trip counts to get the size of the flattened
31086ad0af8SEugene Zhulenev   // one-dimensional iteration space.
31186ad0af8SEugene Zhulenev   Value tripCount = tripCounts[0];
31286ad0af8SEugene Zhulenev   for (unsigned i = 1; i < tripCounts.size(); ++i)
313a54f4eaeSMogball     tripCount = b.create<arith::MulIOp>(tripCount, tripCounts[i]);
31486ad0af8SEugene Zhulenev 
31586ad0af8SEugene Zhulenev   // Find one-dimensional iteration bounds: [blockFirstIndex, blockLastIndex]:
31686ad0af8SEugene Zhulenev   //   blockFirstIndex = blockIndex * blockSize
317a54f4eaeSMogball   Value blockFirstIndex = b.create<arith::MulIOp>(blockIndex, blockSize);
31886ad0af8SEugene Zhulenev 
31986ad0af8SEugene Zhulenev   // The last one-dimensional index in the block defined by the `blockIndex`:
32068a7c001SEugene Zhulenev   //   blockLastIndex = min(blockFirstIndex + blockSize, tripCount) - 1
321a54f4eaeSMogball   Value blockEnd0 = b.create<arith::AddIOp>(blockFirstIndex, blockSize);
3227bd87a03Sbakhtiyar   Value blockEnd1 = b.create<arith::MinSIOp>(blockEnd0, tripCount);
3237bd87a03Sbakhtiyar   Value blockLastIndex = b.create<arith::SubIOp>(blockEnd1, c1);
32486ad0af8SEugene Zhulenev 
32586ad0af8SEugene Zhulenev   // Convert one-dimensional indices to multi-dimensional coordinates.
32686ad0af8SEugene Zhulenev   auto blockFirstCoord = delinearize(b, blockFirstIndex, tripCounts);
32786ad0af8SEugene Zhulenev   auto blockLastCoord = delinearize(b, blockLastIndex, tripCounts);
32886ad0af8SEugene Zhulenev 
32934a164c9SEugene Zhulenev   // Compute loops upper bounds derived from the block last coordinates:
33086ad0af8SEugene Zhulenev   //   blockEndCoord[i] = blockLastCoord[i] + 1
33186ad0af8SEugene Zhulenev   //
33286ad0af8SEugene Zhulenev   // Block first and last coordinates can be the same along the outer compute
33334a164c9SEugene Zhulenev   // dimension when inner compute dimension contains multiple blocks.
33486ad0af8SEugene Zhulenev   SmallVector<Value> blockEndCoord(op.getNumLoops());
33586ad0af8SEugene Zhulenev   for (size_t i = 0; i < blockLastCoord.size(); ++i)
336a54f4eaeSMogball     blockEndCoord[i] = b.create<arith::AddIOp>(blockLastCoord[i], c1);
33786ad0af8SEugene Zhulenev 
33886ad0af8SEugene Zhulenev   // Construct a loop nest out of scf.for operations that will iterate over
33986ad0af8SEugene Zhulenev   // all coordinates in [blockFirstCoord, blockLastCoord] range.
34086ad0af8SEugene Zhulenev   using LoopBodyBuilder =
34186ad0af8SEugene Zhulenev       std::function<void(OpBuilder &, Location, Value, ValueRange)>;
34286ad0af8SEugene Zhulenev   using LoopNestBuilder = std::function<LoopBodyBuilder(size_t loopIdx)>;
34386ad0af8SEugene Zhulenev 
34486ad0af8SEugene Zhulenev   // Parallel region induction variables computed from the multi-dimensional
34586ad0af8SEugene Zhulenev   // iteration coordinate using parallel operation bounds and step:
34686ad0af8SEugene Zhulenev   //
34786ad0af8SEugene Zhulenev   //   computeBlockInductionVars[loopIdx] =
34868a7c001SEugene Zhulenev   //       lowerBound[loopIdx] + blockCoord[loopIdx] * step[loopIdx]
34986ad0af8SEugene Zhulenev   SmallVector<Value> computeBlockInductionVars(op.getNumLoops());
35086ad0af8SEugene Zhulenev 
35186ad0af8SEugene Zhulenev   // We need to know if we are in the first or last iteration of the
35286ad0af8SEugene Zhulenev   // multi-dimensional loop for each loop in the nest, so we can decide what
35386ad0af8SEugene Zhulenev   // loop bounds should we use for the nested loops: bounds defined by compute
35486ad0af8SEugene Zhulenev   // block interval, or bounds defined by the parallel operation.
35586ad0af8SEugene Zhulenev   //
35686ad0af8SEugene Zhulenev   // Example: 2d parallel operation
35786ad0af8SEugene Zhulenev   //                   i   j
35886ad0af8SEugene Zhulenev   //   loop sizes:   [50, 50]
35986ad0af8SEugene Zhulenev   //   first coord:  [25, 25]
36086ad0af8SEugene Zhulenev   //   last coord:   [30, 30]
36186ad0af8SEugene Zhulenev   //
36286ad0af8SEugene Zhulenev   // If `i` is equal to 25 then iteration over `j` should start at 25, when `i`
36386ad0af8SEugene Zhulenev   // is between 25 and 30 it should start at 0. The upper bound for `j` should
36486ad0af8SEugene Zhulenev   // be 50, except when `i` is equal to 30, then it should also be 30.
36586ad0af8SEugene Zhulenev   //
36686ad0af8SEugene Zhulenev   // Value at ith position specifies if all loops in [0, i) range of the loop
36786ad0af8SEugene Zhulenev   // nest are in the first/last iteration.
36886ad0af8SEugene Zhulenev   SmallVector<Value> isBlockFirstCoord(op.getNumLoops());
36986ad0af8SEugene Zhulenev   SmallVector<Value> isBlockLastCoord(op.getNumLoops());
37086ad0af8SEugene Zhulenev 
37186ad0af8SEugene Zhulenev   // Builds inner loop nest inside async.execute operation that does all the
37286ad0af8SEugene Zhulenev   // work concurrently.
37386ad0af8SEugene Zhulenev   LoopNestBuilder workLoopBuilder = [&](size_t loopIdx) -> LoopBodyBuilder {
37486ad0af8SEugene Zhulenev     return [&, loopIdx](OpBuilder &nestedBuilder, Location loc, Value iv,
37586ad0af8SEugene Zhulenev                         ValueRange args) {
376abe2dee5SEugene Zhulenev       ImplicitLocOpBuilder b(loc, nestedBuilder);
37786ad0af8SEugene Zhulenev 
37886ad0af8SEugene Zhulenev       // Compute induction variable for `loopIdx`.
379abe2dee5SEugene Zhulenev       computeBlockInductionVars[loopIdx] = b.create<arith::AddIOp>(
380abe2dee5SEugene Zhulenev           lowerBounds[loopIdx], b.create<arith::MulIOp>(iv, steps[loopIdx]));
38186ad0af8SEugene Zhulenev 
38286ad0af8SEugene Zhulenev       // Check if we are inside first or last iteration of the loop.
383abe2dee5SEugene Zhulenev       isBlockFirstCoord[loopIdx] = b.create<arith::CmpIOp>(
384a54f4eaeSMogball           arith::CmpIPredicate::eq, iv, blockFirstCoord[loopIdx]);
385abe2dee5SEugene Zhulenev       isBlockLastCoord[loopIdx] = b.create<arith::CmpIOp>(
386a54f4eaeSMogball           arith::CmpIPredicate::eq, iv, blockLastCoord[loopIdx]);
38786ad0af8SEugene Zhulenev 
38834a164c9SEugene Zhulenev       // Check if the previous loop is in its first or last iteration.
38986ad0af8SEugene Zhulenev       if (loopIdx > 0) {
390abe2dee5SEugene Zhulenev         isBlockFirstCoord[loopIdx] = b.create<arith::AndIOp>(
39186ad0af8SEugene Zhulenev             isBlockFirstCoord[loopIdx], isBlockFirstCoord[loopIdx - 1]);
392abe2dee5SEugene Zhulenev         isBlockLastCoord[loopIdx] = b.create<arith::AndIOp>(
39386ad0af8SEugene Zhulenev             isBlockLastCoord[loopIdx], isBlockLastCoord[loopIdx - 1]);
39486ad0af8SEugene Zhulenev       }
39586ad0af8SEugene Zhulenev 
39686ad0af8SEugene Zhulenev       // Keep building loop nest.
39786ad0af8SEugene Zhulenev       if (loopIdx < op.getNumLoops() - 1) {
39849ce40e9SEugene Zhulenev         if (loopIdx + 1 >= op.getNumLoops() - numBlockAlignedInnerLoops) {
39949ce40e9SEugene Zhulenev           // For block aligned loops we always iterate starting from 0 up to
40049ce40e9SEugene Zhulenev           // the loop trip counts.
401abe2dee5SEugene Zhulenev           b.create<scf::ForOp>(c0, tripCounts[loopIdx + 1], c1, ValueRange(),
40249ce40e9SEugene Zhulenev                                workLoopBuilder(loopIdx + 1));
40349ce40e9SEugene Zhulenev 
40449ce40e9SEugene Zhulenev         } else {
40568a7c001SEugene Zhulenev           // Select nested loop lower/upper bounds depending on our position in
40686ad0af8SEugene Zhulenev           // the multi-dimensional iteration space.
407abe2dee5SEugene Zhulenev           auto lb = b.create<arith::SelectOp>(isBlockFirstCoord[loopIdx],
408abe2dee5SEugene Zhulenev                                               blockFirstCoord[loopIdx + 1], c0);
40986ad0af8SEugene Zhulenev 
410abe2dee5SEugene Zhulenev           auto ub = b.create<arith::SelectOp>(isBlockLastCoord[loopIdx],
41186ad0af8SEugene Zhulenev                                               blockEndCoord[loopIdx + 1],
41286ad0af8SEugene Zhulenev                                               tripCounts[loopIdx + 1]);
41386ad0af8SEugene Zhulenev 
414abe2dee5SEugene Zhulenev           b.create<scf::ForOp>(lb, ub, c1, ValueRange(),
41586ad0af8SEugene Zhulenev                                workLoopBuilder(loopIdx + 1));
41649ce40e9SEugene Zhulenev         }
41749ce40e9SEugene Zhulenev 
418abe2dee5SEugene Zhulenev         b.create<scf::YieldOp>(loc);
41986ad0af8SEugene Zhulenev         return;
42086ad0af8SEugene Zhulenev       }
42186ad0af8SEugene Zhulenev 
42286ad0af8SEugene Zhulenev       // Copy the body of the parallel op into the inner-most loop.
4234d67b278SJeff Niu       IRMapping mapping;
42486ad0af8SEugene Zhulenev       mapping.map(op.getInductionVars(), computeBlockInductionVars);
42586ad0af8SEugene Zhulenev       mapping.map(computeFuncType.captures, captures);
42686ad0af8SEugene Zhulenev 
42710056c82SMatthias Springer       for (auto &bodyOp : op.getRegion().front().without_terminator())
428abe2dee5SEugene Zhulenev         b.clone(bodyOp, mapping);
42910056c82SMatthias Springer       b.create<scf::YieldOp>(loc);
43086ad0af8SEugene Zhulenev     };
43186ad0af8SEugene Zhulenev   };
43286ad0af8SEugene Zhulenev 
43386ad0af8SEugene Zhulenev   b.create<scf::ForOp>(blockFirstCoord[0], blockEndCoord[0], c1, ValueRange(),
43486ad0af8SEugene Zhulenev                        workLoopBuilder(0));
43523aa5a74SRiver Riddle   b.create<func::ReturnOp>(ValueRange());
43686ad0af8SEugene Zhulenev 
4379f151b78SEugene Zhulenev   return {op.getNumLoops(), func, std::move(computeFuncType.captures)};
43886ad0af8SEugene Zhulenev }
43986ad0af8SEugene Zhulenev 
44086ad0af8SEugene Zhulenev // Creates recursive async dispatch function for the given parallel compute
44186ad0af8SEugene Zhulenev // function. Dispatch function keeps splitting block range into halves until it
44286ad0af8SEugene Zhulenev // reaches a single block, and then excecutes it inline.
44386ad0af8SEugene Zhulenev //
44486ad0af8SEugene Zhulenev // Function pseudocode (mix of C++ and MLIR):
44586ad0af8SEugene Zhulenev //
44686ad0af8SEugene Zhulenev //   func @async_dispatch(%block_start : index, %block_end : index, ...) {
44786ad0af8SEugene Zhulenev //
44886ad0af8SEugene Zhulenev //     // Keep splitting block range until we reached a range of size 1.
44986ad0af8SEugene Zhulenev //     while (%block_end - %block_start > 1) {
45086ad0af8SEugene Zhulenev //       %mid_index = block_start + (block_end - block_start) / 2;
45186ad0af8SEugene Zhulenev //       async.execute { call @async_dispatch(%mid_index, %block_end); }
45286ad0af8SEugene Zhulenev //       %block_end = %mid_index
45386ad0af8SEugene Zhulenev //     }
45486ad0af8SEugene Zhulenev //
45586ad0af8SEugene Zhulenev //     // Call parallel compute function for a single block.
45686ad0af8SEugene Zhulenev //     call @parallel_compute_fn(%block_start, %block_size, ...);
45786ad0af8SEugene Zhulenev //   }
45886ad0af8SEugene Zhulenev //
45958ceae95SRiver Riddle static func::FuncOp
46058ceae95SRiver Riddle createAsyncDispatchFunction(ParallelComputeFunction &computeFunc,
46186ad0af8SEugene Zhulenev                             PatternRewriter &rewriter) {
46286ad0af8SEugene Zhulenev   OpBuilder::InsertionGuard guard(rewriter);
46386ad0af8SEugene Zhulenev   Location loc = computeFunc.func.getLoc();
46486ad0af8SEugene Zhulenev   ImplicitLocOpBuilder b(loc, rewriter);
46586ad0af8SEugene Zhulenev 
46686ad0af8SEugene Zhulenev   ModuleOp module = computeFunc.func->getParentOfType<ModuleOp>();
46786ad0af8SEugene Zhulenev 
4684a3460a7SRiver Riddle   ArrayRef<Type> computeFuncInputTypes =
4694a3460a7SRiver Riddle       computeFunc.func.getFunctionType().getInputs();
47086ad0af8SEugene Zhulenev 
47186ad0af8SEugene Zhulenev   // Compared to the parallel compute function async dispatch function takes
47286ad0af8SEugene Zhulenev   // additional !async.group argument. Also instead of a single `blockIndex` it
47386ad0af8SEugene Zhulenev   // takes `blockStart` and `blockEnd` arguments to define the range of
47486ad0af8SEugene Zhulenev   // dispatched blocks.
47586ad0af8SEugene Zhulenev   SmallVector<Type> inputTypes;
47686ad0af8SEugene Zhulenev   inputTypes.push_back(async::GroupType::get(rewriter.getContext()));
47786ad0af8SEugene Zhulenev   inputTypes.push_back(rewriter.getIndexType()); // add blockStart argument
47886ad0af8SEugene Zhulenev   inputTypes.append(computeFuncInputTypes.begin(), computeFuncInputTypes.end());
47986ad0af8SEugene Zhulenev 
48086ad0af8SEugene Zhulenev   FunctionType type = rewriter.getFunctionType(inputTypes, TypeRange());
48158ceae95SRiver Riddle   func::FuncOp func = func::FuncOp::create(loc, "async_dispatch_fn", type);
48286ad0af8SEugene Zhulenev   func.setPrivate();
48386ad0af8SEugene Zhulenev 
48486ad0af8SEugene Zhulenev   // Insert function into the module symbol table and assign it unique name.
48586ad0af8SEugene Zhulenev   SymbolTable symbolTable(module);
48686ad0af8SEugene Zhulenev   symbolTable.insert(func);
4875cc0f76dSMatthias Springer   rewriter.getListener()->notifyOperationInserted(func, /*previous=*/{});
48886ad0af8SEugene Zhulenev 
48986ad0af8SEugene Zhulenev   // Create function entry block.
490e084679fSRiver Riddle   Block *block = b.createBlock(&func.getBody(), func.begin(), type.getInputs(),
491e084679fSRiver Riddle                                SmallVector<Location>(type.getNumInputs(), loc));
49286ad0af8SEugene Zhulenev   b.setInsertionPointToEnd(block);
49386ad0af8SEugene Zhulenev 
49486ad0af8SEugene Zhulenev   Type indexTy = b.getIndexType();
495a54f4eaeSMogball   Value c1 = b.create<arith::ConstantIndexOp>(1);
496a54f4eaeSMogball   Value c2 = b.create<arith::ConstantIndexOp>(2);
49786ad0af8SEugene Zhulenev 
49886ad0af8SEugene Zhulenev   // Get the async group that will track async dispatch completion.
49986ad0af8SEugene Zhulenev   Value group = block->getArgument(0);
50086ad0af8SEugene Zhulenev 
50186ad0af8SEugene Zhulenev   // Get the block iteration range: [blockStart, blockEnd)
50286ad0af8SEugene Zhulenev   Value blockStart = block->getArgument(1);
50386ad0af8SEugene Zhulenev   Value blockEnd = block->getArgument(2);
50486ad0af8SEugene Zhulenev 
50586ad0af8SEugene Zhulenev   // Create a work splitting while loop for the [blockStart, blockEnd) range.
50686ad0af8SEugene Zhulenev   SmallVector<Type> types = {indexTy, indexTy};
50786ad0af8SEugene Zhulenev   SmallVector<Value> operands = {blockStart, blockEnd};
508e084679fSRiver Riddle   SmallVector<Location> locations = {loc, loc};
50986ad0af8SEugene Zhulenev 
51086ad0af8SEugene Zhulenev   // Create a recursive dispatch loop.
51186ad0af8SEugene Zhulenev   scf::WhileOp whileOp = b.create<scf::WhileOp>(types, operands);
512e084679fSRiver Riddle   Block *before = b.createBlock(&whileOp.getBefore(), {}, types, locations);
513e084679fSRiver Riddle   Block *after = b.createBlock(&whileOp.getAfter(), {}, types, locations);
51486ad0af8SEugene Zhulenev 
51586ad0af8SEugene Zhulenev   // Setup dispatch loop condition block: decide if we need to go into the
51686ad0af8SEugene Zhulenev   // `after` block and launch one more async dispatch.
51786ad0af8SEugene Zhulenev   {
51886ad0af8SEugene Zhulenev     b.setInsertionPointToEnd(before);
51986ad0af8SEugene Zhulenev     Value start = before->getArgument(0);
52086ad0af8SEugene Zhulenev     Value end = before->getArgument(1);
521a54f4eaeSMogball     Value distance = b.create<arith::SubIOp>(end, start);
522a54f4eaeSMogball     Value dispatch =
523a54f4eaeSMogball         b.create<arith::CmpIOp>(arith::CmpIPredicate::sgt, distance, c1);
52486ad0af8SEugene Zhulenev     b.create<scf::ConditionOp>(dispatch, before->getArguments());
52586ad0af8SEugene Zhulenev   }
52686ad0af8SEugene Zhulenev 
52786ad0af8SEugene Zhulenev   // Setup the async dispatch loop body: recursively call dispatch function
52834a164c9SEugene Zhulenev   // for the seconds half of the original range and go to the next iteration.
52986ad0af8SEugene Zhulenev   {
53086ad0af8SEugene Zhulenev     b.setInsertionPointToEnd(after);
53186ad0af8SEugene Zhulenev     Value start = after->getArgument(0);
53286ad0af8SEugene Zhulenev     Value end = after->getArgument(1);
533a54f4eaeSMogball     Value distance = b.create<arith::SubIOp>(end, start);
534a54f4eaeSMogball     Value halfDistance = b.create<arith::DivSIOp>(distance, c2);
535a54f4eaeSMogball     Value midIndex = b.create<arith::AddIOp>(start, halfDistance);
53686ad0af8SEugene Zhulenev 
53786ad0af8SEugene Zhulenev     // Call parallel compute function inside the async.execute region.
53886ad0af8SEugene Zhulenev     auto executeBodyBuilder = [&](OpBuilder &executeBuilder,
53986ad0af8SEugene Zhulenev                                   Location executeLoc, ValueRange executeArgs) {
54086ad0af8SEugene Zhulenev       // Update the original `blockStart` and `blockEnd` with new range.
54186ad0af8SEugene Zhulenev       SmallVector<Value> operands{block->getArguments().begin(),
54286ad0af8SEugene Zhulenev                                   block->getArguments().end()};
54386ad0af8SEugene Zhulenev       operands[1] = midIndex;
54486ad0af8SEugene Zhulenev       operands[2] = end;
54586ad0af8SEugene Zhulenev 
546f8d5c73cSRiver Riddle       executeBuilder.create<func::CallOp>(executeLoc, func.getSymName(),
54734a35a8bSMartin Erhart                                           func.getResultTypes(), operands);
54886ad0af8SEugene Zhulenev       executeBuilder.create<async::YieldOp>(executeLoc, ValueRange());
54986ad0af8SEugene Zhulenev     };
55086ad0af8SEugene Zhulenev 
55186ad0af8SEugene Zhulenev     // Create async.execute operation to dispatch half of the block range.
55286ad0af8SEugene Zhulenev     auto execute = b.create<ExecuteOp>(TypeRange(), ValueRange(), ValueRange(),
55386ad0af8SEugene Zhulenev                                        executeBodyBuilder);
554a5aa7836SRiver Riddle     b.create<AddToGroupOp>(indexTy, execute.getToken(), group);
55534a164c9SEugene Zhulenev     b.create<scf::YieldOp>(ValueRange({start, midIndex}));
55686ad0af8SEugene Zhulenev   }
55786ad0af8SEugene Zhulenev 
55886ad0af8SEugene Zhulenev   // After dispatching async operations to process the tail of the block range
55986ad0af8SEugene Zhulenev   // call the parallel compute function for the first block of the range.
56086ad0af8SEugene Zhulenev   b.setInsertionPointAfter(whileOp);
56186ad0af8SEugene Zhulenev 
56286ad0af8SEugene Zhulenev   // Drop async dispatch specific arguments: async group, block start and end.
56386ad0af8SEugene Zhulenev   auto forwardedInputs = block->getArguments().drop_front(3);
56486ad0af8SEugene Zhulenev   SmallVector<Value> computeFuncOperands = {blockStart};
56586ad0af8SEugene Zhulenev   computeFuncOperands.append(forwardedInputs.begin(), forwardedInputs.end());
56686ad0af8SEugene Zhulenev 
567f8d5c73cSRiver Riddle   b.create<func::CallOp>(computeFunc.func.getSymName(),
56834a35a8bSMartin Erhart                          computeFunc.func.getResultTypes(),
56923aa5a74SRiver Riddle                          computeFuncOperands);
57023aa5a74SRiver Riddle   b.create<func::ReturnOp>(ValueRange());
57186ad0af8SEugene Zhulenev 
57286ad0af8SEugene Zhulenev   return func;
57386ad0af8SEugene Zhulenev }
57486ad0af8SEugene Zhulenev 
57586ad0af8SEugene Zhulenev // Launch async dispatch of the parallel compute function.
57686ad0af8SEugene Zhulenev static void doAsyncDispatch(ImplicitLocOpBuilder &b, PatternRewriter &rewriter,
57786ad0af8SEugene Zhulenev                             ParallelComputeFunction &parallelComputeFunction,
57886ad0af8SEugene Zhulenev                             scf::ParallelOp op, Value blockSize,
57986ad0af8SEugene Zhulenev                             Value blockCount,
58086ad0af8SEugene Zhulenev                             const SmallVector<Value> &tripCounts) {
58186ad0af8SEugene Zhulenev   MLIRContext *ctx = op->getContext();
58286ad0af8SEugene Zhulenev 
58386ad0af8SEugene Zhulenev   // Add one more level of indirection to dispatch parallel compute functions
58486ad0af8SEugene Zhulenev   // using async operations and recursive work splitting.
58558ceae95SRiver Riddle   func::FuncOp asyncDispatchFunction =
58686ad0af8SEugene Zhulenev       createAsyncDispatchFunction(parallelComputeFunction, rewriter);
58786ad0af8SEugene Zhulenev 
588a54f4eaeSMogball   Value c0 = b.create<arith::ConstantIndexOp>(0);
589a54f4eaeSMogball   Value c1 = b.create<arith::ConstantIndexOp>(1);
59086ad0af8SEugene Zhulenev 
591a8f819c6SEugene Zhulenev   // Appends operands shared by async dispatch and parallel compute functions to
592a8f819c6SEugene Zhulenev   // the given operands vector.
593a8f819c6SEugene Zhulenev   auto appendBlockComputeOperands = [&](SmallVector<Value> &operands) {
594a8f819c6SEugene Zhulenev     operands.append(tripCounts);
595c0342a2dSJacques Pienaar     operands.append(op.getLowerBound().begin(), op.getLowerBound().end());
596c0342a2dSJacques Pienaar     operands.append(op.getUpperBound().begin(), op.getUpperBound().end());
597c0342a2dSJacques Pienaar     operands.append(op.getStep().begin(), op.getStep().end());
598a8f819c6SEugene Zhulenev     operands.append(parallelComputeFunction.captures);
599a8f819c6SEugene Zhulenev   };
600a8f819c6SEugene Zhulenev 
601a8f819c6SEugene Zhulenev   // Check if the block size is one, in this case we can skip the async dispatch
602a8f819c6SEugene Zhulenev   // completely. If this will be known statically, then canonicalization will
603a8f819c6SEugene Zhulenev   // erase async group operations.
604a54f4eaeSMogball   Value isSingleBlock =
605a54f4eaeSMogball       b.create<arith::CmpIOp>(arith::CmpIPredicate::eq, blockCount, c1);
606a8f819c6SEugene Zhulenev 
607a8f819c6SEugene Zhulenev   auto syncDispatch = [&](OpBuilder &nestedBuilder, Location loc) {
608abe2dee5SEugene Zhulenev     ImplicitLocOpBuilder b(loc, nestedBuilder);
609a8f819c6SEugene Zhulenev 
610a8f819c6SEugene Zhulenev     // Call parallel compute function for the single block.
611a8f819c6SEugene Zhulenev     SmallVector<Value> operands = {c0, blockSize};
612a8f819c6SEugene Zhulenev     appendBlockComputeOperands(operands);
613a8f819c6SEugene Zhulenev 
614f8d5c73cSRiver Riddle     b.create<func::CallOp>(parallelComputeFunction.func.getSymName(),
61534a35a8bSMartin Erhart                            parallelComputeFunction.func.getResultTypes(),
616a8f819c6SEugene Zhulenev                            operands);
617abe2dee5SEugene Zhulenev     b.create<scf::YieldOp>();
618a8f819c6SEugene Zhulenev   };
619a8f819c6SEugene Zhulenev 
620a8f819c6SEugene Zhulenev   auto asyncDispatch = [&](OpBuilder &nestedBuilder, Location loc) {
621abe2dee5SEugene Zhulenev     ImplicitLocOpBuilder b(loc, nestedBuilder);
622b171583aSEugene Zhulenev 
623bdde9595Sbakhtiyar     // Create an async.group to wait on all async tokens from the concurrent
624bdde9595Sbakhtiyar     // execution of multiple parallel compute function. First block will be
625bdde9595Sbakhtiyar     // executed synchronously in the caller thread.
626abe2dee5SEugene Zhulenev     Value groupSize = b.create<arith::SubIOp>(blockCount, c1);
627abe2dee5SEugene Zhulenev     Value group = b.create<CreateGroupOp>(GroupType::get(ctx), groupSize);
62886ad0af8SEugene Zhulenev 
62986ad0af8SEugene Zhulenev     // Launch async dispatch function for [0, blockCount) range.
630a8f819c6SEugene Zhulenev     SmallVector<Value> operands = {group, c0, blockCount, blockSize};
631a8f819c6SEugene Zhulenev     appendBlockComputeOperands(operands);
632a8f819c6SEugene Zhulenev 
633f8d5c73cSRiver Riddle     b.create<func::CallOp>(asyncDispatchFunction.getSymName(),
63434a35a8bSMartin Erhart                            asyncDispatchFunction.getResultTypes(), operands);
635bdde9595Sbakhtiyar 
636bdde9595Sbakhtiyar     // Wait for the completion of all parallel compute operations.
637abe2dee5SEugene Zhulenev     b.create<AwaitAllOp>(group);
638bdde9595Sbakhtiyar 
639abe2dee5SEugene Zhulenev     b.create<scf::YieldOp>();
640a8f819c6SEugene Zhulenev   };
641a8f819c6SEugene Zhulenev 
642a8f819c6SEugene Zhulenev   // Dispatch either single block compute function, or launch async dispatch.
6431125c5c0SFrederik Gossen   b.create<scf::IfOp>(isSingleBlock, syncDispatch, asyncDispatch);
64486ad0af8SEugene Zhulenev }
64586ad0af8SEugene Zhulenev 
64686ad0af8SEugene Zhulenev // Dispatch parallel compute functions by submitting all async compute tasks
64786ad0af8SEugene Zhulenev // from a simple for loop in the caller thread.
64886ad0af8SEugene Zhulenev static void
64955dfab39Sbakhtiyar doSequentialDispatch(ImplicitLocOpBuilder &b, PatternRewriter &rewriter,
65086ad0af8SEugene Zhulenev                      ParallelComputeFunction &parallelComputeFunction,
65186ad0af8SEugene Zhulenev                      scf::ParallelOp op, Value blockSize, Value blockCount,
65286ad0af8SEugene Zhulenev                      const SmallVector<Value> &tripCounts) {
65386ad0af8SEugene Zhulenev   MLIRContext *ctx = op->getContext();
65486ad0af8SEugene Zhulenev 
65558ceae95SRiver Riddle   func::FuncOp compute = parallelComputeFunction.func;
65686ad0af8SEugene Zhulenev 
657a54f4eaeSMogball   Value c0 = b.create<arith::ConstantIndexOp>(0);
658a54f4eaeSMogball   Value c1 = b.create<arith::ConstantIndexOp>(1);
65986ad0af8SEugene Zhulenev 
66086ad0af8SEugene Zhulenev   // Create an async.group to wait on all async tokens from the concurrent
66186ad0af8SEugene Zhulenev   // execution of multiple parallel compute function. First block will be
66286ad0af8SEugene Zhulenev   // executed synchronously in the caller thread.
663a54f4eaeSMogball   Value groupSize = b.create<arith::SubIOp>(blockCount, c1);
66486ad0af8SEugene Zhulenev   Value group = b.create<CreateGroupOp>(GroupType::get(ctx), groupSize);
66586ad0af8SEugene Zhulenev 
66686ad0af8SEugene Zhulenev   // Call parallel compute function for all blocks.
66786ad0af8SEugene Zhulenev   using LoopBodyBuilder =
66886ad0af8SEugene Zhulenev       std::function<void(OpBuilder &, Location, Value, ValueRange)>;
66986ad0af8SEugene Zhulenev 
67086ad0af8SEugene Zhulenev   // Returns parallel compute function operands to process the given block.
67186ad0af8SEugene Zhulenev   auto computeFuncOperands = [&](Value blockIndex) -> SmallVector<Value> {
67286ad0af8SEugene Zhulenev     SmallVector<Value> computeFuncOperands = {blockIndex, blockSize};
67386ad0af8SEugene Zhulenev     computeFuncOperands.append(tripCounts);
674c0342a2dSJacques Pienaar     computeFuncOperands.append(op.getLowerBound().begin(),
675c0342a2dSJacques Pienaar                                op.getLowerBound().end());
676c0342a2dSJacques Pienaar     computeFuncOperands.append(op.getUpperBound().begin(),
677c0342a2dSJacques Pienaar                                op.getUpperBound().end());
678c0342a2dSJacques Pienaar     computeFuncOperands.append(op.getStep().begin(), op.getStep().end());
67986ad0af8SEugene Zhulenev     computeFuncOperands.append(parallelComputeFunction.captures);
68086ad0af8SEugene Zhulenev     return computeFuncOperands;
68186ad0af8SEugene Zhulenev   };
68286ad0af8SEugene Zhulenev 
68386ad0af8SEugene Zhulenev   // Induction variable is the index of the block: [0, blockCount).
68486ad0af8SEugene Zhulenev   LoopBodyBuilder loopBuilder = [&](OpBuilder &loopBuilder, Location loc,
68586ad0af8SEugene Zhulenev                                     Value iv, ValueRange args) {
686abe2dee5SEugene Zhulenev     ImplicitLocOpBuilder b(loc, loopBuilder);
68786ad0af8SEugene Zhulenev 
68886ad0af8SEugene Zhulenev     // Call parallel compute function inside the async.execute region.
68986ad0af8SEugene Zhulenev     auto executeBodyBuilder = [&](OpBuilder &executeBuilder,
69086ad0af8SEugene Zhulenev                                   Location executeLoc, ValueRange executeArgs) {
691f8d5c73cSRiver Riddle       executeBuilder.create<func::CallOp>(executeLoc, compute.getSymName(),
69234a35a8bSMartin Erhart                                           compute.getResultTypes(),
69386ad0af8SEugene Zhulenev                                           computeFuncOperands(iv));
69486ad0af8SEugene Zhulenev       executeBuilder.create<async::YieldOp>(executeLoc, ValueRange());
69586ad0af8SEugene Zhulenev     };
69686ad0af8SEugene Zhulenev 
69786ad0af8SEugene Zhulenev     // Create async.execute operation to launch parallel computate function.
698abe2dee5SEugene Zhulenev     auto execute = b.create<ExecuteOp>(TypeRange(), ValueRange(), ValueRange(),
69986ad0af8SEugene Zhulenev                                        executeBodyBuilder);
700a5aa7836SRiver Riddle     b.create<AddToGroupOp>(rewriter.getIndexType(), execute.getToken(), group);
701abe2dee5SEugene Zhulenev     b.create<scf::YieldOp>();
70286ad0af8SEugene Zhulenev   };
70386ad0af8SEugene Zhulenev 
70486ad0af8SEugene Zhulenev   // Iterate over all compute blocks and launch parallel compute operations.
70586ad0af8SEugene Zhulenev   b.create<scf::ForOp>(c1, blockCount, c1, ValueRange(), loopBuilder);
70686ad0af8SEugene Zhulenev 
70786ad0af8SEugene Zhulenev   // Call parallel compute function for the first block in the caller thread.
70834a35a8bSMartin Erhart   b.create<func::CallOp>(compute.getSymName(), compute.getResultTypes(),
70986ad0af8SEugene Zhulenev                          computeFuncOperands(c0));
71086ad0af8SEugene Zhulenev 
71186ad0af8SEugene Zhulenev   // Wait for the completion of all async compute operations.
71286ad0af8SEugene Zhulenev   b.create<AwaitAllOp>(group);
71386ad0af8SEugene Zhulenev }
71486ad0af8SEugene Zhulenev 
715c30ab6c2SEugene Zhulenev LogicalResult
716c30ab6c2SEugene Zhulenev AsyncParallelForRewrite::matchAndRewrite(scf::ParallelOp op,
717c30ab6c2SEugene Zhulenev                                          PatternRewriter &rewriter) const {
718c30ab6c2SEugene Zhulenev   // We do not currently support rewrite for parallel op with reductions.
719c30ab6c2SEugene Zhulenev   if (op.getNumReductions() != 0)
720c30ab6c2SEugene Zhulenev     return failure();
721c30ab6c2SEugene Zhulenev 
72286ad0af8SEugene Zhulenev   ImplicitLocOpBuilder b(op.getLoc(), rewriter);
723c30ab6c2SEugene Zhulenev 
724ec0e4545Sbakhtiyar   // Computing minTaskSize emits IR and can be implemented as executing a cost
725ec0e4545Sbakhtiyar   // model on the body of the scf.parallel. Thus it needs to be computed before
726ec0e4545Sbakhtiyar   // the body of the scf.parallel has been manipulated.
727ec0e4545Sbakhtiyar   Value minTaskSize = computeMinTaskSize(b, op);
728ec0e4545Sbakhtiyar 
7299f151b78SEugene Zhulenev   // Make sure that all constants will be inside the parallel operation body to
7309f151b78SEugene Zhulenev   // reduce the number of parallel compute function arguments.
7319b5ef2beSMatthias Springer   cloneConstantsIntoTheRegion(op.getRegion(), rewriter);
7329f151b78SEugene Zhulenev 
733c30ab6c2SEugene Zhulenev   // Compute trip count for each loop induction variable:
73486ad0af8SEugene Zhulenev   //   tripCount = ceil_div(upperBound - lowerBound, step);
73586ad0af8SEugene Zhulenev   SmallVector<Value> tripCounts(op.getNumLoops());
736c30ab6c2SEugene Zhulenev   for (size_t i = 0; i < op.getNumLoops(); ++i) {
737c0342a2dSJacques Pienaar     auto lb = op.getLowerBound()[i];
738c0342a2dSJacques Pienaar     auto ub = op.getUpperBound()[i];
739c0342a2dSJacques Pienaar     auto step = op.getStep()[i];
7409f151b78SEugene Zhulenev     auto range = b.createOrFold<arith::SubIOp>(ub, lb);
7419f151b78SEugene Zhulenev     tripCounts[i] = b.createOrFold<arith::CeilDivSIOp>(range, step);
742c30ab6c2SEugene Zhulenev   }
743c30ab6c2SEugene Zhulenev 
74486ad0af8SEugene Zhulenev   // Compute a product of trip counts to get the 1-dimensional iteration space
74586ad0af8SEugene Zhulenev   // for the scf.parallel operation.
74686ad0af8SEugene Zhulenev   Value tripCount = tripCounts[0];
74786ad0af8SEugene Zhulenev   for (size_t i = 1; i < tripCounts.size(); ++i)
748a54f4eaeSMogball     tripCount = b.create<arith::MulIOp>(tripCount, tripCounts[i]);
749c30ab6c2SEugene Zhulenev 
7506c1f6558SEugene Zhulenev   // Short circuit no-op parallel loops (zero iterations) that can arise from
7516c1f6558SEugene Zhulenev   // the memrefs with dynamic dimension(s) equal to zero.
752a54f4eaeSMogball   Value c0 = b.create<arith::ConstantIndexOp>(0);
753a54f4eaeSMogball   Value isZeroIterations =
754a54f4eaeSMogball       b.create<arith::CmpIOp>(arith::CmpIPredicate::eq, tripCount, c0);
7556c1f6558SEugene Zhulenev 
7566c1f6558SEugene Zhulenev   // Do absolutely nothing if the trip count is zero.
7576c1f6558SEugene Zhulenev   auto noOp = [&](OpBuilder &nestedBuilder, Location loc) {
7586c1f6558SEugene Zhulenev     nestedBuilder.create<scf::YieldOp>(loc);
7596c1f6558SEugene Zhulenev   };
7606c1f6558SEugene Zhulenev 
7616c1f6558SEugene Zhulenev   // Compute the parallel block size and dispatch concurrent tasks computing
7626c1f6558SEugene Zhulenev   // results for each block.
7636c1f6558SEugene Zhulenev   auto dispatch = [&](OpBuilder &nestedBuilder, Location loc) {
764abe2dee5SEugene Zhulenev     ImplicitLocOpBuilder b(loc, nestedBuilder);
7656c1f6558SEugene Zhulenev 
76649ce40e9SEugene Zhulenev     // Collect statically known constants defining the loop nest in the parallel
76749ce40e9SEugene Zhulenev     // compute function. LLVM can't always push constants across the non-trivial
76849ce40e9SEugene Zhulenev     // async dispatch call graph, by providing these values explicitly we can
76949ce40e9SEugene Zhulenev     // choose to build more efficient loop nest, and rely on a better constant
77049ce40e9SEugene Zhulenev     // folding, loop unrolling and vectorization.
77149ce40e9SEugene Zhulenev     ParallelComputeFunctionBounds staticBounds = {
77249ce40e9SEugene Zhulenev         integerConstants(tripCounts),
773c0342a2dSJacques Pienaar         integerConstants(op.getLowerBound()),
774c0342a2dSJacques Pienaar         integerConstants(op.getUpperBound()),
775c0342a2dSJacques Pienaar         integerConstants(op.getStep()),
77649ce40e9SEugene Zhulenev     };
77749ce40e9SEugene Zhulenev 
77849ce40e9SEugene Zhulenev     // Find how many inner iteration dimensions are statically known, and their
779ec0e4545Sbakhtiyar     // product is smaller than the `512`. We align the parallel compute block
78049ce40e9SEugene Zhulenev     // size by the product of statically known dimensions, so that we can
78149ce40e9SEugene Zhulenev     // guarantee that the inner loops executes from 0 to the loop trip counts
78249ce40e9SEugene Zhulenev     // and we can elide dynamic loop boundaries, and give LLVM an opportunity to
78349ce40e9SEugene Zhulenev     // unroll the loops. The constant `512` is arbitrary, it should depend on
78449ce40e9SEugene Zhulenev     // how many iterations LLVM will typically decide to unroll.
785beff16f7SEugene Zhulenev     static constexpr int64_t maxUnrollableIterations = 512;
78649ce40e9SEugene Zhulenev 
78749ce40e9SEugene Zhulenev     // The number of inner loops with statically known number of iterations less
788beff16f7SEugene Zhulenev     // than the `maxUnrollableIterations` value.
78949ce40e9SEugene Zhulenev     int numUnrollableLoops = 0;
79049ce40e9SEugene Zhulenev 
79149ce40e9SEugene Zhulenev     auto getInt = [](IntegerAttr attr) { return attr ? attr.getInt() : 0; };
79249ce40e9SEugene Zhulenev 
79349ce40e9SEugene Zhulenev     SmallVector<int64_t> numIterations(op.getNumLoops());
79449ce40e9SEugene Zhulenev     numIterations.back() = getInt(staticBounds.tripCounts.back());
79549ce40e9SEugene Zhulenev 
79649ce40e9SEugene Zhulenev     for (int i = op.getNumLoops() - 2; i >= 0; --i) {
79749ce40e9SEugene Zhulenev       int64_t tripCount = getInt(staticBounds.tripCounts[i]);
79849ce40e9SEugene Zhulenev       int64_t innerIterations = numIterations[i + 1];
79949ce40e9SEugene Zhulenev       numIterations[i] = tripCount * innerIterations;
80049ce40e9SEugene Zhulenev 
80149ce40e9SEugene Zhulenev       // Update the number of inner loops that we can potentially unroll.
802beff16f7SEugene Zhulenev       if (innerIterations > 0 && innerIterations <= maxUnrollableIterations)
80349ce40e9SEugene Zhulenev         numUnrollableLoops++;
80449ce40e9SEugene Zhulenev     }
80549ce40e9SEugene Zhulenev 
806149311b4Sbakhtiyar     Value numWorkerThreadsVal;
807149311b4Sbakhtiyar     if (numWorkerThreads >= 0)
808149311b4Sbakhtiyar       numWorkerThreadsVal = b.create<arith::ConstantIndexOp>(numWorkerThreads);
809149311b4Sbakhtiyar     else
810149311b4Sbakhtiyar       numWorkerThreadsVal = b.create<async::RuntimeNumWorkerThreadsOp>();
811c1194c2eSEugene Zhulenev 
812149311b4Sbakhtiyar     // With large number of threads the value of creating many compute blocks
813149311b4Sbakhtiyar     // is reduced because the problem typically becomes memory bound. For this
814149311b4Sbakhtiyar     // reason we scale the number of workers using an equivalent to the
815149311b4Sbakhtiyar     // following logic:
816149311b4Sbakhtiyar     //   float overshardingFactor = numWorkerThreads <= 4    ? 8.0
817149311b4Sbakhtiyar     //                              : numWorkerThreads <= 8  ? 4.0
818149311b4Sbakhtiyar     //                              : numWorkerThreads <= 16 ? 2.0
819149311b4Sbakhtiyar     //                              : numWorkerThreads <= 32 ? 1.0
820149311b4Sbakhtiyar     //                              : numWorkerThreads <= 64 ? 0.8
821149311b4Sbakhtiyar     //                                                       : 0.6;
822149311b4Sbakhtiyar 
823149311b4Sbakhtiyar     // Pairs of non-inclusive lower end of the bracket and factor that the
824149311b4Sbakhtiyar     // number of workers needs to be scaled with if it falls in that bucket.
825149311b4Sbakhtiyar     const SmallVector<std::pair<int, float>> overshardingBrackets = {
826149311b4Sbakhtiyar         {4, 4.0f}, {8, 2.0f}, {16, 1.0f}, {32, 0.8f}, {64, 0.6f}};
827149311b4Sbakhtiyar     const float initialOvershardingFactor = 8.0f;
828149311b4Sbakhtiyar 
829149311b4Sbakhtiyar     Value scalingFactor = b.create<arith::ConstantFloatOp>(
830149311b4Sbakhtiyar         llvm::APFloat(initialOvershardingFactor), b.getF32Type());
831149311b4Sbakhtiyar     for (const std::pair<int, float> &p : overshardingBrackets) {
832149311b4Sbakhtiyar       Value bracketBegin = b.create<arith::ConstantIndexOp>(p.first);
833149311b4Sbakhtiyar       Value inBracket = b.create<arith::CmpIOp>(
834149311b4Sbakhtiyar           arith::CmpIPredicate::sgt, numWorkerThreadsVal, bracketBegin);
835149311b4Sbakhtiyar       Value bracketScalingFactor = b.create<arith::ConstantFloatOp>(
836149311b4Sbakhtiyar           llvm::APFloat(p.second), b.getF32Type());
837dec8af70SRiver Riddle       scalingFactor = b.create<arith::SelectOp>(inBracket, bracketScalingFactor,
838dec8af70SRiver Riddle                                                 scalingFactor);
839149311b4Sbakhtiyar     }
840149311b4Sbakhtiyar     Value numWorkersIndex =
8413c69bc4dSRiver Riddle         b.create<arith::IndexCastOp>(b.getI32Type(), numWorkerThreadsVal);
842149311b4Sbakhtiyar     Value numWorkersFloat =
8433c69bc4dSRiver Riddle         b.create<arith::SIToFPOp>(b.getF32Type(), numWorkersIndex);
844149311b4Sbakhtiyar     Value scaledNumWorkers =
845149311b4Sbakhtiyar         b.create<arith::MulFOp>(scalingFactor, numWorkersFloat);
846149311b4Sbakhtiyar     Value scaledNumInt =
8473c69bc4dSRiver Riddle         b.create<arith::FPToSIOp>(b.getI32Type(), scaledNumWorkers);
848149311b4Sbakhtiyar     Value scaledWorkers =
8493c69bc4dSRiver Riddle         b.create<arith::IndexCastOp>(b.getIndexType(), scaledNumInt);
850149311b4Sbakhtiyar 
851149311b4Sbakhtiyar     Value maxComputeBlocks = b.create<arith::MaxSIOp>(
852149311b4Sbakhtiyar         b.create<arith::ConstantIndexOp>(1), scaledWorkers);
853c30ab6c2SEugene Zhulenev 
85486ad0af8SEugene Zhulenev     // Compute parallel block size from the parallel problem size:
85586ad0af8SEugene Zhulenev     //   blockSize = min(tripCount,
85634a164c9SEugene Zhulenev     //                   max(ceil_div(tripCount, maxComputeBlocks),
857ec0e4545Sbakhtiyar     //                       minTaskSize))
8587bd87a03Sbakhtiyar     Value bs0 = b.create<arith::CeilDivSIOp>(tripCount, maxComputeBlocks);
859ec0e4545Sbakhtiyar     Value bs1 = b.create<arith::MaxSIOp>(bs0, minTaskSize);
8607bd87a03Sbakhtiyar     Value blockSize = b.create<arith::MinSIOp>(tripCount, bs1);
86149ce40e9SEugene Zhulenev 
862ec0e4545Sbakhtiyar     // Dispatch parallel compute function using async recursive work splitting,
863ec0e4545Sbakhtiyar     // or by submitting compute task sequentially from a caller thread.
864ec0e4545Sbakhtiyar     auto doDispatch = asyncDispatch ? doAsyncDispatch : doSequentialDispatch;
865ec0e4545Sbakhtiyar 
866ec0e4545Sbakhtiyar     // Create a parallel compute function that takes a block id and computes
867ec0e4545Sbakhtiyar     // the parallel operation body for a subset of iteration space.
86849ce40e9SEugene Zhulenev 
86949ce40e9SEugene Zhulenev     // Compute the number of parallel compute blocks.
870a54f4eaeSMogball     Value blockCount = b.create<arith::CeilDivSIOp>(tripCount, blockSize);
87186ad0af8SEugene Zhulenev 
872beff16f7SEugene Zhulenev     // Dispatch parallel compute function without hints to unroll inner loops.
873beff16f7SEugene Zhulenev     auto dispatchDefault = [&](OpBuilder &nestedBuilder, Location loc) {
874beff16f7SEugene Zhulenev       ParallelComputeFunction compute =
875beff16f7SEugene Zhulenev           createParallelComputeFunction(op, staticBounds, 0, rewriter);
876beff16f7SEugene Zhulenev 
877abe2dee5SEugene Zhulenev       ImplicitLocOpBuilder b(loc, nestedBuilder);
878beff16f7SEugene Zhulenev       doDispatch(b, rewriter, compute, op, blockSize, blockCount, tripCounts);
879abe2dee5SEugene Zhulenev       b.create<scf::YieldOp>();
880ec0e4545Sbakhtiyar     };
881ec0e4545Sbakhtiyar 
882beff16f7SEugene Zhulenev     // Dispatch parallel compute function with hints for unrolling inner loops.
883beff16f7SEugene Zhulenev     auto dispatchBlockAligned = [&](OpBuilder &nestedBuilder, Location loc) {
884beff16f7SEugene Zhulenev       ParallelComputeFunction compute = createParallelComputeFunction(
885beff16f7SEugene Zhulenev           op, staticBounds, numUnrollableLoops, rewriter);
886ec0e4545Sbakhtiyar 
887abe2dee5SEugene Zhulenev       ImplicitLocOpBuilder b(loc, nestedBuilder);
888ec0e4545Sbakhtiyar       // Align the block size to be a multiple of the statically known
889ec0e4545Sbakhtiyar       // number of iterations in the inner loops.
890abe2dee5SEugene Zhulenev       Value numIters = b.create<arith::ConstantIndexOp>(
891ec0e4545Sbakhtiyar           numIterations[op.getNumLoops() - numUnrollableLoops]);
892abe2dee5SEugene Zhulenev       Value alignedBlockSize = b.create<arith::MulIOp>(
893abe2dee5SEugene Zhulenev           b.create<arith::CeilDivSIOp>(blockSize, numIters), numIters);
894beff16f7SEugene Zhulenev       doDispatch(b, rewriter, compute, op, alignedBlockSize, blockCount,
895beff16f7SEugene Zhulenev                  tripCounts);
896abe2dee5SEugene Zhulenev       b.create<scf::YieldOp>();
8976c1f6558SEugene Zhulenev     };
8986c1f6558SEugene Zhulenev 
899beff16f7SEugene Zhulenev     // Dispatch to block aligned compute function only if the computed block
900beff16f7SEugene Zhulenev     // size is larger than the number of iterations in the unrollable inner
901beff16f7SEugene Zhulenev     // loops, because otherwise it can reduce the available parallelism.
902beff16f7SEugene Zhulenev     if (numUnrollableLoops > 0) {
903beff16f7SEugene Zhulenev       Value numIters = b.create<arith::ConstantIndexOp>(
904beff16f7SEugene Zhulenev           numIterations[op.getNumLoops() - numUnrollableLoops]);
905beff16f7SEugene Zhulenev       Value useBlockAlignedComputeFn = b.create<arith::CmpIOp>(
906beff16f7SEugene Zhulenev           arith::CmpIPredicate::sge, blockSize, numIters);
907beff16f7SEugene Zhulenev 
9081125c5c0SFrederik Gossen       b.create<scf::IfOp>(useBlockAlignedComputeFn, dispatchBlockAligned,
9091125c5c0SFrederik Gossen                           dispatchDefault);
910abe2dee5SEugene Zhulenev       b.create<scf::YieldOp>();
911ec0e4545Sbakhtiyar     } else {
912beff16f7SEugene Zhulenev       dispatchDefault(b, loc);
913ec0e4545Sbakhtiyar     }
914ec0e4545Sbakhtiyar   };
915ec0e4545Sbakhtiyar 
9166c1f6558SEugene Zhulenev   // Replace the `scf.parallel` operation with the parallel compute function.
9171125c5c0SFrederik Gossen   b.create<scf::IfOp>(isZeroIterations, noOp, dispatch);
9186c1f6558SEugene Zhulenev 
91934a164c9SEugene Zhulenev   // Parallel operation was replaced with a block iteration loop.
920c30ab6c2SEugene Zhulenev   rewriter.eraseOp(op);
921c30ab6c2SEugene Zhulenev 
922c30ab6c2SEugene Zhulenev   return success();
923c30ab6c2SEugene Zhulenev }
924c30ab6c2SEugene Zhulenev 
9258a316b00SEugene Zhulenev void AsyncParallelForPass::runOnOperation() {
926c30ab6c2SEugene Zhulenev   MLIRContext *ctx = &getContext();
927c30ab6c2SEugene Zhulenev 
928dc4e913bSChris Lattner   RewritePatternSet patterns(ctx);
929ec0e4545Sbakhtiyar   populateAsyncParallelForPatterns(
930ec0e4545Sbakhtiyar       patterns, asyncDispatch, numWorkerThreads,
931ec0e4545Sbakhtiyar       [&](ImplicitLocOpBuilder builder, scf::ParallelOp op) {
932ec0e4545Sbakhtiyar         return builder.create<arith::ConstantIndexOp>(minTaskSize);
933ec0e4545Sbakhtiyar       });
934*09dfc571SJacques Pienaar   if (failed(applyPatternsGreedily(getOperation(), std::move(patterns))))
935c30ab6c2SEugene Zhulenev     signalPassFailure();
936c30ab6c2SEugene Zhulenev }
937c30ab6c2SEugene Zhulenev 
9388a316b00SEugene Zhulenev std::unique_ptr<Pass> mlir::createAsyncParallelForPass() {
939c30ab6c2SEugene Zhulenev   return std::make_unique<AsyncParallelForPass>();
940c30ab6c2SEugene Zhulenev }
94134a164c9SEugene Zhulenev 
94255dfab39Sbakhtiyar std::unique_ptr<Pass> mlir::createAsyncParallelForPass(bool asyncDispatch,
94355dfab39Sbakhtiyar                                                        int32_t numWorkerThreads,
94455dfab39Sbakhtiyar                                                        int32_t minTaskSize) {
94534a164c9SEugene Zhulenev   return std::make_unique<AsyncParallelForPass>(asyncDispatch, numWorkerThreads,
94655dfab39Sbakhtiyar                                                 minTaskSize);
94734a164c9SEugene Zhulenev }
948ec0e4545Sbakhtiyar 
949ec0e4545Sbakhtiyar void mlir::async::populateAsyncParallelForPatterns(
950ec0e4545Sbakhtiyar     RewritePatternSet &patterns, bool asyncDispatch, int32_t numWorkerThreads,
9511fc096afSMehdi Amini     const AsyncMinTaskSizeComputationFunction &computeMinTaskSize) {
952ec0e4545Sbakhtiyar   MLIRContext *ctx = patterns.getContext();
953ec0e4545Sbakhtiyar   patterns.add<AsyncParallelForRewrite>(ctx, asyncDispatch, numWorkerThreads,
954ec0e4545Sbakhtiyar                                         computeMinTaskSize);
955ec0e4545Sbakhtiyar }
956