1 //===- AsyncParallelFor.cpp - Implementation of Async Parallel For --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements scf.parallel to scf.for + async.execute conversion pass.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PassDetail.h"
14 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
15 #include "mlir/Dialect/Async/IR/Async.h"
16 #include "mlir/Dialect/Async/Passes.h"
17 #include "mlir/Dialect/SCF/SCF.h"
18 #include "mlir/Dialect/StandardOps/IR/Ops.h"
19 #include "mlir/IR/BlockAndValueMapping.h"
20 #include "mlir/IR/ImplicitLocOpBuilder.h"
21 #include "mlir/IR/PatternMatch.h"
22 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
23 #include "mlir/Transforms/RegionUtils.h"
24 
25 using namespace mlir;
26 using namespace mlir::async;
27 
28 #define DEBUG_TYPE "async-parallel-for"
29 
30 namespace {
31 
32 // Rewrite scf.parallel operation into multiple concurrent async.execute
33 // operations over non overlapping subranges of the original loop.
34 //
35 // Example:
36 //
37 //   scf.parallel (%i, %j) = (%lbi, %lbj) to (%ubi, %ubj) step (%si, %sj) {
38 //     "do_some_compute"(%i, %j): () -> ()
39 //   }
40 //
41 // Converted to:
42 //
43 //   // Parallel compute function that executes the parallel body region for
44 //   // a subset of the parallel iteration space defined by the one-dimensional
45 //   // compute block index.
46 //   func parallel_compute_function(%block_index : index, %block_size : index,
47 //                                  <parallel operation properties>, ...) {
48 //     // Compute multi-dimensional loop bounds for %block_index.
49 //     %block_lbi, %block_lbj = ...
50 //     %block_ubi, %block_ubj = ...
51 //
52 //     // Clone parallel operation body into the scf.for loop nest.
53 //     scf.for %i = %blockLbi to %blockUbi {
54 //       scf.for %j = block_lbj to %block_ubj {
55 //         "do_some_compute"(%i, %j): () -> ()
56 //       }
57 //     }
58 //   }
59 //
60 // And a dispatch function depending on the `asyncDispatch` option.
61 //
62 // When async dispatch is on: (pseudocode)
63 //
64 //   %block_size = ... compute parallel compute block size
65 //   %block_count = ... compute the number of compute blocks
66 //
67 //   func @async_dispatch(%block_start : index, %block_end : index, ...) {
68 //     // Keep splitting block range until we reached a range of size 1.
69 //     while (%block_end - %block_start > 1) {
70 //       %mid_index = block_start + (block_end - block_start) / 2;
71 //       async.execute { call @async_dispatch(%mid_index, %block_end); }
72 //       %block_end = %mid_index
73 //     }
74 //
75 //     // Call parallel compute function for a single block.
76 //     call @parallel_compute_fn(%block_start, %block_size, ...);
77 //   }
78 //
79 //   // Launch async dispatch for [0, block_count) range.
80 //   call @async_dispatch(%c0, %block_count);
81 //
82 // When async dispatch is off:
83 //
84 //   %block_size = ... compute parallel compute block size
85 //   %block_count = ... compute the number of compute blocks
86 //
87 //   scf.for %block_index = %c0 to %block_count {
88 //      call @parallel_compute_fn(%block_index, %block_size, ...)
89 //   }
90 //
91 struct AsyncParallelForPass
92     : public AsyncParallelForBase<AsyncParallelForPass> {
93   AsyncParallelForPass() = default;
94 
95   AsyncParallelForPass(bool asyncDispatch, int32_t numWorkerThreads,
96                        int32_t minTaskSize) {
97     this->asyncDispatch = asyncDispatch;
98     this->numWorkerThreads = numWorkerThreads;
99     this->minTaskSize = minTaskSize;
100   }
101 
102   void runOnOperation() override;
103 };
104 
105 struct AsyncParallelForRewrite : public OpRewritePattern<scf::ParallelOp> {
106 public:
107   AsyncParallelForRewrite(MLIRContext *ctx, bool asyncDispatch,
108                           int32_t numWorkerThreads, int32_t minTaskSize)
109       : OpRewritePattern(ctx), asyncDispatch(asyncDispatch),
110         numWorkerThreads(numWorkerThreads), minTaskSize(minTaskSize) {}
111 
112   LogicalResult matchAndRewrite(scf::ParallelOp op,
113                                 PatternRewriter &rewriter) const override;
114 
115 private:
116   bool asyncDispatch;
117   int32_t numWorkerThreads;
118   int32_t minTaskSize;
119 };
120 
121 struct ParallelComputeFunctionType {
122   FunctionType type;
123   llvm::SmallVector<Value> captures;
124 };
125 
126 struct ParallelComputeFunction {
127   FuncOp func;
128   llvm::SmallVector<Value> captures;
129 };
130 
131 } // namespace
132 
133 // Converts one-dimensional iteration index in the [0, tripCount) interval
134 // into multidimensional iteration coordinate.
135 static SmallVector<Value> delinearize(ImplicitLocOpBuilder &b, Value index,
136                                       ArrayRef<Value> tripCounts) {
137   SmallVector<Value> coords(tripCounts.size());
138   assert(!tripCounts.empty() && "tripCounts must be not empty");
139 
140   for (ssize_t i = tripCounts.size() - 1; i >= 0; --i) {
141     coords[i] = b.create<arith::RemSIOp>(index, tripCounts[i]);
142     index = b.create<arith::DivSIOp>(index, tripCounts[i]);
143   }
144 
145   return coords;
146 }
147 
148 // Returns a function type and implicit captures for a parallel compute
149 // function. We'll need a list of implicit captures to setup block and value
150 // mapping when we'll clone the body of the parallel operation.
151 static ParallelComputeFunctionType
152 getParallelComputeFunctionType(scf::ParallelOp op, PatternRewriter &rewriter) {
153   // Values implicitly captured by the parallel operation.
154   llvm::SetVector<Value> captures;
155   getUsedValuesDefinedAbove(op.region(), op.region(), captures);
156 
157   llvm::SmallVector<Type> inputs;
158   inputs.reserve(2 + 4 * op.getNumLoops() + captures.size());
159 
160   Type indexTy = rewriter.getIndexType();
161 
162   // One-dimensional iteration space defined by the block index and size.
163   inputs.push_back(indexTy); // blockIndex
164   inputs.push_back(indexTy); // blockSize
165 
166   // Multi-dimensional parallel iteration space defined by the loop trip counts.
167   for (unsigned i = 0; i < op.getNumLoops(); ++i)
168     inputs.push_back(indexTy); // loop tripCount
169 
170   // Parallel operation lower bound, upper bound and step.
171   for (unsigned i = 0; i < op.getNumLoops(); ++i) {
172     inputs.push_back(indexTy); // lower bound
173     inputs.push_back(indexTy); // upper bound
174     inputs.push_back(indexTy); // step
175   }
176 
177   // Types of the implicit captures.
178   for (Value capture : captures)
179     inputs.push_back(capture.getType());
180 
181   // Convert captures to vector for later convenience.
182   SmallVector<Value> capturesVector(captures.begin(), captures.end());
183   return {rewriter.getFunctionType(inputs, TypeRange()), capturesVector};
184 }
185 
186 // Create a parallel compute fuction from the parallel operation.
187 static ParallelComputeFunction
188 createParallelComputeFunction(scf::ParallelOp op, PatternRewriter &rewriter) {
189   OpBuilder::InsertionGuard guard(rewriter);
190   ImplicitLocOpBuilder b(op.getLoc(), rewriter);
191 
192   ModuleOp module = op->getParentOfType<ModuleOp>();
193 
194   // Make sure that all constants will be inside the parallel operation body to
195   // reduce the number of parallel compute function arguments.
196   cloneConstantsIntoTheRegion(op.getLoopBody(), rewriter);
197 
198   ParallelComputeFunctionType computeFuncType =
199       getParallelComputeFunctionType(op, rewriter);
200 
201   FunctionType type = computeFuncType.type;
202   FuncOp func = FuncOp::create(op.getLoc(), "parallel_compute_fn", type);
203   func.setPrivate();
204 
205   // Insert function into the module symbol table and assign it unique name.
206   SymbolTable symbolTable(module);
207   symbolTable.insert(func);
208   rewriter.getListener()->notifyOperationInserted(func);
209 
210   // Create function entry block.
211   Block *block = b.createBlock(&func.getBody(), func.begin(), type.getInputs());
212   b.setInsertionPointToEnd(block);
213 
214   unsigned offset = 0; // argument offset for arguments decoding
215 
216   // Returns `numArguments` arguments starting from `offset` and updates offset
217   // by moving forward to the next argument.
218   auto getArguments = [&](unsigned numArguments) -> ArrayRef<Value> {
219     auto args = block->getArguments();
220     auto slice = args.drop_front(offset).take_front(numArguments);
221     offset += numArguments;
222     return {slice.begin(), slice.end()};
223   };
224 
225   // Block iteration position defined by the block index and size.
226   Value blockIndex = block->getArgument(offset++);
227   Value blockSize = block->getArgument(offset++);
228 
229   // Constants used below.
230   Value c0 = b.create<arith::ConstantIndexOp>(0);
231   Value c1 = b.create<arith::ConstantIndexOp>(1);
232 
233   // Multi-dimensional parallel iteration space defined by the loop trip counts.
234   ArrayRef<Value> tripCounts = getArguments(op.getNumLoops());
235 
236   // Compute a product of trip counts to get the size of the flattened
237   // one-dimensional iteration space.
238   Value tripCount = tripCounts[0];
239   for (unsigned i = 1; i < tripCounts.size(); ++i)
240     tripCount = b.create<arith::MulIOp>(tripCount, tripCounts[i]);
241 
242   // Parallel operation lower bound and step.
243   ArrayRef<Value> lowerBound = getArguments(op.getNumLoops());
244   offset += op.getNumLoops(); // skip upper bound arguments
245   ArrayRef<Value> step = getArguments(op.getNumLoops());
246 
247   // Remaining arguments are implicit captures of the parallel operation.
248   ArrayRef<Value> captures = getArguments(block->getNumArguments() - offset);
249 
250   // Find one-dimensional iteration bounds: [blockFirstIndex, blockLastIndex]:
251   //   blockFirstIndex = blockIndex * blockSize
252   Value blockFirstIndex = b.create<arith::MulIOp>(blockIndex, blockSize);
253 
254   // The last one-dimensional index in the block defined by the `blockIndex`:
255   Value blockEnd0 = b.create<arith::AddIOp>(blockFirstIndex, blockSize);
256   Value blockEnd1 = b.create<arith::MinSIOp>(blockEnd0, tripCount);
257   Value blockLastIndex = b.create<arith::SubIOp>(blockEnd1, c1);
258 
259   // Convert one-dimensional indices to multi-dimensional coordinates.
260   auto blockFirstCoord = delinearize(b, blockFirstIndex, tripCounts);
261   auto blockLastCoord = delinearize(b, blockLastIndex, tripCounts);
262 
263   // Compute loops upper bounds derived from the block last coordinates:
264   //   blockEndCoord[i] = blockLastCoord[i] + 1
265   //
266   // Block first and last coordinates can be the same along the outer compute
267   // dimension when inner compute dimension contains multiple blocks.
268   SmallVector<Value> blockEndCoord(op.getNumLoops());
269   for (size_t i = 0; i < blockLastCoord.size(); ++i)
270     blockEndCoord[i] = b.create<arith::AddIOp>(blockLastCoord[i], c1);
271 
272   // Construct a loop nest out of scf.for operations that will iterate over
273   // all coordinates in [blockFirstCoord, blockLastCoord] range.
274   using LoopBodyBuilder =
275       std::function<void(OpBuilder &, Location, Value, ValueRange)>;
276   using LoopNestBuilder = std::function<LoopBodyBuilder(size_t loopIdx)>;
277 
278   // Parallel region induction variables computed from the multi-dimensional
279   // iteration coordinate using parallel operation bounds and step:
280   //
281   //   computeBlockInductionVars[loopIdx] =
282   //       lowerBound[loopIdx] + blockCoord[loopIdx] * step[loopDdx]
283   SmallVector<Value> computeBlockInductionVars(op.getNumLoops());
284 
285   // We need to know if we are in the first or last iteration of the
286   // multi-dimensional loop for each loop in the nest, so we can decide what
287   // loop bounds should we use for the nested loops: bounds defined by compute
288   // block interval, or bounds defined by the parallel operation.
289   //
290   // Example: 2d parallel operation
291   //                   i   j
292   //   loop sizes:   [50, 50]
293   //   first coord:  [25, 25]
294   //   last coord:   [30, 30]
295   //
296   // If `i` is equal to 25 then iteration over `j` should start at 25, when `i`
297   // is between 25 and 30 it should start at 0. The upper bound for `j` should
298   // be 50, except when `i` is equal to 30, then it should also be 30.
299   //
300   // Value at ith position specifies if all loops in [0, i) range of the loop
301   // nest are in the first/last iteration.
302   SmallVector<Value> isBlockFirstCoord(op.getNumLoops());
303   SmallVector<Value> isBlockLastCoord(op.getNumLoops());
304 
305   // Builds inner loop nest inside async.execute operation that does all the
306   // work concurrently.
307   LoopNestBuilder workLoopBuilder = [&](size_t loopIdx) -> LoopBodyBuilder {
308     return [&, loopIdx](OpBuilder &nestedBuilder, Location loc, Value iv,
309                         ValueRange args) {
310       ImplicitLocOpBuilder nb(loc, nestedBuilder);
311 
312       // Compute induction variable for `loopIdx`.
313       computeBlockInductionVars[loopIdx] = nb.create<arith::AddIOp>(
314           lowerBound[loopIdx], nb.create<arith::MulIOp>(iv, step[loopIdx]));
315 
316       // Check if we are inside first or last iteration of the loop.
317       isBlockFirstCoord[loopIdx] = nb.create<arith::CmpIOp>(
318           arith::CmpIPredicate::eq, iv, blockFirstCoord[loopIdx]);
319       isBlockLastCoord[loopIdx] = nb.create<arith::CmpIOp>(
320           arith::CmpIPredicate::eq, iv, blockLastCoord[loopIdx]);
321 
322       // Check if the previous loop is in its first or last iteration.
323       if (loopIdx > 0) {
324         isBlockFirstCoord[loopIdx] = nb.create<arith::AndIOp>(
325             isBlockFirstCoord[loopIdx], isBlockFirstCoord[loopIdx - 1]);
326         isBlockLastCoord[loopIdx] = nb.create<arith::AndIOp>(
327             isBlockLastCoord[loopIdx], isBlockLastCoord[loopIdx - 1]);
328       }
329 
330       // Keep building loop nest.
331       if (loopIdx < op.getNumLoops() - 1) {
332         // Select nested loop lower/upper bounds depending on out position in
333         // the multi-dimensional iteration space.
334         auto lb = nb.create<SelectOp>(isBlockFirstCoord[loopIdx],
335                                       blockFirstCoord[loopIdx + 1], c0);
336 
337         auto ub = nb.create<SelectOp>(isBlockLastCoord[loopIdx],
338                                       blockEndCoord[loopIdx + 1],
339                                       tripCounts[loopIdx + 1]);
340 
341         nb.create<scf::ForOp>(lb, ub, c1, ValueRange(),
342                               workLoopBuilder(loopIdx + 1));
343         nb.create<scf::YieldOp>(loc);
344         return;
345       }
346 
347       // Copy the body of the parallel op into the inner-most loop.
348       BlockAndValueMapping mapping;
349       mapping.map(op.getInductionVars(), computeBlockInductionVars);
350       mapping.map(computeFuncType.captures, captures);
351 
352       for (auto &bodyOp : op.getLoopBody().getOps())
353         nb.clone(bodyOp, mapping);
354     };
355   };
356 
357   b.create<scf::ForOp>(blockFirstCoord[0], blockEndCoord[0], c1, ValueRange(),
358                        workLoopBuilder(0));
359   b.create<ReturnOp>(ValueRange());
360 
361   return {func, std::move(computeFuncType.captures)};
362 }
363 
364 // Creates recursive async dispatch function for the given parallel compute
365 // function. Dispatch function keeps splitting block range into halves until it
366 // reaches a single block, and then excecutes it inline.
367 //
368 // Function pseudocode (mix of C++ and MLIR):
369 //
370 //   func @async_dispatch(%block_start : index, %block_end : index, ...) {
371 //
372 //     // Keep splitting block range until we reached a range of size 1.
373 //     while (%block_end - %block_start > 1) {
374 //       %mid_index = block_start + (block_end - block_start) / 2;
375 //       async.execute { call @async_dispatch(%mid_index, %block_end); }
376 //       %block_end = %mid_index
377 //     }
378 //
379 //     // Call parallel compute function for a single block.
380 //     call @parallel_compute_fn(%block_start, %block_size, ...);
381 //   }
382 //
383 static FuncOp createAsyncDispatchFunction(ParallelComputeFunction &computeFunc,
384                                           PatternRewriter &rewriter) {
385   OpBuilder::InsertionGuard guard(rewriter);
386   Location loc = computeFunc.func.getLoc();
387   ImplicitLocOpBuilder b(loc, rewriter);
388 
389   ModuleOp module = computeFunc.func->getParentOfType<ModuleOp>();
390 
391   ArrayRef<Type> computeFuncInputTypes =
392       computeFunc.func.type().cast<FunctionType>().getInputs();
393 
394   // Compared to the parallel compute function async dispatch function takes
395   // additional !async.group argument. Also instead of a single `blockIndex` it
396   // takes `blockStart` and `blockEnd` arguments to define the range of
397   // dispatched blocks.
398   SmallVector<Type> inputTypes;
399   inputTypes.push_back(async::GroupType::get(rewriter.getContext()));
400   inputTypes.push_back(rewriter.getIndexType()); // add blockStart argument
401   inputTypes.append(computeFuncInputTypes.begin(), computeFuncInputTypes.end());
402 
403   FunctionType type = rewriter.getFunctionType(inputTypes, TypeRange());
404   FuncOp func = FuncOp::create(loc, "async_dispatch_fn", type);
405   func.setPrivate();
406 
407   // Insert function into the module symbol table and assign it unique name.
408   SymbolTable symbolTable(module);
409   symbolTable.insert(func);
410   rewriter.getListener()->notifyOperationInserted(func);
411 
412   // Create function entry block.
413   Block *block = b.createBlock(&func.getBody(), func.begin(), type.getInputs());
414   b.setInsertionPointToEnd(block);
415 
416   Type indexTy = b.getIndexType();
417   Value c1 = b.create<arith::ConstantIndexOp>(1);
418   Value c2 = b.create<arith::ConstantIndexOp>(2);
419 
420   // Get the async group that will track async dispatch completion.
421   Value group = block->getArgument(0);
422 
423   // Get the block iteration range: [blockStart, blockEnd)
424   Value blockStart = block->getArgument(1);
425   Value blockEnd = block->getArgument(2);
426 
427   // Create a work splitting while loop for the [blockStart, blockEnd) range.
428   SmallVector<Type> types = {indexTy, indexTy};
429   SmallVector<Value> operands = {blockStart, blockEnd};
430 
431   // Create a recursive dispatch loop.
432   scf::WhileOp whileOp = b.create<scf::WhileOp>(types, operands);
433   Block *before = b.createBlock(&whileOp.before(), {}, types);
434   Block *after = b.createBlock(&whileOp.after(), {}, types);
435 
436   // Setup dispatch loop condition block: decide if we need to go into the
437   // `after` block and launch one more async dispatch.
438   {
439     b.setInsertionPointToEnd(before);
440     Value start = before->getArgument(0);
441     Value end = before->getArgument(1);
442     Value distance = b.create<arith::SubIOp>(end, start);
443     Value dispatch =
444         b.create<arith::CmpIOp>(arith::CmpIPredicate::sgt, distance, c1);
445     b.create<scf::ConditionOp>(dispatch, before->getArguments());
446   }
447 
448   // Setup the async dispatch loop body: recursively call dispatch function
449   // for the seconds half of the original range and go to the next iteration.
450   {
451     b.setInsertionPointToEnd(after);
452     Value start = after->getArgument(0);
453     Value end = after->getArgument(1);
454     Value distance = b.create<arith::SubIOp>(end, start);
455     Value halfDistance = b.create<arith::DivSIOp>(distance, c2);
456     Value midIndex = b.create<arith::AddIOp>(start, halfDistance);
457 
458     // Call parallel compute function inside the async.execute region.
459     auto executeBodyBuilder = [&](OpBuilder &executeBuilder,
460                                   Location executeLoc, ValueRange executeArgs) {
461       // Update the original `blockStart` and `blockEnd` with new range.
462       SmallVector<Value> operands{block->getArguments().begin(),
463                                   block->getArguments().end()};
464       operands[1] = midIndex;
465       operands[2] = end;
466 
467       executeBuilder.create<CallOp>(executeLoc, func.sym_name(),
468                                     func.getCallableResults(), operands);
469       executeBuilder.create<async::YieldOp>(executeLoc, ValueRange());
470     };
471 
472     // Create async.execute operation to dispatch half of the block range.
473     auto execute = b.create<ExecuteOp>(TypeRange(), ValueRange(), ValueRange(),
474                                        executeBodyBuilder);
475     b.create<AddToGroupOp>(indexTy, execute.token(), group);
476     b.create<scf::YieldOp>(ValueRange({start, midIndex}));
477   }
478 
479   // After dispatching async operations to process the tail of the block range
480   // call the parallel compute function for the first block of the range.
481   b.setInsertionPointAfter(whileOp);
482 
483   // Drop async dispatch specific arguments: async group, block start and end.
484   auto forwardedInputs = block->getArguments().drop_front(3);
485   SmallVector<Value> computeFuncOperands = {blockStart};
486   computeFuncOperands.append(forwardedInputs.begin(), forwardedInputs.end());
487 
488   b.create<CallOp>(computeFunc.func.sym_name(),
489                    computeFunc.func.getCallableResults(), computeFuncOperands);
490   b.create<ReturnOp>(ValueRange());
491 
492   return func;
493 }
494 
495 // Launch async dispatch of the parallel compute function.
496 static void doAsyncDispatch(ImplicitLocOpBuilder &b, PatternRewriter &rewriter,
497                             ParallelComputeFunction &parallelComputeFunction,
498                             scf::ParallelOp op, Value blockSize,
499                             Value blockCount,
500                             const SmallVector<Value> &tripCounts) {
501   MLIRContext *ctx = op->getContext();
502 
503   // Add one more level of indirection to dispatch parallel compute functions
504   // using async operations and recursive work splitting.
505   FuncOp asyncDispatchFunction =
506       createAsyncDispatchFunction(parallelComputeFunction, rewriter);
507 
508   Value c0 = b.create<arith::ConstantIndexOp>(0);
509   Value c1 = b.create<arith::ConstantIndexOp>(1);
510 
511   // Appends operands shared by async dispatch and parallel compute functions to
512   // the given operands vector.
513   auto appendBlockComputeOperands = [&](SmallVector<Value> &operands) {
514     operands.append(tripCounts);
515     operands.append(op.lowerBound().begin(), op.lowerBound().end());
516     operands.append(op.upperBound().begin(), op.upperBound().end());
517     operands.append(op.step().begin(), op.step().end());
518     operands.append(parallelComputeFunction.captures);
519   };
520 
521   // Check if the block size is one, in this case we can skip the async dispatch
522   // completely. If this will be known statically, then canonicalization will
523   // erase async group operations.
524   Value isSingleBlock =
525       b.create<arith::CmpIOp>(arith::CmpIPredicate::eq, blockCount, c1);
526 
527   auto syncDispatch = [&](OpBuilder &nestedBuilder, Location loc) {
528     ImplicitLocOpBuilder nb(loc, nestedBuilder);
529 
530     // Call parallel compute function for the single block.
531     SmallVector<Value> operands = {c0, blockSize};
532     appendBlockComputeOperands(operands);
533 
534     nb.create<CallOp>(parallelComputeFunction.func.sym_name(),
535                       parallelComputeFunction.func.getCallableResults(),
536                       operands);
537     nb.create<scf::YieldOp>();
538   };
539 
540   auto asyncDispatch = [&](OpBuilder &nestedBuilder, Location loc) {
541     // Create an async.group to wait on all async tokens from the concurrent
542     // execution of multiple parallel compute function. First block will be
543     // executed synchronously in the caller thread.
544     Value groupSize = b.create<arith::SubIOp>(blockCount, c1);
545     Value group = b.create<CreateGroupOp>(GroupType::get(ctx), groupSize);
546 
547     ImplicitLocOpBuilder nb(loc, nestedBuilder);
548 
549     // Launch async dispatch function for [0, blockCount) range.
550     SmallVector<Value> operands = {group, c0, blockCount, blockSize};
551     appendBlockComputeOperands(operands);
552 
553     nb.create<CallOp>(asyncDispatchFunction.sym_name(),
554                       asyncDispatchFunction.getCallableResults(), operands);
555 
556     // Wait for the completion of all parallel compute operations.
557     b.create<AwaitAllOp>(group);
558 
559     nb.create<scf::YieldOp>();
560   };
561 
562   // Dispatch either single block compute function, or launch async dispatch.
563   b.create<scf::IfOp>(TypeRange(), isSingleBlock, syncDispatch, asyncDispatch);
564 }
565 
566 // Dispatch parallel compute functions by submitting all async compute tasks
567 // from a simple for loop in the caller thread.
568 static void
569 doSequentialDispatch(ImplicitLocOpBuilder &b, PatternRewriter &rewriter,
570                      ParallelComputeFunction &parallelComputeFunction,
571                      scf::ParallelOp op, Value blockSize, Value blockCount,
572                      const SmallVector<Value> &tripCounts) {
573   MLIRContext *ctx = op->getContext();
574 
575   FuncOp compute = parallelComputeFunction.func;
576 
577   Value c0 = b.create<arith::ConstantIndexOp>(0);
578   Value c1 = b.create<arith::ConstantIndexOp>(1);
579 
580   // Create an async.group to wait on all async tokens from the concurrent
581   // execution of multiple parallel compute function. First block will be
582   // executed synchronously in the caller thread.
583   Value groupSize = b.create<arith::SubIOp>(blockCount, c1);
584   Value group = b.create<CreateGroupOp>(GroupType::get(ctx), groupSize);
585 
586   // Call parallel compute function for all blocks.
587   using LoopBodyBuilder =
588       std::function<void(OpBuilder &, Location, Value, ValueRange)>;
589 
590   // Returns parallel compute function operands to process the given block.
591   auto computeFuncOperands = [&](Value blockIndex) -> SmallVector<Value> {
592     SmallVector<Value> computeFuncOperands = {blockIndex, blockSize};
593     computeFuncOperands.append(tripCounts);
594     computeFuncOperands.append(op.lowerBound().begin(), op.lowerBound().end());
595     computeFuncOperands.append(op.upperBound().begin(), op.upperBound().end());
596     computeFuncOperands.append(op.step().begin(), op.step().end());
597     computeFuncOperands.append(parallelComputeFunction.captures);
598     return computeFuncOperands;
599   };
600 
601   // Induction variable is the index of the block: [0, blockCount).
602   LoopBodyBuilder loopBuilder = [&](OpBuilder &loopBuilder, Location loc,
603                                     Value iv, ValueRange args) {
604     ImplicitLocOpBuilder nb(loc, loopBuilder);
605 
606     // Call parallel compute function inside the async.execute region.
607     auto executeBodyBuilder = [&](OpBuilder &executeBuilder,
608                                   Location executeLoc, ValueRange executeArgs) {
609       executeBuilder.create<CallOp>(executeLoc, compute.sym_name(),
610                                     compute.getCallableResults(),
611                                     computeFuncOperands(iv));
612       executeBuilder.create<async::YieldOp>(executeLoc, ValueRange());
613     };
614 
615     // Create async.execute operation to launch parallel computate function.
616     auto execute = nb.create<ExecuteOp>(TypeRange(), ValueRange(), ValueRange(),
617                                         executeBodyBuilder);
618     nb.create<AddToGroupOp>(rewriter.getIndexType(), execute.token(), group);
619     nb.create<scf::YieldOp>();
620   };
621 
622   // Iterate over all compute blocks and launch parallel compute operations.
623   b.create<scf::ForOp>(c1, blockCount, c1, ValueRange(), loopBuilder);
624 
625   // Call parallel compute function for the first block in the caller thread.
626   b.create<CallOp>(compute.sym_name(), compute.getCallableResults(),
627                    computeFuncOperands(c0));
628 
629   // Wait for the completion of all async compute operations.
630   b.create<AwaitAllOp>(group);
631 }
632 
633 LogicalResult
634 AsyncParallelForRewrite::matchAndRewrite(scf::ParallelOp op,
635                                          PatternRewriter &rewriter) const {
636   // We do not currently support rewrite for parallel op with reductions.
637   if (op.getNumReductions() != 0)
638     return failure();
639 
640   ImplicitLocOpBuilder b(op.getLoc(), rewriter);
641 
642   // Compute trip count for each loop induction variable:
643   //   tripCount = ceil_div(upperBound - lowerBound, step);
644   SmallVector<Value> tripCounts(op.getNumLoops());
645   for (size_t i = 0; i < op.getNumLoops(); ++i) {
646     auto lb = op.lowerBound()[i];
647     auto ub = op.upperBound()[i];
648     auto step = op.step()[i];
649     auto range = b.create<arith::SubIOp>(ub, lb);
650     tripCounts[i] = b.create<arith::CeilDivSIOp>(range, step);
651   }
652 
653   // Compute a product of trip counts to get the 1-dimensional iteration space
654   // for the scf.parallel operation.
655   Value tripCount = tripCounts[0];
656   for (size_t i = 1; i < tripCounts.size(); ++i)
657     tripCount = b.create<arith::MulIOp>(tripCount, tripCounts[i]);
658 
659   // Short circuit no-op parallel loops (zero iterations) that can arise from
660   // the memrefs with dynamic dimension(s) equal to zero.
661   Value c0 = b.create<arith::ConstantIndexOp>(0);
662   Value isZeroIterations =
663       b.create<arith::CmpIOp>(arith::CmpIPredicate::eq, tripCount, c0);
664 
665   // Do absolutely nothing if the trip count is zero.
666   auto noOp = [&](OpBuilder &nestedBuilder, Location loc) {
667     nestedBuilder.create<scf::YieldOp>(loc);
668   };
669 
670   // Compute the parallel block size and dispatch concurrent tasks computing
671   // results for each block.
672   auto dispatch = [&](OpBuilder &nestedBuilder, Location loc) {
673     ImplicitLocOpBuilder nb(loc, nestedBuilder);
674 
675     // With large number of threads the value of creating many compute blocks
676     // is reduced because the problem typically becomes memory bound. For small
677     // number of threads it helps with stragglers.
678     float overshardingFactor = numWorkerThreads <= 4    ? 8.0
679                                : numWorkerThreads <= 8  ? 4.0
680                                : numWorkerThreads <= 16 ? 2.0
681                                : numWorkerThreads <= 32 ? 1.0
682                                : numWorkerThreads <= 64 ? 0.8
683                                                         : 0.6;
684 
685     // Do not overload worker threads with too many compute blocks.
686     Value maxComputeBlocks = b.create<arith::ConstantIndexOp>(
687         std::max(1, static_cast<int>(numWorkerThreads * overshardingFactor)));
688 
689     // Target block size from the pass parameters.
690     Value minTaskSizeCst = b.create<arith::ConstantIndexOp>(minTaskSize);
691 
692     // Compute parallel block size from the parallel problem size:
693     //   blockSize = min(tripCount,
694     //                   max(ceil_div(tripCount, maxComputeBlocks),
695     //                       ceil_div(minTaskSize, bodySize)))
696     Value bs0 = b.create<arith::CeilDivSIOp>(tripCount, maxComputeBlocks);
697     Value bs1 = b.create<arith::MaxSIOp>(bs0, minTaskSizeCst);
698     Value blockSize = b.create<arith::MinSIOp>(tripCount, bs1);
699     Value blockCount = b.create<arith::CeilDivSIOp>(tripCount, blockSize);
700 
701     // Create a parallel compute function that takes a block id and computes the
702     // parallel operation body for a subset of iteration space.
703     ParallelComputeFunction parallelComputeFunction =
704         createParallelComputeFunction(op, rewriter);
705 
706     // Dispatch parallel compute function using async recursive work splitting,
707     // or by submitting compute task sequentially from a caller thread.
708     if (asyncDispatch) {
709       doAsyncDispatch(b, rewriter, parallelComputeFunction, op, blockSize,
710                       blockCount, tripCounts);
711     } else {
712       doSequentialDispatch(b, rewriter, parallelComputeFunction, op, blockSize,
713                            blockCount, tripCounts);
714     }
715 
716     nb.create<scf::YieldOp>();
717   };
718 
719   // Replace the `scf.parallel` operation with the parallel compute function.
720   b.create<scf::IfOp>(TypeRange(), isZeroIterations, noOp, dispatch);
721 
722   // Parallel operation was replaced with a block iteration loop.
723   rewriter.eraseOp(op);
724 
725   return success();
726 }
727 
728 void AsyncParallelForPass::runOnOperation() {
729   MLIRContext *ctx = &getContext();
730 
731   RewritePatternSet patterns(ctx);
732   patterns.add<AsyncParallelForRewrite>(ctx, asyncDispatch, numWorkerThreads,
733                                         minTaskSize);
734 
735   if (failed(applyPatternsAndFoldGreedily(getOperation(), std::move(patterns))))
736     signalPassFailure();
737 }
738 
739 std::unique_ptr<Pass> mlir::createAsyncParallelForPass() {
740   return std::make_unique<AsyncParallelForPass>();
741 }
742 
743 std::unique_ptr<Pass> mlir::createAsyncParallelForPass(bool asyncDispatch,
744                                                        int32_t numWorkerThreads,
745                                                        int32_t minTaskSize) {
746   return std::make_unique<AsyncParallelForPass>(asyncDispatch, numWorkerThreads,
747                                                 minTaskSize);
748 }
749