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  // Generate a InsertSliceOp for copying the PadOp source.
977  auto sourceType = padOp.getSourceType();
978  // Compute size of source of tensor::PadOp.
979  SmallVector<OpFoldResult> srcSizes =
980  tensor::getMixedSizes(rewriter, padOp.getLoc(), padOp.getSource());
981  // Strides of InsertSliceOp are all 1.
982  SmallVector<OpFoldResult> strides(sourceType.getRank(),
983  rewriter.getIndexAttr(1));
984  rewriter.replaceOpWithNewOp<tensor::InsertSliceOp>(
985  padOp, padOp.getSource(), fill, padOp.getMixedLowPad(), srcSizes,
986  strides);
987 
988  return success();
989 }
990 
992  tensor::ExtractSliceOp sliceOp, PatternRewriter &rewriter) const {
993  if (!sliceOp.hasUnitStride())
994  return failure();
995 
996  auto padOp = sliceOp.getSource().getDefiningOp<tensor::PadOp>();
997  if (!padOp)
998  return failure();
999 
1000  bool zeroSliceGuard = true;
1001  if (controlFn) {
1002  if (std::optional<bool> control = controlFn(sliceOp))
1003  zeroSliceGuard = *control;
1004  else
1005  return failure();
1006  }
1007 
1008  FailureOr<TilingResult> tilingResult =
1009  tensor::bubbleUpPadSlice(rewriter, padOp, sliceOp.getMixedOffsets(),
1010  sliceOp.getMixedSizes(), zeroSliceGuard);
1011  if (failed(tilingResult))
1012  return failure();
1013  // All shapes are static and the data source is actually used. Rewrite into
1014  // pad(extract_slice(x)).
1015  rewriter.replaceOp(sliceOp, tilingResult->tiledValues);
1016  return success();
1017 }
1018 
1019 /// If padding value is set, returns a tensor.pad Op for the source tensor,
1020 /// with the output shape matching the output of `packOp`. Otherwise, returns
1021 /// the source directly.
1022 ///
1023 /// This method assumes that all outer dims for this pack Op are 1.
1025  tensor::PackOp packOp) {
1026  Value input = packOp.getSource();
1027  if (!packOp.getPaddingValue()) {
1028  return input;
1029  }
1030 
1031  assert(llvm::all_of(packOp.getAllOuterDims(),
1032  [](int64_t val) { return val == 1; }) &&
1033  "some outer dims are != 1");
1034 
1035  Location loc = packOp.getLoc();
1036  ShapedType inputType = packOp.getSourceType();
1037  int64_t inputRank = inputType.getRank();
1038 
1039  DenseMap<int64_t, OpFoldResult> tileAndPosMapping =
1040  packOp.getDimAndTileMapping();
1041 
1042  // The sizes of dynamic tiles
1043  SmallVector<Value> dynamicTileSizes;
1044 
1045  // Collect dims for the padded shape.
1046  SmallVector<int64_t> paddedShape;
1047  for (int64_t dimIdx = 0; dimIdx < inputRank; ++dimIdx) {
1048  // 1. Non-tiled outer dims.
1049  // These dims should be 1 and we simply preserve them.
1050  if (!tileAndPosMapping.count(dimIdx)) {
1051  int64_t inputDimSize = inputType.getDimSize(dimIdx);
1052  assert(inputDimSize == 1 &&
1053  "with all outer dims == 1, this non-tiled input dim should be 1!");
1054  paddedShape.push_back(inputDimSize);
1055  continue;
1056  }
1057 
1058  // 2. Tiled outer dims
1059  // As all outer dims == 1, it is safe to use the tile size for the padded
1060  // shape.
1061  OpFoldResult tileSizeForDim = tileAndPosMapping.lookup(dimIdx);
1062 
1063  // 2.1 Static tile sizes
1064  std::optional<int64_t> cstTileSize = getConstantIntValue(tileSizeForDim);
1065  if (cstTileSize.has_value()) {
1066  paddedShape.push_back(cstTileSize.value());
1067  continue;
1068  }
1069 
1070  // 2.2 Dynamic tile sizes
1071  paddedShape.push_back(ShapedType::kDynamic);
1072 
1073  // Get the value that holds the dynamic size.
1074  dynamicTileSizes.push_back(llvm::dyn_cast<Value>(tileSizeForDim));
1075  }
1076  auto resultType =
1077  RankedTensorType::get(paddedShape, inputType.getElementType());
1078  return tensor::createPadHighOp(resultType, input, packOp.getPaddingValue(),
1079  /*nofold=*/false, loc, builder,
1080  dynamicTileSizes);
1081 }
1082 
1083 // Normalizes a permutation on a higher rank space to its actual size, e.g.
1084 // perm = [1, 4, 2]
1085 // becomes
1086 // norm = [0, 2, 1]
1087 static SmallVector<int64_t>
1089  constexpr int64_t kNonTiledMarker = -1;
1090  SmallVector<int64_t> vec(rank, kNonTiledMarker);
1091  for (auto [index, value] : llvm::enumerate(perm))
1092  vec[value] = index;
1093  SmallVector<int64_t> normalizedPerm = llvm::to_vector(llvm::make_filter_range(
1094  vec, [&](int64_t v) { return v != kNonTiledMarker; }));
1095  // This inverts the permutation in addition to normalizing so invert back.
1096  return invertPermutationVector(normalizedPerm);
1097 }
1098 
1099 // Gets the normalized permutation implied by innerDimsPos and outerDimsPerm
1100 // assuming rank reduction of unit outer dims.
1101 static SmallVector<int64_t>
1103  ArrayRef<int64_t> innerDimsPos,
1104  ArrayRef<int64_t> outerDimsPerm) {
1105  SmallVector<int64_t> rankReducedOuterDimsPerm;
1106  SmallVector<int64_t> outerDims;
1107  SmallVector<int64_t> innerDims;
1108  int64_t dim = 0;
1109  int64_t unpackedRank = shape.size();
1110  for (auto i : llvm::seq<unsigned>(0, unpackedRank)) {
1111  if (llvm::is_contained(innerDimsPos, i)) {
1112  innerDims.push_back(dim++);
1113  continue;
1114  }
1115  if (shape[i] == 1)
1116  continue;
1117  outerDims.push_back(dim++);
1118  if (!outerDimsPerm.empty())
1119  rankReducedOuterDimsPerm.push_back(outerDimsPerm[i]);
1120  }
1121 
1122  // Get the position of the inner dims after permutation.
1123  SmallVector<int64_t> innerPerm =
1124  getPackUnpackNormalizedPerm(unpackedRank, innerDimsPos);
1125  applyPermutationToVector<int64_t>(innerDims, innerPerm);
1126 
1127  // Ditto for the outer dims.
1128  SmallVector<int64_t> perm = outerDims;
1129 
1130  rankReducedOuterDimsPerm =
1131  getPackUnpackNormalizedPerm(unpackedRank, rankReducedOuterDimsPerm);
1132  if (!rankReducedOuterDimsPerm.empty())
1133  applyPermutationToVector<int64_t>(perm, rankReducedOuterDimsPerm);
1134 
1135  // The tile always ends up as the inner most dims after packing.
1136  perm.append(innerDims);
1137 
1138  return perm;
1139 }
1140 
1142  tensor::PackOp packOp, PatternRewriter &rewriter) const {
1143  // TODO: support the case that outer dimensions are not all 1s. A
1144  // tensor.expand_shape will be generated in this case.
1145  if (llvm::any_of(packOp.getAllOuterDims(),
1146  [](int64_t dim) { return dim != 1; })) {
1147  return rewriter.notifyMatchFailure(
1148  packOp, "not all outer dimensions of the result are 1s");
1149  }
1150 
1151  Attribute zeroIdxAttr = rewriter.getIndexAttr(0);
1152  Attribute oneIdxAttr = rewriter.getIndexAttr(1);
1153  Location loc = packOp.getLoc();
1154 
1155  Value input = getPackOpSourceOrPaddedSource(rewriter, packOp);
1156  DenseMap<int64_t, OpFoldResult> dimAndTileMapping =
1157  packOp.getDimAndTileMapping();
1158  int64_t srcRank = packOp.getSourceRank();
1159  int64_t destRank = packOp.getDestRank();
1160  int64_t numTiles = destRank - srcRank;
1161 
1162  if (!llvm::all_of(packOp.getInnerDimsPos(),
1163  [&srcRank, &numTiles](int64_t dimPos) {
1164  return dimPos >= (srcRank - numTiles - 1);
1165  }))
1166  return rewriter.notifyMatchFailure(
1167  packOp, "Attempting to tile non-trailing source dims!");
1168 
1169  // 1. Extract the inner tile sizes.
1170  // Where possible, values are replaced with constant attributes (to match the
1171  // behaviour of `getPackOpSourceOrPaddedSource`).
1172  SmallVector<OpFoldResult> tileSizes;
1173  for (auto i : llvm::seq<unsigned>(0, srcRank)) {
1174  if (dimAndTileMapping.count(i)) {
1175  // Rather than taking the tile size as is, extact the actual constant
1176  // value Attribute where possible, e.g.:
1177  // [Value: %tile_size = arith.constant 8 : index] --> [Attribute: 8]
1178  auto [_, tileSize] =
1179  getSimplifiedOfrAndStaticSizePair(dimAndTileMapping[i], rewriter);
1180  tileSizes.push_back(tileSize);
1181  }
1182  }
1183 
1184  // 2. Transpose the input to match the inner tile order:
1185  // %init = tensor.empty()
1186  // %transposed_tile = linalg.transpose ins(%source_or_padded_source),
1187  // outs(%init)
1188  // Two assumptions are made:
1189  // 1. All outer dims are 1 - the corresponding transposition doesn't matter.
1190  // 2. Inner dims position correspond to the trailing `numTiles` dims.
1191  SmallVector<int64_t> tilesPermNormalized =
1192  getPackUnpackNormalizedPerm(srcRank, packOp.getInnerDimsPos());
1193  SmallVector<int64_t> srcPermForTranspose;
1194  for (int64_t i = 0; i < (srcRank - numTiles); i++)
1195  srcPermForTranspose.push_back(i);
1196 
1197  srcPermForTranspose.append(SmallVector<int64_t>(packOp.getInnerDimsPos()));
1198 
1199  LLVM_DEBUG(DBGS() << "Pack permutation: " << packOp << "\n";
1200  llvm::interleaveComma(srcPermForTranspose, DBGS() << "perm: ");
1201  DBGSNL(););
1202 
1203  // 2.1 Create tensor.empty (init value for TransposeOp)
1204  SmallVector<OpFoldResult> transShapeForEmptyOp(srcRank - numTiles,
1205  oneIdxAttr);
1206  transShapeForEmptyOp.append(tileSizes);
1207 
1208  applyPermutationToVector<OpFoldResult>(transShapeForEmptyOp,
1209  srcPermForTranspose);
1210  Value empty = rewriter.create<tensor::EmptyOp>(
1211  loc, transShapeForEmptyOp, packOp.getSourceType().getElementType());
1212 
1213  // 2.2 Create linalg.transpose
1214  auto transposedOp = rewriter.create<linalg::TransposeOp>(loc, input, empty,
1215  srcPermForTranspose);
1216 
1217  // 3. Insert the inner tile to the destination:
1218  // %inserted_tile = tensor.insert_slice(%transposed_tile)
1219  SmallVector<OpFoldResult> writeStrides(destRank, oneIdxAttr);
1220  SmallVector<OpFoldResult> writeOffsets(destRank, zeroIdxAttr);
1221  // Outer dims are all 1s!
1222  SmallVector<OpFoldResult> writeSizes(destRank - dimAndTileMapping.size(),
1223  oneIdxAttr);
1224  SmallVector<int64_t> writeShape;
1225 
1226  for (auto tileSize : packOp.getMixedTiles()) {
1227  auto [tileSizeStatic, tileSizeOfr] =
1228  getSimplifiedOfrAndStaticSizePair(tileSize, rewriter);
1229  writeSizes.push_back(tileSizeOfr);
1230  writeShape.push_back(tileSizeStatic);
1231  }
1232 
1233  // 4. Replace tensor.packOp with tensor.insert_slice created above
1234  auto insert = rewriter.create<tensor::InsertSliceOp>(
1235  loc, transposedOp.getResult()[0], packOp.getDest(), writeOffsets,
1236  writeSizes, writeStrides);
1237  rewriter.replaceOp(packOp, insert.getResult());
1238 
1239  return success();
1240 }
1241 
1243  tensor::UnPackOp unpackOp, PatternRewriter &rewriter) const {
1244  int64_t srcRank = unpackOp.getSourceRank();
1245  int64_t destRank = unpackOp.getDestRank();
1246  ArrayRef<int64_t> srcShape = unpackOp.getSourceType().getShape();
1247  ArrayRef<int64_t> innerDimsPos = unpackOp.getInnerDimsPos();
1248  if (llvm::any_of(unpackOp.getTiledOuterDims(),
1249  [](int64_t dim) { return dim != 1; })) {
1250  return rewriter.notifyMatchFailure(
1251  unpackOp,
1252  "require the tiled outer dimensions of the result are all 1s");
1253  }
1254 
1255  // 1. Use rank-reduced tensor.extract_slice op to extract the tile.
1256  Location loc = unpackOp.getLoc();
1257  Value source = unpackOp.getSource();
1258  DenseMap<int64_t, OpFoldResult> dimAndTileMapping =
1259  unpackOp.getDimAndTileMapping();
1260  Attribute zeroIdxAttr = rewriter.getIndexAttr(0);
1261  Attribute oneIdxAttr = rewriter.getIndexAttr(1);
1262  SmallVector<OpFoldResult> readOffsets(srcRank, zeroIdxAttr);
1263  SmallVector<OpFoldResult> readStrides(srcRank, oneIdxAttr);
1264  SmallVector<OpFoldResult> readSizes;
1265  SmallVector<int64_t> readShape;
1266  SmallVector<Value> dynamicDims;
1267  for (auto i : llvm::seq<unsigned>(0, destRank)) {
1268  if (dimAndTileMapping.count(i)) {
1269  readSizes.push_back(oneIdxAttr);
1270  continue;
1271  }
1272 
1273  if (ShapedType::isDynamic(srcShape[i])) {
1274  Value dynamicDim =
1275  rewriter.create<tensor::DimOp>(loc, source, i).getResult();
1276  readSizes.push_back(dynamicDim);
1277  dynamicDims.push_back(dynamicDim);
1278  } else {
1279  readSizes.push_back(rewriter.getIndexAttr(srcShape[i]));
1280  }
1281  if (srcShape[i] != 1)
1282  readShape.push_back(srcShape[i]);
1283  }
1284  auto mixedTiles = unpackOp.getMixedTiles();
1285  readSizes.append(mixedTiles.begin(), mixedTiles.end());
1286 
1287  // Explicitly create the type for extract_slice op because the inner tile
1288  // size could be 1. We want to represent the whole inner tile in this case.
1289  auto tileShape = srcShape.drop_front(destRank);
1290  // Append the inner tile shape to the permuted and rank-reduced outer shape.
1291  readShape.append(tileShape.begin(), tileShape.end());
1292  Type elemType = unpackOp.getSourceType().getElementType();
1293  auto readType = RankedTensorType::get(readShape, elemType);
1294  Value innerTile = rewriter.create<tensor::ExtractSliceOp>(
1295  loc, readType, unpackOp.getSource(), readOffsets, readSizes, readStrides);
1296 
1297  // 2. Transpose the tile to match the outer corresponding tile order.
1299  srcShape.take_front(destRank), innerDimsPos, unpackOp.getOuterDimsPerm());
1300  // Unpack is a transition out of packed space so we invert the permutation.
1301  perm = invertPermutationVector(perm);
1302  SmallVector<int64_t> transpShape(readShape);
1303  applyPermutationToVector<int64_t>(transpShape, perm);
1304 
1305  Value empty =
1306  rewriter.create<tensor::EmptyOp>(loc, transpShape, elemType, dynamicDims);
1307  auto transposedOp =
1308  rewriter.create<linalg::TransposeOp>(loc, innerTile, empty, perm);
1309 
1310  // 3. Handle in-complete tiles if needed. It truncates trailing data from the
1311  // transposed tile.
1312  int numLoops = transpShape.size();
1313  SmallVector<OpFoldResult> tileStrides(numLoops, oneIdxAttr);
1314  SmallVector<OpFoldResult> tileOffsets(numLoops, zeroIdxAttr);
1315  SmallVector<OpFoldResult> tileSizes;
1316  ArrayRef<int64_t> destShape = unpackOp.getDestType().getShape();
1317  for (auto i : llvm::seq<unsigned>(0, destRank)) {
1318  if (dimAndTileMapping.count(i) || destShape[i] != 1)
1319  tileSizes.push_back(
1320  tensor::getMixedSize(rewriter, loc, unpackOp.getDest(), i));
1321  }
1322 
1323  auto partialTile = rewriter.create<tensor::ExtractSliceOp>(
1324  loc, transposedOp.getResult()[0], tileOffsets, tileSizes, tileStrides);
1325 
1326  // 4. Insert the result to the destination tensor.
1327  SmallVector<OpFoldResult> writeSizes;
1328  SmallVector<OpFoldResult> writeStrides(destRank, oneIdxAttr);
1329  SmallVector<OpFoldResult> writeOffsets(destRank, zeroIdxAttr);
1330  for (int i = 0, idx = 0; i < destRank; ++i) {
1331  if (dimAndTileMapping.count(i) || destShape[i] != 1)
1332  writeSizes.push_back(tileSizes[idx++]);
1333  else
1334  writeSizes.push_back(oneIdxAttr);
1335  }
1336  auto insert = rewriter.create<tensor::InsertSliceOp>(
1337  loc, partialTile, unpackOp.getDest(), writeOffsets, writeSizes,
1338  writeStrides);
1339  rewriter.replaceOp(unpackOp, insert.getResult());
1340 
1341  return success();
1342 }
1343 
1344 // The following are patterns for downscaling convolution ops with size-1
1345 // window dimensions.
1346 //
1347 // Note that we'd eventually want to write such transformations in a generic
1348 // way, e.g., converting to linalg.generic, removing the size-1 dimensions,
1349 // and then turning back to named ops. But for now it's fine to have a few
1350 // patterns matching special ops to get started.
1351 
1352 template <typename Conv2DOp, typename Conv1DOp>
1354  returningMatchAndRewrite(Conv2DOp convOp, PatternRewriter &rewriter) const {
1355  if (convOp.hasPureBufferSemantics())
1356  return failure(); // To be implemented.
1357 
1358  Value input = convOp.getInputs().front();
1359  Value kernel = convOp.getInputs().back();
1360  Value output = convOp.getOutputs().front();
1361 
1362  auto inputType = dyn_cast<RankedTensorType>(input.getType());
1363  auto kernelType = dyn_cast<RankedTensorType>(kernel.getType());
1364  auto outputType = dyn_cast<RankedTensorType>(output.getType());
1365 
1366  auto kernelShape = kernelType.getShape();
1367  auto outputShape = outputType.getShape();
1368 
1369  // Get domain indices based on conv2D layout.
1370  auto [khIndex, kwIndex, ohIndex, owIndex] =
1372  convOp)
1373  .Case([&](linalg::Conv2DNhwcHwcfOp op) {
1374  return std::make_tuple(0, 1, 1, 2);
1375  })
1376  .Case([&](linalg::Conv2DNchwFchwOp op) {
1377  return std::make_tuple(2, 3, 2, 3);
1378  })
1379  .Case([&](linalg::PoolingNhwcSumOp op) {
1380  return std::make_tuple(0, 1, 1, 2);
1381  })
1382  .Case([&](linalg::PoolingNchwSumOp op) {
1383  return std::make_tuple(0, 1, 2, 3);
1384  })
1385  .Case([&](linalg::PoolingNhwcMaxOp op) {
1386  return std::make_tuple(0, 1, 1, 2);
1387  })
1388  .Case([&](linalg::PoolingNhwcMaxUnsignedOp op) {
1389  return std::make_tuple(0, 1, 1, 2);
1390  })
1391  .Case([&](linalg::PoolingNhwcMinOp op) {
1392  return std::make_tuple(0, 1, 1, 2);
1393  })
1394  .Case([&](linalg::PoolingNhwcMinUnsignedOp op) {
1395  return std::make_tuple(0, 1, 1, 2);
1396  })
1397  .Case([&](linalg::PoolingNchwMaxOp op) {
1398  return std::make_tuple(0, 1, 2, 3);
1399  })
1400  .Default([&](Operation *op) {
1401  llvm_unreachable("unexpected conv2d/pool2d operation.");
1402  return std::make_tuple(0, 0, 0, 0);
1403  });
1404 
1405  // Only handle the case where at least one of the window dimensions is
1406  // of size 1. Other cases can rely on tiling to reduce to such cases.
1407  int64_t khSize = kernelShape[khIndex], kwSize = kernelShape[kwIndex];
1408  int64_t ohSize = outputShape[ohIndex], owSize = outputShape[owIndex];
1409  bool removeH = (khSize == 1 && ohSize == 1);
1410  bool removeW = (kwSize == 1 && owSize == 1);
1411  if (!removeH && !removeW)
1412  return failure();
1413 
1414  // Get new shapes and types for all operands by removing the size-1
1415  // dimension.
1416  using RTTBuilder = RankedTensorType::Builder;
1417  RankedTensorType newInputType =
1418  RTTBuilder(inputType).dropDim((removeH ? ohIndex : owIndex));
1419  RankedTensorType newKernelType =
1420  RTTBuilder(kernelType).dropDim((removeH ? khIndex : kwIndex));
1421  RankedTensorType newOutputType =
1422  RTTBuilder(outputType).dropDim((removeH ? ohIndex : owIndex));
1423 
1424  // Rank-reduce operands.
1425  Location loc = convOp.getLoc();
1427  rewriter, loc, input, newInputType);
1429  rewriter, loc, kernel, newKernelType);
1431  rewriter, loc, output, newOutputType);
1432 
1433  // Rank-reduce strides and dilations too.
1434  // TODO: dropDim 1-liner helper.
1435  auto strides =
1436  llvm::to_vector<4>(convOp.getStrides().template getValues<int64_t>());
1437  strides.erase(strides.begin() + (removeH ? 0 : 1));
1438  auto stridesAttr = rewriter.getI64VectorAttr(strides);
1439 
1440  auto dilations =
1441  llvm::to_vector<4>(convOp.getDilations().template getValues<int64_t>());
1442  dilations.erase(dilations.begin() + (removeH ? 0 : 1));
1443  auto dilationsAttr = rewriter.getI64VectorAttr(dilations);
1444 
1445  auto conv1DOp = rewriter.create<Conv1DOp>(
1446  loc, newOutputType, ValueRange{newInput, newKernel},
1447  ValueRange{newOutput}, stridesAttr, dilationsAttr);
1448 
1449  // Insert back.
1451  rewriter, loc, conv1DOp.getResult(0), output);
1452  rewriter.replaceOp(convOp, inserted);
1453 
1454  return conv1DOp;
1455 }
1456 
1457 template struct linalg::DownscaleSizeOneWindowed2DConvolution<Conv2DNhwcHwcfOp,
1458  Conv1DNwcWcfOp>;
1459 template struct linalg::DownscaleSizeOneWindowed2DConvolution<Conv2DNchwFchwOp,
1460  Conv1DNcwFcwOp>;
1461 template struct linalg::DownscaleSizeOneWindowed2DConvolution<PoolingNhwcSumOp,
1462  PoolingNwcSumOp>;
1463 template struct linalg::DownscaleSizeOneWindowed2DConvolution<PoolingNchwSumOp,
1464  PoolingNcwSumOp>;
1465 template struct linalg::DownscaleSizeOneWindowed2DConvolution<PoolingNhwcMaxOp,
1466  PoolingNwcMaxOp>;
1468  PoolingNhwcMaxUnsignedOp, PoolingNwcMaxUnsignedOp>;
1469 template struct linalg::DownscaleSizeOneWindowed2DConvolution<PoolingNhwcMinOp,
1470  PoolingNwcMinOp>;
1472  PoolingNhwcMinUnsignedOp, PoolingNwcMinUnsignedOp>;
1473 template struct linalg::DownscaleSizeOneWindowed2DConvolution<PoolingNchwMaxOp,
1474  PoolingNcwMaxOp>;
1475 
1476 FailureOr<DepthwiseConv1DNwcWcOp>
1478  DepthwiseConv2DNhwcHwcOp convOp, PatternRewriter &rewriter) const {
1479  if (convOp.hasPureBufferSemantics())
1480  return failure(); // To be implemented.
1481 
1482  Value input = convOp.getInputs().front();
1483  Value kernel = convOp.getInputs().back();
1484  Value output = convOp.getOutputs().front();
1485 
1486  auto inputType = dyn_cast<RankedTensorType>(input.getType());
1487  auto kernelType = dyn_cast<RankedTensorType>(kernel.getType());
1488  auto outputType = dyn_cast<RankedTensorType>(output.getType());
1489 
1490  auto kernelShape = kernelType.getShape();
1491  auto outputShape = outputType.getShape();
1492 
1493  // Only handle the case where at least one of the window dimensions is
1494  // of size 1. Other cases can rely on tiling to reduce to such cases.
1495  int64_t khSize = kernelShape[0], kwSize = kernelShape[1];
1496  int64_t ohSize = outputShape[1], owSize = outputShape[2];
1497  bool removeH = (khSize == 1 && ohSize == 1);
1498  bool removeW = (kwSize == 1 && owSize == 1);
1499  if (!removeH && !removeW)
1500  return failure();
1501 
1502  // Get new shapes and types for all operands by removing the size-1
1503  // dimension.
1504  using RTTBuilder = RankedTensorType::Builder;
1505  RankedTensorType newInputType =
1506  RTTBuilder(inputType).dropDim((removeH ? 1 : 2));
1507  RankedTensorType newKernelType =
1508  RTTBuilder(kernelType).dropDim((removeH ? 0 : 1));
1509  RankedTensorType newOutputType =
1510  RTTBuilder(outputType).dropDim(removeH ? 1 : 2);
1511 
1512  // Rank-reduce operands.
1513  Location loc = convOp.getLoc();
1515  rewriter, loc, input, newInputType);
1517  rewriter, loc, kernel, newKernelType);
1519  rewriter, loc, output, newOutputType);
1520 
1521  // Rank-reduce strides and dilations too.
1522  // TODO: dropDim 1-liner helper.
1523  auto strides = llvm::to_vector<4>(convOp.getStrides().getValues<int64_t>());
1524  strides.erase(strides.begin() + (removeH ? 0 : 1));
1525  auto stridesAttr = rewriter.getI64VectorAttr(strides);
1526 
1527  auto dilations =
1528  llvm::to_vector<4>(convOp.getDilations().getValues<int64_t>());
1529  dilations.erase(dilations.begin() + (removeH ? 0 : 1));
1530  auto dilationsAttr = rewriter.getI64VectorAttr(dilations);
1531 
1532  auto conv1DOp = rewriter.create<DepthwiseConv1DNwcWcOp>(
1533  loc, newOutputType, ValueRange{newInput, newKernel},
1534  ValueRange{newOutput}, stridesAttr, dilationsAttr);
1535 
1536  // Insert back.
1538  rewriter, loc, conv1DOp.getResult(0), output);
1539  rewriter.replaceOp(convOp, inserted);
1540 
1541  return conv1DOp;
1542 }
1543 
1544 FailureOr<Conv1DOp>
1546  PatternRewriter &rewriter) const {
1547  if (convOp.hasPureBufferSemantics())
1548  return failure(); // To be implemented.
1549 
1550  Value input = convOp.getInputs().front();
1551  Value kernel = convOp.getInputs().back();
1552  Value output = convOp.getOutputs().front();
1553 
1554  auto inputType = dyn_cast<RankedTensorType>(input.getType());
1555  auto kernelType = dyn_cast<RankedTensorType>(kernel.getType());
1556  auto outputType = dyn_cast<RankedTensorType>(output.getType());
1557 
1558  auto kernelShape = kernelType.getShape();
1559  auto outputShape = outputType.getShape();
1560 
1561  // Only handle the case where at least one of the window dimensions is
1562  // of size 1. Other cases can rely on tiling to reduce to such cases.
1563  int64_t khSize = kernelShape[0], kwSize = kernelShape[1];
1564  int64_t ohSize = outputShape[0], owSize = outputShape[1];
1565  bool removeH = (khSize == 1 && ohSize == 1);
1566  bool removeW = (kwSize == 1 && owSize == 1);
1567  if (!removeH && !removeW)
1568  return failure();
1569 
1570  // Get new shapes and types for all operands by removing the size-1
1571  // dimension.
1572  using RTTBuilder = RankedTensorType::Builder;
1573  RankedTensorType newInputType =
1574  RTTBuilder(inputType).dropDim((removeH ? 0 : 1));
1575  RankedTensorType newKernelType =
1576  RTTBuilder(kernelType).dropDim((removeH ? 0 : 1));
1577  RankedTensorType newOutputType =
1578  RTTBuilder(outputType).dropDim(removeH ? 0 : 1);
1579 
1580  // Rank-reduce operands.
1581  Location loc = convOp.getLoc();
1583  rewriter, loc, input, newInputType);
1585  rewriter, loc, kernel, newKernelType);
1587  rewriter, loc, output, newOutputType);
1588 
1589  auto conv1DOp = rewriter.create<Conv1DOp>(loc, newOutputType,
1590  ValueRange{newInput, newKernel},
1591  ValueRange{newOutput});
1592 
1593  // Insert back.
1595  rewriter, loc, conv1DOp.getResult(0), output);
1596  rewriter.replaceOp(convOp, inserted);
1597 
1598  return conv1DOp;
1599 }
1600 
1602  PatternBenefit benefit) {
1603  patterns.add<DownscaleSizeOneWindowed2DConvolution<linalg::Conv2DNhwcHwcfOp,
1604  Conv1DNwcWcfOp>,
1605  DownscaleSizeOneWindowed2DConvolution<linalg::Conv2DNchwFchwOp,
1606  Conv1DNcwFcwOp>,
1608  patterns.getContext(), benefit);
1609  patterns.add<
1613  DownscaleSizeOneWindowed2DConvolution<PoolingNhwcMaxUnsignedOp,
1614  PoolingNwcMaxUnsignedOp>,
1616  DownscaleSizeOneWindowed2DConvolution<PoolingNhwcMinUnsignedOp,
1617  PoolingNwcMinUnsignedOp>,
1619  patterns.getContext(), benefit);
1620 }
1621 
1623  // TODO: Add and test patterns for tensor.unpack
1624  patterns.add<DecomposeOuterUnitDimsPackOpPattern>(patterns.getContext());
1625 }
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:964
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:364
AffineExpr getAffineDimExpr(unsigned position)
Definition: Builders.cpp:404
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:497
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
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:791
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:829
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:853
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:724
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:542
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:1194
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
void populateDecomposePackUnpackPatterns(RewritePatternSet &patterns)
Populates patterns to decompose tensor.pack and tensor.unpack Ops into e.g.
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:3005
Value createCanonicalRankReducingExtractSliceOp(OpBuilder &b, Location loc, Value tensor, RankedTensorType targetType)
Create a rank-reducing ExtractSliceOp @[0 .
Definition: TensorOps.cpp:2626
OpFoldResult getMixedSize(OpBuilder &builder, Location loc, Value value, int64_t dim)
Return the dimension of the given tensor value.
Definition: TensorOps.cpp:56
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:66
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:1282
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
std::pair< int64_t, OpFoldResult > getSimplifiedOfrAndStaticSizePair(OpFoldResult ofr, Builder &b)
Given OpFoldResult representing dim size value (*), generates a pair of sizes:
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
Rewrites a tensor::PackOp into a sequence of:
Definition: Transforms.h:1552
LogicalResult matchAndRewrite(tensor::PackOp packOp, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tensor::UnPackOp unpackOp, PatternRewriter &rewriter) const override
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:991
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