MLIR 24.0.0git
VectorUnroll.cpp
Go to the documentation of this file.
1//===- VectorUnrollDistribute.cpp - patterns to do vector unrolling -------===//
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 patterns to do vector unrolling and vector distribution.
10//
11//===----------------------------------------------------------------------===//
12
19#include "llvm/ADT/MapVector.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/Support/DebugLog.h"
22#include "llvm/Support/InterleavedRange.h"
23#include <optional>
24
25#define DEBUG_TYPE "vector-unroll"
26
27using namespace mlir;
28using namespace mlir::vector;
29
30SmallVector<Value> mlir::vector::sliceTransferIndices(
32 AffineMap permutationMap, Location loc, OpBuilder &builder) {
33 MLIRContext *ctx = builder.getContext();
34 auto isBroadcast = [](AffineExpr expr) {
35 if (auto constExpr = dyn_cast<AffineConstantExpr>(expr))
36 return constExpr.getValue() == 0;
37 return false;
38 };
39 // Compute 'sliceIndices' by adding 'sliceOffsets[i]' to 'indices[i]'.
40 SmallVector<Value> slicedIndices(indices);
41 for (const auto &dim : llvm::enumerate(permutationMap.getResults())) {
42 int64_t elementOffset = elementOffsets[dim.index()];
43 if (isBroadcast(dim.value()) || elementOffset == 0)
44 continue;
45 unsigned pos = cast<AffineDimExpr>(dim.value()).getPosition();
46 auto expr = getAffineDimExpr(0, builder.getContext()) +
47 getAffineConstantExpr(elementOffset, ctx);
48 auto map = AffineMap::get(/*dimCount=*/1, /*symbolCount=*/0, expr);
49 slicedIndices[pos] =
50 affine::AffineApplyOp::create(builder, loc, map, indices[pos]);
51 }
52 return slicedIndices;
53}
54
55// Compute the new indices by adding `offsets` to `originalIndices`.
56// If m < n (m = offsets.size(), n = originalIndices.size()),
57// then only the trailing m values in `originalIndices` are updated.
59 Location loc,
60 OperandRange originalIndices,
61 ArrayRef<int64_t> offsets) {
62 assert(offsets.size() <= originalIndices.size() &&
63 "Offsets should not exceed the number of original indices");
64 SmallVector<Value> indices(originalIndices);
65
66 auto start = indices.size() - offsets.size();
67 for (auto [i, offset] : llvm::enumerate(offsets)) {
68 if (offset != 0) {
69 indices[start + i] = arith::AddIOp::create(
70 rewriter, loc, originalIndices[start + i],
71 arith::ConstantIndexOp::create(rewriter, loc, offset));
72 }
73 }
74 return indices;
75}
76
77// Clones `op` into a new operations that takes `operands` and returns
78// `resultTypes`.
80 Operation *op,
81 ArrayRef<Value> operands,
82 ArrayRef<Type> resultTypes) {
83 OperationState state(loc, op->getName(), operands, resultTypes,
84 op->getDiscardableAttrDictionary().getValue());
86 return builder.create(state);
87}
88
89/// Return the target shape for unrolling for the given op, provided through its
90/// VectorUnrollOpInterface object, `iface`. Return std::nullopt if the op
91/// shouldn't be or cannot be unrolled. Ops masked by an enclosing vector.mask
92/// are rejected unless `allowMasked` is set, which only patterns that slice the
93/// mask for each unrolled op may do.
94///
95/// ATM, target shape can be specified two-fold:
96/// 1. Via `VectorUnrollOpInterface` (see `getDefaultUnrollTargetShape`).
97/// 2. Via `UnrollVectorOptions` (see `nativeShape`).
98///
99/// Input from a "user" always takes precedence, i.e. 1. is used iff 2. (used
100/// for "user" input) is not available.
101static std::optional<SmallVector<int64_t>>
103 VectorUnrollOpInterface &iface, bool allowMasked = false) {
104 auto op = iface.getOperation();
105
106 if (options.filterConstraint && failed(options.filterConstraint(op))) {
107 LDBG() << "--no filter constraint -> BAIL";
108 return std::nullopt;
109 }
110
111 LDBG() << "Get unroll shape for op " << op->getName().getStringRef();
112 auto tS = iface.getDefaultUnrollTargetShape();
113
114 // Unrolling a masked op would put several ops inside its vector.mask region,
115 // and the enclosing mask would not be sliced to match them.
116 auto maskableOp = dyn_cast<vector::MaskableOpInterface>(op);
117 if (!allowMasked && maskableOp && maskableOp.isMasked()) {
118 LDBG() << "--op is masked -> BAIL";
119 return std::nullopt;
120 }
121 auto maybeUnrollShape = iface.getIterationShapeToUnroll();
122 if (!maybeUnrollShape) {
123 LDBG() << "--could not get shape of op " << *op << " -> BAIL";
124 return std::nullopt;
125 }
126 LDBG() << "--vector op shape: " << llvm::interleaved(*maybeUnrollShape);
127
128 std::optional<SmallVector<int64_t>> targetShape =
129 options.nativeShape ? options.nativeShape(op) : tS;
130 if (!targetShape) {
131 LDBG() << "--no unrolling target shape defined " << *op << "-> SKIP";
132 return std::nullopt;
133 }
134 LDBG() << "--target shape: " << llvm::interleaved(*targetShape);
135
136 auto maybeShapeRatio = computeShapeRatio(*maybeUnrollShape, *targetShape);
137 if (!maybeShapeRatio) {
138 LDBG() << "--could not compute integral shape ratio -> BAIL";
139 return std::nullopt;
140 }
141 if (llvm::all_of(*maybeShapeRatio, [](int64_t v) { return v == 1; })) {
142 LDBG() << "--no unrolling needed -> SKIP";
143 return std::nullopt;
144 }
145 LDBG() << "--found an integral shape ratio to unroll to -> SUCCESS";
146 return targetShape;
147}
148
149/// Fail if `xferOp`, masked by an enclosing vector.mask, is masked in a way
150/// that the transfer unrolling patterns do not support yet.
151template <typename TransferOpTy>
152static LogicalResult
154 PatternRewriter &rewriter) {
155 // Extra dimensions from a vector element type are not represented in the
156 // transfer's mask.
157 if (xferOp.getVectorType().getRank() != xferOp.getTransferRank())
158 return rewriter.notifyMatchFailure(
159 xferOp, "masked transfer with a vector element type");
160 // With a minor identity map and a scalar element type, the mask has the same
161 // shape as the vector, so each tile of the vector has the tile of the mask at
162 // the same offsets.
163 if (!xferOp.getPermutationMap().isMinorIdentity())
164 return rewriter.notifyMatchFailure(
165 xferOp, "masked transfer with a non-minor-identity map");
166 if (xferOp.getVectorType().isScalable())
167 return rewriter.notifyMatchFailure(xferOp, "masked scalable transfer");
168 return success();
169}
170
171/// Wrap `tiledXferOp`, the new transfer for one tile, in a vector.mask with the
172/// tile of `maskingOp`'s mask (and passthru, if any) at `offsets` with shape
173/// `sizes`. `maskingOp` is the vector.mask around the original transfer;
174/// `tiledXferOp` is created outside of it. Return `tiledXferOp` itself if
175/// `maskingOp` is null.
177 Operation *tiledXferOp,
178 vector::MaskingOpInterface maskingOp,
180 ArrayRef<int64_t> strides) {
181 if (!maskingOp)
182 return tiledXferOp;
183 Value mask = rewriter.createOrFold<vector::ExtractStridedSliceOp>(
184 loc, maskingOp.getMask(), offsets, sizes, strides);
185 Value passthru;
186 if (maskingOp.hasPassthru())
187 passthru = rewriter.createOrFold<vector::ExtractStridedSliceOp>(
188 loc, maskingOp.getPassthru(), offsets, sizes, strides);
189 return vector::maskOperation(rewriter, tiledXferOp, mask, passthru);
190}
191
192namespace {
193struct UnrollTransferReadPattern
194 : public vector::MaskableOpRewritePattern<vector::TransferReadOp> {
195 UnrollTransferReadPattern(MLIRContext *context,
196 const vector::UnrollVectorOptions &options,
197 PatternBenefit benefit = 1)
198 : MaskableOpRewritePattern<vector::TransferReadOp>(context, benefit),
199 options(options) {}
200
201 FailureOr<Value>
202 matchAndRewriteMaskableOp(vector::TransferReadOp readOp,
203 vector::MaskingOpInterface maskingOp,
204 PatternRewriter &rewriter) const override {
205 // TODO: support 0-d corner case.
206 if (readOp.getTransferRank() == 0)
207 return failure();
208 if (readOp.getMask())
209 return failure();
210 // A read masked by an enclosing vector.mask is unrolled into one
211 // vector.mask per tile, each with its tile of the mask.
212 if (maskingOp &&
214 return failure();
215 // TODO: This is shared between all Unroll patterns - merge.
216 auto iface = dyn_cast<VectorUnrollOpInterface>(readOp.getOperation());
217 auto targetShape = getTargetShape(options, iface, /*allowMasked=*/true);
218 if (!targetShape)
219 return failure();
220 auto sourceVectorType = readOp.getVectorType();
221 SmallVector<int64_t> strides(targetShape->size(), 1);
222 Location loc = readOp.getLoc();
223 ArrayRef<int64_t> originalSize = sourceVectorType.getShape();
224 // Bail-out if rank(source) != rank(target). The rewrite reuses the original
225 // permutation_map and in_bounds attributes, which must match the sliced
226 // vector rank. If needed, we can relax this later.
227 if (originalSize.size() != targetShape->size())
228 return rewriter.notifyMatchFailure(
229 readOp,
230 "expected source input vector rank to match target shape rank");
231
232 // Prepare the result vector;
233 Value result =
234 arith::ConstantOp::create(rewriter, loc, sourceVectorType,
235 rewriter.getZeroAttr(sourceVectorType));
236 auto targetType =
237 VectorType::get(*targetShape, sourceVectorType.getElementType());
238 SmallVector<Value> originalIndices(readOp.getIndices().begin(),
239 readOp.getIndices().end());
240 SmallVector<int64_t> loopOrder =
241 readOp.getUnrollOrder(options.reverseDefaultTraversalOrder);
242 for (SmallVector<int64_t> elementOffsets :
243 StaticTileOffsetRange(originalSize, *targetShape, loopOrder)) {
244 SmallVector<Value> indices =
245 sliceTransferIndices(elementOffsets, originalIndices,
246 readOp.getPermutationMap(), loc, rewriter);
247 Operation *slicedRead = vector::TransferReadOp::create(
248 rewriter, loc, targetType, readOp.getBase(), indices,
249 readOp.getPermutationMapAttr(), readOp.getPadding(), readOp.getMask(),
250 readOp.getInBoundsAttr());
251 slicedRead = maskTile(rewriter, loc, slicedRead, maskingOp,
252 elementOffsets, *targetShape, strides);
253
254 result = rewriter.createOrFold<vector::InsertStridedSliceOp>(
255 loc, slicedRead->getResult(0), result, elementOffsets, strides);
256 }
257 return result;
258 }
259
260private:
261 vector::UnrollVectorOptions options;
262};
263
264struct UnrollTransferWritePattern
265 : public vector::MaskableOpRewritePattern<vector::TransferWriteOp> {
266 UnrollTransferWritePattern(MLIRContext *context,
267 const vector::UnrollVectorOptions &options,
268 PatternBenefit benefit = 1)
269 : MaskableOpRewritePattern<vector::TransferWriteOp>(context, benefit),
270 options(options) {}
271
272 FailureOr<Value>
273 matchAndRewriteMaskableOp(vector::TransferWriteOp writeOp,
274 vector::MaskingOpInterface maskingOp,
275 PatternRewriter &rewriter) const override {
276 // TODO: support 0-d corner case.
277 if (writeOp.getTransferRank() == 0)
278 return failure();
279
280 if (writeOp.getMask())
281 return failure();
282 // A write masked by an enclosing vector.mask is unrolled into one
283 // vector.mask per tile, each with its tile of the mask.
284 if (maskingOp &&
286 return failure();
287 // TODO: This is shared between all Unroll patterns - merge.
288 auto iface = dyn_cast<VectorUnrollOpInterface>(writeOp.getOperation());
289 auto targetShape = getTargetShape(options, iface, /*allowMasked=*/true);
290 if (!targetShape)
291 return failure();
292 auto sourceVectorType = writeOp.getVectorType();
293 SmallVector<int64_t> strides(targetShape->size(), 1);
294 Location loc = writeOp.getLoc();
295 ArrayRef<int64_t> originalSize = sourceVectorType.getShape();
296 // Bail-out if rank(source) != rank(target). The main limitation here is the
297 // fact that `ExtractStridedSlice` requires the rank for the input and
298 // output to match. If needed, we can relax this later.
299 if (originalSize.size() != targetShape->size())
300 return rewriter.notifyMatchFailure(
301 writeOp,
302 "expected source input vector rank to match target shape rank");
303
304 SmallVector<Value> originalIndices(writeOp.getIndices().begin(),
305 writeOp.getIndices().end());
306 SmallVector<int64_t> loopOrder =
307 writeOp.getUnrollOrder(options.reverseDefaultTraversalOrder);
308 Value resultTensor;
309 for (SmallVector<int64_t> elementOffsets :
310 StaticTileOffsetRange(originalSize, *targetShape, loopOrder)) {
311 Value slicedVector = rewriter.createOrFold<vector::ExtractStridedSliceOp>(
312 loc, writeOp.getVector(), elementOffsets, *targetShape, strides);
313 SmallVector<Value> indices =
314 sliceTransferIndices(elementOffsets, originalIndices,
315 writeOp.getPermutationMap(), loc, rewriter);
316 Operation *slicedWrite = vector::TransferWriteOp::create(
317 rewriter, loc, slicedVector,
318 resultTensor ? resultTensor : writeOp.getBase(), indices,
319 writeOp.getPermutationMapAttr(), writeOp.getInBoundsAttr());
320 slicedWrite = maskTile(rewriter, loc, slicedWrite, maskingOp,
321 elementOffsets, *targetShape, strides);
322 // For the tensor case update the destination for the next transfer write.
323 if (!slicedWrite->getResults().empty())
324 resultTensor = slicedWrite->getResult(0);
325 }
326 // A write to a memref has no result to replace.
327 return resultTensor;
328 }
329
330private:
331 vector::UnrollVectorOptions options;
332};
333
334struct OffsetMapInfo {
335 static unsigned getHashValue(const SmallVector<int64_t> &v) {
336 return static_cast<unsigned>(llvm::hash_combine_range(v));
337 }
338
339 static bool isEqual(const SmallVector<int64_t> &lhs,
340 const SmallVector<int64_t> &rhs) {
341 return lhs == rhs;
342 }
343};
344
345struct UnrollContractionPattern
346 : public OpRewritePattern<vector::ContractionOp> {
347 UnrollContractionPattern(MLIRContext *context,
348 const vector::UnrollVectorOptions &options,
349 PatternBenefit benefit = 1)
350 : OpRewritePattern<vector::ContractionOp>(context, benefit),
351 options(options) {}
352
353 LogicalResult matchAndRewrite(vector::ContractionOp contractOp,
354 PatternRewriter &rewriter) const override {
355 // TODO: This is shared between all Unroll patterns - merge.
356 auto iface = dyn_cast<VectorUnrollOpInterface>(contractOp.getOperation());
357 auto targetShape = getTargetShape(options, iface);
358 if (!targetShape)
359 return failure();
360 auto dstVecType = cast<VectorType>(contractOp.getResultType());
361 SmallVector<int64_t> originalSize = *contractOp.getIterationShapeToUnroll();
362
363 Location loc = contractOp.getLoc();
364 unsigned accIndex = vector::ContractionOp::getAccOperandIndex();
365 AffineMap dstAffineMap = contractOp.getIndexingMapsArray()[accIndex];
366 llvm::MapVector<
367 SmallVector<int64_t>, Value,
368 llvm::DenseMap<SmallVector<int64_t>, unsigned, OffsetMapInfo>>
369 accCache;
370
371 // Set-up the unrolling order. If there's a user-specified order, make sure
372 // to use that.
373 SmallVector<int64_t> loopOrder =
374 contractOp.getUnrollOrder(options.reverseDefaultTraversalOrder);
375 if (!options.unrollOrderForContractOp.empty()) {
376 assert(options.unrollOrderForContractOp.size() == originalSize.size() &&
377 "Invalid loop order provided!");
378 loopOrder = options.unrollOrderForContractOp;
379 }
380
381 for (SmallVector<int64_t> offsets :
382 StaticTileOffsetRange(originalSize, *targetShape, loopOrder)) {
383 SmallVector<Value> slicesOperands(contractOp.getNumOperands());
384
385 // Helper to compute the new shape of each operand and extract the slice.
386 auto extractOperand = [&](unsigned index, Value operand,
387 AffineMap permutationMap,
388 ArrayRef<int64_t> operandOffets) {
389 SmallVector<int64_t> operandShape = applyPermutationMap(
390 permutationMap, ArrayRef<int64_t>(*targetShape));
391 SmallVector<int64_t> operandStrides(operandOffets.size(), 1);
392 slicesOperands[index] =
393 rewriter.createOrFold<vector::ExtractStridedSliceOp>(
394 loc, operand, operandOffets, operandShape, operandStrides);
395 };
396
397 // Extract the new lhs operand.
398 AffineMap lhsPermutationMap = contractOp.getIndexingMapsArray()[0];
399 SmallVector<int64_t> lhsOffets =
400 applyPermutationMap(lhsPermutationMap, ArrayRef<int64_t>(offsets));
401 extractOperand(0, contractOp.getLhs(), lhsPermutationMap, lhsOffets);
402
403 // Extract the new rhs operand.
404 AffineMap rhsPermutationMap = contractOp.getIndexingMapsArray()[1];
405 SmallVector<int64_t> rhsOffets =
406 applyPermutationMap(rhsPermutationMap, ArrayRef<int64_t>(offsets));
407 extractOperand(1, contractOp.getRhs(), rhsPermutationMap, rhsOffets);
408
409 AffineMap accPermutationMap = contractOp.getIndexingMapsArray()[2];
410 SmallVector<int64_t> accOffets =
411 applyPermutationMap(accPermutationMap, ArrayRef<int64_t>(offsets));
412 // If a version of the accumulator has already been computed, use it
413 // otherwise extract the first version from the original operand.
414 auto *accIt = accCache.find(accOffets);
415 if (accIt != accCache.end())
416 slicesOperands[2] = accIt->second;
417 else
418 extractOperand(2, contractOp.getAcc(), accPermutationMap, accOffets);
419
420 SmallVector<int64_t> dstShape =
421 applyPermutationMap(dstAffineMap, ArrayRef<int64_t>(*targetShape));
422 auto targetType = VectorType::get(dstShape, dstVecType.getElementType());
423 Operation *newOp = cloneOpWithOperandsAndTypes(
424 rewriter, loc, contractOp, slicesOperands, targetType);
425
426 SmallVector<int64_t> dstOffets =
427 applyPermutationMap(dstAffineMap, ArrayRef<int64_t>(offsets));
428 // Save the accumulated value untill all the loops are unrolled since
429 // reduction loop keep updating the accumulator.
430 accCache[dstOffets] = newOp->getResult(0);
431 }
432 // Assemble back the accumulator into a single vector.
433 Value result = arith::ConstantOp::create(rewriter, loc, dstVecType,
434 rewriter.getZeroAttr(dstVecType));
435 for (const auto &it : accCache) {
436 SmallVector<int64_t> dstStrides(it.first.size(), 1);
437 result = rewriter.createOrFold<vector::InsertStridedSliceOp>(
438 loc, it.second, result, it.first, dstStrides);
439 }
440 rewriter.replaceOp(contractOp, result);
441 return success();
442 }
443
444private:
445 vector::UnrollVectorOptions options;
446};
447
448struct UnrollMultiReductionPattern
449 : public OpRewritePattern<vector::MultiDimReductionOp> {
450 UnrollMultiReductionPattern(MLIRContext *context,
451 const vector::UnrollVectorOptions &options,
452 PatternBenefit benefit = 1)
453 : OpRewritePattern<vector::MultiDimReductionOp>(context, benefit),
454 options(options) {}
455
456 LogicalResult matchAndRewrite(vector::MultiDimReductionOp reductionOp,
457 PatternRewriter &rewriter) const override {
458
459 // TODO: This is shared between all Unroll patterns - merge.
460 auto iface = dyn_cast<VectorUnrollOpInterface>(reductionOp.getOperation());
461 std::optional<SmallVector<int64_t>> targetShape =
462 getTargetShape(options, iface);
463 if (!targetShape)
464 return failure();
465 SmallVector<int64_t> originalSize =
466 *reductionOp.getIterationShapeToUnroll();
467 Location loc = reductionOp.getLoc();
468 auto resultType = reductionOp->getResult(0).getType();
469
470 // A target shape with fewer dimensions than the source vector applies to
471 // its trailing dimensions. Add leading unit dimensions so that it can be
472 // used to slice the source and to index its dimensions.
473 SmallVector<int64_t> adjustedTargetShape(originalSize.size(), 1);
474 llvm::copy(*targetShape, adjustedTargetShape.end() - targetShape->size());
475
476 // Handle scalar result case: all dimensions are reduced.
477 // Each source tile is reduced to a scalar, and partial results are
478 // chained through the accumulator operand.
479 if (resultType.isIntOrFloat()) {
480 Value accumulator = reductionOp.getAcc();
481 for (SmallVector<int64_t> offsets :
482 StaticTileOffsetRange(originalSize, adjustedTargetShape)) {
483 SmallVector<int64_t> operandStrides(offsets.size(), 1);
484 Value slicedOperand =
485 rewriter.createOrFold<vector::ExtractStridedSliceOp>(
486 loc, reductionOp.getSource(), offsets, adjustedTargetShape,
487 operandStrides);
488 Operation *newOp = cloneOpWithOperandsAndTypes(
489 rewriter, loc, reductionOp, {slicedOperand, accumulator},
490 resultType);
491 accumulator = newOp->getResult(0);
492 }
493 rewriter.replaceOp(reductionOp, accumulator);
494 return success();
495 }
496
497 // Vector result case.
498 llvm::MapVector<
499 SmallVector<int64_t>, Value,
500 llvm::DenseMap<SmallVector<int64_t>, unsigned, OffsetMapInfo>>
501 accCache;
502
503 // Stride of the ratios, this gives us the offsets of sliceCount in a basis
504 // of multiples of the targetShape.
505 for (SmallVector<int64_t> offsets :
506 StaticTileOffsetRange(originalSize, adjustedTargetShape)) {
507 SmallVector<Value> operands;
508 SmallVector<int64_t> operandStrides(offsets.size(), 1);
509 Value slicedOperand =
510 rewriter.createOrFold<vector::ExtractStridedSliceOp>(
511 loc, reductionOp.getSource(), offsets, adjustedTargetShape,
512 operandStrides);
513 operands.push_back(slicedOperand);
514 SmallVector<int64_t> dstShape;
515 SmallVector<int64_t> destOffset;
516 for (size_t i : llvm::seq(size_t(0), adjustedTargetShape.size())) {
517 if (!reductionOp.isReducedDim(i)) {
518 destOffset.push_back(offsets[i]);
519 dstShape.push_back(adjustedTargetShape[i]);
520 }
521 }
522 Value acc;
523 SmallVector<int64_t> accStrides(destOffset.size(), 1);
524 // If a version of the accumulator has already been computed, use it
525 // otherwise extract the first version from the original operand.
526 auto *accIt = accCache.find(destOffset);
527 if (accIt != accCache.end())
528 acc = accIt->second;
529 else
530 acc = rewriter.createOrFold<vector::ExtractStridedSliceOp>(
531 loc, reductionOp.getAcc(), destOffset, dstShape, accStrides);
532 operands.push_back(acc);
533 auto targetType = VectorType::get(
534 dstShape, reductionOp.getSourceVectorType().getElementType());
535 Operation *newOp = cloneOpWithOperandsAndTypes(rewriter, loc, reductionOp,
536 operands, targetType);
537 Value result = newOp->getResult(0);
538 accCache[destOffset] = result;
539 }
540 // Assemble back the accumulator into a single vector.
541 Value result = arith::ConstantOp::create(
542 rewriter, loc, reductionOp.getDestType(),
543 rewriter.getZeroAttr(reductionOp.getDestType()));
544 for (const auto &it : accCache) {
545 SmallVector<int64_t> dstStrides(it.first.size(), 1);
546 result = rewriter.createOrFold<vector::InsertStridedSliceOp>(
547 loc, it.second, result, it.first, dstStrides);
548 }
549 rewriter.replaceOp(reductionOp, result);
550 return success();
551 }
552
553private:
554 vector::UnrollVectorOptions options;
555};
556
557struct UnrollElementwisePattern : public RewritePattern {
558 UnrollElementwisePattern(MLIRContext *context,
559 const vector::UnrollVectorOptions &options,
560 PatternBenefit benefit = 1)
561 : RewritePattern(MatchAnyOpTypeTag(), benefit, context),
562 options(options) {}
563
564 LogicalResult matchAndRewrite(Operation *op,
565 PatternRewriter &rewriter) const override {
567 return failure();
568 // TODO: This is shared between all Unroll patterns - merge.
569 auto iface = dyn_cast<VectorUnrollOpInterface>(op);
570 if (!iface)
571 return rewriter.notifyMatchFailure(op, "Not an unrollable elem-wise Op!");
572 auto targetShape = getTargetShape(options, iface);
573 if (!targetShape)
574 return failure();
575 int64_t targetShapeRank = targetShape->size();
576 auto dstVecType = cast<VectorType>(op->getResult(0).getType());
577 SmallVector<int64_t> originalSize = *iface.getIterationShapeToUnroll();
578 int64_t originalShapeRank = originalSize.size();
579
580 Location loc = op->getLoc();
581
582 // Handle rank mismatch by adding leading unit dimensions to targetShape
583 SmallVector<int64_t> adjustedTargetShape(originalShapeRank);
584 int64_t rankDiff = originalShapeRank - targetShapeRank;
585 std::fill(adjustedTargetShape.begin(),
586 adjustedTargetShape.begin() + rankDiff, 1);
587 std::copy(targetShape->begin(), targetShape->end(),
588 adjustedTargetShape.begin() + rankDiff);
589
590 int64_t adjustedTargetShapeRank = adjustedTargetShape.size();
591 // Prepare the result vector.
592 Value result = arith::ConstantOp::create(rewriter, loc, dstVecType,
593 rewriter.getZeroAttr(dstVecType));
594 SmallVector<int64_t> strides(adjustedTargetShapeRank, 1);
595 VectorType unrolledVecType =
596 VectorType::get(*targetShape, dstVecType.getElementType());
597
598 // Create the unrolled computation.
599 for (SmallVector<int64_t> offsets :
600 StaticTileOffsetRange(originalSize, adjustedTargetShape)) {
601 SmallVector<Value> extractOperands;
602 for (OpOperand &operand : op->getOpOperands()) {
603 auto vecType = dyn_cast<VectorType>(operand.get().getType());
604 if (!vecType) {
605 extractOperands.push_back(operand.get());
606 continue;
607 }
608 Value extracted = rewriter.createOrFold<vector::ExtractStridedSliceOp>(
609 loc, operand.get(), offsets, adjustedTargetShape, strides);
610
611 // Reshape to remove leading unit dims if needed
612 if (adjustedTargetShapeRank > targetShapeRank) {
613 extracted = rewriter.createOrFold<vector::ShapeCastOp>(
614 loc, VectorType::get(*targetShape, vecType.getElementType()),
615 extracted);
616 }
617 extractOperands.push_back(extracted);
618 }
619
620 Operation *newOp = cloneOpWithOperandsAndTypes(
621 rewriter, loc, op, extractOperands, unrolledVecType);
622
623 Value computeResult = newOp->getResult(0);
624
625 // Use strides sized to targetShape for proper insertion
626 SmallVector<int64_t> insertStrides =
627 (adjustedTargetShapeRank > targetShapeRank)
628 ? SmallVector<int64_t>(targetShapeRank, 1)
629 : strides;
630
631 result = rewriter.createOrFold<vector::InsertStridedSliceOp>(
632 loc, computeResult, result, offsets, insertStrides);
633 }
634 rewriter.replaceOp(op, result);
635 return success();
636 }
637
638private:
639 vector::UnrollVectorOptions options;
640};
641
642struct UnrollReductionPattern : public OpRewritePattern<vector::ReductionOp> {
643 UnrollReductionPattern(MLIRContext *context,
644 const vector::UnrollVectorOptions &options,
645 PatternBenefit benefit = 1)
646 : OpRewritePattern<vector::ReductionOp>(context, benefit),
647 options(options) {}
648
649 LogicalResult matchAndRewrite(vector::ReductionOp reductionOp,
650 PatternRewriter &rewriter) const override {
651 // TODO: This is shared between all Unroll patterns - merge.
652 auto iface = cast<VectorUnrollOpInterface>(*reductionOp);
653 std::optional<SmallVector<int64_t>> targetShape =
654 getTargetShape(options, iface);
655 if (!targetShape)
656 return failure();
657 SmallVector<int64_t> originalSize =
658 *reductionOp.getIterationShapeToUnroll();
659
660 // Create unrolled vector reduction.
661 Location loc = reductionOp.getLoc();
662 Value accumulator = nullptr;
663 for (SmallVector<int64_t> offsets :
664 StaticTileOffsetRange(originalSize, *targetShape)) {
665 SmallVector<int64_t> strides(offsets.size(), 1);
666 Value slicedOperand =
667 rewriter.createOrFold<vector::ExtractStridedSliceOp>(
668 loc, reductionOp.getVector(), offsets, *targetShape, strides);
669 Operation *newOp = cloneOpWithOperandsAndTypes(
670 rewriter, loc, reductionOp, slicedOperand, reductionOp.getType());
671 Value result = newOp->getResult(0);
672
673 if (!accumulator) {
674 // This is the first reduction.
675 accumulator = result;
676 } else {
677 // On subsequent reduction, combine with the accumulator.
678 accumulator = makeArithReduction(rewriter, loc, reductionOp.getKind(),
679 accumulator, result);
680 }
681 }
682
683 rewriter.replaceOp(reductionOp, accumulator);
684 return success();
685 }
686
687private:
688 const vector::UnrollVectorOptions options;
689};
690
691struct UnrollTransposePattern : public OpRewritePattern<vector::TransposeOp> {
692 UnrollTransposePattern(MLIRContext *context,
693 const vector::UnrollVectorOptions &options,
694 PatternBenefit benefit = 1)
695 : OpRewritePattern<vector::TransposeOp>(context, benefit),
696 options(options) {}
697
698 LogicalResult matchAndRewrite(vector::TransposeOp transposeOp,
699 PatternRewriter &rewriter) const override {
700 if (transposeOp.getResultVectorType().getRank() == 0)
701 return failure();
702 // TODO: This is shared between all Unroll patterns - merge.
703 auto iface = cast<VectorUnrollOpInterface>(*transposeOp);
704 auto targetShape = getTargetShape(options, iface);
705 if (!targetShape)
706 return failure();
707 auto originalVectorType = transposeOp.getResultVectorType();
708 SmallVector<int64_t> strides(targetShape->size(), 1);
709 Location loc = transposeOp.getLoc();
710 ArrayRef<int64_t> originalSize = originalVectorType.getShape();
711
712 // Prepare the result vector;
713 Value result =
714 arith::ConstantOp::create(rewriter, loc, originalVectorType,
715 rewriter.getZeroAttr(originalVectorType));
716 ArrayRef<int64_t> permutation = transposeOp.getPermutation();
717
718 // Unroll the computation.
719 for (SmallVector<int64_t> elementOffsets :
720 StaticTileOffsetRange(originalSize, *targetShape)) {
721 SmallVector<int64_t> permutedOffsets(elementOffsets.size());
722 SmallVector<int64_t> permutedShape(elementOffsets.size());
723 // Compute the source offsets and shape.
724 for (auto indices : llvm::enumerate(permutation)) {
725 permutedOffsets[indices.value()] = elementOffsets[indices.index()];
726 permutedShape[indices.value()] = (*targetShape)[indices.index()];
727 }
728 Value slicedOperand =
729 rewriter.createOrFold<vector::ExtractStridedSliceOp>(
730 loc, transposeOp.getVector(), permutedOffsets, permutedShape,
731 strides);
732 Value transposedSlice = rewriter.createOrFold<vector::TransposeOp>(
733 loc, slicedOperand, permutation);
734 result = rewriter.createOrFold<vector::InsertStridedSliceOp>(
735 loc, transposedSlice, result, elementOffsets, strides);
736 }
737 rewriter.replaceOp(transposeOp, result);
738 return success();
739 }
740
741private:
742 vector::UnrollVectorOptions options;
743};
744
745struct UnrollGatherPattern : public OpRewritePattern<vector::GatherOp> {
746 UnrollGatherPattern(MLIRContext *context,
747 const vector::UnrollVectorOptions &options,
748 PatternBenefit benefit = 1)
749 : OpRewritePattern<vector::GatherOp>(context, benefit), options(options) {
750 }
751
752 LogicalResult matchAndRewrite(vector::GatherOp gatherOp,
753 PatternRewriter &rewriter) const override {
754 VectorType sourceVectorType = gatherOp.getVectorType();
755 if (sourceVectorType.getRank() == 0)
756 return failure();
757 // TODO: This is shared between all Unroll patterns - merge.
758 auto iface = cast<VectorUnrollOpInterface>(*gatherOp);
759 auto targetShape = getTargetShape(options, iface);
760 if (!targetShape)
761 return failure();
762 SmallVector<int64_t> strides(targetShape->size(), 1);
763 Location loc = gatherOp.getLoc();
764 ArrayRef<int64_t> originalSize = gatherOp.getVectorType().getShape();
765
766 // Prepare the result vector;
767 Value result =
768 arith::ConstantOp::create(rewriter, loc, sourceVectorType,
769 rewriter.getZeroAttr(sourceVectorType));
770 auto targetType =
771 VectorType::get(*targetShape, sourceVectorType.getElementType());
772
773 SmallVector<int64_t> loopOrder =
774 gatherOp.getUnrollOrder(options.reverseDefaultTraversalOrder);
775 for (SmallVector<int64_t> elementOffsets :
776 StaticTileOffsetRange(originalSize, *targetShape, loopOrder)) {
777 // To get the unrolled gather, extract the same slice based on the
778 // decomposed shape from each of the index, mask, and pass-through
779 // vectors.
780 Value indexSubVec = rewriter.createOrFold<vector::ExtractStridedSliceOp>(
781 loc, gatherOp.getIndices(), elementOffsets, *targetShape, strides);
782 Value maskSubVec = rewriter.createOrFold<vector::ExtractStridedSliceOp>(
783 loc, gatherOp.getMask(), elementOffsets, *targetShape, strides);
784 Value passThruSubVec =
785 rewriter.createOrFold<vector::ExtractStridedSliceOp>(
786 loc, gatherOp.getPassThru(), elementOffsets, *targetShape,
787 strides);
788 auto slicedGather = vector::GatherOp::create(
789 rewriter, loc, targetType, gatherOp.getBase(), gatherOp.getOffsets(),
790 indexSubVec, maskSubVec, passThruSubVec);
791
792 result = rewriter.createOrFold<vector::InsertStridedSliceOp>(
793 loc, slicedGather, result, elementOffsets, strides);
794 }
795 rewriter.replaceOp(gatherOp, result);
796 return success();
797 }
798
799private:
800 vector::UnrollVectorOptions options;
801};
802
803struct UnrollLoadPattern : public OpRewritePattern<vector::LoadOp> {
804 UnrollLoadPattern(MLIRContext *context,
805 const vector::UnrollVectorOptions &options,
806 PatternBenefit benefit = 1)
807 : OpRewritePattern<vector::LoadOp>(context, benefit), options(options) {}
808
809 LogicalResult matchAndRewrite(vector::LoadOp loadOp,
810 PatternRewriter &rewriter) const override {
811 VectorType vecType = loadOp.getVectorType();
812
813 // TODO: This is shared between all Unroll patterns - merge.
814 auto iface = cast<VectorUnrollOpInterface>(*loadOp);
815 auto targetShape = getTargetShape(options, iface);
816 if (!targetShape)
817 return failure();
818
819 Location loc = loadOp.getLoc();
820 ArrayRef<int64_t> originalShape = vecType.getShape();
821 SmallVector<int64_t> strides(targetShape->size(), 1);
822
823 Value result = arith::ConstantOp::create(rewriter, loc, vecType,
824 rewriter.getZeroAttr(vecType));
825
826 SmallVector<int64_t> loopOrder =
827 loadOp.getUnrollOrder(options.reverseDefaultTraversalOrder);
828
829 auto targetVecType =
830 VectorType::get(*targetShape, vecType.getElementType());
831
832 for (SmallVector<int64_t> offsets :
833 StaticTileOffsetRange(originalShape, *targetShape, loopOrder)) {
834 SmallVector<Value> indices =
835 sliceLoadStoreIndices(rewriter, loc, loadOp.getIndices(), offsets);
836 Value slicedLoad = vector::LoadOp::create(rewriter, loc, targetVecType,
837 loadOp.getBase(), indices);
838 result = rewriter.createOrFold<vector::InsertStridedSliceOp>(
839 loc, slicedLoad, result, offsets, strides);
840 }
841 rewriter.replaceOp(loadOp, result);
842 return success();
843 }
844
845private:
846 vector::UnrollVectorOptions options;
847};
848
849struct UnrollStorePattern : public OpRewritePattern<vector::StoreOp> {
850 UnrollStorePattern(MLIRContext *context,
851 const vector::UnrollVectorOptions &options,
852 PatternBenefit benefit = 1)
853 : OpRewritePattern<vector::StoreOp>(context, benefit), options(options) {}
854
855 LogicalResult matchAndRewrite(vector::StoreOp storeOp,
856 PatternRewriter &rewriter) const override {
857 VectorType vecType = storeOp.getVectorType();
858
859 // TODO: This is shared between all Unroll patterns - merge.
860 auto iface = cast<VectorUnrollOpInterface>(*storeOp);
861 auto targetShape = getTargetShape(options, iface);
862 if (!targetShape)
863 return failure();
864
865 Location loc = storeOp.getLoc();
866 ArrayRef<int64_t> originalShape = vecType.getShape();
867 SmallVector<int64_t> strides(targetShape->size(), 1);
868
869 Value base = storeOp.getBase();
870 Value vector = storeOp.getValueToStore();
871
872 SmallVector<int64_t> loopOrder =
873 storeOp.getUnrollOrder(options.reverseDefaultTraversalOrder);
874
875 for (SmallVector<int64_t> offsets :
876 StaticTileOffsetRange(originalShape, *targetShape, loopOrder)) {
877 SmallVector<Value> indices =
878 sliceLoadStoreIndices(rewriter, loc, storeOp.getIndices(), offsets);
879 Value slice = rewriter.createOrFold<vector::ExtractStridedSliceOp>(
880 loc, vector, offsets, *targetShape, strides);
881 vector::StoreOp::create(rewriter, loc, slice, base, indices);
882 }
883 rewriter.eraseOp(storeOp);
884 return success();
885 }
886
887private:
888 vector::UnrollVectorOptions options;
889};
890
891struct UnrollBroadcastPattern : public OpRewritePattern<vector::BroadcastOp> {
892 UnrollBroadcastPattern(MLIRContext *context,
893 const vector::UnrollVectorOptions &options,
894 PatternBenefit benefit = 1)
895 : OpRewritePattern<vector::BroadcastOp>(context, benefit),
896 options(options) {}
897
898 LogicalResult matchAndRewrite(vector::BroadcastOp broadcastOp,
899 PatternRewriter &rewriter) const override {
900 // TODO: This is shared between all Unroll patterns - merge.
901 auto iface = cast<VectorUnrollOpInterface>(*broadcastOp);
902 auto targetShape = getTargetShape(options, iface);
903 if (!targetShape)
904 return failure();
905
906 Location loc = broadcastOp.getLoc();
907 VectorType srcType = dyn_cast<VectorType>(broadcastOp.getSourceType());
908 VectorType resType = broadcastOp.getResultVectorType();
909
910 SmallVector<int64_t> originalShape =
911 *broadcastOp.getIterationShapeToUnroll();
912 // Pad the target shape with leading unit dimensions when the broadcast
913 // result has a higher rank than the native shape.
914 SmallVector<int64_t> adjustedTargetShape(originalShape.size(), 1);
915 llvm::copy(*targetShape, adjustedTargetShape.end() - targetShape->size());
916
917 VectorType targetType =
918 resType.cloneWith(adjustedTargetShape, resType.getElementType());
919 Value result = arith::ConstantOp::create(rewriter, loc, resType,
920 rewriter.getZeroAttr(resType));
921
922 SmallVector<int64_t> strides(originalShape.size(), 1);
923
924 for (SmallVector<int64_t> offsets :
925 StaticTileOffsetRange(originalShape, adjustedTargetShape)) {
926 Value newSrc;
927 if (!srcType) {
928 // Scalar to vector broadcast.
929 newSrc = broadcastOp.getSource();
930 } else {
931 // Vector to vector broadcast.
932 int64_t rank = srcType.getRank();
933 SmallVector<int64_t> srcOffsets(offsets.end() - rank, offsets.end());
934 SmallVector<int64_t> srcShape(adjustedTargetShape.end() - rank,
935 adjustedTargetShape.end());
936 SmallVector<int64_t> srcStrides(strides.end() - rank, strides.end());
937 // adjust the offset and shape for src if the corresponding dim is 1.
938 for (int64_t i = 0; i < rank; ++i) {
939 if (srcType.getDimSize(i) == 1) {
940 srcOffsets[i] = 0;
941 srcShape[i] = 1;
942 }
943 }
944 newSrc = rewriter.createOrFold<vector::ExtractStridedSliceOp>(
945 loc, broadcastOp.getSource(), srcOffsets, srcShape, srcStrides);
946 }
947
948 Operation *newOp = cloneOpWithOperandsAndTypes(rewriter, loc, broadcastOp,
949 newSrc, targetType);
950
951 result = rewriter.createOrFold<vector::InsertStridedSliceOp>(
952 loc, newOp->getResult(0), result, offsets, strides);
953 }
954
955 rewriter.replaceOp(broadcastOp, result);
956 return success();
957 }
958
959private:
960 vector::UnrollVectorOptions options;
961};
962
963/// Unrolls 2 or more dimensional `vector.to_elements` ops by unrolling the
964/// outermost dimension of the operand. For example:
965///
966/// ```
967/// %0:4 = vector.to_elements %v : vector<2x2xf32>
968///
969/// ==>
970///
971/// %v0 = vector.extract %v[0] : vector<2x2xf32> from vector<2x2x2xf32>
972/// %v1 = vector.extract %v[1] : vector<2x2xf32> from vector<2x2x2xf32>
973/// %0:4 = vector.to_elements %v0 : vector<2x2xf32>
974/// %1:4 = vector.to_elements %v1 : vector<2x2xf32>
975/// ```
976///
977/// When this pattern is applied until a fixed-point is reached,
978/// this will produce a sequence of 1-d from_elements
979/// ops.
980struct UnrollToElements final : public OpRewritePattern<vector::ToElementsOp> {
981 UnrollToElements(MLIRContext *context,
982 const vector::UnrollVectorOptions &options,
983 PatternBenefit benefit = 1)
984 : OpRewritePattern<vector::ToElementsOp>(context, benefit),
985 options(options) {}
986
987 LogicalResult matchAndRewrite(vector::ToElementsOp op,
988 PatternRewriter &rewriter) const override {
989
990 TypedValue<VectorType> source = op.getSource();
991 FailureOr<SmallVector<Value>> result =
992 vector::unrollVectorValue(source, rewriter);
993 if (failed(result)) {
994 return failure();
995 }
996 SmallVector<Value> vectors = *result;
997
998 SmallVector<Value> results;
999 for (Value vector : vectors) {
1000 auto subElements =
1001 vector::ToElementsOp::create(rewriter, op.getLoc(), vector);
1002 llvm::append_range(results, subElements.getResults());
1003 }
1004 rewriter.replaceOp(op, results);
1005 return success();
1006 }
1007
1008private:
1009 vector::UnrollVectorOptions options;
1010};
1011
1012/// This pattern unrolls `vector.step` operations according to the provided
1013/// target unroll shape. It decomposes a large step vector into smaller step
1014/// vectors (segments) and assembles the result by inserting each computed
1015/// segment into the appropriate offset of the original vector.
1016///
1017/// The pattern does not support scalable vectors and will fail to match them.
1018///
1019/// For each segment, it adds the base step vector and the segment's offset,
1020/// then inserts the result into the output vector at the corresponding
1021/// position.
1022///
1023/// Example:
1024/// Given a step operation:
1025/// %0 = vector.step : vector<8xindex>
1026///
1027/// and a target unroll shape of <4>, the pattern produces:
1028///
1029/// %base = vector.step : vector<4xindex>
1030/// %zero = arith.constant dense<0> : vector<8xindex>
1031/// %result0 = vector.insert_strided_slice %base, %zero
1032/// {offsets = [0], strides = [1]} : vector<4xindex> into vector<8xindex>
1033/// %offset = arith.constant dense<4> : vector<4xindex>
1034/// %segment1 = arith.addi %base, %offset : vector<4xindex>
1035/// %result1 = vector.insert_strided_slice %segment1, %result0
1036/// {offsets = [4], strides = [1]} : vector<4xindex> into vector<8xindex>
1037///
1038struct UnrollStepPattern : public OpRewritePattern<vector::StepOp> {
1039 UnrollStepPattern(MLIRContext *context,
1040 const vector::UnrollVectorOptions &options,
1041 PatternBenefit benefit = 1)
1042 : OpRewritePattern<vector::StepOp>(context, benefit), options(options) {}
1043
1044 LogicalResult matchAndRewrite(vector::StepOp stepOp,
1045 PatternRewriter &rewriter) const override {
1046 // TODO: This is shared between all Unroll patterns - merge.
1047 auto iface = cast<VectorUnrollOpInterface>(*stepOp);
1048 std::optional<SmallVector<int64_t>> targetShape =
1049 getTargetShape(options, iface);
1050 if (!targetShape)
1051 return failure();
1052
1053 VectorType vecType = stepOp.getType();
1054 if (vecType.isScalable()) {
1055 // Scalable vectors are not supported by this pattern.
1056 return failure();
1057 }
1058 int64_t originalSize = vecType.getShape()[0];
1059 Location loc = stepOp.getLoc();
1060 SmallVector<int64_t> strides(1, 1);
1061
1062 Value result = arith::ConstantOp::create(rewriter, loc, vecType,
1063 rewriter.getZeroAttr(vecType));
1064
1065 auto targetVecType =
1066 VectorType::get(*targetShape, vecType.getElementType());
1067 Value baseStep = vector::StepOp::create(rewriter, loc, targetVecType);
1068 for (const SmallVector<int64_t> &offsets :
1069 StaticTileOffsetRange({originalSize}, *targetShape)) {
1070 Value bcastOffset = arith::ConstantOp::create(
1071 rewriter, loc, targetVecType,
1073 targetVecType,
1074 IntegerAttr::get(targetVecType.getElementType(), offsets[0])));
1075 Value tileStep =
1076 arith::AddIOp::create(rewriter, loc, baseStep, bcastOffset);
1077
1078 result = rewriter.createOrFold<vector::InsertStridedSliceOp>(
1079 loc, tileStep, result, offsets, strides);
1080 }
1081 rewriter.replaceOp(stepOp, result);
1082 return success();
1083 }
1084
1085private:
1086 vector::UnrollVectorOptions options;
1087};
1088
1089/// Unrolls 2 or more dimensional `vector.from_elements` ops by unrolling the
1090/// outermost dimension. For example:
1091/// ```
1092/// %v = vector.from_elements %e0, %e1, %e2, %e3, %e4, %e5 : vector<2x3xf32>
1093///
1094/// ==>
1095///
1096/// %0 = ub.poison : vector<2x3xf32>
1097/// %v0 = vector.from_elements %e0, %e1, %e2 : vector<3xf32>
1098/// %1 = vector.insert %v0, %0 [0] : vector<3xf32> into vector<2x3xf32>
1099/// %v1 = vector.from_elements %e3, %e4, %e5 : vector<3xf32>
1100/// %v = vector.insert %v1, %1 [1] : vector<3xf32> into vector<2x3xf32>
1101/// ```
1102///
1103/// When this pattern is applied until a fixed-point is reached,
1104/// this will produce a sequence of 1-d from_elements
1105/// ops.
1106struct UnrollFromElements : OpRewritePattern<vector::FromElementsOp> {
1107 UnrollFromElements(MLIRContext *context,
1108 const vector::UnrollVectorOptions &options,
1109 PatternBenefit benefit = 1)
1110 : OpRewritePattern<vector::FromElementsOp>(context, benefit),
1111 options(options) {}
1112
1113 LogicalResult matchAndRewrite(vector::FromElementsOp op,
1114 PatternRewriter &rewriter) const override {
1115 ValueRange allElements = op.getElements();
1116
1117 auto unrollFromElementsFn = [&](PatternRewriter &rewriter, Location loc,
1118 VectorType subTy, int64_t index) {
1119 size_t subTyNumElements = subTy.getNumElements();
1120 assert((index + 1) * subTyNumElements <= allElements.size() &&
1121 "out of bounds");
1122 ValueRange subElements =
1123 allElements.slice(index * subTyNumElements, subTyNumElements);
1124 return vector::FromElementsOp::create(rewriter, loc, subTy, subElements);
1125 };
1126
1127 return unrollVectorOp(op, rewriter, unrollFromElementsFn);
1128 }
1129
1130private:
1131 vector::UnrollVectorOptions options;
1132};
1133
1134/// This pattern unrolls `vector.create_mask` operations into smaller mask
1135/// operations based on the target unroll shape. Each unrolled slice computes
1136/// its local mask size in each dimension (d) as:
1137/// min(max(originalMaskSize[d] - offset[d], 0), unrolledDimSize[d]).
1138/// Example:
1139/// Given a create_mask operation:
1140/// %0 = vector.create_mask %c6, %c10 : vector<8x16xi1> // mask first 6x10
1141/// elements
1142///
1143/// and a target unroll shape of <4x8>, the pattern produces:
1144///
1145/// %false = arith.constant dense<false> : vector<8x16xi1>
1146///
1147/// Slice [0,0]:
1148/// mask size = min(max(6-0, 0), 4) x min(max(10-0, 0), 8) = 4x8
1149/// %mask00 = vector.create_mask %c4, %c8 : vector<4x8xi1>
1150/// %r0 = vector.insert_strided_slice %mask00, %false [0, 0], [1, 1]
1151/// : vector<4x8xi1> into vector<8x16xi1>
1152/// Slice [0,8]:
1153/// mask size = min(max(6-0, 0), 4) x min(max(10-8, 0), 8) = 4x2
1154/// %mask01 = vector.create_mask %c4, %c2 : vector<4x8xi1>
1155/// %r1 = vector.insert_strided_slice %mask01, %r0 [0, 8], [1, 1]
1156/// : vector<4x8xi1> into vector<8x16xi1>
1157/// Slice [4,0]:
1158/// mask size = min(max(6-4, 0), 4) x min(max(10-0, 0), 8) = 2x8
1159/// %mask10 = vector.create_mask %c2, %c8 : vector<4x8xi1>
1160/// %r2 = vector.insert_strided_slice %mask10, %r1 [4, 0], [1, 1]
1161/// : vector<4x8xi1> into vector<8x16xi1>
1162/// Slice [4,8]:
1163/// mask size = min(max(6-4, 0), 4) x min(max(10-8, 0), 8) = 2x2
1164/// %mask11 = vector.create_mask %c2, %c2 : vector<4x8xi1>
1165/// %result = vector.insert_strided_slice %mask11, %r2 [4, 8], [1, 1]
1166/// : vector<4x8xi1> into vector<8x16xi1>
1167struct UnrollCreateMaskPattern : public OpRewritePattern<vector::CreateMaskOp> {
1168 UnrollCreateMaskPattern(MLIRContext *context,
1169 const vector::UnrollVectorOptions &options,
1170 PatternBenefit benefit = 1)
1171 : OpRewritePattern<vector::CreateMaskOp>(context, benefit),
1172 options(options) {}
1173
1174 LogicalResult matchAndRewrite(vector::CreateMaskOp createMaskOp,
1175 PatternRewriter &rewriter) const override {
1176 // TODO: This is shared between all Unroll patterns - merge.
1177 auto iface = cast<VectorUnrollOpInterface>(*createMaskOp);
1178 auto targetShape = getTargetShape(options, iface);
1179 if (!targetShape)
1180 return failure();
1181
1182 VectorType resultType = createMaskOp.getVectorType();
1183 SmallVector<int64_t> originalSize =
1184 *createMaskOp.getIterationShapeToUnroll();
1185 Location loc = createMaskOp.getLoc();
1186
1187 // `targetShape` may have a smaller rank than the op - pad with leading unit
1188 // dims.
1189 SmallVector<int64_t> adjustedTargetShape(originalSize.size(), 1);
1190 llvm::copy(*targetShape, adjustedTargetShape.end() - targetShape->size());
1191
1192 Value result = arith::ConstantOp::create(rewriter, loc, resultType,
1193 rewriter.getZeroAttr(resultType));
1194 VectorType targetVectorType =
1195 VectorType::get(adjustedTargetShape, rewriter.getI1Type());
1196 SmallVector<int64_t> strides(adjustedTargetShape.size(), 1);
1197
1198 // In each dimension (d), each unrolled vector computes its mask size as:
1199 // min(max(originalMaskOperands[d] - offset[d], 0), unrolledDimSize[d]).
1200 for (SmallVector<int64_t> offsets :
1201 StaticTileOffsetRange(originalSize, adjustedTargetShape)) {
1202 SmallVector<Value> unrolledOperands;
1203
1204 for (auto [i, originalMaskOperand] :
1205 llvm::enumerate(createMaskOp.getOperands())) {
1206 Value offsetVal =
1207 arith::ConstantIndexOp::create(rewriter, loc, offsets[i]);
1208 Value adjustedMaskSize = rewriter.createOrFold<arith::SubIOp>(
1209 loc, originalMaskOperand, offsetVal);
1210 Value zero = arith::ConstantIndexOp::create(rewriter, loc, 0);
1211 Value unrolledDimSize = arith::ConstantIndexOp::create(
1212 rewriter, loc, adjustedTargetShape[i]);
1213 Value nonNegative =
1214 rewriter.createOrFold<arith::MaxSIOp>(loc, adjustedMaskSize, zero);
1215 Value unrolledOperand = rewriter.createOrFold<arith::MinSIOp>(
1216 loc, nonNegative, unrolledDimSize);
1217 unrolledOperands.push_back(unrolledOperand);
1218 }
1219
1220 auto unrolledMask = rewriter.createOrFold<vector::CreateMaskOp>(
1221 loc, targetVectorType, unrolledOperands);
1222 result = rewriter.createOrFold<vector::InsertStridedSliceOp>(
1223 loc, unrolledMask, result, offsets, strides);
1224 }
1225 rewriter.replaceOp(createMaskOp, result);
1226 return success();
1227 }
1228
1229private:
1230 vector::UnrollVectorOptions options;
1231};
1232
1233/// This pattern unrolls `vector.constant_mask` operations into smaller mask
1234/// operations based on the target unroll shape. Each unrolled slice computes
1235/// whether its elements should be masked based on the original mask dimensions
1236/// and the slice's offset position.
1237///
1238/// Example:
1239/// Given a constant_mask operation:
1240/// %0 = vector.constant_mask [6, 10] : vector<8x16xi1>
1241///
1242/// and a target unroll shape of <4x8>, the pattern produces:
1243///
1244/// %false = arith.constant dense<false> : vector<8x16xi1>
1245///
1246/// Slice [0,0]: elements [0:4, 0:8] - fully within [6, 10] bounds
1247/// %mask00 = vector.constant_mask [4, 8] : vector<4x8xi1>
1248/// %r0 = vector.insert_strided_slice %mask00, %false [0, 0], [1, 1]
1249/// : vector<4x8xi1> into vector<8x16xi1>
1250///
1251/// Slice [0,8]: elements [0:4, 8:16] - partially within bounds
1252/// %mask01 = vector.constant_mask [4, 2] : vector<4x8xi1>
1253/// %r1 = vector.insert_strided_slice %mask01, %r0 [0, 8], [1, 1]
1254/// : vector<4x8xi1> into vector<8x16xi1>
1255///
1256/// Slice [4,0]: elements [4:8, 0:8] - partially within bounds
1257/// %mask10 = vector.constant_mask [2, 8] : vector<4x8xi1>
1258/// %r2 = vector.insert_strided_slice %mask10, %r1 [4, 0], [1, 1]
1259/// : vector<4x8xi1> into vector<8x16xi1>
1260///
1261/// Slice [4,8]: elements [4:8, 8:16] - partially within bounds
1262/// %mask11 = vector.constant_mask [2, 2] : vector<4x8xi1>
1263/// %result = vector.insert_strided_slice %mask11, %r2 [4, 8], [1, 1]
1264/// : vector<4x8xi1> into vector<8x16xi1>
1265struct UnrollConstantMaskPattern
1266 : public OpRewritePattern<vector::ConstantMaskOp> {
1267 UnrollConstantMaskPattern(MLIRContext *context,
1268 const vector::UnrollVectorOptions &options,
1269 PatternBenefit benefit = 1)
1270 : OpRewritePattern<vector::ConstantMaskOp>(context, benefit),
1271 options(options) {}
1272
1273 LogicalResult matchAndRewrite(vector::ConstantMaskOp constantMaskOp,
1274 PatternRewriter &rewriter) const override {
1275 // TODO: This is shared between all Unroll patterns - merge.
1276 auto iface = cast<VectorUnrollOpInterface>(*constantMaskOp);
1277 auto targetShape = getTargetShape(options, iface);
1278 if (!targetShape)
1279 return failure();
1280
1281 VectorType resultType = constantMaskOp.getVectorType();
1282 SmallVector<int64_t> originalSize =
1283 *constantMaskOp.getIterationShapeToUnroll();
1284 Location loc = constantMaskOp.getLoc();
1285
1286 // `targetShape` may have a smaller rank than the op - pad with leading unit
1287 // dims.
1288 SmallVector<int64_t> adjustedTargetShape(originalSize.size(), 1);
1289 llvm::copy(*targetShape, adjustedTargetShape.end() - targetShape->size());
1290
1291 Value result = arith::ConstantOp::create(rewriter, loc, resultType,
1292 rewriter.getZeroAttr(resultType));
1293 VectorType targetVectorType =
1294 VectorType::get(adjustedTargetShape, rewriter.getI1Type());
1295 SmallVector<int64_t> strides(adjustedTargetShape.size(), 1);
1296
1297 // In each dimension (d), each unrolled vector computes its mask size as:
1298 // min(max(originalMaskDim[d] - offset[d], 0), unrolledDimSize[d]).
1299 for (const SmallVector<int64_t> &offsets :
1300 StaticTileOffsetRange(originalSize, adjustedTargetShape)) {
1301 SmallVector<int64_t> unrolledMaskDims;
1302
1303 for (auto [i, originalMaskDim] :
1304 llvm::enumerate(constantMaskOp.getMaskDimSizes())) {
1305 // Calculate how many elements in this dimension should be masked
1306 // for this particular slice
1307 int64_t adjustedMaskSize =
1308 std::max(originalMaskDim - offsets[i], static_cast<int64_t>(0));
1309 int64_t unrolledMaskDim =
1310 std::min(adjustedMaskSize, adjustedTargetShape[i]);
1311 unrolledMaskDims.push_back(unrolledMaskDim);
1312 }
1313
1314 // If any of 'unrolledMaskDims' is zero, then the mask is effectively ALL
1315 // FALSE and we can set all dims to zero (masked region is a conjunction
1316 // of mask dim intervals).
1317 if (llvm::is_contained(unrolledMaskDims, 0))
1318 unrolledMaskDims.assign(unrolledMaskDims.size(), 0);
1319
1320 auto unrolledMask = rewriter.createOrFold<vector::ConstantMaskOp>(
1321 loc, targetVectorType, unrolledMaskDims);
1322 result = rewriter.createOrFold<vector::InsertStridedSliceOp>(
1323 loc, unrolledMask, result, offsets, strides);
1324 }
1325 rewriter.replaceOp(constantMaskOp, result);
1326 return success();
1327 }
1328
1329private:
1330 vector::UnrollVectorOptions options;
1331};
1332
1333/// Checks whether extractShape is a contiguous slice of shape.
1334/// For extractShape to be contiguous in shape:
1335/// 1) All but the leading dimension of extractShape and shape must match
1336/// exactly. 2) The total number of elements in shape must be evenly divisible
1337/// by
1338/// the total number of elements in extractShape.
1339/// Examples:
1340/// isContiguous([4, 4], [8, 4]) == true
1341/// isContiguous([2, 4], [8, 4]) == true
1342/// isContiguous([2, 2], [8, 4]) == false
1343/// Removes leading unit dimensions to handle cases like:
1344/// isContiguous([1, 16], [1, 32]) == true
1345static bool isContiguous(ArrayRef<int64_t> extractShape,
1347
1348 if (extractShape.empty() || shape.empty() ||
1349 extractShape.size() > shape.size())
1350 return false;
1351
1352 while (extractShape.size() > 1 && extractShape.front() == 1)
1353 extractShape = extractShape.drop_front();
1354
1355 while (shape.size() > 1 && shape.front() == 1) {
1356 shape = shape.drop_front();
1357 }
1358
1359 size_t rankDiff = shape.size() - extractShape.size();
1360 if (!llvm::equal(extractShape.drop_front(), shape.drop_front(rankDiff + 1)))
1361 return false;
1362
1363 int64_t extractElements = ShapedType::getNumElements(extractShape);
1364 int64_t shapeElements = ShapedType::getNumElements(shape);
1365 return shapeElements % extractElements == 0;
1366}
1367
1368/// Determines what shape to use with `vector.extract_strided_slice` to extract
1369/// a contiguous memory region from a source vector. The extraction must be
1370/// contiguous and contain exactly the specified number of elements. If such an
1371/// extraction shape cannot be determined, returns std::nullopt.
1372/// EXAMPLE 1:
1373/// sourceShape = [16], targetElements = 8
1374/// Working right-to-left:
1375/// - Take min(8, 16) = 8 from only dim → extractShape = [8],
1376/// remaining = 8/8 = 1
1377/// Result: [8]
1378///
1379/// EXAMPLE 2:
1380/// sourceShape = [4, 4], targetElements = 8
1381/// Working right-to-left:
1382/// - Take min(8, 4) = 4 from last dim → extractShape = [4],
1383/// remaining = 8/4 = 2
1384/// - Take min(2, 4) = 2 from first dim → extractShape = [2, 4],
1385/// remaining = 2/2 = 1
1386/// Result: [2, 4]
1387static std::optional<SmallVector<int64_t>>
1388calculateSourceExtractShape(ArrayRef<int64_t> sourceShape,
1389 int64_t targetElements) {
1390 SmallVector<int64_t> extractShape;
1391 int64_t remainingElements = targetElements;
1392
1393 // Build extract shape from innermost dimension outward to ensure contiguity.
1394 for (int i = sourceShape.size() - 1; i >= 0 && remainingElements > 1; --i) {
1395 int64_t takeFromDim = std::min(remainingElements, sourceShape[i]);
1396 extractShape.insert(extractShape.begin(), takeFromDim);
1397
1398 if (remainingElements % takeFromDim != 0)
1399 return std::nullopt; // Not evenly divisible.
1400 remainingElements /= takeFromDim;
1401 }
1402
1403 // Fill remaining dimensions with 1.
1404 while (extractShape.size() < sourceShape.size())
1405 extractShape.insert(extractShape.begin(), 1);
1406
1407 if (ShapedType::getNumElements(extractShape) != targetElements)
1408 return std::nullopt;
1409
1410 return extractShape;
1411}
1412
1413// Convert result offsets to source offsets via linear position.
1415calculateSourceOffsets(ArrayRef<int64_t> resultOffsets,
1416 ArrayRef<int64_t> sourceShape,
1417 ArrayRef<int64_t> resultShape) {
1418 // Convert result offsets to linear position.
1419 int64_t linearIndex = linearize(resultOffsets, computeStrides(resultShape));
1420 // Convert linear position to source offsets.
1421 return delinearize(linearIndex, computeStrides(sourceShape));
1422}
1423
1424/// A maximal aligned range of source dims [srcBegin, srcEnd) and result dims
1425/// [resBegin, resEnd) of a `vector.shape_cast` that hold equal element counts.
1426struct ShapeCastReassociationGroup {
1427 int64_t srcBegin, srcEnd;
1428 int64_t resBegin, resEnd;
1429};
1430
1431/// Splits a shape_cast from `sourceShape` to `resultShape` into reassociation
1432/// groups (trailing unit dims absorbed). Returns nullopt if shapes misalign.
1433/// E.g. [8, 32, 32] -> [256, 32] ==> {[0,2)->[0,1)}, {[2,3)->[1,2)}
1434static std::optional<SmallVector<ShapeCastReassociationGroup>>
1435computeShapeCastGroups(ArrayRef<int64_t> sourceShape,
1436 ArrayRef<int64_t> resultShape) {
1438 int64_t si = 0, ri = 0;
1439 int64_t srcRank = sourceShape.size(), resRank = resultShape.size();
1440 while (si < srcRank && ri < resRank) {
1441 int64_t srcBegin = si, resBegin = ri;
1442 int64_t srcProd = sourceShape[si++];
1443 int64_t resProd = resultShape[ri++];
1444 // Grow the smaller side until both groups span the same element count.
1445 while (srcProd != resProd) {
1446 if (srcProd < resProd) {
1447 if (si >= srcRank)
1448 return std::nullopt;
1449 srcProd *= sourceShape[si++];
1450 } else {
1451 if (ri >= resRank)
1452 return std::nullopt;
1453 resProd *= resultShape[ri++];
1454 }
1455 }
1456 // Absorb trailing unit dimensions into the current group.
1457 while (si < srcRank && sourceShape[si] == 1)
1458 ++si;
1459 while (ri < resRank && resultShape[ri] == 1)
1460 ++ri;
1461 groups.push_back({srcBegin, si, resBegin, ri});
1462 }
1463 if (si != srcRank || ri != resRank)
1464 return std::nullopt;
1465 return groups;
1466}
1467
1468/// This pattern unrolls `vector.shape_cast` operations according to the
1469/// provided target unroll shape. It unrolls a large shape cast into smaller
1470/// shape casts by extracting contiguous slices from the source vector, casting
1471/// each slice to the target shape, and assembling the result by inserting each
1472/// computed segment into the appropriate offset of the result vector.
1473///
1474/// The target tile need only be contiguous within each reassociation group of
1475/// the cast (not in the whole result vector), so that each extracted slice
1476/// remains a valid vector. The unrolling proceeds as:
1477/// vector.extract_strided_slice -> vector.shape_cast (on the slice) ->
1478/// vector.insert_strided_slice.
1479///
1480/// NOTE: This replaces a NOP `vector.shape_cast` with strided slices. Per-group
1481/// contiguity keeps those slices contiguous, so they are expected to lower to a
1482/// NOP too. Targets where strided slices do not lower to a NOP should not use
1483/// this pattern, or should pick a tile that avoids introducing such slices.
1484///
1485/// Example (single group):
1486/// Given a shape cast operation:
1487/// %0 = vector.shape_cast %src : vector<8x2xf32> to vector<4x4xf32>
1488///
1489/// and a target unroll shape of <2x4>, the pattern produces:
1490///
1491/// %zero = arith.constant dense<0.0> : vector<4x4xf32>
1492/// %s0 = vector.extract_strided_slice %src [0, 0], [4, 2], [1, 1]
1493/// : vector<8x2xf32> to vector<4x2xf32>
1494/// %sc0 = vector.shape_cast %s0 : vector<4x2xf32> to vector<2x4xf32>
1495/// %i0 = vector.insert_strided_slice %sc0, %zero [0, 0], [1, 1]
1496/// : vector<2x4xf32> into vector<4x4xf32>
1497/// %s1 = vector.extract_strided_slice %src [4, 0], [4, 2], [1, 1]
1498/// : vector<8x2xf32> to vector<4x2xf32>
1499/// %sc1 = vector.shape_cast %s1 : vector<4x2xf32> to vector<2x4xf32>
1500/// %i1 = vector.insert_strided_slice %sc1, %i0 [2, 0], [1, 1]
1501/// : vector<2x4xf32> into vector<4x4xf32>
1502///
1503/// Example (multiple groups): with target tile <8x1x4>, the tile is strided in
1504/// the result <8x1x32> but contiguous per group (8|32 -> 8x1|32), so the
1505/// matching strided box <8x4> is extracted from the source:
1506/// %0 = vector.shape_cast %src : vector<8x32xf32> to vector<8x1x32xf32>
1507///
1508/// %s0 = vector.extract_strided_slice %src [0, 0], [8, 4], [1, 1]
1509/// : vector<8x32xf32> to vector<8x4xf32>
1510/// %sc0 = vector.shape_cast %s0 : vector<8x4xf32> to vector<8x1x4xf32>
1511/// %i0 = vector.insert_strided_slice %sc0, %zero [0, 0, 0], [1, 1, 1]
1512/// : vector<8x1x4xf32> into vector<8x1x32xf32>
1513/// // ... repeat for the remaining slices.
1514///
1515struct UnrollShapeCastPattern : public OpRewritePattern<vector::ShapeCastOp> {
1516 UnrollShapeCastPattern(MLIRContext *context,
1517 const vector::UnrollVectorOptions &options,
1518 PatternBenefit benefit = 1)
1519 : OpRewritePattern<vector::ShapeCastOp>(context, benefit),
1520 options(options) {}
1521
1522 LogicalResult matchAndRewrite(vector::ShapeCastOp shapeCastOp,
1523 PatternRewriter &rewriter) const override {
1524 // TODO: This is shared between all Unroll patterns - merge.
1525 auto iface = cast<VectorUnrollOpInterface>(*shapeCastOp);
1526 auto targetShape = getTargetShape(options, iface);
1527 if (!targetShape)
1528 return failure();
1529
1530 VectorType sourceType = shapeCastOp.getSourceVectorType();
1531 VectorType resultType = shapeCastOp.getResultVectorType();
1532 ArrayRef<int64_t> sourceShape = sourceType.getShape();
1533 ArrayRef<int64_t> resultShape = resultType.getShape();
1534
1535 // The cast factors into reassociation groups; the target tile only needs to
1536 // be contiguous within each group, not in the whole result vector.
1537 std::optional<SmallVector<ShapeCastReassociationGroup>> groups =
1538 computeShapeCastGroups(sourceShape, resultShape);
1539 if (!groups)
1540 return rewriter.notifyMatchFailure(
1541 shapeCastOp, "cannot align source and result reassociation groups");
1542
1543 // The tile is right-aligned against the result; left-pad with 1s so it can
1544 // be indexed per group.
1545 SmallVector<int64_t> paddedTarget(resultShape.size(), 1);
1546 llvm::copy(*targetShape,
1547 paddedTarget.end() - static_cast<int64_t>(targetShape->size()));
1548
1549 // Validate per-group contiguity and build the source extract shape.
1550 SmallVector<int64_t> extractShapeStorage;
1551 for (const ShapeCastReassociationGroup &g : *groups) {
1552 ArrayRef<int64_t> resSub =
1553 resultShape.slice(g.resBegin, g.resEnd - g.resBegin);
1554 ArrayRef<int64_t> tgtSub = ArrayRef<int64_t>(paddedTarget)
1555 .slice(g.resBegin, g.resEnd - g.resBegin);
1556 if (!isContiguous(tgtSub, resSub))
1557 return rewriter.notifyMatchFailure(
1558 shapeCastOp, "target shape is not contiguous within a "
1559 "reassociation group of the result vector shape");
1560
1561 ArrayRef<int64_t> srcSub =
1562 sourceShape.slice(g.srcBegin, g.srcEnd - g.srcBegin);
1563 int64_t groupTargetElements = ShapedType::getNumElements(tgtSub);
1564 std::optional<SmallVector<int64_t>> groupExtract =
1565 calculateSourceExtractShape(srcSub, groupTargetElements);
1566 if (!groupExtract)
1567 return rewriter.notifyMatchFailure(
1568 shapeCastOp, "cannot extract the target number of elements "
1569 "contiguously from a source reassociation group");
1570 extractShapeStorage.append(groupExtract->begin(), groupExtract->end());
1571 }
1572 ArrayRef<int64_t> extractShape = extractShapeStorage;
1573
1574 Location loc = shapeCastOp.getLoc();
1575
1576 // Create result vector initialized to zero.
1577 Value result = arith::ConstantOp::create(rewriter, loc, resultType,
1578 rewriter.getZeroAttr(resultType));
1579
1580 VectorType targetType =
1581 VectorType::get(*targetShape, sourceType.getElementType());
1582
1583 SmallVector<int64_t> extractStrides(extractShape.size(), 1);
1584 SmallVector<int64_t> insertStrides(targetShape->size(), 1);
1585
1586 for (SmallVector<int64_t> resultOffsets :
1587 StaticTileOffsetRange(resultShape, *targetShape)) {
1588 SmallVector<int64_t> sourceOffsets =
1589 calculateSourceOffsets(resultOffsets, sourceShape, resultShape);
1590 Value sourceChunk = rewriter.createOrFold<vector::ExtractStridedSliceOp>(
1591 loc, shapeCastOp.getSource(), sourceOffsets, extractShape,
1593 Value targetChunk = rewriter.createOrFold<vector::ShapeCastOp>(
1594 loc, targetType, sourceChunk);
1595 result = rewriter.createOrFold<vector::InsertStridedSliceOp>(
1596 loc, targetChunk, result, resultOffsets, insertStrides);
1597 }
1598
1599 rewriter.replaceOp(shapeCastOp, result);
1600 return success();
1601 }
1602
1603private:
1604 vector::UnrollVectorOptions options;
1605};
1606
1607// Unroll vector::BitCastOp into smaller slice-based bitcast operations.
1608// Decomposes the result vector into target shape chunks and bitcasts
1609// corresponding source slices, accounting for element bitwidth ratios.
1610/// Example:
1611/// Given a bitcast Op:
1612///
1613/// vector.bitcast %src : vector<4x8xf32>
1614///
1615/// and a target unroll shape of <2x4>, the pattern produces:
1616///
1617/// %slice_0 = vector.extract_strided_slice %lhs[0, 0] : vector<2x4xf32>
1618/// %slice_0 = vector.bitcast %slice_0 : vector<2x4xf32>
1619/// %result = vector.insert_strided_slice %slice_0, %init[0, 0]
1620/// // ... repeat for remaining slices
1621struct UnrollBitCastPattern : public OpRewritePattern<vector::BitCastOp> {
1622 UnrollBitCastPattern(MLIRContext *context,
1623 const vector::UnrollVectorOptions &options,
1624 PatternBenefit benefit = 1)
1625 : OpRewritePattern<vector::BitCastOp>(context, benefit),
1626 options(options) {}
1627
1628 LogicalResult matchAndRewrite(vector::BitCastOp bitCastOp,
1629 PatternRewriter &rewriter) const override {
1630 // TODO: This is shared between all Unroll patterns - merge.
1631 auto iface = cast<VectorUnrollOpInterface>(*bitCastOp);
1632 auto targetShape = getTargetShape(options, iface);
1633 if (!targetShape)
1634 return rewriter.notifyMatchFailure(bitCastOp,
1635 "failed to get target shape");
1636
1637 VectorType sourceType = bitCastOp.getSourceVectorType();
1638 VectorType resultType = bitCastOp.getResultVectorType();
1639 ArrayRef<int64_t> resultShape = resultType.getShape();
1640 Location loc = bitCastOp.getLoc();
1641
1642 if (targetShape->size() != resultShape.size())
1643 return rewriter.notifyMatchFailure(
1644 bitCastOp, "target shape rank must match result rank");
1645
1646 unsigned sourceElementBits = sourceType.getElementTypeBitWidth();
1647 unsigned resultElementBits = resultType.getElementTypeBitWidth();
1648
1649 SmallVector<int64_t> sourceSliceShape(targetShape->begin(),
1650 targetShape->end());
1651 int64_t lastDim = sourceSliceShape.size() - 1;
1652
1653 sourceSliceShape[lastDim] =
1654 ((*targetShape)[lastDim] * resultElementBits) / sourceElementBits;
1655
1656 Value result = arith::ConstantOp::create(rewriter, loc, resultType,
1657 rewriter.getZeroAttr(resultType));
1658 SmallVector<int64_t> resultStrides(targetShape->size(), 1);
1659 SmallVector<int64_t> sourceStrides(sourceSliceShape.size(), 1);
1660
1661 VectorType targetType =
1662 VectorType::get(*targetShape, resultType.getElementType());
1663
1664 for (SmallVector<int64_t> resultOffsets :
1665 StaticTileOffsetRange(resultShape, *targetShape)) {
1666 SmallVector<int64_t> sourceOffsets = resultOffsets;
1667 sourceOffsets[lastDim] =
1668 (resultOffsets[lastDim] * resultElementBits) / sourceElementBits;
1669
1670 Value sourceSlice = rewriter.createOrFold<vector::ExtractStridedSliceOp>(
1671 loc, bitCastOp.getSource(), sourceOffsets, sourceSliceShape,
1672 sourceStrides);
1673 Value bitcastSlice = rewriter.createOrFold<vector::BitCastOp>(
1674 loc, targetType, sourceSlice);
1675 result = rewriter.createOrFold<vector::InsertStridedSliceOp>(
1676 loc, bitcastSlice, result, resultOffsets, resultStrides);
1677 }
1678
1679 rewriter.replaceOp(bitCastOp, result);
1680 return success();
1681 }
1682
1683private:
1684 vector::UnrollVectorOptions options;
1685};
1686
1687/// Pattern to unroll vector.interleave into smaller slice-sized operations.
1688/// Decomposes a large interleave into slices by extracting slices from both
1689/// input vectors, interleaving them, and inserting back into the result.
1690///
1691/// Example:
1692/// Given an interleave Op:
1693///
1694/// vector.interleave %lhs, %rhs : vector<4x8xf32>
1695///
1696/// and a target unroll shape of <2x4>, the pattern produces:
1697///
1698/// %slice_lhs_0 = vector.extract_strided_slice %lhs[0, 0] : vector<2x2xf32>
1699/// %slice_rhs_0 = vector.extract_strided_slice %rhs[0, 0] : vector<2x2xf32>
1700/// %slice_0 = vector.interleave %slice_lhs_0, %slice_rhs_0
1701/// : vector<2x4xf32>
1702/// %result = vector.insert_strided_slice %slice_0, %init[0, 0]
1703/// // ... repeat for remaining slices
1704struct UnrollInterleavePattern : public OpRewritePattern<vector::InterleaveOp> {
1705 UnrollInterleavePattern(MLIRContext *context,
1706 const vector::UnrollVectorOptions &options,
1707 PatternBenefit benefit = 1)
1708 : OpRewritePattern<vector::InterleaveOp>(context, benefit),
1709 options(options) {}
1710
1711 LogicalResult matchAndRewrite(vector::InterleaveOp interleaveOp,
1712 PatternRewriter &rewriter) const override {
1713 // TODO: This is shared between all Unroll patterns - merge.
1714 auto iface = cast<VectorUnrollOpInterface>(*interleaveOp);
1715 auto targetShape = getTargetShape(options, iface);
1716 if (!targetShape)
1717 return rewriter.notifyMatchFailure(interleaveOp,
1718 "failed to get target shape");
1719
1720 VectorType resultType = interleaveOp.getResultVectorType();
1721 ArrayRef<int64_t> resultShape = resultType.getShape();
1722 Location loc = interleaveOp.getLoc();
1723
1724 if (targetShape->size() != resultShape.size())
1725 return rewriter.notifyMatchFailure(
1726 interleaveOp, "target shape rank must match result rank");
1727
1728 SmallVector<int64_t> sourceSliceShape(targetShape->begin(),
1729 targetShape->end());
1730 int64_t lastDim = sourceSliceShape.size() - 1;
1731 sourceSliceShape[lastDim] = (*targetShape)[lastDim] / 2;
1732
1733 Value result = arith::ConstantOp::create(rewriter, loc, resultType,
1734 rewriter.getZeroAttr(resultType));
1735 SmallVector<int64_t> resultStrides(targetShape->size(), 1);
1736 SmallVector<int64_t> sourceStrides(sourceSliceShape.size(), 1);
1737
1738 VectorType targetType =
1739 VectorType::get(*targetShape, resultType.getElementType());
1740
1741 for (SmallVector<int64_t> resultOffsets :
1742 StaticTileOffsetRange(resultShape, *targetShape)) {
1743 SmallVector<int64_t> sourceOffsets = resultOffsets;
1744 sourceOffsets[lastDim] = resultOffsets[lastDim] / 2;
1745
1746 Value lhsSlice = rewriter.createOrFold<vector::ExtractStridedSliceOp>(
1747 loc, interleaveOp.getLhs(), sourceOffsets, sourceSliceShape,
1748 sourceStrides);
1749 Value rhsSlice = rewriter.createOrFold<vector::ExtractStridedSliceOp>(
1750 loc, interleaveOp.getRhs(), sourceOffsets, sourceSliceShape,
1751 sourceStrides);
1752 Value interleaveSlice = rewriter.createOrFold<vector::InterleaveOp>(
1753 loc, targetType, lhsSlice, rhsSlice);
1754 result = rewriter.createOrFold<vector::InsertStridedSliceOp>(
1755 loc, interleaveSlice, result, resultOffsets, resultStrides);
1756 }
1757
1758 rewriter.replaceOp(interleaveOp, result);
1759 return success();
1760 }
1761
1762private:
1763 vector::UnrollVectorOptions options;
1764};
1765
1766/// Pattern to unroll vector.deinterleave into smaller slice-sized operations.
1767/// Decomposes a large deinterleave (which splits a vector into even/odd halves)
1768/// by extracting source slices, deinterleaving them, and inserting into two
1769/// result vectors.
1770///
1771/// Example:
1772/// Given a deinterleave Op:
1773///
1774/// vector.deinterleave %src : vector<4x8xf32>
1775///
1776/// and a target unroll shape of <2x4>, the pattern produces:
1777///
1778/// %slice_0 = vector.extract_strided_slice %src[0, 0] : vector<2x4xf32>
1779/// %slice_lhs_0, %slice_rhs_0 = vector.deinterleave %slice_0 :
1780/// vector<2x4xf32> %result1 = vector.insert_strided_slice %slice_lhs_0,
1781/// %init1[0, 0] %result2 = vector.insert_strided_slice %slice_rhs_0,
1782/// %init2[0, 0]
1783/// // ... repeat for remaining slices
1784struct UnrollDeinterleavePattern
1785 : public OpRewritePattern<vector::DeinterleaveOp> {
1786 UnrollDeinterleavePattern(MLIRContext *context,
1787 const vector::UnrollVectorOptions &options,
1788 PatternBenefit benefit = 1)
1789 : OpRewritePattern<vector::DeinterleaveOp>(context, benefit),
1790 options(options) {}
1791
1792 LogicalResult matchAndRewrite(vector::DeinterleaveOp deinterleaveOp,
1793 PatternRewriter &rewriter) const override {
1794 // TODO: This is shared between all Unroll patterns - merge.
1795 auto iface = cast<VectorUnrollOpInterface>(*deinterleaveOp);
1796 auto targetShape = getTargetShape(options, iface);
1797 if (!targetShape)
1798 return rewriter.notifyMatchFailure(deinterleaveOp,
1799 "failed to get target shape");
1800
1801 VectorType resultType = deinterleaveOp.getResultVectorType();
1802 ArrayRef<int64_t> resultShape = resultType.getShape();
1803 Location loc = deinterleaveOp.getLoc();
1804
1805 if (targetShape->size() != resultShape.size())
1806 return rewriter.notifyMatchFailure(
1807 deinterleaveOp, "target shape rank must match result rank");
1808
1809 SmallVector<int64_t> sourceSliceShape(targetShape->begin(),
1810 targetShape->end());
1811 int64_t lastDim = sourceSliceShape.size() - 1;
1812 sourceSliceShape[lastDim] = (*targetShape)[lastDim] * 2;
1813
1814 Value resultOdd = arith::ConstantOp::create(
1815 rewriter, loc, resultType, rewriter.getZeroAttr(resultType));
1816 Value resultEven = arith::ConstantOp::create(
1817 rewriter, loc, resultType, rewriter.getZeroAttr(resultType));
1818 SmallVector<int64_t> resultStrides(targetShape->size(), 1);
1819 SmallVector<int64_t> sourceStrides(sourceSliceShape.size(), 1);
1820
1821 for (SmallVector<int64_t> resultOffsets :
1822 StaticTileOffsetRange(resultShape, *targetShape)) {
1823 SmallVector<int64_t> sourceOffsets = resultOffsets;
1824 sourceOffsets[lastDim] = resultOffsets[lastDim] * 2;
1825
1826 Value sourceSlice = rewriter.createOrFold<vector::ExtractStridedSliceOp>(
1827 loc, deinterleaveOp.getSource(), sourceOffsets, sourceSliceShape,
1828 sourceStrides);
1829
1830 auto deinterleaveSlice =
1831 vector::DeinterleaveOp::create(rewriter, loc, sourceSlice);
1832
1833 resultOdd = rewriter.createOrFold<vector::InsertStridedSliceOp>(
1834 loc, deinterleaveSlice.getResultEven(), resultOdd, resultOffsets,
1835 resultStrides);
1836 resultEven = rewriter.createOrFold<vector::InsertStridedSliceOp>(
1837 loc, deinterleaveSlice.getResultOdd(), resultEven, resultOffsets,
1838 resultStrides);
1839 }
1840
1841 rewriter.replaceOp(deinterleaveOp, ValueRange{resultOdd, resultEven});
1842 return success();
1843 }
1844
1845private:
1846 vector::UnrollVectorOptions options;
1847};
1848} // namespace
1849
1850void mlir::vector::populateVectorUnrollPatterns(
1852 PatternBenefit benefit) {
1853 patterns.add<UnrollTransferReadPattern, UnrollTransferWritePattern,
1854 UnrollContractionPattern, UnrollElementwisePattern,
1855 UnrollReductionPattern, UnrollMultiReductionPattern,
1856 UnrollTransposePattern, UnrollGatherPattern, UnrollLoadPattern,
1857 UnrollStorePattern, UnrollBroadcastPattern, UnrollFromElements,
1858 UnrollToElements, UnrollStepPattern, UnrollShapeCastPattern,
1859 UnrollCreateMaskPattern, UnrollConstantMaskPattern,
1860 UnrollBitCastPattern, UnrollInterleavePattern,
1861 UnrollDeinterleavePattern>(patterns.getContext(), options,
1862 benefit);
1863}
1864
1865void mlir::vector::populateVectorContractUnrollPatterns(
1867 PatternBenefit benefit) {
1868 patterns.add<UnrollContractionPattern>(patterns.getContext(), options,
1869 benefit);
1870}
1871
1872void mlir::vector::populateVectorToElementsUnrollPatterns(
1873 RewritePatternSet &patterns, PatternBenefit benefit) {
1874 patterns.add<UnrollToElements>(patterns.getContext(), UnrollVectorOptions(),
1875 benefit);
1876}
1877
1878void mlir::vector::populateVectorFromElementsUnrollPatterns(
1879 RewritePatternSet &patterns, PatternBenefit benefit) {
1880 patterns.add<UnrollFromElements>(patterns.getContext(), UnrollVectorOptions(),
1881 benefit);
1882}
return success()
static LogicalResult extractStrides(AffineExpr e, AffineExpr multiplicativeFactor, MutableArrayRef< AffineExpr > strides, AffineExpr &offset)
Takes a single AffineExpr e and populates the strides array with the strides expressions for each dim...
lhs
static llvm::ManagedStatic< PassManagerOptions > options
static SmallVector< Value > slice(OpBuilder &b, Location loc, Value value, VectorType nativeType)
static LogicalResult checkSupportedMaskedTransferUnrolling(TransferOpTy xferOp, PatternRewriter &rewriter)
Fail if xferOp, masked by an enclosing vector.mask, is masked in a way that the transfer unrolling pa...
static SmallVector< Value > sliceLoadStoreIndices(PatternRewriter &rewriter, Location loc, OperandRange originalIndices, ArrayRef< int64_t > offsets)
static Operation * maskTile(PatternRewriter &rewriter, Location loc, Operation *tiledXferOp, vector::MaskingOpInterface maskingOp, ArrayRef< int64_t > offsets, ArrayRef< int64_t > sizes, ArrayRef< int64_t > strides)
Wrap tiledXferOp, the new transfer for one tile, in a vector.mask with the tile of maskingOp's mask (...
static std::optional< SmallVector< int64_t > > getTargetShape(const vector::UnrollVectorOptions &options, VectorUnrollOpInterface &iface, bool allowMasked=false)
Return the target shape for unrolling for the given op, provided through its VectorUnrollOpInterface ...
static Operation * cloneOpWithOperandsAndTypes(OpBuilder &builder, Location loc, Operation *op, ArrayRef< Value > operands, ArrayRef< Type > resultTypes)
Base type for affine expression.
Definition AffineExpr.h:68
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
ArrayRef< AffineExpr > getResults() const
TypedAttr getZeroAttr(Type type)
Definition Builders.cpp:333
IntegerType getI1Type()
Definition Builders.cpp:61
MLIRContext * getContext() const
Definition Builders.h:56
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
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
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
Definition Builders.h:528
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition Builders.cpp:466
This class implements the operand iterators for the Operation class.
Definition ValueRange.h:44
StringRef getStringRef() const
Return the name of this operation. This always succeeds.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
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
MutableArrayRef< OpOperand > getOpOperands()
Definition Operation.h:410
Attribute getPropertiesAsAttribute()
Return the properties converted to an attribute.
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
result_range getResults()
Definition Operation.h:442
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
This class represents the benefit of a pattern match in a unitless scheme that ranges from 0 (very li...
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
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.
RewritePattern is the common base class for all DAG to DAG replacements.
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.
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,...
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:453
bool hasElementwiseMappableTraits(Operation *op)
Together, Elementwise, Scalarizable, Vectorizable, and Tensorizable provide an easy way for scalar op...
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Value makeArithReduction(OpBuilder &b, Location loc, CombiningKind kind, Value v1, Value acc, arith::FastMathFlagsAttr fastmath=nullptr, Value mask=nullptr)
Returns the result value of reducing two scalar/vector values with the corresponding arith operation.
Operation * maskOperation(OpBuilder &builder, Operation *maskableOp, Value mask, Value passthru=Value())
Creates a vector.mask operation around a maskable operation.
FailureOr< SmallVector< Value > > unrollVectorValue(TypedValue< VectorType >, RewriterBase &)
Generic utility for unrolling values of type vector<NxAxBx...> to N values of type vector<AxBx....
LogicalResult unrollVectorOp(Operation *op, PatternRewriter &rewriter, UnrollVectorOpFn unrollFn)
Include the generated interface declarations.
SmallVector< int64_t > computeStrides(ArrayRef< int64_t > sizes)
SmallVector< int64_t > delinearize(int64_t linearIndex, ArrayRef< int64_t > strides)
Given the strides together with a linear index in the dimension space, return the vector-space offset...
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
AffineExpr getAffineConstantExpr(int64_t constant, MLIRContext *context)
SmallVector< T > applyPermutationMap(AffineMap map, llvm::ArrayRef< T > source)
Apply a permutation from map to source and return the result.
Definition AffineMap.h:677
int64_t linearize(ArrayRef< int64_t > offsets, ArrayRef< int64_t > basis)
Return the linearized index of 'offsets' w.r.t.
std::optional< SmallVector< int64_t > > computeShapeRatio(ArrayRef< int64_t > shape, ArrayRef< int64_t > subShape)
Return the multi-dimensional integral ratio of subShape to the trailing dimensions of shape.
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
This represents an operation in an abstracted form, suitable for use with the builder APIs.
Attribute propertiesAttr
This Attribute is used to opaquely construct the properties of the operation.
A pattern for ops that implement MaskableOpInterface and that might be masked (i.e.
Options that control the vector unrolling.