MLIR  20.0.0git
Transforms.cpp
Go to the documentation of this file.
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 
28 #include "mlir/IR/AffineExpr.h"
29 #include "mlir/IR/Matchers.h"
30 #include "mlir/Pass/Pass.h"
31 #include "mlir/Support/LLVM.h"
33 #include "llvm/ADT/ScopeExit.h"
34 #include "llvm/ADT/TypeSwitch.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <type_traits>
38 #include <utility>
39 
40 #define DEBUG_TYPE "linalg-transforms"
41 
42 using namespace mlir;
43 using namespace mlir::linalg;
44 
45 #define DBGS() (llvm::dbgs() << "[" DEBUG_TYPE << "]: ")
46 #define DBGSNL() (llvm::dbgs() << "\n")
47 
48 //===----------------------------------------------------------------------===//
49 // Transformations exposed as functional-style API calls.
50 //===----------------------------------------------------------------------===//
51 
52 //===----------------------------------------------------------------------===//
53 // peelLoop transformation.
54 //===----------------------------------------------------------------------===//
55 
56 /// Try to peel and canonicalize loop `op` and return the new result.
57 /// Also applies affine_min/max bounds simplification on the fly where relevant.
58 // TODO: Add support for scf.parallel and affine.for loops.
60  Operation *op) {
62  .Case<scf::ForOp>([&](scf::ForOp forOp) {
63  scf::ForOp partialIteration;
64  if (succeeded(scf::peelForLoopAndSimplifyBounds(rewriter, forOp,
65  partialIteration)))
66  return partialIteration->getResults();
67  assert(!partialIteration && "expected that loop was not peeled");
68  return forOp->getResults();
69  })
70  .Default([&](Operation *op) { return op->getResults(); });
71 }
72 
73 /// Peel 'loops' and applies affine_min/max bounds simplification on the fly
74 /// where relevant.
76  ArrayRef<scf::ForOp> loops) {
77  for (auto loopOp : loops)
78  peelLoop(rewriter, loopOp);
79 }
80 
81 //===----------------------------------------------------------------------===//
82 // pack transformation.
83 //===----------------------------------------------------------------------===//
84 
85 #ifndef NDEBUG
86 /// Return true if `map` has 0 or 1 result function of AffineDimExpr(dim).
87 static bool hasAtMostOneResultFunctionOfDim(AffineMap map, int64_t dim) {
88  bool found = false;
89  for (AffineExpr e : map.getResults()) {
90  if (!e.isFunctionOfDim(dim))
91  continue;
92  if (found)
93  return false;
94  found = true;
95  }
96  return true;
97 }
98 #endif // NDEBUG
99 
100 /// Return the index of the first result of `map` that is a function of
101 /// AffineDimExpr(dim), std::nullopt otherwise.
102 static std::optional<int64_t> getFirstResultIndexFunctionOf(AffineMap map,
103  int64_t dim) {
104  for (int64_t i = 0, e = map.getNumResults(); i < e; ++i) {
105  AffineExpr expr = map.getResult(i);
106  if (!expr.isFunctionOfDim(dim))
107  continue;
108  return i;
109  }
110  return std::nullopt;
111 }
112 
113 /// Perform one step of packing of a LinalgOp's metadata along `dim` into the
114 /// `newDim` at `iteratorTypes.size()` by:
115 /// 1. Appending `iteratorTypes[newDim]`, equal to `iteratorTypes[dim]`.
116 /// 2. Appending a `newDim` to the domain of every indexing map.
117 /// 3. For each operand (i.e. for each map in `indexingMaps`), perform packing
118 /// by potentially adding a `newDim` result to `map`.
119 /// The preserved invariant is that `iteratorTypes.size()` is always equal to
120 /// `map.getNumDims()` for every map in `indexingMaps`.
121 ///
122 /// Update `indexingMaps` and `iteratorTypes` inplace as one step of the update.
123 /// Return a vector that records the optional packing for each operand.
124 /// Return failure if the packed indexing cannot be represented with a LinalgOp.
125 ///
126 /// Further details:
127 /// ================
128 /// The current implementation of packing (i.e. data tiling) consists of
129 /// rewriting a linearized strip-mined form into a higher-dimensional access.
130 /// e.g. consider an access `A[I][f(j, k, l)]` and packing by 4; we rewrite
131 /// `I` into `4 * i + ii`, where `0 <= ii < 4`.
132 /// The access is further rewritten as `A[i][f(j, k, l)][ii]`.
133 ///
134 /// This rewrite into higher dimensional access is not possible for general
135 /// AffineExpr in Linalg atm, it is restricted to an AffineDimExpr:
136 /// e.g. consider an access `A[I + J][f(j, k, l)]` and packing by 4; we
137 /// rewrite `I + J` into `4 * i + ii + J`, where `0 <= ii < 4`.
138 /// The rewrite of the access would be a form not representable in Linalg:
139 /// `A[i + (ii + J) / 4][f(j, k, l)][(ii + J) % 4]`.
140 /// Note however that as `J` and `ii` iterate, the accesses do not have a
141 /// particular alignment, so packing does not achieve alignment in this case
142 ///
143 /// In the future, we may want to consider a mixed-form that allows some
144 /// alignment in the presence of multiple accesses:
145 /// `A[I][f(j, k, l)]` and `B[I + J][f(j, k, l)]`
146 /// And would rewrite accesses as:
147 /// `A[i][f(j, k, l)][ii]` and `B[4 * i + ii + J][f(j, k, l)]`
148 static FailureOr<SmallVector<std::optional<int64_t>>>
151  int64_t dim) {
152  int64_t newDim = iteratorTypes.size();
153  iteratorTypes.push_back(iteratorTypes[dim]);
154 
155  SmallVector<std::optional<int64_t>> packedDimPerIndexingMap(
156  indexingMaps.size(), std::nullopt);
157  SmallVector<AffineMap> newMaps;
158  for (int64_t operandIdx = 0, e = indexingMaps.size(); operandIdx < e;
159  ++operandIdx) {
160  AffineMap map = indexingMaps[operandIdx];
161 
162  // Add the `newDim` to map whatever the case.
163  assert(map.getNumDims() == newDim && "num dims invariant violation");
164  map = map.shiftDims(1, newDim);
165 
166  // Get the at-most-1 index of the result that is a function of `dim`.
167  // If we can find one, we insert `AffineDimExpr(newDim)` to the map, which
168  // logically chunks dimension `dim` into `K * dim + newDim`, where the
169  // packing factor `K` is specified separately.
170  assert(hasAtMostOneResultFunctionOfDim(map, dim) &&
171  "num results invariant violation");
172  auto maybeOperandDimensionToPack = getFirstResultIndexFunctionOf(map, dim);
173  if (!maybeOperandDimensionToPack.has_value()) {
174  newMaps.push_back(map);
175  continue;
176  }
177 
178  // We can only pack AffineDimExpr atm.
179  if (!isa<AffineDimExpr>(map.getResult(maybeOperandDimensionToPack.value())))
180  return failure();
181 
182  // Add `newDim` to the results of the map.
183  map = map.insertResult(Builder(map.getContext()).getAffineDimExpr(newDim),
184  map.getNumResults());
185  newMaps.push_back(map);
186 
187  // Record the that `operandIdx` is packed.
188  packedDimPerIndexingMap[operandIdx] = maybeOperandDimensionToPack;
189  }
190  indexingMaps = newMaps;
191 
192  return packedDimPerIndexingMap;
193 }
194 
195 namespace {
196 
197 /// Helper struct to encode packing along one dimension of a LinalgOp.
198 struct PackedOperandsDim {
199  OpFoldResult packedSize;
200  SmallVector<std::optional<int64_t>> packedDimForEachOperand;
201 };
202 
203 /// Helper struct to encode packing along all dimensions of a LinalgOp.
204 struct PackedOperandsDimList {
205  void pushBack(PackedOperandsDim &&packedOperandsDims) {
206  spec.emplace_back(packedOperandsDims);
207  }
208  /// Return all the dims that have been packed for operand @ `operandPos`.
209  SmallVector<int64_t> extractPackedDimsForOperand(int64_t operandPos);
210  /// Return all the pack sizes by which an operand @ `operandPos` is packed.
211  SmallVector<OpFoldResult> extractPackSizesForOperand(int64_t operandPos);
212 
213 private:
215 };
216 
217 } // namespace
218 
219 FailureOr<LowerPackResult> linalg::lowerPack(RewriterBase &rewriter,
220  tensor::PackOp packOp) {
221  // 1. Filter out NYI cases.
222  auto packedTensorType =
223  cast<RankedTensorType>(packOp->getResultTypes().front());
224  if (llvm::any_of(packOp.getStaticInnerTiles(),
225  [](int64_t size) { return ShapedType::isDynamic(size); })) {
226  return rewriter.notifyMatchFailure(
227  packOp,
228  "non-static shape NYI, needs a more powerful tensor.expand_shape op");
229  }
230 
231  Location loc = packOp->getLoc();
232  OpBuilder::InsertionGuard g(rewriter);
233  rewriter.setInsertionPoint(packOp);
234 
235  // 2. Compute the permutation vector to shuffle packed shape into the shape
236  // before any outer or inner permutations have been applied.
237  PackingMetadata packingMetadata = computePackingMetadata(
238  packedTensorType.getRank(), packOp.getInnerDimsPos());
239  SmallVector<int64_t> packedToStripMinedShapePerm =
241 
242  // 3. Compute the stripMinedShape: this is the packed shape before any outer
243  // or inner permutations have been applied.
244  SmallVector<int64_t> stripMinedShape(packedTensorType.getShape());
245  applyPermutationToVector(stripMinedShape, packedToStripMinedShapePerm);
246 
247  // 4. Pad the source of packOp to a shape we can expand into stripMinedShape.
248  SmallVector<OpFoldResult> lows(packOp.getSourceRank(),
249  rewriter.getIndexAttr(0));
250  SmallVector<OpFoldResult> highs(packOp.getSourceRank(),
251  rewriter.getIndexAttr(0));
252  for (auto [pos, innerSize] :
253  llvm::zip_equal(packOp.getInnerDimsPos(), packOp.getMixedTiles())) {
254  int outerPos =
255  packedToStripMinedShapePerm[packingMetadata.outerPositions[pos]];
256  OpFoldResult origSize =
257  tensor::getMixedSize(rewriter, loc, packOp.getSource(), pos);
258  OpFoldResult outerSize =
259  tensor::getMixedSize(rewriter, loc, packOp.getDest(), outerPos);
260  AffineExpr s0, d0, d1;
261  bindDims(rewriter.getContext(), d0, d1);
262  bindSymbols(rewriter.getContext(), s0);
263  auto map = AffineMap::get(/*dimCount=*/2, /*symbolCount=*/1, d0 * s0 - d1);
265  rewriter, loc, map, {outerSize, origSize, innerSize});
266  }
267  RankedTensorType collapsed = tensor::CollapseShapeOp::inferCollapsedType(
268  RankedTensorType::Builder(packedTensorType).setShape(stripMinedShape),
269  packingMetadata.reassociations);
270  Value paddingValue = packOp.getPaddingValue();
271  if (!paddingValue) {
272  paddingValue = rewriter.create<arith::ConstantOp>(
273  loc, rewriter.getZeroAttr(getElementTypeOrSelf(collapsed)));
274  }
275  auto padOp =
276  rewriter.create<tensor::PadOp>(loc, collapsed, packOp.getSource(), lows,
277  highs, paddingValue, /*nofold=*/false);
278 
279  LLVM_DEBUG(
280  DBGSNL(); DBGSNL(); llvm::interleaveComma(packingMetadata.insertPositions,
281  DBGS() << "insertPositions: ");
282  DBGSNL(); llvm::interleaveComma(packingMetadata.outerPositions,
283  DBGS() << "outerPositions: ");
284  DBGSNL(); llvm::interleaveComma(packedTensorType.getShape(),
285  DBGS() << "packedShape: ");
286  DBGSNL();
287  llvm::interleaveComma(packedToStripMinedShapePerm,
288  DBGS() << "packedToStripMinedShapePerm: ");
289  DBGSNL(); llvm::interleaveComma(
290  packingMetadata.reassociations, DBGS() << "reassociations: ",
291  [&](ReassociationIndices ri) {
292  llvm::interleaveComma(ri, llvm::dbgs() << "|");
293  });
294  DBGSNL();
295  llvm::interleaveComma(stripMinedShape, DBGS() << "stripMinedShape: ");
296  DBGSNL(); DBGS() << "collapsed type: " << collapsed; DBGSNL(););
297 
298  if (packOp.isLikePad()) {
299  // Pack ops which operate as simple pads may not produce legal
300  // tensor.insert_slice operations when the packed type does not rank reduce
301  // to the padded type.
302  SliceVerificationResult rankReduces =
303  isRankReducedType(packedTensorType, padOp.getResultType());
304 
305  if (rankReduces == SliceVerificationResult::Success) {
306  // This pack is just a plain pad.
307  // Just insert the pad in the higher ranked tensor.
308  // Offsets.
309  SmallVector<OpFoldResult> zeros(packOp.getDestRank(),
310  rewriter.getIndexAttr(0));
311  // Strides.
312  SmallVector<OpFoldResult> ones(packOp.getDestRank(),
313  rewriter.getIndexAttr(1));
315  tensor::getMixedSizes(rewriter, loc, packOp.getDest());
316 
317  auto insertSliceOp = rewriter.create<tensor::InsertSliceOp>(
318  loc, /*source=*/padOp, /*dest=*/packOp.getDest(),
319  /*offsets=*/zeros, sizes, /*strides=*/ones);
320 
321  LLVM_DEBUG(DBGS() << "insert_slice op: " << insertSliceOp; DBGSNL(););
322 
323  rewriter.replaceOp(packOp, insertSliceOp->getResults());
324 
325  return LowerPackResult{padOp, /*reshapeOp=*/nullptr,
326  /*transposeOp=*/nullptr};
327  }
328  }
329 
330  // 5. Expand from the padded result to the stripMinedShape.
331  auto expandShapeResultType =
332  RankedTensorType::Builder(packedTensorType).setShape(stripMinedShape);
333  auto reshapeOp = rewriter.create<tensor::ExpandShapeOp>(
334  loc, expandShapeResultType, padOp.getResult(),
335  packingMetadata.reassociations);
336 
337  // 6. Transpose stripMinedShape to packedShape.
338  SmallVector<int64_t> transpPerm =
339  invertPermutationVector(packedToStripMinedShapePerm);
340  auto transposeOp = rewriter.create<linalg::TransposeOp>(
341  loc, reshapeOp.getResult(), packOp.getDest(), transpPerm);
342 
343  LLVM_DEBUG(DBGSNL(); DBGSNL(); DBGSNL();
344  DBGS() << "reshape op: " << reshapeOp; DBGSNL();
345  llvm::interleaveComma(transpPerm, DBGS() << "transpPerm: ");
346  DBGSNL(); DBGS() << "transpose op: " << transposeOp; DBGSNL(););
347 
348  // 7. Replace packOp by transposeOp.
349  rewriter.replaceOp(packOp, transposeOp->getResults());
350 
351  return LowerPackResult{padOp, reshapeOp, transposeOp};
352 }
353 
354 FailureOr<LowerUnPackOpResult> linalg::lowerUnPack(RewriterBase &rewriter,
355  tensor::UnPackOp unPackOp) {
356  Location loc = unPackOp->getLoc();
357  OpBuilder::InsertionGuard g(rewriter);
358  rewriter.setInsertionPoint(unPackOp);
359 
360  RankedTensorType packedTensorType = unPackOp.getSourceType();
361  int64_t packedRank = packedTensorType.getRank();
362 
363  OpFoldResult zero = rewriter.getIndexAttr(0), one = rewriter.getIndexAttr(1);
364  auto destTensorType = cast<RankedTensorType>(unPackOp.getDest().getType());
365  if (unPackOp.isLikeUnPad()) {
366  // This unpack is just a plain unpad.
367  // Just extract the slice from the higher ranked tensor.
368  ArrayRef<int64_t> destShape = destTensorType.getShape();
369  // The inner dimensions stay the same as the destination tensor, but the
370  // outer ones are additional 1s.
371  SmallVector<OpFoldResult> sizes(packedRank - destShape.size(), one);
372  sizes.append(tensor::getMixedSizes(rewriter, loc, unPackOp.getDest()));
373 
374  auto extractSliceOp = rewriter.create<tensor::ExtractSliceOp>(
375  loc, destTensorType, unPackOp.getSource(),
376  SmallVector<OpFoldResult>(packedRank, zero), sizes,
377  SmallVector<OpFoldResult>(packedRank, one));
378 
379  rewriter.replaceOp(unPackOp, extractSliceOp->getResults());
380 
381  return LowerUnPackOpResult{/*emptyOp=*/nullptr, /*transposeOp=*/nullptr,
382  /*reshapeOp=*/nullptr, extractSliceOp};
383  }
384 
385  // 1. Compute the permutation vector to shuffle packed shape into the shape
386  // before any outer or inner permutations have been applied.
387  PackingMetadata packingMetadata;
388  SmallVector<int64_t> packedToStripMinedShapePerm =
389  tensor::getUnPackInverseSrcPerm(unPackOp, packingMetadata);
390 
391  // 2. Compute the stripMinedShape: this is the packed shape without outer and
392  // inner permutations.
393  SmallVector<int64_t> stripMinedShape(packedTensorType.getShape());
394  applyPermutationToVector(stripMinedShape, packedToStripMinedShapePerm);
395 
396  // 3. Transpose packedShape to stripMinedShape.
397  RankedTensorType stripMinedTensorType =
398  RankedTensorType::Builder(packedTensorType).setShape(stripMinedShape);
399  RankedTensorType collapsedType = tensor::CollapseShapeOp::inferCollapsedType(
400  stripMinedTensorType, packingMetadata.reassociations);
401 
402  // Get dynamic dims from input tensor based on packedToStripMinedShapePerm
403  // permutation.
405  tensor::getMixedSizes(rewriter, loc, unPackOp.getSource());
406  applyPermutationToVector(dims, packedToStripMinedShapePerm);
407  auto emptyOp = rewriter.create<tensor::EmptyOp>(
408  loc, dims, stripMinedTensorType.getElementType());
409  auto transposeOp = rewriter.create<linalg::TransposeOp>(
410  loc, unPackOp.getSource(), emptyOp, packedToStripMinedShapePerm);
411 
412  LLVM_DEBUG(
413  DBGSNL(); DBGSNL(); llvm::interleaveComma(packingMetadata.insertPositions,
414  DBGS() << "insertPositions: ");
415  DBGSNL(); llvm::interleaveComma(packedTensorType.getShape(),
416  DBGS() << "packedShape: ");
417  DBGSNL();
418  llvm::interleaveComma(packedToStripMinedShapePerm,
419  DBGS() << "packedToStripMinedShapePerm: ");
420  DBGSNL(); llvm::interleaveComma(
421  packingMetadata.reassociations, DBGS() << "reassociations: ",
422  [&](ReassociationIndices ri) {
423  llvm::interleaveComma(ri, llvm::dbgs() << "|");
424  });
425  DBGSNL();
426  llvm::interleaveComma(stripMinedShape, DBGS() << "stripMinedShape: ");
427  DBGSNL(); DBGS() << "collapsed type: " << collapsedType; DBGSNL(););
428 
429  // 4. Collapse from the stripMinedShape to the padded result.
430  auto reshapeOp = rewriter.create<tensor::CollapseShapeOp>(
431  loc, collapsedType, transposeOp->getResult(0),
432  packingMetadata.reassociations);
433 
434  // 5. ExtractSlice.
435  int64_t destRank = destTensorType.getRank();
436  auto extractSliceOp = rewriter.create<tensor::ExtractSliceOp>(
437  loc, destTensorType, reshapeOp->getResult(0),
438  SmallVector<OpFoldResult>(destRank, zero),
439  tensor::getMixedSizes(rewriter, loc, unPackOp.getDest()),
440  SmallVector<OpFoldResult>(destRank, one));
441 
442  // 6. Inject a copy to preserve DPS.
443  auto copyOp = rewriter.create<linalg::CopyOp>(
444  loc, extractSliceOp->getResult(0), unPackOp.getDest());
445 
446  // 7. Replace unPackOp by copyOp.
447  rewriter.replaceOp(unPackOp, copyOp->getResults());
448 
449  return LowerUnPackOpResult{emptyOp, transposeOp, reshapeOp, extractSliceOp};
450 }
451 
453 PackedOperandsDimList::extractPackedDimsForOperand(int64_t operandPos) {
455  for (auto &i : spec) {
456  if (!i.packedDimForEachOperand[operandPos].has_value())
457  continue;
458  res.push_back(i.packedDimForEachOperand[operandPos].value());
459  }
460  return res;
461 }
462 
464 PackedOperandsDimList::extractPackSizesForOperand(int64_t operandPos) {
466  for (auto &i : spec) {
467  if (!i.packedDimForEachOperand[operandPos].has_value())
468  continue;
469  res.push_back(i.packedSize);
470  }
471  return res;
472 }
473 
474 /// Implement packing of a single LinalgOp by performing packing by
475 /// `packedSizes`. There must be one packedSizes entry per `linalgOp` iterator.
476 /// Return the packed Linalg op on success, failure otherwise.
477 FailureOr<PackResult> linalg::pack(RewriterBase &rewriter,
478  linalg::LinalgOp linalgOp,
479  ArrayRef<OpFoldResult> packedSizes) {
480  if (packedSizes.size() != linalgOp.getNumLoops()) {
481  return rewriter.notifyMatchFailure(linalgOp,
482  "incorrect number of pack sizes");
483  }
484 
485  Location loc = linalgOp->getLoc();
486  SmallVector<AffineMap> indexingMaps = linalgOp.getIndexingMapsArray();
487  SmallVector<utils::IteratorType> iteratorTypes =
488  linalgOp.getIteratorTypesArray();
489  LLVM_DEBUG(DBGS() << "Start packing: " << linalgOp << "\n";
490  llvm::interleaveComma(indexingMaps, DBGS() << "maps: "); DBGSNL();
491  llvm::interleaveComma(iteratorTypes, DBGS() << "iterators: ");
492  DBGSNL(););
493 
496  // Step 1. Pack each dim of the LinalgOp metadata by packedSizes[i].
497  PackedOperandsDimList listOfPackedOperandsDim;
498  for (int64_t i = 0, e = packedSizes.size(); i < e; ++i) {
499  std::optional<int64_t> maybeConstant = getConstantIntValue(packedSizes[i]);
500  // Skip tile sizes explicitly set to 0.
501  if (maybeConstant.has_value() && maybeConstant.value() == 0)
502  continue;
503 
504  PackedOperandsDim packedOperandsDims;
505  packedOperandsDims.packedSize = packedSizes[i];
506  FailureOr<SmallVector<std::optional<int64_t>>>
507  maybePackedDimForEachOperand =
508  packLinalgMetadataOnce(indexingMaps, iteratorTypes, i);
509  if (failed(maybePackedDimForEachOperand))
510  return failure();
511  packedOperandsDims.packedDimForEachOperand = *maybePackedDimForEachOperand;
512  listOfPackedOperandsDim.pushBack(std::move(packedOperandsDims));
513 
514  LLVM_DEBUG(
515  DBGS() << "++++ After pack size #" << i << ": " << packedSizes[i]
516  << "\n";
517  llvm::interleaveComma(indexingMaps, DBGS() << "maps: "); DBGSNL();
518  llvm::interleaveComma(iteratorTypes, DBGS() << "iterators: "); DBGSNL();
519  llvm::interleaveComma(packedOperandsDims.packedDimForEachOperand,
520  DBGS() << "packedDimForEachOperand: ");
521  DBGSNL(););
522  }
523 
524  // Step 2. Propagate packing to all LinalgOp operands.
525  SmallVector<Value> inputsAndInits, results;
526  SmallVector<OpOperand *> initOperands = llvm::to_vector(llvm::map_range(
527  linalgOp.getDpsInitsMutable(), [](OpOperand &o) { return &o; }));
528  SmallVector<OpOperand *> inputOperands = linalgOp.getDpsInputOperands();
529  for (const auto &operandsList : {inputOperands, initOperands}) {
530  for (OpOperand *opOperand : operandsList) {
531  int64_t pos = opOperand->getOperandNumber();
532  Value operand = opOperand->get();
533  SmallVector<int64_t> innerPos =
534  listOfPackedOperandsDim.extractPackedDimsForOperand(pos);
535  SmallVector<OpFoldResult> innerPackSizes =
536  listOfPackedOperandsDim.extractPackSizesForOperand(pos);
537  LLVM_DEBUG(
538  DBGS() << "operand: " << operand << "\n";
539  llvm::interleaveComma(innerPos, DBGS() << "innerPos: "); DBGSNL();
540  llvm::interleaveComma(innerPackSizes, DBGS() << "innerPackSizes: ");
541  DBGSNL(););
542  if (innerPackSizes.empty()) {
543  inputsAndInits.push_back(operand);
544  continue;
545  }
546  Value dest = tensor::PackOp::createDestinationTensor(
547  rewriter, loc, operand, innerPackSizes, innerPos,
548  /*outerDimsPerm=*/{});
549  ShapedType operandType = cast<ShapedType>(operand.getType());
550  bool areConstantTiles =
551  llvm::all_of(innerPackSizes, [](OpFoldResult tile) {
552  return getConstantIntValue(tile).has_value();
553  });
554  if (areConstantTiles && operandType.hasStaticShape() &&
555  !tensor::PackOp::requirePaddingValue(
556  operandType.getShape(), innerPos,
557  cast<ShapedType>(dest.getType()).getShape(), {},
558  innerPackSizes)) {
559  packOps.push_back(rewriter.create<tensor::PackOp>(
560  loc, operand, dest, innerPos, innerPackSizes));
561  } else {
562  // TODO: value of the padding attribute should be determined by
563  // consumers.
564  auto zeroAttr =
565  rewriter.getZeroAttr(getElementTypeOrSelf(dest.getType()));
566  Value zero = rewriter.create<arith::ConstantOp>(loc, zeroAttr);
567  packOps.push_back(rewriter.create<tensor::PackOp>(
568  loc, operand, dest, innerPos, innerPackSizes, zero));
569  }
570  inputsAndInits.push_back(packOps.back());
571  }
572  }
573 
574  // Step 3. Build the packed op, use the type of `inits` as result types.
575  ValueRange inputs =
576  ValueRange{inputsAndInits}.take_front(linalgOp.getNumDpsInputs());
577  ValueRange inits =
578  ValueRange{inputsAndInits}.take_back(linalgOp.getNumDpsInits());
579  auto packedLinalgOp = rewriter.create<linalg::GenericOp>(
580  linalgOp.getLoc(), inits.getTypes(), inputs, inits, indexingMaps,
581  iteratorTypes);
582  packedLinalgOp.getRegion().takeBody(linalgOp->getRegion(0));
583 
584  // Step 4. Propagate packing to all the op results.
585  for (OpResult result : packedLinalgOp->getResults()) {
586  int64_t resultNum = result.getResultNumber();
587  tensor::PackOp maybePackedInit =
588  inits[resultNum].getDefiningOp<tensor::PackOp>();
589  if (!maybePackedInit) {
590  results.push_back(result);
591  continue;
592  }
593  // Build the symmetrical UnPackOp to the existing PackOp.
594  unPackOps.push_back(rewriter.create<tensor::UnPackOp>(
595  packedLinalgOp->getLoc(), result, maybePackedInit.getSource(),
596  maybePackedInit.getInnerDimsPos(), maybePackedInit.getMixedTiles()));
597  results.push_back(unPackOps.back());
598  }
599 
600  // Step 5. Replace `linalgOp`.
601  rewriter.replaceOp(linalgOp, results);
602 
603  // Return packedLinalgOp.
604  return PackResult{packOps,
605  cast<linalg::LinalgOp>(packedLinalgOp.getOperation()),
606  unPackOps};
607 }
608 
609 //===----------------------------------------------------------------------===//
610 // packTranspose transformation.
611 //===----------------------------------------------------------------------===//
612 
613 /// Return a copy of `tensorType` after permutation by `permutationVector`.
614 // Note: Should be a new method in of MemRef/RankedTensor/VectorType::Builder
615 // but this would introduce a dependence on Dialect in IR.
616 // TODO: Restructure.
617 static RankedTensorType permuteShape(RankedTensorType tensorType,
618  ArrayRef<int64_t> permutationVector) {
619  SmallVector<int64_t> shape(tensorType.getShape());
620  applyPermutationToVector(shape, permutationVector);
621  return RankedTensorType::Builder(tensorType).setShape(shape);
622 }
623 
624 /// Return a new GenericOp obtained by transposing opOperand by the permutation
625 /// vector:
626 /// - the corresponding indexing map is transposed by `permutation`
627 /// - the corresponding operand value is replaced by `transposedValue`
628 /// `linalgOp` is replaced by the return op in the process.
629 /// Asserts that `transposedValue` is of the proper transposed ShapedType.
631  RewriterBase &rewriter, LinalgOp linalgOp, OpOperand &opOperand,
632  ArrayRef<int64_t> permutation, Value transposedValue) {
633  // Sanity check the operand.
634  assert(linalgOp == opOperand.getOwner() && "linalg op must own the operand");
635 
636  // Sanity check of the expected transposed tensor type.
637  auto tensorType = permuteShape(
638  cast<RankedTensorType>(opOperand.get().getType()), permutation);
639  (void)tensorType;
640  assert(tensorType == transposedValue.getType() &&
641  "expected tensor type mismatch");
642 
643  // Compute the transposed indexing map.
644  // Sigh unsigned pollution.
645  SmallVector<unsigned> tmpTransposition = llvm::to_vector(
646  llvm::map_range(permutation, [](int64_t i) -> unsigned { return i; }));
647  AffineMap permutationMap =
648  AffineMap::getPermutationMap(tmpTransposition, rewriter.getContext());
649  AffineMap transposedMap =
650  permutationMap.compose(linalgOp.getMatchingIndexingMap(&opOperand));
651 
652  // Set the transposed indexing map in the proper position.
653  SmallVector<AffineMap> indexingMaps = linalgOp.getIndexingMapsArray();
654  indexingMaps[linalgOp.getIndexingMapIndex(&opOperand)] = transposedMap;
655  // Set the transposedValue in the proper operand position.
656  SmallVector<Value> operands = linalgOp->getOperands();
657  operands[opOperand.getOperandNumber()] = transposedValue;
658 
659  ValueRange operandsRef(operands);
660  auto transposedGenericOp = rewriter.create<linalg::GenericOp>(
661  /*location=*/linalgOp->getLoc(),
662  /*resultTensorTypes=*/
663  operandsRef.drop_front(linalgOp.getNumDpsInputs()).getTypes(),
664  /*inputs=*/operandsRef.take_front(linalgOp.getNumDpsInputs()),
665  /*outputs=*/operandsRef.drop_front(linalgOp.getNumDpsInputs()),
666  /*indexingMaps=*/indexingMaps,
667  /*iteratorTypes=*/linalgOp.getIteratorTypesArray());
668  transposedGenericOp.getRegion().takeBody(linalgOp->getRegion(0));
669  rewriter.replaceOp(linalgOp, transposedGenericOp->getResults());
670 
671  return cast<linalg::LinalgOp>(transposedGenericOp.getOperation());
672 }
673 
674 FailureOr<PackTransposeResult>
675 linalg::packTranspose(RewriterBase &rewriter, tensor::PackOp packOp,
676  linalg::LinalgOp linalgOp, tensor::UnPackOp maybeUnPackOp,
677  ArrayRef<int64_t> outerPerm,
678  ArrayRef<int64_t> innerPerm) {
679  Location loc = linalgOp.getLoc();
680 
681  // Step 1. Transpose packOp.
682  rewriter.setInsertionPoint(packOp);
683  tensor::PackOp transposedPackOp =
684  packOp.createTransposedClone(rewriter, loc, innerPerm, outerPerm);
685 
686  if (!packOp.getResult().hasOneUse())
687  return rewriter.notifyMatchFailure(linalgOp, "expect single pack use");
688 
689  OpOperand &packUse = *packOp->getUses().begin();
690  if (packUse.getOwner() != linalgOp) {
691  return rewriter.notifyMatchFailure(
692  linalgOp, "not a single use by the LinalgOp target");
693  }
694  if (maybeUnPackOp &&
695  (!linalgOp.isDpsInit(&packUse) ||
696  maybeUnPackOp.getSource() != linalgOp.getTiedOpResult(&packUse))) {
697  return rewriter.notifyMatchFailure(linalgOp,
698  "not produced by the LinalgOp target");
699  }
700 
701  // Step 2. Transpose linalgOp.
702  // transposedPackOp.getOuterDimsPerm() may be empty, in which case it is the
703  // identity. Don't rely on it.
704  int64_t numLeadingDims = packOp.getSourceRank();
705  int64_t numTrailingDims = packOp.getInnerDimsPos().size();
706  // Step 2.a. Compute the permutation on the whole operand.
707  // Leading part just reuse the outerPerm.
708  SmallVector<int64_t> permutation(outerPerm);
709  if (permutation.empty())
710  llvm::append_range(permutation, llvm::seq<int64_t>(0, numLeadingDims));
711  // Trailing part needs to reindex positions by `numLeadingDims`.
712  if (innerPerm.empty()) {
713  llvm::append_range(
714  permutation,
715  llvm::seq<int64_t>(numLeadingDims, numLeadingDims + numTrailingDims));
716  } else {
717  llvm::append_range(permutation,
718  llvm::map_range(innerPerm, [&](int64_t pos) {
719  return numLeadingDims + pos;
720  }));
721  }
722  if (!isPermutationVector(permutation))
723  return rewriter.notifyMatchFailure(linalgOp, "invalid permutation");
724 
725  // Step 2.b. Save the transposedPackUse operand number in case we need to
726  // get the tied OpResult after `linalgOp` has been replaced.
727  int64_t packUseOperandNumber = packUse.getOperandNumber();
728  // Step 2.c. Actually perform the transposition.
729  rewriter.setInsertionPoint(linalgOp);
730  linalg::LinalgOp transposedLinalgOp = transposeOneLinalgOperandAndReplace(
731  rewriter, linalgOp, packUse, permutation, transposedPackOp.getResult());
732 
733  // Step 3. Maybe transpose unPackOp.
734  tensor::UnPackOp transposedUnPackOp;
735  if (maybeUnPackOp) {
736  OpOperand &opOperand =
737  transposedLinalgOp->getOpOperand(packUseOperandNumber);
738  OpResult transposedResult = transposedLinalgOp.getTiedOpResult(&opOperand);
739  rewriter.setInsertionPoint(maybeUnPackOp);
740  transposedUnPackOp = maybeUnPackOp.createTransposedClone(
741  rewriter, loc, transposedResult, innerPerm, outerPerm);
742 
743  rewriter.replaceOp(maybeUnPackOp, transposedUnPackOp->getResults());
744  }
745 
746  // Step 4. Finally, replace packOp now that we don't need it anymore.
747  rewriter.replaceOp(packOp, transposedPackOp->getResults());
748 
749  return PackTransposeResult{transposedPackOp, transposedLinalgOp,
750  transposedUnPackOp};
751 }
752 
753 //===----------------------------------------------------------------------===//
754 // packMatmulGreedily transformation.
755 //===----------------------------------------------------------------------===//
756 
757 /// Pack a LinalgOp by greedily inferring matmul dimensions (m, n, k) where m
758 /// and n are proper parallel dimensions and k is a proper reduction
759 /// dimension. Packing occurs by rewriting the op as a linalg.generic and
760 /// calling linalg::pack by `mnkPackedSizes`. The order of the packed
761 /// dimensions is customizable: the `mnkOrder` is a permutation of {0, 1, 2}
762 /// to reorder {m, n, k} into one of the 8 possible forms. The outer
763 /// dimensions of the operands are not permuted at this time, this is left for
764 /// future work.
765 FailureOr<PackResult>
766 linalg::packMatmulGreedily(RewriterBase &rewriter, LinalgOp linalgOp,
767  ArrayRef<OpFoldResult> mnkPackedSizes,
768  ArrayRef<int64_t> mnkPaddedSizesNextMultipleOf,
769  ArrayRef<int64_t> mnkOrder) {
770  assert(mnkPackedSizes.size() == 3 && "unexpected num of packing sizes");
771  assert((mnkPaddedSizesNextMultipleOf.empty() ||
772  mnkPaddedSizesNextMultipleOf.size() == 3) &&
773  "num of packing sizes next multiple should be empty or of size 3");
774  assert(mnkOrder.size() == 3 && "unexpected mnkOrder size");
775  assert(isPermutationVector(mnkOrder) && "expected a permutation");
776 
777  int64_t numLoops = linalgOp.getNumLoops();
778  if (numLoops <= 2) {
779  LLVM_DEBUG(DBGS() << "need 3+ loops to find a matmul to pack, got "
780  << numLoops << "\nin: " << linalgOp << "\n");
781  return rewriter.notifyMatchFailure(
782  linalgOp, "need 3+ loops to find a matmul to pack");
783  }
784 
785  // Locally adjust the desired iterator position of mnk and packing sizes.
786  int64_t numPackedDims = mnkPackedSizes.size();
787  SmallVector<int64_t> mmnnkkPos(numPackedDims);
788  for (int64_t i = 0, e = numPackedDims; i < e; ++i)
789  mmnnkkPos[i] = numLoops - numPackedDims + mnkOrder[i];
790  SmallVector<OpFoldResult> packedSizes(numPackedDims);
791  for (int64_t i = 0, e = numPackedDims; i < e; ++i)
792  packedSizes[mnkOrder[i]] = mnkPackedSizes[i];
793  SmallVector<int64_t> paddedSizesNextMultipleOf(numPackedDims);
794  for (int64_t i = 0, e = numPackedDims; i < e; ++i) {
795  paddedSizesNextMultipleOf[mnkOrder[i]] =
796  mnkPaddedSizesNextMultipleOf.empty() ? 0
797  : mnkPaddedSizesNextMultipleOf[i];
798  }
799 
800  // 1. Infer dims that are important for matmul.
801  FailureOr<ContractionDimensions> maybeDimensions =
802  inferContractionDims(linalgOp);
803  if (failed(maybeDimensions)) {
804  LLVM_DEBUG(DBGS() << "couldn't infer matmul iterators in: " << linalgOp
805  << "\n");
806  return rewriter.notifyMatchFailure(linalgOp,
807  "couldn't infer matmul iterators");
808  }
809 
810  // 2. Normalize linalgOp to an kmn-matmul-like with [red, par, par] most
811  // minor iterators. In cases with multiple options for m, n, k bias towards
812  // the most minor embedding.
813  // If we wanted a different normalization order, this is where it would have
814  // to plug a heuristic.
815  int64_t mPos = maybeDimensions->m.back(), nPos = maybeDimensions->n.back(),
816  kPos = maybeDimensions->k.back();
817  LLVM_DEBUG(DBGSNL(); DBGSNL(); DBGSNL();
818  DBGS() << "Start packing generic op greedily with (m@" << mPos
819  << ", n@" << nPos << ", k@" << kPos << "): " << linalgOp
820  << "\n";);
821 
822  // 2.a. Rewrite as a generic.
823  auto genericOp = dyn_cast<GenericOp>(linalgOp.getOperation());
824  if (!genericOp) {
825  FailureOr<GenericOp> generalizeResult =
826  generalizeNamedOp(rewriter, linalgOp);
827  assert(succeeded(generalizeResult) && "unexpected failure generalizing op");
828  genericOp = *generalizeResult;
829  }
830 
831  // 2.b. Interchange to move the dimensions (k, m, n) as most-minor
832  // iterators. Note that this only normalized the iteration order and does
833  // not change the indexings of any operand.
834  SmallVector<int64_t> permutation =
835  computePermutationVector(numLoops, {mPos, nPos, kPos}, mmnnkkPos);
836  LLVM_DEBUG(llvm::interleaveComma(permutation, DBGS() << "perm: "); DBGSNL(););
837  // Sign .. unsigned pollution.
838  SmallVector<unsigned> unsignedPerm(permutation.begin(), permutation.end());
839  FailureOr<GenericOp> interchangeResult =
840  interchangeGenericOp(rewriter, genericOp, unsignedPerm);
841  assert(succeeded(interchangeResult) && "unexpected failure interchanging op");
842  genericOp = *interchangeResult;
843  LLVM_DEBUG(DBGS() << "Generalized Op to pack: " << genericOp << "\n";);
844 
845  // At this point, the op iterators are normalized to {leading, k, m, n}.
846  // The layouts induced by packing will always be:
847  // - LHS{leading_lhs, kk, mm}
848  // - RHS{leading_rhs, kk, nn}
849  // - RES{leading_res, mm, nn}
850  // If we wanted to change the packed order, we would reorder (k, m, n) to
851  // something else above.
852  //
853  // Additional permutations of the outer dims of the operands (i.e.
854  // leading_lhs, leading_rhs and leading_res) could follow by computing the
855  // desired outerPerm for each operand.
856  // This is left for future work.
857 
858  // TODO: this creates too much IR, go use reifyResultShapes.
859  SmallVector<Range, 4> loopRanges =
860  cast<LinalgOp>(genericOp.getOperation())
861  .createLoopRanges(rewriter, genericOp.getLoc());
862 
863  // Add leading zeros to match numLoops, we only pack the last 3 dimensions
864  // post interchange.
865  LLVM_DEBUG(llvm::interleaveComma(paddedSizesNextMultipleOf,
866  DBGS() << "paddedSizesNextMultipleOf: ");
867  DBGSNL(););
868  LLVM_DEBUG(llvm::interleaveComma(loopRanges, DBGS() << "loopRanges: ",
869  [](Range r) { llvm::dbgs() << r.size; });
870  DBGSNL(););
871  SmallVector<OpFoldResult> adjustedPackedSizes(numLoops - packedSizes.size(),
872  rewriter.getIndexAttr(0));
873  for (int64_t i = 0, e = numPackedDims; i < e; ++i) {
874  if (paddedSizesNextMultipleOf[i] == 0) {
875  adjustedPackedSizes.push_back(packedSizes[i]);
876  continue;
877  }
878  AffineExpr d0, s0;
879  bindDims(rewriter.getContext(), d0);
880  bindSymbols(rewriter.getContext(), s0);
881  adjustedPackedSizes.push_back(affine::makeComposedFoldedAffineApply(
882  rewriter, genericOp->getLoc(), d0.ceilDiv(s0) * s0,
883  {loopRanges[adjustedPackedSizes.size()].size,
884  rewriter.getIndexAttr(paddedSizesNextMultipleOf[i])}));
885  }
886  LLVM_DEBUG(llvm::interleaveComma(adjustedPackedSizes,
887  DBGS() << "adjustedPackedSizes: ");
888  DBGSNL(););
889 
890  // TODO: If we wanted to give the genericOp a name after packing, after
891  // calling `pack` would be a good time. One would still need to check that
892  // `containsMostMinorMatmul(packingRes->packedLinalgOp)` is true, since we
893  // also allow degenerate matmul cases (i.e. matvec, dot).
894  return pack(rewriter, genericOp, adjustedPackedSizes);
895 }
896 
897 //===----------------------------------------------------------------------===//
898 // Transformations exposed as rewrite patterns.
899 //===----------------------------------------------------------------------===//
900 
903  assert(!tileSizeComputationFunction && "tile sizes already set");
904  SmallVector<int64_t, 4> tileSizes(ts);
905  tileSizeComputationFunction = [tileSizes](OpBuilder &b, Operation *op) {
906  OpBuilder::InsertionGuard guard(b);
908  &op->getParentOfType<func::FuncOp>().getBody().front());
909  return llvm::to_vector<4>(map_range(tileSizes, [&](int64_t s) {
910  Value v = b.create<arith::ConstantIndexOp>(op->getLoc(), s);
911  return v;
912  }));
913  };
914  return *this;
915 }
916 
918  memref::CopyOp copyOp, PatternRewriter &rewriter) const {
919  return vectorizeCopy(rewriter, copyOp);
920 }
921 
922 /// Filling `dest` using FillOp constant padding value if possible.
923 /// Otherwise, generate a tensor::GenerateOp.
925  RewriterBase &rewriter, tensor::PadOp padOp, Value dest,
926  const SmallVector<Value> &dynSizes) const {
927  auto padValue = padOp.getConstantPaddingValue();
928  if (padValue)
929  return rewriter.create<FillOp>(padOp.getLoc(), padValue, dest).result();
930 
931  // Fill could not be optimized: Lower to tensor::GenerateOp with region.
932  auto generateOp = rewriter.create<tensor::GenerateOp>(
933  padOp.getLoc(), padOp.getResultType(), dynSizes);
934  // Copy region to new op.
935  IRMapping bvm;
936  padOp.getRegion().cloneInto(&generateOp.getRegion(), bvm);
937  return generateOp;
938 }
939 
940 LogicalResult
942  PatternRewriter &rewriter) const {
943  // Given an OpFoldResult, return an index-typed value.
944  auto getIdxValue = [&](OpFoldResult ofr) {
945  if (auto val = llvm::dyn_cast_if_present<Value>(ofr))
946  return val;
947  return rewriter
949  padOp.getLoc(), cast<IntegerAttr>(ofr.get<Attribute>()).getInt())
950  .getResult();
951  };
952 
953  auto resultType = padOp.getResultType();
954  // Compute size of EmptyOp. Any combination of static/dynamic is supported.
955  SmallVector<Value> dynSizes;
956  SmallVector<int64_t> staticSizes;
957  for (unsigned dim = 0; dim < resultType.getRank(); ++dim) {
958  if (resultType.isDynamicDim(dim)) {
959  auto srcSize = getIdxValue(tensor::getMixedSize(rewriter, padOp.getLoc(),
960  padOp.getSource(), dim));
961  // Add low and high padding value.
962  auto plusLow = rewriter.createOrFold<arith::AddIOp>(
963  padOp.getLoc(), srcSize, getIdxValue(padOp.getMixedLowPad()[dim]));
964  auto plusHigh = rewriter.createOrFold<arith::AddIOp>(
965  padOp.getLoc(), plusLow, getIdxValue(padOp.getMixedHighPad()[dim]));
966  dynSizes.push_back(plusHigh);
967  }
968  staticSizes.push_back(resultType.getDimSize(dim));
969  }
970 
971  // Init tensor and fill it with padding.
972  Value emptyTensor = rewriter.create<tensor::EmptyOp>(
973  padOp.getLoc(), staticSizes, resultType.getElementType(), dynSizes);
974  Value fill = createFillOrGenerateOp(rewriter, padOp, emptyTensor, dynSizes);
975 
976  // Try optimize the copy of source.
977  if (optimizeCopyFn && optimizeCopyFn(rewriter, padOp, fill).succeeded())
978  return success();
979 
980  // tensor::PadOps cannot be optimized. Generate a InsertSliceOp instead
981  // for copying the PadOp source.
982  auto sourceType = padOp.getSourceType();
983  // Compute size of source of tensor::PadOp.
984  SmallVector<OpFoldResult> srcSizes =
985  tensor::getMixedSizes(rewriter, padOp.getLoc(), padOp.getSource());
986  // Strides of InsertSliceOp are all 1.
987  SmallVector<OpFoldResult> strides(sourceType.getRank(),
988  rewriter.getIndexAttr(1));
989  rewriter.replaceOpWithNewOp<tensor::InsertSliceOp>(
990  padOp, padOp.getSource(), fill, padOp.getMixedLowPad(), srcSizes,
991  strides);
992 
993  return success();
994 }
995 
997  tensor::ExtractSliceOp sliceOp, PatternRewriter &rewriter) const {
998  if (!sliceOp.hasUnitStride())
999  return failure();
1000 
1001  auto padOp = sliceOp.getSource().getDefiningOp<tensor::PadOp>();
1002  if (!padOp)
1003  return failure();
1004 
1005  bool zeroSliceGuard = true;
1006  if (controlFn) {
1007  if (std::optional<bool> control = controlFn(sliceOp))
1008  zeroSliceGuard = *control;
1009  else
1010  return failure();
1011  }
1012 
1013  FailureOr<TilingResult> tilingResult =
1014  tensor::bubbleUpPadSlice(rewriter, padOp, sliceOp.getMixedOffsets(),
1015  sliceOp.getMixedSizes(), zeroSliceGuard);
1016  if (failed(tilingResult))
1017  return failure();
1018  // All shapes are static and the data source is actually used. Rewrite into
1019  // pad(extract_slice(x)).
1020  rewriter.replaceOp(sliceOp, tilingResult->tiledValues);
1021  return success();
1022 }
1023 
1024 /// If padding value is set, returns a tensor.pad Op for the source tensor,
1025 /// with the output shape matching the output of `packOp`. Otherwise, returns
1026 /// the source directly.
1027 ///
1028 /// This method assumes that all outer dims for this pack Op are 1.
1030  tensor::PackOp packOp) {
1031  Value input = packOp.getSource();
1032  if (!packOp.getPaddingValue()) {
1033  return input;
1034  }
1035 
1036  assert(llvm::all_of(packOp.getAllOuterDims(),
1037  [](int64_t val) { return val == 1; }) &&
1038  "some outer dims are != 1");
1039 
1040  Location loc = packOp.getLoc();
1041  ShapedType inputType = packOp.getSourceType();
1042  int64_t inputRank = inputType.getRank();
1043 
1044  DenseMap<int64_t, OpFoldResult> tileAndPosMapping =
1045  packOp.getDimAndTileMapping();
1046 
1047  // The sizes of dynamic tiles
1048  SmallVector<Value> dynamicTileSizes;
1049 
1050  // Collect dims for the padded shape.
1051  SmallVector<int64_t> paddedShape;
1052  for (int64_t dimIdx = 0; dimIdx < inputRank; ++dimIdx) {
1053  // 1. Non-tiled outer dims.
1054  // These dims should be 1 and we simply preserve them.
1055  if (!tileAndPosMapping.count(dimIdx)) {
1056  int64_t inputDimSize = inputType.getDimSize(dimIdx);
1057  assert(inputDimSize == 1 &&
1058  "with all outer dims == 1, this non-tiled input dim should be 1!");
1059  paddedShape.push_back(inputDimSize);
1060  continue;
1061  }
1062 
1063  // 2. Tiled outer dims
1064  // As all outer dims == 1, it is safe to use the tile size for the padded
1065  // shape.
1066  OpFoldResult tileSizeForDim = tileAndPosMapping.lookup(dimIdx);
1067 
1068  // 2.1 Static tile sizes
1069  std::optional<int64_t> cstTileSize = getConstantIntValue(tileSizeForDim);
1070  if (cstTileSize.has_value()) {
1071  paddedShape.push_back(cstTileSize.value());
1072  continue;
1073  }
1074 
1075  // 2.2 Dynamic tile sizes
1076  paddedShape.push_back(ShapedType::kDynamic);
1077 
1078  // Get the value that holds the dynamic size.
1079  dynamicTileSizes.push_back(llvm::dyn_cast<Value>(tileSizeForDim));
1080  }
1081  auto resultType =
1082  RankedTensorType::get(paddedShape, inputType.getElementType());
1083  return tensor::createPadHighOp(resultType, input, packOp.getPaddingValue(),
1084  /*nofold=*/false, loc, builder,
1085  dynamicTileSizes);
1086 }
1087 
1088 // Normalizes a permutation on a higher rank space to its actual size, e.g.
1089 // perm = [1, 4, 2]
1090 // becomes
1091 // norm = [0, 2, 1]
1092 static SmallVector<int64_t>
1094  constexpr int64_t kNonTiledMarker = -1;
1095  SmallVector<int64_t> vec(rank, kNonTiledMarker);
1096  for (auto [index, value] : llvm::enumerate(perm))
1097  vec[value] = index;
1098  SmallVector<int64_t> normalizedPerm = llvm::to_vector(llvm::make_filter_range(
1099  vec, [&](int64_t v) { return v != kNonTiledMarker; }));
1100  // This inverts the permutation in addition to normalizing so invert back.
1101  return invertPermutationVector(normalizedPerm);
1102 }
1103 
1104 // Gets the normalized permutation implied by innerDimsPos and outerDimsPerm
1105 // assuming rank reduction of unit outer dims.
1106 static SmallVector<int64_t>
1108  ArrayRef<int64_t> innerDimsPos,
1109  ArrayRef<int64_t> outerDimsPerm) {
1110  SmallVector<int64_t> rankReducedOuterDimsPerm;
1111  SmallVector<int64_t> outerDims;
1112  SmallVector<int64_t> innerDims;
1113  int64_t dim = 0;
1114  int64_t unpackedRank = shape.size();
1115  for (auto i : llvm::seq<unsigned>(0, unpackedRank)) {
1116  if (llvm::is_contained(innerDimsPos, i)) {
1117  innerDims.push_back(dim++);
1118  continue;
1119  }
1120  if (shape[i] == 1)
1121  continue;
1122  outerDims.push_back(dim++);
1123  if (!outerDimsPerm.empty())
1124  rankReducedOuterDimsPerm.push_back(outerDimsPerm[i]);
1125  }
1126 
1127  // Get the position of the inner dims after permutation.
1128  SmallVector<int64_t> innerPerm =
1129  getPackUnpackNormalizedPerm(unpackedRank, innerDimsPos);
1130  applyPermutationToVector<int64_t>(innerDims, innerPerm);
1131 
1132  // Ditto for the outer dims.
1133  SmallVector<int64_t> perm = outerDims;
1134 
1135  rankReducedOuterDimsPerm =
1136  getPackUnpackNormalizedPerm(unpackedRank, rankReducedOuterDimsPerm);
1137  if (!rankReducedOuterDimsPerm.empty())
1138  applyPermutationToVector<int64_t>(perm, rankReducedOuterDimsPerm);
1139 
1140  // The tile always ends up as the inner most dims after packing.
1141  perm.append(innerDims);
1142 
1143  return perm;
1144 }
1145 
1147  tensor::PackOp packOp, PatternRewriter &rewriter) const {
1148  // TODO: support the case that outer dimensions are not all 1s. A
1149  // tensor.expand_shape will be generated in this case.
1150  if (llvm::any_of(packOp.getTiledOuterDims(),
1151  [](int64_t dim) { return dim != 1; })) {
1152  return rewriter.notifyMatchFailure(
1153  packOp, "require the tiled outer dimensions of the result are all 1s");
1154  }
1155 
1156  // 1. Use rank-reduced tensor.extract_slice op to extract the tile and untiled
1157  // outer dims.
1158  Location loc = packOp.getLoc();
1159  Value input = getPackOpSourceOrPaddedSource(rewriter, packOp);
1160  auto inputShape = packOp.getSourceType().getShape();
1161  DenseMap<int64_t, OpFoldResult> dimAndTileMapping =
1162  packOp.getDimAndTileMapping();
1163  Attribute zeroIdxAttr = rewriter.getIndexAttr(0);
1164  Attribute oneIdxAttr = rewriter.getIndexAttr(1);
1165  int64_t srcRank = packOp.getSourceRank();
1166  SmallVector<OpFoldResult> readOffsets(srcRank, zeroIdxAttr);
1167  SmallVector<OpFoldResult> readStrides(srcRank, oneIdxAttr);
1168  SmallVector<OpFoldResult> readSizes;
1169  SmallVector<OpFoldResult> transShapeForEmpty;
1170  SmallVector<int64_t> readShapeForExtractSlice;
1171  for (auto i : llvm::seq<unsigned>(0, srcRank)) {
1172  if (dimAndTileMapping.count(i)) {
1173  readShapeForExtractSlice.push_back(
1174  getConstantIntValue(dimAndTileMapping[i])
1175  .value_or(ShapedType::kDynamic));
1176  readSizes.push_back(dimAndTileMapping[i]);
1177  transShapeForEmpty.push_back(dimAndTileMapping[i]);
1178  continue;
1179  }
1180  if (ShapedType::isDynamic(inputShape[i])) {
1181  readSizes.push_back(
1182  rewriter.create<tensor::DimOp>(loc, input, i).getResult());
1183  } else {
1184  readSizes.push_back(rewriter.getIndexAttr(inputShape[i]));
1185  }
1186  if (inputShape[i] != 1) {
1187  readShapeForExtractSlice.push_back(inputShape[i]);
1188  transShapeForEmpty.push_back(rewriter.getIndexAttr(inputShape[i]));
1189  }
1190  }
1191 
1192  Type elemType = packOp.getSourceType().getElementType();
1193  auto readType = RankedTensorType::get(readShapeForExtractSlice, elemType);
1194 
1195  Value tile = rewriter.create<tensor::ExtractSliceOp>(
1196  loc, readType, input, readOffsets, readSizes, readStrides);
1197 
1198  // 2. Transpose the tile to match the inner tile order.
1200  inputShape, packOp.getInnerDimsPos(), packOp.getOuterDimsPerm());
1201 
1202  LLVM_DEBUG(DBGS() << "Pack permutation: " << packOp << "\n";
1203  llvm::interleaveComma(perm, DBGS() << "perm: "); DBGSNL(););
1204 
1205  applyPermutationToVector<OpFoldResult>(transShapeForEmpty, perm);
1206 
1207  Value empty =
1208  rewriter.create<tensor::EmptyOp>(loc, transShapeForEmpty, elemType);
1209  auto transposedOp =
1210  rewriter.create<linalg::TransposeOp>(loc, tile, empty, perm);
1211 
1212  // 3. Insert the inner tile to the destination.
1213  int64_t destRank = packOp.getDestRank();
1214  SmallVector<OpFoldResult> writeStrides(destRank, oneIdxAttr);
1215  SmallVector<OpFoldResult> writeOffsets(destRank, zeroIdxAttr);
1216  SmallVector<OpFoldResult> writeSizes =
1217  tensor::getMixedSizes(rewriter, loc, packOp.getDest());
1218 
1219  auto insert = rewriter.create<tensor::InsertSliceOp>(
1220  loc, transposedOp.getResult()[0], packOp.getDest(), writeOffsets,
1221  writeSizes, writeStrides);
1222  rewriter.replaceOp(packOp, insert.getResult());
1223 
1224  return success();
1225 }
1226 
1228  tensor::UnPackOp unpackOp, PatternRewriter &rewriter) const {
1229  int64_t srcRank = unpackOp.getSourceRank();
1230  int64_t destRank = unpackOp.getDestRank();
1231  ArrayRef<int64_t> srcShape = unpackOp.getSourceType().getShape();
1232  ArrayRef<int64_t> innerDimsPos = unpackOp.getInnerDimsPos();
1233  if (llvm::any_of(unpackOp.getTiledOuterDims(),
1234  [](int64_t dim) { return dim != 1; })) {
1235  return rewriter.notifyMatchFailure(
1236  unpackOp,
1237  "require the tiled outer dimensions of the result are all 1s");
1238  }
1239 
1240  // 1. Use rank-reduced tensor.extract_slice op to extract the tile.
1241  Location loc = unpackOp.getLoc();
1242  Value source = unpackOp.getSource();
1243  DenseMap<int64_t, OpFoldResult> dimAndTileMapping =
1244  unpackOp.getDimAndTileMapping();
1245  Attribute zeroIdxAttr = rewriter.getIndexAttr(0);
1246  Attribute oneIdxAttr = rewriter.getIndexAttr(1);
1247  SmallVector<OpFoldResult> readOffsets(srcRank, zeroIdxAttr);
1248  SmallVector<OpFoldResult> readStrides(srcRank, oneIdxAttr);
1249  SmallVector<OpFoldResult> readSizes;
1250  SmallVector<int64_t> readShape;
1251  SmallVector<Value> dynamicDims;
1252  for (auto i : llvm::seq<unsigned>(0, destRank)) {
1253  if (dimAndTileMapping.count(i)) {
1254  readSizes.push_back(oneIdxAttr);
1255  continue;
1256  }
1257 
1258  if (ShapedType::isDynamic(srcShape[i])) {
1259  Value dynamicDim =
1260  rewriter.create<tensor::DimOp>(loc, source, i).getResult();
1261  readSizes.push_back(dynamicDim);
1262  dynamicDims.push_back(dynamicDim);
1263  } else {
1264  readSizes.push_back(rewriter.getIndexAttr(srcShape[i]));
1265  }
1266  if (srcShape[i] != 1)
1267  readShape.push_back(srcShape[i]);
1268  }
1269  auto mixedTiles = unpackOp.getMixedTiles();
1270  readSizes.append(mixedTiles.begin(), mixedTiles.end());
1271 
1272  // Explicitly create the type for extract_slice op because the inner tile
1273  // size could be 1. We want to represent the whole inner tile in this case.
1274  auto tileShape = srcShape.drop_front(destRank);
1275  // Append the inner tile shape to the permuted and rank-reduced outer shape.
1276  readShape.append(tileShape.begin(), tileShape.end());
1277  Type elemType = unpackOp.getSourceType().getElementType();
1278  auto readType = RankedTensorType::get(readShape, elemType);
1279  Value innerTile = rewriter.create<tensor::ExtractSliceOp>(
1280  loc, readType, unpackOp.getSource(), readOffsets, readSizes, readStrides);
1281 
1282  // 2. Transpose the tile to match the outer corresponding tile order.
1284  srcShape.take_front(destRank), innerDimsPos, unpackOp.getOuterDimsPerm());
1285  // Unpack is a transition out of packed space so we invert the permutation.
1286  perm = invertPermutationVector(perm);
1287  SmallVector<int64_t> transpShape(readShape);
1288  applyPermutationToVector<int64_t>(transpShape, perm);
1289 
1290  Value empty =
1291  rewriter.create<tensor::EmptyOp>(loc, transpShape, elemType, dynamicDims);
1292  auto transposedOp =
1293  rewriter.create<linalg::TransposeOp>(loc, innerTile, empty, perm);
1294 
1295  // 3. Handle in-complete tiles if needed. It truncates trailing data from the
1296  // transposed tile.
1297  int numLoops = transpShape.size();
1298  SmallVector<OpFoldResult> tileStrides(numLoops, oneIdxAttr);
1299  SmallVector<OpFoldResult> tileOffsets(numLoops, zeroIdxAttr);
1300  SmallVector<OpFoldResult> tileSizes;
1301  ArrayRef<int64_t> destShape = unpackOp.getDestType().getShape();
1302  for (auto i : llvm::seq<unsigned>(0, destRank)) {
1303  if (dimAndTileMapping.count(i) || destShape[i] != 1)
1304  tileSizes.push_back(
1305  tensor::getMixedSize(rewriter, loc, unpackOp.getDest(), i));
1306  }
1307 
1308  auto partialTile = rewriter.create<tensor::ExtractSliceOp>(
1309  loc, transposedOp.getResult()[0], tileOffsets, tileSizes, tileStrides);
1310 
1311  // 4. Insert the result to the destination tensor.
1312  SmallVector<OpFoldResult> writeSizes;
1313  SmallVector<OpFoldResult> writeStrides(destRank, oneIdxAttr);
1314  SmallVector<OpFoldResult> writeOffsets(destRank, zeroIdxAttr);
1315  for (int i = 0, idx = 0; i < destRank; ++i) {
1316  if (dimAndTileMapping.count(i) || destShape[i] != 1)
1317  writeSizes.push_back(tileSizes[idx++]);
1318  else
1319  writeSizes.push_back(oneIdxAttr);
1320  }
1321  auto insert = rewriter.create<tensor::InsertSliceOp>(
1322  loc, partialTile, unpackOp.getDest(), writeOffsets, writeSizes,
1323  writeStrides);
1324  rewriter.replaceOp(unpackOp, insert.getResult());
1325 
1326  return success();
1327 }
1328 
1329 // The following are patterns for downscaling convolution ops with size-1
1330 // window dimensions.
1331 //
1332 // Note that we'd eventually want to write such transformations in a generic
1333 // way, e.g., converting to linalg.generic, removing the size-1 dimensions,
1334 // and then turning back to named ops. But for now it's fine to have a few
1335 // patterns matching special ops to get started.
1336 
1337 template <typename Conv2DOp, typename Conv1DOp>
1339  returningMatchAndRewrite(Conv2DOp convOp, PatternRewriter &rewriter) const {
1340  if (convOp.hasPureBufferSemantics())
1341  return failure(); // To be implemented.
1342 
1343  Value input = convOp.getInputs().front();
1344  Value kernel = convOp.getInputs().back();
1345  Value output = convOp.getOutputs().front();
1346 
1347  auto inputType = dyn_cast<RankedTensorType>(input.getType());
1348  auto kernelType = dyn_cast<RankedTensorType>(kernel.getType());
1349  auto outputType = dyn_cast<RankedTensorType>(output.getType());
1350 
1351  auto kernelShape = kernelType.getShape();
1352  auto outputShape = outputType.getShape();
1353 
1354  // Get domain indices based on conv2D layout.
1355  auto [khIndex, kwIndex, ohIndex, owIndex] =
1357  convOp)
1358  .Case([&](linalg::Conv2DNhwcHwcfOp op) {
1359  return std::make_tuple(0, 1, 1, 2);
1360  })
1361  .Case([&](linalg::Conv2DNchwFchwOp op) {
1362  return std::make_tuple(2, 3, 2, 3);
1363  })
1364  .Case([&](linalg::PoolingNhwcSumOp op) {
1365  return std::make_tuple(0, 1, 1, 2);
1366  })
1367  .Case([&](linalg::PoolingNchwSumOp op) {
1368  return std::make_tuple(0, 1, 2, 3);
1369  })
1370  .Case([&](linalg::PoolingNhwcMaxOp op) {
1371  return std::make_tuple(0, 1, 1, 2);
1372  })
1373  .Case([&](linalg::PoolingNhwcMaxUnsignedOp op) {
1374  return std::make_tuple(0, 1, 1, 2);
1375  })
1376  .Case([&](linalg::PoolingNhwcMinOp op) {
1377  return std::make_tuple(0, 1, 1, 2);
1378  })
1379  .Case([&](linalg::PoolingNhwcMinUnsignedOp op) {
1380  return std::make_tuple(0, 1, 1, 2);
1381  })
1382  .Case([&](linalg::PoolingNchwMaxOp op) {
1383  return std::make_tuple(0, 1, 2, 3);
1384  })
1385  .Default([&](Operation *op) {
1386  llvm_unreachable("unexpected conv2d/pool2d operation.");
1387  return std::make_tuple(0, 0, 0, 0);
1388  });
1389 
1390  // Only handle the case where at least one of the window dimensions is
1391  // of size 1. Other cases can rely on tiling to reduce to such cases.
1392  int64_t khSize = kernelShape[khIndex], kwSize = kernelShape[kwIndex];
1393  int64_t ohSize = outputShape[ohIndex], owSize = outputShape[owIndex];
1394  bool removeH = (khSize == 1 && ohSize == 1);
1395  bool removeW = (kwSize == 1 && owSize == 1);
1396  if (!removeH && !removeW)
1397  return failure();
1398 
1399  // Get new shapes and types for all operands by removing the size-1
1400  // dimension.
1401  using RTTBuilder = RankedTensorType::Builder;
1402  RankedTensorType newInputType =
1403  RTTBuilder(inputType).dropDim((removeH ? ohIndex : owIndex));
1404  RankedTensorType newKernelType =
1405  RTTBuilder(kernelType).dropDim((removeH ? khIndex : kwIndex));
1406  RankedTensorType newOutputType =
1407  RTTBuilder(outputType).dropDim((removeH ? ohIndex : owIndex));
1408 
1409  // Rank-reduce operands.
1410  Location loc = convOp.getLoc();
1412  rewriter, loc, input, newInputType);
1414  rewriter, loc, kernel, newKernelType);
1416  rewriter, loc, output, newOutputType);
1417 
1418  // Rank-reduce strides and dilations too.
1419  // TODO: dropDim 1-liner helper.
1420  auto strides =
1421  llvm::to_vector<4>(convOp.getStrides().template getValues<int64_t>());
1422  strides.erase(strides.begin() + (removeH ? 0 : 1));
1423  auto stridesAttr = rewriter.getI64VectorAttr(strides);
1424 
1425  auto dilations =
1426  llvm::to_vector<4>(convOp.getDilations().template getValues<int64_t>());
1427  dilations.erase(dilations.begin() + (removeH ? 0 : 1));
1428  auto dilationsAttr = rewriter.getI64VectorAttr(dilations);
1429 
1430  auto conv1DOp = rewriter.create<Conv1DOp>(
1431  loc, newOutputType, ValueRange{newInput, newKernel},
1432  ValueRange{newOutput}, stridesAttr, dilationsAttr);
1433 
1434  // Insert back.
1436  rewriter, loc, conv1DOp.getResult(0), output);
1437  rewriter.replaceOp(convOp, inserted);
1438 
1439  return conv1DOp;
1440 }
1441 
1442 template struct linalg::DownscaleSizeOneWindowed2DConvolution<Conv2DNhwcHwcfOp,
1443  Conv1DNwcWcfOp>;
1444 template struct linalg::DownscaleSizeOneWindowed2DConvolution<Conv2DNchwFchwOp,
1445  Conv1DNcwFcwOp>;
1446 template struct linalg::DownscaleSizeOneWindowed2DConvolution<PoolingNhwcSumOp,
1447  PoolingNwcSumOp>;
1448 template struct linalg::DownscaleSizeOneWindowed2DConvolution<PoolingNchwSumOp,
1449  PoolingNcwSumOp>;
1450 template struct linalg::DownscaleSizeOneWindowed2DConvolution<PoolingNhwcMaxOp,
1451  PoolingNwcMaxOp>;
1453  PoolingNhwcMaxUnsignedOp, PoolingNwcMaxUnsignedOp>;
1454 template struct linalg::DownscaleSizeOneWindowed2DConvolution<PoolingNhwcMinOp,
1455  PoolingNwcMinOp>;
1457  PoolingNhwcMinUnsignedOp, PoolingNwcMinUnsignedOp>;
1458 template struct linalg::DownscaleSizeOneWindowed2DConvolution<PoolingNchwMaxOp,
1459  PoolingNcwMaxOp>;
1460 
1461 FailureOr<DepthwiseConv1DNwcWcOp>
1463  DepthwiseConv2DNhwcHwcOp convOp, PatternRewriter &rewriter) const {
1464  if (convOp.hasPureBufferSemantics())
1465  return failure(); // To be implemented.
1466 
1467  Value input = convOp.getInputs().front();
1468  Value kernel = convOp.getInputs().back();
1469  Value output = convOp.getOutputs().front();
1470 
1471  auto inputType = dyn_cast<RankedTensorType>(input.getType());
1472  auto kernelType = dyn_cast<RankedTensorType>(kernel.getType());
1473  auto outputType = dyn_cast<RankedTensorType>(output.getType());
1474 
1475  auto kernelShape = kernelType.getShape();
1476  auto outputShape = outputType.getShape();
1477 
1478  // Only handle the case where at least one of the window dimensions is
1479  // of size 1. Other cases can rely on tiling to reduce to such cases.
1480  int64_t khSize = kernelShape[0], kwSize = kernelShape[1];
1481  int64_t ohSize = outputShape[1], owSize = outputShape[2];
1482  bool removeH = (khSize == 1 && ohSize == 1);
1483  bool removeW = (kwSize == 1 && owSize == 1);
1484  if (!removeH && !removeW)
1485  return failure();
1486 
1487  // Get new shapes and types for all operands by removing the size-1
1488  // dimension.
1489  using RTTBuilder = RankedTensorType::Builder;
1490  RankedTensorType newInputType =
1491  RTTBuilder(inputType).dropDim((removeH ? 1 : 2));
1492  RankedTensorType newKernelType =
1493  RTTBuilder(kernelType).dropDim((removeH ? 0 : 1));
1494  RankedTensorType newOutputType =
1495  RTTBuilder(outputType).dropDim(removeH ? 1 : 2);
1496 
1497  // Rank-reduce operands.
1498  Location loc = convOp.getLoc();
1500  rewriter, loc, input, newInputType);
1502  rewriter, loc, kernel, newKernelType);
1504  rewriter, loc, output, newOutputType);
1505 
1506  // Rank-reduce strides and dilations too.
1507  // TODO: dropDim 1-liner helper.
1508  auto strides = llvm::to_vector<4>(convOp.getStrides().getValues<int64_t>());
1509  strides.erase(strides.begin() + (removeH ? 0 : 1));
1510  auto stridesAttr = rewriter.getI64VectorAttr(strides);
1511 
1512  auto dilations =
1513  llvm::to_vector<4>(convOp.getDilations().getValues<int64_t>());
1514  dilations.erase(dilations.begin() + (removeH ? 0 : 1));
1515  auto dilationsAttr = rewriter.getI64VectorAttr(dilations);
1516 
1517  auto conv1DOp = rewriter.create<DepthwiseConv1DNwcWcOp>(
1518  loc, newOutputType, ValueRange{newInput, newKernel},
1519  ValueRange{newOutput}, stridesAttr, dilationsAttr);
1520 
1521  // Insert back.
1523  rewriter, loc, conv1DOp.getResult(0), output);
1524  rewriter.replaceOp(convOp, inserted);
1525 
1526  return conv1DOp;
1527 }
1528 
1529 FailureOr<Conv1DOp>
1531  PatternRewriter &rewriter) const {
1532  if (convOp.hasPureBufferSemantics())
1533  return failure(); // To be implemented.
1534 
1535  Value input = convOp.getInputs().front();
1536  Value kernel = convOp.getInputs().back();
1537  Value output = convOp.getOutputs().front();
1538 
1539  auto inputType = dyn_cast<RankedTensorType>(input.getType());
1540  auto kernelType = dyn_cast<RankedTensorType>(kernel.getType());
1541  auto outputType = dyn_cast<RankedTensorType>(output.getType());
1542 
1543  auto kernelShape = kernelType.getShape();
1544  auto outputShape = outputType.getShape();
1545 
1546  // Only handle the case where at least one of the window dimensions is
1547  // of size 1. Other cases can rely on tiling to reduce to such cases.
1548  int64_t khSize = kernelShape[0], kwSize = kernelShape[1];
1549  int64_t ohSize = outputShape[0], owSize = outputShape[1];
1550  bool removeH = (khSize == 1 && ohSize == 1);
1551  bool removeW = (kwSize == 1 && owSize == 1);
1552  if (!removeH && !removeW)
1553  return failure();
1554 
1555  // Get new shapes and types for all operands by removing the size-1
1556  // dimension.
1557  using RTTBuilder = RankedTensorType::Builder;
1558  RankedTensorType newInputType =
1559  RTTBuilder(inputType).dropDim((removeH ? 0 : 1));
1560  RankedTensorType newKernelType =
1561  RTTBuilder(kernelType).dropDim((removeH ? 0 : 1));
1562  RankedTensorType newOutputType =
1563  RTTBuilder(outputType).dropDim(removeH ? 0 : 1);
1564 
1565  // Rank-reduce operands.
1566  Location loc = convOp.getLoc();
1568  rewriter, loc, input, newInputType);
1570  rewriter, loc, kernel, newKernelType);
1572  rewriter, loc, output, newOutputType);
1573 
1574  auto conv1DOp = rewriter.create<Conv1DOp>(loc, newOutputType,
1575  ValueRange{newInput, newKernel},
1576  ValueRange{newOutput});
1577 
1578  // Insert back.
1580  rewriter, loc, conv1DOp.getResult(0), output);
1581  rewriter.replaceOp(convOp, inserted);
1582 
1583  return conv1DOp;
1584 }
1585 
1587  PatternBenefit benefit) {
1588  patterns.add<DownscaleSizeOneWindowed2DConvolution<linalg::Conv2DNhwcHwcfOp,
1589  Conv1DNwcWcfOp>,
1590  DownscaleSizeOneWindowed2DConvolution<linalg::Conv2DNchwFchwOp,
1591  Conv1DNcwFcwOp>,
1593  patterns.getContext(), benefit);
1594  patterns.add<
1598  DownscaleSizeOneWindowed2DConvolution<PoolingNhwcMaxUnsignedOp,
1599  PoolingNwcMaxUnsignedOp>,
1601  DownscaleSizeOneWindowed2DConvolution<PoolingNhwcMinUnsignedOp,
1602  PoolingNwcMinUnsignedOp>,
1604  patterns.getContext(), benefit);
1605 }
static RankedTensorType permuteShape(RankedTensorType tensorType, ArrayRef< int64_t > permutationVector)
Return a copy of tensorType after permutation by permutationVector.
Definition: Transforms.cpp:617
static SmallVector< int64_t > getPackUnpackRankReducedPerm(ArrayRef< int64_t > shape, ArrayRef< int64_t > innerDimsPos, ArrayRef< int64_t > outerDimsPerm)
static std::optional< int64_t > getFirstResultIndexFunctionOf(AffineMap map, int64_t dim)
Return the index of the first result of map that is a function of AffineDimExpr(dim),...
Definition: Transforms.cpp:102
static FailureOr< SmallVector< std::optional< int64_t > > > packLinalgMetadataOnce(SmallVectorImpl< AffineMap > &indexingMaps, SmallVectorImpl< utils::IteratorType > &iteratorTypes, int64_t dim)
Perform one step of packing of a LinalgOp's metadata along dim into the newDim at iteratorTypes....
Definition: Transforms.cpp:149
static LinalgOp transposeOneLinalgOperandAndReplace(RewriterBase &rewriter, LinalgOp linalgOp, OpOperand &opOperand, ArrayRef< int64_t > permutation, Value transposedValue)
Return a new GenericOp obtained by transposing opOperand by the permutation vector:
Definition: Transforms.cpp:630
static Value getPackOpSourceOrPaddedSource(OpBuilder &builder, tensor::PackOp packOp)
If padding value is set, returns a tensor.pad Op for the source tensor, with the output shape matchin...
static bool hasAtMostOneResultFunctionOfDim(AffineMap map, int64_t dim)
Return true if map has 0 or 1 result function of AffineDimExpr(dim).
Definition: Transforms.cpp:87
static SmallVector< int64_t > getPackUnpackNormalizedPerm(int rank, ArrayRef< int64_t > perm)
#define DBGSNL()
Definition: Transforms.cpp:46
#define DBGS()
Definition: Transforms.cpp:45
Base type for affine expression.
Definition: AffineExpr.h:68
bool isFunctionOfDim(unsigned position) const
Return true if the affine expression involves AffineDimExpr position.
Definition: AffineExpr.cpp:316
AffineExpr ceilDiv(uint64_t v) const
Definition: AffineExpr.cpp:954
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition: AffineMap.h:46
MLIRContext * getContext() const
Definition: AffineMap.cpp:343
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
AffineMap shiftDims(unsigned shift, unsigned offset=0) const
Replace dims[offset ...
Definition: AffineMap.h:267
AffineMap insertResult(AffineExpr expr, unsigned pos) const
Returns a new AffineMap with the same number of dims and symbols and an extra result inserted at pos.
Definition: AffineMap.h:315
unsigned getNumDims() const
Definition: AffineMap.cpp:394
ArrayRef< AffineExpr > getResults() const
Definition: AffineMap.cpp:407
unsigned getNumResults() const
Definition: AffineMap.cpp:402
AffineExpr getResult(unsigned idx) const
Definition: AffineMap.cpp:411
static AffineMap getPermutationMap(ArrayRef< unsigned > permutation, MLIRContext *context)
Returns an AffineMap representing a permutation.
Definition: AffineMap.cpp:264
AffineMap compose(AffineMap map) const
Returns the AffineMap resulting from composing this with map.
Definition: AffineMap.cpp:556
Attributes are known-constant values of operations.
Definition: Attributes.h:25
This class is a general helper class for creating context-global objects like types,...
Definition: Builders.h:50
IntegerAttr getIndexAttr(int64_t value)
Definition: Builders.cpp:148
TypedAttr getZeroAttr(Type type)
Definition: Builders.cpp:355
AffineExpr getAffineDimExpr(unsigned position)
Definition: Builders.cpp:395
MLIRContext * getContext() const
Definition: Builders.h:55
DenseIntElementsAttr getI64VectorAttr(ArrayRef< int64_t > values)
Definition: Builders.cpp:168
This is a utility class for mapping one set of IR entities to another.
Definition: IRMapping.h:26
IRValueT get() const
Return the current value being used by this operand.
Definition: UseDefLists.h:160
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:66
RAII guard to reset the insertion point of the builder when destroyed.
Definition: Builders.h:356
This class helps build Operations.
Definition: Builders.h:215
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition: Builders.h:439
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition: Builders.h:406
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
Definition: Builders.h:528
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:488
This class represents a single result from folding an operation.
Definition: OpDefinition.h:268
This class represents an operand of an operation.
Definition: Value.h:267
unsigned getOperandNumber()
Return which operand this is in the OpOperand list of the Operation.
Definition: Value.cpp:216
This is a value defined by a result of an operation.
Definition: Value.h:457
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition: Operation.h:402
Location getLoc()
The source location the operation was defined or derived from.
Definition: Operation.h:223
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
Definition: Operation.h:238
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
Definition: Operation.h:682
result_range getResults()
Definition: Operation.h:410
This class represents the benefit of a pattern match in a unitless scheme that ranges from 0 (very li...
Definition: PatternMatch.h:34
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
Definition: PatternMatch.h:785
This is a builder type that keeps local references to arguments.
Definition: BuiltinTypes.h:261
Builder & dropDim(unsigned pos)
Erase a dim from shape @pos.
Definition: BuiltinTypes.h:288
Builder & setShape(ArrayRef< int64_t > newShape)
Definition: BuiltinTypes.h:272
void takeBody(Region &other)
Takes body of another region (that region will have no body after this operation completes).
Definition: Region.h:241
MLIRContext * getContext() const
Definition: PatternMatch.h:823
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
Definition: PatternMatch.h:847
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
Definition: PatternMatch.h:400
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
Definition: PatternMatch.h:718
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
Definition: PatternMatch.h:536
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition: ValueRange.h:381
type_range getTypes() const
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
Type getType() const
Return the type of this value.
Definition: Value.h:129
Specialization of arith.constant op that returns an integer of index type.
Definition: Arith.h:93
Operation * getOwner() const
Return the owner of this operand.
Definition: UseDefLists.h:38
OpFoldResult makeComposedFoldedAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands)
Constructs an AffineApplyOp that applies map to operands after composing the map with the maps of any...
Definition: AffineOps.cpp:1192
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
Definition: Matchers.h:344
FailureOr< GenericOp > generalizeNamedOp(RewriterBase &rewriter, LinalgOp namedOp)
Create a GenericOp from the given named operation namedOp and replace namedOp.
FailureOr< LowerUnPackOpResult > lowerUnPack(RewriterBase &rewriter, tensor::UnPackOp unPackOp)
Rewrite pack as empty + transpose + reshape + extract_slice.
Definition: Transforms.cpp:354
void peelLoops(RewriterBase &rewriter, ArrayRef< scf::ForOp > loops)
Peel 'loops' and applies affine_min/max bounds simplification on the fly where relevant.
Definition: Transforms.cpp:75
void populateDecomposeConvolutionPatterns(RewritePatternSet &patterns, PatternBenefit benefit=1)
Linalg decompose convolutions patterns.
LogicalResult vectorizeCopy(RewriterBase &builder, memref::CopyOp copyOp)
Emit a suitable vector form for a Copy op with fully static shape.
FailureOr< GenericOp > interchangeGenericOp(RewriterBase &rewriter, GenericOp genericOp, ArrayRef< unsigned > interchangeVector)
Interchange the iterator_types and iterator_maps dimensions and adapts the index accesses of op.
Definition: Interchange.cpp:50
FailureOr< ContractionDimensions > inferContractionDims(LinalgOp linalgOp)
Find at least 2 parallel (m and n) and 1 reduction (k) dimension candidates that form a matmul subcom...
FailureOr< PackResult > packMatmulGreedily(RewriterBase &rewriter, LinalgOp linalgOp, ArrayRef< OpFoldResult > mnkPackedSizes, ArrayRef< int64_t > mnkPaddedSizesNextMultipleOf, ArrayRef< int64_t > mnkOrder)
Pack a LinalgOp by greedily inferring matmul dimensions (m, n, k) where m and n are proper parallel d...
Definition: Transforms.cpp:766
FailureOr< PackResult > pack(RewriterBase &rewriter, linalg::LinalgOp linalgOp, ArrayRef< OpFoldResult > packedSizes)
Implement packing of a single LinalgOp by packedSizes.
Definition: Transforms.cpp:477
FailureOr< LowerPackResult > lowerPack(RewriterBase &rewriter, tensor::PackOp packOp)
Rewrite pack as pad + reshape + transpose.
Definition: Transforms.cpp:219
SmallVector< Value > peelLoop(RewriterBase &rewriter, Operation *op)
Try to peel and canonicalize loop op and return the new result.
Definition: Transforms.cpp:59
FailureOr< PackTransposeResult > packTranspose(RewriterBase &rewriter, tensor::PackOp packOp, linalg::LinalgOp linalgOp, tensor::UnPackOp maybeUnPackOp, ArrayRef< int64_t > outerPerm, ArrayRef< int64_t > innerPerm)
Transpose a single PackOp -> LinalgOp -> UnPackOp chain and return the transposed PackOp -> LinalgOp ...
Definition: Transforms.cpp:675
LogicalResult peelForLoopAndSimplifyBounds(RewriterBase &rewriter, ForOp forOp, scf::ForOp &partialIteration)
Rewrite a for loop with bounds/step that potentially do not divide evenly into a for loop where the s...
FailureOr< TilingResult > bubbleUpPadSlice(OpBuilder &b, tensor::PadOp padOp, ArrayRef< OpFoldResult > offsets, ArrayRef< OpFoldResult > sizes, bool generateZeroSliceGuard=true)
Bubbles up a slice of this pad by taking the slice first and then performing the padding.
SmallVector< int64_t > getUnPackInverseSrcPerm(tensor::UnPackOp unpackOp)
Shell function to compute the Source Permutation of unPackOp.
Value createCanonicalRankReducingInsertSliceOp(OpBuilder &b, Location loc, Value tensor, Value dest)
Create a rank-reducing InsertSliceOp @[0 .
Definition: TensorOps.cpp:2868
Value createCanonicalRankReducingExtractSliceOp(OpBuilder &b, Location loc, Value tensor, RankedTensorType targetType)
Create a rank-reducing ExtractSliceOp @[0 .
Definition: TensorOps.cpp:2489
OpFoldResult getMixedSize(OpBuilder &builder, Location loc, Value value, int64_t dim)
Return the dimension of the given tensor value.
Definition: TensorOps.cpp:55
SmallVector< int64_t > getPackInverseDestPerm(tensor::PackOp packOp)
Shell function to compute the Destination Permutation of PackOp This function uses the helper functio...
PadOp createPadHighOp(RankedTensorType resType, Value source, Value pad, bool nofold, Location loc, OpBuilder &builder, SmallVector< Value > dynOutDim={})
Definition: Utils.cpp:25
SmallVector< OpFoldResult > getMixedSizes(OpBuilder &builder, Location loc, Value value)
Return the dimensions of the given tensor value.
Definition: TensorOps.cpp:65
Include the generated interface declarations.
SliceVerificationResult
Enum that captures information related to verifier error conditions on slice insert/extract type of o...
Definition: BuiltinTypes.h:387
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
void bindDims(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to DimExpr at positions: [0 .
Definition: AffineExpr.h:348
SmallVector< int64_t > computePermutationVector(int64_t permSize, ArrayRef< int64_t > positions, ArrayRef< int64_t > desiredPositions)
Return a permutation vector of size permSize that would result in moving positions into desiredPositi...
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
void bindSymbols(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to SymbolExpr at positions: [0 .
Definition: AffineExpr.h:362
SmallVector< Loops, 8 > tile(ArrayRef< scf::ForOp > forOps, ArrayRef< Value > sizes, ArrayRef< scf::ForOp > targets)
Performs tiling fo imperfectly nested loops (with interchange) by strip-mining the forOps by sizes an...
Definition: Utils.cpp:1278
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
void applyPermutationToVector(SmallVector< T, N > &inVec, ArrayRef< int64_t > permutation)
Apply the permutation defined by permutation to inVec.
SliceVerificationResult isRankReducedType(ShapedType originalType, ShapedType candidateReducedType)
Check if originalType can be rank reduced to candidateReducedType type by dropping some dimensions wi...
bool isPermutationVector(ArrayRef< int64_t > interchange)
Method to check if an interchange vector is a permutation.
SmallVector< int64_t > invertPermutationVector(ArrayRef< int64_t > permutation)
Helper method to apply to inverse a permutation.
Represents a range (offset, size, and stride) where each element of the triple may be dynamic or stat...
LogicalResult matchAndRewrite(memref::CopyOp copyOp, PatternRewriter &rewriter) const override
Definition: Transforms.cpp:917
FailureOr< Conv1DOp > returningMatchAndRewrite(Conv2DOp convOp, PatternRewriter &rewriter) const
Rewrites 2-D depthwise convolution ops with size-1 (w, kw) or (h, kh) dimensions into 1-D depthwise c...
Definition: Transforms.h:1426
FailureOr< DepthwiseConv1DNwcWcOp > returningMatchAndRewrite(DepthwiseConv2DNhwcHwcOp convOp, PatternRewriter &rewriter) const
Rewrites 2-D convolution ops with size-1 window dimensions into 1-D convolution ops.
Definition: Transforms.h:1406
FailureOr< Conv1DOp > returningMatchAndRewrite(Conv2DOp convOp, PatternRewriter &rewriter) const
LogicalResult matchAndRewrite(tensor::ExtractSliceOp sliceOp, PatternRewriter &rewriter) const override
Definition: Transforms.cpp:996
LogicalResult matchAndRewrite(tensor::PackOp packOp, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tensor::UnPackOp unpackOp, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tensor::PadOp padOp, PatternRewriter &rewriter) const override
Definition: Transforms.cpp:941
Value createFillOrGenerateOp(RewriterBase &rewriter, tensor::PadOp padOp, Value dest, const SmallVector< Value > &dynSizes) const
Filling dest using FillOp constant padding value if possible.
Definition: Transforms.cpp:924
LinalgTilingOptions & setTileSizes(const SmallVector< Value, 4 > &ts)
Set the tileSizeComputationFunction to return the values ts.
Definition: Transforms.h:202
Struct to hold the result of a pack call.
Definition: Transforms.h:1138
Struct to hold the result of a packTranspose call.
Definition: Transforms.h:1150