1 //===- Transforms.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 /// Try to peel a loop `op` and return the new result.
288 // TODO: Add support for scf.parallel and affine.for loops.
289 static SmallVector<Value, 4> peelLoop(RewriterBase &rewriter, Operation *op) {
290   return llvm::TypeSwitch<Operation *, SmallVector<Value, 4>>(op)
291       .Case<scf::ForOp>([&](scf::ForOp forOp) {
292         scf::ForOp partialIteration;
293         if (succeeded(scf::peelAndCanonicalizeForLoop(rewriter, forOp,
294                                                       partialIteration)))
295           return partialIteration->getResults();
296         assert(!partialIteration && "expected that loop was not peeled");
297         return forOp->getResults();
298       })
299       .Default([&](Operation *op) { return op->getResults(); });
300 }
301 
302 /// Try to peel a TiledLoopOp and return the new result.
303 static SmallVector<Value, 4> peelLoop(RewriterBase &rewriter,
304                                       TiledLoopOp tiledLoop, int64_t idx) {
305   assert(idx < static_cast<int64_t>(tiledLoop.iterator_types().size()) &&
306          "requested peeling of non-existing loop");
307   TiledLoopOp result;
308   if (succeeded(peelAndCanonicalizeTiledLoop(rewriter, tiledLoop, idx, result)))
309     return result->getResults();
310   assert(!result && "expected that loop was not peeled");
311   return tiledLoop->getResults();
312 }
313 
314 /// Peel loops after tiling.
315 void mlir::linalg::peelTiledLinalgOp(RewriterBase &rewriter, TiledLinalgOp &res,
316                                      ArrayRef<int64_t> peeledLoops,
317                                      LinalgTilingLoopType loopType) {
318   for (int64_t loop : peeledLoops) {
319     assert(loop < static_cast<int64_t>(res.loops.size()) &&
320            "requested peeling of non-existing loop");
321     SmallVector<Value, 4> loopResults;
322     Operation *loopOp = res.loops[loop];
323     if (loopType == LinalgTilingLoopType::TiledLoops) {
324       assert(llvm::all_of(
325                  res.loops,
326                  [&](Operation *op) { return op == res.loops.front(); }) &&
327              "expected that all loop ops are the same TiledLoopOp");
328       auto tiledLoopOp = dyn_cast<TiledLoopOp>(loopOp);
329       assert(tiledLoopOp && "expected TiledLoopOp");
330       loopResults = peelLoop(rewriter, tiledLoopOp, loop);
331     } else {
332       loopResults = peelLoop(rewriter, loopOp);
333     }
334 
335     // The result of the loop nest may change with peeling.
336     if (res.tensorResults.size() == loopOp->getNumResults() &&
337         std::equal(res.tensorResults.begin(), res.tensorResults.end(),
338                    loopOp->getResults().begin()))
339       res.tensorResults = loopResults;
340   }
341 }
342 
343 static ValueRange getTiledOpResult(TiledLinalgOp tiledOp) {
344   if (tiledOp.loops.empty())
345     return tiledOp.op.getOperation()->getResults();
346   return tiledOp.loops.front()->getResults();
347 }
348 
349 static ValueRange
350 getTiledAndFusedOpResult(TiledAndFusedLinalgOps tiledAndFusedOp) {
351   if (tiledAndFusedOp.fusedLoops.empty())
352     return tiledAndFusedOp.op.getOperation()->getResults();
353   return tiledAndFusedOp.fusedLoops.front()->getResults();
354 }
355 
356 mlir::linalg::LinalgBaseTileAndFusePattern::LinalgBaseTileAndFusePattern(
357     StringRef opName, MLIRContext *context,
358     const LinalgDependenceGraph &dependenceGraph,
359     LinalgTilingOptions tilingOptions, LinalgFusionOptions fusionOptions,
360     LinalgTransformationFilter f, LinalgTransformationFilter fusedOpMarker,
361     LinalgTransformationFilter originalOpMarker, PatternBenefit benefit)
362     : RewritePattern(opName, benefit, context, {}),
363       dependenceGraph(dependenceGraph), tilingOptions(std::move(tilingOptions)),
364       fusionOptions(std::move(fusionOptions)), filter(std::move(f)),
365       fusedOpMarker(std::move(fusedOpMarker)),
366       originalOpMarker(std::move(originalOpMarker)) {}
367 
368 LogicalResult mlir::linalg::LinalgBaseTileAndFusePattern::matchAndRewrite(
369     Operation *op, PatternRewriter &rewriter) const {
370   LinalgOp linalgOp = dyn_cast<LinalgOp>(op);
371   // TODO: remove hasIndexSemantics check once index ops are supported.
372   if (!linalgOp || linalgOp.hasIndexSemantics())
373     return failure();
374   if (failed(filter.checkAndNotify(rewriter, linalgOp)))
375     return failure();
376 
377   DenseSet<Operation *> producers;
378   producers.insert(linalgOp);
379   for (auto dependence : dependenceGraph.getDependentOperationsInto(linalgOp)) {
380     Optional<unsigned> operandNumber = dependence.getIndexingOpViewOperandNum();
381     // When looking at dependences into, indexingOp is always OpOperand. We
382     // could assert, but continue if this is not the case.
383     if (!operandNumber)
384       continue;
385     if (!fusionOptions.indicesToFuse.count(operandNumber.getValue()))
386       continue;
387     if (isa<LinalgOp>(dependence.getDependentOp()))
388       producers.insert(dependence.getDependentOp());
389   }
390 
391   SmallVector<LinalgOp, 1> fusionOps;
392   for (auto it = op->getBlock()->begin(), ie = Block::iterator(op); it != ie;
393        ++it) {
394     auto producerLinalgOp = dyn_cast<LinalgOp>(&(*it));
395     if (producerLinalgOp && producers.count(producerLinalgOp))
396       fusionOps.push_back(producerLinalgOp);
397   }
398   fusionOps.push_back(linalgOp);
399 
400   SmallVector<Value, 4> tileSizes =
401       tilingOptions.tileSizeComputationFunction(rewriter, op);
402   LinalgTilingOptions instanceTilingOptions = tilingOptions;
403   instanceTilingOptions.setTileSizes(tileSizes);
404   Optional<TiledAndFusedLinalgOps> tiledAndFusedOps = tileAndFuseLinalgOps(
405       rewriter, fusionOps, dependenceGraph, instanceTilingOptions);
406   if (!tiledAndFusedOps)
407     return failure();
408 
409   // Tile the unfused loops;
410   SmallVector<Value, 4> unfusedLoopTileSizes;
411   Value zero = rewriter.create<arith::ConstantIndexOp>(op->getLoc(), 0);
412   for (const auto &tileSize : enumerate(tileSizes)) {
413     if (tiledAndFusedOps->fusedLoopDims.count(tileSize.index()))
414       unfusedLoopTileSizes.push_back(zero);
415     else
416       unfusedLoopTileSizes.push_back(tileSize.value());
417   }
418   // Tile the loop only if there is a non-zero tile size.
419   if (unfusedLoopTileSizes.size() > linalgOp.getNumLoops())
420     unfusedLoopTileSizes.resize(linalgOp.getNumLoops());
421   if (llvm::any_of(unfusedLoopTileSizes, [](Value val) {
422         if (auto cst = val.getDefiningOp<arith::ConstantIndexOp>())
423           return cst.value() != 0;
424         return true;
425       })) {
426     LinalgTilingOptions unfusedTilingOptions = tilingOptions;
427     unfusedTilingOptions.setTileSizes(unfusedLoopTileSizes);
428     FailureOr<TiledLinalgOp> unfusedTiledOp =
429         tileLinalgOp(rewriter, tiledAndFusedOps->op, unfusedTilingOptions);
430     if (failed(unfusedTiledOp))
431       return failure();
432     rewriter.replaceOp(tiledAndFusedOps->op,
433                        getTiledOpResult(unfusedTiledOp.getValue()));
434     tiledAndFusedOps->op = unfusedTiledOp->op;
435   }
436   op->replaceAllUsesWith(getTiledAndFusedOpResult(tiledAndFusedOps.getValue()));
437 
438   filter.replaceLinalgTransformationFilter(rewriter,
439                                            tiledAndFusedOps->op.getOperation());
440   for (auto fusedOp : tiledAndFusedOps->fusedProducers) {
441     fusedOpMarker.replaceLinalgTransformationFilter(rewriter,
442                                                     fusedOp.getOperation());
443   }
444   for (auto origProducerOp : ArrayRef<LinalgOp>(fusionOps).drop_back()) {
445     originalOpMarker.replaceLinalgTransformationFilter(
446         rewriter, origProducerOp.getOperation());
447   }
448   rewriter.updateRootInPlace(op, [&]() {
449     originalOpMarker.replaceLinalgTransformationFilter(rewriter, op);
450   });
451   return success();
452 }
453 
454 /// Linalg tiling pattern.
455 mlir::linalg::LinalgTilingPattern::LinalgTilingPattern(
456     MLIRContext *context, LinalgTilingOptions options,
457     LinalgTransformationFilter f, PatternBenefit benefit)
458     : OpInterfaceRewritePattern<LinalgOp>(context, benefit),
459       filter(std::move(f)), options(std::move(options)) {}
460 
461 mlir::linalg::LinalgTilingPattern::LinalgTilingPattern(
462     StringRef opName, MLIRContext *context, LinalgTilingOptions options,
463     LinalgTransformationFilter f, PatternBenefit benefit)
464     : OpInterfaceRewritePattern<LinalgOp>(context, benefit),
465       filter(f.addOpNameFilter(opName)), options(std::move(options)) {}
466 
467 FailureOr<TiledLinalgOp>
468 mlir::linalg::LinalgTilingPattern::returningMatchAndRewrite(
469     LinalgOp op, PatternRewriter &rewriter) const {
470   if (failed(filter.checkAndNotify(rewriter, op)))
471     return failure();
472 
473   FailureOr<TiledLinalgOp> res = tileLinalgOp(rewriter, op, options);
474   if (failed(res))
475     return failure();
476 
477   // Clear filter to stop recursive pattern application.
478   // This must be done here to properly propagate to peeling branches.
479   filter.replaceLinalgTransformationFilter(rewriter, res->op);
480 
481   // Peel the loops of the TiledLinalgOp.
482   peelTiledLinalgOp(rewriter, *res, options.peeledLoops, options.loopType);
483 
484   if (res->tensorResults.empty())
485     rewriter.eraseOp(op);
486   else
487     rewriter.replaceOp(op, res->tensorResults);
488 
489   return res;
490 }
491 
492 /// Linalg padding pattern.
493 mlir::linalg::LinalgPaddingPattern::LinalgPaddingPattern(
494     MLIRContext *context, LinalgPaddingOptions options,
495     LinalgTransformationFilter f, PatternBenefit benefit)
496     : OpInterfaceRewritePattern<LinalgOp>(context, benefit),
497       filter(std::move(f)), options(std::move(options)) {}
498 
499 mlir::linalg::LinalgPaddingPattern::LinalgPaddingPattern(
500     StringRef opName, MLIRContext *context, LinalgPaddingOptions options,
501     LinalgTransformationFilter f, PatternBenefit benefit)
502     : OpInterfaceRewritePattern<LinalgOp>(context, benefit),
503       filter(f.addOpNameFilter(opName)), options(std::move(options)) {}
504 
505 FailureOr<LinalgOp>
506 mlir::linalg::LinalgPaddingPattern::returningMatchAndRewrite(
507     LinalgOp linalgOp, PatternRewriter &rewriter) const {
508   if (!linalgOp.hasTensorSemantics())
509     return failure();
510   if (failed(filter.checkAndNotify(rewriter, linalgOp)))
511     return failure();
512 
513   // Pad the operation.
514   LinalgOp paddedOp;
515   FailureOr<SmallVector<Value>> newResults = rewriteAsPaddedOp(
516       rewriter, linalgOp, options.paddingValueComputationFunction,
517       options.paddingNoFoldComputationFunction, paddedOp);
518   if (failed(newResults))
519     return failure();
520 
521   // Compute the desired hoisting depths.
522   SmallVector<int64_t> depths;
523   if (options.paddingHoistComputationFunction) {
524     for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands())
525       depths.push_back(options.paddingHoistComputationFunction(*opOperand));
526   }
527 
528   // Hoist the padding.
529   for (const auto &en : enumerate(depths)) {
530     OpOperand &opOperand = paddedOp->getOpOperand(en.index());
531     auto padTensorOp = opOperand.get().getDefiningOp<PadTensorOp>();
532     if (!padTensorOp || en.value() == 0)
533       continue;
534     PadTensorOp hoistedOp;
535     FailureOr<Value> newResult =
536         hoistPaddingOnTensors(padTensorOp, en.value(), hoistedOp);
537     if (failed(newResult))
538       continue;
539     rewriter.replaceOp(padTensorOp, newResult.getValue());
540   }
541 
542   // Replace the original operation to pad.
543   rewriter.replaceOp(linalgOp, newResults.getValue());
544   filter.replaceLinalgTransformationFilter(rewriter, paddedOp);
545   return paddedOp;
546 }
547 
548 /// Linalg tile and fuse tensor ops pattern.
549 mlir::linalg::LinalgTileAndFuseTensorOpsPattern::
550     LinalgTileAndFuseTensorOpsPattern(MLIRContext *context,
551                                       LinalgTilingAndFusionOptions options,
552                                       LinalgTransformationFilter f,
553                                       PatternBenefit benefit)
554     : RewritePattern(MatchAnyOpTypeTag(), benefit, context),
555       filter(std::move(f)), options(std::move(options)) {}
556 
557 mlir::linalg::LinalgTileAndFuseTensorOpsPattern::
558     LinalgTileAndFuseTensorOpsPattern(StringRef opName, MLIRContext *context,
559                                       LinalgTilingAndFusionOptions options,
560                                       LinalgTransformationFilter f,
561                                       PatternBenefit benefit)
562     : RewritePattern(opName, benefit, context), filter(std::move(f)),
563       options(std::move(options)) {}
564 
565 LogicalResult mlir::linalg::LinalgTileAndFuseTensorOpsPattern::matchAndRewrite(
566     Operation *op, PatternRewriter &rewriter) const {
567   LinalgOp rootOp = dyn_cast<LinalgOp>(op);
568   if (!rootOp)
569     return failure();
570   if (failed(filter.checkAndNotify(rewriter, op)))
571     return failure();
572 
573   // Check `tileSizes` contains a tile size for every `rootOp` loop dimension.
574   if (options.tileSizes.size() < rootOp.getNumLoops())
575     return rewriter.notifyMatchFailure(op, "expect #tile sizes >= #loops");
576 
577   // Check `tileInterchange` contains no entries or as many as `tileSizes`.
578   if (!options.tileInterchange.empty() &&
579       options.tileInterchange.size() != options.tileSizes.size())
580     return rewriter.notifyMatchFailure(
581         op, "expect the number of tile sizes and interchange dims to match");
582 
583   // Copy the `tileSizes` and `tileInterchange` prefixes needed for `rootOp`.
584   SmallVector<int64_t> rootTileSizes(options.tileSizes.begin(),
585                                      options.tileSizes.begin() +
586                                          rootOp.getNumLoops());
587   SmallVector<int64_t> rootInterchange =
588       options.tileInterchange.empty()
589           ? llvm::to_vector<6>(llvm::seq<int64_t>(0, rootOp.getNumLoops()))
590           : SmallVector<int64_t>(options.tileInterchange.begin(),
591                                  options.tileInterchange.begin() +
592                                      rootOp.getNumLoops());
593 
594   // Check `rootInterchange` is a permutation of the `rootOp` loop dimensions.
595   // It has to be a permutation since the tiling cannot tile the same loop
596   // dimension multiple times.
597   if (!isPermutation(rootInterchange))
598     return rewriter.notifyMatchFailure(
599         op, "expect the tile interchange permutes the root loops");
600 
601   // Tile `rootOp` and fuse its producers.
602   FailureOr<TileLoopNest> tileLoopNest = tileConsumerAndFuseProducers(
603       rewriter, rootOp, rootTileSizes, rootInterchange);
604   if (failed(tileLoopNest))
605     return rewriter.notifyMatchFailure(
606         op, "tileConsumerAndFuseProducers failed unexpectedly");
607 
608   // Replace all uses of the tiled loop operation.
609   rootOp->replaceAllUsesWith(tileLoopNest->getRootOpReplacementResults());
610 
611   // Apply the filter if specified.
612   for (LinalgOp linalgOp : tileLoopNest->getAllTiledAndFusedOps())
613     filter.replaceLinalgTransformationFilter(rewriter, linalgOp);
614   return failure();
615 }
616 
617 /// Linalg generic interchange pattern.
618 mlir::linalg::GenericOpInterchangePattern::GenericOpInterchangePattern(
619     MLIRContext *context, ArrayRef<unsigned> interchangeVector,
620     LinalgTransformationFilter f, PatternBenefit benefit)
621     : OpRewritePattern(context, benefit), filter(std::move(f)),
622       interchangeVector(interchangeVector.begin(), interchangeVector.end()) {}
623 
624 FailureOr<GenericOp>
625 mlir::linalg::GenericOpInterchangePattern::returningMatchAndRewrite(
626     GenericOp genericOp, PatternRewriter &rewriter) const {
627   if (failed(filter.checkAndNotify(rewriter, genericOp)))
628     return failure();
629 
630   FailureOr<GenericOp> transformedOp =
631       interchangeGenericOp(rewriter, genericOp, interchangeVector);
632   if (failed(transformedOp))
633     return failure();
634 
635   // New filter if specified.
636   filter.replaceLinalgTransformationFilter(rewriter, genericOp);
637   return transformedOp;
638 }
639 
640 /// Linalg generalization pattern.
641 mlir::linalg::LinalgGeneralizationPattern::LinalgGeneralizationPattern(
642     MLIRContext *context, LinalgTransformationFilter f, PatternBenefit benefit)
643     : OpInterfaceRewritePattern<LinalgOp>(context, benefit),
644       filter(std::move(f)) {}
645 
646 mlir::linalg::LinalgGeneralizationPattern::LinalgGeneralizationPattern(
647     StringRef opName, MLIRContext *context, LinalgTransformationFilter f,
648     PatternBenefit benefit)
649     : OpInterfaceRewritePattern<LinalgOp>(context, benefit),
650       filter(f.addOpNameFilter(opName)) {}
651 
652 FailureOr<GenericOp>
653 mlir::linalg::LinalgGeneralizationPattern::returningMatchAndRewrite(
654     LinalgOp linalgOp, PatternRewriter &rewriter) const {
655   if (failed(filter.checkAndNotify(rewriter, linalgOp)))
656     return failure();
657   FailureOr<GenericOp> genericOp = generalizeNamedOp(rewriter, linalgOp);
658   if (failed(genericOp))
659     return failure();
660   filter.replaceLinalgTransformationFilter(rewriter, *genericOp);
661   return genericOp;
662 }
663 
664 mlir::linalg::LinalgBasePromotionPattern::LinalgBasePromotionPattern(
665     MLIRContext *context, LinalgTransformationFilter f,
666     LinalgPromotionOptions options, PatternBenefit benefit)
667     : RewritePattern(MatchAnyOpTypeTag(), benefit, context),
668       filter(std::move(f)), options(std::move(options)) {}
669 
670 mlir::linalg::LinalgBasePromotionPattern::LinalgBasePromotionPattern(
671     StringRef opName, MLIRContext *context, LinalgPromotionOptions options,
672     LinalgTransformationFilter f, PatternBenefit benefit)
673     : RewritePattern(opName, benefit, context, {}), filter(std::move(f)),
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::LinalgVectorizationPattern::LinalgVectorizationPattern(
699     MLIRContext *context, LinalgTransformationFilter f,
700     LinalgVectorizationOptions options, PatternBenefit benefit)
701     : OpInterfaceRewritePattern<LinalgOp>(context, benefit),
702       filter(std::move(f)) {}
703 
704 mlir::linalg::LinalgVectorizationPattern::LinalgVectorizationPattern(
705     StringRef opName, MLIRContext *context, LinalgVectorizationOptions options,
706     LinalgTransformationFilter f, PatternBenefit benefit)
707     : OpInterfaceRewritePattern<LinalgOp>(context, benefit),
708       filter(f.addOpNameFilter(opName)) {}
709 
710 LogicalResult mlir::linalg::LinalgVectorizationPattern::matchAndRewrite(
711     LinalgOp linalgOp, PatternRewriter &rewriter) const {
712   if (failed(filter.checkAndNotify(rewriter, linalgOp)))
713     return failure();
714   return vectorize(rewriter, linalgOp);
715 }
716 
717 LogicalResult mlir::linalg::applyStagedPatterns(
718     Operation *op, ArrayRef<FrozenRewritePatternSet> stage1Patterns,
719     const FrozenRewritePatternSet &stage2Patterns,
720     function_ref<LogicalResult(Operation *)> stage3Lambda) {
721   unsigned iteration = 0;
722   (void)iteration;
723   for (const auto &patterns : stage1Patterns) {
724     LLVM_DEBUG(DBGS() << "Before 1st stage, iter: " << ++iteration << "\n"
725                       << *op);
726     if (failed(applyPatternsAndFoldGreedily(op, patterns))) {
727       LLVM_DEBUG(DBGS() << "Underlying first stage rewrite did not converge");
728       return failure();
729     }
730     LLVM_DEBUG(DBGS() << "After 1st stage, iter: " << ++iteration << "\n"
731                       << *op);
732     if (failed(applyPatternsAndFoldGreedily(op, stage2Patterns))) {
733       LLVM_DEBUG(DBGS() << "Underlying 2nd stage rewrite did not converge");
734       return failure();
735     }
736     LLVM_DEBUG(DBGS() << "After 2nd stage, iter : " << iteration << "\n"
737                       << *op);
738     if (stage3Lambda) {
739       if (failed(stage3Lambda(op)))
740         return failure();
741       LLVM_DEBUG(DBGS() << "After 3rd stage, iter : " << iteration << "\n"
742                         << *op);
743     }
744   }
745   return success();
746 }
747 
748 static SmallVector<StringRef> getNParallelLoopsAttrs(unsigned nParallelLoops) {
749   return SmallVector<StringRef>(nParallelLoops, getParallelIteratorTypeName());
750 }
751 
752 /// Rewrite a PadTensorOp into a sequence of InitTensorOp, FillOp (to
753 /// initialize with pad_val) and GenericOp (to copy contents).
754 LogicalResult PadTensorOpTransformationPattern::matchAndRewrite(
755     linalg::PadTensorOp padOp, PatternRewriter &rewriter) const {
756 
757   auto inputShapedType = padOp.source().getType().cast<ShapedType>();
758   auto resultShapedType = padOp.result().getType().cast<ShapedType>();
759 
760   // Bail on non-static shapes.
761   if (!inputShapedType.hasStaticShape())
762     return failure();
763   if (!resultShapedType.hasStaticShape())
764     return failure();
765 
766   // Only support padding with a constant for now, i.e. either:
767   //   1. A BBarg from a different block.
768   //   2. A value defined outside of the current block.
769   Block &block = padOp.region().front();
770   auto yieldOp = cast<YieldOp>(block.getTerminator());
771   assert(yieldOp.getNumOperands() == 1 && "expected single operand yield");
772   Value padValue = yieldOp.values().front();
773   Operation *definingOp = padValue.getDefiningOp();
774   if (definingOp && definingOp->getBlock() == &block)
775     return failure();
776   if (!definingOp && padValue.cast<BlockArgument>().getOwner() == &block)
777     return failure();
778 
779   // Create tensor with the padded shape
780   Location loc = padOp.getLoc();
781   SmallVector<Value> indices(resultShapedType.getRank(),
782                              rewriter.create<arith::ConstantIndexOp>(loc, 0));
783   Value initTensor = rewriter.create<InitTensorOp>(
784       loc, resultShapedType.getShape(), resultShapedType.getElementType());
785 
786   // Initialize tensor with the pad value
787   Value tmpTensor =
788       rewriter.create<linalg::FillOp>(loc, padValue, initTensor).result();
789 
790   // Copy original contents into new tensor
791   // Uses linalg.generic, but could be done with tensor.insert_slice
792   SmallVector<AffineExpr, 4> outputExprs;
793   for (unsigned i = 0; i < resultShapedType.getRank(); ++i) {
794     outputExprs.push_back(getAffineDimExpr(i, rewriter.getContext()) +
795                           padOp.static_low()[i].cast<IntegerAttr>().getInt());
796   }
797 
798   SmallVector<AffineMap, 2> transferMaps = {
799       rewriter.getMultiDimIdentityMap(inputShapedType.getRank()),
800       AffineMap::get(resultShapedType.getRank(),
801                      /*symbolCount=*/0, outputExprs, rewriter.getContext())};
802 
803   rewriter.replaceOpWithNewOp<linalg::GenericOp>(
804       padOp, resultShapedType, padOp.source(), tmpTensor, transferMaps,
805       getNParallelLoopsAttrs(resultShapedType.getRank()),
806       [&](OpBuilder &nestedBuilder, Location nestedLoc, ValueRange args) {
807         nestedBuilder.create<linalg::YieldOp>(nestedLoc, args[0]);
808       });
809 
810   return success();
811 }
812 
813 /// Filling `dest` using FillOp constant padding value if possible.
814 /// Otherwise, generate a tensor::GenerateOp.
815 Value GeneralizePadTensorOpPattern::createFillOrGenerateOp(
816     PatternRewriter &rewriter, PadTensorOp padOp, Value dest,
817     const SmallVector<Value> &dynSizes) const {
818   auto padValue = padOp.getConstantPaddingValue();
819   if (padValue)
820     return rewriter.create<FillOp>(padOp.getLoc(), padValue, dest).result();
821 
822   // Fill could not be optimized: Lower to tensor::GenerateOp with region.
823   auto generateOp = rewriter.create<tensor::GenerateOp>(
824       padOp.getLoc(), padOp.getResultType(), dynSizes);
825   // Copy region to new op.
826   BlockAndValueMapping bvm;
827   padOp.region().cloneInto(&generateOp.getRegion(), bvm);
828   // Rewrite linalg::YieldOp to tensor::YieldOp.
829   OpBuilder::InsertionGuard guard(rewriter);
830   auto yieldOp =
831       dyn_cast<linalg::YieldOp>(generateOp.getRegion().front().getTerminator());
832   assert(yieldOp && "malformed PadTensorOp: expected YieldOp terminator");
833   assert(yieldOp.values().size() == 1);
834   rewriter.setInsertionPoint(yieldOp);
835   rewriter.replaceOpWithNewOp<tensor::YieldOp>(yieldOp, yieldOp.values()[0]);
836   return generateOp;
837 }
838 
839 LogicalResult
840 GeneralizePadTensorOpPattern::matchAndRewrite(PadTensorOp padOp,
841                                               PatternRewriter &rewriter) const {
842   // Given an OpFoldResult, return an index-typed value.
843   auto getIdxValue = [&](OpFoldResult ofr) {
844     if (auto val = ofr.dyn_cast<Value>())
845       return val;
846     return rewriter
847         .create<arith::ConstantIndexOp>(
848             padOp.getLoc(), ofr.get<Attribute>().cast<IntegerAttr>().getInt())
849         .getResult();
850   };
851 
852   auto resultType = padOp.getResultType();
853   // Compute size of InitTensorOp. Any combination of static/dynamic is
854   // supported.
855   SmallVector<Value> dynSizes;
856   SmallVector<int64_t> staticSizes;
857   for (unsigned dim = 0; dim < resultType.getRank(); ++dim) {
858     if (resultType.isDynamicDim(dim)) {
859       auto srcSize = rewriter.createOrFold<tensor::DimOp>(padOp.getLoc(),
860                                                           padOp.source(), dim);
861       // Add low and high padding value.
862       auto plusLow = rewriter.createOrFold<arith::AddIOp>(
863           padOp.getLoc(), srcSize, getIdxValue(padOp.getMixedLowPad()[dim]));
864       auto plusHigh = rewriter.createOrFold<arith::AddIOp>(
865           padOp.getLoc(), plusLow, getIdxValue(padOp.getMixedHighPad()[dim]));
866       dynSizes.push_back(plusHigh);
867     }
868     staticSizes.push_back(resultType.getDimSize(dim));
869   }
870 
871   // Init tensor and fill it with padding.
872   Value init = rewriter.create<InitTensorOp>(
873       padOp.getLoc(), dynSizes, staticSizes, resultType.getElementType());
874   Value fill = createFillOrGenerateOp(rewriter, padOp, init, dynSizes);
875 
876   // Try optimize the copy of source.
877   if (optimizeCopyFn && optimizeCopyFn(rewriter, padOp, fill).succeeded())
878     return success();
879 
880   // PadTensorOps cannot be optimized. Generate a InsertSliceOp instead
881   // for copying the PadOp source.
882   auto sourceType = padOp.getSourceType();
883   // Compute size of source of PadTensorOp.
884   SmallVector<OpFoldResult> srcSizes;
885   for (unsigned dim = 0; dim < sourceType.getRank(); ++dim) {
886     if (sourceType.isDynamicDim(dim)) {
887       srcSizes.push_back(rewriter.createOrFold<tensor::DimOp>(
888           padOp.getLoc(), padOp.source(), dim));
889     } else {
890       srcSizes.push_back(rewriter.getIndexAttr(sourceType.getDimSize(dim)));
891     }
892   }
893   // Strides of InsertSliceOp are all 1.
894   SmallVector<OpFoldResult> strides(sourceType.getRank(),
895                                     rewriter.getIndexAttr(1));
896   rewriter.replaceOpWithNewOp<tensor::InsertSliceOp>(
897       padOp, padOp.source(), fill, padOp.getMixedLowPad(), srcSizes, strides);
898 
899   return success();
900 }
901 
902 LogicalResult ExtractSliceOfPadTensorSwapPattern::matchAndRewrite(
903     tensor::ExtractSliceOp sliceOp, PatternRewriter &rewriter) const {
904   auto padOp = sliceOp.source().getDefiningOp<PadTensorOp>();
905   if (!padOp)
906     return failure();
907   // Only unit stride supported.
908   if (!sliceOp.hasUnitStride())
909     return failure();
910 
911   Operation *tiledPadOp =
912       padOp
913           .getTiledImplementation(
914               rewriter, /*dest=*/ValueRange{}, sliceOp.getMixedOffsets(),
915               sliceOp.getMixedSizes(), /*tileDestOperands=*/false)
916           .front();
917   // All shapes are static and the data source is actually used. Rewrite into
918   // pad_tensor(subtensor(x)).
919   rewriter.replaceOp(sliceOp, tiledPadOp->getResults());
920   return success();
921 }
922 
923 namespace {
924 // The following are patterns for downscaling convolution ops with size-1
925 // window dimensions.
926 //
927 // Note that we'd eventually want to write such transformations in a generic
928 // way, e.g., converting to linalg.generic, removing the size-1 dimensions,
929 // and then turning back to named ops. But for now it's fine to have a few
930 // patterns matching special ops to get started.
931 
932 /// Rewrites 2-D convolution ops with size-1 window dimensions into 1-D
933 /// convolution ops.
934 struct DownscaleSizeOneWindowed2DConvolution final
935     : public OpRewritePattern<Conv2DNhwcHwcfOp> {
936   DownscaleSizeOneWindowed2DConvolution(
937       MLIRContext *context,
938       LinalgTransformationFilter f = LinalgTransformationFilter(),
939       PatternBenefit benefit = 1)
940       : OpRewritePattern<Conv2DNhwcHwcfOp>(context, benefit),
941         filter(std::move(f)) {}
942 
943   LogicalResult matchAndRewrite(linalg::Conv2DNhwcHwcfOp convOp,
944                                 PatternRewriter &rewriter) const override {
945     if (failed(filter.checkAndNotify(rewriter, convOp)))
946       return failure();
947     if (convOp.hasBufferSemantics())
948       return failure(); // To be implemented
949 
950     Value input = convOp.inputs().front();
951     Value kernel = convOp.inputs().back();
952     Value output = convOp.outputs().front();
953 
954     auto inputType = input.getType().dyn_cast<RankedTensorType>();
955     auto kernelType = kernel.getType().dyn_cast<RankedTensorType>();
956     auto outputType = output.getType().dyn_cast<RankedTensorType>();
957 
958     auto kernelShape = kernelType.getShape();
959     auto outputShape = outputType.getShape();
960 
961     // Only handle the case where at least one of the window dimensions is
962     // of size 1. Other cases can rely on tiling to reduce to such cases.
963     int64_t khSize = kernelShape[0], kwSize = kernelShape[1];
964     int64_t ohSize = outputShape[1], owSize = outputShape[2];
965     bool removeH = (khSize == 1 && ohSize == 1);
966     bool removeW = (kwSize == 1 && owSize == 1);
967     if (!removeH && !removeW)
968       return failure();
969 
970     // Get new shapes and types for all operands by removing the size-1
971     // dimension.
972     using RTTBuilder = RankedTensorType::Builder;
973     RankedTensorType newInputType =
974         RTTBuilder(inputType).dropDim((removeH ? 1 : 2));
975     RankedTensorType newKernelType =
976         RTTBuilder(kernelType).dropDim((removeH ? 0 : 1));
977     RankedTensorType newOutputType =
978         RTTBuilder(outputType).dropDim(removeH ? 1 : 2);
979 
980     // Rank-reduce operands.
981     Location loc = convOp.getLoc();
982     Value newInput = tensor::createCanonicalRankReducingExtractSliceOp(
983         rewriter, loc, input, newInputType);
984     Value newKernel = tensor::createCanonicalRankReducingExtractSliceOp(
985         rewriter, loc, kernel, newKernelType);
986     Value newOutput = tensor::createCanonicalRankReducingExtractSliceOp(
987         rewriter, loc, output, newOutputType);
988 
989     // Rank-reduce strides and dilations too.
990     // TODO: dropDim 1-liner helper.
991     auto strides = llvm::to_vector<4>(convOp.strides().getValues<int64_t>());
992     strides.erase(strides.begin() + (removeH ? 0 : 1));
993     auto stridesAttr = rewriter.getI64VectorAttr(strides);
994 
995     auto dilations =
996         llvm::to_vector<4>(convOp.dilations().getValues<int64_t>());
997     dilations.erase(dilations.begin() + (removeH ? 0 : 1));
998     auto dilationsAttr = rewriter.getI64VectorAttr(dilations);
999 
1000     auto conv1DOp = rewriter.create<linalg::Conv1DNwcWcfOp>(
1001         loc, newOutputType, ValueRange{newInput, newKernel},
1002         ValueRange{newOutput}, stridesAttr, dilationsAttr);
1003 
1004     // Insert back.
1005     Value inserted = tensor::createCanonicalRankReducingInsertSliceOp(
1006         rewriter, loc, conv1DOp.getResult(0), output);
1007     rewriter.replaceOp(convOp, inserted);
1008 
1009     filter.replaceLinalgTransformationFilter(rewriter, conv1DOp);
1010     return success();
1011   };
1012 
1013 private:
1014   /// LinalgTransformMarker handles special attribute manipulations.
1015   LinalgTransformationFilter filter;
1016 };
1017 
1018 /// Rewrites 2-D depthwise convolution ops with size-1 (w, kw) or (h, kh)
1019 /// dimensions into 1-D depthwise convolution ops.
1020 struct DownscaleDepthwiseConv2DNhwcHwcOp final
1021     : public OpRewritePattern<DepthwiseConv2DNhwcHwcOp> {
1022   DownscaleDepthwiseConv2DNhwcHwcOp(
1023       MLIRContext *context,
1024       LinalgTransformationFilter f = LinalgTransformationFilter(),
1025       PatternBenefit benefit = 1)
1026       : OpRewritePattern<DepthwiseConv2DNhwcHwcOp>(context, benefit),
1027         filter(std::move(f)) {}
1028 
1029   LogicalResult matchAndRewrite(DepthwiseConv2DNhwcHwcOp convOp,
1030                                 PatternRewriter &rewriter) const override {
1031     if (failed(filter.checkAndNotify(rewriter, convOp)))
1032       return failure();
1033     if (convOp.hasBufferSemantics())
1034       return failure(); // To be implemented
1035 
1036     Value input = convOp.inputs().front();
1037     Value kernel = convOp.inputs().back();
1038     Value output = convOp.outputs().front();
1039 
1040     auto inputType = input.getType().dyn_cast<RankedTensorType>();
1041     auto kernelType = kernel.getType().dyn_cast<RankedTensorType>();
1042     auto outputType = output.getType().dyn_cast<RankedTensorType>();
1043 
1044     auto kernelShape = kernelType.getShape();
1045     auto outputShape = outputType.getShape();
1046 
1047     // Only handle the case where at least one of the window dimensions is
1048     // of size 1. Other cases can rely on tiling to reduce to such cases.
1049     int64_t khSize = kernelShape[0], kwSize = kernelShape[1];
1050     int64_t ohSize = outputShape[1], owSize = outputShape[2];
1051     bool removeH = (khSize == 1 && ohSize == 1);
1052     bool removeW = (kwSize == 1 && owSize == 1);
1053     if (!removeH && !removeW)
1054       return failure();
1055 
1056     // Get new shapes and types for all operands by removing the size-1
1057     // dimension.
1058     using RTTBuilder = RankedTensorType::Builder;
1059     RankedTensorType newInputType =
1060         RTTBuilder(inputType).dropDim((removeH ? 1 : 2));
1061     RankedTensorType newKernelType =
1062         RTTBuilder(kernelType).dropDim((removeH ? 0 : 1));
1063     RankedTensorType newOutputType =
1064         RTTBuilder(outputType).dropDim(removeH ? 1 : 2);
1065 
1066     // Rank-reduce operands.
1067     Location loc = convOp.getLoc();
1068     Value newInput = tensor::createCanonicalRankReducingExtractSliceOp(
1069         rewriter, loc, input, newInputType);
1070     Value newKernel = tensor::createCanonicalRankReducingExtractSliceOp(
1071         rewriter, loc, kernel, newKernelType);
1072     Value newOutput = tensor::createCanonicalRankReducingExtractSliceOp(
1073         rewriter, loc, output, newOutputType);
1074 
1075     // Rank-reduce strides and dilations too.
1076     // TODO: dropDim 1-liner helper.
1077     auto strides = llvm::to_vector<4>(convOp.strides().getValues<int64_t>());
1078     strides.erase(strides.begin() + (removeH ? 0 : 1));
1079     auto stridesAttr = rewriter.getI64VectorAttr(strides);
1080 
1081     auto dilations =
1082         llvm::to_vector<4>(convOp.dilations().getValues<int64_t>());
1083     dilations.erase(dilations.begin() + (removeH ? 0 : 1));
1084     auto dilationsAttr = rewriter.getI64VectorAttr(dilations);
1085 
1086     auto conv1DOp = rewriter.create<DepthwiseConv1DNwcWcOp>(
1087         loc, newOutputType, ValueRange{newInput, newKernel},
1088         ValueRange{newOutput}, stridesAttr, dilationsAttr);
1089 
1090     // Insert back.
1091     Value inserted = tensor::createCanonicalRankReducingInsertSliceOp(
1092         rewriter, loc, conv1DOp.getResult(0), output);
1093     rewriter.replaceOp(convOp, inserted);
1094 
1095     filter.replaceLinalgTransformationFilter(rewriter, conv1DOp);
1096     return success();
1097   };
1098 
1099 private:
1100   /// LinalgTransformMarker handles special attribute manipulations.
1101   LinalgTransformationFilter filter;
1102 };
1103 
1104 } // namespace
1105 
1106 void linalg::populateDecomposeConvolutionPatterns(
1107     RewritePatternSet &patterns, const LinalgTransformationFilter &filter,
1108     PatternBenefit benefit) {
1109   patterns.add<DownscaleSizeOneWindowed2DConvolution,
1110                DownscaleDepthwiseConv2DNhwcHwcOp>(patterns.getContext(), filter,
1111                                                   benefit);
1112 }
1113