MLIR 24.0.0git
Vectorization.cpp
Go to the documentation of this file.
1//===- Vectorization.cpp - Implementation of linalg Vectorization ---------===//
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 the linalg dialect Vectorization transformations.
10//
11//===----------------------------------------------------------------------===//
13
28#include "mlir/IR/AffineExpr.h"
29#include "mlir/IR/AffineMap.h"
30#include "mlir/IR/Builders.h"
35#include "mlir/IR/Value.h"
36#include "mlir/Support/LLVM.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/Sequence.h"
40#include "llvm/ADT/SmallPtrSet.h"
41#include "llvm/ADT/SmallVector.h"
42#include "llvm/ADT/SmallVectorExtras.h"
43#include "llvm/ADT/TypeSwitch.h"
44#include "llvm/Support/DebugLog.h"
45#include "llvm/Support/InterleavedRange.h"
46#include "llvm/Support/MathExtras.h"
47#include "llvm/Support/raw_ostream.h"
48#include <optional>
49
50using namespace mlir;
51using namespace mlir::linalg;
52
53#define DEBUG_TYPE "linalg-vectorization"
54
55/// Try to vectorize `convOp` as a convolution.
56static FailureOr<Operation *>
57vectorizeConvolution(RewriterBase &rewriter, LinalgOp convOp,
58 ArrayRef<int64_t> inputVecSizes = {},
59 ArrayRef<bool> inputVecScalableFlags = {},
60 bool flatten1DDepthwiseConv = false);
61
62/// Vectorize tensor::InsertSliceOp with:
63/// * vector::TransferReadOp + vector::TransferWriteOp
64/// The vector sizes are either:
65/// * user-provided in `inputVectorSizes`, or
66/// * inferred from the static dims in the input and output tensors.
67/// Bails out if:
68/// * vector sizes are not user-provided, and
69/// * at least one dim is dynamic (in both the input and output tensors),
70/// or if the strides are not 1.
71///
72/// Before:
73/// !t_in_type = tensor<1x2x3xf32>
74/// !t_out_type = tensor<9x8x7x1x2x3xf32>
75/// !v_type = vector<1x2x3xf32>
76/// %inserted_slice = tensor.insert_slice %src into %dest ... : !t_in_type
77/// into !t_out_type
78/// After:
79/// %read = vector.transfer_read %src[...], %pad ... : !t_in_type, !v_type
80/// %write = vector.transfer_write %read, %dest ... : !v_type, !t_out_type
81static LogicalResult
82vectorizeAsInsertSliceOp(RewriterBase &rewriter, tensor::InsertSliceOp sliceOp,
83 ArrayRef<int64_t> inputVectorSizes,
84 SmallVectorImpl<Value> &newResults);
85
86/// Returns the effective Pad value for the input op, provided it's a scalar.
87///
88/// Many Ops exhibit pad-like behaviour, but this isn't always explicit. If
89/// this Op performs padding, retrieve the padding value provided that it's
90/// a scalar and static/fixed for all the padded values. Returns an empty value
91/// otherwise.
93
94/// Helper function to extract the input slices after filter is unrolled along
95/// kw.
98 int64_t nSize, int64_t wSize, int64_t cSize,
99 int64_t kwSize, int strideW, int dilationW,
100 int64_t wSizeStep, bool isSingleChanneled) {
102 if (isSingleChanneled) {
103 // Extract input slice of size {wSizeStep} @ [w + kw] for non-channeled
104 // convolution.
105 SmallVector<int64_t> sizes = {wSizeStep};
106 SmallVector<int64_t> strides = {1};
107 for (int64_t kw = 0; kw < kwSize; ++kw) {
108 for (int64_t w = 0; w < wSize; w += wSizeStep) {
109 result.push_back(vector::ExtractStridedSliceOp::create(
110 rewriter, loc, input, /*offsets=*/ArrayRef<int64_t>{w + kw}, sizes,
111 strides));
112 }
113 }
114 } else {
115 // Extract lhs slice of size {n, wSizeStep, c} @ [0, sw * w + dw * kw, 0]
116 // for channeled convolution.
117 SmallVector<int64_t> sizes = {nSize, wSizeStep, cSize};
118 SmallVector<int64_t> strides = {1, 1, 1};
119 for (int64_t kw = 0; kw < kwSize; ++kw) {
120 for (int64_t w = 0; w < wSize; w += wSizeStep) {
121 result.push_back(vector::ExtractStridedSliceOp::create(
122 rewriter, loc, input,
123 /*offsets=*/ArrayRef<int64_t>{0, w * strideW + kw * dilationW, 0},
124 sizes, strides));
125 }
126 }
127 }
128 return result;
129}
130
131/// Helper function to extract the filter slices after filter is unrolled along
132/// kw.
134 Location loc, Value filter,
135 int64_t kwSize) {
137 // Extract rhs slice of size [{c, f} for channeled convolutions and {1} for
138 // non-chanelled convolution] @ [kw].
139 for (int64_t kw = 0; kw < kwSize; ++kw) {
140 result.push_back(vector::ExtractOp::create(
141 rewriter, loc, filter, /*offsets=*/ArrayRef<int64_t>{kw}));
142 }
143 return result;
144}
145
146/// Helper function to extract the result slices after filter is unrolled along
147/// kw.
150 int64_t nSize, int64_t wSize, int64_t fSize,
151 int64_t wSizeStep, bool isSingleChanneled) {
153 if (isSingleChanneled) {
154 // Extract res slice: {wSizeStep} @ [w] for non-channeled convolution.
155 SmallVector<int64_t> sizes = {wSizeStep};
156 SmallVector<int64_t> strides = {1};
157 for (int64_t w = 0; w < wSize; w += wSizeStep) {
158 result.push_back(vector::ExtractStridedSliceOp::create(
159 rewriter, loc, res, /*offsets=*/ArrayRef<int64_t>{w}, sizes,
160 strides));
161 }
162 } else {
163 // Extract res slice: {n, wSizeStep, f} @ [0, w, 0] for channeled
164 // convolution.
165 SmallVector<int64_t> sizes = {nSize, wSizeStep, fSize};
166 SmallVector<int64_t> strides = {1, 1, 1};
167 for (int64_t w = 0; w < wSize; w += wSizeStep) {
168 result.push_back(vector::ExtractStridedSliceOp::create(
169 rewriter, loc, res, /*offsets=*/ArrayRef<int64_t>{0, w, 0}, sizes,
170 strides));
171 }
172 }
173 return result;
174}
175
176/// Helper function to insert the computed result slices.
178 Value res, int64_t wSize, int64_t wSizeStep,
179 SmallVectorImpl<Value> &resVals,
180 bool isSingleChanneled) {
181
182 if (isSingleChanneled) {
183 // Write back res slice: {wSizeStep} @ [w] for non-channeled convolution.
184 // This does not depend on kw.
185 SmallVector<int64_t> strides = {1};
186 for (int64_t w = 0; w < wSize; w += wSizeStep) {
187 res = vector::InsertStridedSliceOp::create(
188 rewriter, loc, resVals[w], res, /*offsets=*/ArrayRef<int64_t>{w},
189 strides);
190 }
191 } else {
192 // Write back res slice: {n, wSizeStep, f} @ [0, w, 0] for channeled
193 // convolution. This does not depend on kw.
194 SmallVector<int64_t> strides = {1, 1, 1};
195 for (int64_t w = 0; w < wSize; w += wSizeStep) {
196 res = vector::InsertStridedSliceOp::create(
197 rewriter, loc, resVals[w], res,
198 /*offsets=*/ArrayRef<int64_t>{0, w, 0}, strides);
199 }
200 }
201 return res;
202}
203
204/// Contains the vectorization state and related methods used across the
205/// vectorization process of a given operation.
207 VectorizationState(RewriterBase &rewriter) : rewriterGuard(rewriter) {}
208
209 /// Initializes the vectorization state, including the computation of the
210 /// canonical vector shape for vectorization.
211 LogicalResult initState(RewriterBase &rewriter, LinalgOp linalgOp,
212 ArrayRef<int64_t> inputVectorSizes,
213 ArrayRef<bool> inputScalableVecDims,
214 bool assumeDynamicDimsMatchVecSizes = false);
215
216 /// Returns the canonical vector shape used to vectorize the iteration space.
217 ArrayRef<int64_t> getCanonicalVecShape() const { return canonicalVecShape; }
218
219 /// Returns the vector dimensions that are scalable in the canonical vector
220 /// shape.
221 ArrayRef<bool> getScalableVecDims() const { return scalableVecDims; }
222
223 /// Returns a vector type of the provided `elementType` with the canonical
224 /// vector shape and the corresponding fixed/scalable dimensions bit. If
225 /// `dimPermutation` is provided, the canonical vector dimensions are permuted
226 /// accordingly.
228 Type elementType,
229 std::optional<AffineMap> dimPermutation = std::nullopt) const {
231 SmallVector<bool> scalableDims;
232 if (dimPermutation.has_value()) {
234 applyPermutationMap<int64_t>(*dimPermutation, canonicalVecShape);
235 scalableDims =
236 applyPermutationMap<bool>(*dimPermutation, scalableVecDims);
237 } else {
238 vectorShape.append(canonicalVecShape.begin(), canonicalVecShape.end());
239 scalableDims.append(scalableVecDims.begin(), scalableVecDims.end());
240 }
241
242 return VectorType::get(vectorShape, elementType, scalableDims);
243 }
244
245 /// Masks an operation with the canonical vector mask if the operation needs
246 /// masking. Returns the masked operation or the original operation if masking
247 /// is not needed. If provided, the canonical mask for this operation is
248 /// permuted using `maybeIndexingMap`.
249 Operation *
250 maskOperation(RewriterBase &rewriter, Operation *opToMask, LinalgOp linalgOp,
251 std::optional<AffineMap> maybeIndexingMap = std::nullopt);
252
253 /// Create or retrieve an existing mask value for the canonical vector
254 /// iteration space. If `maybeMaskingMap` the mask is permuted using that
255 /// permutation map. If a new mask is created, it will be cached for future
256 /// users. Returns a null value if no mask is needed.
257 Value
258 getOrCreateMaskFor(RewriterBase &rewriter, LinalgOp linalgOp,
259 std::optional<AffineMap> maybeMaskingMap = std::nullopt);
260
261private:
262 /// Initializes the iteration space static sizes using the Linalg op
263 /// information. This may become more complicated in the future.
264 void initIterSpaceStaticSizes(LinalgOp linalgOp) {
265 iterSpaceStaticSizes.append(linalgOp.getStaticLoopRanges());
266 }
267
268 /// Generates 'arith.constant' and 'tensor/memref.dim' operations for
269 /// all the static and dynamic dimensions of the iteration space to be
270 /// vectorized and store them in `iterSpaceValueSizes`.
271 LogicalResult precomputeIterSpaceValueSizes(RewriterBase &rewriter,
272 LinalgOp linalgOp);
273
274 /// Check whether this permutation map can be used for masking. At the
275 /// moment we only make sure that there are no broadcast dimensions, but this
276 /// might change if indexing maps evolve.
277 bool isValidMaskingMap(AffineMap maskingMap) {
278 return maskingMap.getBroadcastDims().empty();
279 }
280
281 /// Turn the input indexing map into a valid masking map.
282 ///
283 /// The input indexing map may contain "zero" results, e.g.:
284 /// (d0, d1, d2, d3) -> (d2, d1, d0, 0)
285 /// Applying such maps to canonical vector shapes like this one:
286 /// (1, 16, 16, 4)
287 /// would yield an invalid vector shape like this:
288 /// (16, 16, 1, 0)
289 /// Instead, drop the broadcasting dims that make no sense for masking perm.
290 /// maps:
291 /// (d0, d1, d2, d3) -> (d2, d1, d0)
292 /// This way, the corresponding vector/mask type will be:
293 /// vector<16x16x1xty>
294 /// rather than this invalid Vector type:
295 /// vector<16x16x1x0xty>
296 AffineMap getMaskingMapFromIndexingMap(AffineMap &indexingMap) {
297 return indexingMap.dropZeroResults();
298 }
299
300 // Holds the compile-time static sizes of the iteration space to vectorize.
301 // Dynamic dimensions are represented using ShapedType::kDynamic.
302 SmallVector<int64_t> iterSpaceStaticSizes;
303
304 /// Holds the value sizes of the iteration space to vectorize. Static
305 /// dimensions are represented by 'arith.constant' and dynamic
306 /// dimensions by 'tensor/memref.dim'.
307 SmallVector<Value> iterSpaceValueSizes;
308
309 /// Holds the canonical vector shape used to vectorize the iteration space.
310 SmallVector<int64_t> canonicalVecShape;
311
312 /// Holds the vector dimensions that are scalable in the canonical vector
313 /// shape.
314 SmallVector<bool> scalableVecDims;
315
316 /// Holds the active masks for permutations of the canonical vector iteration
317 /// space.
318 DenseMap<AffineMap, Value> activeMaskCache;
319
320 /// Global vectorization guard for the incoming rewriter. It's initialized
321 /// when the vectorization state is initialized.
322 OpBuilder::InsertionGuard rewriterGuard;
323
324 /// Do all dynamic dims match the corresponding vector sizes?
325 ///
326 /// When a dynamic tensor/memref dimension matches the corresponding vector
327 /// dimension, masking can be safely skipped, despite the presence of dynamic
328 /// shapes. Use this flag with care and only for cases where you are
329 /// confident the assumption holds.
330 bool assumeDynamicDimsMatchVecSizes = false;
331};
332
333LogicalResult
334VectorizationState::precomputeIterSpaceValueSizes(RewriterBase &rewriter,
335 LinalgOp linalgOp) {
336 // TODO: Support 0-d vectors.
337 for (int vecDim = 0, end = canonicalVecShape.size(); vecDim < end; ++vecDim) {
338 if (ShapedType::isStatic(iterSpaceStaticSizes[vecDim])) {
339 // Create constant index op for static dimensions.
340 iterSpaceValueSizes.push_back(arith::ConstantIndexOp::create(
341 rewriter, linalgOp.getLoc(), iterSpaceStaticSizes[vecDim]));
342 continue;
343 }
344
345 // Find an operand defined on this dimension of the iteration space to
346 // extract the runtime dimension size.
347 Value operand;
348 unsigned operandDimPos;
349 if (failed(linalgOp.mapIterationSpaceDimToOperandDim(vecDim, operand,
350 operandDimPos)))
351 return failure();
352
353 Value dynamicDim =
354 linalgOp.hasPureTensorSemantics()
355 ? (Value)tensor::DimOp::create(rewriter, linalgOp.getLoc(), operand,
356 operandDimPos)
357 : (Value)memref::DimOp::create(rewriter, linalgOp.getLoc(), operand,
358 operandDimPos);
359 iterSpaceValueSizes.push_back(dynamicDim);
360 }
361
362 return success();
363}
364
365/// Initializes the vectorization state, including the computation of the
366/// canonical vector shape for vectorization.
367// TODO: Move this to the constructor when we can remove the failure cases.
369 LinalgOp linalgOp,
370 ArrayRef<int64_t> inputVectorSizes,
371 ArrayRef<bool> inputScalableVecDims,
372 bool assumeDimsMatchVec) {
373 assumeDynamicDimsMatchVecSizes = assumeDimsMatchVec;
374 // Initialize the insertion point.
375 rewriter.setInsertionPoint(linalgOp);
376
377 if (!inputVectorSizes.empty()) {
378 // Get the canonical vector shape from the input vector sizes provided. This
379 // path should be taken to vectorize code with dynamic shapes and when using
380 // vector sizes greater than the iteration space sizes.
381 canonicalVecShape.append(inputVectorSizes.begin(), inputVectorSizes.end());
382 scalableVecDims.append(inputScalableVecDims.begin(),
383 inputScalableVecDims.end());
384 } else {
385 // Compute the canonical vector shape from the operation shape. If there are
386 // dynamic shapes, the operation won't be vectorized. We assume all the
387 // vector dimensions are fixed.
388 canonicalVecShape = linalgOp.getStaticLoopRanges();
389 scalableVecDims.append(linalgOp.getNumLoops(), false);
390 }
391
392 LDBG() << "Canonical vector shape: " << llvm::interleaved(canonicalVecShape);
393 LDBG() << "Scalable vector dims: " << llvm::interleaved(scalableVecDims);
394
395 if (ShapedType::isDynamicShape(canonicalVecShape))
396 return failure();
397
398 // Initialize iteration space static sizes.
399 initIterSpaceStaticSizes(linalgOp);
400
401 // Generate 'arith.constant' and 'tensor/memref.dim' operations for
402 // all the static and dynamic dimensions of the iteration space, needed to
403 // compute a mask during vectorization.
404 if (failed(precomputeIterSpaceValueSizes(rewriter, linalgOp)))
405 return failure();
406
407 return success();
408}
409
411 RewriterBase &rewriter, LinalgOp linalgOp,
412 std::optional<AffineMap> maybeMaskingMap) {
413
414 assert((!maybeMaskingMap || isValidMaskingMap(*maybeMaskingMap)) &&
415 "Ill-formed masking map.");
416
417 // If no masking map was provided, use an identity map with the loop dims.
418 assert((!maybeMaskingMap || *maybeMaskingMap) &&
419 "Unexpected null mask permutation map");
420 AffineMap maskingMap =
421 maybeMaskingMap ? *maybeMaskingMap
423 linalgOp.getNumLoops(), rewriter.getContext());
424
425 LDBG() << "Masking map: " << maskingMap;
426
427 // Return the active mask for the masking map of this operation if it was
428 // already created.
429 auto activeMaskIt = activeMaskCache.find(maskingMap);
430 if (activeMaskIt != activeMaskCache.end()) {
431 Value mask = activeMaskIt->second;
432 LDBG() << "Reusing mask: " << mask;
433 return mask;
434 }
435
436 // Compute permuted projection of the iteration space to be masked and the
437 // corresponding mask shape. If the resulting iteration space dimensions are
438 // static and identical to the mask shape, masking is not needed for this
439 // operation.
440 // TODO: Improve this check. Only projected permutation indexing maps are
441 // supported.
442 SmallVector<int64_t> permutedStaticSizes =
443 applyPermutationMap<int64_t>(maskingMap, iterSpaceStaticSizes);
444 auto maskType = getCanonicalVecType(rewriter.getI1Type(), maskingMap);
445 auto maskShape = maskType.getShape();
446
447 LDBG() << "Mask shape: " << llvm::interleaved(maskShape);
448
449 if (permutedStaticSizes == maskShape) {
450 LDBG() << "Masking is not needed for masking map: " << maskingMap;
451 activeMaskCache[maskingMap] = Value();
452 return Value();
453 }
454
455 if (assumeDynamicDimsMatchVecSizes) {
456 // While for _dynamic_ dim sizes we can _assume_ that the corresponding
457 // vector sizes match, we still need to check the _static_ dim sizes. Only
458 // then we can be 100% sure that masking is not required.
459 if (llvm::all_of(llvm::zip(permutedStaticSizes, maskType.getShape()),
460 [](auto it) {
461 return std::get<0>(it) == ShapedType::kDynamic
462 ? true
463 : std::get<0>(it) == std::get<1>(it);
464 })) {
465 LDBG()
466 << "Dynamic + static dimensions match vector sizes, masking is not "
467 "required.";
468 activeMaskCache[maskingMap] = Value();
469 return Value();
470 }
471 }
472
473 // Permute the iteration space value sizes to compute the mask upper bounds.
474 SmallVector<Value> upperBounds =
475 applyPermutationMap(maskingMap, ArrayRef<Value>(iterSpaceValueSizes));
476 assert(!maskShape.empty() && !upperBounds.empty() &&
477 "Masked 0-d vectors are not supported yet");
478
479 // Create the mask based on the dimension values.
480 Value mask = vector::CreateMaskOp::create(rewriter, linalgOp.getLoc(),
481 maskType, upperBounds);
482 LDBG() << "Creating new mask: " << mask;
483 activeMaskCache[maskingMap] = mask;
484 return mask;
485}
486
487Operation *
489 LinalgOp linalgOp,
490 std::optional<AffineMap> maybeIndexingMap) {
491 LDBG() << "Trying to mask: " << *opToMask;
492
493 // No mask is needed if the operation is not maskable.
494 auto maskableOp = dyn_cast<vector::MaskableOpInterface>(opToMask);
495 if (!maskableOp) {
496 LDBG() << "Operation is not maskable";
497 return opToMask;
498 }
499 assert(!maskableOp.isMasked() &&
500 "Masking an operation that is already masked");
501
502 std::optional<AffineMap> maybeMaskingMap = std::nullopt;
503 if (maybeIndexingMap)
504 maybeMaskingMap = getMaskingMapFromIndexingMap(*maybeIndexingMap);
505
506 // Create or retrieve mask for this operation.
507 Value mask = getOrCreateMaskFor(rewriter, linalgOp, maybeMaskingMap);
508
509 if (!mask) {
510 LDBG() << "No mask required, make sure that Xfer Ops set in_bounds to true";
511 // TODO: To be removed: https://github.com/llvm/llvm-project/issues/227821
513 .Case<vector::TransferReadOp, vector::TransferWriteOp>(
514 [&](auto xferOp) {
515 SmallVector<bool> inBoundsMap =
516 SmallVector<bool>(xferOp.getInBounds().size(), true);
517 rewriter.modifyOpInPlace(xferOp, [&]() {
518 xferOp.setInBoundsAttr(rewriter.getBoolArrayAttr(inBoundsMap));
519 });
520 })
521 .Default([](Operation *op) {
522 // No-op if the operation is not an xfer read or write.
523 });
524 return opToMask;
525 }
526
527 // Wrap the operation with a new `vector.mask` and update D-U chain.
528 assert(opToMask && "Expected a valid operation to mask");
529 auto maskOp = cast<vector::MaskOp>(
530 mlir::vector::maskOperation(rewriter, opToMask, mask));
531 Operation *maskOpTerminator = &maskOp.getMaskRegion().front().back();
532
533 for (auto [resIdx, resVal] : llvm::enumerate(opToMask->getResults()))
534 rewriter.replaceAllUsesExcept(resVal, maskOp.getResult(resIdx),
535 maskOpTerminator);
536
537 LDBG() << "Masked operation: " << *maskOp;
538 return maskOp;
539}
540
541/// Given an indexing `map` coming from a LinalgOp indexing, restricted to a
542/// projectedPermutation, compress the unused dimensions to serve as a
543/// permutation_map for a vector transfer operation.
544/// For example, given a linalg op such as:
545///
546/// ```
547/// %0 = linalg.generic {
548/// indexing_maps = affine_map<(d0, d1, d2, d3, d4) -> (d4, d0, d2)>,
549/// indexing_maps = affine_map<(d0, d1, d2, d3, d4) -> (d1, d3)>
550/// }
551/// ins(%0 : tensor<2x3x4xf32>)
552/// outs(%1 : tensor<5x6xf32>)
553/// ```
554///
555/// the iteration domain size of the linalg op is 3x5x4x6x2. The first affine
556/// map is reindexed to `affine_map<(d0, d1, d2) -> (d2, d0, d1)>`, the second
557/// affine map is reindexed to `affine_map<(d0, d1) -> (d0, d1)>`.
559 assert(map.isProjectedPermutation(/*allowZeroInResults=*/true) &&
560 "expected projected permutation");
561 auto res = compressUnusedDims(map);
562 assert(res.getNumDims() ==
563 (res.getNumResults() - res.getNumOfZeroResults()) &&
564 "expected reindexed map with same number of dims and results");
565 return res;
566}
567
568/// Helper enum to represent conv1d input traversal order.
569enum class Conv1DOpOrder {
570 W, // Corresponds to non-channeled 1D convolution operation.
571 Ncw, // Corresponds to operation that traverses the input in (n, c, w) order.
572 Nwc // Corresponds to operation that traverses the input in (n, w, c) order.
573};
574
575/// Helper data structure to represent the result of vectorization for a single
576/// operation. In certain specific cases, like terminators, we do not want to
577/// propagate.
579 /// Op failed to vectorize.
581 /// Op vectorized and custom function took care of replacement logic
583 /// Op vectorized into a new Op whose results will replace original Op's
584 /// results.
586 // TODO: support values if Op vectorized to Many-Ops whose results we need to
587 // aggregate for replacement.
588};
589/// VectorizationHookResult contains the vectorized op returned from a
590/// CustomVectorizationHook. This is an internal implementation detail of
591/// linalg vectorization, not to be confused with VectorizationResult.
593 /// Return status from vectorizing the current op.
595 /// New vectorized operation to replace the current op.
596 /// Replacement behavior is specified by `status`.
598};
599
600std::optional<vector::CombiningKind>
602 using ::mlir::vector::CombiningKind;
603
604 if (!combinerOp)
605 return std::nullopt;
607 .Case<arith::AddIOp, arith::AddFOp>(
608 [&](auto op) { return CombiningKind::ADD; })
609 .Case([&](arith::AndIOp op) { return CombiningKind::AND; })
610 .Case([&](arith::MaxSIOp op) { return CombiningKind::MAXSI; })
611 .Case([&](arith::MaxUIOp op) { return CombiningKind::MAXUI; })
612 .Case([&](arith::MaximumFOp op) { return CombiningKind::MAXIMUMF; })
613 .Case([&](arith::MaxNumFOp op) { return CombiningKind::MAXNUMF; })
614 .Case([&](arith::MaximumNumFOp op) { return CombiningKind::MAXIMUMNUMF; })
615 .Case([&](arith::MinSIOp op) { return CombiningKind::MINSI; })
616 .Case([&](arith::MinUIOp op) { return CombiningKind::MINUI; })
617 .Case([&](arith::MinimumFOp op) { return CombiningKind::MINIMUMF; })
618 .Case([&](arith::MinNumFOp op) { return CombiningKind::MINNUMF; })
619 .Case([&](arith::MinimumNumFOp op) { return CombiningKind::MINIMUMNUMF; })
620 .Case<arith::MulIOp, arith::MulFOp>(
621 [&](auto op) { return CombiningKind::MUL; })
622 .Case([&](arith::OrIOp op) { return CombiningKind::OR; })
623 .Case([&](arith::XOrIOp op) { return CombiningKind::XOR; })
624 .Default(std::nullopt);
625}
626
627/// Check whether `outputOperand` is a reduction with a single combiner
628/// operation. Return the combiner operation of the reduction. Return
629/// nullptr otherwise. Multiple reduction operations would impose an
630/// ordering between reduction dimensions and is currently unsupported in
631/// Linalg. This limitation is motivated by the fact that e.g. min(max(X)) !=
632/// max(min(X))
633// TODO: use in LinalgOp verification, there is a circular dependency atm.
634static Operation *matchLinalgReduction(OpOperand *outputOperand) {
635 auto linalgOp = cast<LinalgOp>(outputOperand->getOwner());
636 unsigned outputPos =
637 outputOperand->getOperandNumber() - linalgOp.getNumDpsInputs();
638 // Only single combiner operations are supported for now.
639 SmallVector<Operation *, 4> combinerOps;
640 if (!matchReduction(linalgOp.getRegionOutputArgs(), outputPos, combinerOps) ||
641 combinerOps.size() != 1)
642 return nullptr;
643
644 // Return the combiner operation.
645 return combinerOps[0];
646}
647
648/// Broadcast `value` to a vector of `shape` if possible. Return value
649/// otherwise.
650static Value broadcastIfNeeded(OpBuilder &b, Value value, Type dstType) {
651 auto dstVecType = dyn_cast<VectorType>(dstType);
652 // If no shape to broadcast to, just return `value`.
653 if (dstVecType.getRank() == 0)
654 return value;
655 if (vector::isBroadcastableTo(value.getType(), dstVecType) !=
657 return value;
658 Location loc = b.getInsertionPoint()->getLoc();
659 return b.createOrFold<vector::BroadcastOp>(loc, dstVecType, value);
660}
661
662/// Create MultiDimReductionOp to compute the reduction for `reductionOp`. This
663/// assumes that `reductionOp` has two operands and one of them is the reduction
664/// initial value.buildMultiDimReduce
665// Note: this is a true builder that notifies the OpBuilder listener.
666// TODO: Consider moving as a static helper on the ReduceOp.
668 Value valueToReduce, Value acc,
669 ArrayRef<bool> dimsToMask) {
670 auto maybeKind = getCombinerOpKind(reduceOp);
671 assert(maybeKind && "Failed precondition: could not get reduction kind");
672 // Keep the combiner's fast-math flags on the reduction.
673 arith::FastMathFlags fastMathFlags = arith::FastMathFlags::none;
674 if (auto fmfOp = dyn_cast<arith::ArithFastMathInterface>(reduceOp))
675 fastMathFlags = fmfOp.getFastMathFlagsAttr().getValue();
676 return vector::MultiDimReductionOp::create(b, reduceOp->getLoc(),
677 valueToReduce, acc, dimsToMask,
678 *maybeKind, fastMathFlags);
679}
680
681static SmallVector<bool> getDimsToReduce(LinalgOp linalgOp) {
682 return llvm::map_to_vector(linalgOp.getIteratorTypesArray(),
684}
685
686/// Check if `op` is a linalg.reduce or a linalg.generic that has at least one
687/// reduction iterator.
688static bool hasReductionIterator(LinalgOp &op) {
689 return isa<linalg::ReduceOp>(op) ||
690 (isa<linalg::GenericOp>(op) &&
691 llvm::any_of(op.getIteratorTypesArray(), isReductionIterator));
692}
693
694/// Build a vector.transfer_write of `value` into `outputOperand` at indices set
695/// to all `0`; where `outputOperand` is an output operand of the LinalgOp
696/// currently being vectorized. If `dest` has null rank, build an memref.store.
697/// Return the produced value or null if no value is produced.
698// Note: this is a true builder that notifies the OpBuilder listener.
699// TODO: Consider moving as a static helper on the ReduceOp.
700static Value buildVectorWrite(RewriterBase &rewriter, Value value,
701 OpOperand *outputOperand,
702 VectorizationState &state) {
703 Location loc = value.getLoc();
704 auto linalgOp = cast<LinalgOp>(outputOperand->getOwner());
705 AffineMap opOperandMap = linalgOp.getMatchingIndexingMap(outputOperand);
706
707 // Compute the vector type of the value to store. This type should be an
708 // identity or projection of the canonical vector type without any permutation
709 // applied, given that any permutation in a transfer write happens as part of
710 // the write itself.
712 opOperandMap.getContext(), opOperandMap.getNumInputs(),
713 [&](AffineDimExpr dimExpr) -> bool {
714 return llvm::is_contained(opOperandMap.getResults(), dimExpr);
715 });
716 auto vectorType = state.getCanonicalVecType(
717 getElementTypeOrSelf(outputOperand->get().getType()), vectorTypeMap);
718
719 SmallVector<Value> indices(linalgOp.getRank(outputOperand),
720 arith::ConstantIndexOp::create(rewriter, loc, 0));
721
722 Operation *write;
723 if (vectorType.getRank() > 0) {
724 AffineMap writeMap = inversePermutation(reindexIndexingMap(opOperandMap));
725 value = broadcastIfNeeded(rewriter, value, vectorType);
726 assert(value.getType() == vectorType && "Incorrect type");
727 write = vector::TransferWriteOp::create(
728 rewriter, loc, value, outputOperand->get(), indices, writeMap);
729 } else {
730 // 0-d case is still special: do not invert the reindexing writeMap.
731 if (!isa<VectorType>(value.getType()))
732 value = vector::BroadcastOp::create(rewriter, loc, vectorType, value);
733 assert(value.getType() == vectorType && "Incorrect type");
734 write = vector::TransferWriteOp::create(rewriter, loc, value,
735 outputOperand->get(), indices);
736 }
737
738 write = state.maskOperation(rewriter, write, linalgOp, opOperandMap);
739
740 // If masked, set in-bounds to true. Masking guarantees that the access will
741 // be in-bounds.
742 if (auto maskOp = dyn_cast<vector::MaskingOpInterface>(write)) {
743 auto maskedWriteOp = cast<vector::TransferWriteOp>(maskOp.getMaskableOp());
744 // TODO: To be removed, see
745 // https://github.com/llvm/llvm-project/issues/227821
746 SmallVector<bool> inBounds(maskedWriteOp.getVectorType().getRank(), true);
747 maskedWriteOp.setInBoundsAttr(rewriter.getBoolArrayAttr(inBounds));
748 }
749
750 LDBG() << "vectorized op: " << *write;
751 if (!write->getResults().empty())
752 return write->getResult(0);
753 return Value();
754}
755
756// Custom vectorization precondition function type. This is intented to be used
757// with CustomVectorizationHook. Returns success if the corresponding custom
758// hook can vectorize the op.
760 std::function<LogicalResult(Operation *, bool)>;
761
762// Custom vectorization function type. Produce a vector form of Operation*
763// assuming all its vectorized operands are already in the IRMapping.
764// Return nullptr if the Operation cannot be vectorized.
766 std::function<VectorizationHookResult(Operation *, const IRMapping &)>;
767
768/// Helper function to vectorize the terminator of a `linalgOp`. New result
769/// vector values are appended to `newResults`. Return
770/// VectorizationHookStatus::NoReplace to signal the vectorization algorithm
771/// that it should not try to map produced operations and instead return the
772/// results using the `newResults` vector making them available to the
773/// vectorization algorithm for RAUW. This function is meant to be used as a
774/// CustomVectorizationHook.
777 const IRMapping &bvm, VectorizationState &state,
778 LinalgOp linalgOp, SmallVectorImpl<Value> &newResults) {
779 auto yieldOp = dyn_cast<linalg::YieldOp>(op);
780 if (!yieldOp)
782 for (const auto &output : llvm::enumerate(yieldOp.getValues())) {
783 // TODO: Scan for an opportunity for reuse.
784 // TODO: use a map.
785 Value vectorValue = bvm.lookup(output.value());
786 Value newResult =
787 buildVectorWrite(rewriter, vectorValue,
788 linalgOp.getDpsInitOperand(output.index()), state);
789 if (newResult)
790 newResults.push_back(newResult);
791 }
792
794}
795
796/// Helper function to vectorize the index operations of a `linalgOp`. Return
797/// VectorizationHookStatus::NewOp to signal the vectorization algorithm that it
798/// should map the produced operations. This function is meant to be used as a
799/// CustomVectorizationHook.
801 VectorizationState &state,
802 Operation *op,
803 LinalgOp linalgOp) {
804 IndexOp indexOp = dyn_cast<linalg::IndexOp>(op);
805 if (!indexOp)
807 auto loc = indexOp.getLoc();
808 // Compute the static loop sizes of the index op.
809 ArrayRef<int64_t> targetShape = state.getCanonicalVecShape();
810 auto dim = indexOp.getDim();
811 // Compute a one-dimensional index vector for the index op dimension.
812 auto indexVectorType =
813 VectorType::get({targetShape[dim]}, rewriter.getIndexType(),
814 state.getScalableVecDims()[dim]);
815 auto indexSteps = vector::StepOp::create(rewriter, loc, indexVectorType);
816 // Return the one-dimensional index vector if it lives in the trailing
817 // dimension of the iteration space since the vectorization algorithm in this
818 // case can handle the broadcast.
819 if (dim == targetShape.size() - 1)
821 // Otherwise permute the targetShape to move the index dimension last,
822 // broadcast the one-dimensional index vector to the permuted shape, and
823 // finally transpose the broadcasted index vector to undo the permutation.
824 auto permPattern =
825 llvm::to_vector(llvm::seq<unsigned>(0, targetShape.size()));
826 std::swap(permPattern[dim], permPattern.back());
827 auto permMap =
828 AffineMap::getPermutationMap(permPattern, linalgOp.getContext());
829
830 auto broadCastOp = vector::BroadcastOp::create(
831 rewriter, loc,
832 state.getCanonicalVecType(rewriter.getIndexType(), permMap), indexSteps);
833 SmallVector<int64_t> transposition =
834 llvm::to_vector<16>(llvm::seq<int64_t>(0, linalgOp.getNumLoops()));
835 std::swap(transposition.back(), transposition[dim]);
836 auto transposeOp =
837 vector::TransposeOp::create(rewriter, loc, broadCastOp, transposition);
839}
840
841/// Helper function to check if the tensor.extract can be vectorized by the
842/// custom hook vectorizeTensorExtract.
843static LogicalResult
845 tensor::ExtractOp extractOp = dyn_cast<tensor::ExtractOp>(op);
846 if (!extractOp)
847 return failure();
848
849 if (extractOp.getIndices().size() != 1 && !vectorizeNDExtract)
850 return failure();
851
852 // Check the index type, but only for non 0-d tensors (for which we do need
853 // access indices).
854 if (not extractOp.getIndices().empty()) {
855 if (!VectorType::isValidElementType(extractOp.getIndices()[0].getType()))
856 return failure();
857 }
858
859 if (!llvm::all_of(extractOp->getResultTypes(),
860 VectorType::isValidElementType)) {
861 return failure();
862 }
863
864 return success();
865}
866
867/// Calculates the offsets (`$index_vec`) for `vector.gather` operations
868/// generated from `tensor.extract`. The offset is calculated as follows
869/// (example using scalar values):
870///
871/// offset = extractOp.indices[0]
872/// for (i = 1; i < numIndices; i++)
873/// offset = extractOp.dimSize[i] * offset + extractOp.indices[i];
874///
875/// For tensor<45 x 80 x 15 x f32> and index [1, 2, 3], this leads to:
876/// offset = ( ( 1 ) * 80 + 2 ) * 15 + 3
878 VectorizationState &state,
879 tensor::ExtractOp extractOp,
880 const IRMapping &bvm) {
881 // The vector of indices for GatherOp should be shaped as the output vector.
882 auto indexVecType = state.getCanonicalVecType(rewriter.getIndexType());
883 auto loc = extractOp.getLoc();
884
885 Value offset = broadcastIfNeeded(
886 rewriter, bvm.lookup(extractOp.getIndices()[0]), indexVecType);
887
888 const size_t numIndices = extractOp.getIndices().size();
889 for (size_t i = 1; i < numIndices; i++) {
890 Value dimIdx = arith::ConstantIndexOp::create(rewriter, loc, i);
891
892 auto dimSize = broadcastIfNeeded(
893 rewriter,
894 tensor::DimOp::create(rewriter, loc, extractOp.getTensor(), dimIdx),
895 indexVecType);
896
897 offset = arith::MulIOp::create(rewriter, loc, offset, dimSize);
898
899 auto extractOpIndex = broadcastIfNeeded(
900 rewriter, bvm.lookup(extractOp.getIndices()[i]), indexVecType);
901
902 offset = arith::AddIOp::create(rewriter, loc, extractOpIndex, offset);
903 }
904
905 return offset;
906}
907
909
910/// Find the index of the trailing non-unit dim in linalgOp. This hook is used
911/// when checking whether `tensor.extract` Op (within a `linalg.generic` Op)
912/// represents a contiguous load operation.
913///
914/// Note that when calling this hook, it is assumed that the output vector is
915/// effectively 1D. Other cases (i.e. reading n-D vectors) should've been
916/// labelled as a gather load before entering this method.
917///
918/// Following on from the above, it is assumed that:
919/// * for statically shaped loops, when no masks are used, only one dim is !=
920/// 1 (that's what the shape of the output vector is based on).
921/// * for dynamically shaped loops, there might be more non-unit dims
922/// as the output vector type is user-specified.
923///
924/// TODO: Statically shaped loops + vector masking
925static uint64_t getTrailingNonUnitLoopDimIdx(LinalgOp linalgOp) {
926 SmallVector<int64_t> loopRanges = linalgOp.getStaticLoopRanges();
927 assert(
928 (linalgOp.hasDynamicShape() ||
929 llvm::count_if(loopRanges, [](int64_t dim) { return dim != 1; }) == 1) &&
930 "For statically shaped Linalg Ops, only one "
931 "non-unit loop dim is expected");
932 assert(!loopRanges.empty() && "Empty loops, nothing to analyse.");
933
934 size_t idx = loopRanges.size() - 1;
935 for (; idx != 0; idx--)
936 if (loopRanges[idx] != 1)
937 break;
938
939 return idx;
940}
941
942/// Checks whether `val` can be used for calculating a loop invariant index.
943static bool isLoopInvariantIdx(LinalgOp &linalgOp, Value &val,
944 VectorType resType) {
945
946 assert(((llvm::count_if(resType.getShape(),
947 [](int64_t dimSize) { return dimSize > 1; }) == 1)) &&
948 "n-D vectors are not yet supported");
949
950 auto *block = linalgOp.getBlock();
951
952 // A shared DAG has exponentially many paths; a revisit adds nothing.
954 SmallVector<Value> worklist{val};
955
956 while (!worklist.empty()) {
957 Value v = worklist.pop_back_val();
958
959 // Blocks outside _this_ linalg.generic are effectively loop invariant.
960 // However, analysing block arguments for _this_ linalg.generic Op is a bit
961 // tricky. Just bail out in the latter case.
962 // TODO: We could try analysing the corresponding affine map here.
963 if (isa<BlockArgument>(v)) {
964 if (llvm::is_contained(block->getArguments(), v))
965 return false;
966 continue;
967 }
968
969 Operation *defOp = v.getDefiningOp();
970 assert(defOp && "This is neither a block argument nor an operation result");
971
972 // IndexOp is loop invariant as long as its result remains constant across
973 // iterations. Note that for dynamic shapes, the corresponding dim will also
974 // be conservatively treated as != 1.
975 if (auto indexOp = dyn_cast<linalg::IndexOp>(defOp)) {
976 if (linalgOp.getStaticLoopRanges()[indexOp.getDim()] != 1)
977 return false;
978 continue;
979 }
980
981 auto *ancestor = block->findAncestorOpInBlock(*defOp);
982
983 // Values define outside `linalgOp` are loop invariant.
984 if (!ancestor)
985 continue;
986
987 // Values defined inside `linalgOp`, which are constant, are loop invariant.
988 if (isa<arith::ConstantOp>(ancestor))
989 continue;
990
991 if (visited.insert(ancestor).second)
992 llvm::append_range(worklist, ancestor->getOperands());
993 }
994
995 return true;
996}
997
998/// Check whether `val` could be used for calculating the trailing index for a
999/// contiguous load operation.
1000///
1001/// There are currently 3 types of values that are allowed here:
1002/// 1. loop-invariant values,
1003/// 2. values that increment by 1 with every loop iteration,
1004/// 3. results of basic arithmetic operations (linear and continuous)
1005/// involving 1., 2. and 3.
1006/// This method returns True if indeed only such values are used in calculating
1007/// `val.`
1008///
1009/// Additionally, the trailing index for a contiguous load operation should
1010/// increment by 1 with every loop iteration, i.e. be based on:
1011/// * `linalg.index <dim>` ,
1012/// where <dim> is the trailing non-unit dim of the iteration space (this way,
1013/// `linalg.index <dim>` increments by 1 with every loop iteration).
1014/// `foundIndexOp` is updated to `true` when such Op is found.
1015static bool isContiguousLoadIdx(LinalgOp &linalgOp, Value &val,
1016 bool &foundIndexOp, VectorType resType) {
1017
1018 assert(((llvm::count_if(resType.getShape(),
1019 [](int64_t dimSize) { return dimSize > 1; }) == 1)) &&
1020 "n-D vectors are not yet supported");
1021
1022 // Blocks outside _this_ linalg.generic are effectively loop invariant.
1023 // However, analysing block arguments for _this_ linalg.generic Op is a bit
1024 // tricky. Just bail out in the latter case.
1025 // TODO: We could try analysing the corresponding affine map here.
1026 auto *block = linalgOp.getBlock();
1027 if (isa<BlockArgument>(val))
1028 return !llvm::is_contained(block->getArguments(), val);
1029
1030 Operation *defOp = val.getDefiningOp();
1031 assert(defOp && "This is neither a block argument nor an operation result");
1032
1033 if (auto indexOp = dyn_cast<linalg::IndexOp>(defOp)) {
1034 auto loopDimThatIncrementsByOne = getTrailingNonUnitLoopDimIdx(linalgOp);
1035
1036 foundIndexOp = (indexOp.getDim() == loopDimThatIncrementsByOne);
1037 return true;
1038 }
1039
1040 auto *ancestor = block->findAncestorOpInBlock(*defOp);
1041
1042 if (!ancestor)
1043 return false;
1044
1045 // Conservatively reject Ops that could lead to indices with stride other
1046 // than 1.
1047 if (!isa<arith::AddIOp, arith::ConstantOp, linalg::IndexOp>(ancestor))
1048 return false;
1049
1050 bool result = false;
1051 for (auto op : ancestor->getOperands())
1052 result |= isContiguousLoadIdx(linalgOp, op, foundIndexOp, resType);
1053
1054 return result;
1055}
1056
1057/// Infer the memory access pattern for the input ExtractOp
1058///
1059/// Based on the ExtratOp result shape and the access indices, decides whether
1060/// this Op corresponds to a contiguous load (including a broadcast of a scalar)
1061/// or a gather load. When analysing the ExtractOp indices (to identify
1062/// contiguous laods), this method looks for "loop" invariant indices (e.g.
1063/// block arguments) and indices that change linearly (e.g. via `linalg.index`
1064/// Op).
1065///
1066/// Note that it is always safe to use gather load operations for contiguous
1067/// loads (albeit slow), but not vice-versa. When in doubt, bail out and assume
1068/// that `extractOp` is a gather load.
1070getTensorExtractMemoryAccessPattern(tensor::ExtractOp extractOp,
1071 LinalgOp &linalgOp, VectorType resType) {
1072
1073 auto inputShape = cast<ShapedType>(extractOp.getTensor().getType());
1074
1075 // 0. Is this a 0-D vector? If yes then this is a scalar broadcast.
1076 if (inputShape.getShape().empty())
1078
1079 // 0a. Is the result a 0-D vector? If yes, there are no iteration dimensions
1080 // so the tensor.extract is a single scalar load regardless of the index.
1081 if (resType.getRank() == 0)
1083
1084 // True for vectors that are effectively 1D, e.g. `vector<1x4x1xi32>`, false
1085 // otherwise.
1086 bool isOutput1DVector =
1087 (llvm::count_if(resType.getShape(),
1088 [](int64_t dimSize) { return dimSize > 1; }) == 1);
1089 // 1. Assume that it's a gather load when reading non-1D vector.
1090 if (!isOutput1DVector)
1092
1093 bool leadingIdxsLoopInvariant = true;
1094
1095 // 2. Analyze the leading indices of `extractOp`.
1096 // Look at the way each index is calculated and decide whether it is suitable
1097 // for a contiguous load, i.e. whether it's loop invariant. If not, it's a
1098 // gather load.
1099 auto indices = extractOp.getIndices();
1100 auto leadIndices = indices.drop_back(1);
1101
1102 for (auto [i, indexVal] : llvm::enumerate(leadIndices)) {
1103 if (inputShape.getShape()[i] == 1)
1104 continue;
1105
1106 leadingIdxsLoopInvariant &= isLoopInvariantIdx(linalgOp, indexVal, resType);
1107 }
1108
1109 if (!leadingIdxsLoopInvariant) {
1110 LDBG() << "Found gather load: " << extractOp;
1112 }
1113
1114 // 3. Analyze the trailing index for `extractOp`.
1115 // At this point we know that the leading indices are loop invariant. This
1116 // means that is potentially a scalar or a contiguous load. We can decide
1117 // based on the trailing idx.
1118 auto extractOpTrailingIdx = indices.back();
1119
1120 // 3a. Scalar broadcast load
1121 // If the trailing index is loop invariant then this is a scalar load.
1122 if (leadingIdxsLoopInvariant &&
1123 isLoopInvariantIdx(linalgOp, extractOpTrailingIdx, resType)) {
1124 LDBG() << "Found scalar broadcast load: " << extractOp;
1125
1127 }
1128
1129 // 3b. Contiguous loads
1130 // The trailing `extractOp` index should increment with every loop iteration.
1131 // This effectively means that it must be based on the trailing loop index.
1132 // This is what the following bool captures.
1133 bool foundIndexOp = false;
1134 bool isContiguousLoad = isContiguousLoadIdx(linalgOp, extractOpTrailingIdx,
1135 foundIndexOp, resType);
1136 // TODO: Support generating contiguous loads for column vectors - that will
1137 // require adding a permutation map to tranfer_read Ops.
1138 bool isRowVector = resType.getShape().back() != 1;
1139 isContiguousLoad &= (foundIndexOp && isRowVector);
1140
1141 if (isContiguousLoad) {
1142 LDBG() << "Found contigous load: " << extractOp;
1144 }
1145
1146 // 4. Fallback case - gather load.
1147 LDBG() << "Found gather load: " << extractOp;
1149}
1150
1151/// Helper function to vectorize the tensor.extract operations. Returns
1152/// VectorizationHookStatus::NewOp to signal the vectorization algorithm that it
1153/// should map the produced operations. This function is meant to be used as a
1154/// CustomVectorizationHook.
1155static VectorizationHookResult
1156vectorizeTensorExtract(RewriterBase &rewriter, VectorizationState &state,
1157 Operation *op, LinalgOp linalgOp, const IRMapping &bvm) {
1158 tensor::ExtractOp extractOp = dyn_cast<tensor::ExtractOp>(op);
1159 if (!extractOp)
1161 auto loc = extractOp.getLoc();
1162
1163 // Compute the static loop sizes of the extract op.
1164 auto resultType = state.getCanonicalVecType(extractOp.getResult().getType());
1165 auto maskConstantOp = arith::ConstantOp::create(
1166 rewriter, loc,
1167 DenseIntElementsAttr::get(state.getCanonicalVecType(rewriter.getI1Type()),
1168 /*value=*/true));
1169 auto passThruConstantOp = arith::ConstantOp::create(
1170 rewriter, loc, rewriter.getZeroAttr(resultType));
1171
1172 // Base indices are currently set to 0. We will need to re-visit if more
1173 // generic scenarios are to be supported.
1174 SmallVector<Value> baseIndices(
1175 extractOp.getIndices().size(),
1176 arith::ConstantIndexOp::create(rewriter, loc, 0));
1177
1178 VectorMemoryAccessKind memAccessKind =
1179 getTensorExtractMemoryAccessPattern(extractOp, linalgOp, resultType);
1180
1181 // 1. Handle gather access
1182 if (memAccessKind == VectorMemoryAccessKind::Gather) {
1183 Value offset = calculateGatherOffset(rewriter, state, extractOp, bvm);
1184
1185 // vector.gather is not maskable, so the iteration space mask (if any) is
1186 // passed as its mask operand.
1187 Value mask = state.getOrCreateMaskFor(rewriter, linalgOp);
1188 if (!mask)
1189 mask = maskConstantOp;
1190
1191 // Generate the gather load
1192 Operation *gatherOp = vector::GatherOp::create(
1193 rewriter, loc, resultType, extractOp.getTensor(), baseIndices, offset,
1194 mask, passThruConstantOp);
1195
1196 LDBG() << "Vectorised as gather load: " << extractOp;
1198 }
1199
1200 // 2. Handle:
1201 // a. scalar loads + broadcast,
1202 // b. contiguous loads.
1203 // Both cases use vector.transfer_read.
1204
1205 // Collect indices for `vector.transfer_read`. At this point, the indices will
1206 // either be scalars or would have been broadcast to vectors matching the
1207 // result type. For indices that are vectors, there are two options:
1208 // * for non-trailing indices, all elements are identical (contiguous
1209 // loads are identified by looking for non-trailing indices that are
1210 // invariant with respect to the corresponding linalg.generic), or
1211 // * for trailing indices, the index vector will contain values with stride
1212 // one, but for `vector.transfer_read` only the first (i.e. 0th) index is
1213 // needed.
1214 // This means that
1215 // * for scalar indices - just re-use it,
1216 // * for vector indices (e.g. `vector<1x1x4xindex>`) - extract the bottom
1217 // (0th) element and use that.
1218 SmallVector<Value> transferReadIdxs;
1219 for (size_t i = 0; i < extractOp.getIndices().size(); i++) {
1220 Value idx = bvm.lookup(extractOp.getIndices()[i]);
1221 if (idx.getType().isIndex()) {
1222 transferReadIdxs.push_back(idx);
1223 continue;
1224 }
1225
1226 auto indexAs1dVector = vector::ShapeCastOp::create(
1227 rewriter, loc,
1228 VectorType::get(resultType.getShape().back(), rewriter.getIndexType(),
1229 resultType.getScalableDims().back()),
1230 idx);
1231 transferReadIdxs.push_back(
1232 vector::ExtractOp::create(rewriter, loc, indexAs1dVector, 0));
1233 }
1234
1235 // `tensor.extract_element` is always in-bounds, hence the following holds.
1236 auto dstRank = resultType.getRank();
1237 auto srcRank = extractOp.getTensor().getType().getRank();
1238 SmallVector<bool> inBounds(dstRank, true);
1239
1240 // 2a. Handle scalar broadcast access.
1241 if (memAccessKind == VectorMemoryAccessKind::ScalarBroadcast) {
1242 MLIRContext *ctx = rewriter.getContext();
1243 SmallVector<AffineExpr> exprs(dstRank, getAffineConstantExpr(0, ctx));
1244 auto permutationMap = AffineMap::get(srcRank, 0, exprs, ctx);
1245
1246 auto transferReadOp = vector::TransferReadOp::create(
1247 rewriter, loc, resultType, extractOp.getTensor(), transferReadIdxs,
1248 /*padding=*/std::nullopt, permutationMap, inBounds);
1249
1250 Operation *readOrMaskedReadOp = transferReadOp;
1251 if (dstRank > 0) {
1252 // Mask this broadcasting xfer_read here rather than relying on the
1253 // generic path (the generic path assumes identity masking map, which
1254 // wouldn't be valid here).
1255 SmallVector<int64_t> readMaskShape = {1};
1256 auto readMaskType = VectorType::get(readMaskShape, rewriter.getI1Type());
1257 auto allTrue = vector::ConstantMaskOp::create(
1258 rewriter, loc, readMaskType, vector::ConstantMaskKind::AllTrue);
1259 readOrMaskedReadOp =
1260 mlir::vector::maskOperation(rewriter, transferReadOp, allTrue);
1261 }
1262
1263 LDBG() << "Vectorised as scalar broadcast load: " << extractOp;
1265 readOrMaskedReadOp};
1266 }
1267
1268 // 2b. Handle contiguous access.
1269 auto permutationMap = AffineMap::getMinorIdentityMap(
1270 srcRank, std::min(dstRank, srcRank), rewriter.getContext());
1271
1272 int32_t rankDiff = dstRank - srcRank;
1273 // When dstRank > srcRank, broadcast the source tensor to the unitary leading
1274 // dims so that the ranks match. This is done by extending the map with 0s.
1275 // For example, for dstRank = 3, srcRank = 2, the following map created
1276 // above:
1277 // (d0, d1) --> (d0, d1)
1278 // is extended as:
1279 // (d0, d1) --> (0, d0, d1)
1280 while (rankDiff > 0) {
1281 permutationMap = permutationMap.insertResult(
1282 mlir::getAffineConstantExpr(0, rewriter.getContext()), 0);
1283 rankDiff--;
1284 }
1285
1286 auto transferReadOp = vector::TransferReadOp::create(
1287 rewriter, loc, resultType, extractOp.getTensor(), transferReadIdxs,
1288 /*padding=*/std::nullopt, permutationMap, inBounds);
1289
1290 // Mask this contiguous xfer_read here rather than relying on the generic
1291 // path (the generic path assumes an identity masking map over all the loop
1292 // dims, which wouldn't be valid here). A contiguous load only reads the
1293 // trailing `min(dstRank, srcRank)` dims of the iteration space - the leading
1294 // dims are broadcast via `permutationMap` above - so its inferred mask is
1295 // rank-reduced. Build a masking map that projects the iteration space onto
1296 // exactly those trailing dims so the created mask matches the xfer_read.
1297 int64_t numReadDims = std::min(dstRank, srcRank);
1298 auto maskingMap = AffineMap::getMinorIdentityMap(
1299 linalgOp.getNumLoops(), numReadDims, rewriter.getContext());
1300 Operation *maskedReadOp =
1301 state.maskOperation(rewriter, transferReadOp, linalgOp, maskingMap);
1302
1303 LDBG() << "Vectorised as contiguous load: " << extractOp;
1305}
1306
1307/// Emit reduction operations if the shapes of the value to reduce is different
1308/// that the result shape.
1309// Note: this is a true builder that notifies the OpBuilder listener.
1310// TODO: Consider moving as a static helper on the ReduceOp.
1311static Operation *reduceIfNeeded(OpBuilder &b, LinalgOp linalgOp, Operation *op,
1312 Value reduceValue, Value initialValue,
1313 const IRMapping &bvm) {
1314 Value reduceVec = bvm.lookup(reduceValue);
1315 Value outputVec = bvm.lookup(initialValue);
1316 auto reduceType = dyn_cast<VectorType>(reduceVec.getType());
1317 auto outputType = dyn_cast<VectorType>(outputVec.getType());
1318 // Reduce only if needed as the value may already have been reduce for
1319 // contraction vectorization.
1320 if (!reduceType ||
1321 (outputType && reduceType.getShape() == outputType.getShape()))
1322 return nullptr;
1323 SmallVector<bool> dimsToMask = getDimsToReduce(linalgOp);
1324 return buildMultiDimReduce(b, op, reduceVec, outputVec, dimsToMask);
1325}
1326
1327/// Generic vectorization for a single operation `op`, given already vectorized
1328/// operands carried by `bvm`. Vectorization occurs as follows:
1329/// 1. Try to apply any of the `customVectorizationHooks` and return its
1330/// result on success.
1331/// 2. Clone any constant in the current scope without vectorization: each
1332/// consumer of the constant will later determine the shape to which the
1333/// constant needs to be broadcast to.
1334/// 3. Fail on any remaining non `ElementwiseMappable` op. It is the purpose
1335/// of the `customVectorizationHooks` to cover such cases.
1336/// 4. Clone `op` in vector form to a vector of shape prescribed by the first
1337/// operand of maximal rank. Other operands have smaller rank and are
1338/// broadcast accordingly. It is assumed this broadcast is always legal,
1339/// otherwise, it means one of the `customVectorizationHooks` is incorrect.
1340///
1341/// This function assumes all operands of `op` have been vectorized and are in
1342/// the `bvm` mapping. As a consequence, this function is meant to be called on
1343/// a topologically-sorted list of ops.
1344/// This function does not update `bvm` but returns a VectorizationHookStatus
1345/// that instructs the caller what `bvm` update needs to occur.
1346static VectorizationHookResult
1347vectorizeOneOp(RewriterBase &rewriter, VectorizationState &state,
1348 LinalgOp linalgOp, Operation *op, const IRMapping &bvm,
1349 ArrayRef<CustomVectorizationHook> customVectorizationHooks) {
1350 LDBG() << "vectorize op " << *op;
1351
1352 // 1. Try to apply any CustomVectorizationHook.
1353 if (!customVectorizationHooks.empty()) {
1354 for (auto &customFunc : customVectorizationHooks) {
1355 VectorizationHookResult result = customFunc(op, bvm);
1357 continue;
1358 return result;
1359 }
1360 }
1361
1362 // 2. Constant ops don't get vectorized but rather broadcasted at their users.
1363 // Clone so that the constant is not confined to the linalgOp block .
1364 if (isa<arith::ConstantOp, func::ConstantOp>(op))
1366 rewriter.clone(*op)};
1367
1368 // 3. Only ElementwiseMappable are allowed in the generic vectorization.
1371
1372 // 4 . Check if the operation is a reduction.
1373 SmallVector<std::pair<Value, Value>> reductionOperands;
1374 for (Value operand : op->getOperands()) {
1375 auto blockArg = dyn_cast<BlockArgument>(operand);
1376 if (!blockArg || blockArg.getOwner() != linalgOp.getBlock() ||
1377 blockArg.getArgNumber() < linalgOp.getNumDpsInputs())
1378 continue;
1379 SmallVector<Operation *> reductionOps;
1380 Value reduceValue = matchReduction(
1381 linalgOp.getRegionOutputArgs(),
1382 blockArg.getArgNumber() - linalgOp.getNumDpsInputs(), reductionOps);
1383 if (!reduceValue)
1384 continue;
1385 reductionOperands.push_back(std::make_pair(reduceValue, operand));
1386 }
1387 if (!reductionOperands.empty()) {
1388 assert(reductionOperands.size() == 1);
1389 Operation *reduceOp =
1390 reduceIfNeeded(rewriter, linalgOp, op, reductionOperands[0].first,
1391 reductionOperands[0].second, bvm);
1392 if (reduceOp)
1394 }
1395
1396 // 5. Generic vectorization path for ElementwiseMappable ops.
1397 // a. Get the first max ranked shape.
1398 VectorType firstMaxRankedType;
1399 for (Value operand : op->getOperands()) {
1400 auto vecOperand = bvm.lookup(operand);
1401 assert(vecOperand && "Vector operand couldn't be found");
1402
1403 auto vecType = dyn_cast<VectorType>(vecOperand.getType());
1404 if (vecType && (!firstMaxRankedType ||
1405 firstMaxRankedType.getRank() < vecType.getRank()))
1406 firstMaxRankedType = vecType;
1407 }
1408 // b. Broadcast each op if needed.
1409 SmallVector<Value> vecOperands;
1410 for (Value scalarOperand : op->getOperands()) {
1411 Value vecOperand = bvm.lookup(scalarOperand);
1412 assert(vecOperand && "Vector operand couldn't be found");
1413
1414 if (firstMaxRankedType) {
1415 auto vecType = VectorType::get(firstMaxRankedType.getShape(),
1416 getElementTypeOrSelf(vecOperand.getType()),
1417 firstMaxRankedType.getScalableDims());
1418 vecOperands.push_back(broadcastIfNeeded(rewriter, vecOperand, vecType));
1419 } else {
1420 vecOperands.push_back(vecOperand);
1421 }
1422 }
1423 // c. for elementwise, the result is the vector with the firstMaxRankedShape
1424 SmallVector<Type> resultTypes;
1425 for (Type resultType : op->getResultTypes()) {
1426 resultTypes.push_back(
1427 firstMaxRankedType
1428 ? VectorType::get(firstMaxRankedType.getShape(), resultType,
1429 firstMaxRankedType.getScalableDims())
1430 : resultType);
1431 }
1432 // d. Build and return the new op.
1434 op->getLoc(), op->getName(), resultTypes, vecOperands,
1436 /*successors=*/{}, /*numRegions=*/0);
1438 rewriter.insert(newOp)};
1439}
1440
1441/// Generic vectorization function that rewrites the body of a `linalgOp` into
1442/// vector form. Generic vectorization proceeds as follows:
1443/// 1. Verify the `linalgOp` has one non-empty region.
1444/// 2. Values defined above the region are mapped to themselves and will be
1445/// broadcasted on a per-need basis by their consumers.
1446/// 3. Each region argument is vectorized into a vector.transfer_read (or 0-d
1447/// load).
1448/// TODO: Reuse opportunities for RAR dependencies.
1449/// 4a. Register CustomVectorizationHook for YieldOp to capture the results.
1450/// 4rewriter. Register CustomVectorizationHook for IndexOp to access the
1451/// iteration indices.
1452/// 5. Iteratively call vectorizeOneOp on the region operations.
1453///
1454/// When `broadcastToMaximalCommonShape` is set to true, eager broadcasting is
1455/// performed to the maximal common vector size implied by the `linalgOp`
1456/// iteration space. This eager broadcasting is introduced in the
1457/// permutation_map of the vector.transfer_read operations. The eager
1458/// broadcasting makes it trivial to determine where broadcast, transposes and
1459/// reductions should occur, without any bookkeeping. The tradeoff is that, in
1460/// the absence of good canonicalizations, the amount of work increases.
1461/// This is not deemed a problem as we expect canonicalizations and foldings to
1462/// aggressively clean up the useless work.
1463static LogicalResult
1464vectorizeAsLinalgGeneric(RewriterBase &rewriter, VectorizationState &state,
1465 LinalgOp linalgOp,
1466 SmallVectorImpl<Value> &newResults) {
1467 LDBG() << "Vectorizing operation as linalg generic/n";
1468 Block *block = linalgOp.getBlock();
1469
1470 // 2. Values defined above the region can only be broadcast for now. Make them
1471 // map to themselves.
1472 IRMapping bvm;
1473 SetVector<Value> valuesSet;
1474 mlir::getUsedValuesDefinedAbove(linalgOp->getRegion(0), valuesSet);
1475 bvm.map(valuesSet.getArrayRef(), valuesSet.getArrayRef());
1476
1477 if (linalgOp.getNumDpsInits() == 0)
1478 return failure();
1479
1480 // 3. Turn all BBArgs into vector.transfer_read / load.
1481 Location loc = linalgOp.getLoc();
1482 Value zero = arith::ConstantIndexOp::create(rewriter, loc, 0);
1483 for (OpOperand *opOperand : linalgOp.getOpOperandsMatchingBBargs()) {
1484 BlockArgument bbarg = linalgOp.getMatchingBlockArgument(opOperand);
1485 if (linalgOp.isScalar(opOperand)) {
1486 bvm.map(bbarg, opOperand->get());
1487 continue;
1488 }
1489
1490 // 3.a. Convert the indexing map for this input/output to a transfer read
1491 // permutation map and masking map.
1492 AffineMap indexingMap = linalgOp.getMatchingIndexingMap(opOperand);
1493
1494 AffineMap readMap;
1495 VectorType readType;
1496 Type elemType = getElementTypeOrSelf(opOperand->get());
1497 if (linalgOp.isDpsInput(opOperand)) {
1498 // 3.a.i. For input reads we use the canonical vector shape.
1499 readMap = inverseAndBroadcastProjectedPermutation(indexingMap);
1500 readType = state.getCanonicalVecType(elemType);
1501 } else {
1502 // 3.a.ii. For output reads (iteration-carried dependence, e.g.,
1503 // reductions), the vector shape is computed by mapping the canonical
1504 // vector shape to the output domain and back to the canonical domain.
1505 readMap = inversePermutation(reindexIndexingMap(indexingMap));
1506 readType =
1507 state.getCanonicalVecType(elemType, readMap.compose(indexingMap));
1508 }
1509
1510 SmallVector<Value> indices(linalgOp.getShape(opOperand).size(), zero);
1511
1512 Operation *read = vector::TransferReadOp::create(
1513 rewriter, loc, readType, opOperand->get(), indices,
1514 /*padding=*/std::nullopt, readMap);
1515 read = state.maskOperation(rewriter, read, linalgOp, indexingMap);
1516 Value readValue = read->getResult(0);
1517
1518 // 3.b. If masked, set in-bounds to true. Masking guarantees that the access
1519 // will be in-bounds.
1520 if (auto maskOp = dyn_cast<vector::MaskingOpInterface>(read)) {
1521 // TODO: To be removed, see
1522 // https://github.com/llvm/llvm-project/issues/227821
1523 SmallVector<bool> inBounds(readType.getRank(), true);
1524 cast<vector::TransferReadOp>(maskOp.getMaskableOp())
1525 .setInBoundsAttr(rewriter.getBoolArrayAttr(inBounds));
1526 }
1527
1528 // 3.c. Not all ops support 0-d vectors, extract the scalar for now.
1529 // TODO: remove this.
1530 if (readType.getRank() == 0)
1531 readValue = vector::ExtractOp::create(rewriter, loc, readValue,
1533
1534 LDBG() << "New vectorized bbarg(" << bbarg.getArgNumber()
1535 << "): " << readValue;
1536 bvm.map(bbarg, readValue);
1537 bvm.map(opOperand->get(), readValue);
1538 }
1539
1541 // 4a. Register CustomVectorizationHook for yieldOp.
1542 CustomVectorizationHook vectorizeYield =
1543 [&](Operation *op, const IRMapping &bvm) -> VectorizationHookResult {
1544 return vectorizeLinalgYield(rewriter, op, bvm, state, linalgOp, newResults);
1545 };
1546 hooks.push_back(vectorizeYield);
1547
1548 // 4b. Register CustomVectorizationHook for indexOp.
1549 CustomVectorizationHook vectorizeIndex =
1550 [&](Operation *op, const IRMapping &bvm) -> VectorizationHookResult {
1551 return vectorizeLinalgIndex(rewriter, state, op, linalgOp);
1552 };
1553 hooks.push_back(vectorizeIndex);
1554
1555 // 4c. Register CustomVectorizationHook for extractOp.
1556 CustomVectorizationHook vectorizeExtract =
1557 [&](Operation *op, const IRMapping &bvm) -> VectorizationHookResult {
1558 return vectorizeTensorExtract(rewriter, state, op, linalgOp, bvm);
1559 };
1560 hooks.push_back(vectorizeExtract);
1561
1562 // 5. Iteratively call `vectorizeOneOp` to each op in the slice.
1563 for (Operation &op : block->getOperations()) {
1565 vectorizeOneOp(rewriter, state, linalgOp, &op, bvm, hooks);
1567 LDBG() << "failed to vectorize: " << op;
1568 return failure();
1569 }
1570 if (result.status == VectorizationHookStatus::NewOp) {
1571 Operation *maybeMaskedOp =
1572 state.maskOperation(rewriter, result.newOp, linalgOp);
1573 LDBG() << "New vector op: " << *maybeMaskedOp;
1574 bvm.map(op.getResults(), maybeMaskedOp->getResults());
1575 }
1576 }
1577
1578 return success();
1579}
1580
1581/// Given the re-associations, "collapses" the input Vector type
1582///
1583/// This is similar to CollapseShapeOp::inferCollapsedType with two notable
1584/// differences:
1585/// * We can safely assume that there are no dynamic sizes.
1586/// * Scalable flags are updated alongside regular dims.
1587///
1588/// When collapsing scalable flags, conservatively avoids cases with two
1589/// scalable dims. We could re-visit this in the future.
1590///
1591/// EXAMPLE:
1592/// type = vector<4x16x[8]x16xf32>
1593/// reassociation = [(d0, d1, d2, d3) -> (d0, d1),
1594/// (d0, d1, d2, d3) -> (d2, d3)]
1595/// Result:
1596/// vector<64x[128]xf32>
1597static VectorType getCollapsedVecType(VectorType type,
1598 ArrayRef<AffineMap> reassociation) {
1599 assert(type.getNumScalableDims() < 2 &&
1600 "Collapsing more than 1 scalable dim is not supported ATM");
1601
1602 // Use the fact that reassociation is valid to simplify the logic: only use
1603 // each map's rank.
1604 assert(isReassociationValid(reassociation) && "invalid reassociation");
1605
1606 auto shape = type.getShape();
1607 auto scalableFlags = type.getScalableDims();
1608 SmallVector<int64_t> newShape;
1609 SmallVector<bool> newScalableFlags;
1610
1611 unsigned currentDim = 0;
1612 for (AffineMap m : reassociation) {
1613 unsigned dim = m.getNumResults();
1614 int64_t size = 1;
1615 bool flag = false;
1616 for (unsigned d = 0; d < dim; ++d) {
1617 size *= shape[currentDim + d];
1618 flag |= scalableFlags[currentDim + d];
1619 }
1620 newShape.push_back(size);
1621 newScalableFlags.push_back(flag);
1622 currentDim += dim;
1623 }
1624
1625 return VectorType::get(newShape, type.getElementType(), newScalableFlags);
1626}
1627
1628/// Vectorize `linalg.pack` as:
1629/// * xfer_read -> shape_cast -> transpose -> xfer_write
1630///
1631/// The input-vector-sizes specify the _write_ vector sizes (i.e. the vector
1632/// sizes for the xfer_write operation). This is sufficient to infer the other
1633/// vector sizes required here.
1634///
1635/// If the vector sizes are not provided:
1636/// * the vector sizes are determined from the destination tensor static shape.
1637///
1638/// EXAMPLE (no vector sizes):
1639/// ```
1640/// %pack = tensor.pack %src
1641/// inner_dims_pos = [2, 1]
1642/// inner_tiles = [16, 2]
1643/// into %dst : tensor<32x8x16xf32> -> tensor<32x4x1x16x2xf32>
1644/// ``
1645/// is vectorizes as:
1646/// ```
1647/// %read = vector.transfer_read %src
1648/// : tensor<32x7x16xf32>, vector<32x8x16xf32>
1649/// %sc = vector.shape_cast %read
1650/// : vector<32x8x16xf32> to vector<32x4x2x1x16xf32>
1651/// %tr = vector.transpose %sc, [0, 1, 3, 4, 2]
1652/// : vector<32x4x2x1x16xf32> to vector<32x4x1x16x2xf32>
1653/// %write = vector.transfer_write %tr into %dest
1654/// : vector<32x4x1x16x2xf32>, tensor<32x4x1x16x2xf32>
1655/// ```
1656static LogicalResult
1657vectorizeAsTensorPackOp(RewriterBase &rewriter, linalg::PackOp packOp,
1658 ArrayRef<int64_t> inputVectorSizes,
1659 SmallVectorImpl<Value> &newResults) {
1660 if (!inputVectorSizes.empty()) {
1661 assert(inputVectorSizes.size() == packOp.getDestRank() &&
1662 "Invalid number of input vector sizes!");
1663 }
1664
1665 // TODO: Introduce a parent class that will handle the insertion point update.
1666 OpBuilder::InsertionGuard g(rewriter);
1667 rewriter.setInsertionPoint(packOp);
1668
1669 Location loc = packOp.getLoc();
1670 std::optional<Value> padValue = packOp.getPaddingValue()
1671 ? std::optional(packOp.getPaddingValue())
1672 : std::nullopt;
1673
1674 SmallVector<int64_t> destShape =
1675 SmallVector<int64_t>(packOp.getDestType().getShape());
1676
1677 // This is just a convenience alias to clearly communicate that the input
1678 // vector sizes determine the _write_ sizes.
1679 ArrayRef<int64_t> &writeVectorSizes = inputVectorSizes;
1680
1681 // In the absence of input-vector-sizes, use the _static_ input tensor shape.
1682 if (writeVectorSizes.empty()) {
1683 if (ShapedType::isDynamicShape(destShape))
1684 return rewriter.notifyMatchFailure(packOp,
1685 "unable to infer vector sizes");
1686
1687 writeVectorSizes = destShape;
1688 }
1689
1690 // Compute pre-transpose-write-vector-type, i.e. the write vector type
1691 // _before_ the transposition (i.e. before dimension permutation). This is
1692 // done by inverting the permutation/transposition that's part of the Pack
1693 // operation. This type is required to:
1694 // 1) compute the read vector type for masked-read below, and
1695 // 2) generate shape-cast Op below that expands the read vector type.
1696 PackingMetadata packMetadata;
1697 SmallVector<int64_t> preTransposeWriteVecSizses(writeVectorSizes);
1698 auto destInvPermutation = getPackInverseDestPerm(packOp, packMetadata);
1699 applyPermutationToVector(preTransposeWriteVecSizses, destInvPermutation);
1700 auto preTransposeWriteVecType =
1701 VectorType::get(preTransposeWriteVecSizses,
1702 packOp.getResult().getType().getElementType());
1703
1704 // Compute vector type for the _read_ opeartion. This is simply
1705 // pre-transpose-write-vector-type with the dimensions collapsed
1706 // as per the Pack operation.
1707 VectorType readVecType = getCollapsedVecType(
1708 preTransposeWriteVecType,
1710 rewriter.getContext(), packMetadata.reassociations)));
1711
1712 // Create masked TransferReadOp.
1713 auto maskedRead = vector::createReadOrMaskedRead(
1714 rewriter, loc, packOp.getSource(), readVecType, padValue);
1715
1716 // Create ShapeCastOp.
1717 auto shapeCastOp = vector::ShapeCastOp::create(
1718 rewriter, loc, preTransposeWriteVecType, maskedRead);
1719
1720 // Create TransposeOp.
1721 auto destPermutation = invertPermutationVector(destInvPermutation);
1722 auto transposeOp = vector::TransposeOp::create(
1723 rewriter, loc, shapeCastOp.getResult(), destPermutation);
1724
1725 // Create TransferWriteOp.
1726 Operation *write = vector::createWriteOrMaskedWrite(
1727 rewriter, loc, transposeOp.getResult(), packOp.getDest());
1728 newResults.push_back(write->getResult(0));
1729 return success();
1730}
1731
1732/// Vectorize `linalg.unpack` as:
1733/// * xfer_read -> vector.transpose -> vector.shape_cast -> xfer_write
1734///
1735/// The input-vector-sizes specify the _read_ vector sizes (i.e. the vector
1736/// sizes for the xfer_read operation). This is sufficient to infer the other
1737/// vector sizes required here.
1738///
1739/// If the vector sizes are not provided:
1740/// * the vector sizes are determined from the input tensor static shape.
1741///
1742/// EXAMPLE (no vector sizes):
1743/// ```
1744/// %unpack = linalg.unpack %src
1745/// inner_dims_pos = [0, 1]
1746/// inner_tiles = [8, 8]
1747/// into %dest : tensor<1x1x8x8xf32> -> tensor<8x8xf32>
1748/// ```
1749/// is vectorized as:
1750/// ```
1751/// %read = vector.transfer_read %src
1752/// : tensor<1x1x8x8xf32>, vector<1x1x8x8xf32>
1753/// %tr = vector.transpose %read, [0, 2, 1, 3]
1754/// : vector<1x1x8x8xf32> to vector<1x8x1x8xf32>
1755/// %sc = vector.shape_cast %tr
1756/// : vector<1x8x1x8xf32> to vector<8x8xf32>
1757/// %vector = vector.transfer_write %sc into %dest
1758/// : vector<8x8xf32>, tensor<8x8xf32>
1759/// ```
1760static LogicalResult
1761vectorizeAsTensorUnpackOp(RewriterBase &rewriter, linalg::UnPackOp unpackOp,
1762 ArrayRef<int64_t> inputVectorSizes,
1763 ArrayRef<bool> inputScalableVecDims,
1764 SmallVectorImpl<Value> &newResults) {
1765 if (!inputVectorSizes.empty()) {
1766 assert(inputVectorSizes.size() == unpackOp.getSourceRank() &&
1767 "Invalid number of input vector sizes!");
1768 assert(inputVectorSizes.size() == inputScalableVecDims.size() &&
1769 "Incompatible number of vector sizes and vector scalable flags!");
1770 }
1771
1772 // TODO: Introduce a parent class that will handle the insertion point update.
1773 OpBuilder::InsertionGuard g(rewriter);
1774 rewriter.setInsertionPoint(unpackOp);
1775
1776 ShapedType unpackTensorType = unpackOp.getSourceType();
1777
1778 ArrayRef<int64_t> sourceShape = unpackTensorType.getShape();
1779
1780 Location loc = unpackOp->getLoc();
1781
1782 // Obtain vector sizes for the read operation.
1783 SmallVector<int64_t> readVectorSizes(inputVectorSizes);
1784 SmallVector<bool> readScalableVectorFlags(inputScalableVecDims);
1785
1786 // In the absence of input-vector-sizes, use the _static_ input tensor shape.
1787 if (inputVectorSizes.empty()) {
1788 if (ShapedType::isDynamicShape(sourceShape))
1789 return rewriter.notifyMatchFailure(unpackOp,
1790 "Unable to infer vector sizes!");
1791
1792 readVectorSizes.assign(sourceShape.begin(), sourceShape.end());
1793 }
1794
1795 // -- Generate the read operation --
1796 VectorType readVecType =
1797 VectorType::get(readVectorSizes, unpackTensorType.getElementType(),
1798 readScalableVectorFlags);
1799 Value readResult = vector::createReadOrMaskedRead(
1800 rewriter, loc, unpackOp.getSource(), readVecType, std::nullopt);
1801
1802 // -- Generate the transpose operation --
1803 PackingMetadata packMetadata;
1804 SmallVector<int64_t> lastDimToInsertPosPerm =
1805 getUnPackInverseSrcPerm(unpackOp, packMetadata);
1806 vector::TransposeOp transposeOp = vector::TransposeOp::create(
1807 rewriter, loc, readResult, lastDimToInsertPosPerm);
1808
1809 // -- Generate the shape_cast operation --
1810 VectorType collapsedVecType = getCollapsedVecType(
1811 transposeOp.getType(),
1813 rewriter.getContext(), packMetadata.reassociations)));
1814 vector::ShapeCastOp shapeCastOp = vector::ShapeCastOp::create(
1815 rewriter, loc, collapsedVecType, transposeOp->getResult(0));
1816
1817 // -- Generate the write operation --
1818 Operation *write = vector::createWriteOrMaskedWrite(
1819 rewriter, loc, shapeCastOp.getResult(), unpackOp.getDest());
1820
1821 newResults.push_back(write->getResult(0));
1822 return success();
1823}
1824
1825/// Vectorize a `padOp` with (1) static result type, (2) constant padding value
1826/// and (3) all-zero lowPad to
1827/// `transfer_write_in_bounds(transfer_read_masked(pad_source, pad_value))`.
1828static LogicalResult
1829vectorizeAsTensorPadOp(RewriterBase &rewriter, tensor::PadOp padOp,
1830 ArrayRef<int64_t> inputVectorSizes,
1831 SmallVectorImpl<Value> &newResults) {
1832 auto padValue = padOp.getConstantPaddingValue();
1833 Location loc = padOp.getLoc();
1834
1835 // TODO: Introduce a parent class that will handle the insertion point update.
1836 OpBuilder::InsertionGuard g(rewriter);
1837 rewriter.setInsertionPoint(padOp);
1838
1839 ReifiedRankedShapedTypeDims reifiedReturnShapes;
1840 LogicalResult status =
1841 cast<ReifyRankedShapedTypeOpInterface>(padOp.getOperation())
1842 .reifyResultShapes(rewriter, reifiedReturnShapes);
1843 (void)status; // prevent unused variable warning on non-assert builds
1844 assert(succeeded(status) && "failed to reify result shapes");
1845 auto readType = VectorType::get(inputVectorSizes, padValue.getType());
1846 auto maskedRead = vector::createReadOrMaskedRead(
1847 rewriter, loc, padOp.getSource(), readType, padValue,
1848 /*useInBoundsInsteadOfMasking=*/false);
1849
1850 // Create Xfer write Op
1851 Value dest = tensor::EmptyOp::create(rewriter, loc, reifiedReturnShapes[0],
1852 padOp.getResultType().getElementType());
1853 Operation *write =
1854 vector::createWriteOrMaskedWrite(rewriter, loc, maskedRead, dest);
1855 newResults.push_back(write->getResult(0));
1856 return success();
1857}
1858
1859// TODO: probably need some extra checks for reduction followed by consumer
1860// ops that may not commute (e.g. linear reduction + non-linear instructions).
1861static LogicalResult reductionPreconditions(LinalgOp op) {
1862 if (llvm::none_of(op.getIteratorTypesArray(), isReductionIterator)) {
1863 LDBG() << "reduction precondition failed: no reduction iterator";
1864 return failure();
1865 }
1866 for (OpOperand &opOperand : op.getDpsInitsMutable()) {
1867 AffineMap indexingMap = op.getMatchingIndexingMap(&opOperand);
1868 if (indexingMap.isPermutation())
1869 continue;
1870
1871 Operation *reduceOp = matchLinalgReduction(&opOperand);
1872 if (!reduceOp || !getCombinerOpKind(reduceOp)) {
1873 LDBG() << "reduction precondition failed: reduction detection failed";
1874 return failure();
1875 }
1876 }
1877 return success();
1878}
1879
1880static LogicalResult
1881vectorizeDynamicConvOpPrecondition(linalg::LinalgOp conv,
1882 bool flatten1DDepthwiseConv) {
1883 if (flatten1DDepthwiseConv) {
1884 LDBG() << "Vectorization of flattened convs with dynamic shapes is not "
1885 "supported";
1886 return failure();
1887 }
1888
1890 LDBG() << "Not a 1D depth-wise WC conv, dynamic shapes are not supported";
1891 return failure();
1892 }
1893
1894 // Support dynamic shapes in 1D depthwise convolution, but only in the
1895 // _channel_ dimension.
1896 Value lhs = conv.getDpsInputOperand(0)->get();
1897 ArrayRef<int64_t> lhsShape = cast<ShapedType>(lhs.getType()).getShape();
1898 auto shapeWithoutCh = lhsShape.drop_back(1);
1899 if (ShapedType::isDynamicShape(shapeWithoutCh)) {
1900 LDBG() << "Dynamically-shaped op vectorization precondition failed: only "
1901 "channel dim can be dynamic";
1902 return failure();
1903 }
1904
1905 return success();
1906}
1907
1908static LogicalResult
1909vectorizeDynamicLinalgOpPrecondition(linalg::LinalgOp op,
1910 bool flatten1DDepthwiseConv) {
1912 return vectorizeDynamicConvOpPrecondition(op, flatten1DDepthwiseConv);
1913
1914 if (hasReductionIterator(op))
1915 return reductionPreconditions(op);
1916
1917 // TODO: Masking only supports dynamic element-wise ops, linalg.generic ops,
1918 // linalg.copy ops and ops that implement ContractionOpInterface for now.
1919 if (!isElementwise(op) &&
1920 !isa<linalg::GenericOp, linalg::CopyOp, linalg::ContractionOpInterface>(
1921 op.getOperation()))
1922 return failure();
1923
1924 LDBG() << "Dynamically-shaped op meets vectorization pre-conditions";
1925 return success();
1926}
1927
1928//// This hook considers two cases:
1929/// (1) If the input-vector-sizes are empty, then the vector sizes will be
1930/// infered. This is only possible when all shapes are static.
1931/// (2) If the input-vector-sizes are non-empty (i.e. user provided), then
1932/// carry out basic sanity-checking.
1933static LogicalResult
1934vectorizeUnPackOpPrecondition(linalg::UnPackOp unpackOp,
1935 ArrayRef<int64_t> inputVectorSizes) {
1936 // Pack/unpack memref transformations are unsupported. The memref forms
1937 // are mainly for bufferization and scalar lowering. Other uses are not
1938 // recommended, see #225650 for details.
1939 if (!unpackOp.hasPureTensorSemantics())
1940 return failure();
1941
1942 // If there are no input vector sizes and all shapes are static, there is
1943 // nothing left to check.
1944 if (inputVectorSizes.empty() && unpackOp.getDestType().hasStaticShape() &&
1945 unpackOp.getSourceType().hasStaticShape())
1946 return success();
1947
1948 // The number of input vector sizes must be equal to:
1949 // * read-vector-rank
1950 if (!inputVectorSizes.empty() &&
1951 (inputVectorSizes.size() != unpackOp.getSourceRank())) {
1952 LDBG() << "Incorrect number of input vector sizes";
1953 return failure();
1954 }
1955
1956 // Check the vector sizes for the read operation.
1958 unpackOp.getSourceType().getShape(), inputVectorSizes))) {
1959 LDBG() << "Invalid vector sizes for the read operation";
1960 return failure();
1961 }
1962
1963 return success();
1964}
1965
1966static LogicalResult
1967vectorizeInsertSliceOpPrecondition(tensor::InsertSliceOp sliceOp,
1968 ArrayRef<int64_t> inputVectorSizes) {
1969
1970 TypedValue<RankedTensorType> source = sliceOp.getSource();
1971 auto sourceType = source.getType();
1972 if (!VectorType::isValidElementType(sourceType.getElementType()))
1973 return failure();
1974
1975 // The write is a vector.transfer_write at the slice offsets, which cannot
1976 // express a stride.
1977 if (!sliceOp.hasUnitStride()) {
1978 LDBG() << "Only unit strides are supported";
1979 return failure();
1980 }
1981
1982 // Get the pad value.
1983 // TransferReadOp (which is used to vectorize InsertSliceOp), requires a
1984 // scalar padding value. Note that:
1985 // * for in-bounds accesses,
1986 // the value is actually irrelevant. There are 2 cases in which xfer.read
1987 // accesses are known to be in-bounds:
1988 // 1. The source shape is static (output vector sizes would be based on
1989 // the source shape and hence all memory accesses would be in-bounds),
1990 // 2. Masking is used, i.e. the output vector sizes are user-provided. In
1991 // this case it is safe to assume that all memory accesses are in-bounds.
1992 //
1993 // When the value is not known and not needed, use 0. Otherwise, bail out.
1994 Value padValue = getStaticPadVal(sliceOp);
1995 bool isOutOfBoundsRead =
1996 !sourceType.hasStaticShape() && inputVectorSizes.empty();
1997
1998 if (!padValue && isOutOfBoundsRead) {
1999 LDBG() << "Failed to get a pad value for out-of-bounds read access";
2000 return failure();
2001 }
2002 return success();
2003}
2004
2005/// Vectorize a named linalg contraction op into:
2006/// vector::TransferReadOp - Reads vectors from the operands
2007/// vector::ContractionOp - Performs contraction
2008/// vector::TransferWriteOp - Write the result vector back to the
2009/// destination
2010/// The operands shapes are preserved and loaded directly into vectors.
2011/// Any further permutations or numerical casting remain within contraction op.
2012static LogicalResult
2013vectorizeAsLinalgContraction(RewriterBase &rewriter, VectorizationState &state,
2014 LinalgOp linalgOp,
2015 SmallVectorImpl<Value> &newResults) {
2016 Location loc = linalgOp.getLoc();
2017 MLIRContext *ctx = linalgOp.getContext();
2018
2019 // For simplicity, contraction vectorization is limited to linalg named ops.
2020 // Generic op is ignored as not every arbitrary contraction body can be
2021 // expressed by a vector.contract.
2022 if (!isa<ContractionOpInterface>(linalgOp.getOperation()))
2023 return failure();
2024
2025 OpOperand *outOperand = linalgOp.getDpsInitOperand(0);
2026 Operation *reduceOp = matchLinalgReduction(outOperand);
2027 auto maybeKind = getCombinerOpKind(reduceOp);
2028 if (!maybeKind) {
2029 LDBG() << "Failed to determine contraction combining kind.";
2030 return failure();
2031 }
2032
2033 // Check that all dimensions are present in the input operands.
2034 // Arbitrary broadcasts are not supported by the vector contraction.
2035 // Broadcasts are expected to be decomposed before vectorization.
2036 AffineMap lhsMap = linalgOp.getIndexingMapsArray()[0];
2037 AffineMap rhsMap = linalgOp.getIndexingMapsArray()[1];
2038 if (getUnusedDimsBitVector({lhsMap, rhsMap}).any()) {
2039 LDBG() << "Contractions with broadcasts are not supported.";
2040 return failure();
2041 }
2042
2043 // Load operands.
2044 SmallVector<Value> vecOperands;
2045 for (OpOperand &opOperand : linalgOp->getOpOperands()) {
2046 // The operand vector shape is computed by mapping the canonical vector
2047 // shape to the operand's domain. Further permutations are left as a part of
2048 // the contraction.
2049 AffineMap indexingMap = linalgOp.getMatchingIndexingMap(&opOperand);
2050 AffineMap readMap = AffineMap::getMultiDimIdentityMap(
2051 indexingMap.getNumResults(), rewriter.getContext());
2052 Type elemType = getElementTypeOrSelf(opOperand.get());
2053 VectorType readType =
2054 state.getCanonicalVecType(elemType, readMap.compose(indexingMap));
2055
2057 rewriter, loc, opOperand.get(), readType,
2058 /*padding=*/arith::getZeroConstant(rewriter, loc, elemType),
2059 /*useInBoundsInsteadOfMasking=*/false);
2060 vecOperands.push_back(read);
2061 }
2062
2063 // Preserve the contraction's cast semantics when converting operands to the
2064 // integer accumulator type. vector.contract provides an implicit signed
2065 // integer promotion; the cases below materialize explicit casts as needed.
2066 auto castAttr = linalgOp->getAttrOfType<TypeFnAttr>("cast");
2067 bool hasUnsignedCast =
2068 castAttr && castAttr.getValue() == TypeFn::cast_unsigned;
2069 auto accType = dyn_cast<VectorType>(vecOperands[2].getType());
2070 auto accElementType =
2071 accType ? dyn_cast<IntegerType>(accType.getElementType()) : nullptr;
2072 if (accElementType && accElementType.isSignless()) {
2073 for (Value &operand : MutableArrayRef(vecOperands).take_front(2)) {
2074 auto operandType = cast<VectorType>(operand.getType());
2075 Type operandElementType = operandType.getElementType();
2076 VectorType castType = operandType.clone(accElementType);
2077
2078 if (isa<FloatType>(operandElementType)) {
2079 operand =
2080 hasUnsignedCast
2081 ? arith::FPToUIOp::create(rewriter, loc, castType, operand)
2082 .getResult()
2083 : arith::FPToSIOp::create(rewriter, loc, castType, operand)
2084 .getResult();
2085 continue;
2086 }
2087
2088 auto operandIntegerType = dyn_cast<IntegerType>(operandElementType);
2089 if (!operandIntegerType || !operandIntegerType.isSignless())
2090 continue;
2091 if (operandIntegerType.getWidth() >= accElementType.getWidth())
2092 continue;
2093 if (!hasUnsignedCast)
2094 continue;
2095
2096 // vector.contract implicitly sign-extends integer operands. Unsigned
2097 // promotion therefore requires an explicit zero extension.
2098 operand = arith::ExtUIOp::create(rewriter, loc, castType, operand);
2099 }
2100 }
2101
2102 // Remap iterators from linalg to vector.
2103 SmallVector<Attribute> iterAttrs;
2104 auto iterators = linalgOp.getIteratorTypesArray();
2105 for (utils::IteratorType iter : iterators) {
2106 auto vecIter = iter == utils::IteratorType::parallel
2107 ? vector::IteratorType::parallel
2108 : vector::IteratorType::reduction;
2109 iterAttrs.push_back(vector::IteratorTypeAttr::get(ctx, vecIter));
2110 }
2111
2112 // Create contraction.
2113 Operation *contractOp = vector::ContractionOp::create(
2114 rewriter, loc, /*lhs=*/vecOperands[0],
2115 /*rhs=*/vecOperands[1], /*acc=*/vecOperands[2],
2116 linalgOp.getIndexingMaps(), rewriter.getArrayAttr(iterAttrs), *maybeKind);
2117 contractOp = state.maskOperation(rewriter, contractOp, linalgOp);
2118
2119 // Store result.
2120 Operation *write = vector::createWriteOrMaskedWrite(
2121 rewriter, loc, contractOp->getResult(0), outOperand->get());
2122
2123 // Finalize.
2124 if (!write->getResults().empty())
2125 newResults.push_back(write->getResult(0));
2126
2127 return success();
2128}
2129
2130namespace {
2131enum class ConvOperationKind { Conv, Pool };
2132} // namespace
2133
2134static bool isCastOfBlockArgument(Operation *op) {
2135 return isa<CastOpInterface>(op) && op->getNumOperands() == 1 &&
2136 isa<BlockArgument>(op->getOperand(0));
2137}
2138
2139// Returns the ConvOperationKind of the op using reduceOp of the generic
2140// payload. If it is neither a convolution nor a pooling, it returns
2141// std::nullopt.
2142//
2143// If (region has 2 ops (reduction + yield) or 3 ops (extension + reduction
2144// + yield) and rhs is not used) then it is the body of a pooling
2145// If conv, check for single `mul` predecessor. The `mul` operands must be
2146// block arguments or extension of block arguments.
2147// Otherwise, check for one or zero `ext` predecessor. The `ext` operands
2148// must be block arguments or extension of block arguments.
2149static std::optional<ConvOperationKind>
2150getConvOperationKind(Operation *reduceOp) {
2151 int numBlockArguments =
2152 llvm::count_if(reduceOp->getOperands(), llvm::IsaPred<BlockArgument>);
2153
2154 switch (numBlockArguments) {
2155 case 1: {
2156 // Will be convolution if feeder is a MulOp.
2157 // A strength reduced version of MulOp for i1 type is AndOp which is also
2158 // supported. Otherwise, it can be pooling. This strength reduction logic
2159 // is in `buildBinaryFn` helper in the Linalg dialect.
2160 auto feedValIt = llvm::find_if_not(reduceOp->getOperands(),
2161 llvm::IsaPred<BlockArgument>);
2162 assert(feedValIt != reduceOp->operand_end() &&
2163 "Expected a non-block argument operand");
2164 Operation *feedOp = (*feedValIt).getDefiningOp();
2165 if (isCastOfBlockArgument(feedOp)) {
2166 return ConvOperationKind::Pool;
2167 }
2168
2169 if (!((isa<arith::MulIOp, arith::MulFOp>(feedOp) ||
2170 (isa<arith::AndIOp>(feedOp) &&
2171 feedOp->getResultTypes()[0].isInteger(1))) &&
2172 llvm::all_of(feedOp->getOperands(), [](Value v) {
2173 if (isa<BlockArgument>(v))
2174 return true;
2175 if (Operation *op = v.getDefiningOp())
2176 return isCastOfBlockArgument(op);
2177 return false;
2178 }))) {
2179 return std::nullopt;
2180 }
2181
2182 return ConvOperationKind::Conv;
2183 }
2184 case 2:
2185 // Must be pooling
2186 return ConvOperationKind::Pool;
2187 default:
2188 return std::nullopt;
2189 }
2190}
2191
2192static bool isSupportedPoolKind(vector::CombiningKind kind) {
2193 switch (kind) {
2194 case vector::CombiningKind::ADD:
2195 case vector::CombiningKind::MAXNUMF:
2196 case vector::CombiningKind::MAXIMUMF:
2197 case vector::CombiningKind::MAXIMUMNUMF:
2198 case vector::CombiningKind::MAXSI:
2199 case vector::CombiningKind::MAXUI:
2200 case vector::CombiningKind::MINNUMF:
2201 case vector::CombiningKind::MINIMUMF:
2202 case vector::CombiningKind::MINIMUMNUMF:
2203 case vector::CombiningKind::MINSI:
2204 case vector::CombiningKind::MINUI:
2205 return true;
2206 default:
2207 return false;
2208 }
2209}
2210
2211static LogicalResult vectorizeConvOpPrecondition(linalg::LinalgOp convOp) {
2212 auto getOperandType = [&](auto operand) {
2213 return dyn_cast<ShapedType>((operand->get()).getType());
2214 };
2215 ShapedType lhsShapedType = getOperandType(convOp.getDpsInputOperand(0));
2216 ShapedType rhsShapedType = getOperandType(convOp.getDpsInputOperand(1));
2217 ShapedType resShapedType = getOperandType(convOp.getDpsInitOperand(0));
2218 // (LHS has dimension NCW/NWC and RES has dimension NFW/NCW/NWF/NWC) OR
2219 // (non-channeled convolution -> LHS and RHS both have single dimensions).
2220 // Note that this also ensures 2D and 3D convolutions are rejected.
2221 if ((lhsShapedType.getRank() != 3 || resShapedType.getRank() != 3) &&
2222 (lhsShapedType.getRank() != 1 || resShapedType.getRank() != 1))
2223 return failure();
2224
2225 Operation *reduceOp = matchLinalgReduction(convOp.getDpsInitOperand(0));
2226 if (!reduceOp)
2227 return failure();
2228
2229 auto maybeOper = getConvOperationKind(reduceOp);
2230 if (!maybeOper.has_value())
2231 return failure();
2232
2233 auto maybeKind = getCombinerOpKind(reduceOp);
2234 // Typically convolution will have a `Add` CombiningKind but for i1 type it
2235 // can get strength reduced to `OR` which is also supported. This strength
2236 // reduction logic is in `buildBinaryFn` helper in the Linalg dialect.
2237 if (!maybeKind || ((*maybeKind != vector::CombiningKind::ADD &&
2238 *maybeKind != vector::CombiningKind::OR) &&
2239 (*maybeOper != ConvOperationKind::Pool ||
2240 !isSupportedPoolKind(*maybeKind)))) {
2241 return failure();
2242 }
2243
2244 auto rhsRank = rhsShapedType.getRank();
2245 if (*maybeOper == ConvOperationKind::Pool) {
2246 if (rhsRank != 1)
2247 return failure();
2248 } else {
2249 if (rhsRank != 1 && rhsRank != 2 && rhsRank != 3)
2250 return failure();
2251 }
2252
2253 return success();
2254}
2255
2256static LogicalResult vectorizeLinalgOpPrecondition(
2257 LinalgOp linalgOp, ArrayRef<int64_t> inputVectorSizes,
2258 bool vectorizeNDExtract, bool flatten1DDepthwiseConv) {
2259 // tensor with dimension of 0 cannot be vectorized.
2260 if (llvm::any_of(linalgOp->getOpOperands(), [&](OpOperand &operand) {
2261 return llvm::is_contained(linalgOp.getShape(&operand), 0);
2262 }))
2263 return failure();
2264 // Check API contract for input vector sizes.
2265 if (!inputVectorSizes.empty() &&
2266 failed(vector::isValidMaskedInputVector(linalgOp.getStaticLoopRanges(),
2267 inputVectorSizes)))
2268 return failure();
2269
2270 if (linalgOp.hasDynamicShape() && failed(vectorizeDynamicLinalgOpPrecondition(
2271 linalgOp, flatten1DDepthwiseConv))) {
2272 LDBG() << "Dynamically-shaped op failed vectorization pre-conditions";
2273 return failure();
2274 }
2275
2276 SmallVector<CustomVectorizationPrecondition> customPreconditions;
2277
2278 // Register CustomVectorizationPrecondition for extractOp.
2279 customPreconditions.push_back(tensorExtractVectorizationPrecondition);
2280
2281 // All types in the body should be a supported element type for VectorType.
2282 for (Operation &innerOp : linalgOp->getRegion(0).front()) {
2283 // Check if any custom hook can vectorize the inner op.
2284 if (llvm::any_of(
2285 customPreconditions,
2286 [&](const CustomVectorizationPrecondition &customPrecondition) {
2287 return succeeded(
2288 customPrecondition(&innerOp, vectorizeNDExtract));
2289 })) {
2290 continue;
2291 }
2292 if (!llvm::all_of(innerOp.getOperandTypes(),
2293 VectorType::isValidElementType)) {
2294 return failure();
2295 }
2296 if (!llvm::all_of(innerOp.getResultTypes(),
2297 VectorType::isValidElementType)) {
2298 return failure();
2299 }
2300 }
2301 if (isElementwise(linalgOp))
2302 return success();
2303
2304 // Check for both named as well as generic convolution ops.
2305 if (isaConvolutionOpInterface(linalgOp))
2306 return vectorizeConvOpPrecondition(linalgOp);
2307
2308 // TODO: the common vector shape is equal to the static loop sizes only when
2309 // all indexing maps are projected permutations. For convs and stencils the
2310 // logic will need to evolve.
2311 if (!allIndexingsAreProjectedPermutation(linalgOp)) {
2312 LDBG() << "precondition failed: not projected permutations";
2313 return failure();
2314 }
2315 if (failed(reductionPreconditions(linalgOp))) {
2316 LDBG() << "precondition failed: reduction preconditions";
2317 return failure();
2318 }
2319 return success();
2320}
2321
2322static LogicalResult
2323vectorizePackOpPrecondition(linalg::PackOp packOp,
2324 ArrayRef<int64_t> inputVectorSizes) {
2325 // Pack/unpack memref transformations are unsupported. The memref forms
2326 // are mainly for bufferization and scalar lowering. Other uses are not
2327 // recommended, see #225650 for details.
2328 if (!packOp.hasPureTensorSemantics())
2329 return failure();
2330
2331 auto padValue = packOp.getPaddingValue();
2332 Attribute cstAttr;
2333 // TODO: Relax this condiiton
2334 if (padValue && !matchPattern(padValue, m_Constant(&cstAttr))) {
2335 LDBG() << "pad value is not constant: " << packOp;
2336 return failure();
2337 }
2338
2339 ArrayRef<int64_t> resultTensorShape = packOp.getDestType().getShape();
2340 bool satisfyEmptyCond = true;
2341 if (inputVectorSizes.empty()) {
2342 if (!packOp.getDestType().hasStaticShape() ||
2343 !packOp.getSourceType().hasStaticShape())
2344 satisfyEmptyCond = false;
2345 }
2346
2347 if (!satisfyEmptyCond &&
2349 resultTensorShape.take_front(packOp.getSourceRank()),
2350 inputVectorSizes)))
2351 return failure();
2352
2353 if (llvm::any_of(packOp.getInnerTiles(), [](OpFoldResult v) {
2354 return !getConstantIntValue(v).has_value();
2355 })) {
2356 LDBG() << "inner_tiles must be constant: " << packOp;
2357 return failure();
2358 }
2359
2360 return success();
2361}
2362
2363static LogicalResult
2364vectorizePadOpPrecondition(tensor::PadOp padOp,
2365 ArrayRef<int64_t> inputVectorSizes) {
2366 auto padValue = padOp.getConstantPaddingValue();
2367 if (!padValue) {
2368 LDBG() << "pad value is not constant: " << padOp;
2369 return failure();
2370 }
2371
2372 ArrayRef<int64_t> resultTensorShape = padOp.getResultType().getShape();
2373 if (failed(vector::isValidMaskedInputVector(resultTensorShape,
2374 inputVectorSizes)))
2375 return failure();
2376
2377 // Padding with non-zero low pad values is not supported, unless the
2378 // corresponding result dim is 1 as this would require shifting the results to
2379 // the right for the low padded dims by the required amount of low padding.
2380 // However, we do support low padding if the dims being low padded have result
2381 // sizes of 1. The reason is when we have a low pad on a unit result dim, the
2382 // input size of that dimension will be dynamically zero (as the sum of the
2383 // low pad and input dim size has to be one) and hence we will create a zero
2384 // mask as the lowering logic just makes the mask one for the input dim size -
2385 // which is zero here. Hence we will load the pad value which is what we want
2386 // in this case. If the low pad is dynamically zero then the lowering is
2387 // correct as well as no shifts are necessary.
2388 if (llvm::any_of(llvm::enumerate(padOp.getMixedLowPad()),
2389 [&](const auto &en) {
2390 OpFoldResult padValue = en.value();
2391 unsigned pos = en.index();
2392 std::optional<int64_t> pad = getConstantIntValue(padValue);
2393 return (!pad.has_value() || pad.value() != 0) &&
2394 resultTensorShape[pos] != 1;
2395 })) {
2396 LDBG() << "low pad must all be zero for all non unit dims: " << padOp;
2397 return failure();
2398 }
2399
2400 return success();
2401}
2402
2403/// Preconditions for scalable vectors.
2404///
2405/// For Ops implementing the LinalgOp interface, this is quite restrictive - it
2406/// models the fact that in practice we would only make selected dimensions
2407/// scalable. For other Ops (e.g. `linalg.unpack`), this will succeed
2408/// unconditionally - we are yet to identify meaningful conditions.
2409static LogicalResult
2410vectorizeScalableVectorPrecondition(Operation *op,
2411 ArrayRef<int64_t> inputVectorSizes,
2412 ArrayRef<bool> inputScalableVecDims) {
2413 assert(inputVectorSizes.size() == inputScalableVecDims.size() &&
2414 "Number of input vector sizes and scalable dims doesn't match");
2415
2416 size_t numOfScalableDims =
2417 llvm::count_if(inputScalableVecDims, [](bool flag) { return flag; });
2418
2419 if (numOfScalableDims == 0)
2420 return success();
2421
2422 auto linalgOp = dyn_cast<LinalgOp>(op);
2423
2424 // Cond 1: Reject Ops that don't implement the LinalgOp interface, with the
2425 // exception of UnpackOp for which there is a dedicated hook.
2426 if (!linalgOp) {
2427 return success(isa<linalg::UnPackOp>(op));
2428 }
2429
2430 // Cond 2: There's been no need for more than 2 scalable dims so far
2431 if (numOfScalableDims > 2)
2432 return failure();
2433
2434 // Cond 3: Look at the configuration in `inputScalableVecDims` and verify that
2435 // it matches one of the supported cases:
2436 // 1. Exactly 1 dim is scalable and that's the _last_ non-unit parallel dim
2437 // (*).
2438 // 2. Exactly 2 dims are scalable and those are the _last two adjacent_
2439 // parallel dims.
2440 // 3. Exactly 1 reduction dim is scalable and that's the last (innermost)
2441 // dim.
2442 // The 2nd restriction above means that only Matmul-like Ops are supported
2443 // when 2 dims are scalable, e.g. :
2444 // * iterators = [parallel, parallel, reduction]
2445 // * scalable flags = [true, true, false]
2446 //
2447 // (*) Non-unit dims get folded away in practice.
2448 // TODO: Relax these conditions as good motivating examples are identified.
2449
2450 // Find the first scalable flag.
2451 bool seenNonUnitParallel = false;
2452 auto iterators = linalgOp.getIteratorTypesArray();
2453 SmallVector<bool> scalableFlags(inputScalableVecDims);
2454 int64_t idx = scalableFlags.size() - 1;
2455 while (!scalableFlags[idx]) {
2456 bool isNonUnitDim = (inputVectorSizes[idx] != 1);
2457 seenNonUnitParallel |=
2458 (iterators[idx] == utils::IteratorType::parallel && isNonUnitDim);
2459
2460 iterators.pop_back();
2461 scalableFlags.pop_back();
2462 --idx;
2463 }
2464
2465 // Analyze the iterator corresponding to the first scalable dim.
2466 switch (iterators.back()) {
2467 case utils::IteratorType::reduction: {
2468 // Check 3. above is met.
2469 if (iterators.size() != inputVectorSizes.size()) {
2470 LDBG() << "Non-trailing reduction dim requested for scalable "
2471 "vectorization";
2472 return failure();
2473 }
2474 if (isa<linalg::MatmulOp>(op)) {
2475 LDBG()
2476 << "Scalable vectorization of the reduction dim in Matmul-like ops "
2477 "is not supported";
2478 return failure();
2479 }
2480 break;
2481 }
2482 case utils::IteratorType::parallel: {
2483 // Check 1. and 2. above are met.
2484 if (seenNonUnitParallel) {
2485 LDBG() << "Inner parallel dim not requested for scalable "
2486 "vectorization";
2487 return failure();
2488 }
2489 break;
2490 }
2491 }
2492
2493 // If present, check the 2nd scalable dim. ATM, only Matmul-like Ops are
2494 // supported for which expect the folowing config:
2495 // * iterators = [parallel, parallel, reduction]
2496 // * scalable flags = [true, true, false]
2497 if (numOfScalableDims == 2) {
2498 // Disallow below case which breaks 3. above:
2499 // * iterators = [..., parallel, reduction]
2500 // * scalable flags = [..., true, true]
2501 if (iterators.back() == utils::IteratorType::reduction) {
2502 LDBG() << "Higher dim than the trailing reduction dim requested for "
2503 "scalable "
2504 "vectorizatio";
2505 return failure();
2506 }
2507 scalableFlags.pop_back();
2508 iterators.pop_back();
2509
2510 if (!scalableFlags.back() ||
2511 (iterators.back() != utils::IteratorType::parallel))
2512 return failure();
2513 }
2514
2515 // Cond 4: Only the following ops are supported in the
2516 // presence of scalable vectors
2517 return success(
2518 isElementwise(linalgOp) || isa<linalg::MatmulOp>(op) ||
2519 isa<linalg::BatchMatmulOp>(op) ||
2521 isa<linalg::MatvecOp>(op) || isa<linalg::Mmt4DOp>(op) ||
2522 isa<linalg::BatchMmt4DOp>(op) || hasReductionIterator(linalgOp));
2523}
2524
2526 Operation *op, ArrayRef<int64_t> inputVectorSizes,
2527 ArrayRef<bool> inputScalableVecDims, bool vectorizeNDExtract,
2528 bool flatten1DDepthwiseConv) {
2529
2530 if (!hasVectorizationImpl(op))
2531 return failure();
2532
2533 if (failed(vectorizeScalableVectorPrecondition(op, inputVectorSizes,
2534 inputScalableVecDims)))
2535 return failure();
2536
2538 .Case([&](linalg::LinalgOp linalgOp) {
2539 return vectorizeLinalgOpPrecondition(linalgOp, inputVectorSizes,
2540 vectorizeNDExtract,
2541 flatten1DDepthwiseConv);
2542 })
2543 .Case([&](tensor::PadOp padOp) {
2544 return vectorizePadOpPrecondition(padOp, inputVectorSizes);
2545 })
2546 .Case([&](linalg::PackOp packOp) {
2547 return vectorizePackOpPrecondition(packOp, inputVectorSizes);
2548 })
2549 .Case([&](linalg::UnPackOp unpackOp) {
2550 return vectorizeUnPackOpPrecondition(unpackOp, inputVectorSizes);
2551 })
2552 .Case([&](tensor::InsertSliceOp sliceOp) {
2553 return vectorizeInsertSliceOpPrecondition(sliceOp, inputVectorSizes);
2554 })
2555 .Default(failure());
2556}
2557
2558/// Converts affine.apply Ops to arithmetic operations.
2559static void convertAffineApply(RewriterBase &rewriter, LinalgOp linalgOp) {
2560 OpBuilder::InsertionGuard g(rewriter);
2561 auto toReplace = linalgOp.getBlock()->getOps<affine::AffineApplyOp>();
2562
2563 for (auto op : make_early_inc_range(toReplace)) {
2564 rewriter.setInsertionPoint(op);
2565 auto expanded = affine::expandAffineExpr(
2566 rewriter, op->getLoc(), op.getAffineMap().getResult(0),
2567 op.getOperands().take_front(op.getAffineMap().getNumDims()),
2568 op.getOperands().take_back(op.getAffineMap().getNumSymbols()));
2569 rewriter.replaceOp(op, expanded);
2570 }
2571}
2572
2573bool mlir::linalg::hasVectorizationImpl(Operation *op) {
2574 return isa<linalg::LinalgOp, tensor::PadOp, linalg::PackOp, linalg::UnPackOp,
2575 tensor::InsertSliceOp>(op);
2576}
2577
2578FailureOr<VectorizationResult> mlir::linalg::vectorize(
2579 RewriterBase &rewriter, Operation *op, ArrayRef<int64_t> inputVectorSizes,
2580 ArrayRef<bool> inputScalableVecDims, bool vectorizeNDExtract,
2581 bool flatten1DDepthwiseConv, bool assumeDynamicDimsMatchVecSizes,
2582 bool createNamedContraction) {
2583 LDBG() << "Attempting to vectorize: " << *op;
2584 LDBG() << "Input vector sizes: " << llvm::interleaved(inputVectorSizes);
2585 LDBG() << "Input scalable vector dims: "
2586 << llvm::interleaved(inputScalableVecDims);
2587
2588 if (failed(vectorizeOpPrecondition(op, inputVectorSizes, inputScalableVecDims,
2589 vectorizeNDExtract,
2590 flatten1DDepthwiseConv))) {
2591 LDBG() << "Vectorization pre-conditions failed";
2592 return failure();
2593 }
2594
2595 // Initialize vectorization state.
2596 VectorizationState state(rewriter);
2597 if (auto linalgOp = dyn_cast<linalg::LinalgOp>(op)) {
2598 if (failed(state.initState(rewriter, linalgOp, inputVectorSizes,
2599 inputScalableVecDims,
2600 assumeDynamicDimsMatchVecSizes))) {
2601 LDBG() << "Vectorization state couldn't be initialized";
2602 return failure();
2603 }
2604 }
2605
2606 SmallVector<Value> results;
2607 auto vectorizeResult =
2609 .Case([&](linalg::LinalgOp linalgOp) {
2610 // Check for both named as well as generic convolution ops.
2611 if (isaConvolutionOpInterface(linalgOp)) {
2612 FailureOr<Operation *> convOr = vectorizeConvolution(
2613 rewriter, linalgOp, inputVectorSizes, inputScalableVecDims,
2614 flatten1DDepthwiseConv);
2615 if (succeeded(convOr)) {
2616 llvm::append_range(results, (*convOr)->getResults());
2617 return success();
2618 }
2619
2620 LDBG() << "Unsupported convolution can't be vectorized.";
2621 return failure();
2622 }
2623
2624 if (createNamedContraction &&
2625 isa<ContractionOpInterface>(linalgOp.getOperation()))
2626 return vectorizeAsLinalgContraction(rewriter, state, linalgOp,
2627 results);
2628
2629 LDBG()
2630 << "Vectorize generic by broadcasting to the canonical vector "
2631 "shape";
2632
2633 // Pre-process before proceeding.
2634 convertAffineApply(rewriter, linalgOp);
2635
2636 // TODO: 'vectorize' takes in a 'RewriterBase' which is up-casted
2637 // to 'OpBuilder' when it is passed over to some methods like
2638 // 'vectorizeAsLinalgGeneric'. This is highly problematic: if we
2639 // erase an op within these methods, the actual rewriter won't be
2640 // notified and we will end up with read-after-free issues!
2641 return vectorizeAsLinalgGeneric(rewriter, state, linalgOp, results);
2642 })
2643 .Case([&](tensor::PadOp padOp) {
2644 return vectorizeAsTensorPadOp(rewriter, padOp, inputVectorSizes,
2645 results);
2646 })
2647 .Case([&](linalg::PackOp packOp) {
2648 return vectorizeAsTensorPackOp(rewriter, packOp, inputVectorSizes,
2649 results);
2650 })
2651 .Case([&](linalg::UnPackOp unpackOp) {
2652 return vectorizeAsTensorUnpackOp(rewriter, unpackOp,
2653 inputVectorSizes,
2654 inputScalableVecDims, results);
2655 })
2656 .Case([&](tensor::InsertSliceOp sliceOp) {
2657 return vectorizeAsInsertSliceOp(rewriter, sliceOp, inputVectorSizes,
2658 results);
2659 })
2660 .Default(failure());
2661
2662 if (failed(vectorizeResult)) {
2663 LDBG() << "Vectorization failed";
2664 return failure();
2665 }
2666
2667 return VectorizationResult{results};
2668}
2669
2670LogicalResult mlir::linalg::vectorizeCopy(RewriterBase &rewriter,
2671 memref::CopyOp copyOp) {
2672 auto srcType = cast<MemRefType>(copyOp.getSource().getType());
2673 auto dstType = cast<MemRefType>(copyOp.getTarget().getType());
2674 if (!srcType.hasStaticShape() || !dstType.hasStaticShape())
2675 return failure();
2676
2677 auto srcElementType = getElementTypeOrSelf(srcType);
2678 auto dstElementType = getElementTypeOrSelf(dstType);
2679 if (!VectorType::isValidElementType(srcElementType) ||
2680 !VectorType::isValidElementType(dstElementType))
2681 return failure();
2682
2683 auto readType = VectorType::get(srcType.getShape(), srcElementType);
2684 auto writeType = VectorType::get(dstType.getShape(), dstElementType);
2685
2686 Location loc = copyOp->getLoc();
2687 Value zero = arith::ConstantIndexOp::create(rewriter, loc, 0);
2688 SmallVector<Value> indices(srcType.getRank(), zero);
2689
2690 Value readValue = vector::TransferReadOp::create(
2691 rewriter, loc, readType, copyOp.getSource(), indices,
2692 /*padding=*/std::nullopt,
2693 rewriter.getMultiDimIdentityMap(srcType.getRank()));
2694 if (cast<VectorType>(readValue.getType()).getRank() == 0) {
2695 readValue = vector::ExtractOp::create(rewriter, loc, readValue,
2696 ArrayRef<int64_t>());
2697 readValue =
2698 vector::BroadcastOp::create(rewriter, loc, writeType, readValue);
2699 }
2700 Operation *writeValue = vector::TransferWriteOp::create(
2701 rewriter, loc, readValue, copyOp.getTarget(), indices,
2702 rewriter.getMultiDimIdentityMap(srcType.getRank()));
2703 rewriter.replaceOp(copyOp, writeValue->getResults());
2704 return success();
2705}
2706
2707//----------------------------------------------------------------------------//
2708// Misc. vectorization patterns.
2709//----------------------------------------------------------------------------//
2710/// Base pattern for rewriting tensor::PadOps whose result is consumed by a
2711/// given operation type OpTy.
2712template <typename OpTy>
2713struct VectorizePadOpUserPattern : public OpRewritePattern<tensor::PadOp> {
2714 using OpRewritePattern<tensor::PadOp>::OpRewritePattern;
2715
2716 LogicalResult matchAndRewrite(tensor::PadOp padOp,
2717 PatternRewriter &rewriter) const final {
2718 bool changed = false;
2719 // Insert users in vector, because some users may be replaced/removed.
2720 for (auto *user : llvm::to_vector<4>(padOp->getUsers()))
2721 if (auto op = dyn_cast<OpTy>(user))
2722 changed |= rewriteUser(rewriter, padOp, op).succeeded();
2723 return success(changed);
2724 }
2725
2726protected:
2727 virtual LogicalResult rewriteUser(PatternRewriter &rewriter,
2728 tensor::PadOp padOp, OpTy op) const = 0;
2729};
2730
2731/// Rewrite use of tensor::PadOp result in TransferReadOp. E.g.:
2732/// ```
2733/// %0 = tensor.pad %src ... : tensor<?x?xf32> to tensor<17x5xf32>
2734/// %r = vector.transfer_read %0[%c0, %c0], %cst
2735/// {in_bounds = [true, true]} : tensor<17x5xf32>, vector<17x5xf32>
2736/// ```
2737/// is rewritten to:
2738/// ```
2739/// %r = vector.transfer_read %src[%c0, %c0], %padding
2740/// {in_bounds = [true, true]}
2741/// : tensor<?x?xf32>, vector<17x5xf32>
2742/// ```
2743/// Note: By restricting this pattern to in-bounds TransferReadOps, we can be
2744/// sure that the original padding value %cst was never used.
2745///
2746/// This rewrite is possible if:
2747/// - `xferOp` has no out-of-bounds dims and is not masked.
2748/// - Low padding is static 0.
2749/// - Single, scalar padding value.
2750struct PadOpVectorizationWithTransferReadPattern
2751 : public VectorizePadOpUserPattern<vector::TransferReadOp> {
2752 using VectorizePadOpUserPattern<
2753 vector::TransferReadOp>::VectorizePadOpUserPattern;
2754
2755 LogicalResult rewriteUser(PatternRewriter &rewriter, tensor::PadOp padOp,
2756 vector::TransferReadOp xferOp) const override {
2757 // Low padding must be static 0.
2758 if (!padOp.hasZeroLowPad())
2759 return failure();
2760 // Pad value must be a constant.
2761 auto padValue = padOp.getConstantPaddingValue();
2762 if (!padValue)
2763 return failure();
2764 // Padding value of existing `xferOp` is unused.
2765 if (xferOp.hasOutOfBoundsDim() || xferOp.getMask() || xferOp.isMasked())
2766 return failure();
2767
2768 rewriter.modifyOpInPlace(xferOp, [&]() {
2769 SmallVector<bool> inBounds(xferOp.getVectorType().getRank(), false);
2770 xferOp->setInherentAttr(xferOp.getInBoundsAttrName(),
2771 rewriter.getBoolArrayAttr(inBounds));
2772 xferOp.getBaseMutable().assign(padOp.getSource());
2773 xferOp.getPaddingMutable().assign(padValue);
2774 });
2775
2776 return success();
2777 }
2778};
2779
2780/// Rewrite use of tensor::PadOp result in TransferWriteOp.
2781/// This pattern rewrites TransferWriteOps that write to a padded tensor
2782/// value, where the same amount of padding is immediately removed again after
2783/// the write. In such cases, the TransferWriteOp can write to the non-padded
2784/// tensor value and apply out-of-bounds masking. E.g.:
2785/// ```
2786/// %0 = tensor.extract_slice ...[...] [%s0, %s1] [1, 1]
2787/// : tensor<...> to tensor<?x?xf32>
2788/// %1 = tensor.pad %0 ... : tensor<?x?xf32> to tensor<17x5xf32>
2789/// %2 = vector.transfer_write %vec, %1[...]
2790/// : vector<17x5xf32>, tensor<17x5xf32>
2791/// %r = tensor.extract_slice %2[0, 0] [%s0, %s1] [1, 1]
2792/// : tensor<17x5xf32> to tensor<?x?xf32>
2793/// ```
2794/// is rewritten to:
2795/// ```
2796/// %0 = tensor.extract_slice ...[...] [%s0, %s1] [1, 1]
2797/// : tensor<...> to tensor<?x?xf32>
2798/// %r = vector.transfer_write %vec, %0[...] : vector<17x5xf32>,
2799/// tensor<?x?xf32>
2800/// ```
2801/// Note: It is important that the ExtractSliceOp %r resizes the result of the
2802/// TransferWriteOp to the same size as the input of the TensorPadOp (or an
2803/// even smaller size). Otherwise, %r's new (dynamic) dimensions would differ
2804/// from %r's old dimensions.
2805///
2806/// This rewrite is possible if:
2807/// - Low padding is static 0.
2808/// - `xferOp` has exactly one use, which is an ExtractSliceOp. This
2809/// ExtractSliceOp trims the same amount of padding that was added
2810/// beforehand.
2811/// - Single, scalar padding value.
2812struct PadOpVectorizationWithTransferWritePattern
2813 : public VectorizePadOpUserPattern<vector::TransferWriteOp> {
2814 using VectorizePadOpUserPattern<
2815 vector::TransferWriteOp>::VectorizePadOpUserPattern;
2816
2817 LogicalResult rewriteUser(PatternRewriter &rewriter, tensor::PadOp padOp,
2818 vector::TransferWriteOp xferOp) const override {
2819 // TODO: support 0-d corner case.
2820 if (xferOp.getTransferRank() == 0)
2821 return failure();
2822
2823 // Low padding must be static 0.
2824 if (!padOp.hasZeroLowPad())
2825 return failure();
2826 // Pad value must be a constant.
2827 auto padValue = padOp.getConstantPaddingValue();
2828 if (!padValue)
2829 return failure();
2830 // TransferWriteOp result must be directly consumed by an ExtractSliceOp.
2831 if (!xferOp->hasOneUse())
2832 return failure();
2833 auto trimPadding = dyn_cast<tensor::ExtractSliceOp>(*xferOp->user_begin());
2834 if (!trimPadding)
2835 return failure();
2836 // Only static zero offsets supported when trimming padding.
2837 if (!trimPadding.hasZeroOffset())
2838 return failure();
2839 // trimPadding must remove the amount of padding that was added earlier.
2840 if (!hasSameTensorSize(padOp.getSource(), trimPadding))
2841 return failure();
2842
2843 // Insert the new TransferWriteOp at position of the old TransferWriteOp.
2844 rewriter.setInsertionPoint(xferOp);
2845
2846 SmallVector<bool> inBounds(xferOp.getVectorType().getRank(), false);
2847 auto newXferOp = rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
2848 xferOp, padOp.getSource().getType(), xferOp.getVector(),
2849 padOp.getSource(), xferOp.getIndices(), xferOp.getPermutationMapAttr(),
2850 xferOp.getMask(), rewriter.getBoolArrayAttr(inBounds));
2851 rewriter.replaceOp(trimPadding, newXferOp->getResult(0));
2852
2853 return success();
2854 }
2855
2856 /// Check if `beforePadding` and `afterTrimming` have the same tensor size,
2857 /// i.e., same dimensions.
2858 ///
2859 /// Dimensions may be static, dynamic or mix of both. In case of dynamic
2860 /// dimensions, this function tries to infer the (static) tensor size by
2861 /// looking at the defining op and utilizing op-specific knowledge.
2862 ///
2863 /// This is a conservative analysis. In case equal tensor sizes cannot be
2864 /// proven statically, this analysis returns `false` even though the tensor
2865 /// sizes may turn out to be equal at runtime.
2866 bool hasSameTensorSize(Value beforePadding,
2867 tensor::ExtractSliceOp afterTrimming) const {
2868 // If the input to tensor::PadOp is a CastOp, try with both CastOp
2869 // result and CastOp operand.
2870 if (auto castOp = beforePadding.getDefiningOp<tensor::CastOp>())
2871 if (hasSameTensorSize(castOp.getSource(), afterTrimming))
2872 return true;
2873
2874 auto t1 = dyn_cast<RankedTensorType>(beforePadding.getType());
2875 auto t2 = dyn_cast<RankedTensorType>(afterTrimming.getType());
2876 // Only RankedTensorType supported.
2877 if (!t1 || !t2)
2878 return false;
2879 // Rank of both values must be the same.
2880 if (t1.getRank() != t2.getRank())
2881 return false;
2882
2883 // All static dimensions must be the same. Mixed cases (e.g., dimension
2884 // static in `t1` but dynamic in `t2`) are not supported.
2885 for (unsigned i = 0; i < t1.getRank(); ++i) {
2886 if (t1.isDynamicDim(i) != t2.isDynamicDim(i))
2887 return false;
2888 if (!t1.isDynamicDim(i) && t1.getDimSize(i) != t2.getDimSize(i))
2889 return false;
2890 }
2891
2892 // Nothing more to check if all dimensions are static.
2893 if (t1.getNumDynamicDims() == 0)
2894 return true;
2895
2896 // All dynamic sizes must be the same. The only supported case at the
2897 // moment is when `beforePadding` is an ExtractSliceOp (or a cast
2898 // thereof).
2899
2900 // Apart from CastOp, only ExtractSliceOp is supported.
2901 auto beforeSlice = beforePadding.getDefiningOp<tensor::ExtractSliceOp>();
2902 if (!beforeSlice)
2903 return false;
2904
2905 assert(static_cast<size_t>(t1.getRank()) ==
2906 beforeSlice.getMixedSizes().size());
2907 assert(static_cast<size_t>(t2.getRank()) ==
2908 afterTrimming.getMixedSizes().size());
2909
2910 for (unsigned i = 0; i < t1.getRank(); ++i) {
2911 // Skip static dimensions.
2912 if (!t1.isDynamicDim(i))
2913 continue;
2914 auto size1 = beforeSlice.getMixedSizes()[i];
2915 auto size2 = afterTrimming.getMixedSizes()[i];
2916
2917 // Case 1: Same value or same constant int.
2918 if (isEqualConstantIntOrValue(size1, size2))
2919 continue;
2920
2921 // Other cases: Take a deeper look at defining ops of values.
2922 auto v1 = llvm::dyn_cast_if_present<Value>(size1);
2923 auto v2 = llvm::dyn_cast_if_present<Value>(size2);
2924 if (!v1 || !v2)
2925 return false;
2926
2927 // Case 2: Both values are identical AffineMinOps. (Should not happen if
2928 // CSE is run.)
2929 auto minOp1 = v1.getDefiningOp<affine::AffineMinOp>();
2930 auto minOp2 = v2.getDefiningOp<affine::AffineMinOp>();
2931 if (minOp1 && minOp2 && minOp1.getAffineMap() == minOp2.getAffineMap() &&
2932 minOp1.getOperands() == minOp2.getOperands())
2933 continue;
2934
2935 // Add additional cases as needed.
2936 }
2937
2938 // All tests passed.
2939 return true;
2940 }
2941};
2942
2943/// Returns the effective Pad value for the input op, provided it's a scalar.
2944///
2945/// Many Ops exhibit pad-like behaviour, but this isn't always explicit. If
2946/// this Op performs padding, retrieve the padding value provided that it's
2947/// a scalar and static/fixed for all the padded values. Returns an empty value
2948/// otherwise.
2949///
2950/// TODO: This is used twice (when checking vectorization pre-conditions and
2951/// when vectorizing). Cache results instead of re-running.
2952static Value getStaticPadVal(Operation *op) {
2953 if (!op)
2954 return {};
2955
2956 // 1. vector.broadcast (f32 -> vector <...xf32>) - return the value that's
2957 // being broadcast, provided that it's a scalar.
2958 if (auto bcast = llvm::dyn_cast<vector::BroadcastOp>(op)) {
2959 auto source = bcast.getSource();
2960 if (llvm::dyn_cast<VectorType>(source.getType()))
2961 return {};
2962
2963 return source;
2964 }
2965
2966 // 2. linalg.fill - use the scalar input value that used to fill the output
2967 // tensor.
2968 if (auto fill = llvm::dyn_cast<linalg::FillOp>(op)) {
2969 return fill.getInputs()[0];
2970 }
2971
2972 // 3. tensor.generateOp - can't guarantee the value is fixed without
2973 // analysing, bail out.
2974 if (auto generate = llvm::dyn_cast<tensor::GenerateOp>(op)) {
2975 return {};
2976 }
2977
2978 // 4. vector.transfer_write - inspect the input vector that's written from. If
2979 // if contains a single value that has been broadcast (e.g. via
2980 // vector.broadcast), extract it, fail otherwise.
2981 if (auto xferWrite = llvm::dyn_cast<vector::TransferWriteOp>(op))
2982 return getStaticPadVal(xferWrite.getVector().getDefiningOp());
2983
2984 // 5. tensor.insert_slice - inspect the destination tensor. If it's larger
2985 // than the input tensor, then, provided it's constant, we'll extract the
2986 // value that was used to generate it (via e.g. linalg.fill), fail otherwise.
2987 // TODO: Clarify the semantics when the input tensor is larger than the
2988 // destination.
2989 if (auto slice = llvm::dyn_cast<tensor::InsertSliceOp>(op))
2990 return getStaticPadVal(slice.getDest().getDefiningOp());
2991
2992 return {};
2993}
2994
2995static LogicalResult
2996vectorizeAsInsertSliceOp(RewriterBase &rewriter, tensor::InsertSliceOp sliceOp,
2997 ArrayRef<int64_t> inputVectorSizes,
2998 SmallVectorImpl<Value> &newResults) {
2999 // TODO: Introduce a parent class that will handle the insertion point update.
3000 OpBuilder::InsertionGuard g(rewriter);
3001 rewriter.setInsertionPoint(sliceOp);
3002
3003 TypedValue<RankedTensorType> source = sliceOp.getSource();
3004 auto sourceType = source.getType();
3005 auto resultType = sliceOp.getResultType();
3006
3007 Value padValue = getStaticPadVal(sliceOp);
3008
3009 if (!padValue) {
3010 auto elemType = sourceType.getElementType();
3011 padValue = arith::ConstantOp::create(rewriter, sliceOp.getLoc(), elemType,
3012 rewriter.getZeroAttr(elemType));
3013 }
3014
3015 // 2. Get the vector shape
3016 // Map each source dim to its corresponding (non-dropped) result dim: for a
3017 // rank-reducing slice, dropped dims need not be the trailing ones.
3018 llvm::SmallBitVector droppedDims = sliceOp.getDroppedDims();
3019 SmallVector<int64_t> resultDimsForSourceDims;
3020 resultDimsForSourceDims.reserve(sourceType.getRank());
3021 for (int64_t resultDim = 0, end = resultType.getRank(); resultDim < end;
3022 ++resultDim)
3023 if (!droppedDims[resultDim])
3024 resultDimsForSourceDims.push_back(resultDim);
3025 assert(resultDimsForSourceDims.size() ==
3026 static_cast<size_t>(sourceType.getRank()) &&
3027 "expected one non-dropped result dim per source dim");
3028
3029 SmallVector<int64_t> vecShape;
3030 for (int64_t i = 0, end = sourceType.getRank(); i < end; ++i) {
3031 if (!inputVectorSizes.empty()) {
3032 vecShape.push_back(inputVectorSizes[i]);
3033 } else if (!sourceType.isDynamicDim(i)) {
3034 vecShape.push_back(sourceType.getDimSize(i));
3035 } else if (!resultType.isDynamicDim(resultDimsForSourceDims[i])) {
3036 // Source shape is not statically known, but result shape is.
3037 // Vectorize with size of result shape. This may be larger than the
3038 // source size.
3039 vecShape.push_back(resultType.getDimSize(resultDimsForSourceDims[i]));
3040 } else {
3041 // Neither source nor result dim of padOp is static. Cannot vectorize
3042 // the copy.
3043 return failure();
3044 }
3045 }
3046 auto vecType = VectorType::get(vecShape, sourceType.getElementType());
3047
3048 // 3. Generate TransferReadOp + TransferWriteOp
3049 auto loc = sliceOp.getLoc();
3050
3051 // Create read
3052 SmallVector<Value> readIndices(
3053 vecType.getRank(), arith::ConstantIndexOp::create(rewriter, loc, 0));
3055 rewriter, loc, source, vecType, padValue,
3056 /*useInBoundsInsteadOfMasking=*/false);
3057
3058 // Create write
3059 auto writeIndices =
3060 getValueOrCreateConstantIndexOp(rewriter, loc, sliceOp.getMixedOffsets());
3061 // For a rank-reducing slice the vector need not cover the trailing result
3062 // dims, so state which result dim each vector dim writes to.
3063 AffineMap writeMap;
3064 if (sourceType.getRank() != resultType.getRank()) {
3065 SmallVector<AffineExpr> exprs;
3066 for (int64_t resultDim : resultDimsForSourceDims)
3067 exprs.push_back(rewriter.getAffineDimExpr(resultDim));
3068 writeMap = AffineMap::get(resultType.getRank(), /*symbolCount=*/0, exprs,
3069 rewriter.getContext());
3070 }
3071
3072 Operation *write = vector::createWriteOrMaskedWrite(
3073 rewriter, loc, read, sliceOp.getDest(), writeIndices,
3074 /*useInBoundsInsteadOfMasking=*/false, writeMap);
3075
3076 // 4. Finalize
3077 newResults.push_back(write->getResult(0));
3078
3079 return success();
3080}
3081
3082/// Rewrite use of tensor::PadOp result in InsertSliceOp. E.g.:
3083/// ```
3084/// %0 = tensor.pad %src ... : tensor<?x?xf32> to tensor<17x5xf32>
3085/// %r = tensor.insert_slice %0
3086/// into %dest[%a, %b, 0, 0] [1, 1, 17, 5] [1, 1, 1, 1]
3087/// : tensor<17x5xf32> into tensor<?x?x17x5xf32>
3088/// ```
3089/// is rewritten to:
3090/// ```
3091/// %0 = vector.transfer_read %src[%c0, %c0], %padding
3092/// : tensor<?x?xf32>, vector<17x5xf32>
3093/// %r = vector.transfer_write %0, %dest[%a, %b, %c0, %c0]
3094/// {in_bounds = [true, true]} : vector<17x5xf32>, tensor<?x?x17x5xf32>
3095/// ```
3096///
3097/// This rewrite is possible if:
3098/// - Low padding is static 0.
3099/// - `padOp` result shape is static.
3100/// - The entire padded tensor is inserted.
3101/// (Implies that sizes of `insertOp` are all static.)
3102/// - Only unit strides in `insertOp`.
3103/// - Single, scalar padding value.
3104/// - `padOp` result not used as destination.
3105struct PadOpVectorizationWithInsertSlicePattern
3106 : public VectorizePadOpUserPattern<tensor::InsertSliceOp> {
3107 using VectorizePadOpUserPattern<
3108 tensor::InsertSliceOp>::VectorizePadOpUserPattern;
3109
3110 LogicalResult rewriteUser(PatternRewriter &rewriter, tensor::PadOp padOp,
3111 tensor::InsertSliceOp insertOp) const override {
3112 // Low padding must be static 0.
3113 if (!padOp.hasZeroLowPad())
3114 return failure();
3115 // Only unit stride supported.
3116 if (!insertOp.hasUnitStride())
3117 return failure();
3118 // Pad value must be a constant.
3119 auto padValue = padOp.getConstantPaddingValue();
3120 if (!padValue)
3121 return failure();
3122 // Dynamic shapes not supported.
3123 if (!cast<ShapedType>(padOp.getResult().getType()).hasStaticShape())
3124 return failure();
3125 // Pad result not used as destination.
3126 if (insertOp.getDest() == padOp.getResult())
3127 return failure();
3128
3129 auto vecType = VectorType::get(padOp.getType().getShape(),
3130 padOp.getType().getElementType());
3131 unsigned vecRank = vecType.getRank();
3132 unsigned tensorRank = insertOp.getType().getRank();
3133
3134 // Check if sizes match: Insert the entire tensor into most minor dims.
3135 // (No permutations allowed.)
3136 SmallVector<int64_t> expectedSizes(tensorRank - vecRank, 1);
3137 expectedSizes.append(vecType.getShape().begin(), vecType.getShape().end());
3138 if (!llvm::all_of(
3139 llvm::zip(insertOp.getMixedSizes(), expectedSizes), [](auto it) {
3140 return getConstantIntValue(std::get<0>(it)) == std::get<1>(it);
3141 }))
3142 return failure();
3143
3144 // Insert the TransferReadOp and TransferWriteOp at the position of the
3145 // InsertSliceOp.
3146 rewriter.setInsertionPoint(insertOp);
3147
3148 // Generate TransferReadOp: Read entire source tensor and add high
3149 // padding.
3150 SmallVector<Value> readIndices(
3151 vecRank, arith::ConstantIndexOp::create(rewriter, padOp.getLoc(), 0));
3152 auto read = vector::TransferReadOp::create(rewriter, padOp.getLoc(),
3153 vecType, padOp.getSource(),
3154 readIndices, padValue);
3155
3156 // Generate TransferWriteOp: Write to InsertSliceOp's dest tensor at
3157 // specified offsets. Write is fully in-bounds because a InsertSliceOp's
3158 // source must fit into the destination at the specified offsets.
3159 auto writeIndices = getValueOrCreateConstantIndexOp(
3160 rewriter, padOp.getLoc(), insertOp.getMixedOffsets());
3161 SmallVector<bool> inBounds(vecRank, true);
3162 rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
3163 insertOp, read, insertOp.getDest(), writeIndices,
3164 ArrayRef<bool>{inBounds});
3165
3166 return success();
3167 }
3168};
3169
3171 RewritePatternSet &patterns, PatternBenefit baseBenefit) {
3172 patterns.add<PadOpVectorizationWithTransferReadPattern,
3173 PadOpVectorizationWithTransferWritePattern,
3174 PadOpVectorizationWithInsertSlicePattern>(
3175 patterns.getContext(), baseBenefit.getBenefit() + 1);
3176}
3177
3178//----------------------------------------------------------------------------//
3179// Forwarding patterns
3180//----------------------------------------------------------------------------//
3181
3182/// Check whether there is any interleaved use of any `values` between
3183/// `firstOp` and `secondOp`. Conservatively return `true` if any op or value
3184/// is in a different block.
3185static bool mayExistInterleavedUses(Operation *firstOp, Operation *secondOp,
3186 ValueRange values) {
3187 if (firstOp->getBlock() != secondOp->getBlock() ||
3188 !firstOp->isBeforeInBlock(secondOp)) {
3189 LDBG() << "interleavedUses precondition failed, firstOp: " << *firstOp
3190 << ", second op: " << *secondOp;
3191 return true;
3192 }
3193 for (auto v : values) {
3194 for (auto &u : v.getUses()) {
3195 Operation *owner = u.getOwner();
3196 if (owner == firstOp || owner == secondOp)
3197 continue;
3198 // TODO: this is too conservative, use dominance info in the future.
3199 if (owner->getBlock() == firstOp->getBlock() &&
3200 (owner->isBeforeInBlock(firstOp) || secondOp->isBeforeInBlock(owner)))
3201 continue;
3202 LDBG() << " found interleaved op " << *owner << ", firstOp: " << *firstOp
3203 << ", second op: " << *secondOp;
3204 return true;
3205 }
3206 }
3207 return false;
3208}
3209
3210/// Return the unique subview use of `v` if it is indeed unique, null
3211/// otherwise.
3212static memref::SubViewOp getSubViewUseIfUnique(Value v) {
3213 memref::SubViewOp subViewOp;
3214 for (auto &u : v.getUses()) {
3215 if (auto newSubViewOp = dyn_cast<memref::SubViewOp>(u.getOwner())) {
3216 if (subViewOp)
3217 return memref::SubViewOp();
3218 subViewOp = newSubViewOp;
3219 }
3220 }
3221 return subViewOp;
3222}
3223
3224/// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
3225/// when available.
3227 vector::TransferReadOp xferOp, PatternRewriter &rewriter) const {
3228
3229 // TODO: support mask.
3230 if (xferOp.getMask())
3231 return rewriter.notifyMatchFailure(xferOp, "unsupported mask");
3232
3233 // Transfer into `view`.
3234 Value viewOrAlloc = xferOp.getBase();
3235 if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() &&
3236 !viewOrAlloc.getDefiningOp<memref::AllocOp>())
3237 return rewriter.notifyMatchFailure(xferOp, "source not a view or alloc");
3238
3239 // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
3240 memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
3241 if (!subViewOp)
3242 return rewriter.notifyMatchFailure(xferOp, "no subview found");
3243 Value subView = subViewOp.getResult();
3244
3245 // Find the copy into `subView` without interleaved uses.
3246 memref::CopyOp copyOp;
3247 for (auto &u : subView.getUses()) {
3248 if (auto newCopyOp = dyn_cast<memref::CopyOp>(u.getOwner())) {
3249 assert(isa<MemRefType>(newCopyOp.getTarget().getType()));
3250 if (newCopyOp.getTarget() != subView)
3251 continue;
3252 if (mayExistInterleavedUses(newCopyOp, xferOp, {viewOrAlloc, subView}))
3253 continue;
3254 copyOp = newCopyOp;
3255 break;
3256 }
3257 }
3258 if (!copyOp)
3259 return rewriter.notifyMatchFailure(xferOp, "no copy found");
3260
3261 // Find the fill into `viewOrAlloc` without interleaved uses before the
3262 // copy.
3263 FillOp maybeFillOp;
3264 for (auto &u : viewOrAlloc.getUses()) {
3265 if (auto newFillOp = dyn_cast<FillOp>(u.getOwner())) {
3266 assert(isa<MemRefType>(newFillOp.output().getType()));
3267 if (newFillOp.output() != viewOrAlloc)
3268 continue;
3269 if (mayExistInterleavedUses(newFillOp, copyOp, {viewOrAlloc, subView}))
3270 continue;
3271 maybeFillOp = newFillOp;
3272 break;
3273 }
3274 }
3275 // Ensure padding matches.
3276 if (maybeFillOp && xferOp.getPadding() != maybeFillOp.value())
3277 return rewriter.notifyMatchFailure(xferOp,
3278 "padding value does not match fill");
3279
3280 // `in` is the subview that memref.copy reads. Replace it.
3281 Value in = copyOp.getSource();
3282
3283 // memref.copy + linalg.fill can be used to create a padded local buffer.
3284 // The `masked` attribute is only valid on this padded buffer.
3285 // When forwarding to vector.transfer_read, the attribute must be reset
3286 // conservatively.
3287 auto vectorType = xferOp.getVectorType();
3288 Value res = vector::TransferReadOp::create(
3289 rewriter, xferOp.getLoc(), vectorType, in, xferOp.getIndices(),
3290 xferOp.getPermutationMapAttr(), xferOp.getPadding(), xferOp.getMask(),
3291 rewriter.getBoolArrayAttr(
3292 SmallVector<bool>(vectorType.getRank(), false)));
3293
3294 if (maybeFillOp)
3295 rewriter.eraseOp(maybeFillOp);
3296 rewriter.eraseOp(copyOp);
3297 rewriter.replaceOp(xferOp, res);
3298
3299 return success();
3300}
3301
3302/// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
3303/// when available.
3305 vector::TransferWriteOp xferOp, PatternRewriter &rewriter) const {
3306 // TODO: support mask.
3307 if (xferOp.getMask())
3308 return rewriter.notifyMatchFailure(xferOp, "unsupported mask");
3309
3310 // Transfer into `viewOrAlloc`.
3311 Value viewOrAlloc = xferOp.getBase();
3312 if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() &&
3313 !viewOrAlloc.getDefiningOp<memref::AllocOp>())
3314 return rewriter.notifyMatchFailure(xferOp, "source not a view or alloc");
3315
3316 // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
3317 memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
3318 if (!subViewOp)
3319 return rewriter.notifyMatchFailure(xferOp, "no subview found");
3320 Value subView = subViewOp.getResult();
3321
3322 // Find the copy from `subView` without interleaved uses.
3323 memref::CopyOp copyOp;
3324 for (auto &u : subViewOp.getResult().getUses()) {
3325 if (auto newCopyOp = dyn_cast<memref::CopyOp>(u.getOwner())) {
3326 if (newCopyOp.getSource() != subView)
3327 continue;
3328 if (mayExistInterleavedUses(xferOp, newCopyOp, {viewOrAlloc, subView}))
3329 continue;
3330 copyOp = newCopyOp;
3331 break;
3332 }
3333 }
3334 if (!copyOp)
3335 return rewriter.notifyMatchFailure(xferOp, "no copy found");
3336
3337 // `out` is the subview copied into that we replace.
3338 assert(isa<MemRefType>(copyOp.getTarget().getType()));
3339 Value out = copyOp.getTarget();
3340
3341 // Forward vector.transfer into copy.
3342 // memref.copy + linalg.fill can be used to create a padded local buffer.
3343 // The `masked` attribute is only valid on this padded buffer.
3344 // When forwarding to vector.transfer_write, the attribute must be reset
3345 // conservatively.
3346 auto vector = xferOp.getVector();
3347 vector::TransferWriteOp::create(
3348 rewriter, xferOp.getLoc(), vector, out, xferOp.getIndices(),
3349 xferOp.getPermutationMapAttr(), xferOp.getMask(),
3350 rewriter.getBoolArrayAttr(SmallVector<bool>(
3351 dyn_cast<VectorType>(vector.getType()).getRank(), false)));
3352
3353 rewriter.eraseOp(copyOp);
3354 rewriter.eraseOp(xferOp);
3355
3356 return success();
3357}
3358
3359//===----------------------------------------------------------------------===//
3360// Convolution vectorization patterns
3361//===----------------------------------------------------------------------===//
3362
3363template <int N>
3364static void bindShapeDims(ShapedType shapedType) {}
3365
3366template <int N, typename IntTy, typename... IntTy2>
3367static void bindShapeDims(ShapedType shapedType, IntTy &val, IntTy2 &...vals) {
3368 val = shapedType.getShape()[N];
3369 bindShapeDims<N + 1, IntTy2 &...>(shapedType, vals...);
3370}
3371
3372/// Bind a pack of int& to the leading dimensions of shapedType.getShape().
3373template <typename... IntTy>
3374static void bindShapeDims(ShapedType shapedType, IntTy &...vals) {
3375 bindShapeDims<0>(shapedType, vals...);
3376}
3377
3378/// Match 1D convolution or pooling operations and return their dilations and
3379/// strides. Returns std::nullopt for unrecognized ops.
3380static std::optional<DilationsAndStrides> match1DConvPoolOp(LinalgOp op) {
3381#define MATCH_1D_CONV_POOL_OP(ConvOpTy) \
3382 if (auto convParams = matchConvolutionOpOfType<ConvOpTy>(op)) \
3383 return convParams;
3384
3385 // 1D Convolution ops.
3386 MATCH_1D_CONV_POOL_OP(linalg::Conv1DOp);
3387 MATCH_1D_CONV_POOL_OP(linalg::Conv1DNwcWcfOp);
3388 MATCH_1D_CONV_POOL_OP(linalg::Conv1DNcwFcwOp);
3389 // Depthwise 1D Convolution ops.
3390 // Note: Only NWC layout without channel multiplier is supported.
3391 // DepthwiseConv1DNcwCwOp (NCW) and DepthwiseConv1DNwcWcmOp (with multiplier)
3392 // are not supported.
3393 MATCH_1D_CONV_POOL_OP(linalg::DepthwiseConv1DNwcWcOp);
3394 // 1D Pooling ops (NWC layout).
3395 MATCH_1D_CONV_POOL_OP(linalg::PoolingNwcSumOp);
3396 MATCH_1D_CONV_POOL_OP(linalg::PoolingNwcMaxOp);
3397 MATCH_1D_CONV_POOL_OP(linalg::PoolingNwcMaxUnsignedOp);
3398 MATCH_1D_CONV_POOL_OP(linalg::PoolingNwcMinOp);
3399 MATCH_1D_CONV_POOL_OP(linalg::PoolingNwcMinUnsignedOp);
3400 // 1D Pooling ops (NCW layout).
3401 MATCH_1D_CONV_POOL_OP(linalg::PoolingNcwSumOp);
3402 MATCH_1D_CONV_POOL_OP(linalg::PoolingNcwMaxOp);
3403
3404#undef MATCH_1D_CONV_POOL_OP
3405
3406 return std::nullopt;
3407}
3408
3409namespace {
3410/// Generate a vector implementation for either:
3411/// ```
3412/// Op def: ( w, kw )
3413/// Iters: ({Par(), Red()})
3414/// Layout: {{w + kw}, {kw}, {w}}
3415/// ```
3416/// kw is unrolled.
3417///
3418/// or
3419///
3420/// ```
3421/// Op def: ( n, w, c, kw, f )
3422/// Iters: ({Par(), Par(), Par(), Red(), Red()})
3423/// Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c, f}, {n, w, f}}
3424/// ```
3425/// kw is unrolled, w is unrolled iff dilationW > 1.
3426///
3427/// or
3428///
3429/// ```
3430/// Op def: ( n, c, w, f, kw )
3431/// Iters: ({Par(), Par(), Par(), Red(), Red()})
3432/// Layout: {{n, c, strideW * w + dilationW * kw}, {f, c, kw}, {n, f, w}}
3433/// ```
3434/// kw is unrolled, w is unrolled iff dilationW > 1.
3435///
3436/// or
3437///
3438/// ```
3439/// Op def: ( n, w, c, kw )
3440/// Iters: ({Par(), Par(), Par(), Red()})
3441/// Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c}, {n, w, c}}
3442/// ```
3443/// kw is unrolled, w is unrolled iff dilationW > 1.
3444struct Conv1DGenerator
3445 : public StructuredGenerator<LinalgOp, utils::IteratorType> {
3446 /// Factory method to create a Conv1DGenerator. Returns failure if the
3447 /// operation doesn't have valid strides/dilations.
3448 static FailureOr<Conv1DGenerator> create(RewriterBase &rewriter,
3449 LinalgOp linalgOp) {
3450 // Try to match a 1D conv/pool op using matchConvolutionOpOfType. This
3451 // works for both named ops and generic ops that match their semantics.
3452 std::optional<DilationsAndStrides> convParams = match1DConvPoolOp(linalgOp);
3453 if (!convParams)
3454 return failure();
3455
3456 int strideW = static_cast<int>(convParams->strides.front());
3457 int dilationW = static_cast<int>(convParams->dilations.front());
3458 return Conv1DGenerator(rewriter, linalgOp, strideW, dilationW);
3459 }
3460
3461private:
3462 Conv1DGenerator(RewriterBase &rewriter, LinalgOp linalgOp, int strideW,
3463 int dilationW)
3464 : StructuredGenerator<LinalgOp, utils::IteratorType>(rewriter, linalgOp),
3465 strideW(strideW), dilationW(dilationW) {
3466
3467 lhsShaped = linalgOp.getDpsInputOperand(0)->get();
3468 rhsShaped = linalgOp.getDpsInputOperand(1)->get();
3469 resShaped = linalgOp.getDpsInitOperand(0)->get();
3470 lhsShapedType = dyn_cast<ShapedType>(lhsShaped.getType());
3471 rhsShapedType = dyn_cast<ShapedType>(rhsShaped.getType());
3472 resShapedType = dyn_cast<ShapedType>(resShaped.getType());
3473
3474 Operation *reduceOp = matchLinalgReduction(linalgOp.getDpsInitOperand(0));
3475 redOp = reduceOp->getName().getIdentifier();
3476
3477 setConvOperationKind(reduceOp);
3478
3479 auto maybeKind = getCombinerOpKind(reduceOp);
3480 reductionKind = maybeKind.value();
3481 }
3482
3483public:
3484 /// Generate a vector implementation for:
3485 /// ```
3486 /// Op def: ( w, kw )
3487 /// Iters: ({Par(), Red()})
3488 /// Layout: {{w + kw}, {kw}, {w}}
3489 /// ```
3490 /// kw is always unrolled.
3491 ///
3492 /// or
3493 ///
3494 /// ```
3495 /// Op def: ( n, w, c, kw, f )
3496 /// Iters: ({Par(), Par(), Par(), Red(), Red()})
3497 /// Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c, f}, {n, w, f}}
3498 /// ```
3499 /// kw is always unrolled.
3500 /// TODO: w (resp. kw) is unrolled when the strideW ( resp. dilationW) is
3501 /// > 1.
3502 FailureOr<Operation *> conv(Conv1DOpOrder conv1DOpOrder) {
3503 int64_t nSize, wSize, cSize, kwSize, fSize;
3504 SmallVector<int64_t, 3> lhsShape, rhsShape, resShape;
3505 bool isSingleChanneled = (conv1DOpOrder == Conv1DOpOrder::W);
3506 switch (conv1DOpOrder) {
3507 case Conv1DOpOrder::W:
3508 // Initialize unused dimensions
3509 nSize = fSize = cSize = 0;
3510 // out{W}
3511 bindShapeDims(resShapedType, wSize);
3512 // kernel{kw}
3513 bindShapeDims(rhsShapedType, kwSize);
3514 lhsShape = {// iw = ow + kw - 1
3515 // (i.e. 16 convolved with 3 -> 14)
3516 (wSize + kwSize - 1)};
3517 rhsShape = {kwSize};
3518 resShape = {wSize};
3519 break;
3520 case Conv1DOpOrder::Nwc:
3521 // out{n, w, f}
3522 bindShapeDims(resShapedType, nSize, wSize, fSize);
3523 switch (oper) {
3524 case ConvOperationKind::Conv:
3525 // kernel{kw, c, f}
3526 bindShapeDims(rhsShapedType, kwSize, cSize);
3527 break;
3528 case ConvOperationKind::Pool:
3529 // kernel{kw}
3530 bindShapeDims(rhsShapedType, kwSize);
3531 cSize = fSize;
3532 break;
3533 }
3534 lhsShape = {nSize,
3535 // iw = ow * sw + kw * dw - 1
3536 // (i.e. 16 convolved with 3 (@stride 1 dilation 1) -> 14)
3537 // Perform the proper inclusive -> exclusive -> inclusive.
3538 ((wSize - 1) * strideW + 1) + ((kwSize - 1) * dilationW + 1) -
3539 1,
3540 cSize};
3541 switch (oper) {
3542 case ConvOperationKind::Conv:
3543 rhsShape = {kwSize, cSize, fSize};
3544 break;
3545 case ConvOperationKind::Pool:
3546 rhsShape = {kwSize};
3547 break;
3548 }
3549 resShape = {nSize, wSize, fSize};
3550 break;
3551 case Conv1DOpOrder::Ncw:
3552 // out{n, f, w}
3553 bindShapeDims(resShapedType, nSize, fSize, wSize);
3554 switch (oper) {
3555 case ConvOperationKind::Conv:
3556 // kernel{f, c, kw}
3557 bindShapeDims(rhsShapedType, fSize, cSize, kwSize);
3558 break;
3559 case ConvOperationKind::Pool:
3560 // kernel{kw}
3561 bindShapeDims(rhsShapedType, kwSize);
3562 cSize = fSize;
3563 break;
3564 }
3565 lhsShape = {nSize, cSize,
3566 // iw = ow * sw + kw * dw - 1
3567 // (i.e. 16 convolved with 3 (@stride 1 dilation 1) -> 14)
3568 // Perform the proper inclusive -> exclusive -> inclusive.
3569 ((wSize - 1) * strideW + 1) + ((kwSize - 1) * dilationW + 1) -
3570 1};
3571 switch (oper) {
3572 case ConvOperationKind::Conv:
3573 rhsShape = {fSize, cSize, kwSize};
3574 break;
3575 case ConvOperationKind::Pool:
3576 rhsShape = {kwSize};
3577 break;
3578 }
3579 resShape = {nSize, fSize, wSize};
3580 break;
3581 }
3582
3583 vector::TransferWriteOp write;
3584 Value zero = arith::ConstantIndexOp::create(rewriter, loc, 0);
3585
3586 // w is unrolled (i.e. wSizeStep == 1) iff strideW > 1.
3587 // When strideW == 1, we can batch the contiguous loads and avoid
3588 // unrolling
3589 int64_t wSizeStep = strideW == 1 ? wSize : 1;
3590
3591 Type lhsEltType = lhsShapedType.getElementType();
3592 Type rhsEltType = rhsShapedType.getElementType();
3593 Type resEltType = resShapedType.getElementType();
3594 auto lhsType = VectorType::get(lhsShape, lhsEltType);
3595 auto rhsType = VectorType::get(rhsShape, rhsEltType);
3596 auto resType = VectorType::get(resShape, resEltType);
3597 // Zero padding with the corresponding dimensions for lhs, rhs and res.
3598 SmallVector<Value> lhsPadding(lhsShape.size(), zero);
3599 SmallVector<Value> rhsPadding(rhsShape.size(), zero);
3600 SmallVector<Value> resPadding(resShape.size(), zero);
3601
3602 // Read the whole lhs, rhs and res in one shot (with zero padding).
3603 Value lhs = vector::TransferReadOp::create(
3604 rewriter, loc, lhsType, lhsShaped, lhsPadding,
3605 /*padding=*/arith::getZeroConstant(rewriter, loc, lhsEltType));
3606 // This is needed only for Conv.
3607 Value rhs = nullptr;
3608 if (oper == ConvOperationKind::Conv)
3609 rhs = vector::TransferReadOp::create(
3610 rewriter, loc, rhsType, rhsShaped, rhsPadding,
3611 /*padding=*/arith::getZeroConstant(rewriter, loc, rhsEltType));
3612 Value res = vector::TransferReadOp::create(
3613 rewriter, loc, resType, resShaped, resPadding,
3614 /*padding=*/arith::getZeroConstant(rewriter, loc, resEltType));
3615
3616 // The base vectorization case for channeled convolution is input:
3617 // {n,w,c}, weight: {kw,c,f}, output: {n,w,f}. To reuse the base pattern
3618 // vectorization case, we do pre transpose on input, weight, and output.
3619 switch (conv1DOpOrder) {
3620 case Conv1DOpOrder::W:
3621 case Conv1DOpOrder::Nwc:
3622 // Base case, so no transposes necessary.
3623 break;
3624 case Conv1DOpOrder::Ncw: {
3625 // To match base vectorization case, we pre-transpose current case.
3626 // ncw -> nwc
3627 static constexpr std::array<int64_t, 3> permLhs = {0, 2, 1};
3628 lhs = vector::TransposeOp::create(rewriter, loc, lhs, permLhs);
3629 // fcw -> wcf
3630 static constexpr std::array<int64_t, 3> permRhs = {2, 1, 0};
3631
3632 // This is needed only for Conv.
3633 if (oper == ConvOperationKind::Conv)
3634 rhs = vector::TransposeOp::create(rewriter, loc, rhs, permRhs);
3635 // nfw -> nwf
3636 static constexpr std::array<int64_t, 3> permRes = {0, 2, 1};
3637 res = vector::TransposeOp::create(rewriter, loc, res, permRes);
3638 break;
3639 }
3640 }
3641
3642 //===------------------------------------------------------------------===//
3643 // Begin vector-only rewrite part
3644 //===------------------------------------------------------------------===//
3645 // Unroll along kw and read slices of lhs and rhs.
3646 SmallVector<Value> lhsVals, rhsVals, resVals;
3647 lhsVals = extractConvInputSlices(rewriter, loc, lhs, nSize, wSize, cSize,
3648 kwSize, strideW, dilationW, wSizeStep,
3649 isSingleChanneled);
3650 // Do not do for pooling.
3651 if (oper == ConvOperationKind::Conv)
3652 rhsVals = extractConvFilterSlices(rewriter, loc, rhs, kwSize);
3653 resVals = extractConvResultSlices(rewriter, loc, res, nSize, wSize, fSize,
3654 wSizeStep, isSingleChanneled);
3655
3656 auto linearIndex = [&](int64_t kw, int64_t w) {
3657 return kw * (wSize / wSizeStep) + w;
3658 };
3659
3660 // Compute contraction: O{n, w, f} += I{n, sw * w + dw * kw, c} * F{c, f}
3661 // or perform outerproduct for non-channeled convolution or perform simple
3662 // arith operation for pooling
3663 for (int64_t kw = 0; kw < kwSize; ++kw) {
3664 for (int64_t w = 0; w < wSize; w += wSizeStep) {
3665 switch (oper) {
3666 case ConvOperationKind::Conv:
3667 if (isSingleChanneled) {
3668 resVals[w] = conv1dSliceAsOuterProduct(rewriter, loc,
3669 lhsVals[linearIndex(kw, w)],
3670 rhsVals[kw], resVals[w]);
3671 } else {
3672 resVals[w] = conv1dSliceAsContraction(rewriter, loc,
3673 lhsVals[linearIndex(kw, w)],
3674 rhsVals[kw], resVals[w]);
3675 }
3676 break;
3677 case ConvOperationKind::Pool:
3678 resVals[w] = pool1dSlice(rewriter, loc, lhsVals[linearIndex(kw, w)],
3679 resVals[w]);
3680 break;
3681 }
3682 }
3683 }
3684
3685 res = insertConvResultSlices(rewriter, loc, res, wSize, wSizeStep, resVals,
3686 isSingleChanneled);
3687 //===------------------------------------------------------------------===//
3688 // End vector-only rewrite part
3689 //===------------------------------------------------------------------===//
3690
3691 // The base vectorization case for channeled convolution is output:
3692 // {n,w,f} To reuse the result from base pattern vectorization case, we
3693 // post transpose the base case result.
3694 switch (conv1DOpOrder) {
3695 case Conv1DOpOrder::W:
3696 case Conv1DOpOrder::Nwc:
3697 // Base case, so no transposes necessary.
3698 break;
3699 case Conv1DOpOrder::Ncw: {
3700 // nwf -> nfw
3701 static constexpr std::array<int64_t, 3> perm = {0, 2, 1};
3702 res = vector::TransposeOp::create(rewriter, loc, res, perm);
3703 break;
3704 }
3705 }
3706
3707 return vector::TransferWriteOp::create(rewriter, loc, res, resShaped,
3708 resPadding)
3709 .getOperation();
3710 }
3711
3712 // Promote `val` to the element type of `ty` using `castOp`.
3713 Value promote(RewriterBase &rewriter, Location loc, Value val, Type ty,
3714 Operation *castOp) {
3715 const Type dstElementType = getElementTypeOrSelf(ty);
3716 if (getElementTypeOrSelf(val.getType()) == dstElementType)
3717 return val;
3718
3719 assert(castOp && "expected a payload cast for promoted operand");
3720
3721 // Handle both shaped as well as scalar types.
3722 Type dstType;
3723 if (auto shapedType = dyn_cast<ShapedType>(val.getType()))
3724 dstType = shapedType.cloneWith(std::nullopt, dstElementType);
3725 else
3726 dstType = dstElementType;
3727
3728 OperationState state(loc, castOp->getName().getIdentifier(), val, dstType,
3729 castOp->getDiscardableAttrDictionary().getValue());
3730 state.propertiesAttr = castOp->getPropertiesAsAttribute();
3731 return rewriter.create(state)->getResult(0);
3732 }
3733
3734 // Create a contraction: lhs{n, w, c} * rhs{c, f} -> res{n, w, f}
3735 Value conv1dSliceAsContraction(RewriterBase &rewriter, Location loc,
3736 Value lhs, Value rhs, Value res) {
3737 vector::IteratorType par = vector::IteratorType::parallel;
3738 vector::IteratorType red = vector::IteratorType::reduction;
3739 AffineExpr n, w, f, c;
3740 bindDims(ctx, n, w, f, c);
3741 lhs = promote(rewriter, loc, lhs, res.getType(), lhsCastOp);
3742 rhs = promote(rewriter, loc, rhs, res.getType(), rhsCastOp);
3743 auto contrationOp = vector::ContractionOp::create(
3744 rewriter, loc, lhs, rhs, res,
3745 /*indexingMaps=*/MapList{{n, w, c}, {c, f}, {n, w, f}},
3746 /*iteratorTypes=*/ArrayRef<vector::IteratorType>{par, par, par, red});
3747 contrationOp.setKind(reductionKind);
3748 return contrationOp;
3749 }
3750
3751 // Create an outerproduct: lhs{w} * rhs{1} -> res{w} for single channel
3752 // convolution.
3753 Value conv1dSliceAsOuterProduct(RewriterBase &rewriter, Location loc,
3754 Value lhs, Value rhs, Value res) {
3755 lhs = promote(rewriter, loc, lhs, res.getType(), lhsCastOp);
3756 rhs = promote(rewriter, loc, rhs, res.getType(), rhsCastOp);
3757 return vector::OuterProductOp::create(rewriter, loc, res.getType(), lhs,
3758 rhs, res, vector::CombiningKind::ADD);
3759 }
3760
3761 // Create a reduction: lhs{n, w, c} -> res{n, w, c}
3762 Value pool1dSlice(RewriterBase &rewriter, Location loc, Value lhs,
3763 Value res) {
3764 if (isPoolExt)
3765 lhs = rewriter.create(loc, poolExtOp, lhs, res.getType())->getResult(0);
3766 return rewriter
3767 .create(loc, redOp, ArrayRef<Value>{lhs, res}, res.getType())
3768 ->getResult(0);
3769 }
3770
3771 /// Generate a vector implementation for:
3772 /// ```
3773 /// Op def: ( n, w, c, kw)
3774 /// Iters: ({Par(), Par(), Par(), Red()})
3775 /// Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c}, {n, w, c}}
3776 /// ```
3777 /// kw is always unrolled.
3778 /// TODO: w (resp. kw) is unrolled when the strideW ( resp. dilationW) is
3779 /// > 1.
3780 FailureOr<Operation *> depthwiseConv(uint64_t channelDimVecSize,
3781 bool channelDimScalableFlag,
3782 bool flatten) {
3783 bool scalableChDim = false;
3784 bool useMasking = false;
3785 int64_t nSize, wSize, cSize, kwSize;
3786 // kernel{kw, c}
3787 bindShapeDims(rhsShapedType, kwSize, cSize);
3788 if (ShapedType::isDynamic(cSize)) {
3789 assert(channelDimVecSize != 0 && "Channel dim vec size must be > 0");
3790 cSize = channelDimVecSize;
3791 // Scalable vectors are only used when both conditions are met:
3792 // 1. channel dim is dynamic
3793 // 2. channelDimScalableFlag is set
3794 scalableChDim = channelDimScalableFlag;
3795 useMasking = true;
3796 }
3797
3798 assert(!(useMasking && flatten) &&
3799 "Unsupported flattened conv with dynamic shapes");
3800
3801 // out{n, w, c}
3802 bindShapeDims(resShapedType, nSize, wSize);
3803
3804 vector::TransferWriteOp write;
3805 Value zero = arith::ConstantIndexOp::create(rewriter, loc, 0);
3806
3807 // w is unrolled (i.e. wSizeStep == 1) iff strideW > 1.
3808 // When strideW == 1, we can batch the contiguous loads and avoid
3809 // unrolling
3810 int64_t wSizeStep = strideW == 1 ? wSize : 1;
3811
3812 Type lhsEltType = lhsShapedType.getElementType();
3813 Type rhsEltType = rhsShapedType.getElementType();
3814 Type resEltType = resShapedType.getElementType();
3815 VectorType lhsType = VectorType::get(
3816 {nSize,
3817 // iw = ow * sw + kw * dw - 1
3818 // (i.e. 16 convolved with 3 (@stride 1 dilation 1) -> 14)
3819 ((wSize - 1) * strideW + 1) + ((kwSize - 1) * dilationW + 1) - 1,
3820 cSize},
3821 lhsEltType, /*scalableDims=*/{false, false, scalableChDim});
3822 VectorType rhsType =
3823 VectorType::get({kwSize, cSize}, rhsEltType,
3824 /*scalableDims=*/{false, scalableChDim});
3825 VectorType resType =
3826 VectorType::get({nSize, wSize, cSize}, resEltType,
3827 /*scalableDims=*/{false, false, scalableChDim});
3828
3829 // Masks the input xfer Op along the channel dim, iff the corresponding
3830 // scalable flag is set.
3831 auto maybeMaskXferOp = [&](ArrayRef<int64_t> maskShape,
3832 ArrayRef<bool> scalableDims,
3833 Operation *opToMask) {
3834 if (!useMasking)
3835 return opToMask;
3836 auto maskType =
3837 VectorType::get(maskShape, rewriter.getI1Type(), scalableDims);
3838
3839 SmallVector<bool> inBounds(maskShape.size(), true);
3840 auto xferOp = cast<VectorTransferOpInterface>(opToMask);
3841 xferOp->setInherentAttr(
3842 rewriter.getStringAttr(xferOp.getInBoundsAttrName()),
3843 rewriter.getBoolArrayAttr(inBounds));
3844
3845 SmallVector<OpFoldResult> mixedDims = vector::getMixedSizesXfer(
3846 cast<LinalgOp>(op).hasPureTensorSemantics(), opToMask, rewriter);
3847
3848 Value maskOp =
3849 vector::CreateMaskOp::create(rewriter, loc, maskType, mixedDims);
3850
3851 return mlir::vector::maskOperation(rewriter, opToMask, maskOp);
3852 };
3853
3854 // Read lhs slice of size {n, w * strideW + kw * dilationW, c} @ [0, 0,
3855 // 0].
3856 Value lhs = vector::TransferReadOp::create(
3857 rewriter, loc, lhsType, lhsShaped, ValueRange{zero, zero, zero},
3858 /*padding=*/arith::getZeroConstant(rewriter, loc, lhsEltType));
3859 auto *maybeMaskedLhs = maybeMaskXferOp(
3860 lhsType.getShape(), lhsType.getScalableDims(), lhs.getDefiningOp());
3861
3862 // Read rhs slice of size {kw, c} @ [0, 0].
3863 Value rhs = vector::TransferReadOp::create(
3864 rewriter, loc, rhsType, rhsShaped, ValueRange{zero, zero},
3865 /*padding=*/arith::getZeroConstant(rewriter, loc, rhsEltType));
3866 auto *maybeMaskedRhs = maybeMaskXferOp(
3867 rhsType.getShape(), rhsType.getScalableDims(), rhs.getDefiningOp());
3868
3869 // Read res slice of size {n, w, c} @ [0, 0, 0].
3870 Value res = vector::TransferReadOp::create(
3871 rewriter, loc, resType, resShaped, ValueRange{zero, zero, zero},
3872 /*padding=*/arith::getZeroConstant(rewriter, loc, resEltType));
3873 auto *maybeMaskedRes = maybeMaskXferOp(
3874 resType.getShape(), resType.getScalableDims(), res.getDefiningOp());
3875
3876 //===------------------------------------------------------------------===//
3877 // Begin vector-only rewrite part
3878 //===------------------------------------------------------------------===//
3879 // Unroll along kw and read slices of lhs and rhs.
3880 SmallVector<Value> lhsVals, rhsVals, resVals;
3881 SmallVector<int64_t> inOutSliceSizes = {nSize, wSizeStep, cSize};
3882 SmallVector<int64_t> inOutStrides = {1, 1, 1};
3883
3884 // Extract lhs slice of size {n, wSizeStep, c}
3885 // @ [0, sw * w + dw * kw, 0].
3886 for (int64_t kw = 0; kw < kwSize; ++kw) {
3887 for (int64_t w = 0; w < wSize; w += wSizeStep) {
3888 lhsVals.push_back(vector::ExtractStridedSliceOp::create(
3889 rewriter, loc, maybeMaskedLhs->getResult(0),
3890 /*offsets=*/ArrayRef<int64_t>{0, w * strideW + kw * dilationW, 0},
3891 inOutSliceSizes, inOutStrides));
3892 }
3893 }
3894 // Extract rhs slice of size {c} @ [kw].
3895 for (int64_t kw = 0; kw < kwSize; ++kw) {
3896 rhsVals.push_back(
3897 vector::ExtractOp::create(rewriter, loc, maybeMaskedRhs->getResult(0),
3898 /*offsets=*/ArrayRef<int64_t>{kw}));
3899 }
3900 // Extract res slice: {n, wSizeStep, c} @ [0, w, 0].
3901 for (int64_t w = 0; w < wSize; w += wSizeStep) {
3902 resVals.push_back(vector::ExtractStridedSliceOp::create(
3903 rewriter, loc, maybeMaskedRes->getResult(0),
3904 /*offsets=*/ArrayRef<int64_t>{0, w, 0}, inOutSliceSizes,
3905 inOutStrides));
3906 }
3907
3908 auto linearIndex = [&](int64_t kw, int64_t w) {
3909 return kw * (wSize / wSizeStep) + w;
3910 };
3911
3912 // Note - the scalable flags are ignored as flattening combined with
3913 // scalable vectorization is not supported.
3914 SmallVector<int64_t> inOutFlattenSliceSizes = {nSize, wSizeStep * cSize};
3915 auto lhsTypeAfterFlattening =
3916 VectorType::get(inOutFlattenSliceSizes, lhsEltType);
3917 auto resTypeAfterFlattening =
3918 VectorType::get(inOutFlattenSliceSizes, resEltType);
3919
3920 // Compute contraction: O{n, w, c} += I{n, sw * w + dw * kw, c} * F{c}
3921 for (int64_t kw = 0; kw < kwSize; ++kw) {
3922 for (int64_t w = 0; w < wSize; w += wSizeStep) {
3923 Value lhsVal = lhsVals[linearIndex(kw, w)];
3924 Value resVal = resVals[w];
3925 if (flatten) {
3926 // Flatten the input and output vectors (collapse the channel
3927 // dimension)
3928 lhsVal =
3929 vector::ShapeCastOp::create(rewriter, loc, lhsTypeAfterFlattening,
3930 lhsVals[linearIndex(kw, w)]);
3931 resVal = vector::ShapeCastOp::create(
3932 rewriter, loc, resTypeAfterFlattening, resVals[w]);
3933 }
3934 resVals[w] = depthwiseConv1dSliceAsMulAcc(rewriter, loc, lhsVal,
3935 rhsVals[kw], resVal, flatten);
3936 if (flatten) {
3937 // Un-flatten the output vector (restore the channel dimension)
3938 resVals[w] = vector::ShapeCastOp::create(
3939 rewriter, loc, VectorType::get(inOutSliceSizes, resEltType),
3940 resVals[w]);
3941 }
3942 }
3943 }
3944
3945 // Its possible we failed to create the Fma.
3946 if (!llvm::all_of(resVals, [](Value v) { return v; })) {
3947 // Manually revert (in reverse order) to avoid leaving a bad IR state.
3948 for (auto &collection :
3949 {resVals, rhsVals, lhsVals, {res, rhs, lhs, zero}})
3950 for (Value v : collection)
3951 rewriter.eraseOp(v.getDefiningOp());
3952 return rewriter.notifyMatchFailure(op, "failed to create FMA");
3953 }
3954
3955 // Write back res slice: {n, wSizeStep, c} @ [0, w, 0].
3956 // This does not depend on kw.
3957 for (int64_t w = 0; w < wSize; w += wSizeStep) {
3958 maybeMaskedRes = vector::InsertStridedSliceOp::create(
3959 rewriter, loc, resVals[w], maybeMaskedRes->getResult(0),
3960 /*offsets=*/ArrayRef<int64_t>{0, w, 0},
3961 /*strides=*/ArrayRef<int64_t>{1, 1, 1});
3962 }
3963 //===------------------------------------------------------------------===//
3964 // End vector-only rewrite part
3965 //===------------------------------------------------------------------===//
3966
3967 // Write back res slice of size {n, w, c} @ [0, 0, 0].
3968 Operation *resOut = vector::TransferWriteOp::create(
3969 rewriter, loc, maybeMaskedRes->getResult(0), resShaped,
3970 ValueRange{zero, zero, zero});
3971 return maybeMaskXferOp(resType.getShape(), resType.getScalableDims(),
3972 resOut);
3973 }
3974
3975 /// Lower:
3976 /// * lhs{n, w, c} * rhs{c} -> res{n, w, c} (flatten = false)
3977 /// * lhs{n, w * c} * rhs{c} -> res{n, w * c} (flatten = true)
3978 /// to MulAcc.
3979 Value depthwiseConv1dSliceAsMulAcc(RewriterBase &rewriter, Location loc,
3980 Value lhs, Value rhs, Value res,
3981 bool flatten) {
3982 auto rhsTy = cast<ShapedType>(rhs.getType());
3983 auto resTy = cast<ShapedType>(res.getType());
3984
3985 // TODO(suderman): Change this to use a vector.ima intrinsic.
3986 lhs = promote(rewriter, loc, lhs, resTy, lhsCastOp);
3987
3988 if (flatten) {
3989 // NOTE: This following logic won't work for scalable vectors. For this
3990 // reason, "flattening" is not supported when shapes are dynamic (this
3991 // should be captured by one of the pre-conditions).
3992
3993 // There are two options for handling the filter:
3994 // * shape_cast(broadcast(filter))
3995 // * broadcast(shuffle(filter))
3996 // Opt for the option without shape_cast to simplify the codegen.
3997 auto rhsSize = cast<VectorType>(rhs.getType()).getShape()[0];
3998 auto resSize = cast<VectorType>(res.getType()).getShape()[1];
3999
4000 SmallVector<int64_t, 16> indices;
4001 for (int i = 0; i < resSize / rhsSize; ++i) {
4002 for (int j = 0; j < rhsSize; ++j)
4003 indices.push_back(j);
4004 }
4005
4006 rhs = vector::ShuffleOp::create(rewriter, loc, rhs, rhs, indices);
4007 }
4008 // Broadcast the filter to match the output vector
4009 rhs = vector::BroadcastOp::create(rewriter, loc,
4010 resTy.clone(rhsTy.getElementType()), rhs);
4011
4012 rhs = promote(rewriter, loc, rhs, resTy, rhsCastOp);
4013
4014 if (!lhs || !rhs)
4015 return nullptr;
4016
4017 if (isa<FloatType>(resTy.getElementType()))
4018 return vector::FMAOp::create(rewriter, loc, lhs, rhs, res);
4019
4020 auto mul = arith::MulIOp::create(rewriter, loc, lhs, rhs);
4021 return arith::AddIOp::create(rewriter, loc, mul, res);
4022 }
4023
4024 /// Entry point for non-channeled convolution:
4025 /// {{w + kw}, {kw}, {w}}
4026 FailureOr<Operation *> generateNonChanneledConv() {
4027 AffineExpr w, kw;
4028 bindDims(ctx, w, kw);
4029 if (!iters({Par(), Red()}))
4030 return rewriter.notifyMatchFailure(op,
4031 "failed to match conv::W 1-par 1-red");
4032
4033 // No transposition needed.
4034 if (layout({/*lhsIndex*/ {w + kw},
4035 /*rhsIndex*/ {kw},
4036 /*resIndex*/ {w}}))
4037 return conv(Conv1DOpOrder::W);
4038
4039 return rewriter.notifyMatchFailure(op, "not a conv::W layout");
4040 }
4041
4042 /// Entry point that transposes into the common form:
4043 /// {{n, strideW * w + dilationW * kw, c}, {kw, c, f}, {n, w, f}}
4044 FailureOr<Operation *> generateNwcConv() {
4045 AffineExpr n, w, f, kw, c;
4046 bindDims(ctx, n, w, f, kw, c);
4047 if (!iters({Par(), Par(), Par(), Red(), Red()}))
4048 return rewriter.notifyMatchFailure(
4049 op, "failed to match conv::Nwc 3-par 2-red");
4050
4051 // No transposition needed.
4052 if (layout({/*lhsIndex*/ {n, strideW * w + dilationW * kw, c},
4053 /*rhsIndex*/ {kw, c, f},
4054 /*resIndex*/ {n, w, f}}))
4055 return conv(Conv1DOpOrder::Nwc);
4056
4057 return rewriter.notifyMatchFailure(op, "not a conv::Nwc layout");
4058 }
4059
4060 /// Entry point that transposes into the common form:
4061 /// {{n, c, strideW * w + dilationW * kw}, {f, c, kw}, {n, f, w}}
4062 FailureOr<Operation *> generateNcwConv() {
4063 AffineExpr n, w, f, kw, c;
4064 bindDims(ctx, n, f, w, c, kw);
4065 if (!iters({Par(), Par(), Par(), Red(), Red()}))
4066 return rewriter.notifyMatchFailure(
4067 op, "failed to match conv::Ncw 3-par 2-red");
4068
4069 if (layout({/*lhsIndex*/ {n, c, strideW * w + dilationW * kw},
4070 /*rhsIndex*/ {f, c, kw},
4071 /*resIndex*/ {n, f, w}}))
4072 return conv(Conv1DOpOrder::Ncw);
4073
4074 return rewriter.notifyMatchFailure(op, "not a conv::Ncw layout");
4075 }
4076
4077 /// Entry point that transposes into the common form:
4078 /// {{n, strideW * w + dilationW * kw, c}, {kw}, {n, w, c}} for pooling
4079 FailureOr<Operation *> generateNwcPooling() {
4080 AffineExpr n, w, c, kw;
4081 bindDims(ctx, n, w, c, kw);
4082 if (!iters({Par(), Par(), Par(), Red()}))
4083 return rewriter.notifyMatchFailure(op,
4084 "failed to match pooling 3-par 1-red");
4085
4086 // No transposition needed.
4087 if (layout({/*lhsIndex*/ {n, strideW * w + dilationW * kw, c},
4088 /*rhsIndex*/ {kw},
4089 /*resIndex*/ {n, w, c}}))
4090 return conv(Conv1DOpOrder::Nwc);
4091
4092 return rewriter.notifyMatchFailure(op, "not a pooling::Nwc layout");
4093 }
4094
4095 /// Entry point that transposes into the common form:
4096 /// {{n, c, strideW * w + dilationW * kw}, {kw}, {n, c, w}} for pooling
4097 FailureOr<Operation *> generateNcwPooling() {
4098 AffineExpr n, w, c, kw;
4099 bindDims(ctx, n, c, w, kw);
4100 if (!iters({Par(), Par(), Par(), Red()}))
4101 return rewriter.notifyMatchFailure(op,
4102 "failed to match pooling 3-par 1-red");
4103
4104 if (layout({/*lhsIndex*/ {n, c, strideW * w + dilationW * kw},
4105 /*rhsIndex*/ {kw},
4106 /*resIndex*/ {n, c, w}}))
4107 return conv(Conv1DOpOrder::Ncw);
4108
4109 return rewriter.notifyMatchFailure(op, "not a pooling::Ncw layout");
4110 }
4111
4112 /// Entry point that transposes into the common form:
4113 /// {{n, strideW * w + dilationW * kw, c}, {kw, c}, {n, w, c}}
4114 FailureOr<Operation *> generateDilatedConv(uint64_t vecChDimSize = 0,
4115 bool vecChDimScalableFlag = false,
4116 bool flatten = false) {
4117 AffineExpr n, w, c, kw;
4118 bindDims(ctx, n, w, c, kw);
4119 if (!iters({Par(), Par(), Par(), Red()}))
4120 return rewriter.notifyMatchFailure(
4121 op, "failed to match depthwise::Nwc conv 3-par 1-red");
4122
4123 // No transposition needed.
4124 if (layout({/*lhsIndex*/ {n, strideW * w + dilationW * kw, c},
4125 /*rhsIndex*/ {kw, c},
4126 /*resIndex*/ {n, w, c}}))
4127 return depthwiseConv(vecChDimSize, vecChDimScalableFlag, flatten);
4128
4129 return rewriter.notifyMatchFailure(op, "not a depthwise::Nwc layout");
4130 }
4131
4132private:
4133 ConvOperationKind oper = ConvOperationKind::Conv;
4134 StringAttr redOp;
4135 StringAttr poolExtOp;
4136 bool isPoolExt = false;
4137 // Casts used to widen the convolution payload's lhs and rhs. These are null
4138 // only when the corresponding operand already has the accumulator type.
4139 Operation *lhsCastOp = nullptr;
4140 Operation *rhsCastOp = nullptr;
4141 int strideW, dilationW;
4142 Value lhsShaped, rhsShaped, resShaped;
4143 ShapedType lhsShapedType, rhsShapedType, resShapedType;
4144 vector::CombiningKind reductionKind;
4145
4146 // Sets oper, poolExtOp, isPoolExt and the conv operand casts for valid
4147 // conv/pooling ops.
4148 void setConvOperationKind(Operation *reduceOp) {
4149 int numBlockArguments =
4150 llvm::count_if(reduceOp->getOperands(), llvm::IsaPred<BlockArgument>);
4151 if (numBlockArguments == 1) {
4152 // Will be convolution if feeder is a MulOp.
4153 // A strength reduced version of MulOp for i1 type is AndOp which is also
4154 // supported. Otherwise, it can be pooling. This strength reduction logic
4155 // is in `buildBinaryFn` helper in the Linalg dialect.
4156 auto feedValIt = llvm::find_if_not(reduceOp->getOperands(),
4157 llvm::IsaPred<BlockArgument>);
4158 Operation *feedOp = (*feedValIt).getDefiningOp();
4159 if (isCastOfBlockArgument(feedOp)) {
4160 oper = ConvOperationKind::Pool;
4161 isPoolExt = true;
4162 poolExtOp = feedOp->getName().getIdentifier();
4163 return;
4164 }
4165 oper = ConvOperationKind::Conv;
4166 setConvCastOps(feedOp);
4167 return;
4168 }
4169 // numBlockArugments == 2 and this is a pooling op.
4170 oper = ConvOperationKind::Pool;
4171 isPoolExt = false;
4172 }
4173
4174 // Record the casts applied to the input and filter.
4175 void setConvCastOps(Operation *feedOp) {
4176 lhsCastOp = feedOp->getOperand(0).getDefiningOp();
4177 rhsCastOp = feedOp->getOperand(1).getDefiningOp();
4178 }
4179};
4180} // namespace
4181
4182/// Helper function to vectorize a LinalgOp with convolution semantics.
4183// TODO: extend the generic vectorization to support windows and drop this.
4184static FailureOr<Operation *> vectorizeConvolution(
4185 RewriterBase &rewriter, LinalgOp op, ArrayRef<int64_t> inputVecSizes,
4186 ArrayRef<bool> inputScalableVecDims, bool flatten1DDepthwiseConv) {
4187 FailureOr<Conv1DGenerator> conv1dGen = Conv1DGenerator::create(rewriter, op);
4188 if (failed(conv1dGen))
4189 return failure();
4190 auto res = conv1dGen->generateNonChanneledConv();
4191 if (succeeded(res))
4192 return res;
4193 res = conv1dGen->generateNwcConv();
4194 if (succeeded(res))
4195 return res;
4196 res = conv1dGen->generateNcwConv();
4197 if (succeeded(res))
4198 return res;
4199 res = conv1dGen->generateNwcPooling();
4200 if (succeeded(res))
4201 return res;
4202 res = conv1dGen->generateNcwPooling();
4203 if (succeeded(res))
4204 return res;
4205
4206 // Only depthwise 1D NWC convs are left - these can be vectorized using masks
4207 // and scalable vectors. Note that ATM the only dim that can be dynamic (i.e.
4208 // masked/scalable) is the channel dim (i.e. the trailing dim).
4209 uint64_t vecChDimSize = ShapedType::kDynamic;
4210 bool vecChDimScalableFlag = false;
4211 if (!inputVecSizes.empty()) {
4212 // Only use the input vector size corresponding to the channel dim. Other
4213 // vector dims will be inferred from the Ops.
4216 "Not a 1D depthwise conv!");
4217 size_t chDimIdx = 0;
4219 chDimIdx = 2;
4221 chDimIdx = 1;
4222
4223 vecChDimSize = inputVecSizes[chDimIdx];
4224 vecChDimScalableFlag = inputScalableVecDims[chDimIdx];
4225 }
4226 return conv1dGen->generateDilatedConv(vecChDimSize, vecChDimScalableFlag,
4227 flatten1DDepthwiseConv);
4228}
4229
4230struct VectorizeConvolution : public OpInterfaceRewritePattern<LinalgOp> {
4231 using Base::Base;
4232
4233 LogicalResult matchAndRewrite(LinalgOp op,
4234 PatternRewriter &rewriter) const override {
4235 FailureOr<Operation *> resultOrFail = vectorizeConvolution(rewriter, op);
4236 if (failed(resultOrFail))
4237 return failure();
4238 Operation *newOp = *resultOrFail;
4239 if (newOp->getNumResults() == 0) {
4240 rewriter.eraseOp(op.getOperation());
4241 return success();
4242 }
4243 assert(newOp->getNumResults() == 1 && "expected single result");
4244 rewriter.replaceOp(op.getOperation(), newOp->getResult(0));
4245 return success();
4246 }
4247};
4248
4250 RewritePatternSet &patterns, PatternBenefit benefit) {
4251 patterns.add<VectorizeConvolution>(patterns.getContext(), benefit);
4252}
return success()
lhs
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
static std::optional< VectorShape > vectorShape(Type type)
static SmallVector< Value > slice(OpBuilder &b, Location loc, Value value, VectorType nativeType)
static bool isLoopInvariantIdx(LinalgOp &linalgOp, Value &val, VectorType resType)
Checks whether val can be used for calculating a loop invariant index.
static Value insertConvResultSlices(RewriterBase &rewriter, Location loc, Value res, int64_t wSize, int64_t wSizeStep, SmallVectorImpl< Value > &resVals, bool isSingleChanneled)
Helper function to insert the computed result slices.
static SmallVector< bool > getDimsToReduce(LinalgOp linalgOp)
static VectorMemoryAccessKind getTensorExtractMemoryAccessPattern(tensor::ExtractOp extractOp, LinalgOp &linalgOp, VectorType resType)
Infer the memory access pattern for the input ExtractOp.
static SmallVector< Value > extractConvInputSlices(RewriterBase &rewriter, Location loc, Value input, int64_t nSize, int64_t wSize, int64_t cSize, int64_t kwSize, int strideW, int dilationW, int64_t wSizeStep, bool isSingleChanneled)
Helper function to extract the input slices after filter is unrolled along kw.
VectorMemoryAccessKind
@ Contiguous
@ Gather
@ ScalarBroadcast
static VectorizationHookResult vectorizeTensorExtract(RewriterBase &rewriter, VectorizationState &state, Operation *op, LinalgOp linalgOp, const IRMapping &bvm)
Helper function to vectorize the tensor.extract operations.
static VectorizationHookResult vectorizeLinalgIndex(RewriterBase &rewriter, VectorizationState &state, Operation *op, LinalgOp linalgOp)
Helper function to vectorize the index operations of a linalgOp.
static LogicalResult vectorizeAsInsertSliceOp(RewriterBase &rewriter, tensor::InsertSliceOp sliceOp, ArrayRef< int64_t > inputVectorSizes, SmallVectorImpl< Value > &newResults)
Vectorize tensor::InsertSliceOp with:
static FailureOr< Operation * > vectorizeConvolution(RewriterBase &rewriter, LinalgOp convOp, ArrayRef< int64_t > inputVecSizes={}, ArrayRef< bool > inputVecScalableFlags={}, bool flatten1DDepthwiseConv=false)
Try to vectorize convOp as a convolution.
static LogicalResult vectorizeAsLinalgGeneric(RewriterBase &rewriter, VectorizationState &state, LinalgOp linalgOp, SmallVectorImpl< Value > &newResults)
Generic vectorization function that rewrites the body of a linalgOp into vector form.
#define MATCH_1D_CONV_POOL_OP(ConvOpTy)
static VectorizationHookResult vectorizeOneOp(RewriterBase &rewriter, VectorizationState &state, LinalgOp linalgOp, Operation *op, const IRMapping &bvm, ArrayRef< CustomVectorizationHook > customVectorizationHooks)
Generic vectorization for a single operation op, given already vectorized operands carried by bvm.
static Operation * matchLinalgReduction(OpOperand *outputOperand)
Check whether outputOperand is a reduction with a single combiner operation.
static Value buildVectorWrite(RewriterBase &rewriter, Value value, OpOperand *outputOperand, VectorizationState &state)
Build a vector.transfer_write of value into outputOperand at indices set to all 0; where outputOperan...
static Value getStaticPadVal(Operation *op)
Returns the effective Pad value for the input op, provided it's a scalar.
static SmallVector< Value > extractConvFilterSlices(RewriterBase &rewriter, Location loc, Value filter, int64_t kwSize)
Helper function to extract the filter slices after filter is unrolled along kw.
static bool hasReductionIterator(LinalgOp &op)
Check if op is a linalg.reduce or a linalg.generic that has at least one reduction iterator.
std::function< LogicalResult(Operation *, bool)> CustomVectorizationPrecondition
static uint64_t getTrailingNonUnitLoopDimIdx(LinalgOp linalgOp)
Find the index of the trailing non-unit dim in linalgOp.
static VectorType getCollapsedVecType(VectorType type, ArrayRef< AffineMap > reassociation)
Given the re-associations, "collapses" the input Vector type.
Conv1DOpOrder
Helper enum to represent conv1d input traversal order.
VectorizationHookStatus
Helper data structure to represent the result of vectorization for a single operation.
@ Failure
Op failed to vectorize.
@ NewOp
Op vectorized into a new Op whose results will replace original Op's results.
@ NoReplace
Op vectorized and custom function took care of replacement logic.
static Operation * reduceIfNeeded(OpBuilder &b, LinalgOp linalgOp, Operation *op, Value reduceValue, Value initialValue, const IRMapping &bvm)
Emit reduction operations if the shapes of the value to reduce is different that the result shape.
std::function< VectorizationHookResult(Operation *, const IRMapping &)> CustomVectorizationHook
static AffineMap reindexIndexingMap(AffineMap map)
Given an indexing map coming from a LinalgOp indexing, restricted to a projectedPermutation,...
static LogicalResult tensorExtractVectorizationPrecondition(Operation *op, bool vectorizeNDExtract)
Helper function to check if the tensor.extract can be vectorized by the custom hook vectorizeTensorEx...
static Value broadcastIfNeeded(OpBuilder &b, Value value, Type dstType)
Broadcast value to a vector of shape if possible.
static Value calculateGatherOffset(RewriterBase &rewriter, VectorizationState &state, tensor::ExtractOp extractOp, const IRMapping &bvm)
Calculates the offsets ($index_vec) for vector.gather operations generated from tensor....
static SmallVector< Value > extractConvResultSlices(RewriterBase &rewriter, Location loc, Value res, int64_t nSize, int64_t wSize, int64_t fSize, int64_t wSizeStep, bool isSingleChanneled)
Helper function to extract the result slices after filter is unrolled along kw.
static bool isContiguousLoadIdx(LinalgOp &linalgOp, Value &val, bool &foundIndexOp, VectorType resType)
Check whether val could be used for calculating the trailing index for a contiguous load operation.
static VectorizationHookResult vectorizeLinalgYield(RewriterBase &rewriter, Operation *op, const IRMapping &bvm, VectorizationState &state, LinalgOp linalgOp, SmallVectorImpl< Value > &newResults)
Helper function to vectorize the terminator of a linalgOp.
static Operation * buildMultiDimReduce(OpBuilder &b, Operation *reduceOp, Value valueToReduce, Value acc, ArrayRef< bool > dimsToMask)
Create MultiDimReductionOp to compute the reduction for reductionOp.
#define mul(a, b)
A dimensional identifier appearing in an affine expression.
Definition AffineExpr.h:225
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
static AffineMap getMinorIdentityMap(unsigned dims, unsigned results, MLIRContext *context)
Returns an identity affine map (d0, ..., dn) -> (dp, ..., dn) on the most minor dimensions.
MLIRContext * getContext() const
static AffineMap getMultiDimIdentityMap(unsigned numDims, MLIRContext *context)
Returns an AffineMap with 'numDims' identity result dim exprs.
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
bool isProjectedPermutation(bool allowZeroInResults=false) const
Returns true if the AffineMap represents a subset (i.e.
unsigned getNumResults() const
unsigned getNumInputs() const
static AffineMap getFilteredIdentityMap(MLIRContext *ctx, unsigned numDims, llvm::function_ref< bool(AffineDimExpr)> keepDimFilter)
Returns an identity affine map with numDims input dimensions and filtered results using keepDimFilter...
AffineMap dropZeroResults()
Returns the AffineMap resulting from removing "zero" results (constant values == 0) from this map.
static AffineMap getPermutationMap(ArrayRef< unsigned > permutation, MLIRContext *context)
Returns an AffineMap representing a permutation.
SmallVector< unsigned > getBroadcastDims() const
Returns the list of broadcast dimensions (i.e.
AffineMap compose(AffineMap map) const
Returns the AffineMap resulting from composing this with map.
bool isPermutation() const
Returns true if the AffineMap represents a symbol-less permutation map.
This class represents an argument of a Block.
Definition Value.h:308
unsigned getArgNumber() const
Returns the number of this argument.
Definition Value.h:320
Block represents an ordered list of Operations.
Definition Block.h:34
OpListType & getOperations()
Definition Block.h:162
AffineMap getMultiDimIdentityMap(unsigned rank)
Definition Builders.cpp:396
StringAttr getStringAttr(const Twine &bytes)
Definition Builders.cpp:271
TypedAttr getZeroAttr(Type type)
Definition Builders.cpp:333
AffineExpr getAffineDimExpr(unsigned position)
Definition Builders.cpp:373
IntegerType getI1Type()
Definition Builders.cpp:61
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
Definition Builders.cpp:275
MLIRContext * getContext() const
Definition Builders.h:56
IndexType getIndexType()
Definition Builders.cpp:59
ArrayAttr getBoolArrayAttr(ArrayRef< bool > values)
Definition Builders.cpp:279
static DenseIntElementsAttr get(const ShapedType &type, Arg &&arg)
Get an instance of a DenseIntElementsAttr with the given arguments.
This is a utility class for mapping one set of IR entities to another.
Definition IRMapping.h:26
auto lookup(T from) const
Lookup a mapped value within the map.
Definition IRMapping.h:72
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
Definition IRMapping.h:30
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
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
This class helps build Operations.
Definition Builders.h:210
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
Definition Builders.cpp:581
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition Builders.cpp:466
Operation * insert(Operation *op)
Insert the given operation at the current insertion point and return it.
Definition Builders.cpp:430
This class represents an operand of an operation.
Definition Value.h:256
unsigned getOperandNumber() const
Return which operand this is in the OpOperand list of the Operation.
Definition Value.cpp:231
StringAttr getIdentifier() const
Return the name of this operation as a StringAttr.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
PropertyRef getPropertiesStorage()
Return a generic (but typed) reference to the property type storage.
Definition Operation.h:955
Value getOperand(unsigned idx)
Definition Operation.h:377
bool isBeforeInBlock(Operation *other)
Given an operation 'other' that is within the same parent block, return whether the current operation...
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
unsigned getNumOperands()
Definition Operation.h:373
Attribute getPropertiesAsAttribute()
Return the properties converted to an attribute.
operand_iterator operand_end()
Definition Operation.h:402
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
DictionaryAttr getDiscardableAttrDictionary()
Return all of the discardable attributes on this operation as a DictionaryAttr.
Definition Operation.h:555
static Operation * create(Location location, OperationName name, TypeRange resultTypes, ValueRange operands, NamedAttrList &&attributes, PropertyRef properties, BlockRange successors, unsigned numRegions)
Create a new Operation with the specific fields.
Definition Operation.cpp:65
result_type_range getResultTypes()
Definition Operation.h:455
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
result_range getResults()
Definition Operation.h:442
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
unsigned short getBenefit() const
If the corresponding pattern can match, return its benefit. If the.
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
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...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
void replaceAllUsesExcept(Value from, Value to, Operation *exceptedUser)
Find uses of from and replace them with to except if the user is exceptedUser.
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,...
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
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
bool isIndex() const
Definition Types.cpp:56
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
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
Definition Value.h:188
Location getLoc() const
Return the location of this value.
Definition Value.cpp:24
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:453
Operation * getOwner() const
Return the owner of this operand.
Definition UseDefLists.h:38
bool hasElementwiseMappableTraits(Operation *op)
Together, Elementwise, Scalarizable, Vectorizable, and Tensorizable provide an easy way for scalar op...
bool hasVectorizationImpl(Operation *)
Return true if there's dedicated logic in the Linalg Vectorizer to vectorize this Op,...
SmallVector< int64_t > getUnPackInverseSrcPerm(linalg::UnPackOp, PackingMetadata &metadata)
Compute inverse permutation for the source tensor (i.e.
bool allIndexingsAreProjectedPermutation(LinalgOp op)
Check if all indexing maps are projected permutations.
Definition Utils.cpp:197
FailureOr< VectorizationResult > vectorize(RewriterBase &rewriter, Operation *op, ArrayRef< int64_t > inputVectorSizes={}, ArrayRef< bool > inputScalableVecDims={}, bool vectorizeNDExtract=false, bool flatten1DDepthwiseConv=false, bool assumeDynamicDimsMatchVecSizes=false, bool createNamedContraction=false)
Returns a VectorizationResult containing the results of the vectorized op, or failure if the transfor...
void populatePadOpVectorizationPatterns(RewritePatternSet &patterns, PatternBenefit baseBenefit=1)
Populates patterns with patterns that vectorize tensor.pad.
bool isReductionIterator(utils::IteratorType iteratorType)
Check if iterator type has "reduction" semantics.
Definition Utils.cpp:236
bool isaConvolutionOpInterface(LinalgOp linalgOp, bool allowEmptyConvolvedDims=false)
Checks whether linalgOp conforms to ConvolutionOpInterface.
void populateConvolutionVectorizationPatterns(RewritePatternSet &patterns, PatternBenefit benefit=1)
Populate patterns for vectorizing low-D convolution ops.
bool isElementwise(LinalgOp op)
Check if a LinalgOp is an element-wise operation.
Definition Utils.cpp:217
LogicalResult vectorizeCopy(RewriterBase &builder, memref::CopyOp copyOp)
Emit a suitable vector form for a Copy op with fully static shape.
LogicalResult vectorizeOpPrecondition(Operation *op, ArrayRef< int64_t > inputVectorSizes={}, ArrayRef< bool > inputScalableVecDims={}, bool vectorizeNDExtract=false, bool flatten1DDepthwiseConv=false)
Return success if the operation can be vectorized.
SmallVector< int64_t > getPackInverseDestPerm(linalg::PackOp packOp, PackingMetadata &metadata)
Compute inverse permutation for the destination tensor (i.e.
bool isaConvolutionOpOfType(LinalgOp op)
Returns true if the linalg op is a convolution op of type ConvOpTy.
Definition Utils.h:126
std::optional< vector::CombiningKind > getCombinerOpKind(Operation *combinerOp)
Return vector::CombiningKind for the given op.
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
LogicalResult promote(RewriterBase &rewriter, scf::ForallOp forallOp)
Promotes the loop body of a scf::ForallOp to its containing block.
Definition SCF.cpp:750
std::enable_if_t<!is_complex< V >::value, V > readValue(char **linePtr)
Returns an element-value of non-complex type.
Definition File.h:50
Operation * maskOperation(OpBuilder &builder, Operation *maskableOp, Value mask, Value passthru=Value())
Creates a vector.mask operation around a maskable operation.
LogicalResult isValidMaskedInputVector(ArrayRef< int64_t > shape, ArrayRef< int64_t > inputVectorSizes)
Returns success if inputVectorSizes is a valid masking configuraion for given shape,...
BroadcastableToResult isBroadcastableTo(Type srcType, VectorType dstVectorType, std::pair< VectorDim, VectorDim > *mismatchingDims=nullptr)
Return whether srcType can be broadcast to dstVectorType under the semantics of the vector....
Operation * createWriteOrMaskedWrite(OpBuilder &builder, Location loc, Value vecToStore, Value dest, SmallVector< Value > writeIndices={}, bool useInBoundsInsteadOfMasking=false, AffineMap permutationMap=AffineMap())
Create a TransferWriteOp of vecToStore into dest.
Value createReadOrMaskedRead(OpBuilder &builder, Location loc, Value source, const VectorType &vecToReadTy, std::optional< Value > padValue=std::nullopt, bool useInBoundsInsteadOfMasking=false, ArrayRef< Value > indices={}, AffineMap permutationMap=AffineMap())
Creates a TransferReadOp from source.
SmallVector< OpFoldResult > getMixedSizesXfer(bool hasTensorSemantics, Operation *xfer, RewriterBase &rewriter)
A wrapper for getMixedSizes for vector.transfer_read and vector.transfer_write Ops (for source and de...
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
bool isEqualConstantIntOrValue(OpFoldResult ofr1, OpFoldResult ofr2)
Return true if ofr1 and ofr2 are the same integer constant attribute values or the same SSA value.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
AffineMap inverseAndBroadcastProjectedPermutation(AffineMap map)
Return the reverse map of a projected permutation where the projected dimensions are transformed into...
void bindDims(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to DimExpr at positions: [0 .
Definition AffineExpr.h:313
AffineMap inversePermutation(AffineMap map)
Returns a map of codomain to domain dimensions such that the first codomain dimension for a particula...
SmallVector< AffineMap, 4 > getSymbolLessAffineMaps(ArrayRef< ReassociationExprs > reassociation)
Constructs affine maps out of Array<Array<AffineExpr>>.
SmallVector< SmallVector< OpFoldResult > > ReifiedRankedShapedTypeDims
Value matchReduction(ArrayRef< BlockArgument > iterCarriedArgs, unsigned redPos, SmallVectorImpl< Operation * > &combinerOps)
Utility to match a generic reduction given a list of iteration-carried arguments, iterCarriedArgs and...
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:128
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
std::conditional_t< std::is_same_v< Ty, mlir::Type >, mlir::Value, detail::TypedValue< Ty > > TypedValue
If Ty is mlir::Type this will select Value instead of having a wrapper around it.
Definition Value.h:496
void getUsedValuesDefinedAbove(Region &region, Region &limit, SetVector< Value > &values)
Fill values with a list of values defined at the ancestors of the limit region and used within region...
AffineMap compressUnusedDims(AffineMap map)
Drop the dims that are not used.
SmallVector< SmallVector< AffineExpr, 2 >, 2 > convertReassociationIndicesToExprs(MLIRContext *context, ArrayRef< ReassociationIndices > reassociationIndices)
Convert reassociation indices to affine expressions.
bool isReassociationValid(ArrayRef< AffineMap > reassociation, int *invalidIndex=nullptr)
Return true if the reassociation specification is valid, false otherwise.
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:147
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
Definition Utils.cpp:114
AffineExpr getAffineConstantExpr(int64_t constant, MLIRContext *context)
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
SmallVector< T > applyPermutationMap(AffineMap map, llvm::ArrayRef< T > source)
Apply a permutation from map to source and return the result.
Definition AffineMap.h:677
llvm::SmallBitVector getUnusedDimsBitVector(ArrayRef< AffineMap > maps)
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
void applyPermutationToVector(SmallVector< T, N > &inVec, ArrayRef< int64_t > permutation)
Apply the permutation defined by permutation to inVec.
SmallVector< int64_t > invertPermutationVector(ArrayRef< int64_t > permutation)
Helper method to apply to inverse a permutation.
VectorizationHookResult contains the vectorized op returned from a CustomVectorizationHook.
enum VectorizationHookStatus status
Return status from vectorizing the current op.
Operation * newOp
New vectorized operation to replace the current op.
ArrayRef< int64_t > getCanonicalVecShape() const
Returns the canonical vector shape used to vectorize the iteration space.
LogicalResult initState(RewriterBase &rewriter, LinalgOp linalgOp, ArrayRef< int64_t > inputVectorSizes, ArrayRef< bool > inputScalableVecDims, bool assumeDynamicDimsMatchVecSizes=false)
Initializes the vectorization state, including the computation of the canonical vector shape for vect...
Operation * maskOperation(RewriterBase &rewriter, Operation *opToMask, LinalgOp linalgOp, std::optional< AffineMap > maybeIndexingMap=std::nullopt)
Masks an operation with the canonical vector mask if the operation needs masking.
VectorType getCanonicalVecType(Type elementType, std::optional< AffineMap > dimPermutation=std::nullopt) const
Returns a vector type of the provided elementType with the canonical vector shape and the correspondi...
ArrayRef< bool > getScalableVecDims() const
Returns the vector dimensions that are scalable in the canonical vector shape.
Value getOrCreateMaskFor(RewriterBase &rewriter, LinalgOp linalgOp, std::optional< AffineMap > maybeMaskingMap=std::nullopt)
Create or retrieve an existing mask value for the canonical vector iteration space.
VectorizationState(RewriterBase &rewriter)
LogicalResult matchAndRewrite(vector::TransferReadOp xferOp, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(vector::TransferWriteOp xferOp, PatternRewriter &rewriter) const override