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