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     : OpInterfaceRewritePattern<LinalgOp>(context, benefit),
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     : OpInterfaceRewritePattern<LinalgOp>(context, benefit),
499       filter(std::move(filter)), options(std::move(options)) {
500   this->filter.addFilter([opName](Operation *op) {
501     return success(op->getName().getStringRef() == opName);
502   });
503 }
504 
505 LogicalResult mlir::linalg::LinalgPaddingPattern::matchAndRewrite(
506     LinalgOp linalgOp, PatternRewriter &rewriter) const {
507   if (!linalgOp.hasTensorSemantics())
508     return failure();
509   if (failed(filter.checkAndNotify(rewriter, linalgOp)))
510     return failure();
511 
512   // Pad the operation.
513   LinalgOp paddedOp;
514   FailureOr<SmallVector<Value>> newResults = rewriteAsPaddedOp(
515       rewriter, linalgOp, options.paddingValueComputationFunction,
516       options.paddingNoFoldComputationFunction, paddedOp);
517   if (failed(newResults))
518     return failure();
519 
520   // Compute the desired hoisting depths.
521   SmallVector<int64_t> depths;
522   if (options.paddingHoistComputationFunction) {
523     for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands())
524       depths.push_back(options.paddingHoistComputationFunction(*opOperand));
525   }
526 
527   // Hoist the padding.
528   for (const auto &en : enumerate(depths)) {
529     OpOperand &opOperand = paddedOp->getOpOperand(en.index());
530     auto padTensorOp = opOperand.get().getDefiningOp<PadTensorOp>();
531     if (!padTensorOp || en.value() == 0)
532       continue;
533     PadTensorOp hoistedOp;
534     FailureOr<Value> newResult =
535         hoistPaddingOnTensors(padTensorOp, en.value(), hoistedOp);
536     if (failed(newResult))
537       continue;
538     rewriter.replaceOp(padTensorOp, newResult.getValue());
539   }
540 
541   // Replace the original operation to pad.
542   rewriter.replaceOp(linalgOp, newResults.getValue());
543   filter.replaceLinalgTransformationFilter(rewriter, paddedOp);
544   return success();
545 }
546 
547 /// Linalg tile and fuse tensor ops pattern.
548 mlir::linalg::LinalgTileAndFuseTensorOpsPattern::
549     LinalgTileAndFuseTensorOpsPattern(MLIRContext *context,
550                                       LinalgTilingAndFusionOptions options,
551                                       LinalgTransformationFilter filter,
552                                       PatternBenefit benefit)
553     : RewritePattern(MatchAnyOpTypeTag(), benefit, context),
554       filter(std::move(filter)), options(std::move(options)) {}
555 
556 mlir::linalg::LinalgTileAndFuseTensorOpsPattern::
557     LinalgTileAndFuseTensorOpsPattern(StringRef opName, MLIRContext *context,
558                                       LinalgTilingAndFusionOptions options,
559                                       LinalgTransformationFilter filter,
560                                       PatternBenefit benefit)
561     : RewritePattern(opName, benefit, context), filter(std::move(filter)),
562       options(std::move(options)) {}
563 
564 LogicalResult mlir::linalg::LinalgTileAndFuseTensorOpsPattern::matchAndRewrite(
565     Operation *op, PatternRewriter &rewriter) const {
566   LinalgOp rootOp = dyn_cast<LinalgOp>(op);
567   if (!rootOp)
568     return failure();
569   if (failed(filter.checkAndNotify(rewriter, op)))
570     return failure();
571 
572   // Check `tileSizes` contains a tile size for every `rootOp` loop dimension.
573   if (options.tileSizes.size() < rootOp.getNumLoops())
574     return rewriter.notifyMatchFailure(op, "expect #tile sizes >= #loops");
575 
576   // Check `tileInterchange` contains no entries or as many as `tileSizes`.
577   if (!options.tileInterchange.empty() &&
578       options.tileInterchange.size() != options.tileSizes.size())
579     return rewriter.notifyMatchFailure(
580         op, "expect the number of tile sizes and interchange dims to match");
581 
582   // Copy the `tileSizes` and `tileInterchange` prefixes needed for `rootOp`.
583   SmallVector<int64_t> rootTileSizes(options.tileSizes.begin(),
584                                      options.tileSizes.begin() +
585                                          rootOp.getNumLoops());
586   SmallVector<int64_t> rootInterchange =
587       options.tileInterchange.empty()
588           ? llvm::to_vector<6>(llvm::seq<int64_t>(0, rootOp.getNumLoops()))
589           : SmallVector<int64_t>(options.tileInterchange.begin(),
590                                  options.tileInterchange.begin() +
591                                      rootOp.getNumLoops());
592 
593   // Check `rootInterchange` is a permutation of the `rootOp` loop dimensions.
594   // It has to be a permutation since the tiling cannot tile the same loop
595   // dimension multiple times.
596   if (!isPermutation(rootInterchange))
597     return rewriter.notifyMatchFailure(
598         op, "expect the tile interchange permutes the root loops");
599 
600   // Tile `rootOp` and fuse its producers.
601   FailureOr<TileLoopNest> tileLoopNest = tileConsumerAndFuseProducers(
602       rewriter, rootOp, rootTileSizes, rootInterchange);
603   if (failed(tileLoopNest))
604     return rewriter.notifyMatchFailure(
605         op, "tileConsumerAndFuseProducers failed unexpectedly");
606 
607   // Replace all uses of the tiled loop operation.
608   rootOp->replaceAllUsesWith(tileLoopNest->getRootOpReplacementResults());
609 
610   // Apply the filter if specified.
611   for (LinalgOp linalgOp : tileLoopNest->getAllTiledAndFusedOps())
612     filter.replaceLinalgTransformationFilter(rewriter, linalgOp);
613   return failure();
614 }
615 
616 /// Linalg generic interchange pattern.
617 mlir::linalg::GenericOpInterchangePattern::GenericOpInterchangePattern(
618     MLIRContext *context, ArrayRef<unsigned> interchangeVector,
619     LinalgTransformationFilter filter, PatternBenefit benefit)
620     : OpRewritePattern(context, benefit), filter(std::move(filter)),
621       interchangeVector(interchangeVector.begin(), interchangeVector.end()) {}
622 
623 LogicalResult mlir::linalg::GenericOpInterchangePattern::matchAndRewrite(
624     GenericOp genericOp, PatternRewriter &rewriter) const {
625   if (failed(filter.checkAndNotify(rewriter, genericOp)))
626     return failure();
627 
628   FailureOr<GenericOp> transformedOp =
629       interchangeGenericOp(rewriter, genericOp, interchangeVector);
630   if (failed(transformedOp))
631     return failure();
632 
633   // New filter if specified.
634   filter.replaceLinalgTransformationFilter(rewriter, genericOp);
635   return success();
636 }
637 
638 /// Linalg generalization pattern.
639 mlir::linalg::LinalgGeneralizationPattern::LinalgGeneralizationPattern(
640     MLIRContext *context, LinalgTransformationFilter filter,
641     PatternBenefit benefit)
642     : RewritePattern(MatchAnyOpTypeTag(), benefit, context),
643       filter(std::move(filter)) {}
644 
645 mlir::linalg::LinalgGeneralizationPattern::LinalgGeneralizationPattern(
646     StringRef opName, MLIRContext *context, LinalgTransformationFilter filter,
647     PatternBenefit benefit)
648     : RewritePattern(opName, benefit, context, {}), filter(std::move(filter)) {}
649 
650 LogicalResult mlir::linalg::LinalgGeneralizationPattern::matchAndRewrite(
651     Operation *op, PatternRewriter &rewriter) const {
652   // TODO: Interface pattern.
653   LinalgOp linalgOp = dyn_cast<LinalgOp>(op);
654   if (!linalgOp)
655     return failure();
656   if (failed(filter.checkAndNotify(rewriter, op)))
657     return failure();
658   FailureOr<GenericOp> genericOp = generalizeNamedOp(rewriter, linalgOp);
659   if (failed(genericOp))
660     return failure();
661   filter.replaceLinalgTransformationFilter(rewriter, *genericOp);
662   return success();
663 }
664 
665 mlir::linalg::LinalgBasePromotionPattern::LinalgBasePromotionPattern(
666     MLIRContext *context, LinalgTransformationFilter filter,
667     LinalgPromotionOptions options, PatternBenefit benefit)
668     : RewritePattern(MatchAnyOpTypeTag(), benefit, context),
669       filter(std::move(filter)), options(std::move(options)) {}
670 
671 mlir::linalg::LinalgBasePromotionPattern::LinalgBasePromotionPattern(
672     StringRef opName, MLIRContext *context, LinalgPromotionOptions options,
673     LinalgTransformationFilter filter, PatternBenefit benefit)
674     : RewritePattern(opName, benefit, context, {}), filter(std::move(filter)),
675       options(std::move(options)) {}
676 
677 LogicalResult mlir::linalg::LinalgBasePromotionPattern::matchAndRewrite(
678     Operation *op, PatternRewriter &rewriter) const {
679   if (failed(filter.checkAndNotify(rewriter, op)))
680     return failure();
681   if (failed(promoteSubviewsPrecondition(op, options)))
682     return failure();
683 
684   // TODO: We cannot use root update here. This pattern is creating other ops,
685   // so if the promotion fails, those need to be cleaned up, which doesnt seem
686   // to be happening here. So to fail properly, we should be cloning the op and
687   // deleting the previous op. This needs more investigation.
688   rewriter.startRootUpdate(op);
689   Optional<LinalgOp> promotedOp = promoteSubViews(rewriter, op, options);
690   if (!promotedOp) {
691     rewriter.cancelRootUpdate(op);
692     return op->emitError("subview promotion failed");
693   }
694   rewriter.finalizeRootUpdate(op);
695   filter.replaceLinalgTransformationFilter(rewriter, op);
696   return success();
697 }
698 
699 mlir::linalg::LinalgBaseVectorizationPattern::LinalgBaseVectorizationPattern(
700     MLIRContext *context, LinalgTransformationFilter filter,
701     PatternBenefit benefit)
702     : RewritePattern(MatchAnyOpTypeTag(), benefit, context),
703       filter(std::move(filter)) {}
704 
705 mlir::linalg::LinalgBaseVectorizationPattern::LinalgBaseVectorizationPattern(
706     StringRef opName, MLIRContext *context, LinalgTransformationFilter filter,
707     PatternBenefit benefit)
708     : RewritePattern(opName, benefit, context, {}), filter(std::move(filter)) {}
709 
710 LogicalResult mlir::linalg::LinalgBaseVectorizationPattern::matchAndRewrite(
711     Operation *op, PatternRewriter &rewriter) const {
712   // TODO: Interface-based rewrite.
713   LinalgOp linalgOp = dyn_cast<LinalgOp>(op);
714   if (!linalgOp)
715     return failure();
716   if (failed(filter.checkAndNotify(rewriter, op)))
717     return failure();
718   return vectorize(rewriter, linalgOp);
719 }
720 
721 LogicalResult mlir::linalg::applyStagedPatterns(
722     Operation *op, ArrayRef<FrozenRewritePatternSet> stage1Patterns,
723     const FrozenRewritePatternSet &stage2Patterns,
724     function_ref<LogicalResult(Operation *)> stage3Lambda) {
725   unsigned iteration = 0;
726   (void)iteration;
727   for (const auto &patterns : stage1Patterns) {
728     LLVM_DEBUG(DBGS() << "Before 1st stage, iter: " << ++iteration << "\n"
729                       << *op);
730     if (failed(applyPatternsAndFoldGreedily(op, patterns))) {
731       LLVM_DEBUG(DBGS() << "Underlying first stage rewrite did not converge");
732       return failure();
733     }
734     LLVM_DEBUG(DBGS() << "After 1st stage, iter: " << ++iteration << "\n"
735                       << *op);
736     if (failed(applyPatternsAndFoldGreedily(op, stage2Patterns))) {
737       LLVM_DEBUG(DBGS() << "Underlying 2nd stage rewrite did not converge");
738       return failure();
739     }
740     LLVM_DEBUG(DBGS() << "After 2nd stage, iter : " << iteration << "\n"
741                       << *op);
742     if (stage3Lambda) {
743       if (failed(stage3Lambda(op)))
744         return failure();
745       LLVM_DEBUG(DBGS() << "After 3rd stage, iter : " << iteration << "\n"
746                         << *op);
747     }
748   }
749   return success();
750 }
751 
752 static SmallVector<StringRef> getNParallelLoopsAttrs(unsigned nParallelLoops) {
753   return SmallVector<StringRef>(nParallelLoops, getParallelIteratorTypeName());
754 }
755 
756 /// Rewrite a PadTensorOp into a sequence of InitTensorOp, FillOp (to
757 /// initialize with pad_val) and GenericOp (to copy contents).
758 LogicalResult PadTensorOpTransformationPattern::matchAndRewrite(
759     linalg::PadTensorOp padOp, PatternRewriter &rewriter) const {
760 
761   auto inputShapedType = padOp.source().getType().cast<ShapedType>();
762   auto resultShapedType = padOp.result().getType().cast<ShapedType>();
763 
764   // Bail on non-static shapes.
765   if (!inputShapedType.hasStaticShape())
766     return failure();
767   if (!resultShapedType.hasStaticShape())
768     return failure();
769 
770   // Only support padding with a constant for now, i.e. either:
771   //   1. A BBarg from a different block.
772   //   2. A value defined outside of the current block.
773   Block &block = padOp.region().front();
774   auto yieldOp = cast<YieldOp>(block.getTerminator());
775   assert(yieldOp.getNumOperands() == 1 && "expected single operand yield");
776   Value padValue = yieldOp.values().front();
777   Operation *definingOp = padValue.getDefiningOp();
778   if (definingOp && definingOp->getBlock() == &block)
779     return failure();
780   if (!definingOp && padValue.cast<BlockArgument>().getOwner() == &block)
781     return failure();
782 
783   // Create tensor with the padded shape
784   Location loc = padOp.getLoc();
785   SmallVector<Value> indices(resultShapedType.getRank(),
786                              rewriter.create<arith::ConstantIndexOp>(loc, 0));
787   Value initTensor = rewriter.create<InitTensorOp>(
788       loc, resultShapedType.getShape(), resultShapedType.getElementType());
789 
790   // Initialize tensor with the pad value
791   Value tmpTensor =
792       rewriter.create<linalg::FillOp>(loc, padValue, initTensor).result();
793 
794   // Copy original contents into new tensor
795   // Uses linalg.generic, but could be done with tensor.insert_slice
796   SmallVector<AffineExpr, 4> outputExprs;
797   for (unsigned i = 0; i < resultShapedType.getRank(); ++i) {
798     outputExprs.push_back(getAffineDimExpr(i, rewriter.getContext()) +
799                           padOp.static_low()[i].cast<IntegerAttr>().getInt());
800   }
801 
802   SmallVector<AffineMap, 2> transferMaps = {
803       rewriter.getMultiDimIdentityMap(inputShapedType.getRank()),
804       AffineMap::get(resultShapedType.getRank(),
805                      /*symbolCount=*/0, outputExprs, rewriter.getContext())};
806 
807   rewriter.replaceOpWithNewOp<linalg::GenericOp>(
808       padOp, resultShapedType, padOp.source(), tmpTensor, transferMaps,
809       getNParallelLoopsAttrs(resultShapedType.getRank()),
810       [&](OpBuilder &nestedBuilder, Location nestedLoc, ValueRange args) {
811         nestedBuilder.create<linalg::YieldOp>(nestedLoc, args[0]);
812       });
813 
814   return success();
815 }
816 
817 /// Filling `dest` using FillOp constant padding value if possible.
818 /// Otherwise, generate a tensor::GenerateOp.
819 Value GeneralizePadTensorOpPattern::createFillOrGenerateOp(
820     PatternRewriter &rewriter, PadTensorOp padOp, Value dest,
821     const SmallVector<Value> &dynSizes) const {
822   auto padValue = padOp.getConstantPaddingValue();
823   if (padValue)
824     return rewriter.create<FillOp>(padOp.getLoc(), padValue, dest).result();
825 
826   // Fill could not be optimized: Lower to tensor::GenerateOp with region.
827   auto generateOp = rewriter.create<tensor::GenerateOp>(
828       padOp.getLoc(), padOp.getResultType(), dynSizes);
829   // Copy region to new op.
830   BlockAndValueMapping bvm;
831   padOp.region().cloneInto(&generateOp.getRegion(), bvm);
832   // Rewrite linalg::YieldOp to tensor::YieldOp.
833   OpBuilder::InsertionGuard guard(rewriter);
834   auto yieldOp =
835       dyn_cast<linalg::YieldOp>(generateOp.getRegion().front().getTerminator());
836   assert(yieldOp && "malformed PadTensorOp: expected YieldOp terminator");
837   assert(yieldOp.values().size() == 1);
838   rewriter.setInsertionPoint(yieldOp);
839   rewriter.replaceOpWithNewOp<tensor::YieldOp>(yieldOp, yieldOp.values()[0]);
840   return generateOp;
841 }
842 
843 LogicalResult
844 GeneralizePadTensorOpPattern::matchAndRewrite(PadTensorOp padOp,
845                                               PatternRewriter &rewriter) const {
846   // Given an OpFoldResult, return an index-typed value.
847   auto getIdxValue = [&](OpFoldResult ofr) {
848     if (auto val = ofr.dyn_cast<Value>())
849       return val;
850     return rewriter
851         .create<arith::ConstantIndexOp>(
852             padOp.getLoc(), ofr.get<Attribute>().cast<IntegerAttr>().getInt())
853         .getResult();
854   };
855 
856   auto resultType = padOp.getResultType();
857   // Compute size of InitTensorOp. Any combination of static/dynamic is
858   // supported.
859   SmallVector<Value> dynSizes;
860   SmallVector<int64_t> staticSizes;
861   for (unsigned dim = 0; dim < resultType.getRank(); ++dim) {
862     if (resultType.isDynamicDim(dim)) {
863       auto srcSize = rewriter.createOrFold<tensor::DimOp>(padOp.getLoc(),
864                                                           padOp.source(), dim);
865       // Add low and high padding value.
866       auto plusLow = rewriter.createOrFold<arith::AddIOp>(
867           padOp.getLoc(), srcSize, getIdxValue(padOp.getMixedLowPad()[dim]));
868       auto plusHigh = rewriter.createOrFold<arith::AddIOp>(
869           padOp.getLoc(), plusLow, getIdxValue(padOp.getMixedHighPad()[dim]));
870       dynSizes.push_back(plusHigh);
871     }
872     staticSizes.push_back(resultType.getDimSize(dim));
873   }
874 
875   // Init tensor and fill it with padding.
876   Value init = rewriter.create<InitTensorOp>(
877       padOp.getLoc(), dynSizes, staticSizes, resultType.getElementType());
878   Value fill = createFillOrGenerateOp(rewriter, padOp, init, dynSizes);
879 
880   // Try optimize the copy of source.
881   if (optimizeCopyFn && optimizeCopyFn(rewriter, padOp, fill).succeeded())
882     return success();
883 
884   // PadTensorOps cannot be optimized. Generate a InsertSliceOp instead
885   // for copying the PadOp source.
886   auto sourceType = padOp.getSourceType();
887   // Compute size of source of PadTensorOp.
888   SmallVector<OpFoldResult> srcSizes;
889   for (unsigned dim = 0; dim < sourceType.getRank(); ++dim) {
890     if (sourceType.isDynamicDim(dim)) {
891       srcSizes.push_back(rewriter.createOrFold<tensor::DimOp>(
892           padOp.getLoc(), padOp.source(), dim));
893     } else {
894       srcSizes.push_back(rewriter.getIndexAttr(sourceType.getDimSize(dim)));
895     }
896   }
897   // Strides of InsertSliceOp are all 1.
898   SmallVector<OpFoldResult> strides(sourceType.getRank(),
899                                     rewriter.getIndexAttr(1));
900   rewriter.replaceOpWithNewOp<tensor::InsertSliceOp>(
901       padOp, padOp.source(), fill, padOp.getMixedLowPad(), srcSizes, strides);
902 
903   return success();
904 }
905 
906 LogicalResult ExtractSliceOfPadTensorSwapPattern::matchAndRewrite(
907     tensor::ExtractSliceOp sliceOp, PatternRewriter &rewriter) const {
908   auto padOp = sliceOp.source().getDefiningOp<PadTensorOp>();
909   if (!padOp)
910     return failure();
911   // Only unit stride supported.
912   if (!sliceOp.hasUnitStride())
913     return failure();
914 
915   Operation *tiledPadOp =
916       padOp
917           .getTiledImplementation(
918               rewriter, /*dest=*/ValueRange{}, sliceOp.getMixedOffsets(),
919               sliceOp.getMixedSizes(), /*tileDestOperands=*/false)
920           .front();
921   // All shapes are static and the data source is actually used. Rewrite into
922   // pad_tensor(subtensor(x)).
923   rewriter.replaceOp(sliceOp, tiledPadOp->getResults());
924   return success();
925 }
926 
927 namespace {
928 // The following are patterns for downscaling convolution ops with size-1
929 // window dimensions.
930 //
931 // Note that we'd eventually want to write such transformations in a generic
932 // way, e.g., converting to linalg.generic, removing the size-1 dimensions,
933 // and then turning back to named ops. But for now it's fine to have a few
934 // patterns matching special ops to get started.
935 
936 /// Rewrites 2-D convolution ops with size-1 window dimensions into 1-D
937 /// convolution ops.
938 struct DownscaleSizeOneWindowed2DConvolution final
939     : public OpRewritePattern<Conv2DNhwcHwcfOp> {
940   DownscaleSizeOneWindowed2DConvolution(
941       MLIRContext *context,
942       LinalgTransformationFilter filter = LinalgTransformationFilter(),
943       PatternBenefit benefit = 1)
944       : OpRewritePattern<Conv2DNhwcHwcfOp>(context, benefit),
945         filter(std::move(filter)) {}
946 
947   LogicalResult matchAndRewrite(linalg::Conv2DNhwcHwcfOp convOp,
948                                 PatternRewriter &rewriter) const override {
949     if (failed(filter.checkAndNotify(rewriter, convOp)))
950       return failure();
951     if (convOp.hasBufferSemantics())
952       return failure(); // To be implemented
953 
954     Value input = convOp.inputs().front();
955     Value kernel = convOp.inputs().back();
956     Value output = convOp.outputs().front();
957 
958     auto inputType = input.getType().dyn_cast<RankedTensorType>();
959     auto kernelType = kernel.getType().dyn_cast<RankedTensorType>();
960     auto outputType = output.getType().dyn_cast<RankedTensorType>();
961 
962     auto kernelShape = kernelType.getShape();
963     auto outputShape = outputType.getShape();
964 
965     // Only handle the case where at least one of the window dimensions is
966     // of size 1. Other cases can rely on tiling to reduce to such cases.
967     int64_t khSize = kernelShape[0], kwSize = kernelShape[1];
968     int64_t ohSize = outputShape[1], owSize = outputShape[2];
969     bool removeH = (khSize == 1 && ohSize == 1);
970     bool removeW = (kwSize == 1 && owSize == 1);
971     if (!removeH && !removeW)
972       return failure();
973 
974     // Get new shapes and types for all operands by removing the size-1
975     // dimension.
976     using RTTBuilder = RankedTensorType::Builder;
977     RankedTensorType newInputType =
978         RTTBuilder(inputType).dropDim((removeH ? 1 : 2));
979     RankedTensorType newKernelType =
980         RTTBuilder(kernelType).dropDim((removeH ? 0 : 1));
981     RankedTensorType newOutputType =
982         RTTBuilder(outputType).dropDim(removeH ? 1 : 2);
983 
984     // Rank-reduce operands.
985     Location loc = convOp.getLoc();
986     Value newInput = tensor::createCanonicalRankReducingExtractSliceOp(
987         rewriter, loc, input, newInputType);
988     Value newKernel = tensor::createCanonicalRankReducingExtractSliceOp(
989         rewriter, loc, kernel, newKernelType);
990     Value newOutput = tensor::createCanonicalRankReducingExtractSliceOp(
991         rewriter, loc, output, newOutputType);
992 
993     // Rank-reduce strides and dilations too.
994     // TODO: dropDim 1-liner helper.
995     auto strides = llvm::to_vector<4>(convOp.strides().getValues<int64_t>());
996     strides.erase(strides.begin() + (removeH ? 0 : 1));
997     auto stridesAttr = rewriter.getI64VectorAttr(strides);
998 
999     auto dilations =
1000         llvm::to_vector<4>(convOp.dilations().getValues<int64_t>());
1001     dilations.erase(dilations.begin() + (removeH ? 0 : 1));
1002     auto dilationsAttr = rewriter.getI64VectorAttr(dilations);
1003 
1004     auto conv1DOp = rewriter.create<linalg::Conv1DNwcWcfOp>(
1005         loc, newOutputType, ValueRange{newInput, newKernel},
1006         ValueRange{newOutput}, stridesAttr, dilationsAttr);
1007 
1008     // Insert back.
1009     Value inserted = tensor::createCanonicalRankReducingInsertSliceOp(
1010         rewriter, loc, conv1DOp.getResult(0), output);
1011     rewriter.replaceOp(convOp, inserted);
1012 
1013     filter.replaceLinalgTransformationFilter(rewriter, conv1DOp);
1014     return success();
1015   };
1016 
1017 private:
1018   /// LinalgTransformMarker handles special attribute manipulations.
1019   LinalgTransformationFilter filter;
1020 };
1021 
1022 /// Rewrites 2-D depthwise convolution ops with size-1 (w, kw) or (h, kh)
1023 /// dimensions into 1-D depthwise convolution ops.
1024 struct DownscaleDepthwiseConv2DNhwcHwcOp final
1025     : public OpRewritePattern<DepthwiseConv2DNhwcHwcOp> {
1026   DownscaleDepthwiseConv2DNhwcHwcOp(
1027       MLIRContext *context,
1028       LinalgTransformationFilter filter = LinalgTransformationFilter(),
1029       PatternBenefit benefit = 1)
1030       : OpRewritePattern<DepthwiseConv2DNhwcHwcOp>(context, benefit),
1031         filter(std::move(filter)) {}
1032 
1033   LogicalResult matchAndRewrite(DepthwiseConv2DNhwcHwcOp convOp,
1034                                 PatternRewriter &rewriter) const override {
1035     if (failed(filter.checkAndNotify(rewriter, convOp)))
1036       return failure();
1037     if (convOp.hasBufferSemantics())
1038       return failure(); // To be implemented
1039 
1040     Value input = convOp.inputs().front();
1041     Value kernel = convOp.inputs().back();
1042     Value output = convOp.outputs().front();
1043 
1044     auto inputType = input.getType().dyn_cast<RankedTensorType>();
1045     auto kernelType = kernel.getType().dyn_cast<RankedTensorType>();
1046     auto outputType = output.getType().dyn_cast<RankedTensorType>();
1047 
1048     auto kernelShape = kernelType.getShape();
1049     auto outputShape = outputType.getShape();
1050 
1051     // Only handle the case where at least one of the window dimensions is
1052     // of size 1. Other cases can rely on tiling to reduce to such cases.
1053     int64_t khSize = kernelShape[0], kwSize = kernelShape[1];
1054     int64_t ohSize = outputShape[1], owSize = outputShape[2];
1055     bool removeH = (khSize == 1 && ohSize == 1);
1056     bool removeW = (kwSize == 1 && owSize == 1);
1057     if (!removeH && !removeW)
1058       return failure();
1059 
1060     // Get new shapes and types for all operands by removing the size-1
1061     // dimension.
1062     using RTTBuilder = RankedTensorType::Builder;
1063     RankedTensorType newInputType =
1064         RTTBuilder(inputType).dropDim((removeH ? 1 : 2));
1065     RankedTensorType newKernelType =
1066         RTTBuilder(kernelType).dropDim((removeH ? 0 : 1));
1067     RankedTensorType newOutputType =
1068         RTTBuilder(outputType).dropDim(removeH ? 1 : 2);
1069 
1070     // Rank-reduce operands.
1071     Location loc = convOp.getLoc();
1072     Value newInput = tensor::createCanonicalRankReducingExtractSliceOp(
1073         rewriter, loc, input, newInputType);
1074     Value newKernel = tensor::createCanonicalRankReducingExtractSliceOp(
1075         rewriter, loc, kernel, newKernelType);
1076     Value newOutput = tensor::createCanonicalRankReducingExtractSliceOp(
1077         rewriter, loc, output, newOutputType);
1078 
1079     // Rank-reduce strides and dilations too.
1080     // TODO: dropDim 1-liner helper.
1081     auto strides = llvm::to_vector<4>(convOp.strides().getValues<int64_t>());
1082     strides.erase(strides.begin() + (removeH ? 0 : 1));
1083     auto stridesAttr = rewriter.getI64VectorAttr(strides);
1084 
1085     auto dilations =
1086         llvm::to_vector<4>(convOp.dilations().getValues<int64_t>());
1087     dilations.erase(dilations.begin() + (removeH ? 0 : 1));
1088     auto dilationsAttr = rewriter.getI64VectorAttr(dilations);
1089 
1090     auto conv1DOp = rewriter.create<DepthwiseConv1DNwcWcOp>(
1091         loc, newOutputType, ValueRange{newInput, newKernel},
1092         ValueRange{newOutput}, stridesAttr, dilationsAttr);
1093 
1094     // Insert back.
1095     Value inserted = tensor::createCanonicalRankReducingInsertSliceOp(
1096         rewriter, loc, conv1DOp.getResult(0), output);
1097     rewriter.replaceOp(convOp, inserted);
1098 
1099     filter.replaceLinalgTransformationFilter(rewriter, conv1DOp);
1100     return success();
1101   };
1102 
1103 private:
1104   /// LinalgTransformMarker handles special attribute manipulations.
1105   LinalgTransformationFilter filter;
1106 };
1107 
1108 } // namespace
1109 
1110 void linalg::populateDecomposeConvolutionPatterns(
1111     RewritePatternSet &patterns, const LinalgTransformationFilter &filter,
1112     PatternBenefit benefit) {
1113   patterns.add<DownscaleSizeOneWindowed2DConvolution,
1114                DownscaleDepthwiseConv2DNhwcHwcOp>(patterns.getContext(), filter,
1115                                                   benefit);
1116 }
1117