1 //===- LinalgTransforms.cpp - Linalg transformations as patterns ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements logic and helpers to expose Linalg transforms as rewrite
10 // patterns.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
15 #include "mlir/Dialect/Affine/Utils.h"
16 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
17 #include "mlir/Dialect/Linalg/Analysis/DependenceAnalysis.h"
18 #include "mlir/Dialect/Linalg/IR/Linalg.h"
19 #include "mlir/Dialect/Linalg/Transforms/HoistPadding.h"
20 #include "mlir/Dialect/Linalg/Utils/Utils.h"
21 #include "mlir/Dialect/SCF/Transforms.h"
22 #include "mlir/Dialect/Tensor/IR/Tensor.h"
23 #include "mlir/Dialect/Utils/StaticValueUtils.h"
24 #include "mlir/Dialect/Utils/StructuredOpsUtils.h"
25 #include "mlir/Dialect/Vector/VectorOps.h"
26 #include "mlir/IR/AffineExpr.h"
27 #include "mlir/IR/Matchers.h"
28 #include "mlir/Pass/Pass.h"
29 #include "mlir/Support/LLVM.h"
30 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
31 #include "llvm/ADT/ScopeExit.h"
32 #include "llvm/ADT/TypeSwitch.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <type_traits>
36 #include <utility>
37 
38 #define DEBUG_TYPE "linalg-transforms"
39 
40 using namespace mlir;
41 using namespace mlir::linalg;
42 
43 #define DBGS() (llvm::dbgs() << "[" DEBUG_TYPE << "]: ")
44 
45 //===----------------------------------------------------------------------===//
46 // Transformations exposed as rewrite patterns.
47 //===----------------------------------------------------------------------===//
48 // Marker used as attribute name in generated Linalg rewriting transformations.
49 const StringLiteral mlir::linalg::LinalgTransforms::kLinalgTransformMarker =
50     "__internal_linalg_transform__";
51 
52 mlir::linalg::LinalgTransformationFilter::LinalgTransformationFilter(
53     ArrayRef<StringAttr> matchDisjunction, Optional<StringAttr> replacement)
54     : matchDisjunction(matchDisjunction.begin(), matchDisjunction.end()),
55       replacement(replacement), matchByDefault(false) {}
56 
57 mlir::linalg::LinalgTransformationFilter::LinalgTransformationFilter(
58     const FilterFunction &f, ArrayRef<StringAttr> matchDisjunction,
59     Optional<StringAttr> replacement)
60     : filters(),
61       matchDisjunction(matchDisjunction.begin(), matchDisjunction.end()),
62       replacement(replacement), matchByDefault(false) {
63   if (f)
64     filters.push_back(f);
65 }
66 
67 LogicalResult mlir::linalg::LinalgTransformationFilter::checkAndNotify(
68     PatternRewriter &rewriter, Operation *op) const {
69   if (llvm::any_of(filters,
70                    [&](const FilterFunction &f) { return failed(f(op)); }))
71     return failure();
72 
73   auto attr = op->template getAttrOfType<StringAttr>(
74       LinalgTransforms::kLinalgTransformMarker);
75 
76   if (!attr) {
77     // 1. Has no filter case and matchDisjunction is empty.
78     if (matchDisjunction.empty() || matchByDefault)
79       return success();
80 
81     // 2. Has no filter but was expecting a filter.
82     return rewriter.notifyMatchFailure(op, [&](Diagnostic &diag) {
83       diag << " does not have any filter from list: ";
84       interleaveComma(matchDisjunction, diag);
85     });
86   }
87 
88   // 4. Match explicit filter.
89   for (auto filter : matchDisjunction)
90     if (attr.getValue() == filter)
91       return success();
92 
93   // 5. Fail to match.
94   return rewriter.notifyMatchFailure(op, [&](Diagnostic &diag) {
95     diag << " does not have any filter from list: ";
96     interleaveComma(matchDisjunction, diag);
97   });
98 }
99 
100 void mlir::linalg::LinalgTransformationFilter::
101     replaceLinalgTransformationFilter(PatternRewriter &rewriter,
102                                       Operation *op) const {
103   if (replacement.hasValue())
104     op->setAttr(LinalgTransforms::kLinalgTransformMarker,
105                 replacement.getValue());
106   else
107     op->removeAttr(
108         rewriter.getStringAttr(LinalgTransforms::kLinalgTransformMarker));
109 }
110 
111 bool mlir::linalg::LinalgTransformationFilter::hasReplacementFilter(
112     Operation *op) const {
113   if (!replacement)
114     return false;
115   auto attr = op->getAttr(LinalgTransforms::kLinalgTransformMarker)
116                   .dyn_cast<StringAttr>();
117   return attr && attr == replacement.getValue();
118 }
119 
120 LinalgTilingOptions &
121 mlir::linalg::LinalgTilingOptions::setTileSizes(ArrayRef<int64_t> ts) {
122   assert(!tileSizeComputationFunction && "tile sizes already set");
123   SmallVector<int64_t, 4> tileSizes(ts.begin(), ts.end());
124   tileSizeComputationFunction = [tileSizes](OpBuilder &b, Operation *op) {
125     OpBuilder::InsertionGuard guard(b);
126     b.setInsertionPointToStart(
127         &op->getParentOfType<FuncOp>().getBody().front());
128     return llvm::to_vector<4>(map_range(tileSizes, [&](int64_t s) {
129       Value v = b.create<arith::ConstantIndexOp>(op->getLoc(), s);
130       return v;
131     }));
132   };
133   return *this;
134 }
135 
136 LinalgTilingOptions &mlir::linalg::LinalgTilingOptions::scalarizeDynamicDims() {
137   assert(!tileSizeComputationFunction && "tile sizes already set");
138   tileSizeComputationFunction = [](OpBuilder &b, Operation *op) {
139     SmallVector<Value, 4> tileSizes;
140     auto linalgOp = dyn_cast<LinalgOp>(op);
141     if (!linalgOp)
142       return tileSizes;
143     Location loc = linalgOp.getLoc();
144     auto allShapeSizes = linalgOp.createFlatListOfOperandDims(b, loc);
145     AffineMap map = linalgOp.getShapesToLoopsMap();
146     if (!map)
147       return tileSizes;
148     auto shapeSizes = applyMapToValues(b, loc, map, allShapeSizes);
149     // If the shape size is dynamic, tile by 1. Otherwise, do not tile (tile
150     // size 0).
151     for (Value shapeSize : shapeSizes)
152       tileSizes.push_back(getConstantIntValue(shapeSize).hasValue()
153                               ? b.create<arith::ConstantIndexOp>(loc, 0)
154                               : b.create<arith::ConstantIndexOp>(loc, 1));
155     return tileSizes;
156   };
157   return *this;
158 }
159 
160 /// Helper function that tries to pad `opOperand`. Exit early for scalar
161 /// operands, if `paddingFunc` returns failure, or if `opOperand` is not defined
162 /// by an ExtractSliceOp. Otherwise, try to pad the operand even if it already
163 /// has a static shape. Set `result` to the result of the created PadTensorOp or
164 /// and return success if the operand either has been padded to a static shape
165 /// or already had a static shape and failure otherwise.
166 static LogicalResult padOperandToSmallestStaticBoundingBox(
167     OpBuilder &b, linalg::LinalgOp opToPad, OpOperand *opOperand,
168     const PaddingValueComputationFunction &paddingFunc,
169     const PaddingNoFoldComputationFunction &nofoldFunc, Value &result) {
170   // Get the shape of the operand and check if it has a dynamic shape. Only
171   // return failure if the operand is not a scalar and has a dynamic shape.
172   ArrayRef<int64_t> shape = opToPad.getShape(opOperand);
173   bool hasDynamicShape = llvm::is_contained(shape, ShapedType::kDynamicSize);
174 
175   // Cannot pad scalar operands.
176   if (shape.empty())
177     return success();
178 
179   // Cannot pad if the padding value is unknown.
180   FailureOr<Value> paddingValue = paddingFunc(b, *opOperand);
181   if (failed(paddingValue))
182     return failure(hasDynamicShape);
183 
184   // Cannot construct a static bounding box if the operand is not defined by an
185   // ExtractSliceOp.
186   auto sliceOp = opOperand->get().getDefiningOp<tensor::ExtractSliceOp>();
187   if (!sliceOp)
188     return failure(hasDynamicShape);
189 
190   // Compute the dropped dimensions if `sliceOp` is ranke-reducing.
191   llvm::SmallDenseSet<unsigned> droppedDims = sliceOp.getDroppedDims();
192 
193   // Upper bound the `sliceOp` sizes to obtain a static bounding box.
194   SmallVector<int64_t> staticSizes;
195   staticSizes.reserve(shape.size());
196   auto shapedOp = cast<OffsetSizeAndStrideOpInterface>(sliceOp.getOperation());
197   for (const auto &en : enumerate(shapedOp.getMixedSizes())) {
198     // Skip dropped dimensions.
199     if (droppedDims.contains(en.index()))
200       continue;
201     // If the size is an attribute add it directly to `staticSizes`.
202     if (en.value().is<Attribute>()) {
203       staticSizes.push_back(
204           en.value().get<Attribute>().dyn_cast<IntegerAttr>().getInt());
205       continue;
206     }
207     // Otherwise, try to compute a constant upper bound for the size value.
208     FailureOr<int64_t> upperBound =
209         getConstantUpperBoundForIndex(en.value().get<Value>());
210     if (failed(upperBound)) {
211       LLVM_DEBUG(DBGS() << "No constant bounding box can be found for padding");
212       return failure();
213     }
214     staticSizes.push_back(upperBound.getValue());
215   }
216   assert(staticSizes.size() == shape.size() &&
217          "expect the dynamic and static ranks to match");
218 
219   // Pad the operand to the bounding box defined by `staticSizes`.
220   auto staticTensorType = RankedTensorType::get(
221       staticSizes, getElementTypeOrSelf(opOperand->get()));
222   bool nofold = nofoldFunc ? nofoldFunc(*opOperand) : false;
223   result =
224       makeComposedPadHighOp(b, opToPad->getLoc(), staticTensorType,
225                             opOperand->get(), paddingValue.getValue(), nofold);
226   return success();
227 }
228 
229 FailureOr<SmallVector<Value>>
230 linalg::rewriteAsPaddedOp(OpBuilder &b, LinalgOp opToPad,
231                           const PaddingValueComputationFunction &paddingFunc,
232                           const PaddingNoFoldComputationFunction &nofoldFunc,
233                           LinalgOp &paddedOp) {
234   Location loc = opToPad->getLoc();
235 
236   // TODO: there are cases where we may still want to pad to larger sizes.
237   assert(opToPad.hasTensorSemantics() &&
238          "expected operation to have tensor semantics");
239 
240   OpBuilder::InsertionGuard g(b);
241   // Set IP after op because we also take the dims of the original output.
242   b.setInsertionPointAfter(opToPad);
243   // Make a copy of the shaped operands and update it.
244   SmallVector<Value> newOperands;
245   newOperands.reserve(opToPad.getNumInputsAndOutputs());
246   for (OpOperand *opOperand : opToPad.getInputAndOutputOperands()) {
247     Value paddedOperand;
248     // If padding was requested but the shape cannot be bounded statically then
249     // the pattern fails to apply.
250     if (failed(padOperandToSmallestStaticBoundingBox(
251             b, opToPad, opOperand, paddingFunc, nofoldFunc, paddedOperand)))
252       return failure();
253     newOperands.push_back(paddedOperand ? paddedOperand : opOperand->get());
254   }
255 
256   SmallVector<SmallVector<Value>> reifiedResultShapes;
257   if (failed(cast<ReifyRankedShapedTypeOpInterface>(opToPad.getOperation())
258                  .reifyResultShapes(b, reifiedResultShapes)))
259     return failure();
260   assert(reifiedResultShapes.size() == opToPad->getNumResults() &&
261          "expected same number of results");
262 
263   // Clone `opToPad` to operate on the statically padded shapes.
264   auto resultTensorTypes =
265       ValueRange(newOperands).take_back(opToPad.getNumOutputs()).getTypes();
266   paddedOp = opToPad.clone(b, loc, resultTensorTypes, newOperands);
267 
268   // Recover the slice out of the new static results. This keeps the original
269   // linalg op around because it uses the dims of the original results.
270   SmallVector<Value> paddedSubviewResults;
271   paddedSubviewResults.reserve(opToPad->getNumResults());
272   for (const auto &en : llvm::enumerate(paddedOp->getResults())) {
273     Value paddedResult = en.value();
274     int64_t resultNumber = en.index();
275     int64_t rank = paddedResult.getType().cast<RankedTensorType>().getRank();
276     SmallVector<OpFoldResult> offsets(rank, b.getIndexAttr(0));
277     SmallVector<OpFoldResult> sizes;
278     for (Value v : reifiedResultShapes[resultNumber])
279       sizes.push_back(getAsOpFoldResult(v));
280     SmallVector<OpFoldResult> strides(rank, b.getIndexAttr(1));
281     paddedSubviewResults.push_back(b.create<tensor::ExtractSliceOp>(
282         loc, paddedResult, offsets, sizes, strides));
283   }
284   return paddedSubviewResults;
285 }
286 
287 /// Linalg base tiling pattern.
288 mlir::linalg::LinalgBaseTilingPattern::LinalgBaseTilingPattern(
289     StringRef opName, MLIRContext *context, LinalgTilingOptions options,
290     LinalgTransformationFilter filter, PatternBenefit benefit)
291     : RewritePattern(opName, benefit, context), filter(std::move(filter)),
292       options(std::move(options)) {}
293 
294 mlir::linalg::LinalgBaseTilingPattern::LinalgBaseTilingPattern(
295     MLIRContext *context, LinalgTilingOptions options,
296     LinalgTransformationFilter filter, PatternBenefit benefit)
297     : RewritePattern(MatchAnyOpTypeTag(), benefit, context),
298       filter(std::move(filter)), options(std::move(options)) {}
299 
300 /// Try to peel a loop `op` and return the new result.
301 // TODO: Add support for scf.parallel and affine.for loops.
302 static SmallVector<Value, 4> peelLoop(RewriterBase &rewriter, Operation *op) {
303   return llvm::TypeSwitch<Operation *, SmallVector<Value, 4>>(op)
304       .Case<scf::ForOp>([&](scf::ForOp forOp) {
305         scf::ForOp partialIteration;
306         if (succeeded(scf::peelAndCanonicalizeForLoop(rewriter, forOp,
307                                                       partialIteration)))
308           return partialIteration->getResults();
309         assert(!partialIteration && "expected that loop was not peeled");
310         return forOp->getResults();
311       })
312       .Default([&](Operation *op) { return op->getResults(); });
313 }
314 
315 /// Try to peel a TiledLoopOp and return the new result.
316 static SmallVector<Value, 4> peelLoop(RewriterBase &rewriter,
317                                       TiledLoopOp tiledLoop, int64_t idx) {
318   assert(idx < static_cast<int64_t>(tiledLoop.iterator_types().size()) &&
319          "requested peeling of non-existing loop");
320   TiledLoopOp result;
321   if (succeeded(peelAndCanonicalizeTiledLoop(rewriter, tiledLoop, idx, result)))
322     return result->getResults();
323   assert(!result && "expected that loop was not peeled");
324   return tiledLoop->getResults();
325 }
326 
327 /// Peel loops after tiling.
328 static void peelLoops(RewriterBase &rewriter, TiledLinalgOp &res,
329                       const LinalgTilingOptions &options) {
330   for (int64_t loop : options.peeledLoops) {
331     assert(loop < static_cast<int64_t>(res.loops.size()) &&
332            "requested peeling of non-existing loop");
333     SmallVector<Value, 4> loopResults;
334     Operation *loopOp = res.loops[loop];
335     if (options.loopType == LinalgTilingLoopType::TiledLoops) {
336       assert(llvm::all_of(
337                  res.loops,
338                  [&](Operation *op) { return op == res.loops.front(); }) &&
339              "expected that all loop ops are the same TiledLoopOp");
340       auto tiledLoopOp = dyn_cast<TiledLoopOp>(loopOp);
341       assert(tiledLoopOp && "expected TiledLoopOp");
342       loopResults = peelLoop(rewriter, tiledLoopOp, loop);
343     } else {
344       loopResults = peelLoop(rewriter, loopOp);
345     }
346 
347     // The result of the loop nest may change with peeling.
348     if (res.tensorResults.size() == loopOp->getNumResults() &&
349         std::equal(res.tensorResults.begin(), res.tensorResults.end(),
350                    loopOp->getResults().begin()))
351       res.tensorResults = loopResults;
352   }
353 }
354 
355 LogicalResult mlir::linalg::LinalgBaseTilingPattern::matchAndRewriteBase(
356     Operation *op, PatternRewriter &rewriter, TiledLinalgOp &result) const {
357   LinalgOp linalgOp = dyn_cast<LinalgOp>(op);
358   if (!linalgOp)
359     return failure();
360   if (failed(filter.checkAndNotify(rewriter, linalgOp)))
361     return failure();
362 
363   Optional<TiledLinalgOp> res = tileLinalgOp(rewriter, linalgOp, options);
364 
365   if (!res)
366     return failure();
367   // Clear filter to stop recursive pattern application.
368   filter.replaceLinalgTransformationFilter(rewriter, res->op);
369 
370   // Peel loops.
371   peelLoops(rewriter, *res, options);
372 
373   result = *res;
374   return success();
375 }
376 
377 static ValueRange getTiledOpResult(TiledLinalgOp tiledOp) {
378   if (tiledOp.loops.empty())
379     return tiledOp.op.getOperation()->getResults();
380   return tiledOp.loops.front()->getResults();
381 }
382 
383 static ValueRange
384 getTiledAndFusedOpResult(TiledAndFusedLinalgOps tiledAndFusedOp) {
385   if (tiledAndFusedOp.fusedLoops.empty())
386     return tiledAndFusedOp.op.getOperation()->getResults();
387   return tiledAndFusedOp.fusedLoops.front()->getResults();
388 }
389 
390 mlir::linalg::LinalgBaseTileAndFusePattern::LinalgBaseTileAndFusePattern(
391     StringRef opName, MLIRContext *context,
392     const LinalgDependenceGraph &dependenceGraph,
393     LinalgTilingOptions tilingOptions, LinalgFusionOptions fusionOptions,
394     LinalgTransformationFilter filter, LinalgTransformationFilter fusedOpMarker,
395     LinalgTransformationFilter originalOpMarker, PatternBenefit benefit)
396     : RewritePattern(opName, benefit, context, {}),
397       dependenceGraph(dependenceGraph), tilingOptions(std::move(tilingOptions)),
398       fusionOptions(std::move(fusionOptions)), filter(std::move(filter)),
399       fusedOpMarker(std::move(fusedOpMarker)),
400       originalOpMarker(std::move(originalOpMarker)) {}
401 
402 LogicalResult mlir::linalg::LinalgBaseTileAndFusePattern::matchAndRewrite(
403     Operation *op, PatternRewriter &rewriter) const {
404   LinalgOp linalgOp = dyn_cast<LinalgOp>(op);
405   // TODO: remove hasIndexSemantics check once index ops are supported.
406   if (!linalgOp || linalgOp.hasIndexSemantics())
407     return failure();
408   if (failed(filter.checkAndNotify(rewriter, linalgOp)))
409     return failure();
410 
411   DenseSet<Operation *> producers;
412   producers.insert(linalgOp);
413   for (auto dependence : dependenceGraph.getDependentOperationsInto(linalgOp)) {
414     Optional<unsigned> operandNumber = dependence.getIndexingOpViewOperandNum();
415     // When looking at dependences into, indexingOp is always OpOperand. We
416     // could assert, but continue if this is not the case.
417     if (!operandNumber)
418       continue;
419     if (!fusionOptions.indicesToFuse.count(operandNumber.getValue()))
420       continue;
421     if (isa<LinalgOp>(dependence.getDependentOp()))
422       producers.insert(dependence.getDependentOp());
423   }
424 
425   SmallVector<LinalgOp, 1> fusionOps;
426   for (auto it = op->getBlock()->begin(), ie = Block::iterator(op); it != ie;
427        ++it) {
428     auto producerLinalgOp = dyn_cast<LinalgOp>(&(*it));
429     if (producerLinalgOp && producers.count(producerLinalgOp))
430       fusionOps.push_back(producerLinalgOp);
431   }
432   fusionOps.push_back(linalgOp);
433 
434   SmallVector<Value, 4> tileSizes =
435       tilingOptions.tileSizeComputationFunction(rewriter, op);
436   LinalgTilingOptions instanceTilingOptions = tilingOptions;
437   instanceTilingOptions.setTileSizes(tileSizes);
438   Optional<TiledAndFusedLinalgOps> tiledAndFusedOps = tileAndFuseLinalgOps(
439       rewriter, fusionOps, dependenceGraph, instanceTilingOptions);
440   if (!tiledAndFusedOps)
441     return failure();
442 
443   // Tile the unfused loops;
444   SmallVector<Value, 4> unfusedLoopTileSizes;
445   Value zero = rewriter.create<arith::ConstantIndexOp>(op->getLoc(), 0);
446   for (const auto &tileSize : enumerate(tileSizes)) {
447     if (tiledAndFusedOps->fusedLoopDims.count(tileSize.index()))
448       unfusedLoopTileSizes.push_back(zero);
449     else
450       unfusedLoopTileSizes.push_back(tileSize.value());
451   }
452   // Tile the loop only if there is a non-zero tile size.
453   if (unfusedLoopTileSizes.size() > linalgOp.getNumLoops())
454     unfusedLoopTileSizes.resize(linalgOp.getNumLoops());
455   if (llvm::any_of(unfusedLoopTileSizes, [](Value val) {
456         if (auto cst = val.getDefiningOp<arith::ConstantIndexOp>())
457           return cst.value() != 0;
458         return true;
459       })) {
460     LinalgTilingOptions unfusedTilingOptions = tilingOptions;
461     unfusedTilingOptions.setTileSizes(unfusedLoopTileSizes);
462     Optional<TiledLinalgOp> unfusedTiledOp =
463         tileLinalgOp(rewriter, tiledAndFusedOps->op, unfusedTilingOptions);
464     if (!unfusedTiledOp)
465       return failure();
466     rewriter.replaceOp(tiledAndFusedOps->op,
467                        getTiledOpResult(unfusedTiledOp.getValue()));
468     tiledAndFusedOps->op = unfusedTiledOp->op;
469   }
470   op->replaceAllUsesWith(getTiledAndFusedOpResult(tiledAndFusedOps.getValue()));
471 
472   filter.replaceLinalgTransformationFilter(rewriter,
473                                            tiledAndFusedOps->op.getOperation());
474   for (auto fusedOp : tiledAndFusedOps->fusedProducers) {
475     fusedOpMarker.replaceLinalgTransformationFilter(rewriter,
476                                                     fusedOp.getOperation());
477   }
478   for (auto origProducerOp : ArrayRef<LinalgOp>(fusionOps).drop_back()) {
479     originalOpMarker.replaceLinalgTransformationFilter(
480         rewriter, origProducerOp.getOperation());
481   }
482   rewriter.updateRootInPlace(op, [&]() {
483     originalOpMarker.replaceLinalgTransformationFilter(rewriter, op);
484   });
485   return success();
486 }
487 
488 /// Linalg padding pattern.
489 mlir::linalg::LinalgPaddingPattern::LinalgPaddingPattern(
490     MLIRContext *context, LinalgPaddingOptions options,
491     LinalgTransformationFilter filter, PatternBenefit benefit)
492     : RewritePattern(MatchAnyOpTypeTag(), benefit, context),
493       filter(std::move(filter)), options(std::move(options)) {}
494 
495 mlir::linalg::LinalgPaddingPattern::LinalgPaddingPattern(
496     StringRef opName, MLIRContext *context, LinalgPaddingOptions options,
497     LinalgTransformationFilter filter, PatternBenefit benefit)
498     : RewritePattern(opName, benefit, context, {}), filter(std::move(filter)),
499       options(std::move(options)) {}
500 
501 LogicalResult mlir::linalg::LinalgPaddingPattern::matchAndRewrite(
502     Operation *op, PatternRewriter &rewriter) const {
503   LinalgOp linalgOp = dyn_cast<LinalgOp>(op);
504   if (!linalgOp)
505     return failure();
506   if (!linalgOp.hasTensorSemantics())
507     return failure();
508   if (failed(filter.checkAndNotify(rewriter, op)))
509     return failure();
510 
511   // Pad the operation.
512   LinalgOp paddedOp;
513   FailureOr<SmallVector<Value>> newResults = rewriteAsPaddedOp(
514       rewriter, linalgOp, options.paddingValueComputationFunction,
515       options.paddingNoFoldComputationFunction, paddedOp);
516   if (failed(newResults))
517     return failure();
518 
519   // Compute the desired hoisting depths.
520   SmallVector<int64_t> depths;
521   if (options.paddingHoistComputationFunction) {
522     for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands())
523       depths.push_back(options.paddingHoistComputationFunction(*opOperand));
524   }
525 
526   // Hoist the padding.
527   for (const auto &en : enumerate(depths)) {
528     OpOperand &opOperand = paddedOp->getOpOperand(en.index());
529     auto padTensorOp = opOperand.get().getDefiningOp<PadTensorOp>();
530     if (!padTensorOp || en.value() == 0)
531       continue;
532     PadTensorOp hoistedOp;
533     FailureOr<Value> newResult =
534         hoistPaddingOnTensors(padTensorOp, en.value(), hoistedOp);
535     if (failed(newResult))
536       continue;
537     rewriter.replaceOp(padTensorOp, newResult.getValue());
538   }
539 
540   // Replace the original operation to pad.
541   rewriter.replaceOp(op, newResults.getValue());
542   filter.replaceLinalgTransformationFilter(rewriter, paddedOp);
543   return success();
544 }
545 
546 /// Linalg tile and fuse tensor ops pattern.
547 mlir::linalg::LinalgTileAndFuseTensorOpsPattern::
548     LinalgTileAndFuseTensorOpsPattern(MLIRContext *context,
549                                       LinalgTilingAndFusionOptions options,
550                                       LinalgTransformationFilter filter,
551                                       PatternBenefit benefit)
552     : RewritePattern(MatchAnyOpTypeTag(), benefit, context),
553       filter(std::move(filter)), options(std::move(options)) {}
554 
555 mlir::linalg::LinalgTileAndFuseTensorOpsPattern::
556     LinalgTileAndFuseTensorOpsPattern(StringRef opName, MLIRContext *context,
557                                       LinalgTilingAndFusionOptions options,
558                                       LinalgTransformationFilter filter,
559                                       PatternBenefit benefit)
560     : RewritePattern(opName, benefit, context), filter(std::move(filter)),
561       options(std::move(options)) {}
562 
563 LogicalResult mlir::linalg::LinalgTileAndFuseTensorOpsPattern::matchAndRewrite(
564     Operation *op, PatternRewriter &rewriter) const {
565   LinalgOp rootOp = dyn_cast<LinalgOp>(op);
566   if (!rootOp)
567     return failure();
568   if (failed(filter.checkAndNotify(rewriter, op)))
569     return failure();
570 
571   // Check `tileSizes` contains a tile size for every `rootOp` loop dimension.
572   if (options.tileSizes.size() < rootOp.getNumLoops())
573     return rewriter.notifyMatchFailure(op, "expect #tile sizes >= #loops");
574 
575   // Check `tileInterchange` contains no entries or as many as `tileSizes`.
576   if (!options.tileInterchange.empty() &&
577       options.tileInterchange.size() != options.tileSizes.size())
578     return rewriter.notifyMatchFailure(
579         op, "expect the number of tile sizes and interchange dims to match");
580 
581   // Copy the `tileSizes` and `tileInterchange` prefixes needed for `rootOp`.
582   SmallVector<int64_t> rootTileSizes(options.tileSizes.begin(),
583                                      options.tileSizes.begin() +
584                                          rootOp.getNumLoops());
585   SmallVector<int64_t> rootInterchange =
586       options.tileInterchange.empty()
587           ? llvm::to_vector<6>(llvm::seq<int64_t>(0, rootOp.getNumLoops()))
588           : SmallVector<int64_t>(options.tileInterchange.begin(),
589                                  options.tileInterchange.begin() +
590                                      rootOp.getNumLoops());
591 
592   // Check `rootInterchange` is a permutation of the `rootOp` loop dimensions.
593   // It has to be a permutation since the tiling cannot tile the same loop
594   // dimension multiple times.
595   if (!isPermutation(rootInterchange))
596     return rewriter.notifyMatchFailure(
597         op, "expect the tile interchange permutes the root loops");
598 
599   // Tile `rootOp` and fuse its producers.
600   FailureOr<TileLoopNest> tileLoopNest = tileConsumerAndFuseProducers(
601       rewriter, rootOp, rootTileSizes, rootInterchange);
602   if (failed(tileLoopNest))
603     return rewriter.notifyMatchFailure(
604         op, "tileConsumerAndFuseProducers failed unexpectedly");
605 
606   // Replace all uses of the tiled loop operation.
607   rootOp->replaceAllUsesWith(tileLoopNest->getRootOpReplacementResults());
608 
609   // Apply the filter if specified.
610   for (LinalgOp linalgOp : tileLoopNest->getAllTiledAndFusedOps())
611     filter.replaceLinalgTransformationFilter(rewriter, linalgOp);
612   return failure();
613 }
614 
615 /// Linalg generic interchange pattern.
616 mlir::linalg::GenericOpInterchangePattern::GenericOpInterchangePattern(
617     MLIRContext *context, ArrayRef<unsigned> interchangeVector,
618     LinalgTransformationFilter filter, PatternBenefit benefit)
619     : OpRewritePattern(context, benefit), filter(std::move(filter)),
620       interchangeVector(interchangeVector.begin(), interchangeVector.end()) {}
621 
622 LogicalResult mlir::linalg::GenericOpInterchangePattern::matchAndRewrite(
623     GenericOp genericOp, PatternRewriter &rewriter) const {
624   if (failed(filter.checkAndNotify(rewriter, genericOp)))
625     return failure();
626   if (failed(interchangeGenericOpPrecondition(genericOp, interchangeVector)))
627     return failure();
628 
629   // TODO: figure out how this interplays with named ops. In particular this
630   // should break the named op property.
631   rewriter.updateRootInPlace(genericOp, [&]() {
632     interchangeGenericOp(rewriter, genericOp, interchangeVector);
633     // New filter if specified.
634     filter.replaceLinalgTransformationFilter(rewriter, genericOp);
635   });
636   return success();
637 }
638 
639 /// Linalg generalization pattern.
640 mlir::linalg::LinalgGeneralizationPattern::LinalgGeneralizationPattern(
641     MLIRContext *context, LinalgTransformationFilter filter,
642     PatternBenefit benefit)
643     : RewritePattern(MatchAnyOpTypeTag(), benefit, context),
644       filter(std::move(filter)) {}
645 
646 mlir::linalg::LinalgGeneralizationPattern::LinalgGeneralizationPattern(
647     StringRef opName, MLIRContext *context, LinalgTransformationFilter filter,
648     PatternBenefit benefit)
649     : RewritePattern(opName, benefit, context, {}), filter(std::move(filter)) {}
650 
651 LogicalResult mlir::linalg::LinalgGeneralizationPattern::matchAndRewrite(
652     Operation *op, PatternRewriter &rewriter) const {
653   if (failed(filter.checkAndNotify(rewriter, op)))
654     return failure();
655   if (failed(generalizeNamedOpPrecondition(op)))
656     return failure();
657 
658   GenericOp genericOp = generalizeNamedOp(rewriter, op);
659   rewriter.replaceOp(op, genericOp.getResults());
660   filter.replaceLinalgTransformationFilter(rewriter, genericOp);
661   return success();
662 }
663 
664 mlir::linalg::LinalgBasePromotionPattern::LinalgBasePromotionPattern(
665     MLIRContext *context, LinalgTransformationFilter filter,
666     LinalgPromotionOptions options, PatternBenefit benefit)
667     : RewritePattern(MatchAnyOpTypeTag(), benefit, context),
668       filter(std::move(filter)), options(std::move(options)) {}
669 
670 mlir::linalg::LinalgBasePromotionPattern::LinalgBasePromotionPattern(
671     StringRef opName, MLIRContext *context, LinalgPromotionOptions options,
672     LinalgTransformationFilter filter, PatternBenefit benefit)
673     : RewritePattern(opName, benefit, context, {}), filter(std::move(filter)),
674       options(std::move(options)) {}
675 
676 LogicalResult mlir::linalg::LinalgBasePromotionPattern::matchAndRewrite(
677     Operation *op, PatternRewriter &rewriter) const {
678   if (failed(filter.checkAndNotify(rewriter, op)))
679     return failure();
680   if (failed(promoteSubviewsPrecondition(op, options)))
681     return failure();
682 
683   // TODO: We cannot use root update here. This pattern is creating other ops,
684   // so if the promotion fails, those need to be cleaned up, which doesnt seem
685   // to be happening here. So to fail properly, we should be cloning the op and
686   // deleting the previous op. This needs more investigation.
687   rewriter.startRootUpdate(op);
688   Optional<LinalgOp> promotedOp = promoteSubViews(rewriter, op, options);
689   if (!promotedOp) {
690     rewriter.cancelRootUpdate(op);
691     return op->emitError("subview promotion failed");
692   }
693   rewriter.finalizeRootUpdate(op);
694   filter.replaceLinalgTransformationFilter(rewriter, op);
695   return success();
696 }
697 
698 mlir::linalg::LinalgBaseVectorizationPattern::LinalgBaseVectorizationPattern(
699     MLIRContext *context, LinalgTransformationFilter filter,
700     PatternBenefit benefit)
701     : RewritePattern(MatchAnyOpTypeTag(), benefit, context),
702       filter(std::move(filter)) {}
703 
704 mlir::linalg::LinalgBaseVectorizationPattern::LinalgBaseVectorizationPattern(
705     StringRef opName, MLIRContext *context, LinalgTransformationFilter filter,
706     PatternBenefit benefit)
707     : RewritePattern(opName, benefit, context, {}), filter(std::move(filter)) {}
708 
709 LogicalResult mlir::linalg::LinalgBaseVectorizationPattern::matchAndRewrite(
710     Operation *op, PatternRewriter &rewriter) const {
711   LinalgOp linalgOp = dyn_cast<LinalgOp>(op);
712   if (!linalgOp)
713     return failure();
714   if (failed(filter.checkAndNotify(rewriter, linalgOp)))
715     return failure();
716   SmallVector<Value> newResults;
717   if (failed(vectorizeLinalgOp(rewriter, op, newResults)))
718     return failure();
719   if (!newResults.empty())
720     rewriter.replaceOp(op, newResults);
721   else
722     rewriter.eraseOp(op);
723   return success();
724 }
725 
726 LogicalResult mlir::linalg::applyStagedPatterns(
727     Operation *op, ArrayRef<FrozenRewritePatternSet> stage1Patterns,
728     const FrozenRewritePatternSet &stage2Patterns,
729     function_ref<LogicalResult(Operation *)> stage3Lambda) {
730   unsigned iteration = 0;
731   (void)iteration;
732   for (const auto &patterns : stage1Patterns) {
733     LLVM_DEBUG(DBGS() << "Before 1st stage, iter: " << ++iteration << "\n"
734                       << *op);
735     if (failed(applyPatternsAndFoldGreedily(op, patterns))) {
736       LLVM_DEBUG(DBGS() << "Underlying first stage rewrite did not converge");
737       return failure();
738     }
739     LLVM_DEBUG(DBGS() << "After 1st stage, iter: " << ++iteration << "\n"
740                       << *op);
741     if (failed(applyPatternsAndFoldGreedily(op, stage2Patterns))) {
742       LLVM_DEBUG(DBGS() << "Underlying 2nd stage rewrite did not converge");
743       return failure();
744     }
745     LLVM_DEBUG(DBGS() << "After 2nd stage, iter : " << iteration << "\n"
746                       << *op);
747     if (stage3Lambda) {
748       if (failed(stage3Lambda(op)))
749         return failure();
750       LLVM_DEBUG(DBGS() << "After 3rd stage, iter : " << iteration << "\n"
751                         << *op);
752     }
753   }
754   return success();
755 }
756 
757 static SmallVector<StringRef> getNParallelLoopsAttrs(unsigned nParallelLoops) {
758   return SmallVector<StringRef>(nParallelLoops, getParallelIteratorTypeName());
759 }
760 
761 /// Rewrite a PadTensorOp into a sequence of InitTensorOp, FillOp (to initialize
762 /// with pad_val) and GenericOp (to copy contents).
763 LogicalResult PadTensorOpTransformationPattern::matchAndRewrite(
764     linalg::PadTensorOp padOp, PatternRewriter &rewriter) const {
765 
766   auto inputShapedType = padOp.source().getType().cast<ShapedType>();
767   auto resultShapedType = padOp.result().getType().cast<ShapedType>();
768 
769   // Bail on non-static shapes.
770   if (!inputShapedType.hasStaticShape())
771     return failure();
772   if (!resultShapedType.hasStaticShape())
773     return failure();
774 
775   // Only support padding with a constant for now, i.e. either:
776   //   1. A BBarg from a different block.
777   //   2. A value defined outside of the current block.
778   Block &block = padOp.region().front();
779   auto yieldOp = cast<YieldOp>(block.getTerminator());
780   assert(yieldOp.getNumOperands() == 1 && "expected single operand yield");
781   Value padValue = yieldOp.values().front();
782   Operation *definingOp = padValue.getDefiningOp();
783   if (definingOp && definingOp->getBlock() == &block)
784     return failure();
785   if (!definingOp && padValue.cast<BlockArgument>().getOwner() == &block)
786     return failure();
787 
788   // Create tensor with the padded shape
789   Location loc = padOp.getLoc();
790   SmallVector<Value> indices(resultShapedType.getRank(),
791                              rewriter.create<arith::ConstantIndexOp>(loc, 0));
792   Value initTensor = rewriter.create<InitTensorOp>(
793       loc, resultShapedType.getShape(), resultShapedType.getElementType());
794 
795   // Initialize tensor with the pad value
796   Value tmpTensor =
797       rewriter.create<linalg::FillOp>(loc, padValue, initTensor).result();
798 
799   // Copy original contents into new tensor
800   // Uses linalg.generic, but could be done with tensor.insert_slice
801   SmallVector<AffineExpr, 4> outputExprs;
802   for (unsigned i = 0; i < resultShapedType.getRank(); ++i) {
803     outputExprs.push_back(getAffineDimExpr(i, rewriter.getContext()) +
804                           padOp.static_low()[i].cast<IntegerAttr>().getInt());
805   }
806 
807   SmallVector<AffineMap, 2> transferMaps = {
808       rewriter.getMultiDimIdentityMap(inputShapedType.getRank()),
809       AffineMap::get(resultShapedType.getRank(),
810                      /*symbolCount=*/0, outputExprs, rewriter.getContext())};
811 
812   rewriter.replaceOpWithNewOp<linalg::GenericOp>(
813       padOp, resultShapedType, padOp.source(), tmpTensor, transferMaps,
814       getNParallelLoopsAttrs(resultShapedType.getRank()),
815       [&](OpBuilder &nestedBuilder, Location nestedLoc, ValueRange args) {
816         nestedBuilder.create<linalg::YieldOp>(nestedLoc, args[0]);
817       });
818 
819   return success();
820 }
821 
822 /// Filling `dest` using FillOp constant padding value if possible.
823 /// Otherwise, generate a tensor::GenerateOp.
824 Value GeneralizePadTensorOpPattern::createFillOrGenerateOp(
825     PatternRewriter &rewriter, PadTensorOp padOp, Value dest,
826     const SmallVector<Value> &dynSizes) const {
827   auto padValue = padOp.getConstantPaddingValue();
828   if (padValue)
829     return rewriter.create<FillOp>(padOp.getLoc(), padValue, dest).result();
830 
831   // Fill could not be optimized: Lower to tensor::GenerateOp with region.
832   auto generateOp = rewriter.create<tensor::GenerateOp>(
833       padOp.getLoc(), padOp.getResultType(), dynSizes);
834   // Copy region to new op.
835   BlockAndValueMapping bvm;
836   padOp.region().cloneInto(&generateOp.getRegion(), bvm);
837   // Rewrite linalg::YieldOp to tensor::YieldOp.
838   OpBuilder::InsertionGuard guard(rewriter);
839   auto yieldOp =
840       dyn_cast<linalg::YieldOp>(generateOp.getRegion().front().getTerminator());
841   assert(yieldOp && "malformed PadTensorOp: expected YieldOp terminator");
842   assert(yieldOp.values().size() == 1);
843   rewriter.setInsertionPoint(yieldOp);
844   rewriter.replaceOpWithNewOp<tensor::YieldOp>(yieldOp, yieldOp.values()[0]);
845   return generateOp;
846 }
847 
848 LogicalResult
849 GeneralizePadTensorOpPattern::matchAndRewrite(PadTensorOp padOp,
850                                               PatternRewriter &rewriter) const {
851   // Given an OpFoldResult, return an index-typed value.
852   auto getIdxValue = [&](OpFoldResult ofr) {
853     if (auto val = ofr.dyn_cast<Value>())
854       return val;
855     return rewriter
856         .create<arith::ConstantIndexOp>(
857             padOp.getLoc(), ofr.get<Attribute>().cast<IntegerAttr>().getInt())
858         .getResult();
859   };
860 
861   auto resultType = padOp.getResultType();
862   // Compute size of InitTensorOp. Any combination of static/dynamic is
863   // supported.
864   SmallVector<Value> dynSizes;
865   SmallVector<int64_t> staticSizes;
866   for (unsigned dim = 0; dim < resultType.getRank(); ++dim) {
867     if (resultType.isDynamicDim(dim)) {
868       auto srcSize = rewriter.createOrFold<tensor::DimOp>(padOp.getLoc(),
869                                                           padOp.source(), dim);
870       // Add low and high padding value.
871       auto plusLow = rewriter.createOrFold<arith::AddIOp>(
872           padOp.getLoc(), srcSize, getIdxValue(padOp.getMixedLowPad()[dim]));
873       auto plusHigh = rewriter.createOrFold<arith::AddIOp>(
874           padOp.getLoc(), plusLow, getIdxValue(padOp.getMixedHighPad()[dim]));
875       dynSizes.push_back(plusHigh);
876     }
877     staticSizes.push_back(resultType.getDimSize(dim));
878   }
879 
880   // Init tensor and fill it with padding.
881   Value init = rewriter.create<InitTensorOp>(
882       padOp.getLoc(), dynSizes, staticSizes, resultType.getElementType());
883   Value fill = createFillOrGenerateOp(rewriter, padOp, init, dynSizes);
884 
885   // Try optimize the copy of source.
886   if (optimizeCopyFn && optimizeCopyFn(rewriter, padOp, fill).succeeded())
887     return success();
888 
889   // PadTensorOps cannot be optimized. Generate a InsertSliceOp instead
890   // for copying the PadOp source.
891   auto sourceType = padOp.getSourceType();
892   // Compute size of source of PadTensorOp.
893   SmallVector<OpFoldResult> srcSizes;
894   for (unsigned dim = 0; dim < sourceType.getRank(); ++dim) {
895     if (sourceType.isDynamicDim(dim)) {
896       srcSizes.push_back(rewriter.createOrFold<tensor::DimOp>(
897           padOp.getLoc(), padOp.source(), dim));
898     } else {
899       srcSizes.push_back(rewriter.getIndexAttr(sourceType.getDimSize(dim)));
900     }
901   }
902   // Strides of InsertSliceOp are all 1.
903   SmallVector<OpFoldResult> strides(sourceType.getRank(),
904                                     rewriter.getIndexAttr(1));
905   rewriter.replaceOpWithNewOp<tensor::InsertSliceOp>(
906       padOp, padOp.source(), fill, padOp.getMixedLowPad(), srcSizes, strides);
907 
908   return success();
909 }
910 
911 LogicalResult ExtractSliceOfPadTensorSwapPattern::matchAndRewrite(
912     tensor::ExtractSliceOp sliceOp, PatternRewriter &rewriter) const {
913   auto padOp = sliceOp.source().getDefiningOp<PadTensorOp>();
914   if (!padOp)
915     return failure();
916   // Only unit stride supported.
917   if (!sliceOp.hasUnitStride())
918     return failure();
919 
920   Operation *tiledPadOp =
921       padOp
922           .getTiledImplementation(
923               rewriter, /*dest=*/ValueRange{}, sliceOp.getMixedOffsets(),
924               sliceOp.getMixedSizes(), /*tileDestOperands=*/false)
925           .front();
926   // All shapes are static and the data source is actually used. Rewrite into
927   // pad_tensor(subtensor(x)).
928   rewriter.replaceOp(sliceOp, tiledPadOp->getResults());
929   return success();
930 }
931 
932 namespace {
933 // The following are patterns for downscaling convolution ops with size-1
934 // window dimensions.
935 //
936 // Note that we'd eventually want to write such transformations in a generic
937 // way, e.g., converting to linalg.generic, removing the size-1 dimensions,
938 // and then turning back to named ops. But for now it's fine to have a few
939 // patterns matching special ops to get started.
940 
941 /// Rewrites 2-D convolution ops with size-1 window dimensions into 1-D
942 /// convolution ops.
943 struct DownscaleSizeOneWindowed2DConvolution final
944     : public OpRewritePattern<Conv2DNhwcHwcfOp> {
945   DownscaleSizeOneWindowed2DConvolution(
946       MLIRContext *context,
947       LinalgTransformationFilter filter = LinalgTransformationFilter(),
948       PatternBenefit benefit = 1)
949       : OpRewritePattern<Conv2DNhwcHwcfOp>(context, benefit),
950         filter(std::move(filter)) {}
951 
952   LogicalResult matchAndRewrite(linalg::Conv2DNhwcHwcfOp convOp,
953                                 PatternRewriter &rewriter) const override {
954     if (failed(filter.checkAndNotify(rewriter, convOp)))
955       return failure();
956     if (convOp.hasBufferSemantics())
957       return failure(); // To be implemented
958 
959     Value input = convOp.inputs().front();
960     Value kernel = convOp.inputs().back();
961     Value output = convOp.outputs().front();
962 
963     auto inputType = input.getType().dyn_cast<RankedTensorType>();
964     auto kernelType = kernel.getType().dyn_cast<RankedTensorType>();
965     auto outputType = output.getType().dyn_cast<RankedTensorType>();
966 
967     auto kernelShape = kernelType.getShape();
968     auto outputShape = outputType.getShape();
969 
970     // Only handle the case where at least one of the window dimensions is
971     // of size 1. Other cases can rely on tiling to reduce to such cases.
972     int64_t khSize = kernelShape[0], kwSize = kernelShape[1];
973     int64_t ohSize = outputShape[1], owSize = outputShape[2];
974     bool removeH = (khSize == 1 && ohSize == 1);
975     bool removeW = (kwSize == 1 && owSize == 1);
976     if (!removeH && !removeW)
977       return failure();
978 
979     // Get new shapes and types for all operands by removing the size-1
980     // dimension.
981     using RTTBuilder = RankedTensorType::Builder;
982     RankedTensorType newInputType =
983         RTTBuilder(inputType).dropDim((removeH ? 1 : 2));
984     RankedTensorType newKernelType =
985         RTTBuilder(kernelType).dropDim((removeH ? 0 : 1));
986     RankedTensorType newOutputType =
987         RTTBuilder(outputType).dropDim(removeH ? 1 : 2);
988 
989     // Rank-reduce operands.
990     Location loc = convOp.getLoc();
991     Value newInput = tensor::createCanonicalRankReducingExtractSliceOp(
992         rewriter, loc, input, newInputType);
993     Value newKernel = tensor::createCanonicalRankReducingExtractSliceOp(
994         rewriter, loc, kernel, newKernelType);
995     Value newOutput = tensor::createCanonicalRankReducingExtractSliceOp(
996         rewriter, loc, output, newOutputType);
997 
998     // Rank-reduce strides and dilations too.
999     // TODO: dropDim 1-liner helper.
1000     auto strides = llvm::to_vector<4>(convOp.strides().getValues<int64_t>());
1001     strides.erase(strides.begin() + (removeH ? 0 : 1));
1002     auto stridesAttr = rewriter.getI64VectorAttr(strides);
1003 
1004     auto dilations =
1005         llvm::to_vector<4>(convOp.dilations().getValues<int64_t>());
1006     dilations.erase(dilations.begin() + (removeH ? 0 : 1));
1007     auto dilationsAttr = rewriter.getI64VectorAttr(dilations);
1008 
1009     auto conv1DOp = rewriter.create<linalg::Conv1DNwcWcfOp>(
1010         loc, newOutputType, ValueRange{newInput, newKernel},
1011         ValueRange{newOutput}, stridesAttr, dilationsAttr);
1012 
1013     // Insert back.
1014     Value inserted = tensor::createCanonicalRankReducingInsertSliceOp(
1015         rewriter, loc, conv1DOp.getResult(0), output);
1016     rewriter.replaceOp(convOp, inserted);
1017 
1018     filter.replaceLinalgTransformationFilter(rewriter, conv1DOp);
1019     return success();
1020   };
1021 
1022 private:
1023   /// LinalgTransformMarker handles special attribute manipulations.
1024   LinalgTransformationFilter filter;
1025 };
1026 
1027 /// Rewrites 2-D depthwise convolution ops with size-1 (w, kw) or (h, kh)
1028 /// dimensions into 1-D depthwise convolution ops.
1029 struct DownscaleDepthwiseConv2DNhwcHwcOp final
1030     : public OpRewritePattern<DepthwiseConv2DNhwcHwcOp> {
1031   DownscaleDepthwiseConv2DNhwcHwcOp(
1032       MLIRContext *context,
1033       LinalgTransformationFilter filter = LinalgTransformationFilter(),
1034       PatternBenefit benefit = 1)
1035       : OpRewritePattern<DepthwiseConv2DNhwcHwcOp>(context, benefit),
1036         filter(std::move(filter)) {}
1037 
1038   LogicalResult matchAndRewrite(DepthwiseConv2DNhwcHwcOp convOp,
1039                                 PatternRewriter &rewriter) const override {
1040     if (failed(filter.checkAndNotify(rewriter, convOp)))
1041       return failure();
1042     if (convOp.hasBufferSemantics())
1043       return failure(); // To be implemented
1044 
1045     Value input = convOp.inputs().front();
1046     Value kernel = convOp.inputs().back();
1047     Value output = convOp.outputs().front();
1048 
1049     auto inputType = input.getType().dyn_cast<RankedTensorType>();
1050     auto kernelType = kernel.getType().dyn_cast<RankedTensorType>();
1051     auto outputType = output.getType().dyn_cast<RankedTensorType>();
1052 
1053     auto kernelShape = kernelType.getShape();
1054     auto outputShape = outputType.getShape();
1055 
1056     // Only handle the case where at least one of the window dimensions is
1057     // of size 1. Other cases can rely on tiling to reduce to such cases.
1058     int64_t khSize = kernelShape[0], kwSize = kernelShape[1];
1059     int64_t ohSize = outputShape[1], owSize = outputShape[2];
1060     bool removeH = (khSize == 1 && ohSize == 1);
1061     bool removeW = (kwSize == 1 && owSize == 1);
1062     if (!removeH && !removeW)
1063       return failure();
1064 
1065     // Get new shapes and types for all operands by removing the size-1
1066     // dimension.
1067     using RTTBuilder = RankedTensorType::Builder;
1068     RankedTensorType newInputType =
1069         RTTBuilder(inputType).dropDim((removeH ? 1 : 2));
1070     RankedTensorType newKernelType =
1071         RTTBuilder(kernelType).dropDim((removeH ? 0 : 1));
1072     RankedTensorType newOutputType =
1073         RTTBuilder(outputType).dropDim(removeH ? 1 : 2);
1074 
1075     // Rank-reduce operands.
1076     Location loc = convOp.getLoc();
1077     Value newInput = tensor::createCanonicalRankReducingExtractSliceOp(
1078         rewriter, loc, input, newInputType);
1079     Value newKernel = tensor::createCanonicalRankReducingExtractSliceOp(
1080         rewriter, loc, kernel, newKernelType);
1081     Value newOutput = tensor::createCanonicalRankReducingExtractSliceOp(
1082         rewriter, loc, output, newOutputType);
1083 
1084     // Rank-reduce strides and dilations too.
1085     // TODO: dropDim 1-liner helper.
1086     auto strides = llvm::to_vector<4>(convOp.strides().getValues<int64_t>());
1087     strides.erase(strides.begin() + (removeH ? 0 : 1));
1088     auto stridesAttr = rewriter.getI64VectorAttr(strides);
1089 
1090     auto dilations =
1091         llvm::to_vector<4>(convOp.dilations().getValues<int64_t>());
1092     dilations.erase(dilations.begin() + (removeH ? 0 : 1));
1093     auto dilationsAttr = rewriter.getI64VectorAttr(dilations);
1094 
1095     auto conv1DOp = rewriter.create<DepthwiseConv1DNwcWcOp>(
1096         loc, newOutputType, ValueRange{newInput, newKernel},
1097         ValueRange{newOutput}, stridesAttr, dilationsAttr);
1098 
1099     // Insert back.
1100     Value inserted = tensor::createCanonicalRankReducingInsertSliceOp(
1101         rewriter, loc, conv1DOp.getResult(0), output);
1102     rewriter.replaceOp(convOp, inserted);
1103 
1104     filter.replaceLinalgTransformationFilter(rewriter, conv1DOp);
1105     return success();
1106   };
1107 
1108 private:
1109   /// LinalgTransformMarker handles special attribute manipulations.
1110   LinalgTransformationFilter filter;
1111 };
1112 
1113 } // namespace
1114 
1115 void linalg::populateDecomposeConvolutionPatterns(
1116     RewritePatternSet &patterns, const LinalgTransformationFilter &filter,
1117     PatternBenefit benefit) {
1118   patterns.add<DownscaleSizeOneWindowed2DConvolution,
1119                DownscaleDepthwiseConv2DNhwcHwcOp>(patterns.getContext(), filter,
1120                                                   benefit);
1121 }
1122