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/Affine/EDSC/Intrinsics.h"
11 #include "mlir/Dialect/Linalg/EDSC/FoldedIntrinsics.h"
12 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
13 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
14 #include "mlir/Dialect/Linalg/Passes.h"
15 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
16 #include "mlir/Dialect/Linalg/Utils/Utils.h"
17 #include "mlir/Dialect/SCF/EDSC/Builders.h"
18 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h"
19 #include "mlir/IR/AffineExpr.h"
20 #include "mlir/IR/AffineMap.h"
21 #include "mlir/IR/BlockAndValueMapping.h"
22 #include "mlir/Support/LLVM.h"
23 #include "mlir/Transforms/DialectConversion.h"
24 #include "mlir/Transforms/FoldUtils.h"
25 
26 using namespace mlir;
27 using namespace mlir::edsc;
28 using namespace mlir::edsc::intrinsics;
29 using namespace mlir::linalg;
30 
31 using edsc::op::operator+;
32 
33 static SmallVector<Value, 8> makeCanonicalAffineApplies(OpBuilder &b,
34                                                         Location loc,
35                                                         AffineMap map,
36                                                         ArrayRef<Value> vals) {
37   if (map.isEmpty())
38     return {};
39 
40   assert(map.getNumInputs() == vals.size());
41   SmallVector<Value, 8> res;
42   res.reserve(map.getNumResults());
43   auto dims = map.getNumDims();
44   for (auto e : map.getResults()) {
45     auto exprMap = AffineMap::get(dims, map.getNumSymbols(), e);
46     SmallVector<Value, 4> operands(vals.begin(), vals.end());
47     canonicalizeMapAndOperands(&exprMap, &operands);
48     res.push_back(affine_apply(exprMap, operands));
49   }
50   return res;
51 }
52 
53 static SmallVector<Value, 4> permuteIvs(ArrayRef<Value> ivs,
54                                         Optional<AffineMap> permutation) {
55   return permutation ? applyMapToValues(ScopedContext::getBuilderRef(),
56                                         ScopedContext::getLocation(),
57                                         permutation.getValue(), ivs)
58                      : SmallVector<Value, 4>(ivs.begin(), ivs.end());
59 }
60 
61 template <typename IndexedValueType, typename OpType>
62 static void inlineRegionAndEmitStore(OpType op, ArrayRef<Value> indexedValues,
63                                      ArrayRef<SmallVector<Value, 8>> indexing,
64                                      ArrayRef<Value> outputBuffers) {
65   assert(op.getOperation()->getNumRegions() == 1 &&
66          "Expected single region op");
67   auto &b = ScopedContext::getBuilderRef();
68   auto &block = op.region().front();
69   BlockAndValueMapping map;
70   map.map(block.getArguments(), indexedValues);
71   for (auto &op : block.without_terminator()) {
72     assert(op.getNumRegions() == 0 && "expected a non-nested region");
73     auto *newOp = b.clone(op, map);
74     map.map(op.getResults(), newOp->getResults());
75   }
76 
77   Operation &terminator = block.back();
78   assert(isa<linalg::YieldOp>(terminator) &&
79          "expected a yield op in the end of the region");
80   for (unsigned i = 0, e = terminator.getNumOperands(); i < e; ++i) {
81     IndexedValueType O(outputBuffers[i]);
82     O(indexing[i]) = map.lookupOrDefault(terminator.getOperand(i));
83   }
84 }
85 
86 // Returns a pair that contains input indices and output indices of a
87 // SingleInputPoolingOp `op`.
88 struct InputAndOutputIndices {
89   SmallVector<Value, 8> inputs;
90   SmallVector<Value, 8> outputs;
91 };
92 template <typename SingleInputPoolingOp>
93 static InputAndOutputIndices getInputAndOutputIndices(ArrayRef<Value> allIvs,
94                                                       SingleInputPoolingOp op) {
95   auto &b = ScopedContext::getBuilderRef();
96   auto loc = ScopedContext::getLocation();
97   auto mapsRange = op.indexing_maps().template getAsRange<AffineMapAttr>();
98   auto maps = llvm::to_vector<8>(
99       llvm::map_range(mapsRange, [](AffineMapAttr a) { return a.getValue(); }));
100   return InputAndOutputIndices{
101       makeCanonicalAffineApplies(b, loc, maps[0], allIvs),
102       makeCanonicalAffineApplies(b, loc, maps[2], allIvs)};
103 }
104 
105 namespace {
106 
107 /// Emits the MLIR for the scalar part of the generic op by:
108 ///   1. Emitting load ops for each input and output view in order. This is
109 ///      achieved by applying the appropriate input or output map to the
110 ///      enclosing induction variables.
111 ///   2. Emitting a call to `op.fun()` that takes as arguments the scalars
112 ///      from point 1. above.
113 ///   3. Emitting store ops to store the results of 2. to the output
114 ///      views.
115 ///
116 /// An example output may resemble:
117 ///
118 /// ```
119 ///    scf.for %i = %c0 to %0 step %c1 {
120 ///      scf.for %j = %c0 to %1 step %c1 {
121 ///        scf.for %k = %c0 to %4 step %c1 {
122 ///          %11 = load %arg0[%i, %j] :
123 ///            memref<?x?xf32, stride_specification>
124 ///          %12 = load %arg1[%i, %j, %k] :
125 ///            memref<?x?x?xf32, stride_specification>
126 ///          %13 = load %arg2[%i, %k, %j] :
127 ///            memref<?x?x?xf32, stride_specification>
128 ///          %14:2 = call @foo(%11, %12, %13) : (f32, f32, f32) -> (f32, f32)
129 ///          store %14#0, %arg1[%i, %j, %k] :
130 ///            memref<?x?x?Xf32, stride_specification>
131 ///          store %14#1, %arg2[%i, %k, %j] :
132 ///            memref<?x?x?Xf32, stride_specification>
133 ///       }
134 ///      }
135 ///    }
136 /// ```
137 // TODO: need a LinalgStructuredOpInterface.
138 template <typename IndexedValueType, typename LinalgStructuredOpType>
139 void emitScalarImplementation(ArrayRef<Value> allIvs,
140                               LinalgStructuredOpType linalgOp) {
141   assert(linalgOp.hasBufferSemantics() &&
142          "expected linalg op with buffer semantics");
143   auto &b = ScopedContext::getBuilderRef();
144   auto loc = ScopedContext::getLocation();
145   unsigned nInputs = linalgOp.getNumInputs();
146   unsigned nOutputs = linalgOp.getNumOutputs();
147   SmallVector<Value, 4> indexedValues;
148   indexedValues.reserve(nInputs + nOutputs);
149 
150   auto attr = linalgOp.template getAttrOfType<IntegerAttr>("symbol_source");
151   auto allIvsPlusDims = SmallVector<Value, 4>(allIvs.begin(), allIvs.end());
152   if (attr) {
153     auto operand = linalgOp.getOperand(attr.getInt());
154     auto shapedType = operand.getType().template cast<ShapedType>();
155     allIvsPlusDims.reserve(allIvs.size() + shapedType.getRank());
156     for (unsigned idx = 0, e = shapedType.getRank(); idx < e; ++idx)
157       allIvsPlusDims.push_back(b.create<DimOp>(loc, operand, idx));
158   }
159 
160   // TODO: Avoid the loads if the corresponding argument of the
161   // region has no uses.
162   // 1.a. Emit load from input views.
163   for (unsigned i = 0; i < nInputs; ++i) {
164     auto indexing = makeCanonicalAffineApplies(
165         b, loc, linalgOp.getInputIndexingMap(i), allIvsPlusDims);
166     // Passing through IndexedValueType emits the proper load operation.
167     indexedValues.push_back(IndexedValueType(linalgOp.getInput(i))(indexing));
168   }
169   // 1.b. Emit load from output views.
170   for (unsigned i = 0; i < nOutputs; ++i) {
171     auto indexing = makeCanonicalAffineApplies(
172         b, loc, linalgOp.getOutputIndexingMap(i), allIvsPlusDims);
173     // Passing through IndexedValueType emits the proper load operation.
174     indexedValues.push_back(
175         IndexedValueType(linalgOp.getOutputBuffer(i))(indexing));
176   }
177 
178   // TODO: When a region inliner exists, use it.
179   // 2. Inline region, currently only works for a single basic block.
180   // 3. Emit store.
181   SmallVector<SmallVector<Value, 8>, 8> indexing;
182   SmallVector<Value, 8> outputBuffers;
183   for (unsigned i = 0; i < nOutputs; ++i) {
184     indexing.push_back(makeCanonicalAffineApplies(
185         b, loc, linalgOp.getOutputIndexingMap(i), allIvsPlusDims));
186     outputBuffers.push_back(linalgOp.getOutputBuffer(i));
187   }
188   inlineRegionAndEmitStore<IndexedValueType>(linalgOp, indexedValues, indexing,
189                                              outputBuffers);
190 }
191 
192 template <typename IndexedValueType>
193 void emitScalarImplementation(ArrayRef<Value> allIvs, CopyOp copyOp) {
194   assert(copyOp.hasBufferSemantics() &&
195          "expected linalg op with buffer semantics");
196   auto nPar = copyOp.getNumParallelLoops();
197   assert(nPar == allIvs.size());
198   auto inputIvs =
199       permuteIvs(allIvs.take_front(nPar), copyOp.inputPermutation());
200   auto outputIvs =
201       permuteIvs(allIvs.take_front(nPar), copyOp.outputPermutation());
202   SmallVector<Value, 8> iivs(inputIvs.begin(), inputIvs.end());
203   SmallVector<Value, 8> oivs(outputIvs.begin(), outputIvs.end());
204   IndexedValueType O(copyOp.getOutputBuffer(0)), I(copyOp.getInput(0));
205   // Emit the proper scalar assignment, whether we are dealing with a 0-D or
206   // an n-D loop nest; with or without permutations.
207   // clang-format off
208     nPar > 0 ? O(oivs) = I(iivs) :
209                O() = I();
210   // clang-format on
211 }
212 
213 template <typename IndexedValueType>
214 void emitScalarImplementation(ArrayRef<Value> allIvs, FillOp fillOp) {
215   assert(fillOp.hasBufferSemantics() &&
216          "expected linalg op with buffer semantics");
217   auto nPar = fillOp.getNumParallelLoops();
218   assert(nPar == allIvs.size());
219   auto ivs = SmallVector<Value, 4>(allIvs.begin(), allIvs.begin() + nPar);
220   IndexedValueType O(fillOp.getOutputBuffer(0));
221   // Emit the proper scalar assignment, whether we are dealing with a 0-D or
222   // an n-D loop nest; with or without permutations.
223   nPar > 0 ? O(ivs) = fillOp.value() : O() = fillOp.value();
224 }
225 
226 template <typename IndexedValueType>
227 Value getConvOpInput(ConvOp convOp, StdIndexedValue im,
228                      MutableArrayRef<Value> imIdx) {
229   // TODO: add a level of indirection to linalg.generic.
230   if (!convOp.padding())
231     return im(imIdx);
232 
233   auto *context = ScopedContext::getContext();
234   Value zeroIndex = std_constant_index(0);
235   SmallVector<Value, 8> conds;
236   SmallVector<Value, 8> clampedImIdx;
237   for (auto iter : llvm::enumerate(imIdx)) {
238     int idx = iter.index();
239     auto dim = iter.value();
240     // Only need to iterate over the window dimensions.
241     if (idx == 0 || idx == static_cast<int>(imIdx.size()) - 1) {
242       clampedImIdx.push_back(dim);
243       continue;
244     }
245 
246     using edsc::op::sge;
247     using edsc::op::slt;
248     using edsc::op::operator||;
249     Value leftOutOfBound = slt(dim, zeroIndex);
250     if (conds.empty())
251       conds.push_back(leftOutOfBound);
252     else
253       conds.push_back(conds.back() || leftOutOfBound);
254     Value rightBound = std_dim(convOp.input(), idx);
255     conds.push_back(conds.back() || (sge(dim, rightBound)));
256 
257     // When padding is involved, the indices will only be shifted to negative,
258     // so having a max op is enough.
259     auto maxMap = AffineMap::get(/*dimCount=*/1, 0,
260                                  {getAffineDimExpr(/*position=*/0, context),
261                                   getAffineConstantExpr(0, context)},
262                                  context);
263     clampedImIdx.push_back(affine_max(dim.getType(), maxMap, ValueRange{dim}));
264   }
265 
266   auto &b = ScopedContext::getBuilderRef();
267   Type type = convOp.input().getType().cast<MemRefType>().getElementType();
268   Value zero = std_constant(type, b.getZeroAttr(type));
269   Value readInput = im(clampedImIdx);
270   return conds.empty() ? readInput
271                        : (Value)std_select(conds.back(), zero, readInput);
272 }
273 
274 /// Returns true is `convOp` has a non-zero padding.
275 static bool hasPadding(ConvOp convOp) {
276   for (unsigned i = 0, e = convOp.getNumSpatialDimensions(); i < e; ++i) {
277     if (convOp.getLowPad(i) > 0 || convOp.getHighPad(i) > 0)
278       return true;
279   }
280   return false;
281 }
282 
283 template <typename IndexedValueType>
284 static void emitScalarImplementation(ArrayRef<Value> allIvs, ConvOp convOp) {
285   assert(convOp.hasBufferSemantics() &&
286          "expected linalg op with buffer semantics");
287   auto &b = ScopedContext::getBuilderRef();
288   auto loc = ScopedContext::getLocation();
289   auto mapsRange = convOp.indexing_maps().getAsRange<AffineMapAttr>();
290   auto maps = llvm::to_vector<8>(
291       llvm::map_range(mapsRange, [](AffineMapAttr a) { return a.getValue(); }));
292   SmallVector<Value, 8> fIdx(
293       makeCanonicalAffineApplies(b, loc, maps[0], allIvs));
294   SmallVector<Value, 8> imIdx(
295       makeCanonicalAffineApplies(b, loc, maps[1], allIvs));
296   SmallVector<Value, 8> oIdx(
297       makeCanonicalAffineApplies(b, loc, maps[2], allIvs));
298 
299   IndexedValueType F(convOp.filter()), O(convOp.output());
300 
301   // Emit scalar form. Padded conv involves an affine.max in the memory access
302   // which is not allowed by affine.load. Override to use an StdIndexedValue
303   // when there is non-zero padding.
304   if (hasPadding(convOp)) {
305     StdIndexedValue I(convOp.input());
306     Value paddedInput = getConvOpInput<IndexedValueType>(convOp, I, imIdx);
307     O(oIdx) += F(fIdx) * paddedInput;
308   } else {
309     IndexedValueType I(convOp.input());
310     O(oIdx) += F(fIdx) * I(imIdx);
311   }
312 }
313 
314 template <typename IndexedValueType>
315 void emitScalarImplementation(ArrayRef<Value> allIvs, PoolingMaxOp op) {
316   InputAndOutputIndices indices = getInputAndOutputIndices(allIvs, op);
317   // Emit scalar form.
318   IndexedValueType output(op.output());
319   IndexedValueType input(op.input());
320   Value lhs = output(indices.outputs);
321   Value rhs = input(indices.inputs);
322   using edsc::op::sgt;
323   Value maxValue = std_select(sgt(lhs, rhs), lhs, rhs);
324   output(indices.outputs) = maxValue;
325 }
326 
327 template <typename IndexedValueType>
328 void emitScalarImplementation(ArrayRef<Value> allIvs, PoolingMinOp op) {
329   InputAndOutputIndices indices = getInputAndOutputIndices(allIvs, op);
330   // Emit scalar form.
331   IndexedValueType output(op.output());
332   IndexedValueType input(op.input());
333   Value lhs = output(indices.outputs);
334   Value rhs = input(indices.inputs);
335   using edsc::op::slt;
336   Value minValue = std_select(slt(lhs, rhs), lhs, rhs);
337   output(indices.outputs) = minValue;
338 }
339 template <typename IndexedValueType>
340 void emitScalarImplementation(ArrayRef<Value> allIvs, PoolingSumOp op) {
341   auto indices = getInputAndOutputIndices(allIvs, op);
342   IndexedValueType input(op.input()), output(op.output());
343 
344   // Emit scalar form.
345   output(indices.outputs) += input(indices.inputs);
346 }
347 /// Emits the MLIR for the scalar part of the indexed generic op by:
348 ///   1. Emitting load ops for each input and output view in order. This is
349 ///      achieved by applying the appropriate input or output map to the
350 ///      enclosing induction variables.
351 ///   2. Emitting a call to `op.fun()` that takes as arguments the induction
352 ///      variables and the scalars from point 1. above.
353 ///   3. Emitting store ops to store the results of 2. to the output views.
354 ///
355 /// An example output may resemble:
356 ///
357 /// ```
358 ///    scf.for %i = %c0 to %0 step %c1 {
359 ///      scf.for %j = %c0 to %1 step %c1 {
360 ///        scf.for %k = %c0 to %4 step %c1 {
361 ///          %11 = load %arg0[%i, %j] :
362 ///            memref<?x?xf32, stride_specification>
363 ///          %12 = load %arg1[%i, %j, %k] :
364 ///            memref<?x?x?xf32, stride_specification>
365 ///          %13 = load %arg2[%i, %k, %j] :
366 ///            memref<?x?x?xf32, stride_specification>
367 ///          %14:2 = call @foo(%i, %j, %k, %11, %12, %13) :
368 ///            (index, index, index, f32, f32, f32) -> (f32, f32)
369 ///          store %14#0, %arg1[%i, %j, %k] :
370 ///            memref<?x?x?Xf32, stride_specification>
371 ///          store %14#1, %arg2[%i, %k, %j] :
372 ///            memref<?x?x?Xf32, stride_specification>
373 ///       }
374 ///      }
375 ///    }
376 /// ```
377 template <typename IndexedValueType>
378 static void emitScalarImplementation(ArrayRef<Value> allIvs,
379                                      IndexedGenericOp indexedGenericOp) {
380   assert(indexedGenericOp.hasBufferSemantics() &&
381          "expected linalg op with buffer semantics");
382   auto &b = ScopedContext::getBuilderRef();
383   auto loc = ScopedContext::getLocation();
384   unsigned nInputs = indexedGenericOp.getNumInputs();
385   unsigned nOutputs = indexedGenericOp.getNumOutputs();
386   unsigned nLoops = allIvs.size();
387   SmallVector<Value, 4> indexedValues;
388   indexedValues.reserve(nLoops + nInputs + nOutputs);
389   for (unsigned i = 0; i < nLoops; ++i)
390     indexedValues.push_back(allIvs[i]);
391 
392   // TODO: Avoid the loads if the corresponding argument of the
393   // region has no uses.
394   // 1.a. Emit load from input views.
395   for (unsigned i = 0; i < nInputs; ++i) {
396     auto indexing = makeCanonicalAffineApplies(
397         b, loc, indexedGenericOp.getInputIndexingMap(i), allIvs);
398     // Pass input i through IndexedValueType emits the proper load operation.
399     indexedValues.push_back(
400         IndexedValueType(indexedGenericOp.getInput(i))(indexing));
401   }
402   // 1.b. Emit load from output views.
403   for (unsigned i = 0; i < nOutputs; ++i) {
404     auto indexing = makeCanonicalAffineApplies(
405         b, loc, indexedGenericOp.getOutputIndexingMap(i), allIvs);
406     // Pass output i through IndexedValueType emits the proper load operation.
407     indexedValues.push_back(
408         IndexedValueType(indexedGenericOp.getOutputBuffer(i))(indexing));
409   }
410 
411   // TODO: When a region inliner exists, use it.
412   // 2. Inline region, currently only works for a single basic block.
413   // 3. Emit store.
414   SmallVector<SmallVector<Value, 8>, 8> indexing;
415   SmallVector<Value, 8> outputBuffers;
416   for (unsigned i = 0; i < nOutputs; ++i) {
417     indexing.push_back(makeCanonicalAffineApplies(
418         b, loc, indexedGenericOp.getOutputIndexingMap(i), allIvs));
419     outputBuffers.push_back(indexedGenericOp.getOutputBuffer(i));
420   }
421   inlineRegionAndEmitStore<IndexedValueType>(indexedGenericOp, indexedValues,
422                                              indexing, outputBuffers);
423 }
424 
425 template <typename LoopTy, typename ConcreteOpTy>
426 Optional<LinalgLoops> linalgOpToLoopsImpl(Operation *op, OpBuilder &builder) {
427   using IndexedValueTy = typename GenerateLoopNest<LoopTy>::IndexedValueTy;
428 
429   ScopedContext scope(builder, op->getLoc());
430 
431   // The flattened loopToOperandRangesMaps is expected to be an invertible
432   // permutation map (which is asserted in the inverse calculation).
433   auto linalgOp = cast<ConcreteOpTy>(op);
434   assert(linalgOp.hasBufferSemantics() &&
435          "expected linalg op with buffer semantics");
436   auto mapsRange =
437       linalgOp.indexing_maps().template getAsRange<AffineMapAttr>();
438   auto maps = llvm::to_vector<8>(
439       llvm::map_range(mapsRange, [](AffineMapAttr a) { return a.getValue(); }));
440   SmallVector<Value, 8> sizes = getShape(builder, linalgOp);
441   AffineMap map = concatAffineMaps(maps);
442   auto loopRanges = emitLoopRanges(scope.getBuilderRef(), scope.getLocation(),
443                                    map, getShape(builder, linalgOp));
444   SmallVector<Value, 4> allIvs;
445   GenerateLoopNest<LoopTy>::doit(
446       loopRanges, /*iterInitArgs*/ {}, linalgOp.iterator_types().getValue(),
447       [&](ValueRange ivs, ValueRange iterArgs) -> scf::ValueVector {
448         assert(iterArgs.empty() && "unexpected iterArgs");
449         allIvs.append(ivs.begin(), ivs.end());
450         emitScalarImplementation<IndexedValueTy>(allIvs, linalgOp);
451         return scf::ValueVector{};
452       });
453   // Number of loop ops might be different from the number of ivs since some
454   // loops like affine.parallel and scf.parallel have multiple ivs.
455   llvm::SetVector<Operation *> loopSet;
456   for (Value iv : allIvs) {
457     if (!iv)
458       return {};
459     // The induction variable is a block argument of the entry block of the
460     // loop operation.
461     BlockArgument ivVal = iv.dyn_cast<BlockArgument>();
462     if (!ivVal)
463       return {};
464     loopSet.insert(ivVal.getOwner()->getParentOp());
465   }
466   LinalgLoops loops(loopSet.begin(), loopSet.end());
467   return loops;
468 }
469 
470 template <typename LoopType, typename ConcreteOp>
471 class LinalgRewritePattern : public RewritePattern {
472 public:
473   explicit LinalgRewritePattern(MLIRContext *context)
474       : RewritePattern(ConcreteOp::getOperationName(), 1, context) {}
475 
476   LogicalResult matchAndRewrite(Operation *op,
477                                 PatternRewriter &rewriter) const override {
478     if (!linalgOpToLoopsImpl<LoopType, ConcreteOp>(op, rewriter))
479       return failure();
480     rewriter.eraseOp(op);
481     return success();
482   }
483 };
484 
485 template <typename LoopType, typename ConcreteOp>
486 void insertOnePattern(OwningRewritePatternList &patterns, MLIRContext *ctx) {
487   patterns.insert<LinalgRewritePattern<LoopType, ConcreteOp>>(ctx);
488 }
489 
490 template <typename LoopType, typename... Args>
491 void insertPatterns(OwningRewritePatternList &patterns, MLIRContext *ctx) {
492   (void)std::initializer_list<int>{
493       0, (insertOnePattern<LoopType, Args>(patterns, ctx), 0)...};
494 }
495 
496 /// Local folding pattern for AffineApplyOp that we can apply greedily.
497 /// This replaces AffineApplyOp by the proper value in cases where the
498 /// associated map is trivial.
499 /// A trivial map here is defined as a map with a single result and either:
500 ///   1. Zero operand + returns a single AffineConstantExpr
501 ///   2. One operand + returns a single AffineDimExpr
502 ///   3. One operand + returns a single AffineSymbolExpr
503 //
504 /// In the first case, the AffineApplyOp is replaced by a new constant. In the
505 /// other cases, it is replaced by its unique operand.
506 struct FoldAffineOp : public RewritePattern {
507   FoldAffineOp(MLIRContext *context)
508       : RewritePattern(AffineApplyOp::getOperationName(), 0, context) {}
509 
510   LogicalResult matchAndRewrite(Operation *op,
511                                 PatternRewriter &rewriter) const override {
512     AffineApplyOp affineApplyOp = cast<AffineApplyOp>(op);
513     auto map = affineApplyOp.getAffineMap();
514     if (map.getNumResults() != 1 || map.getNumInputs() > 1)
515       return failure();
516 
517     AffineExpr expr = map.getResult(0);
518     if (map.getNumInputs() == 0) {
519       if (auto val = expr.dyn_cast<AffineConstantExpr>()) {
520         rewriter.replaceOpWithNewOp<ConstantIndexOp>(op, val.getValue());
521         return success();
522       }
523       return failure();
524     }
525     if (expr.dyn_cast<AffineDimExpr>() || expr.dyn_cast<AffineSymbolExpr>()) {
526       rewriter.replaceOp(op, op->getOperand(0));
527       return success();
528     }
529     return failure();
530   }
531 };
532 } // namespace
533 
534 template <typename LoopType>
535 static void lowerLinalgToLoopsImpl(FuncOp funcOp, MLIRContext *context) {
536   OwningRewritePatternList patterns;
537   // Canonicalization and folding patterns applied greedily allow cleaning up
538   // the emitted IR on the fly.
539   // TODO: fold view and subview ops?
540   insertPatterns<LoopType,
541 #define GET_OP_LIST
542 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
543                  >(patterns, context);
544 
545   DimOp::getCanonicalizationPatterns(patterns, context);
546   AffineApplyOp::getCanonicalizationPatterns(patterns, context);
547   patterns.insert<FoldAffineOp>(context);
548   // Just apply the patterns greedily.
549   applyPatternsAndFoldGreedily(funcOp, patterns);
550 }
551 
552 namespace {
553 struct LowerToAffineLoops
554     : public LinalgLowerToAffineLoopsBase<LowerToAffineLoops> {
555   void runOnFunction() override {
556     lowerLinalgToLoopsImpl<AffineForOp>(getFunction(), &getContext());
557   }
558 };
559 struct LowerToLoops : public LinalgLowerToLoopsBase<LowerToLoops> {
560   void runOnFunction() override {
561     lowerLinalgToLoopsImpl<scf::ForOp>(getFunction(), &getContext());
562   }
563 };
564 struct LowerToParallelLoops
565     : public LinalgLowerToParallelLoopsBase<LowerToParallelLoops> {
566   void runOnFunction() override {
567     lowerLinalgToLoopsImpl<scf::ParallelOp>(getFunction(), &getContext());
568   }
569 };
570 } // namespace
571 
572 std::unique_ptr<OperationPass<FuncOp>> mlir::createConvertLinalgToLoopsPass() {
573   return std::make_unique<LowerToLoops>();
574 }
575 
576 std::unique_ptr<OperationPass<FuncOp>>
577 mlir::createConvertLinalgToParallelLoopsPass() {
578   return std::make_unique<LowerToParallelLoops>();
579 }
580 
581 std::unique_ptr<OperationPass<FuncOp>>
582 mlir::createConvertLinalgToAffineLoopsPass() {
583   return std::make_unique<LowerToAffineLoops>();
584 }
585 
586 // TODO: gradually remove this layer as more ops become "named".
587 template <typename LoopTy>
588 static Optional<LinalgLoops> linalgOpToLoopsImplSwitch(Operation *op,
589                                                        OpBuilder &builder) {
590   assert(isa<LinalgOp>(op) && "LinalgOp expected");
591   if (isa<CopyOp>(op))
592     return linalgOpToLoopsImpl<LoopTy, CopyOp>(op, builder);
593   if (isa<FillOp>(op))
594     return linalgOpToLoopsImpl<LoopTy, FillOp>(op, builder);
595   if (isa<ConvOp>(op))
596     return linalgOpToLoopsImpl<LoopTy, ConvOp>(op, builder);
597   if (isa<PoolingMaxOp>(op))
598     return linalgOpToLoopsImpl<LoopTy, PoolingMaxOp>(op, builder);
599   if (isa<PoolingMinOp>(op))
600     return linalgOpToLoopsImpl<LoopTy, PoolingMinOp>(op, builder);
601   if (isa<PoolingSumOp>(op))
602     return linalgOpToLoopsImpl<LoopTy, PoolingSumOp>(op, builder);
603   if (isa<IndexedGenericOp>(op))
604     return linalgOpToLoopsImpl<LoopTy, IndexedGenericOp>(op, builder);
605 
606   // TODO: Cases below are generic and need a LinalgStructuredOpInterface.
607   if (isa<GenericOp>(op))
608     return linalgOpToLoopsImpl<LoopTy, GenericOp>(op, builder);
609   if (isa<MatmulOp>(op))
610     return linalgOpToLoopsImpl<LoopTy, MatmulOp>(op, builder);
611   if (isa<MatvecOp>(op))
612     return linalgOpToLoopsImpl<LoopTy, MatvecOp>(op, builder);
613   if (isa<VecmatOp>(op))
614     return linalgOpToLoopsImpl<LoopTy, VecmatOp>(op, builder);
615   if (isa<DotOp>(op))
616     return linalgOpToLoopsImpl<LoopTy, DotOp>(op, builder);
617   if (isa<BatchMatmulOp>(op))
618     return linalgOpToLoopsImpl<LoopTy, BatchMatmulOp>(op, builder);
619   if (isa<ConvWOp>(op))
620     return linalgOpToLoopsImpl<LoopTy, ConvWOp>(op, builder);
621   if (isa<ConvNWCOp>(op))
622     return linalgOpToLoopsImpl<LoopTy, ConvNWCOp>(op, builder);
623   if (isa<ConvNCWOp>(op))
624     return linalgOpToLoopsImpl<LoopTy, ConvNCWOp>(op, builder);
625   if (isa<ConvHWOp>(op))
626     return linalgOpToLoopsImpl<LoopTy, ConvHWOp>(op, builder);
627   if (isa<ConvNHWCOp>(op))
628     return linalgOpToLoopsImpl<LoopTy, ConvNHWCOp>(op, builder);
629   if (isa<ConvNCHWOp>(op))
630     return linalgOpToLoopsImpl<LoopTy, ConvNCHWOp>(op, builder);
631   if (isa<ConvDHWOp>(op))
632     return linalgOpToLoopsImpl<LoopTy, ConvDHWOp>(op, builder);
633   if (isa<ConvNDHWCOp>(op))
634     return linalgOpToLoopsImpl<LoopTy, ConvNDHWCOp>(op, builder);
635   if (isa<ConvNCDHWOp>(op))
636     return linalgOpToLoopsImpl<LoopTy, ConvNCDHWOp>(op, builder);
637   llvm_unreachable("Unexpected op in linalgOpToLoopsImpl");
638 }
639 
640 SmallVector<Range, 4> mlir::linalg::emitLoopRanges(OpBuilder &b, Location loc,
641                                                    AffineMap map,
642                                                    ValueRange viewSizes) {
643   unsigned numDims = map.getNumDims(), numRes = map.getNumResults();
644   unsigned numSym = map.getNumSymbols();
645   assert(viewSizes.size() == numRes + numSym &&
646          "viewSizes must contain sizes of all views and values for symbols");
647   SmallVector<Range, 4> res(numDims);
648   for (unsigned idx = 0; idx < numRes; ++idx) {
649     auto result = map.getResult(idx);
650     if (auto d = result.dyn_cast<AffineDimExpr>()) {
651       if (res[d.getPosition()].offset)
652         continue;
653       res[d.getPosition()] =
654           Range{std_constant_index(0), viewSizes[idx], std_constant_index(1)};
655     }
656 
657     // If the access pattern is of form (m, n)[s] -> (m + n - s floordiv 2),
658     // then the bounds are:
659     //   (s floordiv 2) <= m <= (size(m) + s floordiv 2 - s + 1).
660     // where size(n) is applied to the symbol s.
661     // This is done statically now.
662     if (auto binOp = result.dyn_cast<AffineBinaryOpExpr>()) {
663       auto lhs = binOp.getLHS().dyn_cast<AffineBinaryOpExpr>();
664       auto rhs = binOp.getRHS().dyn_cast<AffineBinaryOpExpr>();
665       if (!lhs || !rhs || binOp.getKind() != AffineExprKind::Add ||
666           lhs.getKind() != AffineExprKind::Add ||
667           rhs.getKind() != mlir::AffineExprKind::Mul)
668         continue;
669 
670       auto m = lhs.getLHS().dyn_cast<AffineDimExpr>();
671       auto n = lhs.getRHS().dyn_cast<AffineDimExpr>();
672       auto fDiv = rhs.getLHS().dyn_cast<AffineBinaryOpExpr>();
673       auto minusOne = rhs.getRHS().dyn_cast<AffineConstantExpr>();
674       if (!m || !n || !fDiv || !minusOne ||
675           fDiv.getKind() != AffineExprKind::FloorDiv ||
676           fDiv.getLHS().getKind() != AffineExprKind::SymbolId ||
677           fDiv.getRHS().getKind() != AffineExprKind::Constant)
678         continue;
679 
680       auto s = fDiv.getLHS().dyn_cast<AffineSymbolExpr>();
681       if (minusOne.getValue() != -1)
682         continue;
683 
684       int mPos = m.getPosition();
685       AffineExpr one = getAffineConstantExpr(1, s.getContext());
686       AffineExpr sizeOfM = getAffineSymbolExpr(numSym, s.getContext());
687       // Construction of upper bound (size(m) + s floordiv 2 - s + 1).
688       AffineExpr upperOffsetExpr = sizeOfM + fDiv + one - s;
689       AffineMap fromMap = AffineMap::get(numDims, numSym + 1, fDiv);
690       AffineMap toMap = AffineMap::get(numDims, numSym + 1, upperOffsetExpr);
691       SmallVector<Value, 8> values(viewSizes.begin(),
692                                    viewSizes.begin() + numDims);
693       values.insert(values.end(), viewSizes.begin() + numRes, viewSizes.end());
694       values.push_back(viewSizes[mPos]);
695       // Construction of the lower bound (s floordiv 2).
696       Value from = applyMapToValues(b, loc, fromMap, values).front();
697       Value to = applyMapToValues(b, loc, toMap, values).front();
698       res[mPos] = Range{from, to, std_constant_index(1)};
699     }
700   }
701   return res;
702 }
703 
704 /// Emits a loop nest with the proper body for `op`.
705 template <typename LoopTy>
706 Optional<LinalgLoops> mlir::linalg::linalgLowerOpToLoops(OpBuilder &builder,
707                                                          Operation *op) {
708   return linalgOpToLoopsImplSwitch<LoopTy>(op, builder);
709 }
710 
711 template Optional<LinalgLoops>
712 mlir::linalg::linalgLowerOpToLoops<AffineForOp>(OpBuilder &builder,
713                                                 Operation *op);
714 template Optional<LinalgLoops>
715 mlir::linalg::linalgLowerOpToLoops<scf::ForOp>(OpBuilder &builder,
716                                                Operation *op);
717 template Optional<LinalgLoops>
718 mlir::linalg::linalgLowerOpToLoops<scf::ParallelOp>(OpBuilder &builder,
719                                                     Operation *op);
720 
721 /// Emits a loop nest of `affine.for` with the proper body for `op`.
722 LogicalResult mlir::linalg::linalgOpToAffineLoops(OpBuilder &builder,
723                                                   Operation *op) {
724   Optional<LinalgLoops> loops = linalgLowerOpToLoops<AffineForOp>(builder, op);
725   return loops ? success() : failure();
726 }
727 
728 /// Emits a loop nest of `scf.for` with the proper body for `op`.
729 LogicalResult mlir::linalg::linalgOpToLoops(OpBuilder &builder, Operation *op) {
730   Optional<LinalgLoops> loops = linalgLowerOpToLoops<scf::ForOp>(builder, op);
731   return loops ? success() : failure();
732 }
733 
734 /// Emits a loop nest of `scf.parallel` with the proper body for `op`.
735 LogicalResult mlir::linalg::linalgOpToParallelLoops(OpBuilder &builder,
736                                                     Operation *op) {
737   Optional<LinalgLoops> loops =
738       linalgLowerOpToLoops<scf::ParallelOp>(builder, op);
739   return loops ? success() : failure();
740 }
741