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 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
26 
27 #include "llvm/ADT/TypeSwitch.h"
28 
29 using namespace mlir;
30 using namespace mlir::edsc;
31 using namespace mlir::edsc::intrinsics;
32 using namespace mlir::linalg;
33 
34 using edsc::op::operator+;
35 
36 static SmallVector<Value, 8> makeCanonicalAffineApplies(OpBuilder &b,
37                                                         Location loc,
38                                                         AffineMap map,
39                                                         ArrayRef<Value> vals) {
40   if (map.isEmpty())
41     return {};
42 
43   assert(map.getNumInputs() == vals.size());
44   SmallVector<Value, 8> res;
45   res.reserve(map.getNumResults());
46   auto dims = map.getNumDims();
47   for (auto e : map.getResults()) {
48     auto exprMap = AffineMap::get(dims, map.getNumSymbols(), e);
49     SmallVector<Value, 4> operands(vals.begin(), vals.end());
50     canonicalizeMapAndOperands(&exprMap, &operands);
51     res.push_back(affine_apply(exprMap, operands));
52   }
53   return res;
54 }
55 
56 static SmallVector<Value, 4> permuteIvs(ArrayRef<Value> ivs,
57                                         Optional<AffineMap> permutation) {
58   return permutation ? applyMapToValues(ScopedContext::getBuilderRef(),
59                                         ScopedContext::getLocation(),
60                                         permutation.getValue(), ivs)
61                      : SmallVector<Value, 4>(ivs.begin(), ivs.end());
62 }
63 
64 template <typename IndexedValueType, typename OpType>
65 static void inlineRegionAndEmitStore(OpType op, ArrayRef<Value> indexedValues,
66                                      ArrayRef<SmallVector<Value, 8>> indexing,
67                                      ArrayRef<Value> outputBuffers) {
68   assert(op.getOperation()->getNumRegions() == 1 &&
69          "Expected single region op");
70   auto &b = ScopedContext::getBuilderRef();
71   auto &block = op.getOperation()->getRegion(0).front();
72   BlockAndValueMapping map;
73   map.map(block.getArguments(), indexedValues);
74   for (auto &op : block.without_terminator()) {
75     assert(op.getNumRegions() == 0 && "expected a non-nested region");
76     auto *newOp = b.clone(op, map);
77     map.map(op.getResults(), newOp->getResults());
78   }
79 
80   Operation &terminator = block.back();
81   assert(isa<linalg::YieldOp>(terminator) &&
82          "expected a yield op in the end of the region");
83   for (unsigned i = 0, e = terminator.getNumOperands(); i < e; ++i) {
84     IndexedValueType O(outputBuffers[i]);
85     O(indexing[i]) = map.lookupOrDefault(terminator.getOperand(i));
86   }
87 }
88 
89 // Returns a pair that contains input indices and output indices of a
90 // SingleInputPoolingOp `op`.
91 struct InputAndOutputIndices {
92   SmallVector<Value, 8> inputs;
93   SmallVector<Value, 8> outputs;
94 };
95 template <typename SingleInputPoolingOp>
96 static InputAndOutputIndices getInputAndOutputIndices(ArrayRef<Value> allIvs,
97                                                       SingleInputPoolingOp op) {
98   auto &b = ScopedContext::getBuilderRef();
99   auto loc = ScopedContext::getLocation();
100   auto mapsRange = op.indexing_maps().template getAsRange<AffineMapAttr>();
101   auto maps = llvm::to_vector<8>(
102       llvm::map_range(mapsRange, [](AffineMapAttr a) { return a.getValue(); }));
103   return InputAndOutputIndices{
104       makeCanonicalAffineApplies(b, loc, maps[0], allIvs),
105       makeCanonicalAffineApplies(b, loc, maps[2], allIvs)};
106 }
107 
108 /// Emits the MLIR for the scalar part of the generic op by:
109 ///   1. Emitting load ops for each input and output view in order. This is
110 ///      achieved by applying the appropriate input or output map to the
111 ///      enclosing induction variables.
112 ///   2. Emitting a call to `op.fun()` that takes as arguments the scalars
113 ///      from point 1. above.
114 ///   3. Emitting store ops to store the results of 2. to the output
115 ///      views.
116 ///
117 /// An example output may resemble:
118 ///
119 /// ```
120 ///    scf.for %i = %c0 to %0 step %c1 {
121 ///      scf.for %j = %c0 to %1 step %c1 {
122 ///        scf.for %k = %c0 to %4 step %c1 {
123 ///          %11 = load %arg0[%i, %j] :
124 ///            memref<?x?xf32, stride_specification>
125 ///          %12 = load %arg1[%i, %j, %k] :
126 ///            memref<?x?x?xf32, stride_specification>
127 ///          %13 = load %arg2[%i, %k, %j] :
128 ///            memref<?x?x?xf32, stride_specification>
129 ///          %14:2 = call @foo(%11, %12, %13) : (f32, f32, f32) -> (f32, f32)
130 ///          store %14#0, %arg1[%i, %j, %k] :
131 ///            memref<?x?x?Xf32, stride_specification>
132 ///          store %14#1, %arg2[%i, %k, %j] :
133 ///            memref<?x?x?Xf32, stride_specification>
134 ///       }
135 ///      }
136 ///    }
137 /// ```
138 template <typename IndexedValueType>
139 static void emitScalarImplementation(ArrayRef<Value> allIvs,
140                                      LinalgOp 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.getOperation()->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 static 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 static 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 // Create a padded view into the given `input` tensor using the 'indices'
227 // to access the tensor. `skipPadding` lists the dimensions for which no padding
228 // is needed e.g. the non-spatial dimensions for convolutions.
229 template <typename IndexedValueType>
230 Value getPaddedInput(Value input, ArrayRef<Value> indices,
231                      ArrayRef<int> skipPadding, Value padValue) {
232   // TODO: add a level of indirection to linalg.generic.
233 
234   IndexedValueType indexedInput(input);
235 
236   auto *context = ScopedContext::getContext();
237   Value zeroIndex = std_constant_index(0);
238   SmallVector<Value, 8> conds;
239   SmallVector<Value, 8> clampedImIdx;
240   for (auto iter : llvm::enumerate(indices)) {
241     int idx = iter.index();
242     auto dim = iter.value();
243     if (is_contained(skipPadding, idx)) {
244       clampedImIdx.push_back(dim);
245       continue;
246     }
247 
248     using edsc::op::sge;
249     using edsc::op::slt;
250     using edsc::op::operator||;
251     Value leftOutOfBound = slt(dim, zeroIndex);
252     if (conds.empty())
253       conds.push_back(leftOutOfBound);
254     else
255       conds.push_back(conds.back() || leftOutOfBound);
256     Value rightBound = std_dim(input, idx);
257     conds.push_back(conds.back() || (sge(dim, rightBound)));
258 
259     // When padding is involved, the indices will only be shifted to negative,
260     // so having a max op is enough.
261     auto maxMap = AffineMap::get(/*dimCount=*/1, 0,
262                                  {getAffineDimExpr(/*position=*/0, context),
263                                   getAffineConstantExpr(0, context)},
264                                  context);
265     clampedImIdx.push_back(affine_max(dim.getType(), maxMap, ValueRange{dim}));
266   }
267 
268   Value readInput = indexedInput(clampedImIdx);
269   return conds.empty() ? readInput
270                        : (Value)std_select(conds.back(), padValue, readInput);
271 }
272 
273 namespace {
274 
275 /// The padding value for a given Op depends on the semantics of the Op.
276 /// The identity value for ConvOp and PoolingSumOp is 0, for PoolingMaxOp is
277 /// -inf or minInt and for PoolingMinOp is inf or maxInt.
278 template <typename OpType>
279 Attribute getPadValueAttr(Type type) {
280   llvm_unreachable("Unexpected op type for getPadValueAttr");
281   return {};
282 }
283 
284 template <>
285 Attribute getPadValueAttr<PoolingMaxOp>(Type type) {
286   auto &b = ScopedContext::getBuilderRef();
287   if (auto floatType = type.dyn_cast<FloatType>()) {
288     return b.getFloatAttr(
289         floatType,
290         APFloat::getInf(floatType.getFloatSemantics(), /*Negative*/ true));
291   }
292   if (auto intType = type.dyn_cast<IntegerType>()) {
293     unsigned width = intType.getWidth();
294     // The select instruction used to lower the PoolingMin uses a signed
295     // comparison, use a signed constant irrespective of the signedness of the
296     // integer type.
297     return b.getIntegerAttr(intType, APInt::getSignedMinValue(width));
298   }
299   llvm_unreachable("Unsupported data type for PoolingMaxOp");
300   return {};
301 }
302 
303 template <>
304 Attribute getPadValueAttr<PoolingMinOp>(Type type) {
305   auto &b = ScopedContext::getBuilderRef();
306   if (auto floatType = type.dyn_cast<FloatType>()) {
307     return b.getFloatAttr(floatType,
308                           APFloat::getInf(floatType.getFloatSemantics()));
309   }
310   if (auto intType = type.dyn_cast<IntegerType>()) {
311     unsigned width = intType.getWidth();
312     // The select instruction used to lower the PoolingMin uses a signed
313     // comparison, use a signed constant irrespective of the signedness of the
314     // integer type.
315     return b.getIntegerAttr(intType, APInt::getSignedMaxValue(width));
316   }
317   llvm_unreachable("Unsupported data type for PoolingMinOp");
318   return {};
319 }
320 
321 template <>
322 Attribute getPadValueAttr<PoolingSumOp>(Type type) {
323   auto &b = ScopedContext::getBuilderRef();
324   return b.getZeroAttr(type);
325 }
326 
327 template <>
328 Attribute getPadValueAttr<ConvOp>(Type type) {
329   auto &b = ScopedContext::getBuilderRef();
330   return b.getZeroAttr(type);
331 }
332 
333 } // namespace
334 
335 /// Returns true is `convOp` has a non-zero padding.
336 static bool hasPadding(ConvOp convOp) {
337   for (unsigned i = 0, e = convOp.getNumSpatialDimensions(); i < e; ++i) {
338     if (convOp.getLowPad(i) > 0 || convOp.getHighPad(i) > 0)
339       return true;
340   }
341   return false;
342 }
343 
344 template <typename IndexedValueType>
345 static void emitScalarImplementation(ArrayRef<Value> allIvs, ConvOp convOp) {
346   assert(convOp.hasBufferSemantics() &&
347          "expected linalg op with buffer semantics");
348   auto &b = ScopedContext::getBuilderRef();
349   auto loc = ScopedContext::getLocation();
350   auto mapsRange = convOp.indexing_maps().getAsRange<AffineMapAttr>();
351   auto maps = llvm::to_vector<8>(
352       llvm::map_range(mapsRange, [](AffineMapAttr a) { return a.getValue(); }));
353   SmallVector<Value, 8> fIdx(
354       makeCanonicalAffineApplies(b, loc, maps[0], allIvs));
355   SmallVector<Value, 8> imIdx(
356       makeCanonicalAffineApplies(b, loc, maps[1], allIvs));
357   SmallVector<Value, 8> oIdx(
358       makeCanonicalAffineApplies(b, loc, maps[2], allIvs));
359 
360   IndexedValueType F(convOp.filter()), O(convOp.output());
361 
362   // Emit scalar form. Padded conv involves an affine.max in the memory access
363   // which is not allowed by affine.load. Override to use an StdIndexedValue
364   // when there is non-zero padding.
365   if (hasPadding(convOp)) {
366     Type type = convOp.input().getType().cast<MemRefType>().getElementType();
367     Value padValue = std_constant(type, getPadValueAttr<ConvOp>(type));
368     Value paddedInput = getPaddedInput<StdIndexedValue>(
369         convOp.input(), imIdx,
370         /* Only need to pad the window dimensions */
371         {0, static_cast<int>(imIdx.size()) - 1}, padValue);
372     O(oIdx) += F(fIdx) * paddedInput;
373   } else {
374     IndexedValueType I(convOp.input());
375     O(oIdx) += F(fIdx) * I(imIdx);
376   }
377 }
378 
379 template <typename PoolingOp>
380 static bool hasPadding(PoolingOp poolingOp) {
381   for (unsigned i = 0, e = poolingOp.getNumWindowLoops(); i < e; ++i) {
382     if (poolingOp.getLowPad(i) > 0 || poolingOp.getHighPad(i) > 0)
383       return true;
384   }
385   return false;
386 }
387 
388 template <typename IndexedValueType, typename PoolingOp>
389 static Value getPoolingInput(PoolingOp op, ArrayRef<Value> inputIndices) {
390   if (hasPadding(op)) {
391     Type type =
392         op.input().getType().template cast<MemRefType>().getElementType();
393     Value padValue = std_constant(type, getPadValueAttr<PoolingOp>(type));
394     return getPaddedInput<StdIndexedValue>(op.input(), inputIndices,
395                                            /*Pad every dimension*/ {},
396                                            padValue);
397   }
398   IndexedValueType input(op.input());
399   return input(inputIndices);
400 }
401 
402 template <typename IndexedValueType, typename OpType>
403 void emitPoolingMinMaxScalarImplementation(ArrayRef<Value> allIvs, OpType op) {
404   InputAndOutputIndices indices = getInputAndOutputIndices(allIvs, op);
405   // Emit scalar form.
406   IndexedValueType output(op.output());
407   Value lhs = output(indices.outputs);
408   Value rhs = getPoolingInput<IndexedValueType>(op, indices.inputs);
409   using edsc::op::sgt;
410   using edsc::op::slt;
411   Value value = std::is_same<OpType, PoolingMinOp>()
412                     ? std_select(slt(lhs, rhs), lhs, rhs)
413                     : std_select(sgt(lhs, rhs), lhs, rhs);
414   output(indices.outputs) = value;
415 }
416 
417 template <typename IndexedValueType>
418 static void emitScalarImplementation(ArrayRef<Value> allIvs, PoolingMaxOp op) {
419   emitPoolingMinMaxScalarImplementation<IndexedValueType, PoolingMaxOp>(allIvs,
420                                                                         op);
421 }
422 
423 template <typename IndexedValueType>
424 static void emitScalarImplementation(ArrayRef<Value> allIvs, PoolingMinOp op) {
425   emitPoolingMinMaxScalarImplementation<IndexedValueType, PoolingMinOp>(allIvs,
426                                                                         op);
427 }
428 
429 template <typename IndexedValueType>
430 static void emitScalarImplementation(ArrayRef<Value> allIvs, PoolingSumOp op) {
431   auto indices = getInputAndOutputIndices(allIvs, op);
432   IndexedValueType output(op.output());
433 
434   // Emit scalar form.
435   output(indices.outputs) +=
436       getPoolingInput<IndexedValueType>(op, indices.inputs);
437 }
438 
439 /// Emits the MLIR for the scalar part of the indexed generic op by:
440 ///   1. Emitting load ops for each input and output view in order. This is
441 ///      achieved by applying the appropriate input or output map to the
442 ///      enclosing induction variables.
443 ///   2. Emitting a call to `op.fun()` that takes as arguments the induction
444 ///      variables and the scalars from point 1. above.
445 ///   3. Emitting store ops to store the results of 2. to the output views.
446 ///
447 /// An example output may resemble:
448 ///
449 /// ```
450 ///    scf.for %i = %c0 to %0 step %c1 {
451 ///      scf.for %j = %c0 to %1 step %c1 {
452 ///        scf.for %k = %c0 to %4 step %c1 {
453 ///          %11 = load %arg0[%i, %j] :
454 ///            memref<?x?xf32, stride_specification>
455 ///          %12 = load %arg1[%i, %j, %k] :
456 ///            memref<?x?x?xf32, stride_specification>
457 ///          %13 = load %arg2[%i, %k, %j] :
458 ///            memref<?x?x?xf32, stride_specification>
459 ///          %14:2 = call @foo(%i, %j, %k, %11, %12, %13) :
460 ///            (index, index, index, f32, f32, f32) -> (f32, f32)
461 ///          store %14#0, %arg1[%i, %j, %k] :
462 ///            memref<?x?x?Xf32, stride_specification>
463 ///          store %14#1, %arg2[%i, %k, %j] :
464 ///            memref<?x?x?Xf32, stride_specification>
465 ///       }
466 ///      }
467 ///    }
468 /// ```
469 template <typename IndexedValueType>
470 static void emitScalarImplementation(ArrayRef<Value> allIvs,
471                                      IndexedGenericOp indexedGenericOp) {
472   assert(indexedGenericOp.hasBufferSemantics() &&
473          "expected linalg op with buffer semantics");
474   auto &b = ScopedContext::getBuilderRef();
475   auto loc = ScopedContext::getLocation();
476   unsigned nInputs = indexedGenericOp.getNumInputs();
477   unsigned nOutputs = indexedGenericOp.getNumOutputs();
478   unsigned nLoops = allIvs.size();
479   SmallVector<Value, 4> indexedValues;
480   indexedValues.reserve(nLoops + nInputs + nOutputs);
481   for (unsigned i = 0; i < nLoops; ++i)
482     indexedValues.push_back(allIvs[i]);
483 
484   // TODO: Avoid the loads if the corresponding argument of the
485   // region has no uses.
486   // 1.a. Emit load from input views.
487   for (unsigned i = 0; i < nInputs; ++i) {
488     auto indexing = makeCanonicalAffineApplies(
489         b, loc, indexedGenericOp.getInputIndexingMap(i), allIvs);
490     // Pass input i through IndexedValueType emits the proper load operation.
491     indexedValues.push_back(
492         IndexedValueType(indexedGenericOp.getInput(i))(indexing));
493   }
494   // 1.b. Emit load from output views.
495   for (unsigned i = 0; i < nOutputs; ++i) {
496     auto indexing = makeCanonicalAffineApplies(
497         b, loc, indexedGenericOp.getOutputIndexingMap(i), allIvs);
498     // Pass output i through IndexedValueType emits the proper load operation.
499     indexedValues.push_back(
500         IndexedValueType(indexedGenericOp.getOutputBuffer(i))(indexing));
501   }
502 
503   // TODO: When a region inliner exists, use it.
504   // 2. Inline region, currently only works for a single basic block.
505   // 3. Emit store.
506   SmallVector<SmallVector<Value, 8>, 8> indexing;
507   SmallVector<Value, 8> outputBuffers;
508   for (unsigned i = 0; i < nOutputs; ++i) {
509     indexing.push_back(makeCanonicalAffineApplies(
510         b, loc, indexedGenericOp.getOutputIndexingMap(i), allIvs));
511     outputBuffers.push_back(indexedGenericOp.getOutputBuffer(i));
512   }
513   inlineRegionAndEmitStore<IndexedValueType>(indexedGenericOp, indexedValues,
514                                              indexing, outputBuffers);
515 }
516 
517 template <typename LoopTy>
518 static Optional<LinalgLoops> linalgOpToLoopsImpl(Operation *op,
519                                                  OpBuilder &builder) {
520   using IndexedValueTy = typename GenerateLoopNest<LoopTy>::IndexedValueTy;
521 
522   ScopedContext scope(builder, op->getLoc());
523 
524   // The flattened loopToOperandRangesMaps is expected to be an invertible
525   // permutation map (which is asserted in the inverse calculation).
526   auto linalgOp = cast<LinalgOp>(op);
527   assert(linalgOp.hasBufferSemantics() &&
528          "expected linalg op with buffer semantics");
529   auto mapsRange =
530       linalgOp.indexing_maps().template getAsRange<AffineMapAttr>();
531   auto maps = llvm::to_vector<8>(
532       llvm::map_range(mapsRange, [](AffineMapAttr a) { return a.getValue(); }));
533   SmallVector<Value, 8> sizes = getShape(builder, linalgOp);
534   AffineMap map = concatAffineMaps(maps);
535   auto loopRanges = emitLoopRanges(scope.getBuilderRef(), scope.getLocation(),
536                                    map, getShape(builder, linalgOp));
537   SmallVector<Value, 4> allIvs;
538   GenerateLoopNest<LoopTy>::doit(
539       loopRanges, /*iterInitArgs*/ {}, linalgOp.iterator_types().getValue(),
540       [&](ValueRange ivs, ValueRange iterArgs) -> scf::ValueVector {
541         assert(iterArgs.empty() && "unexpected iterArgs");
542         allIvs.append(ivs.begin(), ivs.end());
543         llvm::TypeSwitch<Operation *>(op)
544             .Case<CopyOp, FillOp, ConvOp, PoolingMaxOp, PoolingMinOp,
545                   PoolingSumOp, IndexedGenericOp, LinalgOp>([&](auto op) {
546               emitScalarImplementation<IndexedValueTy>(allIvs, op);
547             })
548             .Default([&](Operation *op) { assert(false && "unexpected op"); });
549         return scf::ValueVector{};
550       });
551   // Number of loop ops might be different from the number of ivs since some
552   // loops like affine.parallel and scf.parallel have multiple ivs.
553   llvm::SetVector<Operation *> loopSet;
554   for (Value iv : allIvs) {
555     if (!iv)
556       return {};
557     // The induction variable is a block argument of the entry block of the
558     // loop operation.
559     BlockArgument ivVal = iv.dyn_cast<BlockArgument>();
560     if (!ivVal)
561       return {};
562     loopSet.insert(ivVal.getOwner()->getParentOp());
563   }
564   LinalgLoops loops(loopSet.begin(), loopSet.end());
565   return loops;
566 }
567 
568 namespace {
569 template <typename LoopType>
570 class LinalgRewritePattern : public RewritePattern {
571 public:
572   LinalgRewritePattern() : RewritePattern(/*benefit=*/1, MatchAnyOpTypeTag()) {}
573 
574   LogicalResult matchAndRewrite(Operation *op,
575                                 PatternRewriter &rewriter) const override {
576     if (!isa<LinalgOp>(op))
577       return failure();
578     if (!linalgOpToLoopsImpl<LoopType>(op, rewriter))
579       return failure();
580     rewriter.eraseOp(op);
581     return success();
582   }
583 };
584 
585 struct FoldAffineOp;
586 } // namespace
587 
588 template <typename LoopType>
589 static void lowerLinalgToLoopsImpl(FuncOp funcOp, MLIRContext *context) {
590   OwningRewritePatternList patterns;
591   patterns.insert<LinalgRewritePattern<LoopType>>();
592   DimOp::getCanonicalizationPatterns(patterns, context);
593   AffineApplyOp::getCanonicalizationPatterns(patterns, context);
594   patterns.insert<FoldAffineOp>(context);
595   // Just apply the patterns greedily.
596   applyPatternsAndFoldGreedily(funcOp, std::move(patterns));
597 }
598 
599 namespace {
600 /// Local folding pattern for AffineApplyOp that we can apply greedily.
601 /// This replaces AffineApplyOp by the proper value in cases where the
602 /// associated map is trivial.
603 /// A trivial map here is defined as a map with a single result and either:
604 ///   1. Zero operand + returns a single AffineConstantExpr
605 ///   2. One operand + returns a single AffineDimExpr
606 ///   3. One operand + returns a single AffineSymbolExpr
607 //
608 /// In the first case, the AffineApplyOp is replaced by a new constant. In the
609 /// other cases, it is replaced by its unique operand.
610 struct FoldAffineOp : public RewritePattern {
611   FoldAffineOp(MLIRContext *context)
612       : RewritePattern(AffineApplyOp::getOperationName(), 0, context) {}
613 
614   LogicalResult matchAndRewrite(Operation *op,
615                                 PatternRewriter &rewriter) const override {
616     AffineApplyOp affineApplyOp = cast<AffineApplyOp>(op);
617     auto map = affineApplyOp.getAffineMap();
618     if (map.getNumResults() != 1 || map.getNumInputs() > 1)
619       return failure();
620 
621     AffineExpr expr = map.getResult(0);
622     if (map.getNumInputs() == 0) {
623       if (auto val = expr.dyn_cast<AffineConstantExpr>()) {
624         rewriter.replaceOpWithNewOp<ConstantIndexOp>(op, val.getValue());
625         return success();
626       }
627       return failure();
628     }
629     if (expr.dyn_cast<AffineDimExpr>() || expr.dyn_cast<AffineSymbolExpr>()) {
630       rewriter.replaceOp(op, op->getOperand(0));
631       return success();
632     }
633     return failure();
634   }
635 };
636 
637 struct LowerToAffineLoops
638     : public LinalgLowerToAffineLoopsBase<LowerToAffineLoops> {
639   void runOnFunction() override {
640     lowerLinalgToLoopsImpl<AffineForOp>(getFunction(), &getContext());
641   }
642 };
643 
644 struct LowerToLoops : public LinalgLowerToLoopsBase<LowerToLoops> {
645   void runOnFunction() override {
646     lowerLinalgToLoopsImpl<scf::ForOp>(getFunction(), &getContext());
647   }
648 };
649 
650 struct LowerToParallelLoops
651     : public LinalgLowerToParallelLoopsBase<LowerToParallelLoops> {
652   void runOnFunction() override {
653     lowerLinalgToLoopsImpl<scf::ParallelOp>(getFunction(), &getContext());
654   }
655 };
656 } // namespace
657 
658 std::unique_ptr<OperationPass<FuncOp>> mlir::createConvertLinalgToLoopsPass() {
659   return std::make_unique<LowerToLoops>();
660 }
661 
662 std::unique_ptr<OperationPass<FuncOp>>
663 mlir::createConvertLinalgToParallelLoopsPass() {
664   return std::make_unique<LowerToParallelLoops>();
665 }
666 
667 std::unique_ptr<OperationPass<FuncOp>>
668 mlir::createConvertLinalgToAffineLoopsPass() {
669   return std::make_unique<LowerToAffineLoops>();
670 }
671 
672 SmallVector<Range, 4> mlir::linalg::emitLoopRanges(OpBuilder &b, Location loc,
673                                                    AffineMap map,
674                                                    ValueRange viewSizes) {
675   unsigned numDims = map.getNumDims(), numRes = map.getNumResults();
676   unsigned numSym = map.getNumSymbols();
677   assert(viewSizes.size() == numRes + numSym &&
678          "viewSizes must contain sizes of all views and values for symbols");
679   SmallVector<Range, 4> res(numDims);
680   for (unsigned idx = 0; idx < numRes; ++idx) {
681     auto result = map.getResult(idx);
682     if (auto d = result.dyn_cast<AffineDimExpr>()) {
683       if (res[d.getPosition()].offset)
684         continue;
685       res[d.getPosition()] =
686           Range{std_constant_index(0), viewSizes[idx], std_constant_index(1)};
687     }
688 
689     // If the access pattern is of form (m, n)[s] -> (m + n - s floordiv 2),
690     // then the bounds are:
691     //   (s floordiv 2) <= m <= (size(m) + s floordiv 2 - s + 1).
692     // where size(n) is applied to the symbol s.
693     // This is done statically now.
694     if (auto binOp = result.dyn_cast<AffineBinaryOpExpr>()) {
695       auto lhs = binOp.getLHS().dyn_cast<AffineBinaryOpExpr>();
696       auto rhs = binOp.getRHS().dyn_cast<AffineBinaryOpExpr>();
697       if (!lhs || !rhs || binOp.getKind() != AffineExprKind::Add ||
698           lhs.getKind() != AffineExprKind::Add ||
699           rhs.getKind() != mlir::AffineExprKind::Mul)
700         continue;
701 
702       auto m = lhs.getLHS().dyn_cast<AffineDimExpr>();
703       auto n = lhs.getRHS().dyn_cast<AffineDimExpr>();
704       auto fDiv = rhs.getLHS().dyn_cast<AffineBinaryOpExpr>();
705       auto minusOne = rhs.getRHS().dyn_cast<AffineConstantExpr>();
706       if (!m || !n || !fDiv || !minusOne ||
707           fDiv.getKind() != AffineExprKind::FloorDiv ||
708           fDiv.getLHS().getKind() != AffineExprKind::SymbolId ||
709           fDiv.getRHS().getKind() != AffineExprKind::Constant)
710         continue;
711 
712       auto s = fDiv.getLHS().dyn_cast<AffineSymbolExpr>();
713       if (minusOne.getValue() != -1)
714         continue;
715 
716       int mPos = m.getPosition();
717       AffineExpr one = getAffineConstantExpr(1, s.getContext());
718       AffineExpr sizeOfM = getAffineSymbolExpr(numSym, s.getContext());
719       // Construction of upper bound (size(m) + s floordiv 2 - s + 1).
720       AffineExpr upperOffsetExpr = sizeOfM + fDiv + one - s;
721       AffineMap fromMap = AffineMap::get(numDims, numSym + 1, fDiv);
722       AffineMap toMap = AffineMap::get(numDims, numSym + 1, upperOffsetExpr);
723       SmallVector<Value, 8> values(viewSizes.begin(),
724                                    viewSizes.begin() + numDims);
725       values.insert(values.end(), viewSizes.begin() + numRes, viewSizes.end());
726       values.push_back(viewSizes[mPos]);
727       // Construction of the lower bound (s floordiv 2).
728       Value from = applyMapToValues(b, loc, fromMap, values).front();
729       Value to = applyMapToValues(b, loc, toMap, values).front();
730       res[mPos] = Range{from, to, std_constant_index(1)};
731     }
732   }
733   return res;
734 }
735 
736 /// Emits a loop nest with the proper body for `op`.
737 template <typename LoopTy>
738 Optional<LinalgLoops> mlir::linalg::linalgLowerOpToLoops(OpBuilder &builder,
739                                                          Operation *op) {
740   return linalgOpToLoopsImpl<LoopTy>(op, builder);
741 }
742 
743 template Optional<LinalgLoops>
744 mlir::linalg::linalgLowerOpToLoops<AffineForOp>(OpBuilder &builder,
745                                                 Operation *op);
746 template Optional<LinalgLoops>
747 mlir::linalg::linalgLowerOpToLoops<scf::ForOp>(OpBuilder &builder,
748                                                Operation *op);
749 template Optional<LinalgLoops>
750 mlir::linalg::linalgLowerOpToLoops<scf::ParallelOp>(OpBuilder &builder,
751                                                     Operation *op);
752 
753 /// Emits a loop nest of `affine.for` with the proper body for `op`.
754 LogicalResult mlir::linalg::linalgOpToAffineLoops(OpBuilder &builder,
755                                                   Operation *op) {
756   Optional<LinalgLoops> loops = linalgLowerOpToLoops<AffineForOp>(builder, op);
757   return loops ? success() : failure();
758 }
759 
760 /// Emits a loop nest of `scf.for` with the proper body for `op`.
761 LogicalResult mlir::linalg::linalgOpToLoops(OpBuilder &builder, Operation *op) {
762   Optional<LinalgLoops> loops = linalgLowerOpToLoops<scf::ForOp>(builder, op);
763   return loops ? success() : failure();
764 }
765 
766 /// Emits a loop nest of `scf.parallel` with the proper body for `op`.
767 LogicalResult mlir::linalg::linalgOpToParallelLoops(OpBuilder &builder,
768                                                     Operation *op) {
769   Optional<LinalgLoops> loops =
770       linalgLowerOpToLoops<scf::ParallelOp>(builder, op);
771   return loops ? success() : failure();
772 }
773