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