1 //===- Loops.cpp - conversion from Linalg named and generic ops to loops --===//
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 #include "PassDetail.h"
10 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
11 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
12 #include "mlir/Dialect/Linalg/Passes.h"
13 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
14 #include "mlir/Dialect/Linalg/Utils/Utils.h"
15 #include "mlir/Dialect/StandardOps/Utils/Utils.h"
16 #include "mlir/IR/AffineExpr.h"
17 #include "mlir/IR/AffineMap.h"
18 #include "mlir/IR/BlockAndValueMapping.h"
19 #include "mlir/Support/LLVM.h"
20 #include "mlir/Transforms/DialectConversion.h"
21 #include "mlir/Transforms/FoldUtils.h"
22 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
23 #include "llvm/ADT/TypeSwitch.h"
24 
25 using namespace mlir;
26 using namespace mlir::linalg;
27 
28 static SmallVector<Value> makeCanonicalAffineApplies(OpBuilder &b, Location loc,
29                                                      AffineMap map,
30                                                      ArrayRef<Value> vals) {
31   if (map.isEmpty())
32     return {};
33 
34   assert(map.getNumInputs() == vals.size());
35   SmallVector<Value> res;
36   res.reserve(map.getNumResults());
37   auto dims = map.getNumDims();
38   for (auto e : map.getResults()) {
39     auto exprMap = AffineMap::get(dims, map.getNumSymbols(), e);
40     SmallVector<Value> operands(vals.begin(), vals.end());
41     canonicalizeMapAndOperands(&exprMap, &operands);
42     res.push_back(b.create<AffineApplyOp>(loc, exprMap, operands));
43   }
44   return res;
45 }
46 
47 template <typename LoadOpTy, typename StoreOpTy, typename OpType>
48 static void inlineRegionAndEmitStore(OpBuilder &b, Location loc, OpType op,
49                                      ArrayRef<Value> indexedValues,
50                                      ArrayRef<SmallVector<Value>> indexing,
51                                      ArrayRef<Value> outputBuffers) {
52   auto &block = op->getRegion(0).front();
53   BlockAndValueMapping map;
54   map.map(block.getArguments(), indexedValues);
55   for (auto &op : block.without_terminator()) {
56     auto *newOp = b.clone(op, map);
57     map.map(op.getResults(), newOp->getResults());
58   }
59 
60   Operation *terminator = block.getTerminator();
61   for (OpOperand &operand : terminator->getOpOperands()) {
62     Value toStore = map.lookupOrDefault(operand.get());
63     b.create<StoreOpTy>(loc, toStore, outputBuffers[operand.getOperandNumber()],
64                         indexing[operand.getOperandNumber()]);
65   }
66 }
67 
68 // Returns a pair that contains input indices and output indices of a
69 // SingleInputPoolingOp `op`.
70 struct InputAndOutputIndices {
71   SmallVector<Value> inputs;
72   SmallVector<Value> outputs;
73 };
74 template <typename SingleInputPoolingOp>
75 static InputAndOutputIndices
76 getInputAndOutputIndices(OpBuilder &b, Location loc, ArrayRef<Value> allIvs,
77                          SingleInputPoolingOp op) {
78   auto mapsRange = op.indexing_maps().template getAsRange<AffineMapAttr>();
79   auto maps = llvm::to_vector<8>(
80       llvm::map_range(mapsRange, [](AffineMapAttr a) { return a.getValue(); }));
81   return InputAndOutputIndices{
82       makeCanonicalAffineApplies(b, loc, maps[0], allIvs),
83       makeCanonicalAffineApplies(b, loc, maps[2], allIvs)};
84 }
85 
86 /// Emits the MLIR for the scalar part of the generic op by:
87 ///   1. Emitting load ops for each input and output view in order. This is
88 ///      achieved by applying the appropriate input or output map to the
89 ///      enclosing induction variables.
90 ///   2. Emitting a call to `op.fun()` that takes as arguments the scalars
91 ///      from point 1. above.
92 ///   3. Emitting store ops to store the results of 2. to the output
93 ///      views.
94 ///
95 /// An example output may resemble:
96 ///
97 /// ```
98 ///    scf.for %i = %c0 to %0 step %c1 {
99 ///      scf.for %j = %c0 to %1 step %c1 {
100 ///        scf.for %k = %c0 to %4 step %c1 {
101 ///          %11 = load %arg0[%i, %j] :
102 ///            memref<?x?xf32, stride_specification>
103 ///          %12 = load %arg1[%i, %j, %k] :
104 ///            memref<?x?x?xf32, stride_specification>
105 ///          %13 = load %arg2[%i, %k, %j] :
106 ///            memref<?x?x?xf32, stride_specification>
107 ///          %14:2 = call @foo(%11, %12, %13) : (f32, f32, f32) -> (f32, f32)
108 ///          store %14#0, %arg1[%i, %j, %k] :
109 ///            memref<?x?x?Xf32, stride_specification>
110 ///          store %14#1, %arg2[%i, %k, %j] :
111 ///            memref<?x?x?Xf32, stride_specification>
112 ///       }
113 ///      }
114 ///    }
115 /// ```
116 template <typename LoadOpTy, typename StoreOpTy>
117 static void emitScalarImplementation(OpBuilder &b, Location loc,
118                                      ArrayRef<Value> allIvs,
119                                      LinalgOp linalgOp) {
120   assert(linalgOp.hasBufferSemantics() &&
121          "expected linalg op with buffer semantics");
122   SmallVector<Value> indexedValues;
123   indexedValues.reserve(linalgOp.getNumInputsAndOutputs());
124 
125   auto allIvsPlusDims = SmallVector<Value>(allIvs.begin(), allIvs.end());
126 
127   // TODO: Avoid the loads if the corresponding argument of the
128   // region has no uses.
129   // 1.a. Emit load from input views.
130   for (OpOperand *inputOperand : linalgOp.getInputOperands()) {
131     auto indexing = makeCanonicalAffineApplies(
132         b, loc, linalgOp.getTiedIndexingMap(inputOperand), allIvsPlusDims);
133     indexedValues.push_back(
134         b.create<LoadOpTy>(loc, inputOperand->get(), indexing));
135   }
136   // 1.b. Emit load from output views.
137   for (OpOperand *outputOperand : linalgOp.getOutputOperands()) {
138     SmallVector<Value> indexing = makeCanonicalAffineApplies(
139         b, loc, linalgOp.getTiedIndexingMap(outputOperand), allIvsPlusDims);
140     indexedValues.push_back(
141         b.create<LoadOpTy>(loc, outputOperand->get(), indexing));
142   }
143 
144   // TODO: When a region inliner exists, use it.
145   // 2. Inline region, currently only works for a single basic block.
146   // 3. Emit store.
147   SmallVector<SmallVector<Value>, 8> indexing;
148   SmallVector<Value> outputBuffers;
149   for (OpOperand *outputOperand : linalgOp.getOutputBufferOperands()) {
150     indexing.push_back(makeCanonicalAffineApplies(
151         b, loc, linalgOp.getTiedIndexingMap(outputOperand), allIvsPlusDims));
152     outputBuffers.push_back(outputOperand->get());
153   }
154   inlineRegionAndEmitStore<LoadOpTy, StoreOpTy>(b, loc, linalgOp, indexedValues,
155                                                 indexing, outputBuffers);
156 }
157 
158 // Create a padded view into the given `input` tensor using the 'indices'
159 // to access the tensor. `skipPadding` lists the dimensions for which no padding
160 // is needed e.g. the non-spatial dimensions for convolutions.
161 Value getPaddedInput(OpBuilder &b, Location loc, Value input,
162                      ArrayRef<Value> indices, ArrayRef<int> skipPadding,
163                      Value padValue) {
164   Value zeroIndex = b.create<ConstantIndexOp>(loc, 0);
165   SmallVector<Value> conds;
166   SmallVector<Value> clampedImIdx;
167   for (auto iter : llvm::enumerate(indices)) {
168     int idx = iter.index();
169     auto dim = iter.value();
170     if (is_contained(skipPadding, idx)) {
171       clampedImIdx.push_back(dim);
172       continue;
173     }
174 
175     Value leftOutOfBound =
176         b.create<CmpIOp>(loc, CmpIPredicate::slt, dim, zeroIndex);
177     if (conds.empty())
178       conds.push_back(leftOutOfBound);
179     else
180       conds.push_back(b.create<OrOp>(loc, conds.back(), leftOutOfBound));
181     Value rightBound = b.create<memref::DimOp>(loc, input, idx);
182     Value rightOutOfBound =
183         b.create<CmpIOp>(loc, CmpIPredicate::sge, dim, rightBound);
184     conds.push_back(b.create<OrOp>(loc, conds.back(), rightOutOfBound));
185 
186     // When padding is involved, the indices will only be shifted to negative,
187     // so having a max op is enough.
188     MLIRContext *ctx = input.getContext();
189     AffineExpr m = getAffineDimExpr(/*position=*/0, ctx),
190                zero = getAffineConstantExpr(0, ctx);
191     AffineMap maxMap =
192         AffineMap::inferFromExprList(ArrayRef<ArrayRef<AffineExpr>>{{m, zero}})
193             .front();
194     clampedImIdx.push_back(b.create<AffineMaxOp>(loc, maxMap, ValueRange{dim}));
195   }
196 
197   Value readInput = b.create<memref::LoadOp>(loc, input, clampedImIdx);
198   if (conds.empty())
199     return readInput;
200 
201   return b.create<SelectOp>(loc, conds.back(), padValue, readInput);
202 }
203 
204 namespace {
205 
206 /// The padding value for a given Op depends on the semantics of the Op.
207 /// The identity value for ConvOp and PoolingSumOp is 0, for PoolingMaxOp is
208 /// -inf or minInt and for PoolingMinOp is inf or maxInt.
209 template <typename OpType> Attribute getPadValueAttr(Type type) {
210   llvm_unreachable("Unexpected op type for getPadValueAttr");
211   return {};
212 }
213 
214 template <> Attribute getPadValueAttr<PoolingMaxOp>(Type type) {
215   if (auto floatType = type.dyn_cast<FloatType>()) {
216     return OpBuilder(type.getContext())
217         .getFloatAttr(floatType, APFloat::getInf(floatType.getFloatSemantics(),
218                                                  /*Negative*/ true));
219   }
220   if (auto intType = type.dyn_cast<IntegerType>()) {
221     unsigned width = intType.getWidth();
222     // The select instruction used to lower the PoolingMin uses a signed
223     // comparison, use a signed constant irrespective of the signedness of the
224     // integer type.
225     return OpBuilder(type.getContext())
226         .getIntegerAttr(intType, APInt::getSignedMinValue(width));
227   }
228   llvm_unreachable("Unsupported data type for PoolingMaxOp");
229   return {};
230 }
231 
232 template <> Attribute getPadValueAttr<PoolingMinOp>(Type type) {
233   if (auto floatType = type.dyn_cast<FloatType>()) {
234     return OpBuilder(type.getContext())
235         .getFloatAttr(floatType,
236                       APFloat::getInf(floatType.getFloatSemantics()));
237   }
238   if (auto intType = type.dyn_cast<IntegerType>()) {
239     unsigned width = intType.getWidth();
240     // The select instruction used to lower the PoolingMin uses a signed
241     // comparison, use a signed constant irrespective of the signedness of the
242     // integer type.
243     return OpBuilder(type.getContext())
244         .getIntegerAttr(intType, APInt::getSignedMaxValue(width));
245   }
246   llvm_unreachable("Unsupported data type for PoolingMinOp");
247   return {};
248 }
249 
250 template <> Attribute getPadValueAttr<PoolingSumOp>(Type type) {
251   return OpBuilder(type.getContext()).getZeroAttr(type);
252 }
253 
254 template <> Attribute getPadValueAttr<ConvOp>(Type type) {
255   return OpBuilder(type.getContext()).getZeroAttr(type);
256 }
257 
258 } // namespace
259 
260 /// Returns true is `convOp` has a non-zero padding.
261 static bool hasPadding(ConvOp convOp) {
262   for (unsigned i = 0, e = convOp.getNumSpatialDimensions(); i < e; ++i) {
263     if (convOp.getLowPad(i) > 0 || convOp.getHighPad(i) > 0)
264       return true;
265   }
266   return false;
267 }
268 
269 template <typename LoadOpTy, typename StoreOpTy>
270 static void emitScalarImplementation(OpBuilder &b, Location loc,
271                                      ArrayRef<Value> allIvs, ConvOp convOp) {
272   assert(convOp.hasBufferSemantics() &&
273          "expected linalg op with buffer semantics");
274   auto mapsRange = convOp.indexing_maps().getAsRange<AffineMapAttr>();
275   auto maps = llvm::to_vector<8>(
276       llvm::map_range(mapsRange, [](AffineMapAttr a) { return a.getValue(); }));
277   SmallVector<Value> fIdx(makeCanonicalAffineApplies(b, loc, maps[0], allIvs));
278   SmallVector<Value> imIdx(makeCanonicalAffineApplies(b, loc, maps[1], allIvs));
279   SmallVector<Value> oIdx(makeCanonicalAffineApplies(b, loc, maps[2], allIvs));
280 
281   Value filter = convOp.filter(), output = convOp.output();
282 
283   // Emit scalar form. Padded conv involves an affine.max in the memory access
284   // which is not allowed by affine.load. Override to use an MemRefIndexedValue
285   // when there is non-zero padding.
286   if (hasPadding(convOp)) {
287     Type type = convOp.input().getType().cast<MemRefType>().getElementType();
288     Value padValue =
289         b.create<ConstantOp>(loc, type, getPadValueAttr<ConvOp>(type));
290     Value paddedInput =
291         getPaddedInput(b, loc, convOp.input(), imIdx,
292                        /* Only need to pad the window dimensions */
293                        {0, static_cast<int>(imIdx.size()) - 1}, padValue);
294     Value filterVal = b.create<LoadOpTy>(loc, filter, fIdx);
295     Value mulVal = ArithBuilder(b, loc).mul(filterVal, paddedInput);
296     Value outputVal = b.create<LoadOpTy>(loc, output, oIdx);
297     Value addVal = ArithBuilder(b, loc).add(mulVal, outputVal);
298     b.create<StoreOpTy>(loc, addVal, output, oIdx);
299   } else {
300     Value inputVal = b.create<LoadOpTy>(loc, convOp.input(), imIdx);
301     Value filterVal = b.create<LoadOpTy>(loc, filter, fIdx);
302     Value mulVal = ArithBuilder(b, loc).mul(filterVal, inputVal);
303     Value outputVal = b.create<LoadOpTy>(loc, output, oIdx);
304     Value addVal = ArithBuilder(b, loc).add(mulVal, outputVal);
305     b.create<StoreOpTy>(loc, addVal, output, oIdx);
306   }
307 }
308 
309 template <typename PoolingOp> static bool hasPadding(PoolingOp poolingOp) {
310   for (unsigned i = 0, e = poolingOp.getNumWindowLoops(); i < e; ++i) {
311     if (poolingOp.getLowPad(i) > 0 || poolingOp.getHighPad(i) > 0)
312       return true;
313   }
314   return false;
315 }
316 
317 template <typename LoadOpTy, typename StoreOpTy, typename PoolingOp>
318 static Value getPoolingInput(OpBuilder &b, Location loc, PoolingOp op,
319                              ArrayRef<Value> inputIndices) {
320   if (hasPadding(op)) {
321     Type type =
322         op.input().getType().template cast<MemRefType>().getElementType();
323     Value padValue =
324         b.create<ConstantOp>(loc, type, getPadValueAttr<PoolingOp>(type));
325     return getPaddedInput(b, loc, op.input(), inputIndices,
326                           /*Pad every dimension*/ {}, padValue);
327   }
328   return b.create<LoadOpTy>(loc, op.input(), inputIndices);
329 }
330 
331 template <typename LoadOpTy, typename StoreOpTy, typename OpType>
332 void emitPoolingMinMaxScalarImplementation(OpBuilder &b, Location loc,
333                                            ArrayRef<Value> allIvs, OpType op) {
334   InputAndOutputIndices indices = getInputAndOutputIndices(b, loc, allIvs, op);
335   Value lhs = b.create<LoadOpTy>(loc, op.output(), indices.outputs);
336   Value rhs = getPoolingInput<LoadOpTy, StoreOpTy>(b, loc, op, indices.inputs);
337   Value value = llvm::TypeSwitch<Operation *, Value>(op)
338                     .Case([&](PoolingMinOp poolingOp) {
339                       return ArithBuilder(b, loc).select(
340                           ArithBuilder(b, loc).slt(lhs, rhs), lhs, rhs);
341                     })
342                     .Case([&](PoolingMaxOp poolingOp) {
343                       return ArithBuilder(b, loc).select(
344                           ArithBuilder(b, loc).sgt(lhs, rhs), lhs, rhs);
345                     })
346                     .Default([&](auto) { return Value(); });
347   b.create<StoreOpTy>(loc, value, op.output(), indices.outputs);
348 }
349 
350 template <typename LoadOpTy, typename StoreOpTy>
351 static void emitScalarImplementation(OpBuilder &b, Location loc,
352                                      ArrayRef<Value> allIvs, PoolingMaxOp op) {
353   emitPoolingMinMaxScalarImplementation<LoadOpTy, StoreOpTy, PoolingMaxOp>(
354       b, loc, allIvs, op);
355 }
356 
357 template <typename LoadOpTy, typename StoreOpTy>
358 static void emitScalarImplementation(OpBuilder &b, Location loc,
359                                      ArrayRef<Value> allIvs, PoolingMinOp op) {
360   emitPoolingMinMaxScalarImplementation<LoadOpTy, StoreOpTy, PoolingMinOp>(
361       b, loc, allIvs, op);
362 }
363 
364 template <typename LoadOpTy, typename StoreOpTy>
365 static void emitScalarImplementation(OpBuilder &b, Location loc,
366                                      ArrayRef<Value> allIvs, PoolingSumOp op) {
367   auto indices = getInputAndOutputIndices(b, loc, allIvs, op);
368   Value inputVal =
369       getPoolingInput<LoadOpTy, StoreOpTy>(b, loc, op, indices.inputs);
370   Value outputVal = b.create<LoadOpTy>(loc, op.output(), indices.outputs);
371   Value added = ArithBuilder(b, loc).add(outputVal, inputVal);
372   b.create<StoreOpTy>(loc, added, op.output(), indices.outputs);
373 }
374 
375 /// Replace the index operations in the body of the loop nest by the matching
376 /// induction variables.
377 static void replaceIndexOpsByInductionVariables(LinalgOp linalgOp,
378                                                 PatternRewriter &rewriter,
379                                                 ArrayRef<Operation *> loopOps) {
380   // Extract the induction variables of the loop nest from outer to inner.
381   SmallVector<Value> allIvs;
382   for (Operation *loopOp : loopOps) {
383     llvm::TypeSwitch<Operation *>(loopOp)
384         .Case([&](scf::ParallelOp parallelOp) {
385           allIvs.append(parallelOp.getInductionVars().begin(),
386                         parallelOp.getInductionVars().end());
387         })
388         .Case([&](scf::ForOp forOp) {
389           allIvs.push_back(forOp.getInductionVar());
390         })
391         .Case([&](AffineForOp affineForOp) {
392           allIvs.push_back(affineForOp.getInductionVar());
393         })
394         .Default([&](Operation *op) { assert(false && "unexpected op"); });
395   }
396   assert(linalgOp.getNumLoops() == allIvs.size() &&
397          "expected the number of loops and induction variables to match");
398   // Replace the index operations in the body of the innermost loop op.
399   if (!loopOps.empty()) {
400     LoopLikeOpInterface loopOp = loopOps.back();
401     for (IndexOp indexOp :
402          llvm::make_early_inc_range(loopOp.getLoopBody().getOps<IndexOp>()))
403       rewriter.replaceOp(indexOp, allIvs[indexOp.dim()]);
404   }
405 }
406 
407 template <typename LoopTy>
408 static Optional<LinalgLoops> linalgOpToLoopsImpl(PatternRewriter &rewriter,
409                                                  LinalgOp linalgOp) {
410   using LoadOpTy =
411       typename std::conditional<std::is_same<LoopTy, AffineForOp>::value,
412                                 AffineLoadOp, memref::LoadOp>::type;
413   using StoreOpTy =
414       typename std::conditional<std::is_same<LoopTy, AffineForOp>::value,
415                                 AffineStoreOp, memref::StoreOp>::type;
416 
417   // Canonicalize indexed_generic operations before lowering them to loops.
418   if (isa<IndexedGenericOp>(linalgOp))
419     return llvm::None;
420 
421   // The flattened loopToOperandRangesMaps is expected to be an invertible
422   // permutation map (which is asserted in the inverse calculation).
423   assert(linalgOp.hasBufferSemantics() &&
424          "expected linalg op with buffer semantics");
425 
426   auto loopRanges = linalgOp.createLoopRanges(rewriter, linalgOp.getLoc());
427   auto iteratorTypes = llvm::to_vector<4>(linalgOp.iterator_types().getValue());
428 
429   SmallVector<Value> allIvs;
430   GenerateLoopNest<LoopTy>::doit(
431       rewriter, linalgOp.getLoc(), loopRanges, linalgOp, iteratorTypes,
432       [&](OpBuilder &b, Location loc, ValueRange ivs,
433           ValueRange iterArgs) -> scf::ValueVector {
434         assert(iterArgs.empty() && "unexpected iterArgs");
435         allIvs.append(ivs.begin(), ivs.end());
436         llvm::TypeSwitch<Operation *>(linalgOp)
437             .Case<ConvOp, PoolingMaxOp, PoolingMinOp, PoolingSumOp, LinalgOp>(
438                 [&](auto op) {
439                   emitScalarImplementation<LoadOpTy, StoreOpTy>(b, loc, allIvs,
440                                                                 op);
441                 })
442             .Default([&](Operation *op) { assert(false && "unexpected op"); });
443         return scf::ValueVector{};
444       });
445   // Number of loop ops might be different from the number of ivs since some
446   // loops like affine.parallel and scf.parallel have multiple ivs.
447   SetVector<Operation *> loopSet;
448   for (Value iv : allIvs) {
449     if (!iv)
450       return {};
451     // The induction variable is a block argument of the entry block of the
452     // loop operation.
453     BlockArgument ivVal = iv.dyn_cast<BlockArgument>();
454     if (!ivVal)
455       return {};
456     loopSet.insert(ivVal.getOwner()->getParentOp());
457   }
458   LinalgLoops loops(loopSet.begin(), loopSet.end());
459   // Replace all index operations in the loop body.
460   replaceIndexOpsByInductionVariables(linalgOp, rewriter, loops);
461   return loops;
462 }
463 
464 namespace {
465 template <typename LoopType>
466 class LinalgRewritePattern : public RewritePattern {
467 public:
468   LinalgRewritePattern(MLIRContext *context)
469       : RewritePattern(MatchAnyOpTypeTag(), /*benefit=*/1, context) {}
470 
471   LogicalResult matchAndRewrite(Operation *op,
472                                 PatternRewriter &rewriter) const override {
473     auto linalgOp = dyn_cast<LinalgOp>(op);
474     if (!isa<LinalgOp>(op))
475       return failure();
476     if (!linalgOpToLoopsImpl<LoopType>(rewriter, linalgOp))
477       return failure();
478     rewriter.eraseOp(op);
479     return success();
480   }
481 };
482 
483 struct TiledLoopToSCFPattern : public OpRewritePattern<TiledLoopOp> {
484   using OpRewritePattern<TiledLoopOp>::OpRewritePattern;
485 
486   LogicalResult matchAndRewrite(TiledLoopOp tiledLoop,
487                                 PatternRewriter &rewriter) const override {
488     Location loc = tiledLoop.getLoc();
489 
490     // Fail conversion if the `tiled_loop` has not been bufferized.
491     if (!llvm::all_of(tiledLoop.outputs(), [&](Value arg) {
492           return arg.getType().isa<MemRefType>();
493         }))
494       return failure();
495 
496     // TODO: Build loop nest with `scf.for` and `scf.parallel` depending on the
497     // iterator type.
498     scf::buildLoopNest(rewriter, loc, tiledLoop.lowerBound(),
499                        tiledLoop.upperBound(), tiledLoop.step(),
500                        [&](OpBuilder &builder, Location loc, ValueRange ivs) {
501                          // Move body without its terminator.
502                          SmallVector<Value> newBlockArgs;
503                          newBlockArgs.append(ivs.begin(), ivs.end());
504                          newBlockArgs.append(tiledLoop.inputs().begin(),
505                                              tiledLoop.inputs().end());
506                          newBlockArgs.append(tiledLoop.outputs().begin(),
507                                              tiledLoop.outputs().end());
508                          Block *newBody = rewriter.getInsertionBlock();
509                          rewriter.mergeBlocks(tiledLoop.getBody(), newBody,
510                                               newBlockArgs);
511                          rewriter.eraseOp(newBody->getTerminator());
512                        });
513     rewriter.eraseOp(tiledLoop);
514     return success();
515   }
516 };
517 
518 /// Local folding pattern for AffineApplyOp that we can apply greedily.
519 /// This replaces AffineApplyOp by the proper value in cases where the
520 /// associated map is trivial.
521 /// A trivial map here is defined as a map with a single result and either:
522 ///   1. Zero operand + returns a single AffineConstantExpr
523 ///   2. One operand + returns a single AffineDimExpr
524 ///   3. One operand + returns a single AffineSymbolExpr
525 //
526 /// In the first case, the AffineApplyOp is replaced by a new constant. In the
527 /// other cases, it is replaced by its unique operand.
528 struct FoldAffineOp : public RewritePattern {
529   FoldAffineOp(MLIRContext *context)
530       : RewritePattern(AffineApplyOp::getOperationName(), 0, context) {}
531 
532   LogicalResult matchAndRewrite(Operation *op,
533                                 PatternRewriter &rewriter) const override {
534     AffineApplyOp affineApplyOp = cast<AffineApplyOp>(op);
535     auto map = affineApplyOp.getAffineMap();
536     if (map.getNumResults() != 1 || map.getNumInputs() > 1)
537       return failure();
538 
539     AffineExpr expr = map.getResult(0);
540     if (map.getNumInputs() == 0) {
541       if (auto val = expr.dyn_cast<AffineConstantExpr>()) {
542         rewriter.replaceOpWithNewOp<ConstantIndexOp>(op, val.getValue());
543         return success();
544       }
545       return failure();
546     }
547     if (expr.dyn_cast<AffineDimExpr>() || expr.dyn_cast<AffineSymbolExpr>()) {
548       rewriter.replaceOp(op, op->getOperand(0));
549       return success();
550     }
551     return failure();
552   }
553 };
554 
555 template <typename LoopType>
556 static void lowerLinalgToLoopsImpl(FuncOp funcOp) {
557   MLIRContext *context = funcOp.getContext();
558   RewritePatternSet patterns(context);
559   patterns.add<LinalgRewritePattern<LoopType>>(context);
560   memref::DimOp::getCanonicalizationPatterns(patterns, context);
561   AffineApplyOp::getCanonicalizationPatterns(patterns, context);
562   patterns.add<FoldAffineOp>(context);
563   // Just apply the patterns greedily.
564   (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns));
565 }
566 
567 struct LowerToAffineLoops
568     : public LinalgLowerToAffineLoopsBase<LowerToAffineLoops> {
569   void getDependentDialects(DialectRegistry &registry) const override {
570     registry.insert<memref::MemRefDialect>();
571   }
572   void runOnFunction() override {
573     lowerLinalgToLoopsImpl<AffineForOp>(getFunction());
574   }
575 };
576 
577 struct LowerToLoops : public LinalgLowerToLoopsBase<LowerToLoops> {
578   void getDependentDialects(DialectRegistry &registry) const override {
579     registry.insert<memref::MemRefDialect, scf::SCFDialect>();
580   }
581   void runOnFunction() override {
582     lowerLinalgToLoopsImpl<scf::ForOp>(getFunction());
583   }
584 };
585 
586 struct LowerToParallelLoops
587     : public LinalgLowerToParallelLoopsBase<LowerToParallelLoops> {
588   void runOnFunction() override {
589     lowerLinalgToLoopsImpl<scf::ParallelOp>(getFunction());
590   }
591 };
592 
593 struct LowerTiledLoopsToSCF
594     : public LinalgLowerTiledLoopsToSCFBase<LowerTiledLoopsToSCF> {
595   void runOnFunction() override {
596     MLIRContext *context = &getContext();
597     RewritePatternSet patterns(context);
598     populateTiledLoopToSCFPattern(patterns);
599     (void)applyPatternsAndFoldGreedily(getFunction(), std::move(patterns));
600   }
601 };
602 } // namespace
603 
604 void mlir::linalg::populateTiledLoopToSCFPattern(RewritePatternSet &patterns) {
605   patterns.add<TiledLoopToSCFPattern>(patterns.getContext());
606 }
607 
608 std::unique_ptr<OperationPass<FuncOp>>
609 mlir::createConvertLinalgTiledLoopsToSCFPass() {
610   return std::make_unique<LowerTiledLoopsToSCF>();
611 }
612 
613 std::unique_ptr<OperationPass<FuncOp>> mlir::createConvertLinalgToLoopsPass() {
614   return std::make_unique<LowerToLoops>();
615 }
616 
617 std::unique_ptr<OperationPass<FuncOp>>
618 mlir::createConvertLinalgToParallelLoopsPass() {
619   return std::make_unique<LowerToParallelLoops>();
620 }
621 
622 std::unique_ptr<OperationPass<FuncOp>>
623 mlir::createConvertLinalgToAffineLoopsPass() {
624   return std::make_unique<LowerToAffineLoops>();
625 }
626 
627 /// Emits a loop nest of `affine.for` with the proper body for `linalgOp`.
628 Optional<LinalgLoops>
629 mlir::linalg::linalgOpToAffineLoops(PatternRewriter &rewriter,
630                                     LinalgOp linalgOp) {
631   return linalgOpToLoopsImpl<AffineForOp>(rewriter, linalgOp);
632 }
633 
634 /// Emits a loop nest of `scf.for` with the proper body for `linalgOp`.
635 Optional<LinalgLoops> mlir::linalg::linalgOpToLoops(PatternRewriter &rewriter,
636                                                     LinalgOp linalgOp) {
637   return linalgOpToLoopsImpl<scf::ForOp>(rewriter, linalgOp);
638 }
639 
640 /// Emits a loop nest of `scf.parallel` with the proper body for `linalgOp`.
641 Optional<LinalgLoops>
642 mlir::linalg::linalgOpToParallelLoops(PatternRewriter &rewriter,
643                                       LinalgOp linalgOp) {
644   return linalgOpToLoopsImpl<scf::ParallelOp>(rewriter, linalgOp);
645 }
646