MLIR 24.0.0git
VectorOps.cpp
Go to the documentation of this file.
1//===- VectorOps.cpp - MLIR Vector Dialect Operations ---------------------===//
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 convenience types for working with super-vectorization
10// operations, in particular super-vector loads and stores.
11//
12//===----------------------------------------------------------------------===//
13
15
29#include "mlir/IR/AffineExpr.h"
30#include "mlir/IR/AffineMap.h"
31#include "mlir/IR/Builders.h"
34#include "mlir/IR/IRMapping.h"
38#include "mlir/IR/ValueRange.h"
42#include "mlir/Support/LLVM.h"
44#include "llvm/ADT/ArrayRef.h"
45#include "llvm/ADT/Repeated.h"
46#include "llvm/ADT/STLExtras.h"
47#include "llvm/ADT/SmallVector.h"
48#include "llvm/ADT/SmallVectorExtras.h"
49#include "llvm/ADT/StringSet.h"
50#include "llvm/Support/Casting.h"
51
52#include <cassert>
53#include <cstdint>
54#include <numeric>
55
56#include "mlir/Dialect/Vector/IR/VectorDialect.cpp.inc"
57// Pull in all enum type and utility function definitions.
58#include "mlir/Dialect/Vector/IR/VectorEnums.cpp.inc"
59
60using namespace mlir;
61using namespace mlir::vector;
62
63/// Helper enum to classify mask value.
64enum class MaskFormat {
68};
69
70// Default target shape for unrolling CreateMaskOp and ConstantMaskOp
71static std::optional<SmallVector<int64_t>>
75
76// Default target shape for unrolling InterleaveOp and DeinterleaveOp
77static std::optional<SmallVector<int64_t>>
81
82/// Helper method to classify a mask value. Currently, the method
83/// looks "under the hood" of a constant value with dense attributes
84/// and a constant mask operation (since the client may be called at
85/// various stages during progressive lowering).
87 if (auto c = mask.getDefiningOp<arith::ConstantOp>()) {
88 // Inspect constant dense values. We count up for bits that
89 // are set, count down for bits that are cleared, and bail
90 // when a mix is detected.
91 if (auto denseElts = llvm::dyn_cast<DenseIntElementsAttr>(c.getValue())) {
92 int64_t val = 0;
93 for (bool b : denseElts.getValues<bool>())
94 if (b && val >= 0)
95 val++;
96 else if (!b && val <= 0)
97 val--;
98 else
100 if (val > 0)
101 return MaskFormat::AllTrue;
102 if (val < 0)
104 }
105 } else if (auto m = mask.getDefiningOp<ConstantMaskOp>()) {
106 // Inspect constant mask index. If the index exceeds the
107 // dimension size, all bits are set. If the index is zero
108 // or less, no bits are set.
109 ArrayRef<int64_t> masks = m.getMaskDimSizes();
110 auto shape = m.getType().getShape();
111 bool allTrue = true;
112 bool allFalse = true;
113 for (auto [maskIdx, dimSize] : llvm::zip_equal(masks, shape)) {
114 if (maskIdx < dimSize)
115 allTrue = false;
116 if (maskIdx > 0)
117 allFalse = false;
118 }
119 if (allTrue)
120 return MaskFormat::AllTrue;
121 if (allFalse)
123 } else if (auto m = mask.getDefiningOp<CreateMaskOp>()) {
124 // Finds all-false create_masks. An all-true create_mask requires all
125 // dims to be constants, so that'll be folded to a constant_mask, then
126 // detected in the constant_mask case.
127 auto maskOperands = m.getOperands();
128 for (Value operand : maskOperands) {
129 if (auto constantOp = operand.getDefiningOp<arith::ConstantOp>()) {
130 int64_t dimSize =
131 llvm::cast<IntegerAttr>(constantOp.getValue()).getInt();
132 if (dimSize <= 0)
134 }
135 }
136 return MaskFormat::Unknown;
137 }
138 return MaskFormat::Unknown;
139}
140
141/// Default callback to build a region with a 'vector.yield' terminator with no
142/// arguments.
144 vector::YieldOp::create(builder, loc);
145}
146
147// Helper for verifying combining kinds in contractions and reductions.
148static bool isSupportedCombiningKind(CombiningKind combiningKind,
149 Type elementType) {
150 switch (combiningKind) {
151 case CombiningKind::ADD:
152 case CombiningKind::MUL:
153 return elementType.isIntOrIndexOrFloat();
154 case CombiningKind::MINUI:
155 case CombiningKind::MINSI:
156 case CombiningKind::MAXUI:
157 case CombiningKind::MAXSI:
158 case CombiningKind::AND:
159 case CombiningKind::OR:
160 case CombiningKind::XOR:
161 return elementType.isIntOrIndex();
162 case CombiningKind::MINNUMF:
163 case CombiningKind::MAXNUMF:
164 case CombiningKind::MINIMUMF:
165 case CombiningKind::MAXIMUMF:
166 case CombiningKind::MINIMUMNUMF:
167 case CombiningKind::MAXIMUMNUMF:
168 return llvm::isa<FloatType>(elementType);
169 }
170 return false;
171}
172
173/// Returns the effective rank of the vector to read/write for Xfer Ops
174///
175/// When the element type of the shaped type is _a scalar_, this will simply
176/// return the rank of the vector ( the result for xfer_read or the value to
177/// store for xfer_write).
178///
179/// When the element type of the base shaped type is _a vector_, returns the
180/// difference between the original vector type and the element type of the
181/// shaped type.
182///
183/// EXAMPLE 1 (element type is _a scalar_):
184/// - shapedType = tensor<10x20xf32>, vectorType = vector<2x4xf32>
185/// - shapedType.getElementType() = f32 (rank 0)
186/// - vectorType.getRank() = 2
187/// - Result = 2 - 0 = 2
188///
189/// EXAMPLE 2 (element type is _a vector_):
190/// - shapedType = tensor<10xvector<20xf32>>, vectorType = vector<20xf32>
191/// - shapedType.getElementType() = vector<20xf32> (rank 1)
192/// - vectorType.getRank() = 1
193/// - Result = 1 - 1 = 0
194///
195/// This is used to determine the number of minor dimensions for identity maps
196/// in vector transfer Ops.
197static unsigned getEffectiveVectorRankForXferOp(ShapedType shapedType,
198 VectorType vectorType) {
199 unsigned elementVectorRank = 0;
200 VectorType elementVectorType =
201 llvm::dyn_cast<VectorType>(shapedType.getElementType());
202 if (elementVectorType)
203 elementVectorRank += elementVectorType.getRank();
204 return vectorType.getRank() - elementVectorRank;
205}
206
208 VectorType vectorType) {
209 // 0-d transfers are to/from tensor<t>/memref<t> and vector<1xt>.
210 // TODO: replace once we have 0-d vectors.
211 if (shapedType.getRank() == 0 &&
212 vectorType.getShape() == ArrayRef<int64_t>{1})
213 return AffineMap::get(
214 /*numDims=*/0, /*numSymbols=*/0,
215 getAffineConstantExpr(0, shapedType.getContext()));
217 shapedType.getRank(),
218 getEffectiveVectorRankForXferOp(shapedType, vectorType),
219 shapedType.getContext());
220}
221
222/// Check if `write` is of a constant splat and the masked `read` is padded with
223/// the same splat value -- meaning it could be the same value as the initial
224/// constant splat.
225static bool isSplatWriteConsistentWithMaskedRead(vector::TransferWriteOp write,
226 vector::TransferReadOp read) {
227 auto readMask = read.getMask();
228 auto writeMask = write.getMask();
229 // Check if the masks are consistent. The splat value could be the same if the
230 // read is masked (and padded with the splat value), and the write is unmasked
231 // or has the same mask. Note this does not allow the case where the write is
232 // masked and the read is unmasked, as then the read could be of more elements
233 // than the write (which may not be the same value).
234 bool couldBeSameSplat = readMask && (!writeMask || writeMask == readMask);
235 if (!couldBeSameSplat)
236 return false;
237 // Check for constant splat (as the source of the write).
238 DenseElementsAttr splatAttr;
239 if (!matchPattern(write.getVector(),
240 m_Constant<DenseElementsAttr>(&splatAttr)) ||
241 !splatAttr.isSplat()) {
242 return false;
243 }
244 // The padding of the read and the constant splat value must be the same.
245 Attribute padAttr;
246 if (!matchPattern(read.getPadding(), m_Constant(&padAttr)))
247 return false;
248 return padAttr == splatAttr.getSplatValue<Attribute>();
249}
250
251bool mlir::vector::checkSameValueRAW(vector::TransferWriteOp defWrite,
252 vector::TransferReadOp read) {
253 // An enclosing vector.mask may leave some lanes unwritten or padded, so the
254 // read may not see the written vector as a whole. This conservatively
255 // includes all-true masks. MaskOp::fold removes them during canonicalization,
256 // so this only matters when a caller such as transferOpflowOpt runs first.
257 // TODO: Account for compatible region masks instead of conservatively
258 // rejecting all region-masked operations.
259 if (defWrite.isMasked() || read.isMasked())
260 return false;
261 return !defWrite.hasOutOfBoundsDim() &&
262 defWrite.getIndices() == read.getIndices() &&
263 defWrite.getVectorType() == read.getVectorType() &&
264 defWrite.getPermutationMap() == read.getPermutationMap() &&
265 ((!defWrite.getMask() && !read.getMask()) ||
267}
268
269bool mlir::vector::checkSameValueWAW(vector::TransferWriteOp write,
270 vector::TransferWriteOp priorWrite) {
271 // A write under an enclosing vector.mask may not overwrite all lanes of the
272 // prior write. This conservatively includes all-true masks, which
273 // MaskOp::fold removes during canonicalization. Only the later write needs
274 // checking: a region-masked prior write is still dead if the later write
275 // fully overwrites it.
276 // TODO: Handle a region-masked later write when it is known to fully
277 // overwrite the prior write.
278 if (write.isMasked())
279 return false;
280 return priorWrite.getIndices() == write.getIndices() &&
281 priorWrite.getMask() == write.getMask() &&
282 priorWrite.getVectorType() == write.getVectorType() &&
283 priorWrite.getPermutationMap() == write.getPermutationMap();
284}
285
287 VectorTransferOpInterface transferA, VectorTransferOpInterface transferB,
288 bool testDynamicValueUsingBounds) {
289 // For simplicity only look at transfer of same type.
290 if (transferA.getVectorType() != transferB.getVectorType())
291 return false;
292 unsigned rankOffset = transferA.getLeadingShapedRank();
293 for (unsigned i = 0, e = transferA.getIndices().size(); i < e; i++) {
294 Value indexA = transferA.getIndices()[i];
295 Value indexB = transferB.getIndices()[i];
296 std::optional<int64_t> cstIndexA = getConstantIntValue(indexA);
297 std::optional<int64_t> cstIndexB = getConstantIntValue(indexB);
298
299 if (i < rankOffset) {
300 // For leading dimensions, if we can prove that index are different we
301 // know we are accessing disjoint slices.
302 if (cstIndexA.has_value() && cstIndexB.has_value()) {
303 if (*cstIndexA != *cstIndexB)
304 return true;
305 continue;
306 }
307 if (testDynamicValueUsingBounds) {
308 // First try to see if we can fully compose and simplify the affine
309 // expression as a fast track.
310 FailureOr<uint64_t> delta =
312 if (succeeded(delta) && *delta != 0)
313 return true;
314
315 FailureOr<bool> testEqual =
317 if (succeeded(testEqual) && !testEqual.value())
318 return true;
319 }
320 } else {
321 // For this dimension, we slice a part of the memref we need to make sure
322 // the intervals accessed don't overlap.
323 int64_t vectorDim = transferA.getVectorType().getDimSize(i - rankOffset);
324 if (cstIndexA.has_value() && cstIndexB.has_value()) {
325 int64_t distance = std::abs(*cstIndexA - *cstIndexB);
326 if (distance >= vectorDim)
327 return true;
328 continue;
329 }
330 if (testDynamicValueUsingBounds) {
331 // First try to see if we can fully compose and simplify the affine
332 // expression as a fast track.
333 FailureOr<int64_t> delta =
335 if (succeeded(delta) && std::abs(*delta) >= vectorDim)
336 return true;
337
338 FailureOr<int64_t> computeDelta =
340 if (succeeded(computeDelta)) {
341 if (std::abs(computeDelta.value()) >= vectorDim)
342 return true;
343 }
344 }
345 }
346 }
347 return false;
348}
349
350bool mlir::vector::isDisjointTransferSet(VectorTransferOpInterface transferA,
351 VectorTransferOpInterface transferB,
352 bool testDynamicValueUsingBounds) {
353 if (transferA.getBase() != transferB.getBase())
354 return false;
355 return isDisjointTransferIndices(transferA, transferB,
356 testDynamicValueUsingBounds);
357}
358
359// Helper to iterate over n-D vector slice elements. Calculate the next
360// `position` in the n-D vector of size `shape`, applying an offset `offsets`.
361// Modifies the `position` in place. Returns a failure when `position` becomes
362// the end position.
363static LogicalResult incSlicePosition(MutableArrayRef<int64_t> position,
365 ArrayRef<int64_t> offsets) {
366 for (auto [posInDim, dimSize, offsetInDim] :
367 llvm::reverse(llvm::zip_equal(position, shape, offsets))) {
368 ++posInDim;
369 if (posInDim < dimSize + offsetInDim)
370 return success();
371
372 // Carry the overflow to the next loop iteration.
373 posInDim = offsetInDim;
374 }
375
376 return failure();
377}
378
379/// Returns the integer numbers in `values`. `values` are expected to be
380/// constant operations.
383 llvm::transform(values, std::back_inserter(ints), [](Value value) {
384 auto constOp = value.getDefiningOp<arith::ConstantIndexOp>();
385 assert(constOp && "Unexpected non-constant index");
386 return constOp.value();
387 });
388 return ints;
389}
390
391/// Returns the integer numbers in `foldResults`. `foldResults` are expected to
392/// be constant operations.
395 llvm::transform(
396 foldResults, std::back_inserter(ints), [](OpFoldResult foldResult) {
397 assert(isa<Attribute>(foldResult) && "Unexpected non-constant index");
398 return cast<IntegerAttr>(cast<Attribute>(foldResult)).getInt();
399 });
400 return ints;
401}
402
403/// Convert `foldResults` into Values. Integer attributes are converted to
404/// constant op.
406 ArrayRef<OpFoldResult> foldResults) {
407 SmallVector<Value> values;
408 llvm::transform(foldResults, std::back_inserter(values),
409 [&](OpFoldResult foldResult) {
410 if (auto attr = dyn_cast<Attribute>(foldResult))
412 builder, loc, cast<IntegerAttr>(attr).getInt())
413 .getResult();
414
415 return cast<Value>(foldResult);
416 });
417 return values;
418}
419
420std::optional<int64_t> vector::getConstantVscaleMultiplier(Value value) {
421 if (value.getDefiningOp<vector::VectorScaleOp>())
422 return 1;
423 auto mul = value.getDefiningOp<arith::MulIOp>();
424 if (!mul)
425 return {};
426 auto lhs = mul.getLhs();
427 auto rhs = mul.getRhs();
428 if (lhs.getDefiningOp<vector::VectorScaleOp>())
429 return getConstantIntValue(rhs);
430 if (rhs.getDefiningOp<vector::VectorScaleOp>())
431 return getConstantIntValue(lhs);
432 return {};
433}
434
435/// Converts numeric attributes to the expected type. Supports
436/// integer-to-integer and float-to-integer conversions. Returns the original
437/// attribute if no conversion is needed or supported.
438static Attribute convertNumericAttr(Attribute attr, Type expectedType) {
439 // Integer-to-integer conversion
440 if (auto intAttr = dyn_cast<IntegerAttr>(attr)) {
441 if (auto intType = dyn_cast<IntegerType>(expectedType)) {
442 if (intAttr.getType() != expectedType)
443 return IntegerAttr::get(expectedType, intAttr.getInt());
444 }
445 return attr;
446 }
447
448 // Float-to-integer bitcast (preserves bit representation)
449 if (auto floatAttr = dyn_cast<FloatAttr>(attr)) {
450 auto intType = dyn_cast<IntegerType>(expectedType);
451 if (!intType)
452 return attr;
453
454 APFloat floatVal = floatAttr.getValue();
455 APInt intVal = floatVal.bitcastToAPInt();
456 return IntegerAttr::get(expectedType, intVal);
457 }
458
459 return attr;
460}
461
462/// Return whether `srcType` can be broadcast to `dstVectorType` under the
463/// semantics of the `vector.broadcast` op.
465 Type srcType, VectorType dstVectorType,
466 std::pair<VectorDim, VectorDim> *mismatchingDims) {
467 // Broadcast scalar to vector of the same element type.
468 if (isa<VectorElementTypeInterface>(srcType) && dstVectorType &&
469 srcType == getElementTypeOrSelf(dstVectorType))
471 // From now on, only vectors broadcast.
472 VectorType srcVectorType = llvm::dyn_cast<VectorType>(srcType);
473 if (!srcVectorType)
475
476 int64_t srcRank = srcVectorType.getRank();
477 int64_t dstRank = dstVectorType.getRank();
478 if (srcRank > dstRank)
480 // Source has an exact match or singleton value for all trailing dimensions
481 // (all leading dimensions are simply duplicated).
482 int64_t lead = dstRank - srcRank;
483 for (int64_t dimIdx = 0; dimIdx < srcRank; ++dimIdx) {
484 // Have mismatching dims (in the sense of vector.broadcast semantics) been
485 // encountered?
486 bool foundMismatchingDims = false;
487
488 // Check fixed-width dims.
489 int64_t srcDim = srcVectorType.getDimSize(dimIdx);
490 int64_t dstDim = dstVectorType.getDimSize(lead + dimIdx);
491 if (srcDim != 1 && srcDim != dstDim)
492 foundMismatchingDims = true;
493
494 // Check scalable flags.
495 bool srcDimScalableFlag = srcVectorType.getScalableDims()[dimIdx];
496 bool dstDimScalableFlag = dstVectorType.getScalableDims()[lead + dimIdx];
497 if ((srcDim == 1 && srcDimScalableFlag && dstDim != 1) ||
498 // 1 -> [N] is fine, everything else should be rejected when mixing
499 // fixed-width and scalable dims
500 (srcDimScalableFlag != dstDimScalableFlag &&
501 (srcDim != 1 || srcDimScalableFlag)))
502 foundMismatchingDims = true;
503
504 if (foundMismatchingDims) {
505 if (mismatchingDims != nullptr) {
506 mismatchingDims->first.dim = srcDim;
507 mismatchingDims->first.isScalable = srcDimScalableFlag;
508
509 mismatchingDims->second.dim = dstDim;
510 mismatchingDims->second.isScalable = dstDimScalableFlag;
511 }
513 }
514 }
515
517}
518
519//===----------------------------------------------------------------------===//
520// CombiningKindAttr
521//===----------------------------------------------------------------------===//
522
523namespace mlir {
524namespace vector {
525namespace detail {
527 using KeyTy = uint64_t;
528
530
531 bool operator==(const KeyTy &key) const { return value == key; }
532
534 const KeyTy &key) {
535 return new (allocator.allocate<BitmaskEnumStorage>())
537 }
538
540};
541} // namespace detail
542} // namespace vector
543} // namespace mlir
544
545//===----------------------------------------------------------------------===//
546// VectorDialect
547//===----------------------------------------------------------------------===//
548
549namespace {
550/// This class defines the interface for handling inlining with vector dialect
551/// operations.
552struct VectorInlinerInterface : public DialectInlinerInterface {
553 using DialectInlinerInterface::DialectInlinerInterface;
554
555 /// All vector dialect ops can be inlined.
556 bool isLegalToInline(Operation *, Region *, bool, IRMapping &) const final {
557 return true;
558 }
559};
560} // namespace
561
562void VectorDialect::initialize() {
563 addInterfaces<VectorInlinerInterface>();
564
565 declarePromisedInterfaces<memref::IndexedAccessOpInterface, LoadOp, StoreOp,
566 MaskedLoadOp, MaskedStoreOp, ExpandLoadOp,
567 CompressStoreOp>();
568 declarePromisedInterfaces<bufferization::BufferizableOpInterface,
569 TransferReadOp, TransferWriteOp, GatherOp, MaskOp,
570 YieldOp>();
571 declarePromisedInterfaces<SubsetOpInterface, TransferReadOp,
572 TransferWriteOp>();
573 declarePromisedInterface<SubsetExtractionOpInterface, TransferReadOp>();
574 declarePromisedInterface<SubsetInsertionOpInterface, TransferWriteOp>();
575 declarePromisedInterface<ConvertToLLVMPatternInterface, VectorDialect>();
576}
577
578/// Materialize a single constant operation from a given attribute value with
579/// the desired resultant type.
580Operation *VectorDialect::materializeConstant(OpBuilder &builder,
581 Attribute value, Type type,
582 Location loc) {
583 if (matchPattern(value, ub::m_Poison()))
584 return value.getDialect().materializeConstant(builder, value, type, loc);
585
586 return arith::ConstantOp::materialize(builder, value, type, loc);
587}
588
590 return builder.getIntegerType(64);
591}
592
594 ArrayRef<int64_t> values) {
595 return builder.getI64ArrayAttr(values);
596}
597
598//===----------------------------------------------------------------------===//
599// MultiDimReductionOp
600//===----------------------------------------------------------------------===//
601
602void vector::MultiDimReductionOp::build(OpBuilder &builder,
603 OperationState &result, Value source,
604 Value acc, ArrayRef<bool> reductionMask,
605 CombiningKind kind,
606 arith::FastMathFlags fastMathFlags) {
607 SmallVector<int64_t> reductionDims;
608 for (const auto &en : llvm::enumerate(reductionMask))
609 if (en.value())
610 reductionDims.push_back(en.index());
611 build(builder, result, kind, source, acc, reductionDims, fastMathFlags);
612}
613
614OpFoldResult MultiDimReductionOp::fold(FoldAdaptor adaptor) {
615 // No reduction dims: this is a noop regardless of rank.
616 if (getReductionDims().empty())
617 return getSource();
618 return {};
619}
620
621LogicalResult MultiDimReductionOp::verify() {
622 // Verify the reduction dimensions.
623 int64_t sourceRank = getSourceVectorType().getRank();
624 SmallVector<bool> isReduced(sourceRank, false);
625 for (int64_t dim : getReductionDims()) {
626 if (dim < 0 || dim >= sourceRank)
627 return emitOpError("reduction dimension out of range: ") << dim;
628 if (isReduced[dim])
629 return emitOpError("duplicate reduction dimension: ") << dim;
630 isReduced[dim] = true;
631 }
632
633 SmallVector<int64_t> targetShape;
634 SmallVector<bool> scalableDims;
635 Type inferredReturnType;
636 auto sourceScalableDims = getSourceVectorType().getScalableDims();
637 for (auto [dimIdx, dimSize] :
638 llvm::enumerate(getSourceVectorType().getShape()))
639 if (!isReduced[dimIdx]) {
640 targetShape.push_back(dimSize);
641 scalableDims.push_back(sourceScalableDims[dimIdx]);
642 }
643 // TODO: update to also allow 0-d vectors when available.
644 if (targetShape.empty())
645 inferredReturnType = getSourceVectorType().getElementType();
646 else
647 inferredReturnType = VectorType::get(
648 targetShape, getSourceVectorType().getElementType(), scalableDims);
649 if (getType() != inferredReturnType)
650 return emitOpError() << "destination type " << getType()
651 << " is incompatible with source type "
652 << getSourceVectorType();
653
654 return success();
655}
656
657/// Returns the mask type expected by this operation.
658Type MultiDimReductionOp::getExpectedMaskType() {
659 auto vecType = getSourceVectorType();
660 return VectorType::get(vecType.getShape(),
661 IntegerType::get(vecType.getContext(), /*width=*/1),
662 vecType.getScalableDims());
663}
664
665//-----------------------------------------------------------------------------
666// VectorUnrollOpInterface methods
667//-----------------------------------------------------------------------------
668std::optional<SmallVector<int64_t, 4>>
669MultiDimReductionOp::getIterationShapeToUnroll() {
670 return llvm::to_vector<4>(getSourceVectorType().getShape());
671}
672
673namespace {
674// Only unit dimensions that are being reduced are folded. If the dimension is
675// unit, but not reduced, it is not folded, thereby keeping the output type the
676// same. If not all dimensions which are reduced are of unit dimension, this
677// transformation does nothing. This is just a generalization of
678// ElideSingleElementReduction for ReduceOp.
679struct ElideUnitDimsInMultiDimReduction
680 : public OpRewritePattern<MultiDimReductionOp> {
681 using Base::Base;
682
683 LogicalResult matchAndRewrite(MultiDimReductionOp reductionOp,
684 PatternRewriter &rewriter) const override {
685 ArrayRef<int64_t> shape = reductionOp.getSourceVectorType().getShape();
686 for (const auto &dim : enumerate(shape)) {
687 if (reductionOp.isReducedDim(dim.index()) && dim.value() != 1)
688 return failure();
689 }
690
691 // Vector mask setup.
692 OpBuilder::InsertionGuard guard(rewriter);
693 Operation *rootOp;
694 Value mask;
695 if (reductionOp.isMasked()) {
696 rewriter.setInsertionPoint(reductionOp.getMaskingOp());
697 rootOp = reductionOp.getMaskingOp();
698 mask = reductionOp.getMaskingOp().getMask();
699 } else {
700 rootOp = reductionOp;
701 }
702
703 Location loc = reductionOp.getLoc();
704 Value acc = reductionOp.getAcc();
705 Value cast;
706 if (auto dstVecType = dyn_cast<VectorType>(reductionOp.getDestType())) {
707 if (mask) {
708 VectorType newMaskType =
709 VectorType::get(dstVecType.getShape(), rewriter.getI1Type(),
710 dstVecType.getScalableDims());
711 mask = vector::ShapeCastOp::create(rewriter, loc, newMaskType, mask);
712 }
713 cast = vector::ShapeCastOp::create(
714 rewriter, loc, reductionOp.getDestType(), reductionOp.getSource());
715 } else {
716 // This means we are reducing all the dimensions, and all reduction
717 // dimensions are of size 1. So a simple extraction would do.
718 if (mask)
719 mask = vector::ExtractOp::create(rewriter, loc, mask);
720 cast = vector::ExtractOp::create(rewriter, loc, reductionOp.getSource());
721 }
722
723 Value result =
724 vector::makeArithReduction(rewriter, loc, reductionOp.getKind(), cast,
725 acc, reductionOp.getFastmathAttr(), mask);
726 rewriter.replaceOp(rootOp, result);
727 return success();
728 }
729};
730} // namespace
731
732void MultiDimReductionOp::getCanonicalizationPatterns(
733 RewritePatternSet &results, MLIRContext *context) {
734 results.add<ElideUnitDimsInMultiDimReduction>(context);
735}
736
737//===----------------------------------------------------------------------===//
738// ReductionOp
739//===----------------------------------------------------------------------===//
740
741void vector::ReductionOp::build(OpBuilder &builder, OperationState &result,
742 CombiningKind kind, Value vector,
743 arith::FastMathFlags fastMathFlags) {
744 build(builder, result, kind, vector, /*acc=*/Value(), fastMathFlags);
745}
746
747void vector::ReductionOp::build(OpBuilder &builder, OperationState &result,
748 CombiningKind kind, Value vector, Value acc,
749 arith::FastMathFlags fastMathFlags) {
750 build(builder, result,
751 llvm::cast<VectorType>(vector.getType()).getElementType(), kind, vector,
752 acc, fastMathFlags);
753}
754
755LogicalResult ReductionOp::verify() {
756 // Verify for 0-D and 1-D vector.
757 int64_t rank = getSourceVectorType().getRank();
758 if (rank > 1)
759 return emitOpError("unsupported reduction rank: ") << rank;
760
761 // Verify supported reduction kind.
762 Type eltType = getResult().getType();
763 if (!isSupportedCombiningKind(getKind(), eltType))
764 return emitOpError("unsupported reduction type '")
765 << eltType << "' for kind '" << stringifyCombiningKind(getKind())
766 << "'";
767
768 return success();
769}
770
771// MaskableOpInterface methods.
772
773/// Returns the mask type expected by this operation.
774Type ReductionOp::getExpectedMaskType() {
775 auto vecType = getSourceVectorType();
776 return VectorType::get(vecType.getShape(),
777 IntegerType::get(vecType.getContext(), /*width=*/1),
778 vecType.getScalableDims());
779}
780
782 OpBuilder &builder, Location loc,
783 Value vector) {
784 switch (op) {
785 case arith::AtomicRMWKind::addf:
786 case arith::AtomicRMWKind::addi:
787 return vector::ReductionOp::create(builder, vector.getLoc(),
788 CombiningKind::ADD, vector);
789 case arith::AtomicRMWKind::mulf:
790 case arith::AtomicRMWKind::muli:
791 return vector::ReductionOp::create(builder, vector.getLoc(),
792 CombiningKind::MUL, vector);
793 case arith::AtomicRMWKind::minimumf:
794 return vector::ReductionOp::create(builder, vector.getLoc(),
795 CombiningKind::MINIMUMF, vector);
796 case arith::AtomicRMWKind::mins:
797 return vector::ReductionOp::create(builder, vector.getLoc(),
798 CombiningKind::MINSI, vector);
799 case arith::AtomicRMWKind::minu:
800 return vector::ReductionOp::create(builder, vector.getLoc(),
801 CombiningKind::MINUI, vector);
802 case arith::AtomicRMWKind::maximumf:
803 return vector::ReductionOp::create(builder, vector.getLoc(),
804 CombiningKind::MAXIMUMF, vector);
805 case arith::AtomicRMWKind::maxs:
806 return vector::ReductionOp::create(builder, vector.getLoc(),
807 CombiningKind::MAXSI, vector);
808 case arith::AtomicRMWKind::maxu:
809 return vector::ReductionOp::create(builder, vector.getLoc(),
810 CombiningKind::MAXUI, vector);
811 case arith::AtomicRMWKind::andi:
812 return vector::ReductionOp::create(builder, vector.getLoc(),
813 CombiningKind::AND, vector);
814 case arith::AtomicRMWKind::ori:
815 return vector::ReductionOp::create(builder, vector.getLoc(),
816 CombiningKind::OR, vector);
817 case arith::AtomicRMWKind::minnumf:
818 return vector::ReductionOp::create(builder, vector.getLoc(),
819 CombiningKind::MINNUMF, vector);
820 case arith::AtomicRMWKind::maxnumf:
821 return vector::ReductionOp::create(builder, vector.getLoc(),
822 CombiningKind::MAXNUMF, vector);
823 case arith::AtomicRMWKind::xori:
824 return vector::ReductionOp::create(builder, vector.getLoc(),
825 CombiningKind::XOR, vector);
826 default:
827 (void)emitOptionalError(loc, "Reduction operation type not supported");
828 break;
829 }
830 return nullptr;
831}
832
833//-----------------------------------------------------------------------------
834// VectorUnrollOpInterface methods
835//-----------------------------------------------------------------------------
836std::optional<SmallVector<int64_t, 4>>
837ReductionOp::getIterationShapeToUnroll() {
838 return llvm::to_vector<4>(getSourceVectorType().getShape());
839}
840std::optional<SmallVector<int64_t>> ReductionOp::getDefaultUnrollTargetShape() {
841 return SmallVector<int64_t>{2};
842}
843
844namespace {
845struct ElideSingleElementReduction : public OpRewritePattern<ReductionOp> {
846 using Base::Base;
847
848 LogicalResult matchAndRewrite(ReductionOp reductionOp,
849 PatternRewriter &rewriter) const override {
850 // Vector mask setup.
851 OpBuilder::InsertionGuard guard(rewriter);
852 auto maskableOp =
853 cast<vector::MaskableOpInterface>(reductionOp.getOperation());
854 Operation *rootOp;
855 Value mask;
856 if (maskableOp.isMasked()) {
857 rewriter.setInsertionPoint(maskableOp.getMaskingOp());
858 rootOp = maskableOp.getMaskingOp();
859 mask = maskableOp.getMaskingOp().getMask();
860 } else {
861 rootOp = reductionOp;
862 }
863
864 auto vectorType = reductionOp.getSourceVectorType();
865 if (vectorType.getRank() != 0 && vectorType.getDimSize(0) != 1)
866 return failure();
867
868 Location loc = reductionOp.getLoc();
869 if (mask)
870 mask = ExtractOp::create(rewriter, loc, mask);
871 Value result = ExtractOp::create(rewriter, loc, reductionOp.getVector());
872
873 if (Value acc = reductionOp.getAcc())
874 result = vector::makeArithReduction(rewriter, loc, reductionOp.getKind(),
875 result, acc,
876 reductionOp.getFastmathAttr(), mask);
877
878 rewriter.replaceOp(rootOp, result);
879 return success();
880 }
881};
882} // namespace
883
884void ReductionOp::getCanonicalizationPatterns(RewritePatternSet &results,
885 MLIRContext *context) {
886 results.add<ElideSingleElementReduction>(context);
887}
888
889//===----------------------------------------------------------------------===//
890// ContractionOp
891//===----------------------------------------------------------------------===//
892
893void vector::ContractionOp::build(OpBuilder &builder, OperationState &result,
894 Value lhs, Value rhs, Value acc,
895 ArrayRef<ArrayRef<AffineExpr>> indexingExprs,
896 ArrayRef<IteratorType> iteratorTypes) {
897 result.addOperands({lhs, rhs, acc});
898 result.addTypes(acc.getType());
899 result.addAttribute(
900 getIndexingMapsAttrName(result.name),
901 builder.getAffineMapArrayAttr(
902 AffineMap::inferFromExprList(indexingExprs, builder.getContext())));
903 result.addAttribute(
904 getIteratorTypesAttrName(result.name),
905 builder.getArrayAttr(llvm::map_to_vector(
906 iteratorTypes, [&](IteratorType t) -> mlir::Attribute {
907 return IteratorTypeAttr::get(builder.getContext(), t);
908 })));
909}
910
911void vector::ContractionOp::build(OpBuilder &builder, OperationState &result,
912 Value lhs, Value rhs, Value acc,
913 ArrayAttr indexingMaps,
914 ArrayAttr iteratorTypes) {
915 build(builder, result, lhs, rhs, acc, indexingMaps, iteratorTypes,
916 ContractionOp::getDefaultKind());
917}
918
919void vector::ContractionOp::build(OpBuilder &builder, OperationState &result,
920 Value lhs, Value rhs, Value acc,
921 ArrayAttr indexingMaps,
922 ArrayAttr iteratorTypes, CombiningKind kind,
923 arith::FastMathFlags fastMathFlags) {
924 result.addOperands({lhs, rhs, acc});
925 result.addTypes(acc.getType());
926 result.addAttribute(getIndexingMapsAttrName(result.name), indexingMaps);
927 result.addAttribute(getIteratorTypesAttrName(result.name), iteratorTypes);
928 result.addAttribute(getKindAttrName(result.name),
929 CombiningKindAttr::get(builder.getContext(), kind));
930 if (fastMathFlags != arith::FastMathFlags::none)
931 result.addAttribute(
932 getFastmathAttrName(result.name),
933 arith::FastMathFlagsAttr::get(builder.getContext(), fastMathFlags));
934}
935
936ParseResult ContractionOp::parse(OpAsmParser &parser, OperationState &result) {
942 Type resultType;
943 auto loc = parser.getCurrentLocation();
944 DictionaryAttr dictAttr;
945 // TODO: Unify linalg op attribute parsing.
946 if (parser.parseAttribute(dictAttr) || parser.parseOperand(lhsInfo) ||
947 parser.parseComma() || parser.parseOperand(rhsInfo) ||
948 parser.parseComma() || parser.parseOperand(accInfo) ||
949 parser.parseTrailingOperandList(masksInfo) ||
950 parser.parseOptionalAttrDict(result.attributes) ||
951 parser.parseColonTypeList(types) ||
952 parser.parseKeywordType("into", resultType) ||
953 parser.resolveOperand(lhsInfo, types[0], result.operands) ||
954 parser.resolveOperand(rhsInfo, types[1], result.operands) ||
955 parser.resolveOperand(accInfo, resultType, result.operands) ||
956 parser.addTypeToList(resultType, result.types))
957 return failure();
958 result.attributes.append(dictAttr.getValue().begin(),
959 dictAttr.getValue().end());
960
961 // Convert array of string into an array of IteratyType enums. This is needed,
962 // because tests still use the old format when 'iterator_types' attribute is
963 // represented as an array of strings.
964 // TODO: Remove this conversion once tests are fixed.
965 auto iteratorTypes = dyn_cast_or_null<ArrayAttr>(
966 result.attributes.get(getIteratorTypesAttrName(result.name)));
967 if (!iteratorTypes) {
968 return parser.emitError(loc)
969 << "expected " << getIteratorTypesAttrName(result.name)
970 << " array attribute";
971 }
972
973 SmallVector<Attribute> iteratorTypeAttrs;
974
975 for (StringRef s : iteratorTypes.getAsValueRange<StringAttr>()) {
976 auto maybeIteratorType = symbolizeIteratorType(s);
977 if (!maybeIteratorType.has_value())
978 return parser.emitError(loc) << "unexpected iterator_type (" << s << ")";
979
980 iteratorTypeAttrs.push_back(
981 IteratorTypeAttr::get(parser.getContext(), maybeIteratorType.value()));
982 }
983 result.attributes.set(getIteratorTypesAttrName(result.name),
984 parser.getBuilder().getArrayAttr(iteratorTypeAttrs));
985
986 if (!result.attributes.get(getKindAttrName(result.name))) {
987 result.addAttribute(
988 getKindAttrName(result.name),
989 CombiningKindAttr::get(result.getContext(),
990 ContractionOp::getDefaultKind()));
991 }
992 if (masksInfo.empty())
993 return success();
994 if (masksInfo.size() != 2)
995 return parser.emitError(parser.getNameLoc(),
996 "expected zero or exactly 2 vector mask operands");
997 auto lhsType = llvm::cast<VectorType>(types[0]);
998 auto rhsType = llvm::cast<VectorType>(types[1]);
999 auto maskElementType = parser.getBuilder().getI1Type();
1000 std::array<VectorType, 2> maskTypes = {
1001 VectorType::Builder(lhsType).setElementType(maskElementType),
1002 VectorType::Builder(rhsType).setElementType(maskElementType)};
1003 if (parser.resolveOperands(masksInfo, maskTypes, loc, result.operands))
1004 return failure();
1005 return success();
1006}
1007
1008void ContractionOp::print(OpAsmPrinter &p) {
1009 // TODO: Unify printing code with linalg ops.
1010 auto attrNames = getTraitAttrNames();
1011 llvm::StringSet<> traitAttrsSet;
1012 traitAttrsSet.insert_range(attrNames);
1013 NamedAttrList allAttrs(getOperation()->getRawDictionaryAttrs());
1014 getOperation()->getName().walkInherentAttrs(
1015 getOperation(),
1016 [&](StringRef name, Attribute &attr) { allAttrs.append(name, attr); });
1018 for (auto attr : allAttrs) {
1019 if (attr.getName() == getIteratorTypesAttrName()) {
1020 auto iteratorTypes =
1021 llvm::cast<ArrayAttr>(attr.getValue())
1022 .getAsValueRange<IteratorTypeAttr, IteratorType>();
1023 // Convert IteratorType enums into the string representation. This is
1024 // needed, because tests still use the old format when 'iterator_types'
1025 // attribute is represented as an array of strings.
1026 // TODO: Remove this conversion once tests are fixed.
1027 SmallVector<Attribute> iteratorTypeNames =
1028 llvm::map_to_vector(iteratorTypes, [&](IteratorType t) -> Attribute {
1029 return StringAttr::get(getContext(), stringifyIteratorType(t));
1030 });
1031
1032 attrs.emplace_back(getIteratorTypesAttrName(),
1033 ArrayAttr::get(getContext(), iteratorTypeNames));
1034 } else if (traitAttrsSet.count(attr.getName().strref()) > 0) {
1035 // Omit fastmath when it equals the default (none) to keep output clean.
1036 if (attr.getName() == getFastmathAttrName() &&
1037 llvm::cast<arith::FastMathFlagsAttr>(attr.getValue()).getValue() ==
1038 arith::FastMathFlags::none)
1039 continue;
1040 attrs.push_back(attr);
1041 }
1042 }
1043
1044 auto dictAttr = DictionaryAttr::get(getContext(), attrs);
1045 p << " " << dictAttr << " " << getLhs() << ", ";
1046 p << getRhs() << ", " << getAcc();
1047
1048 p.printOptionalAttrDict(allAttrs.getAttrs(), attrNames);
1049 p << " : " << getLhs().getType() << ", " << getRhs().getType() << " into "
1050 << getResultType();
1051}
1052
1053static bool verifyDimMap(VectorType lhsType, VectorType rhsType,
1054 const std::vector<std::pair<int64_t, int64_t>> &map) {
1055 for (auto &dimPair : map) {
1056 if (dimPair.first < 0 || dimPair.first >= lhsType.getRank() ||
1057 dimPair.second < 0 || dimPair.second >= rhsType.getRank() ||
1058 lhsType.getDimSize(dimPair.first) != rhsType.getDimSize(dimPair.second))
1059 return false;
1060 }
1061 return true;
1062}
1063
1064static LogicalResult verifyOutputShape(
1065 ContractionOp op, VectorType lhsType, VectorType rhsType, Type accType,
1066 Type resType,
1067 const std::vector<std::pair<int64_t, int64_t>> &contractingDimMap,
1068 const std::vector<std::pair<int64_t, int64_t>> &batchDimMap) {
1069 DenseSet<int64_t> lhsContractingDimSet;
1070 DenseSet<int64_t> rhsContractingDimSet;
1071 for (auto &dimPair : contractingDimMap) {
1072 lhsContractingDimSet.insert(dimPair.first);
1073 rhsContractingDimSet.insert(dimPair.second);
1074 }
1075 DenseSet<int64_t> rhsBatchDimSet(llvm::from_range,
1076 llvm::make_second_range(batchDimMap));
1077
1078 // Add free and batch dimensions from 'lhsType' to 'expectedResultDims'.
1079 SmallVector<int64_t, 4> expectedResultDims;
1080 for (int64_t i = 0, e = lhsType.getRank(); i < e; ++i) {
1081 if (lhsContractingDimSet.count(i) > 0)
1082 continue;
1083 expectedResultDims.push_back(lhsType.getDimSize(i));
1084 }
1085
1086 // Add free dimensions from 'rhsType' to 'expectedResultDims'.
1087 for (int64_t i = 0, e = rhsType.getRank(); i < e; ++i) {
1088 if (rhsContractingDimSet.count(i) > 0 || rhsBatchDimSet.count(i) > 0)
1089 continue;
1090 expectedResultDims.push_back(rhsType.getDimSize(i));
1091 }
1092
1093 // The accumulator and the result must agree, regardless of the rank.
1094 if (resType != accType)
1095 return op.emitOpError("expected same accumulator and result type");
1096
1097 // Verify 'expectedResultDims'.
1098 if (expectedResultDims.empty()) {
1099 // No batch or free dimension implies a scalar or 0-D vector result.
1100 if (auto resVectorType = llvm::dyn_cast<VectorType>(resType))
1101 if (resVectorType.getRank() != 0)
1102 return op.emitOpError("expected scalar or 0-D vector result when "
1103 "there are no batch or free dimensions");
1104 } else {
1105 // At least one batch or free dimension implies a vector result.
1106 auto resVectorType = llvm::dyn_cast<VectorType>(resType);
1107 auto accVectorType = llvm::dyn_cast<VectorType>(accType);
1108 if (!resVectorType || !accVectorType)
1109 return op.emitOpError("invalid accumulator/result vector shape");
1110
1111 // Infer expected result vector type. Lhs + rhs map and lhs + rhs vector
1112 // types fully define the result vector type. This assumes the affine maps
1113 // are well-formed, which must have been verified already.
1114 MLIRContext *ctx = op.getContext();
1115 AffineMap lhsMap = op.getIndexingMapsArray()[0];
1116 AffineMap rhsMap = op.getIndexingMapsArray()[1];
1117 if (getUnusedDimsBitVector({lhsMap, rhsMap}).any())
1118 return op.emitOpError(
1119 "expected all dimensions to be either a LHS or a RHS dimension");
1120 SmallVector<AffineExpr, 4> extents(lhsMap.getNumInputs());
1121 for (auto pair :
1122 {std::make_pair(lhsType, lhsMap), std::make_pair(rhsType, rhsMap)}) {
1123 VectorType v = pair.first;
1124 auto map = pair.second;
1125 for (unsigned idx = 0, e = v.getRank(); idx < e; ++idx) {
1126 unsigned pos = map.getDimPosition(idx);
1127 if (!extents[pos])
1128 extents[pos] = getAffineConstantExpr(v.getShape()[idx], ctx);
1129 }
1130 }
1131 if (!llvm::all_of(extents, [](AffineExpr e) { return e; }))
1132 return op.emitOpError("expected all dimensions to get an extent as "
1133 "either a LHS or a RHS dimension");
1134
1135 AffineMap resMap = op.getIndexingMapsArray()[2];
1136 auto extentsMap = AffineMap::get(/*dimCount=*/extents.size(),
1137 /*symbolCount=*/0, extents, ctx);
1138 // Compose the resMap with the extentsMap, which is a constant map.
1139 AffineMap expectedMap = simplifyAffineMap(resMap.compose(extentsMap));
1140 assert(llvm::all_of(expectedMap.getResults(),
1141 llvm::IsaPred<AffineConstantExpr>) &&
1142 "expected constant extent along all dimensions.");
1143 // Extract the expected shape and build the type.
1144 auto expectedShape =
1145 llvm::map_to_vector<4>(expectedMap.getResults(), [](AffineExpr e) {
1146 return cast<AffineConstantExpr>(e).getValue();
1147 });
1148 auto expected =
1149 VectorType::get(expectedShape, resVectorType.getElementType(),
1150 resVectorType.getScalableDims());
1151 if (resVectorType != expected || accVectorType != expected)
1152 return op.emitOpError(
1153 "invalid accumulator/result vector shape, expected: ")
1154 << expected;
1155 }
1156 return success();
1157}
1158
1159// Find a one-sided reduction dim, i.e. a reduction dim that is present in only
1160// one of the inputs.
1161static std::optional<int64_t>
1162getOneSidedReductionDim(vector::ContractionOp *contract) {
1163 auto maps = contract->getIndexingMapsArray();
1164 AffineMap lhsMap = maps[0];
1165 AffineMap rhsMap = maps[1];
1166
1167 for (auto [dim, attr] : llvm::enumerate(contract->getIteratorTypes())) {
1168 auto iteratorType = cast<vector::IteratorTypeAttr>(attr).getValue();
1169 if (iteratorType == vector::IteratorType::reduction &&
1170 (!lhsMap.isFunctionOfDim(dim) || !rhsMap.isFunctionOfDim(dim)))
1171 return dim;
1172 }
1173
1174 return std::nullopt;
1175}
1176
1177LogicalResult ContractionOp::verify() {
1178 VectorType lhsType = getLhsType();
1179 VectorType rhsType = getRhsType();
1180 Type accType = getAccType();
1181 Type resType = getResultType();
1182
1183 if (llvm::isa<IntegerType>(lhsType.getElementType())) {
1184 if (!lhsType.getElementType().isSignlessInteger())
1185 return emitOpError("only supports signless integer types");
1186 }
1187
1188 // Verify that an indexing map was specified for each vector operand.
1189 if (getIndexingMapsArray().size() != 3)
1190 return emitOpError("expected an indexing map for each vector operand");
1191
1192 // Verify that each index map has 'numIterators' inputs, no symbols, and
1193 // that the number of map outputs equals the rank of its associated
1194 // vector operand.
1195 unsigned numIterators = getIteratorTypes().getValue().size();
1196 for (const auto &it : llvm::enumerate(getIndexingMapsArray())) {
1197 auto index = it.index();
1198 auto map = it.value();
1199 if (map.getNumSymbols() != 0)
1200 return emitOpError("expected indexing map ")
1201 << index << " to have no symbols";
1202 auto vectorType = llvm::dyn_cast<VectorType>(getOperand(index).getType());
1203 unsigned rank = vectorType ? vectorType.getShape().size() : 0;
1204 // Verify that the map has the right number of inputs, outputs, and indices.
1205 // This also correctly accounts for (..) -> () for rank-0 results.
1206 if (map.getNumDims() != numIterators)
1207 return emitOpError("expected indexing map ")
1208 << index << " to have " << numIterators << " number of inputs";
1209 if (map.getNumResults() != rank)
1210 return emitOpError("expected indexing map ")
1211 << index << " to have " << rank << " number of outputs";
1212 if (!map.isProjectedPermutation())
1213 return emitOpError("expected indexing map ")
1214 << index << " to be a projected permutation of its inputs";
1215 }
1216
1217 // TODO: For better code re-use, unify this with linalg.contract.
1218 auto dimIdx = getOneSidedReductionDim(this);
1219 if (dimIdx.has_value())
1220 return emitOpError("reduction dim at index ")
1221 << dimIdx.value() << " must appear in both LHS and RHS";
1222
1223 auto contractingDimMap = getContractingDimMap();
1224 auto batchDimMap = getBatchDimMap();
1225
1226 // Verify at least one contracting dimension pair was specified.
1227 if (contractingDimMap.empty())
1228 return emitOpError("expected at least one contracting dimension pair");
1229
1230 // Verify contracting dimension map was properly constructed.
1231 if (!verifyDimMap(lhsType, rhsType, contractingDimMap))
1232 return emitOpError("invalid contracting dimension map");
1233
1234 // Verify batch dimension map was properly constructed.
1235 if (!verifyDimMap(lhsType, rhsType, batchDimMap))
1236 return emitOpError("invalid batch dimension map");
1237
1238 // Verify 'accType' and 'resType' shape.
1239 if (failed(verifyOutputShape(*this, lhsType, rhsType, accType, resType,
1240 contractingDimMap, batchDimMap)))
1241 return failure();
1242
1243 if (!getKindAttr()) {
1244 return emitOpError("expected 'kind' attribute of type CombiningKind (e.g. "
1245 "'vector.kind<add>')");
1246 }
1247
1248 // Verify supported combining kind.
1249 auto vectorType = llvm::dyn_cast<VectorType>(resType);
1250 auto elementType = vectorType ? vectorType.getElementType() : resType;
1251 if (!isSupportedCombiningKind(getKind(), elementType))
1252 return emitOpError("unsupported contraction type");
1253
1254 // Delayed calling of IndexingMapOpInterface::verifyImpl.
1255 return cast<IndexingMapOpInterface>(this->getOperation()).verifyImpl();
1256}
1257
1258// MaskableOpInterface methods.
1259
1260/// Returns the mask type expected by this operation. Mostly used for
1261/// verification purposes. It requires the operation to be vectorized."
1262Type ContractionOp::getExpectedMaskType() {
1263 auto indexingMaps = this->getIndexingMapsArray();
1264 AffineMap lhsIdxMap = indexingMaps[0];
1265 AffineMap rhsIdxMap = indexingMaps[1];
1266 VectorType lhsType = this->getLhsType();
1267 VectorType rhsType = this->getRhsType();
1268
1269 unsigned numVecDims = lhsIdxMap.getNumDims();
1270 SmallVector<int64_t> maskShape(numVecDims, ShapedType::kDynamic);
1271 SmallVector<bool> maskShapeScalableDims(numVecDims, false);
1272
1273 // Using the information in the indexing maps, extract the size of each
1274 // dimension in the vector.contract operation from the two input operands.
1275 for (auto [dimIdx, dimSize] : llvm::enumerate(lhsType.getShape())) {
1276 maskShape[lhsIdxMap.getDimPosition(dimIdx)] = dimSize;
1277 maskShapeScalableDims[lhsIdxMap.getDimPosition(dimIdx)] =
1278 lhsType.getScalableDims()[dimIdx];
1279 }
1280 for (auto [dimIdx, dimSize] : llvm::enumerate(rhsType.getShape())) {
1281 maskShape[rhsIdxMap.getDimPosition(dimIdx)] = dimSize;
1282 maskShapeScalableDims[rhsIdxMap.getDimPosition(dimIdx)] =
1283 rhsType.getScalableDims()[dimIdx];
1284 }
1285
1286 assert(ShapedType::isStaticShape(maskShape) &&
1287 "Mask shape couldn't be computed");
1288
1289 return VectorType::get(maskShape,
1290 IntegerType::get(lhsType.getContext(), /*width=*/1),
1291 maskShapeScalableDims);
1292}
1293
1294SmallVector<StringRef> ContractionOp::getTraitAttrNames() {
1295 return SmallVector<StringRef>{getIndexingMapsAttrName(),
1296 getIteratorTypesAttrName(), getKindAttrName(),
1297 getFastmathAttrName()};
1298}
1299
1301 for (int64_t i = 0, e = map.getNumResults(); i < e; ++i)
1302 if (targetExpr == map.getResult(i))
1303 return i;
1304 return -1;
1305}
1306
1307// For every contraction `dim` for which:
1308// * the corresponding iteratory type matches `targetIteratorType`,
1309// returns a pair: <lhsIdx, rhsIdx>, where:
1310// * {lhs|rhs}Idx is the index of `dim` in the (result of) indexing map for
1311// {lhs|rhs}.
1312// If `oneSidedDim` is true, only dims indexed on exactly one of the `contract`
1313// operands are returned.
1314static std::vector<std::pair<int64_t, int64_t>>
1315getDimPairForIterTy(ContractionOp *contract, IteratorType targetIteratorType,
1316 bool oneSidedDim = false) {
1317 SmallVector<AffineMap, 4> indexingMaps(contract->getIndexingMapsArray());
1318 ArrayAttr iteratorTypes = contract->getIteratorTypes();
1319 std::vector<std::pair<int64_t, int64_t>> dimMap;
1320 for (const auto &it : llvm::enumerate(iteratorTypes)) {
1321 auto iteratorType = llvm::cast<IteratorTypeAttr>(it.value()).getValue();
1322 if (iteratorType != targetIteratorType)
1323 continue;
1324 // Search lhs/rhs map results for 'targetExpr'.
1325 auto targetExpr = getAffineDimExpr(it.index(), contract->getContext());
1326 int64_t lhsDim = getResultIndex(indexingMaps[0], targetExpr);
1327 int64_t rhsDim = getResultIndex(indexingMaps[1], targetExpr);
1328 bool isOneSidedDim = (lhsDim >= 0) != (rhsDim >= 0);
1329 bool isTwoSidedDim = lhsDim >= 0 && rhsDim >= 0;
1330 if (oneSidedDim ? isOneSidedDim : isTwoSidedDim)
1331 dimMap.emplace_back(lhsDim, rhsDim);
1332 }
1333 return dimMap;
1334}
1335
1336std::vector<std::pair<int64_t, int64_t>> ContractionOp::getContractingDimMap() {
1337 return getDimPairForIterTy(this, IteratorType::reduction);
1338}
1339
1340std::vector<std::pair<int64_t, int64_t>> ContractionOp::getBatchDimMap() {
1341 return getDimPairForIterTy(this, IteratorType::parallel);
1342}
1343
1344std::vector<std::pair<int64_t, int64_t>> ContractionOp::getFreeDimMap() {
1345 return getDimPairForIterTy(this, IteratorType::parallel,
1346 /*oneSidedDim=*/true);
1347}
1348
1349void ContractionOp::getIterationBounds(
1350 SmallVectorImpl<int64_t> &iterationBounds) {
1351 auto lhsShape = getLhsType().getShape();
1352 auto resVectorType = llvm::dyn_cast<VectorType>(getResultType());
1353 SmallVector<AffineMap, 4> indexingMaps(getIndexingMapsArray());
1354 for (const auto &it : llvm::enumerate(getIteratorTypes())) {
1355 // Search lhs/rhs map results for 'targetExpr'.
1356 auto targetExpr = getAffineDimExpr(it.index(), getContext());
1357 auto iteratorType = llvm::cast<IteratorTypeAttr>(it.value()).getValue();
1358 if (iteratorType == IteratorType::reduction) {
1359 // Get reduction dim size from lhs shape (same size in rhsShape).
1360 int64_t lhsDimIndex = getResultIndex(indexingMaps[0], targetExpr);
1361 assert(lhsDimIndex >= 0);
1362 iterationBounds.push_back(lhsShape[lhsDimIndex]);
1363 continue;
1364 }
1365 // Get parallel dimension size from result shape.
1366 int64_t resDimIndex = getResultIndex(indexingMaps[2], targetExpr);
1367 assert(resDimIndex >= 0);
1368 assert(resVectorType != nullptr);
1369 iterationBounds.push_back(resVectorType.getShape()[resDimIndex]);
1370 }
1371}
1372
1373void ContractionOp::getIterationIndexMap(
1374 std::vector<DenseMap<int64_t, int64_t>> &iterationIndexMap) {
1375 unsigned numMaps = getIndexingMapsArray().size();
1376 iterationIndexMap.resize(numMaps);
1377 for (const auto &it : llvm::enumerate(getIndexingMapsArray())) {
1378 auto index = it.index();
1379 auto map = it.value();
1380 for (unsigned i = 0, e = map.getNumResults(); i < e; ++i) {
1381 auto dim = cast<AffineDimExpr>(map.getResult(i));
1382 iterationIndexMap[index][dim.getPosition()] = i;
1383 }
1384 }
1385}
1386
1387//-----------------------------------------------------------------------------
1388// VectorUnrollOpInterface methods
1389//-----------------------------------------------------------------------------
1390std::optional<SmallVector<int64_t, 4>>
1391ContractionOp::getIterationShapeToUnroll() {
1393 getIterationBounds(shape);
1394 return shape;
1395}
1396
1397std::optional<SmallVector<int64_t>>
1398ContractionOp::getDefaultUnrollTargetShape() {
1399 SmallVector<int64_t> nativeShape(this->getIteratorTypes().size(), 4);
1400 Type lhsType = this->getLhsType().getElementType();
1401 nativeShape[nativeShape.size() - 1] = lhsType.isF16() ? 4 : 2;
1402 return nativeShape;
1403}
1404
1405/// Return a fused vector::ContractionOp which represents a patterns such as:
1406///
1407/// ```mlir
1408/// %c0 = vector.constant 0: ...
1409/// %c = vector.contract %a, %b, %c0: ...
1410/// %e = add %c, %d: ...
1411/// ```
1412///
1413/// by:
1414///
1415/// ```mlir
1416/// %e = vector.contract %a, %b, %d: ...
1417/// ```
1418///
1419/// Return null if the canonicalization does not apply.
1420// TODO: This should be a folding of Add into Contract in core but while they
1421// live in different dialects, it is not possible without unnatural
1422// dependencies.
1423template <typename AddOpType>
1424struct CanonicalizeContractAdd : public OpRewritePattern<AddOpType> {
1425 using OpRewritePattern<AddOpType>::OpRewritePattern;
1426
1427 LogicalResult matchAndRewrite(AddOpType addOp,
1428 PatternRewriter &rewriter) const override {
1429 auto canonicalize = [&](Value maybeContraction,
1430 Value otherOperand) -> vector::ContractionOp {
1431 vector::ContractionOp contractionOp =
1432 dyn_cast_or_null<vector::ContractionOp>(
1433 maybeContraction.getDefiningOp());
1434 if (!contractionOp)
1435 return vector::ContractionOp();
1436 if (auto maybeZero = dyn_cast_or_null<arith::ConstantOp>(
1437 contractionOp.getAcc().getDefiningOp())) {
1438 if (maybeZero.getValue() ==
1439 rewriter.getZeroAttr(contractionOp.getAcc().getType())) {
1440 IRMapping bvm;
1441 bvm.map(contractionOp.getAcc(), otherOperand);
1442 auto newContraction =
1443 cast<vector::ContractionOp>(rewriter.clone(*contractionOp, bvm));
1444 rewriter.replaceOp(addOp, newContraction.getResult());
1445 return newContraction;
1446 }
1447 }
1448 return vector::ContractionOp();
1449 };
1450
1451 Value a = addOp->getOperand(0), b = addOp->getOperand(1);
1452 vector::ContractionOp contract = canonicalize(a, b);
1453 contract = contract ? contract : canonicalize(b, a);
1454 return contract ? success() : failure();
1455 }
1456};
1457
1458void ContractionOp::getCanonicalizationPatterns(RewritePatternSet &results,
1459 MLIRContext *context) {
1462}
1463
1464// Returns `true` if `index` is either within [0, maxIndex) or equal to
1465// `poisonValue`.
1467 int64_t maxIndex) {
1468 return index == poisonValue || (index >= 0 && index < maxIndex);
1469}
1470
1471//===----------------------------------------------------------------------===//
1472// ExtractOp
1473//===----------------------------------------------------------------------===//
1474
1475void ExtractOp::inferResultRanges(ArrayRef<ConstantIntRanges> argRanges,
1476 SetIntRangeFn setResultRanges) {
1477 setResultRanges(getResult(), argRanges.front());
1478}
1479
1480void vector::ExtractOp::build(OpBuilder &builder, OperationState &result,
1481 Value source) {
1482 auto vectorTy = cast<VectorType>(source.getType());
1483 build(builder, result, source, SmallVector<int64_t>(vectorTy.getRank(), 0));
1484}
1485
1486void vector::ExtractOp::build(OpBuilder &builder, OperationState &result,
1487 Value source, int64_t position) {
1488 build(builder, result, source, ArrayRef<int64_t>{position});
1489}
1490
1491void vector::ExtractOp::build(OpBuilder &builder, OperationState &result,
1492 Value source, OpFoldResult position) {
1493 build(builder, result, source, ArrayRef<OpFoldResult>{position});
1494}
1495
1496void vector::ExtractOp::build(OpBuilder &builder, OperationState &result,
1497 Value source, ArrayRef<int64_t> position) {
1498 build(builder, result, source, /*dynamic_position=*/ArrayRef<Value>(),
1499 builder.getDenseI64ArrayAttr(position));
1500}
1501
1502void vector::ExtractOp::build(OpBuilder &builder, OperationState &result,
1503 Value source, ArrayRef<OpFoldResult> position) {
1504 SmallVector<int64_t> staticPos;
1505 SmallVector<Value> dynamicPos;
1506 dispatchIndexOpFoldResults(position, dynamicPos, staticPos);
1507 build(builder, result, source, dynamicPos,
1508 builder.getDenseI64ArrayAttr(staticPos));
1509}
1510
1511LogicalResult
1512ExtractOp::inferReturnTypes(MLIRContext *, std::optional<Location>,
1513 ExtractOp::Adaptor adaptor,
1514 SmallVectorImpl<Type> &inferredReturnTypes) {
1515 auto vectorType = llvm::cast<VectorType>(adaptor.getSource().getType());
1516 if (static_cast<int64_t>(adaptor.getStaticPosition().size()) ==
1517 vectorType.getRank()) {
1518 inferredReturnTypes.push_back(vectorType.getElementType());
1519 } else {
1520 auto n = std::min<size_t>(adaptor.getStaticPosition().size(),
1521 vectorType.getRank());
1522 inferredReturnTypes.push_back(VectorType::get(
1523 vectorType.getShape().drop_front(n), vectorType.getElementType(),
1524 vectorType.getScalableDims().drop_front(n)));
1525 }
1526 return success();
1527}
1528
1529LogicalResult vector::ExtractOp::verify() {
1530 if (auto resTy = dyn_cast<VectorType>(getResult().getType()))
1531 if (resTy.getRank() == 0)
1532 return emitError(
1533 "expected a scalar instead of a 0-d vector as the result type");
1534
1535 // Note: This check must come before getMixedPosition() to prevent a crash.
1536 auto dynamicMarkersCount =
1537 llvm::count_if(getStaticPosition(), ShapedType::isDynamic);
1538 if (static_cast<size_t>(dynamicMarkersCount) != getDynamicPosition().size())
1539 return emitOpError(
1540 "mismatch between dynamic and static positions (kDynamic marker but no "
1541 "corresponding dynamic position) -- this can only happen due to an "
1542 "incorrect fold/rewrite");
1543 auto position = getMixedPosition();
1544 if (position.size() > static_cast<unsigned>(getSourceVectorType().getRank()))
1545 return emitOpError(
1546 "expected position attribute of rank no greater than vector rank");
1547 for (auto [idx, pos] : llvm::enumerate(position)) {
1548 if (auto attr = dyn_cast<Attribute>(pos)) {
1549 int64_t constIdx = cast<IntegerAttr>(attr).getInt();
1551 constIdx, kPoisonIndex, getSourceVectorType().getDimSize(idx))) {
1552 return emitOpError("expected position attribute #")
1553 << (idx + 1)
1554 << " to be a non-negative integer smaller than the "
1555 "corresponding vector dimension or poison (-1)";
1556 }
1557 }
1558 }
1559 return success();
1560}
1561
1562template <typename IntType>
1564 return llvm::map_to_vector<4>(
1565 arrayAttr.getAsRange<IntegerAttr>(),
1566 [](IntegerAttr attr) { return static_cast<IntType>(attr.getInt()); });
1567}
1568
1569/// Fold the result of chains of ExtractOp in place by simply concatenating the
1570/// positions. Both static and dynamic positions are supported.
1571///
1572/// BEFORE:
1573/// ```mlir
1574/// %0 = vector.extract %v[1, 2] : vector<3x4x5xf32>
1575/// %1 = vector.extract %0[%idx, 3] : vector<5xf32>
1576/// ```
1577///
1578/// AFTER:
1579/// ```mlir
1580/// %1 = vector.extract %v[1, 2, %idx, 3] : vector<3x4x5xf32>
1581/// ```
1582static LogicalResult foldExtractOpFromExtractChain(ExtractOp extractOp) {
1583 if (!extractOp.getSource().getDefiningOp<ExtractOp>())
1584 return failure();
1585
1586 SmallVector<OpFoldResult> globalPosition = extractOp.getMixedPosition();
1587 ExtractOp currentOp = extractOp;
1588 while (ExtractOp nextOp = currentOp.getSource().getDefiningOp<ExtractOp>()) {
1589 currentOp = nextOp;
1590 SmallVector<OpFoldResult> pos = currentOp.getMixedPosition();
1591 globalPosition.insert(globalPosition.begin(), pos.begin(), pos.end());
1592 }
1593 auto [staticPos, dynPos] = decomposeMixedValues(globalPosition);
1594 Value source = currentOp.getSource();
1595 extractOp->setOperands(
1596 llvm::to_vector(llvm::concat<Value>(ValueRange(source), dynPos)));
1597 extractOp.setStaticPosition(staticPos);
1598 return success();
1599}
1600
1601namespace {
1602/// Fold an ExtractOp that is fed by a chain of InsertOps and TransposeOps.
1603/// Walk back a chain of InsertOp/TransposeOp until we hit a match.
1604/// Compose TransposeOp permutations as we walk back.
1605/// This helper class keeps an updated extraction position `extractPosition`
1606/// with extra trailing sentinels.
1607/// The sentinels encode the internal transposition status of the result vector.
1608/// As we iterate, extractPosition is permuted and updated.
1609class ExtractFromInsertTransposeChainState {
1610public:
1611 ExtractFromInsertTransposeChainState(ExtractOp e);
1612
1613 /// Iterate over producing insert and transpose ops until we find a fold.
1614 Value fold();
1615
1616private:
1617 /// Return true if the vector at position `a` is contained within the vector
1618 /// at position `b`. Under insert/extract semantics, this is the same as `a`
1619 /// is a prefix of `b`.
1620 template <typename ContainerA, typename ContainerB>
1621 bool isContainedWithin(const ContainerA &a, const ContainerB &b) {
1622 return a.size() <= b.size() &&
1623 std::equal(a.begin(), a.begin() + a.size(), b.begin());
1624 }
1625
1626 /// Return true if the vector at position `a` intersects the vector at
1627 /// position `b`. Under insert/extract semantics, this is the same as equality
1628 /// of all entries of `a` that are >=0 with the corresponding entries of b.
1629 /// Comparison is on the common prefix (i.e. zip).
1630 template <typename ContainerA, typename ContainerB>
1631 bool intersectsWhereNonNegative(const ContainerA &a, const ContainerB &b) {
1632 for (auto [elemA, elemB] : llvm::zip(a, b)) {
1633 if (elemA < 0 || elemB < 0)
1634 continue;
1635 if (elemA != elemB)
1636 return false;
1637 }
1638 return true;
1639 }
1640
1641 /// Folding is only possible in the absence of an internal permutation in the
1642 /// result vector.
1643 bool canFold() {
1644 return (sentinels == ArrayRef(extractPosition).drop_front(extractedRank));
1645 }
1646
1647 // Helper to get the next defining op of interest.
1648 void updateStateForNextIteration(Value v) {
1649 nextInsertOp = v.getDefiningOp<vector::InsertOp>();
1650 nextTransposeOp = v.getDefiningOp<vector::TransposeOp>();
1651 };
1652
1653 // Case 1. If we hit a transpose, just compose the map and iterate.
1654 // Invariant: insert + transpose do not change rank, we can always compose.
1655 LogicalResult handleTransposeOp();
1656
1657 // Case 2: the insert position matches extractPosition exactly, early return.
1658 LogicalResult handleInsertOpWithMatchingPos(Value &res);
1659
1660 /// Case 3: if the insert position is a prefix of extractPosition, extract a
1661 /// portion of the source of the insert.
1662 /// Example:
1663 /// ```
1664 /// %ins = vector.insert %source, %vest[1]: vector<3x4> into vector<2x3x4x5>
1665 /// // extractPosition == [1, 2, 3]
1666 /// %ext = vector.extract %ins[1, 0]: vector<5> from vector<3x4x5>
1667 /// // can fold to vector.extract %source[0, 3]
1668 /// %ext = vector.extract %source[3]: vector<6> from vector<5x6>
1669 /// ```
1670 /// To traverse through %source, we need to set the leading dims to 0 and
1671 /// drop the extra leading dims.
1672 /// This method updates the internal state.
1673 LogicalResult handleInsertOpWithPrefixPos(Value &res);
1674
1675 /// Try to fold in place to extract(source, extractPosition) and return the
1676 /// folded result. Return null if folding is not possible (e.g. due to an
1677 /// internal transposition in the result).
1678 Value tryToFoldExtractOpInPlace(Value source);
1679
1680 ExtractOp extractOp;
1681 int64_t vectorRank;
1682 int64_t extractedRank;
1683
1684 InsertOp nextInsertOp;
1685 TransposeOp nextTransposeOp;
1686
1687 /// Sentinel values that encode the internal permutation status of the result.
1688 /// They are set to (-1, ... , -k) at the beginning and appended to
1689 /// `extractPosition`.
1690 /// In the end, the tail of `extractPosition` must be exactly `sentinels` to
1691 /// ensure that there is no internal transposition.
1692 /// Internal transposition cannot be accounted for with a folding pattern.
1693 // TODO: We could relax the internal transposition with an extra transposition
1694 // operation in a future canonicalizer.
1695 SmallVector<int64_t> sentinels;
1696 SmallVector<int64_t> extractPosition;
1697};
1698} // namespace
1699
1700ExtractFromInsertTransposeChainState::ExtractFromInsertTransposeChainState(
1701 ExtractOp e)
1702 : extractOp(e), vectorRank(extractOp.getSourceVectorType().getRank()),
1703 extractedRank(extractOp.getNumIndices()) {
1704 assert(vectorRank >= extractedRank && "Extracted position overflow");
1705 sentinels.reserve(vectorRank - extractedRank);
1706 for (int64_t i = 0, e = vectorRank - extractedRank; i < e; ++i)
1707 sentinels.push_back(-(i + 1));
1708 extractPosition.assign(extractOp.getStaticPosition().begin(),
1709 extractOp.getStaticPosition().end());
1710 llvm::append_range(extractPosition, sentinels);
1711}
1712
1713// Case 1. If we hit a transpose, just compose the map and iterate.
1714// Invariant: insert + transpose do not change rank, we can always compose.
1715LogicalResult ExtractFromInsertTransposeChainState::handleTransposeOp() {
1716 // TODO: Canonicalization for dynamic position not implemented yet.
1717 if (extractOp.hasDynamicPosition())
1718 return failure();
1719
1720 if (!nextTransposeOp)
1721 return failure();
1722
1723 if (nextTransposeOp.getResultVectorType().getRank() == 0)
1724 return success();
1725
1727 nextTransposeOp.getPermutation(), extractOp.getContext()));
1729 return success();
1730}
1731
1732// Case 2: the insert position matches extractPosition exactly, early return.
1733LogicalResult
1734ExtractFromInsertTransposeChainState::handleInsertOpWithMatchingPos(
1735 Value &res) {
1736 // TODO: Canonicalization for dynamic position not implemented yet.
1737 if (extractOp.hasDynamicPosition() || nextInsertOp.hasDynamicPosition())
1738 return failure();
1739
1740 ArrayRef<int64_t> insertedPos = nextInsertOp.getStaticPosition();
1741 if (insertedPos != llvm::ArrayRef(extractPosition).take_front(extractedRank))
1742 return failure();
1743 // Case 2.a. early-exit fold.
1744 res = nextInsertOp.getValueToStore();
1745 // Case 2.b. if internal transposition is present, canFold will be false.
1746 return success(canFold());
1747}
1748
1749/// Case 3: if inserted position is a prefix of extractPosition,
1750/// extract a portion of the source of the insertion.
1751/// This method updates the internal state.
1752LogicalResult
1753ExtractFromInsertTransposeChainState::handleInsertOpWithPrefixPos(Value &res) {
1754 // TODO: Canonicalization for dynamic position not implemented yet.
1755 if (extractOp.hasDynamicPosition() || nextInsertOp.hasDynamicPosition())
1756 return failure();
1757
1758 ArrayRef<int64_t> insertedPos = nextInsertOp.getStaticPosition();
1759 if (!isContainedWithin(insertedPos, extractPosition))
1760 return failure();
1761 // Set leading dims to zero.
1762 std::fill_n(extractPosition.begin(), insertedPos.size(), 0);
1763 // Drop extra leading dims.
1764 extractPosition.erase(extractPosition.begin(),
1765 extractPosition.begin() + insertedPos.size());
1766 extractedRank = extractPosition.size() - sentinels.size();
1767 // Case 3.a. early-exit fold (break and delegate to post-while path).
1768 res = nextInsertOp.getValueToStore();
1769 // Case 3.b. if internal transposition is present, canFold will be false.
1770 return success();
1771}
1772
1773/// Try to fold in place to extract(source, extractPosition) and return the
1774/// folded result. Return null if folding is not possible (e.g. due to an
1775/// internal transposition in the result).
1776Value ExtractFromInsertTransposeChainState::tryToFoldExtractOpInPlace(
1777 Value source) {
1778 // TODO: Canonicalization for dynamic position not implemented yet.
1779 if (extractOp.hasDynamicPosition())
1780 return Value();
1781
1782 // If we can't fold (either internal transposition, or nothing to fold), bail.
1783 bool nothingToFold = (source == extractOp.getSource());
1784 if (nothingToFold || !canFold())
1785 return Value();
1786
1787 // Otherwise, fold by updating the op inplace and return its result.
1788 OpBuilder b(extractOp.getContext());
1789 extractOp.setStaticPosition(
1790 ArrayRef(extractPosition).take_front(extractedRank));
1791 extractOp.getSourceMutable().assign(source);
1792 return extractOp.getResult();
1793}
1794
1795/// Iterate over producing insert and transpose ops until we find a fold.
1796Value ExtractFromInsertTransposeChainState::fold() {
1797 // TODO: Canonicalization for dynamic position not implemented yet.
1798 if (extractOp.hasDynamicPosition())
1799 return Value();
1800
1801 Value valueToExtractFrom = extractOp.getSource();
1802 updateStateForNextIteration(valueToExtractFrom);
1803 while (nextInsertOp || nextTransposeOp) {
1804 // Case 1. If we hit a transpose, just compose the map and iterate.
1805 // Invariant: insert + transpose do not change rank, we can always compose.
1806 if (succeeded(handleTransposeOp())) {
1807 valueToExtractFrom = nextTransposeOp.getVector();
1808 updateStateForNextIteration(valueToExtractFrom);
1809 continue;
1810 }
1811
1812 Value result;
1813 // Case 2: the position match exactly.
1814 if (succeeded(handleInsertOpWithMatchingPos(result)))
1815 return result;
1816
1817 // Case 3: if the inserted position is a prefix of extractPosition, we can
1818 // just extract a portion of the source of the insert.
1819 if (succeeded(handleInsertOpWithPrefixPos(result)))
1820 return tryToFoldExtractOpInPlace(result);
1821
1822 // Case 4: extractPositionRef intersects insertedPosRef on non-sentinel
1823 // values. This is a more difficult case and we bail.
1824 ArrayRef<int64_t> insertedPos = nextInsertOp.getStaticPosition();
1825 if (isContainedWithin(extractPosition, insertedPos) ||
1826 intersectsWhereNonNegative(extractPosition, insertedPos))
1827 return Value();
1828
1829 // Case 5: No intersection, we forward the extract to insertOp.dest().
1830 valueToExtractFrom = nextInsertOp.getDest();
1831 updateStateForNextIteration(valueToExtractFrom);
1832 }
1833 // If after all this we can fold, go for it.
1834 return tryToFoldExtractOpInPlace(valueToExtractFrom);
1835}
1836
1837/// Returns true if the operation has a 0-D vector type operand or result.
1839 auto hasZeroDimVectorType = [](Type type) -> bool {
1840 auto vecType = dyn_cast<VectorType>(type);
1841 return vecType && vecType.getRank() == 0;
1842 };
1843
1844 return llvm::any_of(op->getOperandTypes(), hasZeroDimVectorType) ||
1845 llvm::any_of(op->getResultTypes(), hasZeroDimVectorType);
1846}
1847
1848/// All BroadcastOps, as well as ShapeCastOps that only prepend 1s, are
1849/// considered to be 'broadcastlike'.
1850static bool isBroadcastLike(Operation *op) {
1851 if (isa<BroadcastOp>(op))
1852 return true;
1853
1854 auto shapeCast = dyn_cast<ShapeCastOp>(op);
1855 if (!shapeCast)
1856 return false;
1857
1858 // Check that shape_cast **only** prepends 1s, like (2,3) -> (1,1,2,3).
1859 // Checking that the destination shape has a prefix of 1s is not sufficient,
1860 // for example (2,3) -> (1,3,2) is not broadcastlike. A sufficient condition
1861 // is that the source shape is a suffix of the destination shape.
1862 VectorType srcType = shapeCast.getSourceVectorType();
1863 ArrayRef<int64_t> srcShape = srcType.getShape();
1864 uint64_t srcRank = srcType.getRank();
1865 ArrayRef<int64_t> dstShape = shapeCast.getType().getShape();
1866 return dstShape.size() >= srcRank && dstShape.take_back(srcRank) == srcShape;
1867}
1868
1869/// Fold extract(broadcast(X)) to either extract(X) or just X.
1870///
1871/// Example:
1872///
1873/// broadcast extract [1][2]
1874/// (3, 4) --------> (2, 3, 4) ----------------> (4)
1875///
1876/// becomes
1877/// extract [1]
1878/// (3,4) -------------------------------------> (4)
1879///
1880///
1881/// The variable names used in this implementation correspond to the above
1882/// shapes as,
1883///
1884/// - (3, 4) is `input` shape.
1885/// - (2, 3, 4) is `broadcast` shape.
1886/// - (4) is `extract` shape.
1887///
1888/// This folding is possible when the suffix of `input` shape is the same as
1889/// `extract` shape.
1890static Value foldExtractFromBroadcast(ExtractOp extractOp) {
1891
1892 Operation *defOp = extractOp.getSource().getDefiningOp();
1893 if (!defOp || !isBroadcastLike(defOp))
1894 return Value();
1895
1896 Value input = defOp->getOperand(0);
1897
1898 // Replace extract(broadcast(X)) with X
1899 if (extractOp.getType() == input.getType())
1900 return input;
1901
1902 // Get required types and ranks in the chain
1903 // input -> broadcast -> extract
1904 // (scalars are treated as rank-0).
1905 auto inputType = llvm::dyn_cast<VectorType>(input.getType());
1906 auto extractType = llvm::dyn_cast<VectorType>(extractOp.getType());
1907 unsigned inputRank = inputType ? inputType.getRank() : 0;
1908 unsigned broadcastRank = extractOp.getSourceVectorType().getRank();
1909 unsigned extractRank = extractType ? extractType.getRank() : 0;
1910
1911 // Cannot do without the broadcast if overall the rank increases.
1912 if (extractRank > inputRank)
1913 return Value();
1914
1915 // The above condition guarantees that input is a vector.
1916 assert(inputType && "input must be a vector type because of previous checks");
1917 ArrayRef<int64_t> inputShape = inputType.getShape();
1918
1919 // In the case where there is a broadcast dimension in the suffix, it is not
1920 // possible to replace extract(broadcast(X)) with extract(X). Example:
1921 //
1922 // broadcast extract
1923 // (1) --------> (3,4) ------> (4)
1924 if (extractType &&
1925 extractType.getShape() != inputShape.take_back(extractRank))
1926 return Value();
1927
1928 // Replace extract(broadcast(X)) with extract(X).
1929 // First, determine the new extraction position.
1930 unsigned deltaOverall = inputRank - extractRank;
1931 unsigned deltaBroadcast = broadcastRank - inputRank;
1932 SmallVector<OpFoldResult> oldPositions = extractOp.getMixedPosition();
1933 SmallVector<OpFoldResult> newPositions(deltaOverall);
1934 IntegerAttr zero = OpBuilder(extractOp.getContext()).getIndexAttr(0);
1935 for (auto [i, size] : llvm::enumerate(inputShape.take_front(deltaOverall))) {
1936 newPositions[i] = size == 1 ? zero : oldPositions[i + deltaBroadcast];
1937 }
1938 auto [staticPos, dynPos] = decomposeMixedValues(newPositions);
1939 extractOp->setOperands(
1940 llvm::to_vector(llvm::concat<Value>(ValueRange(input), dynPos)));
1941 extractOp.setStaticPosition(staticPos);
1942 return extractOp.getResult();
1943}
1944
1945/// Fold extractOp coming from ShuffleOp.
1946///
1947/// Example:
1948///
1949/// %shuffle = vector.shuffle %a, %b [0, 8, 7, 15]
1950/// : vector<8xf32>, vector<8xf32>
1951/// %extract = vector.extract %shuffle[3] : f32 from vector<4xf32>
1952/// ->
1953/// %extract = vector.extract %b[7] : f32 from vector<8xf32>
1954///
1955static Value foldExtractFromShuffle(ExtractOp extractOp) {
1956 // Dynamic positions are not folded as the resulting code would be more
1957 // complex than the input code.
1958 if (extractOp.hasDynamicPosition())
1959 return Value();
1960
1961 auto shuffleOp = extractOp.getSource().getDefiningOp<ShuffleOp>();
1962 if (!shuffleOp)
1963 return Value();
1964
1965 // TODO: 0-D or multi-dimensional vectors not supported yet.
1966 if (shuffleOp.getResultVectorType().getRank() != 1)
1967 return Value();
1968
1969 int64_t inputVecSize = shuffleOp.getV1().getType().getShape()[0];
1970 auto shuffleMask = shuffleOp.getMask();
1971 int64_t extractIdx = extractOp.getStaticPosition()[0];
1972 int64_t shuffleIdx = shuffleMask[extractIdx];
1973
1974 // Find the shuffled vector to extract from based on the shuffle index.
1975 if (shuffleIdx < inputVecSize) {
1976 extractOp.setOperand(0, shuffleOp.getV1());
1977 extractOp.setStaticPosition({shuffleIdx});
1978 } else {
1979 extractOp.setOperand(0, shuffleOp.getV2());
1980 extractOp.setStaticPosition({shuffleIdx - inputVecSize});
1981 }
1982
1983 return extractOp.getResult();
1984}
1985
1986// Fold extractOp with source coming from ShapeCast op.
1987static Value foldExtractFromShapeCast(ExtractOp extractOp) {
1988 // TODO: Canonicalization for dynamic position not implemented yet.
1989 if (extractOp.hasDynamicPosition())
1990 return Value();
1991
1992 auto shapeCastOp = extractOp.getSource().getDefiningOp<vector::ShapeCastOp>();
1993 if (!shapeCastOp)
1994 return Value();
1995
1996 // Get the nth dimension size starting from lowest dimension.
1997 auto getDimReverse = [](VectorType type, int64_t n) {
1998 return type.getShape().take_back(n + 1).front();
1999 };
2000 int64_t destinationRank =
2001 llvm::isa<VectorType>(extractOp.getType())
2002 ? llvm::cast<VectorType>(extractOp.getType()).getRank()
2003 : 0;
2004 if (destinationRank > shapeCastOp.getSourceVectorType().getRank())
2005 return Value();
2006 if (destinationRank > 0) {
2007 auto destinationType =
2008 llvm::cast<VectorType>(extractOp.getResult().getType());
2009 for (int64_t i = 0; i < destinationRank; i++) {
2010 // The lowest dimension of the destination must match the lowest
2011 // dimension of the shapecast op source.
2012 // TODO: This case could be support in a canonicalization pattern.
2013 if (getDimReverse(shapeCastOp.getSourceVectorType(), i) !=
2014 getDimReverse(destinationType, i))
2015 return Value();
2016 }
2017 }
2018 // Extract the strides associated with the extract op vector source. Then use
2019 // this to calculate a linearized position for the extract.
2020 SmallVector<int64_t> extractedPos(extractOp.getStaticPosition());
2021 std::reverse(extractedPos.begin(), extractedPos.end());
2023 int64_t stride = 1;
2024 for (int64_t i = 0, e = extractedPos.size(); i < e; i++) {
2025 strides.push_back(stride);
2026 stride *=
2027 getDimReverse(extractOp.getSourceVectorType(), i + destinationRank);
2028 }
2029
2030 int64_t position = linearize(extractedPos, strides);
2031 // Then extract the strides associated to the shapeCast op vector source and
2032 // delinearize the position using those strides.
2033 SmallVector<int64_t, 4> newStrides;
2034 int64_t numDimension =
2035 shapeCastOp.getSourceVectorType().getRank() - destinationRank;
2036 stride = 1;
2037 for (int64_t i = 0; i < numDimension; i++) {
2038 newStrides.push_back(stride);
2039 stride *=
2040 getDimReverse(shapeCastOp.getSourceVectorType(), i + destinationRank);
2041 }
2042 std::reverse(newStrides.begin(), newStrides.end());
2043 SmallVector<int64_t, 4> newPosition = delinearize(position, newStrides);
2044 // OpBuilder is only used as a helper to build an I64ArrayAttr.
2045 OpBuilder b(extractOp.getContext());
2046 extractOp.setStaticPosition(newPosition);
2047 extractOp.setOperand(0, shapeCastOp.getSource());
2048 return extractOp.getResult();
2049}
2050
2051/// Fold an ExtractOp from ExtractStridedSliceOp.
2052static Value foldExtractFromExtractStrided(ExtractOp extractOp) {
2053 // TODO: Canonicalization for dynamic position not implemented yet.
2054 if (extractOp.hasDynamicPosition())
2055 return Value();
2056
2057 auto extractStridedSliceOp =
2058 extractOp.getSource().getDefiningOp<vector::ExtractStridedSliceOp>();
2059 if (!extractStridedSliceOp)
2060 return Value();
2061
2062 // 0-D vectors not supported.
2063 assert(!hasZeroDimVectors(extractOp) && "0-D vectors not supported");
2064 if (hasZeroDimVectors(extractStridedSliceOp))
2065 return Value();
2066
2067 // Return if 'extractStridedSliceOp' has non-unit strides.
2068 if (extractStridedSliceOp.hasNonUnitStrides())
2069 return Value();
2070
2071 // Trim offsets for dimensions fully extracted.
2072 auto sliceOffsets =
2073 extractVector<int64_t>(extractStridedSliceOp.getOffsets());
2074 while (!sliceOffsets.empty()) {
2075 size_t lastOffset = sliceOffsets.size() - 1;
2076 if (sliceOffsets.back() != 0 ||
2077 extractStridedSliceOp.getType().getDimSize(lastOffset) !=
2078 extractStridedSliceOp.getSourceVectorType().getDimSize(lastOffset))
2079 break;
2080 sliceOffsets.pop_back();
2081 }
2082 unsigned destinationRank = 0;
2083 if (auto vecType = llvm::dyn_cast<VectorType>(extractOp.getType()))
2084 destinationRank = vecType.getRank();
2085 // The dimensions of the result need to be untouched by the
2086 // extractStridedSlice op.
2087 if (destinationRank > extractStridedSliceOp.getSourceVectorType().getRank() -
2088 sliceOffsets.size())
2089 return Value();
2090
2091 SmallVector<int64_t> extractedPos(extractOp.getStaticPosition());
2092 assert(extractedPos.size() >= sliceOffsets.size());
2093 for (size_t i = 0, e = sliceOffsets.size(); i < e; i++)
2094 extractedPos[i] = extractedPos[i] + sliceOffsets[i];
2095 extractOp.getSourceMutable().assign(extractStridedSliceOp.getSource());
2096
2097 // OpBuilder is only used as a helper to build an I64ArrayAttr.
2098 OpBuilder b(extractOp.getContext());
2099 extractOp.setStaticPosition(extractedPos);
2100 return extractOp.getResult();
2101}
2102
2103/// Fold extract_op fed from a chain of insertStridedSlice ops.
2104static Value foldExtractStridedOpFromInsertChain(ExtractOp extractOp) {
2105 // TODO: Canonicalization for dynamic position not implemented yet.
2106 if (extractOp.hasDynamicPosition())
2107 return Value();
2108
2109 int64_t destinationRank =
2110 llvm::isa<VectorType>(extractOp.getType())
2111 ? llvm::cast<VectorType>(extractOp.getType()).getRank()
2112 : 0;
2113 auto insertOp = extractOp.getSource().getDefiningOp<InsertStridedSliceOp>();
2114 if (!insertOp)
2115 return Value();
2116
2117 // 0-D vectors not supported.
2118 assert(!hasZeroDimVectors(extractOp) && "0-D vectors not supported");
2119 if (hasZeroDimVectors(insertOp))
2120 return Value();
2121
2122 while (insertOp) {
2123 int64_t insertRankDiff = insertOp.getDestVectorType().getRank() -
2124 insertOp.getSourceVectorType().getRank();
2125 if (destinationRank > insertOp.getSourceVectorType().getRank())
2126 return Value();
2127 auto insertOffsets = extractVector<int64_t>(insertOp.getOffsets());
2128 ArrayRef<int64_t> extractOffsets = extractOp.getStaticPosition();
2129
2130 if (llvm::any_of(insertOp.getStrides(), [](Attribute attr) {
2131 return llvm::cast<IntegerAttr>(attr).getInt() != 1;
2132 }))
2133 return Value();
2134 bool disjoint = false;
2135 SmallVector<int64_t, 4> offsetDiffs;
2136 for (unsigned dim = 0, e = extractOffsets.size(); dim < e; ++dim) {
2137 int64_t start = insertOffsets[dim];
2138 int64_t size =
2139 (dim < insertRankDiff)
2140 ? 1
2141 : insertOp.getSourceVectorType().getDimSize(dim - insertRankDiff);
2142 int64_t end = start + size;
2143 int64_t offset = extractOffsets[dim];
2144 // Check if the start of the extract offset is in the interval inserted.
2145 if (start <= offset && offset < end) {
2146 if (dim >= insertRankDiff)
2147 offsetDiffs.push_back(offset - start);
2148 continue;
2149 }
2150 disjoint = true;
2151 break;
2152 }
2153 // The extract element chunk overlap with the vector inserted.
2154 if (!disjoint) {
2155 // If any of the inner dimensions are only partially inserted we have a
2156 // partial overlap.
2157 int64_t srcRankDiff =
2158 insertOp.getSourceVectorType().getRank() - destinationRank;
2159 for (int64_t i = 0; i < destinationRank; i++) {
2160 if (insertOp.getSourceVectorType().getDimSize(i + srcRankDiff) !=
2161 insertOp.getDestVectorType().getDimSize(i + srcRankDiff +
2162 insertRankDiff))
2163 return Value();
2164 }
2165 extractOp.getSourceMutable().assign(insertOp.getValueToStore());
2166 // OpBuilder is only used as a helper to build an I64ArrayAttr.
2167 OpBuilder b(extractOp.getContext());
2168 extractOp.setStaticPosition(offsetDiffs);
2169 return extractOp.getResult();
2170 }
2171 // If the chunk extracted is disjoint from the chunk inserted, keep
2172 // looking in the insert chain.
2173 insertOp = insertOp.getDest().getDefiningOp<InsertStridedSliceOp>();
2174 }
2175 return Value();
2176}
2177
2178/// Try to fold the extraction of a scalar from a vector defined by
2179/// vector.from_elements. E.g.:
2180///
2181/// %0 = vector.from_elements %a, %b : vector<2xf32>
2182/// %1 = vector.extract %0[0] : f32 from vector<2xf32>
2183/// ==> fold to %a
2184static Value foldScalarExtractFromFromElements(ExtractOp extractOp) {
2185 // Dynamic extractions cannot be folded.
2186 if (extractOp.hasDynamicPosition())
2187 return {};
2188
2189 // Look for extract(from_elements).
2190 auto fromElementsOp = extractOp.getSource().getDefiningOp<FromElementsOp>();
2191 if (!fromElementsOp)
2192 return {};
2193
2194 // Scalable vectors are not supported.
2195 auto vecType = llvm::cast<VectorType>(fromElementsOp.getType());
2196 if (vecType.isScalable())
2197 return {};
2198
2199 // Only extractions of scalars are supported.
2200 int64_t rank = vecType.getRank();
2201 ArrayRef<int64_t> indices = extractOp.getStaticPosition();
2202 if (extractOp.getType() != vecType.getElementType())
2203 return {};
2204 assert(static_cast<int64_t>(indices.size()) == rank &&
2205 "unexpected number of indices");
2206
2207 // Compute flattened/linearized index and fold to operand.
2208 int flatIndex = 0;
2209 int stride = 1;
2210 for (int i = rank - 1; i >= 0; --i) {
2211 flatIndex += indices[i] * stride;
2212 stride *= vecType.getDimSize(i);
2213 }
2214 return fromElementsOp.getElements()[flatIndex];
2215}
2216
2217/// If the dynamic indices of `extractOp` or `insertOp` are in fact constants,
2218/// then fold it.
2219template <typename OpType, typename AdaptorType>
2220static Value extractInsertFoldConstantOp(OpType op, AdaptorType adaptor,
2221 SmallVectorImpl<Value> &operands) {
2222 std::vector<int64_t> staticPosition = op.getStaticPosition().vec();
2223 OperandRange dynamicPosition = op.getDynamicPosition();
2224 ArrayRef<Attribute> dynamicPositionAttr = adaptor.getDynamicPosition();
2226 if constexpr (std::is_same_v<OpType, ExtractOp>)
2227 vectorShape = op.getSourceVectorType().getShape();
2228 else
2229 vectorShape = op.getDestVectorType().getShape();
2230
2231 // If the dynamic operands is empty, it is returned directly.
2232 if (!dynamicPosition.size())
2233 return {};
2234
2235 // `index` is used to iterate over the `dynamicPosition`.
2236 unsigned index = 0;
2237
2238 // `opChange` is a flag. If it is true, it means to update `op` in place.
2239 bool opChange = false;
2240 for (unsigned i = 0, e = staticPosition.size(); i < e; ++i) {
2241 if (ShapedType::isStatic(staticPosition[i]))
2242 continue;
2243 Attribute positionAttr = dynamicPositionAttr[index];
2244 Value position = dynamicPosition[index++];
2245 if (auto attr = mlir::dyn_cast_if_present<IntegerAttr>(positionAttr)) {
2246 int64_t value = attr.getInt();
2247 // Do not fold if the value is out of bounds (-1 signifies a poison
2248 // value rather than OOB index).
2249 if (value >= -1 && value < vectorShape[i]) {
2250 staticPosition[i] = attr.getInt();
2251 opChange = true;
2252 continue;
2253 }
2254 }
2255 operands.push_back(position);
2256 }
2257
2258 if (opChange) {
2259 op.setStaticPosition(staticPosition);
2260 op.getOperation()->setOperands(operands);
2261 // Return the original result to indicate an in-place folding happened.
2262 return op.getResult();
2263 }
2264 return {};
2265}
2266
2267/// Fold an insert or extract operation into an poison value when a poison index
2268/// is found at any dimension of the static position.
2270 ArrayRef<int64_t> staticPos,
2271 int64_t poisonVal) {
2272 if (!is_contained(staticPos, poisonVal))
2273 return {};
2274
2275 return ub::PoisonAttr::get(context);
2276}
2277
2278/// Fold a vector extract from is a poison source.
2280 if (matchPattern(srcAttr, ub::m_Poison()))
2281 return srcAttr;
2282
2283 return {};
2284}
2285
2286/// Fold a vector extract extracting from a DenseElementsAttr.
2288 Attribute srcAttr) {
2289 auto denseAttr = dyn_cast_if_present<DenseElementsAttr>(srcAttr);
2290 if (!denseAttr) {
2291 return {};
2292 }
2293
2294 if (denseAttr.isSplat()) {
2295 Attribute newAttr = denseAttr.getSplatValue<Attribute>();
2296 if (auto vecDstType = dyn_cast<VectorType>(extractOp.getType()))
2297 newAttr = DenseElementsAttr::get(vecDstType, newAttr);
2298 return newAttr;
2299 }
2300
2301 auto vecTy = cast<VectorType>(extractOp.getSourceVectorType());
2302 if (vecTy.isScalable())
2303 return {};
2304
2305 if (extractOp.hasDynamicPosition()) {
2306 return {};
2307 }
2308
2309 // Materializing subsets of a large constant array can generally lead to
2310 // explosion in IR size because of different combination of subsets that
2311 // can exist. However, vector.extract is a restricted form of subset
2312 // extract where you can only extract non-overlapping (or the same) subset for
2313 // a given rank of the subset. Because of this property, the IR size can only
2314 // increase at most by `rank * size(array)` from a single constant array being
2315 // extracted by multiple extracts.
2316
2317 // Calculate the linearized position of the continuous chunk of elements to
2318 // extract.
2319 SmallVector<int64_t> completePositions(vecTy.getRank(), 0);
2320 copy(extractOp.getStaticPosition(), completePositions.begin());
2321 int64_t startPos =
2322 linearize(completePositions, computeStrides(vecTy.getShape()));
2323 auto denseValuesBegin = denseAttr.value_begin<TypedAttr>() + startPos;
2324
2325 TypedAttr newAttr;
2326 if (auto resVecTy = dyn_cast<VectorType>(extractOp.getType())) {
2327 SmallVector<Attribute> elementValues(
2328 denseValuesBegin, denseValuesBegin + resVecTy.getNumElements());
2329 newAttr = DenseElementsAttr::get(resVecTy, elementValues);
2330 } else {
2331 newAttr = *denseValuesBegin;
2332 }
2333
2334 return newAttr;
2335}
2336
2337OpFoldResult ExtractOp::fold(FoldAdaptor adaptor) {
2338 // Fold "vector.extract %v[] : vector<2x2xf32> from vector<2x2xf32>" to %v.
2339 // Note: Do not fold "vector.extract %v[] : f32 from vector<f32>" (type
2340 // mismatch).
2341 if (getNumIndices() == 0 && getSource().getType() == getResult().getType())
2342 return getSource();
2343 if (auto res = foldPoisonSrcExtractOp(adaptor.getSource()))
2344 return res;
2345 // Fold `arith.constant` indices into the `vector.extract` operation.
2346 // Do not stop here as this fold may enable subsequent folds that require
2347 // constant indices.
2348 SmallVector<Value> operands = {getSource()};
2349 auto inplaceFolded = extractInsertFoldConstantOp(*this, adaptor, operands);
2350
2351 if (auto res = foldPoisonIndexInsertExtractOp(
2352 getContext(), adaptor.getStaticPosition(), kPoisonIndex))
2353 return res;
2354 if (auto res = foldDenseElementsAttrSrcExtractOp(*this, adaptor.getSource()))
2355 return res;
2356 if (succeeded(foldExtractOpFromExtractChain(*this)))
2357 return getResult();
2358 if (auto res = ExtractFromInsertTransposeChainState(*this).fold())
2359 return res;
2360 if (auto res = foldExtractFromBroadcast(*this))
2361 return res;
2362 if (auto res = foldExtractFromShuffle(*this))
2363 return res;
2364 if (auto res = foldExtractFromShapeCast(*this))
2365 return res;
2366 if (auto val = foldExtractFromExtractStrided(*this))
2367 return val;
2368 if (auto val = foldExtractStridedOpFromInsertChain(*this))
2369 return val;
2370 if (auto val = foldScalarExtractFromFromElements(*this))
2371 return val;
2372
2373 return inplaceFolded;
2374}
2375
2376namespace {
2377
2378// Pattern to rewrite a ExtractOp(Broadcast) -> Broadcast.
2379class ExtractOpFromBroadcast final : public OpRewritePattern<ExtractOp> {
2380public:
2381 using Base::Base;
2382
2383 LogicalResult matchAndRewrite(ExtractOp extractOp,
2384 PatternRewriter &rewriter) const override {
2385
2386 Operation *defOp = extractOp.getSource().getDefiningOp();
2387 VectorType outType = dyn_cast<VectorType>(extractOp.getType());
2388 if (!defOp || !isBroadcastLike(defOp) || !outType)
2389 return failure();
2390
2391 Value source = defOp->getOperand(0);
2392 if (isBroadcastableTo(source.getType(), outType) !=
2393 BroadcastableToResult::Success)
2394 return failure();
2395
2396 rewriter.replaceOpWithNewOp<BroadcastOp>(extractOp, outType, source);
2397 return success();
2398 }
2399};
2400
2401// Pattern to rewrite a ExtractOp(CreateMask) -> CreateMask.
2402class ExtractOpFromCreateMask final : public OpRewritePattern<ExtractOp> {
2403public:
2404 using Base::Base;
2405
2406 LogicalResult matchAndRewrite(ExtractOp extractOp,
2407 PatternRewriter &rewriter) const override {
2408 auto createMaskOp =
2409 extractOp.getSource().getDefiningOp<vector::CreateMaskOp>();
2410 if (!createMaskOp)
2411 return failure();
2412
2413 VectorType extractedMaskType =
2414 llvm::dyn_cast<VectorType>(extractOp.getResult().getType());
2415
2416 if (!extractedMaskType)
2417 return failure();
2418
2419 auto maskOperands = createMaskOp.getOperands();
2420 ArrayRef<int64_t> extractOpPos = extractOp.getStaticPosition();
2421 VectorType maskType = createMaskOp.getVectorType();
2422
2423 bool containsUnknownDims = false;
2424 bool allFalse = getMaskFormat(createMaskOp) == MaskFormat::AllFalse;
2425
2426 for (size_t dimIdx = 0; !allFalse && dimIdx < extractOpPos.size();
2427 dimIdx++) {
2428 int64_t pos = extractOpPos[dimIdx];
2429 Value operand = maskOperands[dimIdx];
2430 auto constantOp = operand.getDefiningOp<arith::ConstantOp>();
2431 if (!constantOp) {
2432 // Bounds of this dim unknown.
2433 containsUnknownDims = true;
2434 continue;
2435 }
2436
2437 int64_t createMaskBound =
2438 llvm::cast<IntegerAttr>(constantOp.getValue()).getInt();
2439
2440 if (pos != ShapedType::kDynamic) {
2441 // If any position is outside the range from the `create_mask`, then the
2442 // extracted mask will be all-false.
2443 allFalse |= pos >= createMaskBound;
2444 } else if (createMaskBound < maskType.getDimSize(dimIdx)) {
2445 // This dim is not all-true and since this is a dynamic index we don't
2446 // know if the extraction is within the true or false region.
2447 // Note: Zero dims have already handled via getMaskFormat().
2448 containsUnknownDims = true;
2449 }
2450 }
2451
2452 if (allFalse) {
2453 rewriter.replaceOpWithNewOp<arith::ConstantOp>(
2454 extractOp, DenseElementsAttr::get(extractedMaskType, false));
2455 } else if (!containsUnknownDims) {
2456 rewriter.replaceOpWithNewOp<vector::CreateMaskOp>(
2457 extractOp, extractedMaskType,
2458 maskOperands.drop_front(extractOpPos.size()));
2459 } else {
2460 return failure();
2461 }
2462 return success();
2463 }
2464};
2465
2466// Pattern to rewrite a ExtractOp(ConstantMask) -> ConstantMask.
2467class ExtractOpFromConstantMask final : public OpRewritePattern<ExtractOp> {
2468public:
2469 using Base::Base;
2470
2471 LogicalResult matchAndRewrite(ExtractOp extractOp,
2472 PatternRewriter &rewriter) const override {
2473 auto constantMaskOp =
2474 extractOp.getSource().getDefiningOp<vector::ConstantMaskOp>();
2475 if (!constantMaskOp)
2476 return failure();
2477
2478 Type resultType = extractOp.getResult().getType();
2479 auto extractedMaskType = dyn_cast<VectorType>(resultType);
2480
2481 ArrayRef<int64_t> extractOpPos = extractOp.getStaticPosition();
2482 ArrayRef<int64_t> maskDimSizes = constantMaskOp.getMaskDimSizes();
2483
2484 VectorType maskType = constantMaskOp.getVectorType();
2485
2486 // Check if any extracted position is outside the mask bounds.
2487 for (size_t dimIdx = 0; dimIdx < extractOpPos.size(); dimIdx++) {
2488 int64_t pos = extractOpPos[dimIdx];
2489 if (pos == ShapedType::kDynamic) {
2490 // If the dim is all-true, a dynamic index is fine — any position
2491 // is within the masked region.
2492 if (maskDimSizes[dimIdx] == maskType.getDimSize(dimIdx))
2493 continue;
2494 // Otherwise we don't know if the position is inside or outside of
2495 // the masked area, so bail out.
2496 return failure();
2497 }
2498
2499 // If the position is statically outside of the masked area, the result
2500 // will be all-false.
2501 if (pos >= maskDimSizes[dimIdx]) {
2502 if (extractedMaskType) {
2503 rewriter.replaceOpWithNewOp<arith::ConstantOp>(
2504 extractOp, DenseElementsAttr::get(extractedMaskType, false));
2505 } else {
2506 rewriter.replaceOpWithNewOp<arith::ConstantOp>(
2507 extractOp, rewriter.getIntegerAttr(resultType, false));
2508 }
2509 return success();
2510 }
2511 }
2512
2513 // All positions are within the mask bounds.
2514 if (extractedMaskType) {
2515 // Vector result: the result is a constant_mask with the remaining
2516 // dimensions.
2517 rewriter.replaceOpWithNewOp<vector::ConstantMaskOp>(
2518 extractOp, extractedMaskType,
2519 maskDimSizes.drop_front(extractOpPos.size()));
2520 } else {
2521 // Scalar result: all positions are within the masked region, so the
2522 // result is true.
2523 rewriter.replaceOpWithNewOp<arith::ConstantOp>(
2524 extractOp, rewriter.getIntegerAttr(resultType, true));
2525 }
2526 return success();
2527 }
2528};
2529
2530// Folds extract(shape_cast(..)) into shape_cast when the total element count
2531// does not change.
2532LogicalResult foldExtractFromShapeCastToShapeCast(ExtractOp extractOp,
2533 PatternRewriter &rewriter) {
2534 auto castOp = extractOp.getSource().getDefiningOp<ShapeCastOp>();
2535 if (!castOp)
2536 return failure();
2537
2538 VectorType sourceType = castOp.getSourceVectorType();
2539 auto targetType = dyn_cast<VectorType>(extractOp.getResult().getType());
2540 if (!targetType)
2541 return failure();
2542
2543 if (sourceType.getNumElements() != targetType.getNumElements())
2544 return failure();
2545
2546 rewriter.replaceOpWithNewOp<vector::ShapeCastOp>(extractOp, targetType,
2547 castOp.getSource());
2548 return success();
2549}
2550
2551/// Try to canonicalize the extraction of a subvector from a vector defined by
2552/// vector.from_elements. E.g.:
2553///
2554/// %0 = vector.from_elements %a, %b, %a, %a : vector<2x2xf32>
2555/// %1 = vector.extract %0[0] : vector<2xf32> from vector<2x2xf32>
2556/// ==> canonicalize to vector.from_elements %a, %b : vector<2xf32>
2557LogicalResult foldExtractFromFromElements(ExtractOp extractOp,
2558 PatternRewriter &rewriter) {
2559 // Dynamic positions are not supported.
2560 if (extractOp.hasDynamicPosition())
2561 return failure();
2562
2563 // Scalar extracts are handled by the folder.
2564 auto resultType = dyn_cast<VectorType>(extractOp.getType());
2565 if (!resultType)
2566 return failure();
2567
2568 // Look for extracts from a from_elements op.
2569 auto fromElementsOp = extractOp.getSource().getDefiningOp<FromElementsOp>();
2570 if (!fromElementsOp)
2571 return failure();
2572 VectorType inputType = fromElementsOp.getType();
2573
2574 // Scalable vectors are not supported.
2575 if (resultType.isScalable() || inputType.isScalable())
2576 return failure();
2577
2578 // Compute the position of first extracted element and flatten/linearize the
2579 // position.
2580 SmallVector<int64_t> firstElementPos =
2581 llvm::to_vector(extractOp.getStaticPosition());
2582 firstElementPos.append(/*NumInputs=*/resultType.getRank(), /*Elt=*/0);
2583 int flatIndex = 0;
2584 int stride = 1;
2585 for (int64_t i = inputType.getRank() - 1; i >= 0; --i) {
2586 flatIndex += firstElementPos[i] * stride;
2587 stride *= inputType.getDimSize(i);
2588 }
2589
2590 // Replace the op with a smaller from_elements op.
2591 rewriter.replaceOpWithNewOp<FromElementsOp>(
2592 extractOp, resultType,
2593 fromElementsOp.getElements().slice(flatIndex,
2594 resultType.getNumElements()));
2595 return success();
2596}
2597
2598/// Replace `vector.extract` with `vector.shape_cast`.
2599///
2600/// BEFORE:
2601/// %0 = vector.extract %arg0[0] : vector<4xf32> from vector<1x4xf32>
2602/// AFTER:
2603/// %0 = vector.shape_cast %arg0 : vector<1x4xf32> to vector<4xf32>
2604///
2605/// The canonical form of vector operations that reshape vectors is shape_cast.
2606struct ExtractToShapeCast final : OpRewritePattern<vector::ExtractOp> {
2607 using Base::Base;
2608 LogicalResult matchAndRewrite(vector::ExtractOp extractOp,
2609 PatternRewriter &rewriter) const override {
2610 VectorType sourceType = extractOp.getSourceVectorType();
2611 VectorType outType = dyn_cast<VectorType>(extractOp.getType());
2612 if (!outType)
2613 return failure();
2614
2615 if (sourceType.getNumElements() != outType.getNumElements())
2616 return rewriter.notifyMatchFailure(
2617 extractOp, "extract to vector with fewer elements");
2618
2619 // Negative values in `position` means that the extacted value is poison.
2620 // There is a vector.extract folder for this.
2621 if (llvm::any_of(extractOp.getMixedPosition(),
2622 [](OpFoldResult v) { return !isConstantIntValue(v, 0); }))
2623 return rewriter.notifyMatchFailure(extractOp,
2624 "leaving for extract poison folder");
2625
2626 rewriter.replaceOpWithNewOp<vector::ShapeCastOp>(extractOp, outType,
2627 extractOp.getSource());
2628
2629 return success();
2630 }
2631};
2632
2633/// Folds vector.extract from vector.insert when the extract position is a
2634/// prefix of the insert position and the remaining (un-indexed) dimensions
2635/// of the extracted sub-vector are all size 1. In that case the extracted
2636/// value is fully determined by the inserted value.
2637///
2638/// Examples:
2639/// %ins = vector.insert %s, %v [3, 0] : f32 into vector<16x1xf32>
2640/// %ext = vector.extract %ins [3] : vector<1xf32> from vector<16x1xf32>
2641/// folds to:
2642/// %ext = vector.broadcast %s : f32 to vector<1xf32>
2643///
2644/// %ins = vector.insert %s, %v [0, 0] : vector<1xf32> into vector<16x1x1xf32>
2645// %ext = vector.extract %ins [0] : vector<1x1xf32> from vector<16x1x1xf32>
2646/// folds to:
2647/// %ext = vector.shape_cast %arg0 : vector<1xf32> to vector<1x1xf32>
2648struct FoldExtractFromInsertUnitDim final
2649 : OpRewritePattern<vector::ExtractOp> {
2650 using Base::Base;
2651
2652 LogicalResult matchAndRewrite(vector::ExtractOp extractOp,
2653 PatternRewriter &rewriter) const override {
2654 if (extractOp.hasDynamicPosition())
2655 return failure();
2656
2657 auto insertOp = extractOp.getSource().getDefiningOp<vector::InsertOp>();
2658 if (!insertOp || insertOp.hasDynamicPosition())
2659 return failure();
2660
2661 ArrayRef<int64_t> extractPos = extractOp.getStaticPosition();
2662 ArrayRef<int64_t> insertPos = insertOp.getStaticPosition();
2663
2664 // The extract position must be a strict prefix of the insert position.
2665 if (extractPos.size() >= insertPos.size() ||
2666 extractPos != insertPos.take_front(extractPos.size()))
2667 return failure();
2668
2669 // The remaining dimensions (those not indexed by the extract) must all
2670 // be size 1 in the source vector type. This guarantees that the inserted
2671 // value fully determines the extracted sub-vector.
2672 auto srcVecType = extractOp.getSourceVectorType();
2673 for (int64_t i = extractPos.size(), e = srcVecType.getRank(); i < e; ++i)
2674 if (srcVecType.getDimSize(i) != 1)
2675 return failure();
2676
2677 Value inserted = insertOp.getValueToStore();
2678 Type extractedType = extractOp.getResult().getType();
2679 if (isa<VectorType>(inserted.getType())) {
2680 rewriter.replaceOpWithNewOp<vector::ShapeCastOp>(extractOp, extractedType,
2681 inserted);
2682 } else {
2683 // The inserted value fully determines the extracted sub-vector; broadcast
2684 // it to the extracted type.
2685 rewriter.replaceOpWithNewOp<vector::BroadcastOp>(
2686 extractOp, extractOp.getResult().getType(),
2687 insertOp.getValueToStore());
2688 }
2689 return success();
2690 }
2691};
2692
2693} // namespace
2694
2695void ExtractOp::getCanonicalizationPatterns(RewritePatternSet &results,
2696 MLIRContext *context) {
2697 results.add<ExtractOpFromBroadcast, ExtractOpFromCreateMask,
2698 ExtractOpFromConstantMask, ExtractToShapeCast,
2699 FoldExtractFromInsertUnitDim>(context);
2700 results.add(foldExtractFromShapeCastToShapeCast);
2701 results.add(foldExtractFromFromElements);
2702}
2703
2705 SmallVectorImpl<int64_t> &results) {
2706 for (auto attr : arrayAttr)
2707 results.push_back(llvm::cast<IntegerAttr>(attr).getInt());
2708}
2709
2710//===----------------------------------------------------------------------===//
2711// FmaOp
2712//===----------------------------------------------------------------------===//
2713
2714//-----------------------------------------------------------------------------
2715// VectorUnrollOpInterface methods
2716//-----------------------------------------------------------------------------
2717std::optional<SmallVector<int64_t, 4>> FMAOp::getIterationShapeToUnroll() {
2718 return llvm::to_vector<4>(getVectorType().getShape());
2719}
2720
2721//===----------------------------------------------------------------------===//
2722// ToElementsOp
2723//===----------------------------------------------------------------------===//
2724
2725/// Returns true if all the `operands` are defined by `defOp`.
2726/// Otherwise, returns false.
2727static bool haveSameDefiningOp(OperandRange operands, Operation *defOp) {
2728 if (operands.empty())
2729 return false;
2730
2731 return llvm::all_of(operands, [&](Value operand) {
2732 Operation *currentDef = operand.getDefiningOp();
2733 return currentDef == defOp;
2734 });
2735}
2736
2737/// Folds vector.to_elements(vector.from_elements(%e0, %e1, ...)) into
2738/// (%e0, %e1, ...). For example:
2739///
2740/// %0 = vector.from_elements %a, %b, %c : vector<3xf32>
2741/// %1:3 = vector.to_elements %0 : vector<3xf32>
2742/// user_op %1#0, %1#1, %1#2
2743///
2744/// becomes:
2745///
2746/// user_op %a, %b, %c
2747///
2748static LogicalResult
2749foldToElementsFromElements(ToElementsOp toElementsOp,
2751 auto fromElementsOp =
2752 toElementsOp.getSource().getDefiningOp<FromElementsOp>();
2753 if (!fromElementsOp)
2754 return failure();
2755
2756 llvm::append_range(results, fromElementsOp.getElements());
2757 return success();
2758}
2759
2760/// Folds vector.to_elements(vector.broadcast(%x)) for the scalar case only.
2761///
2762/// Example:
2763/// %b = vector.broadcast %x : i32 to vector<3xf32>
2764/// %e:3 = vector.to_elements %b : vector<3xf32>
2765/// user_op %e#0, %e#1, %e#2
2766/// becomes:
2767/// user_op %x, %x, %x
2768///
2769/// The vector source case is handled by a canonicalization pattern.
2770static LogicalResult
2771foldToElementsOfBroadcast(ToElementsOp toElementsOp,
2773 auto bcastOp = toElementsOp.getSource().getDefiningOp<BroadcastOp>();
2774 if (!bcastOp)
2775 return failure();
2776 // Vectors are handled in the ToElementsOfBroadcast RewritePattern.
2777 if (isa<VectorType>(bcastOp.getSource().getType()))
2778 return failure();
2779
2780 auto resultVecType = cast<VectorType>(toElementsOp.getSource().getType());
2781
2782 Value scalar = bcastOp.getSource();
2783 results.assign(resultVecType.getNumElements(), scalar);
2784 return success();
2785}
2786
2787LogicalResult ToElementsOp::fold(FoldAdaptor adaptor,
2788 SmallVectorImpl<OpFoldResult> &results) {
2789 if (succeeded(foldToElementsFromElements(*this, results)))
2790 return success();
2791
2792 // Y = ToElements(ShapeCast(X)) -> Y = ToElements(X)
2793 if (auto shapeCast = getSource().getDefiningOp<ShapeCastOp>()) {
2794 setOperand(shapeCast.getSource());
2795 return success();
2796 }
2797
2798 return foldToElementsOfBroadcast(*this, results);
2799}
2800
2801LogicalResult
2802ToElementsOp::inferReturnTypes(MLIRContext *ctx, std::optional<Location> loc,
2803 ToElementsOp::Adaptor adaptor,
2804 SmallVectorImpl<Type> &inferredReturnTypes) {
2805 auto vecType = cast<VectorType>(adaptor.getSource().getType());
2806 Type elType = vecType.getElementType();
2807 inferredReturnTypes.append(vecType.getNumElements(), elType);
2808 return success();
2809}
2810
2811/// Canonicalize `vector.to_elements(vector.broadcast(%v))` where `%v` is a
2812/// vector.
2813/// - Build `vector.to_elements %v` and remap each destination element to the
2814/// corresponding source element using broadcast rules (match or 1 →
2815/// replicate).
2816///
2817/// Example:
2818/// %v = vector.broadcast %src : vector<2xf32> to vector<3x2xf32>
2819/// %e:6 = vector.to_elements %v : vector<3x2xf32>
2820/// becomes:
2821/// %src_elems:2 = vector.to_elements %src : vector<2xf32>
2822/// // uses: %src_elems#0, %src_elems#1, %src_elems#0,
2823/// // %src_elems#1, %src_elems#0, %src_elems#1
2824struct ToElementsOfBroadcast final : OpRewritePattern<ToElementsOp> {
2825 using Base::Base;
2826
2827 LogicalResult matchAndRewrite(ToElementsOp toElementsOp,
2828 PatternRewriter &rewriter) const override {
2829 auto bcastOp = toElementsOp.getSource().getDefiningOp<BroadcastOp>();
2830 if (!bcastOp)
2831 return failure();
2832
2833 // Only handle broadcasts from a vector source here.
2834 auto srcType = dyn_cast<VectorType>(bcastOp.getSource().getType());
2835 if (!srcType)
2836 return failure();
2837
2838 auto dstType = cast<VectorType>(toElementsOp.getSource().getType());
2839
2840 ArrayRef<int64_t> dstShape = dstType.getShape();
2841 ArrayRef<int64_t> srcShape = srcType.getShape();
2842
2843 int64_t dstRank = dstShape.size();
2844 int64_t srcRank = srcShape.size();
2845
2846 // Create elements for the broadcast source vector.
2847 auto srcElems = vector::ToElementsOp::create(
2848 rewriter, toElementsOp.getLoc(), bcastOp.getSource());
2849
2850 int64_t dstCount = llvm::product_of(dstShape);
2851
2852 SmallVector<Value> replacements;
2853 replacements.reserve(dstCount);
2854
2855 // For each element of the destination, determine which element of the
2856 // source should be used. We walk all destination positions using a single
2857 // counter, decode it into per-dimension indices, then build the matching
2858 // source position: use the same index where sizes match, and use 0 where
2859 // the source size is 1 (replication). This mapping is needed so we can
2860 // replace each result of to_elements with the corresponding element from
2861 // the broadcast source.
2862 // Inner-dimension stretch example:
2863 // %v = vector.broadcast %src : vector<2x1x2xf32> to vector<2x3x2xf32>
2864 // %e:12 = vector.to_elements %v : vector<2x3x2xf32>
2865 // becomes:
2866 // %src_elems:4 = vector.to_elements %src : vector<2x1x2xf32>
2867 // // uses: %src_elems#0, %src_elems#1, %src_elems#0,
2868 // // %src_elems#1, %src_elems#0, %src_elems#1,
2869 // // %src_elems#2, %src_elems#3, %src_elems#2,
2870 // // %src_elems#3, %src_elems#2, %src_elems#3
2871
2872 // Row-major strides for the destination shape.
2873 SmallVector<int64_t> dstStrides = computeStrides(dstShape);
2874 // Row-major strides for the source shape.
2875 SmallVector<int64_t> srcStrides = computeStrides(srcShape);
2876 SmallVector<int64_t> dstIdx(dstRank);
2877 SmallVector<int64_t> srcIdx(srcRank);
2878 for (int64_t lin = 0; lin < dstCount; ++lin) {
2879 // Convert linear destination index to per-dimension indices.
2880 dstIdx = delinearize(lin, dstStrides);
2881 for (int64_t k = 0; k < srcRank; ++k)
2882 srcIdx[k] = (srcShape[k] == 1) ? 0 : dstIdx[dstRank - srcRank + k];
2883 // Convert per-dimension source indices back to a linear index.
2884 int64_t srcLin = linearize(srcIdx, srcStrides);
2885 replacements.push_back(srcElems.getResult(srcLin));
2886 }
2887
2888 rewriter.replaceOp(toElementsOp, replacements);
2889 return success();
2890 }
2891};
2892
2893void ToElementsOp::getCanonicalizationPatterns(RewritePatternSet &results,
2894 MLIRContext *context) {
2895 results.add<ToElementsOfBroadcast>(context);
2896}
2897
2898//===----------------------------------------------------------------------===//
2899// FromElementsOp
2900//===----------------------------------------------------------------------===//
2901
2902/// Folds vector.from_elements(vector.to_elements(%vector)) into %vector.
2903///
2904/// Case #1: Input and output vectors are the same.
2905///
2906/// %0:3 = vector.to_elements %a : vector<3xf32>
2907/// %1 = vector.from_elements %0#0, %0#1, %0#2 : vector<3xf32>
2908/// user_op %1
2909///
2910/// becomes:
2911///
2912/// user_op %a
2913///
2914static OpFoldResult foldFromElementsToElements(FromElementsOp fromElementsOp) {
2915 OperandRange fromElemsOperands = fromElementsOp.getElements();
2916 if (fromElemsOperands.empty())
2917 return {};
2918
2919 auto toElementsOp = fromElemsOperands[0].getDefiningOp<ToElementsOp>();
2920 if (!toElementsOp)
2921 return {};
2922
2923 if (!haveSameDefiningOp(fromElemsOperands, toElementsOp))
2924 return {};
2925
2926 // Case #1: Input and output vectors are the same. Forward the input vector.
2927 Value toElementsInput = toElementsOp.getSource();
2928 if (fromElementsOp.getType() == toElementsInput.getType() &&
2929 llvm::equal(fromElemsOperands, toElementsOp.getResults())) {
2930 return toElementsInput;
2931 }
2932
2933 // TODO: Support cases with different input and output shapes and different
2934 // number of elements.
2935
2936 return {};
2937}
2938
2939/// Fold vector.from_elements to a constant when all operands are constants.
2940/// Example:
2941/// %c1 = arith.constant 1 : i32
2942/// %c2 = arith.constant 2 : i32
2943/// %v = vector.from_elements %c1, %c2 : vector<2xi32>
2944/// =>
2945/// %v = arith.constant dense<[1, 2]> : vector<2xi32>
2946///
2947static OpFoldResult foldFromElementsToConstant(FromElementsOp fromElementsOp,
2948 ArrayRef<Attribute> elements) {
2949 // Check for null or poison attributes before any processing.
2950 if (llvm::any_of(elements, [](Attribute attr) {
2951 return !attr || matchPattern(attr, ub::m_Poison());
2952 }))
2953 return {};
2954
2955 // DenseElementsAttr only supports int/index/float/complex types.
2956 auto resVecType = fromElementsOp.getResult().getType();
2957 auto resEltType = resVecType.getElementType();
2958 if (!resEltType.isIntOrIndexOrFloat() && !isa<ComplexType>(resEltType))
2959 return {};
2960
2961 // Constant attributes might have a different type than the return type.
2962 // Convert them before creating the dense elements attribute.
2963 auto convertedElements = llvm::map_to_vector(elements, [&](Attribute attr) {
2964 return convertNumericAttr(attr, resEltType);
2965 });
2966
2967 return DenseElementsAttr::get(resVecType, convertedElements);
2968}
2969
2970OpFoldResult FromElementsOp::fold(FoldAdaptor adaptor) {
2971 if (auto res = foldFromElementsToElements(*this))
2972 return res;
2973 if (auto res = foldFromElementsToConstant(*this, adaptor.getElements()))
2974 return res;
2975
2976 return {};
2977}
2978
2979/// Rewrite vector.from_elements as vector.broadcast if the elements are the
2980/// same. Example:
2981/// %0 = vector.from_elements %a, %a, %a : vector<3xf32>
2982/// =>
2983/// %0 = vector.broadcast %a : f32 to vector<3xf32>
2984static LogicalResult
2985rewriteFromElementsAsBroadcast(FromElementsOp fromElementsOp,
2986 PatternRewriter &rewriter) {
2987 if (!llvm::all_equal(fromElementsOp.getElements()))
2988 return failure();
2989 rewriter.replaceOpWithNewOp<BroadcastOp>(
2990 fromElementsOp, fromElementsOp.getType(),
2991 fromElementsOp.getElements().front());
2992 return success();
2993}
2994
2995/// Rewrite from_elements on multiple scalar extracts as a shape_cast
2996/// on a single extract. Example:
2997/// %0 = vector.extract %source[0, 0] : i8 from vector<2x2xi8>
2998/// %1 = vector.extract %source[0, 1] : i8 from vector<2x2xi8>
2999/// %2 = vector.from_elements %0, %1 : vector<2xi8>
3000///
3001/// becomes
3002/// %1 = vector.extract %source[0] : vector<1x2xi8> from vector<2x2xi8>
3003/// %2 = vector.shape_cast %1 : vector<1x2xi8> to vector<2xi8>
3004///
3005/// The requirements for this to be valid are
3006///
3007/// i) The elements are extracted from the same vector (%source).
3008///
3009/// ii) The elements form a suffix of %source. Specifically, the number
3010/// of elements is the same as the product of the last N dimension sizes
3011/// of %source, for some N.
3012///
3013/// iii) The elements are extracted contiguously in ascending order.
3014
3015class FromElementsToShapeCast : public OpRewritePattern<FromElementsOp> {
3016
3017 using Base::Base;
3018
3019 LogicalResult matchAndRewrite(FromElementsOp fromElements,
3020 PatternRewriter &rewriter) const override {
3021
3022 // Handled by `rewriteFromElementsAsBroadcast`.
3023 if (fromElements.getType().getNumElements() == 1)
3024 return failure();
3025
3026 // The common source that all elements are extracted from, if one exists.
3028 // The position of the combined extract operation, if one is created.
3029 ArrayRef<int64_t> combinedPosition;
3030 // The expected index of extraction of the current element in the loop, if
3031 // elements are extracted contiguously in ascending order.
3032 SmallVector<int64_t> expectedPosition;
3033
3034 for (auto [insertIndex, element] :
3035 llvm::enumerate(fromElements.getElements())) {
3036
3037 // Check that the element is from a vector.extract operation.
3038 auto extractOp = element.getDefiningOp<vector::ExtractOp>();
3039 if (!extractOp) {
3040 return rewriter.notifyMatchFailure(fromElements,
3041 "element not from vector.extract");
3042 }
3043
3044 // Check condition (i) by checking that all elements have the same source
3045 // as the first element.
3046 if (insertIndex == 0) {
3047 source = extractOp.getSource();
3048 } else if (extractOp.getSource() != source) {
3049 return rewriter.notifyMatchFailure(fromElements,
3050 "element from different vector");
3051 }
3052
3053 ArrayRef<int64_t> position = extractOp.getStaticPosition();
3054 int64_t rank = position.size();
3055 assert(rank == source.getType().getRank() &&
3056 "scalar extract must have full rank position");
3057
3058 // Check condition (ii) by checking that the position that the first
3059 // element is extracted from has sufficient trailing 0s. For example, in
3060 //
3061 // %elm0 = vector.extract %source[1, 0, 0] : i8 from vector<2x3x4xi8>
3062 // [...]
3063 // %elms = vector.from_elements %elm0, [...] : vector<12xi8>
3064 //
3065 // The 2 trailing 0s in the position of extraction of %elm0 cover 3*4 = 12
3066 // elements, which is the number of elements of %n, so this is valid.
3067 if (insertIndex == 0) {
3068 const int64_t numElms = fromElements.getType().getNumElements();
3069 int64_t numSuffixElms = 1;
3070 int64_t index = rank;
3071 while (index > 0 && position[index - 1] == 0 &&
3072 numSuffixElms < numElms) {
3073 numSuffixElms *= source.getType().getDimSize(index - 1);
3074 --index;
3075 }
3076 if (numSuffixElms != numElms) {
3077 return rewriter.notifyMatchFailure(
3078 fromElements, "elements do not form a suffix of source");
3079 }
3080 expectedPosition = llvm::to_vector(position);
3081 combinedPosition = position.drop_back(rank - index);
3082 }
3083
3084 // Check condition (iii).
3085 else if (expectedPosition != position) {
3086 return rewriter.notifyMatchFailure(
3087 fromElements, "elements not in ascending order (static order)");
3088 }
3089 increment(expectedPosition, source.getType().getShape());
3090 }
3091
3092 auto extracted = rewriter.createOrFold<vector::ExtractOp>(
3093 fromElements.getLoc(), source, combinedPosition);
3094
3095 rewriter.replaceOpWithNewOp<vector::ShapeCastOp>(
3096 fromElements, fromElements.getType(), extracted);
3097
3098 return success();
3099 }
3100
3101 /// Increments n-D `indices` by 1 starting from the innermost dimension.
3102 static void increment(MutableArrayRef<int64_t> indices,
3104 for (int dim : llvm::reverse(llvm::seq<int>(0, indices.size()))) {
3105 indices[dim] += 1;
3106 if (indices[dim] < shape[dim])
3107 break;
3108 indices[dim] = 0;
3109 }
3110 }
3111};
3112
3113void FromElementsOp::getCanonicalizationPatterns(RewritePatternSet &results,
3114 MLIRContext *context) {
3116 results.add<FromElementsToShapeCast>(context);
3117}
3118
3119//===----------------------------------------------------------------------===//
3120// BroadcastOp
3121//===----------------------------------------------------------------------===//
3122
3123void BroadcastOp::inferResultRanges(ArrayRef<ConstantIntRanges> argRanges,
3124 SetIntRangeFn setResultRanges) {
3125 setResultRanges(getResult(), argRanges.front());
3126}
3127
3128//-----------------------------------------------------------------------------
3129// VectorUnrollOpInterface methods
3130//-----------------------------------------------------------------------------
3131std::optional<SmallVector<int64_t, 4>>
3132BroadcastOp::getIterationShapeToUnroll() {
3133 return llvm::to_vector<4>(getResultVectorType().getShape());
3134}
3135
3136/// Return the dimensions of the result vector that were formerly ones in the
3137/// source tensor and thus correspond to "dim-1" broadcasting.
3138static llvm::SetVector<int64_t>
3140 ArrayRef<int64_t> dstShape) {
3141 int64_t rankDiff = dstShape.size() - srcShape.size();
3142 int64_t dstDim = rankDiff;
3144 for (auto [s1, s2] :
3145 llvm::zip_equal(srcShape, dstShape.drop_front(rankDiff))) {
3146 if (s1 != s2) {
3147 assert(s1 == 1 && "expected \"dim-1\" broadcasting");
3148 res.insert(dstDim);
3149 }
3150 ++dstDim;
3151 }
3152 return res;
3153}
3154
3155llvm::SetVector<int64_t> BroadcastOp::computeBroadcastedUnitDims() {
3156 // Scalar broadcast is without any unit dim broadcast.
3157 auto srcVectorType = llvm::dyn_cast<VectorType>(getSourceType());
3158 if (!srcVectorType)
3159 return {};
3160 return ::computeBroadcastedUnitDims(srcVectorType.getShape(),
3161 getResultVectorType().getShape());
3162}
3163
3164/// Broadcast `value` to a vector of `dstShape`, knowing that exactly the
3165/// `broadcastedDims` dimensions in the dstShape are broadcasted.
3166/// This requires (and asserts) that the broadcast is free of "dim-1"
3167/// broadcasting.
3168/// Since vector.broadcast only allows expanding leading dimensions, an extra
3169/// vector.transpose may be inserted to make the broadcast possible.
3170/// `value`, `dstShape` and `broadcastedDims` must be properly specified or
3171/// the helper will assert. This means:
3172/// 1. `dstShape` must not be empty.
3173/// 2. `broadcastedDims` must be confined to [0 .. rank(value.getVectorType)]
3174/// 2. `dstShape` trimmed of the dimensions specified in `broadcastedDims`
3175// must match the `value` shape.
3176Value BroadcastOp::createOrFoldBroadcastOp(
3177 OpBuilder &b, Value value, ArrayRef<int64_t> dstShape,
3178 const llvm::SetVector<int64_t> &broadcastedDims) {
3179 assert(!dstShape.empty() && "unexpected empty dst shape");
3180
3181 // Well-formedness check.
3182 SmallVector<int64_t> checkShape;
3183 for (int i = 0, e = dstShape.size(); i < e; ++i) {
3184 if (broadcastedDims.contains(i))
3185 continue;
3186 checkShape.push_back(dstShape[i]);
3187 }
3188 assert(broadcastedDims.size() == dstShape.size() - checkShape.size() &&
3189 "ill-formed broadcastedDims contains values not confined to "
3190 "destVectorShape");
3191
3192 Location loc = value.getLoc();
3193 Type elementType = getElementTypeOrSelf(value.getType());
3194 VectorType srcVectorType = llvm::dyn_cast<VectorType>(value.getType());
3195 VectorType dstVectorType = VectorType::get(dstShape, elementType);
3196
3197 // Step 2. If scalar -> dstShape broadcast, just do it.
3198 if (!srcVectorType) {
3199 assert(checkShape.empty() &&
3200 "ill-formed createOrFoldBroadcastOp arguments");
3201 return b.createOrFold<vector::BroadcastOp>(loc, dstVectorType, value);
3202 }
3203
3204 assert(srcVectorType.getShape().equals(checkShape) &&
3205 "ill-formed createOrFoldBroadcastOp arguments");
3206
3207 // Step 3. Since vector.broadcast only allows creating leading dims,
3208 // vector -> dstShape broadcast may require a transpose.
3209 // Traverse the dims in order and construct:
3210 // 1. The leading entries of the broadcastShape that is guaranteed to be
3211 // achievable by a simple broadcast.
3212 // 2. The induced permutation for the subsequent vector.transpose that will
3213 // bring us from `broadcastShape` back to he desired `dstShape`.
3214 // If the induced permutation is not the identity, create a vector.transpose.
3215 SmallVector<int64_t> broadcastShape, permutation(dstShape.size(), -1);
3216 broadcastShape.reserve(dstShape.size());
3217 // Consider the example:
3218 // srcShape = 2x4
3219 // dstShape = 1x2x3x4x5
3220 // broadcastedDims = [0, 2, 4]
3221 //
3222 // We want to build:
3223 // broadcastShape = 1x3x5x2x4
3224 // permutation = [0, 2, 4, 1, 3]
3225 // ---V--- -----V-----
3226 // leading broadcast part src shape part
3227 //
3228 // Note that the trailing dims of broadcastShape are exactly the srcShape
3229 // by construction.
3230 // nextSrcShapeDim is used to keep track of where in the permutation the
3231 // "src shape part" occurs.
3232 int64_t nextSrcShapeDim = broadcastedDims.size();
3233 for (int64_t i = 0, e = dstShape.size(); i < e; ++i) {
3234 if (broadcastedDims.contains(i)) {
3235 // 3.a. For each dim in the dst shape, if it is a broadcasted dim,
3236 // bring it to the head of the broadcastShape.
3237 // It will need to be permuted back from `broadcastShape.size() - 1` into
3238 // position `i`.
3239 broadcastShape.push_back(dstShape[i]);
3240 permutation[i] = broadcastShape.size() - 1;
3241 } else {
3242 // 3.b. Otherwise, the dim is not broadcasted, it comes from the src
3243 // shape and needs to be permuted into position `i`.
3244 // Don't touch `broadcastShape` here, the whole srcShape will be
3245 // appended after.
3246 permutation[i] = nextSrcShapeDim++;
3247 }
3248 }
3249 // 3.c. Append the srcShape.
3250 llvm::append_range(broadcastShape, srcVectorType.getShape());
3251
3252 // Ensure there are no "dim-1" broadcasts.
3253 assert(::computeBroadcastedUnitDims(srcVectorType.getShape(), broadcastShape)
3254 .empty() &&
3255 "unexpected \"dim-1\" broadcast");
3256
3257 VectorType broadcastType = VectorType::get(broadcastShape, elementType);
3258 assert(vector::isBroadcastableTo(value.getType(), broadcastType) ==
3259 vector::BroadcastableToResult::Success &&
3260 "must be broadcastable");
3261 Value res = b.createOrFold<vector::BroadcastOp>(loc, broadcastType, value);
3262 // Step 4. If we find any dimension that indeed needs to be permuted,
3263 // immediately return a new vector.transpose.
3264 for (int64_t i = 0, e = permutation.size(); i < e; ++i)
3265 if (permutation[i] != i)
3266 return b.createOrFold<vector::TransposeOp>(loc, res, permutation);
3267 // Otherwise return res.
3268 return res;
3269}
3270
3271LogicalResult BroadcastOp::verify() {
3272 std::pair<VectorDim, VectorDim> mismatchingDims;
3274 getSourceType(), getResultVectorType(), &mismatchingDims);
3275 if (res == BroadcastableToResult::Success)
3276 return success();
3277 if (res == BroadcastableToResult::SourceRankHigher)
3278 return emitOpError("source rank higher than destination rank");
3279 if (res == BroadcastableToResult::DimensionMismatch) {
3280 return emitOpError("dimension mismatch (")
3281 << (mismatchingDims.first.isScalable ? "[" : "")
3282 << mismatchingDims.first.dim
3283 << (mismatchingDims.first.isScalable ? "]" : "") << " vs. "
3284 << (mismatchingDims.second.isScalable ? "[" : "")
3285 << mismatchingDims.second.dim
3286 << (mismatchingDims.second.isScalable ? "]" : "") << ")";
3287 }
3288 if (res == BroadcastableToResult::SourceTypeNotAVector)
3289 return emitOpError("source type is not a vector");
3290 llvm_unreachable("unexpected vector.broadcast op error");
3291}
3292
3293// Fold broadcast(shape_cast(x)) into broadcast(x) if x's type is compatible
3294// with broadcast's result type and shape_cast only adds or removes ones in the
3295// leading dimensions.
3296static LogicalResult foldBroadcastOfShapeCast(BroadcastOp broadcastOp) {
3297 auto srcShapeCast = broadcastOp.getSource().getDefiningOp<ShapeCastOp>();
3298 if (!srcShapeCast)
3299 return failure();
3300
3301 VectorType srcType = srcShapeCast.getSourceVectorType();
3302 VectorType destType = broadcastOp.getResultVectorType();
3303 // Check type compatibility.
3304 if (vector::isBroadcastableTo(srcType, destType) !=
3306 return failure();
3307
3308 ArrayRef<int64_t> srcShape = srcType.getShape();
3309 ArrayRef<int64_t> shapecastShape =
3310 srcShapeCast.getResultVectorType().getShape();
3311 // Trailing dimensions should be the same if shape_cast only alters the
3312 // leading dimensions.
3313 unsigned numTrailingDims = std::min(srcShape.size(), shapecastShape.size());
3314 if (!llvm::equal(srcShape.take_back(numTrailingDims),
3315 shapecastShape.take_back(numTrailingDims)))
3316 return failure();
3317
3318 assert(all_of(srcShape.drop_back(numTrailingDims),
3319 [](int64_t E) { return E == 1; }) &&
3320 all_of(shapecastShape.drop_back(numTrailingDims),
3321 [](int64_t E) { return E == 1; }) &&
3322 "ill-formed shape_cast");
3323
3324 broadcastOp.getSourceMutable().assign(srcShapeCast.getSource());
3325 return success();
3326}
3327
3328OpFoldResult BroadcastOp::fold(FoldAdaptor adaptor) {
3329 if (getSourceType() == getResultVectorType())
3330 return getSource();
3331 if (succeeded(foldBroadcastOfShapeCast(*this)))
3332 return getResult();
3333
3334 if (!adaptor.getSource())
3335 return {};
3336 auto vectorType = getResultVectorType();
3337 if (auto attr = llvm::dyn_cast<IntegerAttr>(adaptor.getSource())) {
3338 if (vectorType.getElementType() != attr.getType())
3339 return {};
3340 return DenseElementsAttr::get(vectorType, attr);
3341 }
3342 if (auto attr = llvm::dyn_cast<FloatAttr>(adaptor.getSource())) {
3343 if (vectorType.getElementType() != attr.getType())
3344 return {};
3345 return DenseElementsAttr::get(vectorType, attr);
3346 }
3347 if (auto attr = llvm::dyn_cast<SplatElementsAttr>(adaptor.getSource()))
3348 return DenseElementsAttr::get(vectorType, attr.getSplatValue<Attribute>());
3349 if (matchPattern(adaptor.getSource(), ub::m_Poison()))
3350 return ub::PoisonAttr::get(getContext());
3351 return {};
3352}
3353
3354namespace {
3355
3356// Fold broadcast1(broadcast2(x)) into broadcast1(x).
3357struct BroadcastFolder : public OpRewritePattern<BroadcastOp> {
3358 using Base::Base;
3359
3360 LogicalResult matchAndRewrite(BroadcastOp broadcastOp,
3361 PatternRewriter &rewriter) const override {
3362 auto srcBroadcast = broadcastOp.getSource().getDefiningOp<BroadcastOp>();
3363 if (!srcBroadcast)
3364 return failure();
3365 rewriter.replaceOpWithNewOp<BroadcastOp>(broadcastOp,
3366 broadcastOp.getResultVectorType(),
3367 srcBroadcast.getSource());
3368 return success();
3369 }
3370};
3371
3372/// Replace `vector.broadcast` with `vector.shape_cast`.
3373///
3374/// BEFORE:
3375/// %0 = vector.broadcast %arg0 : vector<4xi8> to vector<1x1x4xi8>
3376/// AFTER:
3377/// %0 = vector.shape_cast %arg0 : vector<4xi8> to vector<1x1x4xi8>
3378///
3379/// The canonical form of vector operations that reshape vectors is shape_cast.
3380struct BroadcastToShapeCast final
3381 : public OpRewritePattern<vector::BroadcastOp> {
3382 using Base::Base;
3383 LogicalResult matchAndRewrite(vector::BroadcastOp broadcast,
3384 PatternRewriter &rewriter) const override {
3385
3386 auto sourceType = dyn_cast<VectorType>(broadcast.getSourceType());
3387 if (!sourceType) {
3388 return rewriter.notifyMatchFailure(
3389 broadcast, "source is a scalar, shape_cast doesn't support scalar");
3390 }
3391
3392 VectorType outType = broadcast.getType();
3393 if (sourceType.getNumElements() != outType.getNumElements()) {
3394 return rewriter.notifyMatchFailure(
3395 broadcast, "broadcast to a greater number of elements");
3396 }
3397
3398 rewriter.replaceOpWithNewOp<vector::ShapeCastOp>(broadcast, outType,
3399 broadcast.getSource());
3400 return success();
3401 }
3402};
3403} // namespace
3404
3405void BroadcastOp::getCanonicalizationPatterns(RewritePatternSet &results,
3406 MLIRContext *context) {
3407 results.add<BroadcastFolder, BroadcastToShapeCast>(context);
3408}
3409
3410//===----------------------------------------------------------------------===//
3411// ShuffleOp
3412//===----------------------------------------------------------------------===//
3413
3414LogicalResult ShuffleOp::verify() {
3415 VectorType resultType = getResultVectorType();
3416 VectorType v1Type = getV1VectorType();
3417 VectorType v2Type = getV2VectorType();
3418 // Verify ranks.
3419 int64_t resRank = resultType.getRank();
3420 int64_t v1Rank = v1Type.getRank();
3421 int64_t v2Rank = v2Type.getRank();
3422 bool wellFormed0DCase = v1Rank == 0 && v2Rank == 0 && resRank == 1;
3423 bool wellFormedNDCase = v1Rank == resRank && v2Rank == resRank;
3424 if (!wellFormed0DCase && !wellFormedNDCase)
3425 return emitOpError("rank mismatch");
3426
3427 // Verify all but leading dimension sizes.
3428 for (int64_t r = 1; r < v1Rank; ++r) {
3429 int64_t resDim = resultType.getDimSize(r);
3430 int64_t v1Dim = v1Type.getDimSize(r);
3431 int64_t v2Dim = v2Type.getDimSize(r);
3432 if (resDim != v1Dim || v1Dim != v2Dim)
3433 return emitOpError("dimension mismatch");
3434 }
3435 // Verify mask length.
3436 ArrayRef<int64_t> mask = getMask();
3437 int64_t maskLength = mask.size();
3438 if (maskLength <= 0)
3439 return emitOpError("invalid mask length");
3440 if (maskLength != resultType.getDimSize(0))
3441 return emitOpError("mask length mismatch");
3442 // Verify all indices.
3443 int64_t indexSize = (v1Type.getRank() == 0 ? 1 : v1Type.getDimSize(0)) +
3444 (v2Type.getRank() == 0 ? 1 : v2Type.getDimSize(0));
3445 for (auto [idx, maskPos] : llvm::enumerate(mask)) {
3446 if (!isValidPositiveIndexOrPoison(maskPos, kPoisonIndex, indexSize))
3447 return emitOpError("mask index #") << (idx + 1) << " out of range";
3448 }
3449 return success();
3450}
3451
3452LogicalResult
3453ShuffleOp::inferReturnTypes(MLIRContext *, std::optional<Location> loc,
3454 ShuffleOp::Adaptor adaptor,
3455 SmallVectorImpl<Type> &inferredReturnTypes) {
3456 auto v1Type = llvm::dyn_cast<VectorType>(adaptor.getV1().getType());
3457 if (!v1Type) {
3458 return emitOptionalError(loc, "expected vector type");
3459 }
3460 auto v1Rank = v1Type.getRank();
3461 // Construct resulting type: leading dimension matches mask
3462 // length, all trailing dimensions match the operands.
3463 SmallVector<int64_t, 4> shape;
3464 shape.reserve(v1Rank);
3465 shape.push_back(std::max<size_t>(1, adaptor.getMask().size()));
3466 // In the 0-D case there is no trailing shape to append.
3467 if (v1Rank > 0)
3468 llvm::append_range(shape, v1Type.getShape().drop_front());
3469 inferredReturnTypes.push_back(
3470 VectorType::get(shape, v1Type.getElementType()));
3471 return success();
3472}
3473
3474template <typename T>
3475static bool isStepIndexArray(ArrayRef<T> idxArr, uint64_t begin, size_t width) {
3476 T expected = begin;
3477 return idxArr.size() == width && llvm::all_of(idxArr, [&expected](T value) {
3478 return value == expected++;
3479 });
3480}
3481
3482/// Fold shuffle V1, V2, [0, 1, 2, 3] : <4xi32>, <2xi32> -> V1.
3483/// Fold shuffle V1, V2, [4, 5] : <4xi32>, <2xi32> -> V2.
3485 auto v1Type = op.getV1VectorType();
3486 auto v2Type = op.getV2VectorType();
3487 auto mask = op.getMask();
3488 if (isStepIndexArray(mask, 0, v1Type.getDimSize(0)))
3489 return op.getV1();
3490 if (isStepIndexArray(mask, v1Type.getDimSize(0), v2Type.getDimSize(0)))
3491 return op.getV2();
3492 return {};
3493}
3494
3495/// If a shuffle operand is poison, replace all mask indices that reference it
3496/// with kPoisonIndex. This is an in-place fold.
3498 bool isV1Poison = matchPattern(op.getV1(), ub::m_Poison());
3499 bool isV2Poison = matchPattern(op.getV2(), ub::m_Poison());
3500 if (!isV1Poison && !isV2Poison)
3501 return {};
3502
3503 int64_t v1Size = op.getV1VectorType().getDimSize(0);
3504 bool changed = false;
3505 SmallVector<int64_t> newMask = llvm::to_vector(op.getMask());
3506 for (int64_t &idx : newMask) {
3507 if (idx == ShuffleOp::kPoisonIndex)
3508 continue;
3509 if ((isV1Poison && idx < v1Size) || (isV2Poison && idx >= v1Size)) {
3510 idx = ShuffleOp::kPoisonIndex;
3511 changed = true;
3512 }
3513 }
3514
3515 if (!changed)
3516 return {};
3517
3518 op.setMask(newMask);
3519 return op.getResult();
3520}
3521
3522/// Fold shuffle poison, poison -> poison.
3524 Attribute v1Attr,
3525 Attribute v2Attr) {
3526 if (matchPattern(v1Attr, ub::m_Poison()) &&
3527 matchPattern(v2Attr, ub::m_Poison()))
3528 return ub::PoisonAttr::get(context);
3529 return {};
3530}
3531
3532/// Fold a shuffle of constant 1-D inputs by evaluating the mask.
3534 Attribute v2Attr) {
3535 auto v1Type = op.getV1VectorType();
3536 if (v1Type.getRank() != 1)
3537 return {};
3538
3539 bool isV1Poison = matchPattern(v1Attr, ub::m_Poison());
3540 bool isV2Poison = matchPattern(v2Attr, ub::m_Poison());
3541
3542 // Poison input attributes need special handling as they are not
3543 // DenseElementsAttr. If an index is poison, we select the first element of
3544 // the first non-poison input.
3545 SmallVector<Attribute> v1Elements, v2Elements;
3546 Attribute poisonElement;
3547 if (!isV2Poison) {
3548 auto v2DenseAttr = dyn_cast<DenseElementsAttr>(v2Attr);
3549 if (!v2DenseAttr)
3550 return {};
3551 v2Elements = to_vector(v2DenseAttr.getValues<Attribute>());
3552 poisonElement = v2Elements[0];
3553 }
3554 if (!isV1Poison) {
3555 auto v1DenseAttr = dyn_cast<DenseElementsAttr>(v1Attr);
3556 if (!v1DenseAttr)
3557 return {};
3558 v1Elements = to_vector(v1DenseAttr.getValues<Attribute>());
3559 poisonElement = v1Elements[0];
3560 }
3561
3562 ArrayRef<int64_t> mask = op.getMask();
3563 SmallVector<Attribute> results;
3564 int64_t v1Size = v1Type.getDimSize(0);
3565 for (int64_t maskIdx : mask) {
3566 Attribute indexedElm;
3567 // TODO: Return a partial poison vector when supported by the UB dialect.
3568 if (maskIdx == ShuffleOp::kPoisonIndex) {
3569 indexedElm = poisonElement;
3570 } else {
3571 if (maskIdx < v1Size)
3572 indexedElm = isV1Poison ? poisonElement : v1Elements[maskIdx];
3573 else
3574 indexedElm = isV2Poison ? poisonElement : v2Elements[maskIdx - v1Size];
3575 }
3576
3577 results.push_back(indexedElm);
3578 }
3579
3580 return DenseElementsAttr::get(op.getResultVectorType(), results);
3581}
3582
3583OpFoldResult vector::ShuffleOp::fold(FoldAdaptor adaptor) {
3584 auto v1Type = getV1VectorType();
3585
3586 assert(!v1Type.isScalable() && !getV2VectorType().isScalable() &&
3587 "Vector shuffle does not support scalable vectors");
3588
3589 // For consistency: 0-D shuffle return type is 1-D, this cannot be a folding
3590 // but must be a canonicalization into a vector.broadcast.
3591 if (v1Type.getRank() == 0)
3592 return {};
3593
3594 if (auto res = foldShuffleIdentityMask(*this))
3595 return res;
3596 if (auto res = foldShufflePoisonOperandToMask(*this))
3597 return res;
3598
3599 Attribute v1Attr = adaptor.getV1(), v2Attr = adaptor.getV2();
3600 if (!v1Attr || !v2Attr)
3601 return {};
3602
3603 if (auto res = foldShufflePoisonInputs(getContext(), v1Attr, v2Attr))
3604 return res;
3605 if (auto res = foldShuffleConstantInputs(*this, v1Attr, v2Attr))
3606 return res;
3607
3608 return {};
3609}
3610
3611namespace {
3612
3613// Pattern to rewrite a 0-D shuffle with [0] or [1] mask returning a 1-D vector
3614// to a broadcast.
3615struct Canonicalize0DShuffleOp : public OpRewritePattern<ShuffleOp> {
3616 using Base::Base;
3617
3618 LogicalResult matchAndRewrite(ShuffleOp shuffleOp,
3619 PatternRewriter &rewriter) const override {
3620 VectorType v1VectorType = shuffleOp.getV1VectorType();
3621 ArrayRef<int64_t> mask = shuffleOp.getMask();
3622 if (v1VectorType.getRank() > 0)
3623 return failure();
3624 if (mask.size() != 1)
3625 return failure();
3626 VectorType resType = VectorType::Builder(v1VectorType).setShape({1});
3627 if (mask[0] == 0)
3628 rewriter.replaceOpWithNewOp<vector::BroadcastOp>(shuffleOp, resType,
3629 shuffleOp.getV1());
3630 else
3631 rewriter.replaceOpWithNewOp<vector::BroadcastOp>(shuffleOp, resType,
3632 shuffleOp.getV2());
3633 return success();
3634 }
3635};
3636
3637/// Consider the defining operation `defOp` of `value`. If `defOp` is a
3638/// vector.broadcast with a scalar operand, return the scalar value that is
3639/// splatted. Otherwise return null.
3640///
3641/// Example:
3642///
3643/// scalar_source --> vector.broadcast --> value - return scalar_source
3644static Value getScalarSplatSource(Value value) {
3645 // Block argument:
3646 Operation *defOp = value.getDefiningOp();
3647 if (!defOp)
3648 return {};
3649
3650 auto broadcast = dyn_cast<vector::BroadcastOp>(defOp);
3651
3652 // Not broadcast (and not splat):
3653 if (!broadcast)
3654 return {};
3655
3656 // Broadcast of a vector:
3657 if (isa<VectorType>(broadcast.getSourceType()))
3658 return {};
3659
3660 // Broadcast of a scalar:
3661 return broadcast.getSource();
3662}
3663
3664/// Pattern to rewrite shuffle(splat-like(v), splat-like(v)) as broadcast(v).
3665class ShuffleSplat final : public OpRewritePattern<ShuffleOp> {
3666public:
3667 using Base::Base;
3668
3669 LogicalResult matchAndRewrite(ShuffleOp op,
3670 PatternRewriter &rewriter) const override {
3671 Value splat = getScalarSplatSource(op.getV1());
3672 if (!splat || getScalarSplatSource(op.getV2()) != splat)
3673 return failure();
3674
3675 rewriter.replaceOpWithNewOp<BroadcastOp>(op, op.getType(), splat);
3676 return success();
3677 }
3678};
3679
3680/// Pattern to rewrite a fixed-size interleave via vector.shuffle to
3681/// vector.interleave.
3682class ShuffleInterleave : public OpRewritePattern<ShuffleOp> {
3683public:
3684 using Base::Base;
3685
3686 LogicalResult matchAndRewrite(ShuffleOp op,
3687 PatternRewriter &rewriter) const override {
3688 VectorType resultType = op.getResultVectorType();
3689 if (resultType.isScalable())
3690 return rewriter.notifyMatchFailure(
3691 op, "ShuffleOp can't represent a scalable interleave");
3692
3693 if (resultType.getRank() != 1)
3694 return rewriter.notifyMatchFailure(
3695 op, "ShuffleOp can't represent an n-D interleave");
3696
3697 VectorType sourceType = op.getV1VectorType();
3698 if (sourceType != op.getV2VectorType() ||
3699 sourceType.getNumElements() * 2 != resultType.getNumElements()) {
3700 return rewriter.notifyMatchFailure(
3701 op, "ShuffleOp types don't match an interleave");
3702 }
3703
3704 ArrayRef<int64_t> shuffleMask = op.getMask();
3705 int64_t resultVectorSize = resultType.getNumElements();
3706 for (int i = 0, e = resultVectorSize / 2; i < e; ++i) {
3707 int64_t maskValueA = shuffleMask[i * 2];
3708 int64_t maskValueB = shuffleMask[(i * 2) + 1];
3709 if (maskValueA != i || maskValueB != (resultVectorSize / 2) + i)
3710 return rewriter.notifyMatchFailure(op,
3711 "ShuffleOp mask not interleaving");
3712 }
3713
3714 rewriter.replaceOpWithNewOp<InterleaveOp>(op, op.getV1(), op.getV2());
3715 return success();
3716 }
3717};
3718
3719/// Pattern to replace usused shuffle operands / results with poison.
3720///
3721/// Example Input:
3722/// %r = vector.shuffle %v1, %v2 [2, 3, 3, 3] : vector<2xi32>, vector<2xi32>
3723///
3724/// Example Output:
3725/// %0 = ub.poison : vector<2xi32>
3726/// %r = vector.shuffle %0, %v2 [2, 3, 3, 3] : vector<2xi32>, vector<2xi32>
3727class FoldUnusedShuffleOperand final : public OpRewritePattern<ShuffleOp> {
3728public:
3729 using Base::Base;
3730
3731 LogicalResult matchAndRewrite(ShuffleOp op,
3732 PatternRewriter &rewriter) const override {
3733 // Replace with poison if all mask elements are poison.
3734 if (llvm::all_of(op.getMask(), [](int64_t mask) {
3735 return mask == ShuffleOp::kPoisonIndex;
3736 })) {
3737 rewriter.replaceOpWithNewOp<ub::PoisonOp>(op, op.getType());
3738 return success();
3739 }
3740
3741 // Helper function to replace an operand with poison.
3742 auto replaceOperandWithPoison = [&](OpOperand &operand) {
3743 // Do not replace if the operand is already poison.
3744 if (!matchPattern(operand.get(), ub::m_Poison())) {
3745 Value poison = ub::PoisonOp::create(rewriter, op.getLoc(),
3746 operand.get().getType());
3747 rewriter.modifyOpInPlace(op, [&]() { operand.set(poison); });
3748 return success();
3749 }
3750 return failure();
3751 };
3752
3753 // Replace V1 with poison if it is not used.
3754 int64_t leadingV1Size = op.getV1VectorType().getRank() > 0
3755 ? op.getV1VectorType().getDimSize(0)
3756 : 1;
3757 bool isV1Used = llvm::any_of(op.getMask(), [&](int64_t mask) {
3758 return mask != ShuffleOp::kPoisonIndex && mask < leadingV1Size;
3759 });
3760 if (!isV1Used && succeeded(replaceOperandWithPoison(op.getV1Mutable())))
3761 return success();
3762
3763 // Replace V2 with poison if it is not used.
3764 bool isV2Used = llvm::any_of(op.getMask(), [&](int64_t mask) {
3765 return mask != ShuffleOp::kPoisonIndex && mask >= leadingV1Size;
3766 });
3767 if (!isV2Used && succeeded(replaceOperandWithPoison(op.getV2Mutable())))
3768 return success();
3769
3770 return failure();
3771 }
3772};
3773} // namespace
3774
3775void ShuffleOp::getCanonicalizationPatterns(RewritePatternSet &results,
3776 MLIRContext *context) {
3777 results.add<ShuffleSplat, ShuffleInterleave, Canonicalize0DShuffleOp,
3778 FoldUnusedShuffleOperand>(context);
3779}
3780
3781//===----------------------------------------------------------------------===//
3782// InsertOp
3783//===----------------------------------------------------------------------===//
3784
3785void vector::InsertOp::inferResultRanges(ArrayRef<ConstantIntRanges> argRanges,
3786 SetIntRangeFn setResultRanges) {
3787 setResultRanges(getResult(), argRanges[0].rangeUnion(argRanges[1]));
3788}
3789
3790void vector::InsertOp::build(OpBuilder &builder, OperationState &result,
3791 Value source, Value dest) {
3792 auto vectorTy = cast<VectorType>(dest.getType());
3793 build(builder, result, source, dest,
3794 SmallVector<int64_t>(vectorTy.getRank(), 0));
3795}
3796
3797void vector::InsertOp::build(OpBuilder &builder, OperationState &result,
3798 Value source, Value dest, int64_t position) {
3799 build(builder, result, source, dest, ArrayRef<int64_t>{position});
3800}
3801
3802void vector::InsertOp::build(OpBuilder &builder, OperationState &result,
3803 Value source, Value dest, OpFoldResult position) {
3804 build(builder, result, source, dest, ArrayRef<OpFoldResult>{position});
3805}
3806
3807void vector::InsertOp::build(OpBuilder &builder, OperationState &result,
3808 Value source, Value dest,
3809 ArrayRef<int64_t> position) {
3810 SmallVector<OpFoldResult> posVals;
3811 posVals.reserve(position.size());
3812 llvm::transform(position, std::back_inserter(posVals),
3813 [&](int64_t pos) { return builder.getI64IntegerAttr(pos); });
3814 build(builder, result, source, dest, posVals);
3815}
3816
3817void vector::InsertOp::build(OpBuilder &builder, OperationState &result,
3818 Value source, Value dest,
3819 ArrayRef<OpFoldResult> position) {
3820 SmallVector<int64_t> staticPos;
3821 SmallVector<Value> dynamicPos;
3822 dispatchIndexOpFoldResults(position, dynamicPos, staticPos);
3823 build(builder, result, source, dest, dynamicPos,
3824 builder.getDenseI64ArrayAttr(staticPos));
3825}
3826
3827LogicalResult InsertOp::verify() {
3828 if (auto srcTy = dyn_cast<VectorType>(getValueToStoreType()))
3829 if (srcTy.getRank() == 0)
3830 return emitError(
3831 "expected a scalar instead of a 0-d vector as the source operand");
3832
3833 SmallVector<OpFoldResult> position = getMixedPosition();
3834 auto destVectorType = getDestVectorType();
3835 if (position.size() > static_cast<unsigned>(destVectorType.getRank()))
3836 return emitOpError(
3837 "expected position attribute of rank no greater than dest vector rank");
3838 auto srcVectorType = llvm::dyn_cast<VectorType>(getValueToStoreType());
3839 if (srcVectorType &&
3840 (static_cast<unsigned>(srcVectorType.getRank()) + position.size() !=
3841 static_cast<unsigned>(destVectorType.getRank())))
3842 return emitOpError("expected position attribute rank + source rank to "
3843 "match dest vector rank");
3844 if (!srcVectorType &&
3845 (position.size() != static_cast<unsigned>(destVectorType.getRank())))
3846 return emitOpError(
3847 "expected position attribute rank to match the dest vector rank");
3848 for (auto [idx, pos] : llvm::enumerate(position)) {
3849 if (auto attr = dyn_cast<Attribute>(pos)) {
3850 int64_t constIdx = cast<IntegerAttr>(attr).getInt();
3851 if (!isValidPositiveIndexOrPoison(constIdx, kPoisonIndex,
3852 destVectorType.getDimSize(idx))) {
3853 return emitOpError("expected position attribute #")
3854 << (idx + 1)
3855 << " to be a non-negative integer smaller than the "
3856 "corresponding "
3857 "dest vector dimension";
3858 }
3859 }
3860 }
3861 return success();
3862}
3863
3864// Calculate the linearized position of the continuous chunk of elements to
3865// insert, based on the shape of the value to insert and the positions to insert
3866// at.
3867static int64_t calculateInsertPosition(VectorType destTy,
3868 ArrayRef<int64_t> positions) {
3869 llvm::SmallVector<int64_t> completePositions(destTy.getRank(), 0);
3870 assert(positions.size() <= completePositions.size() &&
3871 "positions size must be less than or equal to destTy rank");
3872 copy(positions, completePositions.begin());
3873 return linearize(completePositions, computeStrides(destTy.getShape()));
3874}
3875
3876namespace {
3877
3878// If insertOp is only inserting unit dimensions it can be transformed to a
3879// broadcast.
3880class InsertToBroadcast final : public OpRewritePattern<InsertOp> {
3881public:
3882 using Base::Base;
3883
3884 LogicalResult matchAndRewrite(InsertOp insertOp,
3885 PatternRewriter &rewriter) const override {
3886 auto srcVecType =
3887 llvm::dyn_cast<VectorType>(insertOp.getValueToStoreType());
3888 if (!srcVecType || insertOp.getDestVectorType().getNumElements() !=
3889 srcVecType.getNumElements())
3890 return failure();
3891 rewriter.replaceOpWithNewOp<BroadcastOp>(
3892 insertOp, insertOp.getDestVectorType(), insertOp.getValueToStore());
3893 return success();
3894 }
3895};
3896
3897/// Pattern to rewrite a insert(splat-like(v), splat-like(v)) as broadcast(v).
3898class InsertSplatToSplat final : public OpRewritePattern<InsertOp> {
3899public:
3900 using Base::Base;
3901
3902 LogicalResult matchAndRewrite(InsertOp op,
3903 PatternRewriter &rewriter) const override {
3904
3905 Value splat = getScalarSplatSource(op.getValueToStore());
3906 if (!splat || getScalarSplatSource(op.getDest()) != splat)
3907 return failure();
3908
3909 rewriter.replaceOpWithNewOp<BroadcastOp>(op, op.getType(), splat);
3910 return success();
3911 }
3912};
3913
3914/// Pattern to optimize a chain of insertions.
3915///
3916/// This pattern identifies chains of vector.insert operations that:
3917/// 1. Only insert values at static positions.
3918/// 2. Completely initialize all elements in the resulting vector.
3919/// 3. All intermediate insert operations have only one use.
3920///
3921/// When these conditions are met, the entire chain can be replaced with a
3922/// single vector.from_elements operation.
3923///
3924/// To keep this pattern simple, and avoid spending too much time on matching
3925/// fragmented insert chains, this pattern only considers the last insert op in
3926/// the chain.
3927///
3928/// Example transformation:
3929/// %poison = ub.poison : vector<2xi32>
3930/// %0 = vector.insert %c1, %poison[0] : i32 into vector<2xi32>
3931/// %1 = vector.insert %c2, %0[1] : i32 into vector<2xi32>
3932/// ->
3933/// %result = vector.from_elements %c1, %c2 : vector<2xi32>
3934class InsertChainFullyInitialized final : public OpRewritePattern<InsertOp> {
3935public:
3936 using Base::Base;
3937 LogicalResult matchAndRewrite(InsertOp op,
3938 PatternRewriter &rewriter) const override {
3939
3940 VectorType destTy = op.getDestVectorType();
3941 if (destTy.isScalable())
3942 return failure();
3943 // Ensure this is the trailing vector.insert op in a chain of inserts.
3944 for (Operation *user : op.getResult().getUsers())
3945 if (auto insertOp = dyn_cast<InsertOp>(user))
3946 if (insertOp.getDest() == op.getResult())
3947 return failure();
3948
3949 InsertOp currentOp = op;
3950 SmallVector<InsertOp> chainInsertOps;
3951 while (currentOp) {
3952 // Check cond 1: Dynamic position is not supported.
3953 if (currentOp.hasDynamicPosition())
3954 return failure();
3955
3956 chainInsertOps.push_back(currentOp);
3957 currentOp = currentOp.getDest().getDefiningOp<InsertOp>();
3958 // Check cond 3: Intermediate inserts have only one use to avoid an
3959 // explosion of vectors.
3960 if (currentOp && !currentOp->hasOneUse())
3961 return failure();
3962 }
3963
3964 int64_t vectorSize = destTy.getNumElements();
3965 int64_t initializedCount = 0;
3966 SmallVector<bool> initializedDestIdxs(vectorSize, false);
3967 SmallVector<int64_t> pendingInsertPos;
3968 SmallVector<int64_t> pendingInsertSize;
3969 SmallVector<Value> pendingInsertValues;
3970
3971 for (auto insertOp : chainInsertOps) {
3972 // This pattern can do nothing with poison index.
3973 if (is_contained(insertOp.getStaticPosition(), InsertOp::kPoisonIndex))
3974 return failure();
3975
3976 // Calculate the linearized position for inserting elements.
3977 int64_t insertBeginPosition =
3978 calculateInsertPosition(destTy, insertOp.getStaticPosition());
3979
3980 // The valueToStore operand may be a vector or a scalar. Need to handle
3981 // both cases.
3982 int64_t insertSize = 1;
3983 if (auto srcVectorType =
3984 llvm::dyn_cast<VectorType>(insertOp.getValueToStoreType()))
3985 insertSize = srcVectorType.getNumElements();
3986
3987 assert(insertBeginPosition + insertSize <= vectorSize &&
3988 "insert would overflow the vector");
3989
3990 for (auto index : llvm::seq<int64_t>(insertBeginPosition,
3991 insertBeginPosition + insertSize)) {
3992 if (initializedDestIdxs[index])
3993 continue;
3994 initializedDestIdxs[index] = true;
3995 ++initializedCount;
3996 }
3997
3998 // Defer the creation of ops before we can make sure the pattern can
3999 // succeed.
4000 pendingInsertPos.push_back(insertBeginPosition);
4001 pendingInsertSize.push_back(insertSize);
4002 pendingInsertValues.push_back(insertOp.getValueToStore());
4003
4004 if (initializedCount == vectorSize)
4005 break;
4006 }
4007
4008 // Check cond 2: all positions must be initialized.
4009 if (initializedCount != vectorSize)
4010 return failure();
4011
4012 SmallVector<Value> elements(vectorSize);
4013 for (auto [insertBeginPosition, insertSize, valueToStore] :
4014 llvm::reverse(llvm::zip(pendingInsertPos, pendingInsertSize,
4015 pendingInsertValues))) {
4016 auto srcVectorType = llvm::dyn_cast<VectorType>(valueToStore.getType());
4017
4018 if (!srcVectorType) {
4019 elements[insertBeginPosition] = valueToStore;
4020 continue;
4021 }
4022
4023 Repeated<Type> elementToInsertTypes(insertSize,
4024 srcVectorType.getElementType());
4025 // Get all elements from the vector in row-major order.
4026 auto elementsToInsert = vector::ToElementsOp::create(
4027 rewriter, op.getLoc(), elementToInsertTypes, valueToStore);
4028 for (int64_t linearIdx = 0; linearIdx < insertSize; linearIdx++) {
4029 elements[insertBeginPosition + linearIdx] =
4030 elementsToInsert.getResult(linearIdx);
4031 }
4032 }
4033
4034 rewriter.replaceOpWithNewOp<vector::FromElementsOp>(op, destTy, elements);
4035 return success();
4036 }
4037};
4038
4039} // namespace
4040
4041static Attribute
4043 Attribute dstAttr,
4044 int64_t maxVectorSizeFoldThreshold) {
4045 if (insertOp.hasDynamicPosition())
4046 return {};
4047
4048 auto denseDst = llvm::dyn_cast_if_present<DenseElementsAttr>(dstAttr);
4049 if (!denseDst)
4050 return {};
4051
4052 if (!srcAttr) {
4053 return {};
4054 }
4055
4056 VectorType destTy = insertOp.getDestVectorType();
4057 if (destTy.isScalable())
4058 return {};
4059
4060 // Make sure we do not create too many large constants.
4061 if (destTy.getNumElements() > maxVectorSizeFoldThreshold &&
4062 !insertOp->hasOneUse())
4063 return {};
4064
4065 // Bail out on poison indices (kPoisonIndex = -1) to avoid computing an
4066 // invalid (negative) linearized position which would cause UB below.
4067 if (is_contained(insertOp.getStaticPosition(), InsertOp::kPoisonIndex))
4068 return {};
4069
4070 // Calculate the linearized position for inserting elements.
4071 int64_t insertBeginPosition =
4072 calculateInsertPosition(destTy, insertOp.getStaticPosition());
4073 SmallVector<Attribute> insertedValues;
4074 Type destEltType = destTy.getElementType();
4075
4076 /// Converts attribute to the expected type if there's
4077 /// a mismatch.
4078 if (auto denseSource = llvm::dyn_cast<DenseElementsAttr>(srcAttr)) {
4079 for (auto value : denseSource.getValues<Attribute>())
4080 insertedValues.push_back(convertNumericAttr(value, destEltType));
4081 } else {
4082 insertedValues.push_back(convertNumericAttr(srcAttr, destEltType));
4083 }
4084
4085 auto allValues = llvm::to_vector(denseDst.getValues<Attribute>());
4086 copy(insertedValues, allValues.begin() + insertBeginPosition);
4087 auto newAttr = DenseElementsAttr::get(destTy, allValues);
4088
4089 return newAttr;
4090}
4091
4092/// Folder to replace the `dest` operand of the insert op with the root dest of
4093/// the insert op use chain.
4094static Value foldInsertUseChain(InsertOp insertOp) {
4095 auto destInsert = insertOp.getDest().getDefiningOp<InsertOp>();
4096 if (!destInsert)
4097 return {};
4098
4099 if (insertOp.getMixedPosition() != destInsert.getMixedPosition())
4100 return {};
4101
4102 insertOp.setOperand(1, destInsert.getDest());
4103 return insertOp.getResult();
4104}
4105
4106void InsertOp::getCanonicalizationPatterns(RewritePatternSet &results,
4107 MLIRContext *context) {
4108 results.add<InsertToBroadcast, BroadcastFolder, InsertSplatToSplat,
4109 InsertChainFullyInitialized>(context);
4110}
4111
4112OpFoldResult InsertOp::fold(FoldAdaptor adaptor) {
4113 // Do not create constants with more than `vectorSizeFoldThreashold` elements,
4114 // unless the source vector constant has a single use.
4115 constexpr int64_t vectorSizeFoldThreshold = 256;
4116 // Fold "vector.insert %v, %dest [] : vector<2x2xf32> from vector<2x2xf32>" to
4117 // %v. Note: Do not fold "vector.insert %v, %dest [] : f32 into vector<f32>"
4118 // (type mismatch).
4119 if (getNumIndices() == 0 && getValueToStoreType() == getType())
4120 return getValueToStore();
4121 // Fold `arith.constant` indices into the `vector.insert` operation.
4122 // Do not stop here as this fold may enable subsequent folds that require
4123 // constant indices.
4124 SmallVector<Value> operands = {getValueToStore(), getDest()};
4125 auto inplaceFolded = extractInsertFoldConstantOp(*this, adaptor, operands);
4126
4127 if (auto res = foldInsertUseChain(*this))
4128 return res;
4129 if (auto res = foldPoisonIndexInsertExtractOp(
4130 getContext(), adaptor.getStaticPosition(), kPoisonIndex))
4131 return res;
4132 if (auto res = foldDenseElementsAttrDestInsertOp(
4133 *this, adaptor.getValueToStore(), adaptor.getDest(),
4134 vectorSizeFoldThreshold)) {
4135 return res;
4136 }
4137
4138 return inplaceFolded;
4139}
4140
4141//===----------------------------------------------------------------------===//
4142// InsertStridedSliceOp
4143//===----------------------------------------------------------------------===//
4144
4145void InsertStridedSliceOp::build(OpBuilder &builder, OperationState &result,
4146 Value source, Value dest,
4147 ArrayRef<int64_t> offsets,
4148 ArrayRef<int64_t> strides) {
4149 result.addOperands({source, dest});
4150 auto offsetsAttr = getVectorSubscriptAttr(builder, offsets);
4151 auto stridesAttr = getVectorSubscriptAttr(builder, strides);
4152 result.addTypes(dest.getType());
4153 result.addAttribute(InsertStridedSliceOp::getOffsetsAttrName(result.name),
4154 offsetsAttr);
4155 result.addAttribute(InsertStridedSliceOp::getStridesAttrName(result.name),
4156 stridesAttr);
4157}
4158
4159// TODO: Should be moved to Tablegen ConfinedAttr attributes.
4160template <typename OpType>
4161static LogicalResult isIntegerArrayAttrSmallerThanShape(OpType op,
4162 ArrayAttr arrayAttr,
4164 StringRef attrName) {
4165 if (arrayAttr.size() > shape.size())
4166 return op.emitOpError("expected ")
4167 << attrName << " attribute of rank no greater than vector rank";
4168 return success();
4169}
4170
4171// Returns true if all integers in `arrayAttr` are in the half-open [min, max}
4172// interval. If `halfOpen` is true then the admissible interval is [min, max).
4173// Otherwise, the admissible interval is [min, max].
4174template <typename OpType>
4175static LogicalResult
4177 int64_t max, StringRef attrName,
4178 bool halfOpen = true) {
4179 for (auto attr : arrayAttr) {
4180 auto val = llvm::cast<IntegerAttr>(attr).getInt();
4181 auto upper = max;
4182 if (!halfOpen)
4183 upper += 1;
4184 if (val < min || val >= upper)
4185 return op.emitOpError("expected ") << attrName << " to be confined to ["
4186 << min << ", " << upper << ")";
4187 }
4188 return success();
4189}
4190
4191// Returns true if all integers in `arrayAttr` are in the half-open [min, max}
4192// interval. If `halfOpen` is true then the admissible interval is [min, max).
4193// Otherwise, the admissible interval is [min, max].
4194template <typename OpType>
4195static LogicalResult
4197 ArrayRef<int64_t> shape, StringRef attrName,
4198 bool halfOpen = true, int64_t min = 0) {
4199 for (auto [index, attrDimPair] :
4200 llvm::enumerate(llvm::zip_first(arrayAttr, shape))) {
4201 int64_t val = llvm::cast<IntegerAttr>(std::get<0>(attrDimPair)).getInt();
4202 int64_t max = std::get<1>(attrDimPair);
4203 if (!halfOpen)
4204 max += 1;
4205 if (val < min || val >= max)
4206 return op.emitOpError("expected ")
4207 << attrName << " dimension " << index << " to be confined to ["
4208 << min << ", " << max << ")";
4209 }
4210 return success();
4211}
4212
4213// Returns true if, for all indices i = 0..shape.size()-1, val is in the
4214// [min, max} interval:
4215// val = `arrayAttr1[i]` + `arrayAttr2[i]`,
4216// If `halfOpen` is true then the admissible interval is [min, max). Otherwise,
4217// the admissible interval is [min, max].
4218template <typename OpType>
4220 OpType op, ArrayAttr arrayAttr1, ArrayAttr arrayAttr2,
4221 ArrayRef<int64_t> shape, StringRef attrName1, StringRef attrName2,
4222 bool halfOpen = true, int64_t min = 1) {
4223 assert(arrayAttr1.size() <= shape.size());
4224 assert(arrayAttr2.size() <= shape.size());
4225 for (auto [index, it] :
4226 llvm::enumerate(llvm::zip(arrayAttr1, arrayAttr2, shape))) {
4227 auto val1 = llvm::cast<IntegerAttr>(std::get<0>(it)).getInt();
4228 auto val2 = llvm::cast<IntegerAttr>(std::get<1>(it)).getInt();
4229 int64_t max = std::get<2>(it);
4230 if (!halfOpen)
4231 max += 1;
4232 if (val1 + val2 < 0 || val1 + val2 >= max)
4233 return op.emitOpError("expected sum(")
4234 << attrName1 << ", " << attrName2 << ") dimension " << index
4235 << " to be confined to [" << min << ", " << max << ")";
4236 }
4237 return success();
4238}
4239
4241 MLIRContext *context) {
4242 auto attrs = llvm::map_range(values, [context](int64_t v) -> Attribute {
4243 return IntegerAttr::get(IntegerType::get(context, 64), APInt(64, v));
4244 });
4245 return ArrayAttr::get(context, llvm::to_vector<8>(attrs));
4246}
4247
4248LogicalResult InsertStridedSliceOp::verify() {
4249 auto sourceVectorType = getSourceVectorType();
4250 auto destVectorType = getDestVectorType();
4251 auto offsets = getOffsetsAttr();
4252 auto strides = getStridesAttr();
4253 if (offsets.size() != static_cast<unsigned>(destVectorType.getRank()))
4254 return emitOpError(
4255 "expected offsets of same size as destination vector rank");
4256 if (strides.size() != static_cast<unsigned>(sourceVectorType.getRank()))
4257 return emitOpError("expected strides of same size as source vector rank");
4258 if (sourceVectorType.getRank() > destVectorType.getRank())
4259 return emitOpError(
4260 "expected source rank to be no greater than destination rank");
4261
4262 auto sourceShape = sourceVectorType.getShape();
4263 auto destShape = destVectorType.getShape();
4264 SmallVector<int64_t, 4> sourceShapeAsDestShape(
4265 destShape.size() - sourceShape.size(), 0);
4266 sourceShapeAsDestShape.append(sourceShape.begin(), sourceShape.end());
4267 auto offName = InsertStridedSliceOp::getOffsetsAttrName();
4268 auto stridesName = InsertStridedSliceOp::getStridesAttrName();
4269 if (failed(isIntegerArrayAttrConfinedToShape(*this, offsets, destShape,
4270 offName)) ||
4271 failed(isIntegerArrayAttrConfinedToRange(*this, strides, /*min=*/1,
4272 /*max=*/1, stridesName,
4273 /*halfOpen=*/false)) ||
4275 *this, offsets,
4276 makeI64ArrayAttr(sourceShapeAsDestShape, getContext()), destShape,
4277 offName, "source vector shape",
4278 /*halfOpen=*/false, /*min=*/1)))
4279 return failure();
4280
4281 unsigned rankDiff = destShape.size() - sourceShape.size();
4282 for (unsigned idx = 0; idx < sourceShape.size(); ++idx) {
4283 if (sourceVectorType.getScalableDims()[idx] !=
4284 destVectorType.getScalableDims()[idx + rankDiff]) {
4285 return emitOpError("mismatching scalable flags (at source vector idx=")
4286 << idx << ")";
4287 }
4288 if (sourceVectorType.getScalableDims()[idx]) {
4289 auto sourceSize = sourceShape[idx];
4290 auto destSize = destShape[idx + rankDiff];
4291 if (sourceSize != destSize) {
4292 return emitOpError("expected size at idx=")
4293 << idx
4294 << (" to match the corresponding base size from the input "
4295 "vector (")
4296 << sourceSize << (" vs ") << destSize << (")");
4297 }
4298 }
4299 }
4300
4301 return success();
4302}
4303
4304namespace {
4305/// Rewrite insert_strided_slice(splat-like(v), splat-like(v)) as v.
4306class FoldInsertStridedSliceSplat final
4307 : public OpRewritePattern<InsertStridedSliceOp> {
4308public:
4309 using Base::Base;
4310
4311 LogicalResult matchAndRewrite(InsertStridedSliceOp insertStridedSliceOp,
4312 PatternRewriter &rewriter) const override {
4313
4314 auto dst = insertStridedSliceOp.getDest();
4315 auto splat = getScalarSplatSource(insertStridedSliceOp.getValueToStore());
4316 if (!splat || getScalarSplatSource(dst) != splat)
4317 return failure();
4318
4319 rewriter.replaceOp(insertStridedSliceOp, dst);
4320 return success();
4321 }
4322};
4323
4324/// Pattern to rewrite an InsertStridedSliceOp(ExtractStridedSliceOp(dst), dst)
4325/// to dst.
4326class FoldInsertStridedSliceOfExtract final
4327 : public OpRewritePattern<InsertStridedSliceOp> {
4328public:
4329 using Base::Base;
4330
4331 LogicalResult matchAndRewrite(InsertStridedSliceOp insertStridedSliceOp,
4332 PatternRewriter &rewriter) const override {
4333 auto extractStridedSliceOp =
4334 insertStridedSliceOp.getValueToStore()
4335 .getDefiningOp<vector::ExtractStridedSliceOp>();
4336
4337 if (!extractStridedSliceOp)
4338 return failure();
4339
4340 if (extractStridedSliceOp.getOperand() != insertStridedSliceOp.getDest())
4341 return failure();
4342
4343 // Check if have the same strides and offsets.
4344 if (extractStridedSliceOp.getStrides() !=
4345 insertStridedSliceOp.getStrides() ||
4346 extractStridedSliceOp.getOffsets() != insertStridedSliceOp.getOffsets())
4347 return failure();
4348
4349 rewriter.replaceOp(insertStridedSliceOp, insertStridedSliceOp.getDest());
4350 return success();
4351 }
4352};
4353
4354// Pattern to rewrite an InsertStridedSliceOp(ConstantOp into ConstantOp) ->
4355// ConstantOp.
4356class InsertStridedSliceConstantFolder final
4357 : public OpRewritePattern<InsertStridedSliceOp> {
4358public:
4359 using Base::Base;
4360
4361 // Do not create constants with more than `vectorSizeFoldThreashold` elements,
4362 // unless the source vector constant has a single use.
4363 static constexpr int64_t vectorSizeFoldThreshold = 256;
4364
4365 LogicalResult matchAndRewrite(InsertStridedSliceOp op,
4366 PatternRewriter &rewriter) const override {
4367 // Return if 'InsertOp' operand is not defined by a compatible vector
4368 // ConstantOp.
4369 TypedValue<VectorType> destVector = op.getDest();
4370 Attribute vectorDestCst;
4371 if (!matchPattern(destVector, m_Constant(&vectorDestCst)))
4372 return failure();
4373
4374 VectorType destTy = destVector.getType();
4375 if (destTy.isScalable())
4376 return failure();
4377
4378 // Make sure we do not create too many large constants.
4379 if (destTy.getNumElements() > vectorSizeFoldThreshold &&
4380 !destVector.hasOneUse())
4381 return failure();
4382
4383 TypedValue<VectorType> sourceValue = op.getValueToStore();
4384 Attribute sourceCst;
4385 if (!matchPattern(sourceValue, m_Constant(&sourceCst)))
4386 return failure();
4387
4388 // TODO: Support poison.
4389 if (matchPattern(vectorDestCst, ub::m_Poison()) ||
4390 matchPattern(sourceCst, ub::m_Poison()))
4391 return failure();
4392
4393 // TODO: Handle non-unit strides when they become available.
4394 if (op.hasNonUnitStrides())
4395 return failure();
4396
4397 VectorType sliceVecTy = sourceValue.getType();
4398 ArrayRef<int64_t> sliceShape = sliceVecTy.getShape();
4399 int64_t rankDifference = destTy.getRank() - sliceVecTy.getRank();
4400 SmallVector<int64_t, 4> offsets = getI64SubArray(op.getOffsets());
4401 SmallVector<int64_t, 4> destStrides = computeStrides(destTy.getShape());
4402
4403 // Calcualte the destination element indices by enumerating all slice
4404 // positions within the destination and linearizing them. The enumeration
4405 // order is lexicographic which yields a sequence of monotonically
4406 // increasing linearized position indices.
4407 // Because the destination may have higher dimensionality then the slice,
4408 // we keep track of two overlapping sets of positions and offsets.
4409 auto denseDest = llvm::cast<DenseElementsAttr>(vectorDestCst);
4410 auto denseSlice = llvm::cast<DenseElementsAttr>(sourceCst);
4411 auto sliceValuesIt = denseSlice.value_begin<Attribute>();
4412 auto newValues = llvm::to_vector(denseDest.getValues<Attribute>());
4413 SmallVector<int64_t> currDestPosition(offsets.begin(), offsets.end());
4414 MutableArrayRef<int64_t> currSlicePosition(
4415 currDestPosition.begin() + rankDifference, currDestPosition.end());
4416 ArrayRef<int64_t> sliceOffsets(offsets.begin() + rankDifference,
4417 offsets.end());
4418 do {
4419 int64_t linearizedPosition = linearize(currDestPosition, destStrides);
4420 assert(linearizedPosition < destTy.getNumElements() && "Invalid index");
4421 assert(sliceValuesIt != denseSlice.value_end<Attribute>() &&
4422 "Invalid slice element");
4423 newValues[linearizedPosition] = *sliceValuesIt;
4424 ++sliceValuesIt;
4425 } while (succeeded(
4426 incSlicePosition(currSlicePosition, sliceShape, sliceOffsets)));
4427
4428 auto newAttr = DenseElementsAttr::get(destTy, newValues);
4429 rewriter.replaceOpWithNewOp<arith::ConstantOp>(op, newAttr);
4430 return success();
4431 }
4432};
4433
4434} // namespace
4435
4436void vector::InsertStridedSliceOp::getCanonicalizationPatterns(
4437 RewritePatternSet &results, MLIRContext *context) {
4438 results.add<FoldInsertStridedSliceSplat, FoldInsertStridedSliceOfExtract,
4439 InsertStridedSliceConstantFolder>(context);
4440}
4441
4442OpFoldResult InsertStridedSliceOp::fold(FoldAdaptor adaptor) {
4443 if (getSourceVectorType() == getDestVectorType())
4444 return getValueToStore();
4445 return {};
4446}
4447
4448//===----------------------------------------------------------------------===//
4449// OuterProductOp
4450//===----------------------------------------------------------------------===//
4451
4452/// Build an op without mask, use the type of `acc` as the return type.
4453void OuterProductOp::build(OpBuilder &builder, OperationState &result,
4454 Value lhs, Value rhs, Value acc) {
4455 result.addOperands({lhs, rhs, acc});
4456 result.addTypes(acc.getType());
4457}
4458
4459void OuterProductOp::print(OpAsmPrinter &p) {
4460 p << " " << getLhs() << ", " << getRhs();
4461 if (getAcc()) {
4462 p << ", " << getAcc();
4463 SmallVector<NamedAttribute> attrs((*this)->getDiscardableAttrs());
4464 attrs.emplace_back(getKindAttrName(), getKindAttr());
4465 llvm::sort(attrs);
4466 p.printOptionalAttrDict(attrs);
4467 }
4468 p << " : " << getLhs().getType() << ", " << getRhs().getType();
4469}
4470
4471ParseResult OuterProductOp::parse(OpAsmParser &parser, OperationState &result) {
4472 SmallVector<OpAsmParser::UnresolvedOperand, 3> operandsInfo;
4473 Type tLHS, tRHS;
4474 if (parser.parseOperandList(operandsInfo) ||
4475 parser.parseOptionalAttrDict(result.attributes) ||
4476 parser.parseColonType(tLHS) || parser.parseComma() ||
4477 parser.parseType(tRHS))
4478 return failure();
4479 if (operandsInfo.size() < 2)
4480 return parser.emitError(parser.getNameLoc(),
4481 "expected at least 2 operands");
4482 VectorType vLHS = llvm::dyn_cast<VectorType>(tLHS);
4483 VectorType vRHS = llvm::dyn_cast<VectorType>(tRHS);
4484 if (!vLHS)
4485 return parser.emitError(parser.getNameLoc(),
4486 "expected vector type for operand #1");
4487 // The result type is built below from dimension 0 of the operands, which a
4488 // 0-d vector does not have. Only that case has to be caught here; a higher
4489 // rank still reaches the verifier, which rejects it with the same wording.
4490 if (vLHS.getRank() == 0)
4491 return parser.emitError(parser.getNameLoc(),
4492 "expected 1-d vector for operand #1");
4493 if (vRHS && vRHS.getRank() == 0)
4494 return parser.emitError(parser.getNameLoc(),
4495 "expected 1-d vector for operand #2");
4496
4497 VectorType resType;
4498 if (vRHS) {
4499 SmallVector<bool> scalableDimsRes{vLHS.getScalableDims()[0],
4500 vRHS.getScalableDims()[0]};
4501 resType = VectorType::get({vLHS.getDimSize(0), vRHS.getDimSize(0)},
4502 vLHS.getElementType(), scalableDimsRes);
4503 } else {
4504 // Scalar RHS operand
4505 SmallVector<bool> scalableDimsRes{vLHS.getScalableDims()[0]};
4506 resType = VectorType::get({vLHS.getDimSize(0)}, vLHS.getElementType(),
4507 scalableDimsRes);
4508 }
4509
4510 if (!result.attributes.get(OuterProductOp::getKindAttrName(result.name))) {
4511 result.attributes.append(
4512 OuterProductOp::getKindAttrName(result.name),
4513 CombiningKindAttr::get(result.getContext(),
4514 OuterProductOp::getDefaultKind()));
4515 }
4516
4517 return failure(
4518 parser.resolveOperand(operandsInfo[0], tLHS, result.operands) ||
4519 parser.resolveOperand(operandsInfo[1], tRHS, result.operands) ||
4520 (operandsInfo.size() > 2 &&
4521 parser.resolveOperand(operandsInfo[2], resType, result.operands)) ||
4522 parser.addTypeToList(resType, result.types));
4523}
4524
4525LogicalResult OuterProductOp::verify() {
4526 Type tRHS = getOperandTypeRHS();
4527 VectorType vLHS = getOperandVectorTypeLHS(),
4528 vRHS = llvm::dyn_cast<VectorType>(tRHS),
4529 vACC = getOperandVectorTypeACC(), vRES = getResultVectorType();
4530
4531 if (vLHS.getRank() != 1)
4532 return emitOpError("expected 1-d vector for operand #1");
4533
4534 if (vRHS) {
4535 // Proper OUTER operation.
4536 if (vRHS.getRank() != 1)
4537 return emitOpError("expected 1-d vector for operand #2");
4538 if (vRES.getRank() != 2)
4539 return emitOpError("expected 2-d vector result");
4540 if (vLHS.getDimSize(0) != vRES.getDimSize(0))
4541 return emitOpError("expected #1 operand dim to match result dim #1");
4542 if (vRHS.getDimSize(0) != vRES.getDimSize(1))
4543 return emitOpError("expected #2 operand dim to match result dim #2");
4544 if (vLHS.isScalable() && !vRHS.isScalable()) {
4545 // This restriction reflects what's currently supported in terms of
4546 // scalable vectors. However, we could relax this if there's a use case.
4547 return emitOpError(
4548 "expected either both or only #2 operand dim to be scalable");
4549 }
4550 } else {
4551 // An AXPY operation.
4552 if (vRES.getRank() != 1)
4553 return emitOpError("expected 1-d vector result");
4554 if (vLHS.getDimSize(0) != vRES.getDimSize(0))
4555 return emitOpError("expected #1 operand dim to match result dim #1");
4556 }
4557
4558 if (vACC && vACC != vRES)
4559 return emitOpError("expected operand #3 of same type as result type");
4560
4561 if (!getKindAttr()) {
4562 return emitOpError("expected 'kind' attribute of type CombiningKind (e.g. "
4563 "'vector.kind<add>')");
4564 }
4565
4566 // Verify supported combining kind.
4567 if (!isSupportedCombiningKind(getKind(), vRES.getElementType()))
4568 return emitOpError("unsupported outerproduct type");
4569
4570 return success();
4571}
4572
4573// MaskableOpInterface methods.
4574
4575/// Returns the mask type expected by this operation. Mostly used for
4576/// verification purposes. It requires the operation to be vectorized."
4577Type OuterProductOp::getExpectedMaskType() {
4578 auto vecType = this->getResultVectorType();
4579 return VectorType::get(vecType.getShape(),
4580 IntegerType::get(vecType.getContext(), /*width=*/1),
4581 vecType.getScalableDims());
4582}
4583
4584//===----------------------------------------------------------------------===//
4585// ExtractStridedSliceOp
4586//===----------------------------------------------------------------------===//
4587
4588// Inference works as follows:
4589// 1. Add 'sizes' from prefix of dims in 'offsets'.
4590// 2. Add sizes from 'vectorType' for remaining dims.
4591// Scalable flags are inherited from 'vectorType'.
4592static Type inferStridedSliceOpResultType(VectorType vectorType,
4593 ArrayAttr offsets, ArrayAttr sizes,
4594 ArrayAttr strides) {
4595 assert(offsets.size() == sizes.size() && offsets.size() == strides.size());
4597 shape.reserve(vectorType.getRank());
4598 unsigned idx = 0;
4599 for (unsigned e = offsets.size(); idx < e; ++idx)
4600 shape.push_back(llvm::cast<IntegerAttr>(sizes[idx]).getInt());
4601 for (unsigned e = vectorType.getShape().size(); idx < e; ++idx)
4602 shape.push_back(vectorType.getShape()[idx]);
4603
4604 return VectorType::get(shape, vectorType.getElementType(),
4605 vectorType.getScalableDims());
4606}
4607
4608void ExtractStridedSliceOp::build(OpBuilder &builder, OperationState &result,
4609 Value source, ArrayRef<int64_t> offsets,
4610 ArrayRef<int64_t> sizes,
4611 ArrayRef<int64_t> strides) {
4612 result.addOperands(source);
4613 auto offsetsAttr = getVectorSubscriptAttr(builder, offsets);
4614 auto sizesAttr = getVectorSubscriptAttr(builder, sizes);
4615 auto stridesAttr = getVectorSubscriptAttr(builder, strides);
4616 result.addTypes(
4617 inferStridedSliceOpResultType(llvm::cast<VectorType>(source.getType()),
4618 offsetsAttr, sizesAttr, stridesAttr));
4619 result.addAttribute(ExtractStridedSliceOp::getOffsetsAttrName(result.name),
4620 offsetsAttr);
4621 result.addAttribute(ExtractStridedSliceOp::getSizesAttrName(result.name),
4622 sizesAttr);
4623 result.addAttribute(ExtractStridedSliceOp::getStridesAttrName(result.name),
4624 stridesAttr);
4625}
4626
4627LogicalResult ExtractStridedSliceOp::verify() {
4628 auto type = getSourceVectorType();
4629 auto offsets = getOffsetsAttr();
4630 auto sizes = getSizesAttr();
4631 auto strides = getStridesAttr();
4632 if (offsets.size() != sizes.size() || offsets.size() != strides.size())
4633 return emitOpError(
4634 "expected offsets, sizes and strides attributes of same size");
4635
4636 auto shape = type.getShape();
4637 auto offName = getOffsetsAttrName();
4638 auto sizesName = getSizesAttrName();
4639 auto stridesName = getStridesAttrName();
4640 if (failed(
4641 isIntegerArrayAttrSmallerThanShape(*this, offsets, shape, offName)) ||
4642 failed(
4643 isIntegerArrayAttrSmallerThanShape(*this, sizes, shape, sizesName)) ||
4644 failed(isIntegerArrayAttrSmallerThanShape(*this, strides, shape,
4645 stridesName)) ||
4646 failed(
4647 isIntegerArrayAttrConfinedToShape(*this, offsets, shape, offName)) ||
4648 failed(isIntegerArrayAttrConfinedToShape(*this, sizes, shape, sizesName,
4649 /*halfOpen=*/false,
4650 /*min=*/1)) ||
4651 failed(isIntegerArrayAttrConfinedToRange(*this, strides, /*min=*/1,
4652 /*max=*/1, stridesName,
4653 /*halfOpen=*/false)) ||
4654 failed(isSumOfIntegerArrayAttrConfinedToShape(*this, offsets, sizes,
4655 shape, offName, sizesName,
4656 /*halfOpen=*/false)))
4657 return failure();
4658
4659 auto resultType = inferStridedSliceOpResultType(getSourceVectorType(),
4660 offsets, sizes, strides);
4661 if (getResult().getType() != resultType)
4662 return emitOpError("expected result type to be ") << resultType;
4663
4664 for (unsigned idx = 0; idx < sizes.size(); ++idx) {
4665 if (type.getScalableDims()[idx]) {
4666 auto inputDim = type.getShape()[idx];
4667 auto inputSize = llvm::cast<IntegerAttr>(sizes[idx]).getInt();
4668 if (inputDim != inputSize)
4669 return emitOpError("expected size at idx=")
4670 << idx
4671 << (" to match the corresponding base size from the input "
4672 "vector (")
4673 << inputSize << (" vs ") << inputDim << (")");
4674 }
4675 }
4676
4677 return success();
4678}
4679
4680// When the source of ExtractStrided comes from a chain of InsertStrided ops try
4681// to use the source of the InsertStrided ops if we can detect that the
4682// extracted vector is a subset of one of the vector inserted.
4683static LogicalResult
4684foldExtractStridedOpFromInsertChain(ExtractStridedSliceOp op) {
4685 // Helper to extract integer out of ArrayAttr.
4686 auto getElement = [](ArrayAttr array, int idx) {
4687 return llvm::cast<IntegerAttr>(array[idx]).getInt();
4688 };
4689 ArrayAttr extractOffsets = op.getOffsets();
4690 ArrayAttr extractStrides = op.getStrides();
4691 ArrayAttr extractSizes = op.getSizes();
4692 auto insertOp = op.getSource().getDefiningOp<InsertStridedSliceOp>();
4693 while (insertOp) {
4694 if (op.getSourceVectorType().getRank() !=
4695 insertOp.getSourceVectorType().getRank())
4696 return failure();
4697 ArrayAttr insertOffsets = insertOp.getOffsets();
4698 ArrayAttr insertStrides = insertOp.getStrides();
4699 // If the rank of extract is greater than the rank of insert, we are likely
4700 // extracting a partial chunk of the vector inserted.
4701 if (extractOffsets.size() > insertOffsets.size())
4702 return failure();
4703 bool patialoverlap = false;
4704 bool disjoint = false;
4705 SmallVector<int64_t, 4> offsetDiffs;
4706 for (unsigned dim = 0, e = extractOffsets.size(); dim < e; ++dim) {
4707 if (getElement(extractStrides, dim) != getElement(insertStrides, dim))
4708 return failure();
4709 int64_t start = getElement(insertOffsets, dim);
4710 int64_t end = start + insertOp.getSourceVectorType().getDimSize(dim);
4711 int64_t offset = getElement(extractOffsets, dim);
4712 int64_t size = getElement(extractSizes, dim);
4713 // Check if the start of the extract offset is in the interval inserted.
4714 if (start <= offset && offset < end) {
4715 // If the extract interval overlaps but is not fully included we may
4716 // have a partial overlap that will prevent any folding.
4717 if (offset + size > end)
4718 patialoverlap = true;
4719 offsetDiffs.push_back(offset - start);
4720 continue;
4721 }
4722 disjoint = true;
4723 break;
4724 }
4725 // The extract element chunk is a subset of the insert element.
4726 if (!disjoint && !patialoverlap) {
4727 op.setOperand(insertOp.getValueToStore());
4728 // OpBuilder is only used as a helper to build an I64ArrayAttr.
4729 OpBuilder b(op.getContext());
4730 op.setOffsetsAttr(b.getI64ArrayAttr(offsetDiffs));
4731 return success();
4732 }
4733 // If the chunk extracted is disjoint from the chunk inserted, keep looking
4734 // in the insert chain.
4735 if (disjoint)
4736 insertOp = insertOp.getDest().getDefiningOp<InsertStridedSliceOp>();
4737 else {
4738 // The extracted vector partially overlap the inserted vector, we cannot
4739 // fold.
4740 return failure();
4741 }
4742 }
4743 return failure();
4744}
4745
4746// ExtractStridedSliceOp(non-splat ConstantOp) -> ConstantOp.
4747static OpFoldResult
4749 Attribute foldInput) {
4750
4751 auto dense = llvm::dyn_cast_if_present<DenseElementsAttr>(foldInput);
4752 if (!dense)
4753 return {};
4754
4755 // TODO: Handle non-unit strides when they become available.
4756 if (op.hasNonUnitStrides())
4757 return {};
4758
4759 VectorType sourceVecTy = op.getSourceVectorType();
4760 ArrayRef<int64_t> sourceShape = sourceVecTy.getShape();
4761 SmallVector<int64_t, 4> sourceStrides = computeStrides(sourceShape);
4762
4763 VectorType sliceVecTy = op.getType();
4764 ArrayRef<int64_t> sliceShape = sliceVecTy.getShape();
4765 int64_t rank = sliceVecTy.getRank();
4766
4767 // Expand offsets and sizes to match the vector rank.
4768 SmallVector<int64_t, 4> offsets(rank, 0);
4769 copy(getI64SubArray(op.getOffsets()), offsets.begin());
4770
4771 SmallVector<int64_t, 4> sizes(sourceShape);
4772 copy(getI64SubArray(op.getSizes()), sizes.begin());
4773
4774 // Calculate the slice elements by enumerating all slice positions and
4775 // linearizing them. The enumeration order is lexicographic which yields a
4776 // sequence of monotonically increasing linearized position indices.
4777 const auto denseValuesBegin = dense.value_begin<Attribute>();
4778 SmallVector<Attribute> sliceValues;
4779 sliceValues.reserve(sliceVecTy.getNumElements());
4780 SmallVector<int64_t> currSlicePosition(offsets.begin(), offsets.end());
4781 do {
4782 int64_t linearizedPosition = linearize(currSlicePosition, sourceStrides);
4783 assert(linearizedPosition < sourceVecTy.getNumElements() &&
4784 "Invalid index");
4785 sliceValues.push_back(*(denseValuesBegin + linearizedPosition));
4786 } while (succeeded(incSlicePosition(currSlicePosition, sliceShape, offsets)));
4787
4788 assert(static_cast<int64_t>(sliceValues.size()) ==
4789 sliceVecTy.getNumElements() &&
4790 "Invalid number of slice elements");
4791 return DenseElementsAttr::get(sliceVecTy, sliceValues);
4792}
4793
4794OpFoldResult ExtractStridedSliceOp::fold(FoldAdaptor adaptor) {
4795 if (getSourceVectorType() == getResult().getType())
4796 return getSource();
4797 if (succeeded(foldExtractStridedOpFromInsertChain(*this)))
4798 return getResult();
4799
4800 // ExtractStridedSliceOp(splat ConstantOp) -> ConstantOp.
4801 if (auto splat =
4802 llvm::dyn_cast_if_present<SplatElementsAttr>(adaptor.getSource()))
4803 return DenseElementsAttr::get(getType(), splat.getSplatValue<Attribute>());
4804
4805 // ExtractStridedSliceOp(non-splat ConstantOp) -> ConstantOp.
4806 return foldExtractStridedSliceNonSplatConstant(*this, adaptor.getSource());
4807}
4808
4809void ExtractStridedSliceOp::getOffsets(SmallVectorImpl<int64_t> &results) {
4810 populateFromInt64AttrArray(getOffsets(), results);
4811}
4812
4813namespace {
4814
4815// Pattern to rewrite nested ExtractStridedSliceOp into a single one.
4816//
4817// Example:
4818//
4819// %0 = vector.extract_strided_slice %arg0
4820// {offsets = [1, 2], sizes = [3, 4], strides = [1, 1]}
4821// : vector<4x8x16xf32> to vector<3x4x16xf32>
4822// %1 = vector.extract_strided_slice %0
4823// {offsets = [0, 1], sizes = [2, 2], strides = [1, 1]}
4824// : vector<3x4x16xf32> to vector<2x2x16xf32>
4825//
4826// to
4827//
4828// %1 = vector.extract_strided_slice %arg0
4829// {offsets = [1, 3], sizes = [2, 2], strides = [1, 1]}
4830// : vector<4x8x16xf32> to vector<2x2x16xf32>
4831class StridedSliceFolder final
4832 : public OpRewritePattern<ExtractStridedSliceOp> {
4833public:
4834 using OpRewritePattern<ExtractStridedSliceOp>::OpRewritePattern;
4835
4836 LogicalResult matchAndRewrite(ExtractStridedSliceOp secondOp,
4837 PatternRewriter &rewriter) const override {
4838 auto firstOp = secondOp.getSource().getDefiningOp<ExtractStridedSliceOp>();
4839 if (!firstOp)
4840 return failure();
4841
4842 if (secondOp.hasNonUnitStrides() || firstOp.hasNonUnitStrides())
4843 return failure();
4844
4845 SmallVector<int64_t> firstOffsets = getI64SubArray(firstOp.getOffsets());
4846 SmallVector<int64_t> firstSizes = getI64SubArray(firstOp.getSizes());
4847 SmallVector<int64_t> secondOffsets = getI64SubArray(secondOp.getOffsets());
4848 SmallVector<int64_t> secondSizes = getI64SubArray(secondOp.getSizes());
4849
4850 unsigned newRank = std::max(firstOffsets.size(), secondOffsets.size());
4851 SmallVector<int64_t> combinedOffsets(newRank, 0);
4852 SmallVector<int64_t> combinedSizes(newRank);
4853 ArrayRef<int64_t> firstSourceShape =
4854 firstOp.getSourceVectorType().getShape();
4855 for (unsigned i = 0; i < newRank; ++i) {
4856 int64_t off1 = (i < firstOffsets.size()) ? firstOffsets[i] : 0;
4857 int64_t off2 = (i < secondOffsets.size()) ? secondOffsets[i] : 0;
4858 combinedOffsets[i] = off1 + off2;
4859
4860 if (i < secondSizes.size()) {
4861 combinedSizes[i] = secondSizes[i];
4862 } else if (i < firstSizes.size()) {
4863 combinedSizes[i] = firstSizes[i];
4864 } else {
4865 combinedSizes[i] = firstSourceShape[i];
4866 }
4867 }
4868
4869 SmallVector<int64_t> combinedStrides(newRank, 1);
4870 rewriter.replaceOpWithNewOp<ExtractStridedSliceOp>(
4871 secondOp, firstOp.getSource(), combinedOffsets, combinedSizes,
4872 combinedStrides);
4873 return success();
4874 }
4875};
4876
4877// Pattern to rewrite an ExtractStridedSliceOp(CreateMaskOp) to
4878// CreateMaskOp.
4879//
4880// Example:
4881//
4882// %mask = vector.create_mask %ub : vector<16xi1>
4883// %slice = vector.extract_strided_slice [%offset] [8] [1]
4884//
4885// to
4886//
4887// %new_ub = arith.subi %ub, %offset
4888// %mask = vector.create_mask %new_ub : vector<8xi1>
4889class StridedSliceCreateMaskFolder final
4890 : public OpRewritePattern<ExtractStridedSliceOp> {
4891 using Base::Base;
4892
4893public:
4894 LogicalResult matchAndRewrite(ExtractStridedSliceOp extractStridedSliceOp,
4895 PatternRewriter &rewriter) const override {
4896 Location loc = extractStridedSliceOp.getLoc();
4897 // Return if 'extractStridedSliceOp' operand is not defined by a
4898 // CreateMaskOp.
4899 auto createMaskOp =
4900 extractStridedSliceOp.getSource().getDefiningOp<CreateMaskOp>();
4901 if (!createMaskOp)
4902 return failure();
4903 // Return if 'extractStridedSliceOp' has non-unit strides.
4904 if (extractStridedSliceOp.hasNonUnitStrides())
4905 return failure();
4906 // Gather constant mask dimension sizes.
4907 SmallVector<Value> maskDimSizes(createMaskOp.getOperands());
4908 // Gather strided slice offsets and sizes.
4909 SmallVector<int64_t> sliceOffsets;
4910 populateFromInt64AttrArray(extractStridedSliceOp.getOffsets(),
4911 sliceOffsets);
4912 SmallVector<int64_t> sliceSizes;
4913 populateFromInt64AttrArray(extractStridedSliceOp.getSizes(), sliceSizes);
4914
4915 // Compute slice of vector mask region.
4916 SmallVector<Value> sliceMaskDimSizes;
4917 sliceMaskDimSizes.reserve(maskDimSizes.size());
4918 // sliceOffsets.size() <= maskDimSizes.size(), so we use llvm::zip and
4919 // only iterate on the leading dim sizes. The tail accounts for the
4920 // remaining dim sizes.
4921 for (auto [maskDimSize, sliceOffset, sliceSize] :
4922 llvm::zip(maskDimSizes, sliceOffsets, sliceSizes)) {
4923 // No need to clamp on min/max values, because create_mask has clamping
4924 // semantics, i.e. the sliceMaskDimSize is allowed to be negative or
4925 // greater than the vector dim size.
4926 IntegerAttr offsetAttr =
4927 rewriter.getIntegerAttr(maskDimSize.getType(), sliceOffset);
4928 Value offset = arith::ConstantOp::create(rewriter, loc, offsetAttr);
4929 Value sliceMaskDimSize =
4930 arith::SubIOp::create(rewriter, loc, maskDimSize, offset);
4931 sliceMaskDimSizes.push_back(sliceMaskDimSize);
4932 }
4933 // Add unchanged dimensions.
4934 llvm::append_range(
4935 sliceMaskDimSizes,
4936 llvm::drop_begin(maskDimSizes, sliceMaskDimSizes.size()));
4937 // Replace 'extractStridedSliceOp' with CreateMaskOp with sliced mask
4938 // region.
4939 rewriter.replaceOpWithNewOp<CreateMaskOp>(
4940 extractStridedSliceOp, extractStridedSliceOp.getResult().getType(),
4941 sliceMaskDimSizes);
4942 return success();
4943 }
4944};
4945
4946// Pattern to rewrite an ExtractStridedSliceOp(ConstantMaskOp) to
4947// ConstantMaskOp.
4948class StridedSliceConstantMaskFolder final
4949 : public OpRewritePattern<ExtractStridedSliceOp> {
4950public:
4951 using Base::Base;
4952
4953 LogicalResult matchAndRewrite(ExtractStridedSliceOp extractStridedSliceOp,
4954 PatternRewriter &rewriter) const override {
4955 // Return if 'extractStridedSliceOp' operand is not defined by a
4956 // ConstantMaskOp.
4957 auto *defOp = extractStridedSliceOp.getSource().getDefiningOp();
4958 auto constantMaskOp = dyn_cast_or_null<ConstantMaskOp>(defOp);
4959 if (!constantMaskOp)
4960 return failure();
4961 // Return if 'extractStridedSliceOp' has non-unit strides.
4962 if (extractStridedSliceOp.hasNonUnitStrides())
4963 return failure();
4964 // Gather constant mask dimension sizes.
4965 ArrayRef<int64_t> maskDimSizes = constantMaskOp.getMaskDimSizes();
4966 // Gather strided slice offsets and sizes.
4967 SmallVector<int64_t> sliceOffsets;
4968 populateFromInt64AttrArray(extractStridedSliceOp.getOffsets(),
4969 sliceOffsets);
4970 SmallVector<int64_t> sliceSizes;
4971 populateFromInt64AttrArray(extractStridedSliceOp.getSizes(), sliceSizes);
4972
4973 // Compute slice of vector mask region.
4974 SmallVector<int64_t> sliceMaskDimSizes;
4975 sliceMaskDimSizes.reserve(maskDimSizes.size());
4976 for (auto [maskDimSize, sliceOffset, sliceSize] :
4977 llvm::zip(maskDimSizes, sliceOffsets, sliceSizes)) {
4978 int64_t sliceMaskDimSize = std::max(
4979 static_cast<int64_t>(0),
4980 std::min(sliceOffset + sliceSize, maskDimSize) - sliceOffset);
4981 sliceMaskDimSizes.push_back(sliceMaskDimSize);
4982 }
4983 // Add unchanged dimensions.
4984 if (sliceMaskDimSizes.size() < maskDimSizes.size())
4985 for (size_t i = sliceMaskDimSizes.size(); i < maskDimSizes.size(); ++i)
4986 sliceMaskDimSizes.push_back(maskDimSizes[i]);
4987 // If any of 'sliceMaskDimSizes' are zero, then set all to zero (masked
4988 // region is a conjunction of mask dim intervals).
4989 if (llvm::is_contained(sliceMaskDimSizes, 0))
4990 sliceMaskDimSizes.assign(maskDimSizes.size(), 0);
4991
4992 // Replace 'extractStridedSliceOp' with ConstantMaskOp with sliced mask
4993 // region.
4994 rewriter.replaceOpWithNewOp<ConstantMaskOp>(
4995 extractStridedSliceOp, extractStridedSliceOp.getResult().getType(),
4996 sliceMaskDimSizes);
4997 return success();
4998 }
4999};
5000
5001// Pattern to rewrite an ExtractStridedSliceOp(BroadcastOp) to
5002// BroadcastOp(ExtractStrideSliceOp).
5003class StridedSliceBroadcast final
5004 : public OpRewritePattern<ExtractStridedSliceOp> {
5005public:
5006 using Base::Base;
5007
5008 LogicalResult matchAndRewrite(ExtractStridedSliceOp op,
5009 PatternRewriter &rewriter) const override {
5010 auto broadcast = op.getSource().getDefiningOp<BroadcastOp>();
5011 if (!broadcast)
5012 return failure();
5013 auto srcVecType =
5014 llvm::dyn_cast<VectorType>(broadcast.getSource().getType());
5015 unsigned srcRank = srcVecType ? srcVecType.getRank() : 0;
5016 auto dstVecType = llvm::cast<VectorType>(op.getType());
5017 unsigned dstRank = dstVecType.getRank();
5018 unsigned rankDiff = dstRank - srcRank;
5019 // Source dimensions can be broadcasted (1 -> n with n > 1) or sliced
5020 // (n -> m with n > m). If they are originally both broadcasted *and*
5021 // sliced, this can be simplified to just broadcasting.
5022 bool needsSlice = false;
5023 for (unsigned i = 0; i < srcRank; i++) {
5024 if (srcVecType.getDimSize(i) != 1 &&
5025 srcVecType.getDimSize(i) != dstVecType.getDimSize(i + rankDiff)) {
5026 needsSlice = true;
5027 break;
5028 }
5029 }
5030 Value source = broadcast.getSource();
5031 if (needsSlice) {
5032 SmallVector<int64_t> offsets =
5033 getI64SubArray(op.getOffsets(), /*dropFront=*/rankDiff);
5034 SmallVector<int64_t> sizes =
5035 getI64SubArray(op.getSizes(), /*dropFront=*/rankDiff);
5036 // Slice attributes (i.e. offsets, sizes, etc) are only required for the
5037 // leading/prefix source dimensions. This is why we use
5038 // `offset.size()` instead of `srcRank` below.
5039 for (unsigned i = 0; i < offsets.size(); i++) {
5040 if (srcVecType.getDimSize(i) == 1) {
5041 // In case this dimension was broadcasted *and* sliced, the offset
5042 // and size need to be updated now that there is no broadcast before
5043 // the slice.
5044 offsets[i] = 0;
5045 sizes[i] = 1;
5046 }
5047 }
5048 source = ExtractStridedSliceOp::create(
5049 rewriter, op->getLoc(), source, offsets, sizes,
5050 getI64SubArray(op.getStrides(), /*dropFront=*/rankDiff));
5051 }
5052 rewriter.replaceOpWithNewOp<BroadcastOp>(op, op.getType(), source);
5053 return success();
5054 }
5055};
5056
5057/// Rewrite extract_strided_slice(splat-like(v)) with broadcast(v).
5058class StridedSliceSplat final : public OpRewritePattern<ExtractStridedSliceOp> {
5059public:
5060 using Base::Base;
5061
5062 LogicalResult matchAndRewrite(ExtractStridedSliceOp op,
5063 PatternRewriter &rewriter) const override {
5064
5065 Value splat = getScalarSplatSource(op.getSource());
5066 if (!splat)
5067 return failure();
5068 rewriter.replaceOpWithNewOp<BroadcastOp>(op, op.getType(), splat);
5069 return success();
5070 }
5071};
5072
5073/// Pattern to rewrite simple cases of N-D extract_strided_slice, where the
5074/// slice is contiguous, into extract and shape_cast.
5075///
5076/// Example:
5077/// Before:
5078/// %1 = vector.extract_strided_slice %arg0 {
5079/// offsets = [0, 0, 0, 0, 0],
5080/// sizes = [1, 1, 1, 1, 8],
5081/// strides = [1, 1, 1, 1, 1]
5082/// } : vector<8x1x1x2x8xi8> to vector<1x1x1x1x8xi8>
5083/// After:
5084/// %0 = vector.extract %arg0[0, 0, 0, 0]
5085/// : vector<8xi8> from vector<8x1x1x2x8xi8>
5086/// %1 = vector.shape_cast %0
5087/// : vector<8xi8> to vector<1x1x1x1x8xi8>
5088///
5089class ContiguousExtractStridedSliceToExtract final
5090 : public OpRewritePattern<ExtractStridedSliceOp> {
5091public:
5092 using Base::Base;
5093
5094 LogicalResult matchAndRewrite(ExtractStridedSliceOp op,
5095 PatternRewriter &rewriter) const override {
5096 if (op.hasNonUnitStrides())
5097 return failure();
5098 Value source = op.getOperand();
5099 auto sourceType = cast<VectorType>(source.getType());
5100 if (sourceType.isScalable() || sourceType.getRank() == 0)
5101 return failure();
5102
5103 // Compute the number of offsets to pass to ExtractOp::build. That is the
5104 // difference between the source rank and the desired slice rank. We walk
5105 // the dimensions from innermost out, and stop when the next slice dimension
5106 // is not full-size.
5107 SmallVector<int64_t> sizes = getI64SubArray(op.getSizes());
5108 int numOffsets;
5109 for (numOffsets = sizes.size(); numOffsets > 0; --numOffsets) {
5110 if (sizes[numOffsets - 1] != sourceType.getDimSize(numOffsets - 1))
5111 break;
5112 }
5113
5114 // If the created extract op would have no offsets, then this whole
5115 // extract_strided_slice is the identity and should have been handled by
5116 // other canonicalizations.
5117 if (numOffsets == 0)
5118 return failure();
5119
5120 // If not even the inner-most dimension is full-size, this op can't be
5121 // rewritten as an ExtractOp.
5122 if (numOffsets == sourceType.getRank() &&
5123 static_cast<int>(sizes.size()) == sourceType.getRank())
5124 return failure();
5125
5126 // The outer dimensions must have unit size.
5127 for (int i = 0; i < numOffsets; ++i) {
5128 if (sizes[i] != 1)
5129 return failure();
5130 }
5131
5132 // Avoid generating slices that have leading unit dimensions. The shape_cast
5133 // op that we create below would take bad generic fallback patterns
5134 // (ShapeCastOpRewritePattern).
5135 while (numOffsets < static_cast<int>(sizes.size()) - 1 &&
5136 sizes[numOffsets] == 1) {
5137 ++numOffsets;
5138 }
5139
5140 SmallVector<int64_t> offsets = getI64SubArray(op.getOffsets());
5141 auto extractOffsets = ArrayRef(offsets).take_front(numOffsets);
5142 Value extract = vector::ExtractOp::create(rewriter, op->getLoc(), source,
5143 extractOffsets);
5144 rewriter.replaceOpWithNewOp<vector::ShapeCastOp>(op, op.getType(), extract);
5145 return success();
5146 }
5147};
5148
5149} // namespace
5150
5151void ExtractStridedSliceOp::getCanonicalizationPatterns(
5152 RewritePatternSet &results, MLIRContext *context) {
5153 // Pattern to rewrite a ExtractStridedSliceOp(ConstantMaskOp) ->
5154 // ConstantMaskOp and ExtractStridedSliceOp(ConstantOp) -> ConstantOp.
5155 results.add<StridedSliceFolder, StridedSliceCreateMaskFolder,
5156 StridedSliceConstantMaskFolder, StridedSliceBroadcast,
5157 StridedSliceSplat, ContiguousExtractStridedSliceToExtract>(
5158 context);
5159}
5160
5161//===----------------------------------------------------------------------===//
5162// TransferReadOp
5163//===----------------------------------------------------------------------===//
5164
5165/// 1. Builder that sets padding to zero and an empty mask (variant with attrs).
5166/// If `padding` is null, a poison value is used.
5167void TransferReadOp::build(OpBuilder &builder, OperationState &result,
5168 VectorType vectorType, Value source,
5169 ValueRange indices, std::optional<Value> padding,
5170 AffineMapAttr permutationMapAttr,
5171 /*optional*/ ArrayAttr inBoundsAttr) {
5172
5173 Type elemType = llvm::cast<ShapedType>(source.getType()).getElementType();
5174 if (!padding)
5175 padding = ub::PoisonOp::create(builder, result.location, elemType);
5176 // Delegate to the most general builder (see
5177 // `mlir/Dialect/Vector/IR/VectorOps.cpp.inc`)
5178 build(builder, result, vectorType, source, indices, permutationMapAttr,
5179 *padding, /*mask=*/Value(), inBoundsAttr);
5180}
5181
5182/// 2. Builder that sets padding to zero and an empty mask (variant without
5183/// attrs).
5184/// If `padding` is null, a poison value is used.
5185/// If `permutationMap` is null, a minor identity map is used.
5186/// If `inBounds` is null, an empty mask is used.
5187void TransferReadOp::build(OpBuilder &builder, OperationState &result,
5188 VectorType vectorType, Value source,
5189 ValueRange indices, std::optional<Value> padding,
5190 AffineMap permutationMap,
5191 std::optional<ArrayRef<bool>> inBounds) {
5192 if (!permutationMap)
5193 permutationMap = getTransferMinorIdentityMap(
5194 llvm::cast<ShapedType>(source.getType()), vectorType);
5195 auto permutationMapAttr = AffineMapAttr::get(permutationMap);
5196 auto inBoundsAttr = (inBounds && !inBounds.value().empty())
5197 ? builder.getBoolArrayAttr(inBounds.value())
5198 : builder.getBoolArrayAttr(
5199 SmallVector<bool>(vectorType.getRank(), false));
5200 // Delegate to Builder 1
5201 build(builder, result, vectorType, source, indices, padding,
5202 permutationMapAttr, inBoundsAttr);
5203}
5204
5205/// 3. Builder that sets permutation map to 'getMinorIdentityMap'.
5206/// If `padding` is null, a poison value is used.
5207/// If `inBounds` is null, an empty mask is used.
5208void TransferReadOp::build(OpBuilder &builder, OperationState &result,
5209 VectorType vectorType, Value source,
5210 ValueRange indices, std::optional<Value> padding,
5211 std::optional<ArrayRef<bool>> inBounds) {
5212 // Delegate to Builder 2
5213 build(builder, result, vectorType, source, indices, padding,
5214 /*permutationMap=*/AffineMap(), inBounds);
5215}
5216
5217template <typename EmitFun>
5218static LogicalResult verifyPermutationMap(AffineMap permutationMap,
5219 EmitFun emitOpError) {
5220 SmallVector<bool, 8> seen(permutationMap.getNumInputs(), false);
5221 for (auto expr : permutationMap.getResults()) {
5222 auto dim = dyn_cast<AffineDimExpr>(expr);
5223 auto zero = dyn_cast<AffineConstantExpr>(expr);
5224 if (zero) {
5225 if (zero.getValue() != 0) {
5226 return emitOpError(
5227 "requires a projected permutation_map (at most one dim or the zero "
5228 "constant can appear in each result)");
5229 }
5230 continue;
5231 }
5232 if (!dim) {
5233 return emitOpError("requires a projected permutation_map (at most one "
5234 "dim or the zero constant can appear in each result)");
5235 }
5236 if (seen[dim.getPosition()]) {
5237 return emitOpError(
5238 "requires a permutation_map that is a permutation (found one dim "
5239 "used more than once)");
5240 }
5241 seen[dim.getPosition()] = true;
5242 }
5243 return success();
5244}
5245
5246static LogicalResult
5247verifyTransferOp(VectorTransferOpInterface op, ShapedType shapedType,
5248 VectorType vectorType, VectorType maskType,
5249 VectorType inferredMaskType, AffineMap permutationMap,
5250 ArrayAttr inBounds) {
5251 if (op->hasDiscardableAttr("masked")) {
5252 return op->emitOpError("masked attribute has been removed. "
5253 "Use in_bounds instead.");
5254 }
5255
5256 if (!llvm::isa<MemRefType, RankedTensorType>(shapedType))
5257 return op->emitOpError(
5258 "requires source to be a memref or ranked tensor type");
5259
5260 auto elementType = shapedType.getElementType();
5261 DataLayout dataLayout = DataLayout::closest(op);
5262 if (auto vectorElementType = llvm::dyn_cast<VectorType>(elementType)) {
5263 // Memref or tensor has vector element type.
5264 unsigned sourceVecSize =
5265 dataLayout.getTypeSizeInBits(vectorElementType.getElementType()) *
5266 vectorElementType.getShape().back();
5267 unsigned resultVecSize =
5268 dataLayout.getTypeSizeInBits(vectorType.getElementType()) *
5269 vectorType.getShape().back();
5270 if (resultVecSize % sourceVecSize != 0)
5271 return op->emitOpError(
5272 "requires the bitwidth of the minor 1-D vector to be an integral "
5273 "multiple of the bitwidth of the minor 1-D vector of the source");
5274
5275 unsigned sourceVecEltRank = vectorElementType.getRank();
5276 unsigned resultVecRank = vectorType.getRank();
5277 if (sourceVecEltRank > resultVecRank)
5278 return op->emitOpError(
5279 "requires source vector element and vector result ranks to match.");
5280 unsigned rankOffset = resultVecRank - sourceVecEltRank;
5281 // Check that permutation map results match 'rankOffset' of vector type.
5282 if (permutationMap.getNumResults() != rankOffset)
5283 return op->emitOpError("requires a permutation_map with result dims of "
5284 "the same rank as the vector type");
5285
5286 if (maskType)
5287 return op->emitOpError("does not support masks with vector element type");
5288 } else {
5289 // Memref or tensor has scalar element type.
5290 unsigned minorSize =
5291 vectorType.getRank() == 0 ? 1 : vectorType.getShape().back();
5292 unsigned resultVecSize =
5293 dataLayout.getTypeSizeInBits(vectorType.getElementType()) * minorSize;
5294 if (resultVecSize % dataLayout.getTypeSizeInBits(elementType) != 0)
5295 return op->emitOpError(
5296 "requires the bitwidth of the minor 1-D vector to be an integral "
5297 "multiple of the bitwidth of the source element type");
5298
5299 // Check that permutation map results match rank of vector type.
5300 if (permutationMap.getNumResults() != vectorType.getRank())
5301 return op->emitOpError("requires a permutation_map with result dims of "
5302 "the same rank as the vector type");
5303 }
5304
5305 if (permutationMap.getNumSymbols() != 0)
5306 return op->emitOpError("requires permutation_map without symbols");
5307
5308 if (permutationMap.getNumInputs() != shapedType.getRank())
5309 return op->emitOpError("requires a permutation_map with input dims of the "
5310 "same rank as the source type");
5311
5312 if (maskType && maskType != inferredMaskType)
5313 return op->emitOpError("inferred mask type (")
5314 << inferredMaskType << ") and mask operand type (" << maskType
5315 << ") don't match";
5316
5317 if (permutationMap.getNumResults() != static_cast<int64_t>(inBounds.size()))
5318 return op->emitOpError("expects the in_bounds attr of same rank "
5319 "as permutation_map results: ")
5320 << AffineMapAttr::get(permutationMap)
5321 << " vs inBounds of size: " << inBounds.size();
5322
5323 return success();
5324}
5325
5326static void printTransferAttrs(OpAsmPrinter &p, VectorTransferOpInterface op) {
5327 SmallVector<NamedAttribute> attrs(op->getDiscardableAttrs());
5328 // Elide in_bounds attribute if all dims are out-of-bounds.
5329 if (llvm::any_of(op.getInBoundsValues(), [](bool b) { return b; }))
5330 attrs.emplace_back(op.getInBoundsAttrName(), op.getInBounds());
5331 if (!op.getPermutationMap().isMinorIdentity())
5332 attrs.emplace_back(op.getPermutationMapAttrName(),
5333 AffineMapAttr::get(op.getPermutationMap()));
5334 llvm::sort(attrs);
5335 p.printOptionalAttrDict(attrs);
5336}
5337
5338void TransferReadOp::print(OpAsmPrinter &p) {
5339 p << " " << getBase() << "[" << getIndices() << "], " << getPadding();
5340 if (getMask())
5341 p << ", " << getMask();
5342 printTransferAttrs(p, *this);
5343 p << " : " << getShapedType() << ", " << getVectorType();
5344}
5345
5346VectorType mlir::vector::inferTransferOpMaskType(VectorType vecType,
5347 AffineMap permMap) {
5348 auto i1Type = IntegerType::get(permMap.getContext(), 1);
5349 AffineMap invPermMap = inversePermutation(compressUnusedDims(permMap));
5350 assert(invPermMap && "Inversed permutation map couldn't be computed");
5351 SmallVector<int64_t, 8> maskShape = invPermMap.compose(vecType.getShape());
5352
5353 // The MaskOp specification doesn't support 0-D vectors at the moment. Turn a
5354 // 0-D mask into a single-element 1-D mask.
5355 if (maskShape.empty())
5356 maskShape.push_back(1);
5357
5358 SmallVector<bool> scalableDims =
5359 applyPermutationMap(invPermMap, vecType.getScalableDims());
5360
5361 return VectorType::get(maskShape, i1Type, scalableDims);
5362}
5363
5364ParseResult TransferReadOp::parse(OpAsmParser &parser, OperationState &result) {
5365 auto &builder = parser.getBuilder();
5366 SMLoc typesLoc;
5372 // Parsing with support for paddingValue.
5373 if (parser.parseOperand(sourceInfo) ||
5375 parser.parseComma() || parser.parseOperand(paddingInfo))
5376 return failure();
5377 ParseResult hasMask = parser.parseOptionalComma();
5378 if (hasMask.succeeded()) {
5379 if (parser.parseOperand(maskInfo))
5380 return failure();
5381 }
5382 if (parser.parseOptionalAttrDict(result.attributes) ||
5383 parser.getCurrentLocation(&typesLoc) || parser.parseColonTypeList(types))
5384 return failure();
5385 if (types.size() != 2)
5386 return parser.emitError(typesLoc, "requires two types");
5387 auto indexType = builder.getIndexType();
5388 auto shapedType = llvm::dyn_cast<ShapedType>(types[0]);
5389 if (!shapedType || !llvm::isa<MemRefType, RankedTensorType>(shapedType))
5390 return parser.emitError(typesLoc, "requires memref or ranked tensor type");
5391 VectorType vectorType = llvm::dyn_cast<VectorType>(types[1]);
5392 if (!vectorType)
5393 return parser.emitError(typesLoc, "requires vector type");
5394 auto permMapAttrName = TransferReadOp::getPermutationMapAttrName(result.name);
5395 Attribute permMapAttr = result.attributes.get(permMapAttrName);
5396 AffineMap permMap;
5397 if (!permMapAttr) {
5398 if (shapedType.getRank() <
5399 getEffectiveVectorRankForXferOp(shapedType, vectorType))
5400 return parser.emitError(typesLoc,
5401 "expected a custom permutation_map when "
5402 "rank(source) != rank(destination)");
5403 permMap = getTransferMinorIdentityMap(shapedType, vectorType);
5404 result.attributes.set(permMapAttrName, AffineMapAttr::get(permMap));
5405 } else {
5406 permMap = llvm::cast<AffineMapAttr>(permMapAttr).getValue();
5407 }
5408 auto inBoundsAttrName = TransferReadOp::getInBoundsAttrName(result.name);
5409 Attribute inBoundsAttr = result.attributes.get(inBoundsAttrName);
5410 if (!inBoundsAttr) {
5411 result.addAttribute(inBoundsAttrName,
5412 builder.getBoolArrayAttr(
5413 SmallVector<bool>(permMap.getNumResults(), false)));
5414 }
5415 if (parser.resolveOperand(sourceInfo, shapedType, result.operands) ||
5416 parser.resolveOperands(indexInfo, indexType, result.operands) ||
5417 parser.resolveOperand(paddingInfo, shapedType.getElementType(),
5418 result.operands))
5419 return failure();
5420 if (hasMask.succeeded()) {
5421 if (llvm::dyn_cast<VectorType>(shapedType.getElementType()))
5422 return parser.emitError(
5423 maskInfo.location, "does not support masks with vector element type");
5424 if (vectorType.getRank() != permMap.getNumResults()) {
5425 return parser.emitError(typesLoc,
5426 "expected the same rank for the vector and the "
5427 "results of the permutation map");
5428 }
5429 // Instead of adding the mask type as an op type, compute it based on the
5430 // vector type and the permutation map (to keep the type signature small).
5431 auto maskType = inferTransferOpMaskType(vectorType, permMap);
5432 if (parser.resolveOperand(maskInfo, maskType, result.operands))
5433 return failure();
5434 }
5435 result.addAttribute(TransferReadOp::getOperandSegmentSizeAttr(),
5436 builder.getDenseI32ArrayAttr(
5437 {1, static_cast<int32_t>(indexInfo.size()), 1,
5438 static_cast<int32_t>(hasMask.succeeded())}));
5439 return parser.addTypeToList(vectorType, result.types);
5440}
5441
5442LogicalResult TransferReadOp::verify() {
5443 // Consistency of elemental types in source and vector.
5444 ShapedType shapedType = getShapedType();
5445 VectorType vectorType = getVectorType();
5446 VectorType maskType = getMaskType();
5447 auto paddingType = getPadding().getType();
5448 auto permutationMap = getPermutationMap();
5449 VectorType inferredMaskType =
5450 maskType ? inferTransferOpMaskType(vectorType, permutationMap)
5451 : VectorType();
5452 auto sourceElementType = shapedType.getElementType();
5453
5454 if (static_cast<int64_t>(getIndices().size()) != shapedType.getRank())
5455 return emitOpError("requires ") << shapedType.getRank() << " indices";
5456
5457 if (failed(verifyTransferOp(cast<VectorTransferOpInterface>(getOperation()),
5458 shapedType, vectorType, maskType,
5459 inferredMaskType, permutationMap, getInBounds())))
5460 return failure();
5461
5462 if (auto sourceVectorElementType =
5463 llvm::dyn_cast<VectorType>(sourceElementType)) {
5464 // Source has vector element type.
5465 // Check that 'sourceVectorElementType' and 'paddingType' types match.
5466 if (sourceVectorElementType != paddingType)
5467 return emitOpError(
5468 "requires source element type and padding type to match.");
5469
5470 } else {
5471 // Check that 'paddingType' is valid to store in a vector type.
5472 if (!VectorType::isValidElementType(paddingType))
5473 return emitOpError("requires valid padding vector elemental type");
5474
5475 // Check that padding type and vector element types match.
5476 if (paddingType != sourceElementType)
5477 return emitOpError(
5478 "requires formal padding and source of the same elemental type");
5479 }
5480
5481 return verifyPermutationMap(permutationMap,
5482 [&](Twine t) { return emitOpError(t); });
5483}
5484
5485// MaskableOpInterface methods.
5486
5487/// Returns the mask type expected by this operation. Mostly used for
5488/// verification purposes. It requires the operation to be vectorized."
5489Type TransferReadOp::getExpectedMaskType() {
5490 return inferTransferOpMaskType(getVectorType(), getPermutationMap());
5491}
5492
5493//===----------------------------------------------------------------------===//
5494// TransferReadOp: VectorTransferOpInterface methods.
5495//===----------------------------------------------------------------------===//
5496VectorType TransferReadOp::getVectorType() { return getResult().getType(); }
5497
5498Value TransferReadOp::getVector() { return getResult(); }
5499
5500template <typename TransferOp>
5501static bool isInBounds(TransferOp op, int64_t resultIdx, int64_t indicesIdx) {
5502 // TODO: support more aggressive createOrFold on:
5503 // op.getIndices()[indicesIdx] + vectorType < dim(op.getSource(), indicesIdx)
5504 if (op.getShapedType().isDynamicDim(indicesIdx))
5505 return false;
5506 // Scalable dimensions are `vscale` times larger at runtime, so the static
5507 // size is only a lower bound and cannot prove that the transfer fits.
5508 if (op.getVectorType().getScalableDims()[resultIdx])
5509 return false;
5510 Value index = op.getIndices()[indicesIdx];
5511 std::optional<int64_t> cstOp = getConstantIntValue(index);
5512 if (!cstOp.has_value())
5513 return false;
5514
5515 int64_t sourceSize = op.getShapedType().getDimSize(indicesIdx);
5516 int64_t vectorSize = op.getVectorType().getDimSize(resultIdx);
5517 // Largest index at which a full vector still fits. Computed as a subtraction
5518 // rather than adding to the index, which could overflow. The subtraction is
5519 // safe only because of the `isDynamicDim` early return above: `sourceSize`
5520 // is a real static extent here, never `ShapedType::kDynamic`, which is
5521 // `INT64_MIN` and would make this signed overflow.
5522 int64_t maxStart = sourceSize - vectorSize;
5523
5524 // `in_bounds` guarantees that the transfer stays within the source *including
5525 // its starting point*, so a negative index is not in bounds.
5526 return *cstOp >= 0 && *cstOp <= maxStart;
5527}
5528
5529template <typename TransferOp>
5530static LogicalResult foldTransferInBoundsAttribute(TransferOp op) {
5531 // TODO: support 0-d corner case.
5532 // TODO: Be less conservative.
5533 if (op.getTransferRank() == 0)
5534 return failure();
5535 AffineMap permutationMap = op.getPermutationMap();
5536 bool changed = false;
5537 SmallVector<bool, 4> newInBounds;
5538 newInBounds.reserve(op.getTransferRank());
5539 // Idxs of non-bcast dims - used when analysing bcast dims.
5540 SmallVector<unsigned> nonBcastDims;
5541
5542 // 1. Process non-broadcast dims
5543 for (unsigned i = 0; i < op.getTransferRank(); ++i) {
5544 // 1.1. Already marked as in-bounds, nothing to see here.
5545 if (op.isDimInBounds(i)) {
5546 newInBounds.push_back(true);
5547 continue;
5548 }
5549 // 1.2. Currently out-of-bounds, check whether we can statically determine
5550 // it is inBounds.
5551 bool inBounds = false;
5552 auto dimExpr = dyn_cast<AffineDimExpr>(permutationMap.getResult(i));
5553 if (dimExpr) {
5554 inBounds = isInBounds(op, /*resultIdx=*/i,
5555 /*indicesIdx=*/dimExpr.getPosition());
5556 nonBcastDims.push_back(i);
5557 }
5558
5559 newInBounds.push_back(inBounds);
5560 // We commit the pattern if it is "more inbounds".
5561 changed |= inBounds;
5562 }
5563
5564 // 2. Handle broadcast dims
5565 // If all non-broadcast dims are "in bounds", then all bcast dims should be
5566 // "in bounds" as well.
5567 bool allNonBcastDimsInBounds = llvm::all_of(
5568 nonBcastDims, [&newInBounds](unsigned idx) { return newInBounds[idx]; });
5569 if (allNonBcastDimsInBounds) {
5570 for (size_t idx : permutationMap.getBroadcastDims()) {
5571 changed |= !newInBounds[idx];
5572 newInBounds[idx] = true;
5573 }
5574 }
5575
5576 if (!changed)
5577 return failure();
5578 // OpBuilder is only used as a helper to build an I64ArrayAttr.
5579 OpBuilder b(op.getContext());
5580 op.setInBoundsAttr(b.getBoolArrayAttr(newInBounds));
5581 return success();
5582}
5583
5584template <typename TransferOp>
5585static LogicalResult foldTransferFullMask(TransferOp op) {
5586 auto mask = op.getMask();
5587 if (!mask)
5588 return failure();
5589
5591 return failure();
5592
5593 op.getMaskMutable().clear();
5594 return success();
5595}
5596
5597/// When the vector type is `vector<1xT>`, the permutation map is irrelevant:
5598/// the single vector lane always has iteration offset 0, so the element is at
5599/// `indices` regardless of which source dimension the map points at. Replace
5600/// with the minor identity to unblock lowering to vector.load / vector.store.
5601template <typename TransferOp>
5602static LogicalResult foldSize1TransferPermutationMap(TransferOp op) {
5603 VectorType vecType = op.getVectorType();
5604 if (vecType.getRank() != 1 || vecType.getShape()[0] != 1 ||
5605 vecType.isScalable())
5606 return failure();
5607
5608 AffineMap map = op.getPermutationMap();
5609 if (map.isMinorIdentity())
5610 return failure();
5611
5612 int64_t srcRank = op.getShapedType().getRank();
5613 if (srcRank < 1)
5614 return failure();
5615
5616 AffineMap minorIdentity =
5617 AffineMap::getMinorIdentityMap(srcRank, 1, op.getContext());
5618 op.setPermutationMapAttr(AffineMapAttr::get(minorIdentity));
5619 return success();
5620}
5621
5622/// ```
5623/// %w0 = vector.transfer_write %v0, %arg0[%c1, %c0] {in_bounds = [true, true]}
5624/// : vector<1x4xf32>, tensor<4x4xf32>
5625/// %0 = vector.transfer_read %w0[%c1, %c0], %cf0 {in_bounds = [true, true]}
5626/// : tensor<4x4xf32>, vector<1x4xf32>
5627/// ```
5628/// -> Folds into
5629/// ```
5630/// %v0
5631/// ```
5632static Value foldRAW(TransferReadOp readOp) {
5633 if (!llvm::isa<RankedTensorType>(readOp.getShapedType()))
5634 return {};
5635 auto defWrite = readOp.getBase().getDefiningOp<vector::TransferWriteOp>();
5636 while (defWrite) {
5637 if (checkSameValueRAW(defWrite, readOp))
5638 return defWrite.getVector();
5640 cast<VectorTransferOpInterface>(defWrite.getOperation()),
5641 cast<VectorTransferOpInterface>(readOp.getOperation())))
5642 break;
5643 defWrite = defWrite.getBase().getDefiningOp<vector::TransferWriteOp>();
5644 }
5645 return {};
5646}
5647
5648OpFoldResult TransferReadOp::fold(FoldAdaptor) {
5649 if (Value vec = foldRAW(*this))
5650 return vec;
5651 /// transfer_read(memrefcast) -> transfer_read
5652 if (succeeded(foldTransferInBoundsAttribute(*this)))
5653 return getResult();
5654 if (succeeded(foldTransferFullMask(*this)))
5655 return getResult();
5656 if (succeeded(foldSize1TransferPermutationMap(*this)))
5657 return getResult();
5658 if (succeeded(memref::foldMemRefCast(*this)))
5659 return getResult();
5660 if (succeeded(tensor::foldTensorCast(*this)))
5661 return getResult();
5662 return OpFoldResult();
5663}
5664
5665//-----------------------------------------------------------------------------
5666// VectorUnrollOpInterface methods
5667//-----------------------------------------------------------------------------
5668std::optional<SmallVector<int64_t, 4>>
5669TransferReadOp::getIterationShapeToUnroll() {
5670 return llvm::to_vector<4>(getVectorType().getShape());
5671}
5672
5673void TransferReadOp::getEffects(
5674 SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
5675 &effects) {
5676 if (llvm::isa<MemRefType>(getShapedType()))
5677 effects.emplace_back(MemoryEffects::Read::get(), &getBaseMutable(),
5678 SideEffects::DefaultResource::get());
5679}
5680
5681Speculation::Speculatability TransferReadOp::getSpeculatability() {
5682 if (hasPureTensorSemantics())
5685}
5686
5687/// Given a projected permutation, inverse an affine map, making the unused dims
5688/// 0 in the result.
5689static AffineMap inverseWithUnusedDims(AffineMap map) {
5690 assert(map.isProjectedPermutation() &&
5691 "expected a projected permutation map");
5692 SmallVector<AffineExpr> results(map.getNumInputs(),
5694 for (auto [idx, result] : llvm::enumerate(map.getResults())) {
5695 // We should only have dim exprs because this is a projected permutation.
5696 int64_t pos = cast<AffineDimExpr>(result).getPosition();
5697 results[pos] = getAffineDimExpr(idx, map.getContext());
5698 }
5699 return AffineMap::get(/*dimCount=*/map.getNumResults(), /*symbolCount=*/0,
5700 results, map.getContext());
5701}
5702
5703namespace {
5704/// Store to load forwarding for transfer operations with permuation maps.
5705/// Even if the permutation maps are different we can still propagate the store
5706/// into the load if the size of the dimensions read and written match. Then we
5707/// can replace the transfer_read + transfer_write by vector.broadcast and
5708/// vector.transpose.
5709/// Example:
5710/// ```
5711/// %w0 = vector.transfer_write %v0, %arg0[%c0, %c0, %c0]
5712/// {in_bounds = [true, true],
5713/// permutation_map = affine_map<(d0, d1, d2) -> (d2, d1)>} :
5714/// vector<4x1xf32>, tensor<4x4x4xf32>
5715/// %r = vector.transfer_read %w0[%c0, %c0, %c0], %cf0
5716/// {in_bounds = [true, true, true, true],
5717/// permutation_map = affine_map<(d0, d1, d2) -> (d1, 0, d2, 0)>} :
5718/// tensor<4x4x4xf32>, vector<1x100x4x5xf32>
5719/// ```
5720/// To:
5721/// ```
5722/// %0 = vector.broadcast %arg1 : vector<4x1xf32> to vector<100x5x4x1xf32>
5723/// %r = vector.transpose %0, [3, 0, 2, 1] :
5724/// vector<100x5x4x1xf32> to vector<1x100x4x5xf32>
5725/// ```
5726struct TransferReadAfterWriteToBroadcast
5727 : public OpRewritePattern<TransferReadOp> {
5728 using Base::Base;
5729
5730 LogicalResult matchAndRewrite(TransferReadOp readOp,
5731 PatternRewriter &rewriter) const override {
5732 auto defWrite = readOp.getBase().getDefiningOp<vector::TransferWriteOp>();
5733 if (!defWrite)
5734 return failure();
5735 // Bail if we need an alias analysis.
5736 if (!readOp.hasPureTensorSemantics() || !defWrite.hasPureTensorSemantics())
5737 return failure();
5738 // Bail in the masked case (too complex atm and needed to properly account
5739 // for padding). This includes an enclosing vector.mask.
5740 // TODO: Support mask operands and reads nested in vector.mask while
5741 // properly accounting for padding.
5742 if (readOp.getMask() || defWrite.getMask() || readOp.isMasked())
5743 return failure();
5744 // If indices are not the same a shift may be required, bail.
5745 if (readOp.getIndices() != defWrite.getIndices())
5746 return failure();
5747 // Bail if we need a bounds analysis.
5748 if (readOp.hasOutOfBoundsDim() || defWrite.hasOutOfBoundsDim())
5749 return failure();
5750 // TODO: If the written transfer chunk is a superset of the read transfer
5751 // chunk we could do an extract_strided_slice.
5752 if (readOp.getTransferChunkAccessed() !=
5753 defWrite.getTransferChunkAccessed())
5754 return failure();
5755 // WriteMap: tensor -> w_vec
5756 // ReadMap: tensor -> r_vec
5757 //
5758 // inv(WriteMap): w_vec -> tensor
5759 // inv(WriteMap) o ReadMap: w_vec -> r_vec
5760 AffineMap readMap = readOp.getPermutationMap();
5761 AffineMap writeMap = defWrite.getPermutationMap();
5762 AffineMap invWriteMap = inverseWithUnusedDims(writeMap);
5763 AffineMap composedMap = readMap.compose(invWriteMap);
5764 // If there are any unused dims in the composedMap, we have to drop some
5765 // unit dims from the written vector before we can do transpose(broadcast).
5766 // TODO: Support this case.
5767 if (getUnusedDimsBitVector(composedMap).any())
5768 return failure();
5769 // readVec = transpose(broadcast(writeVec))
5770 //
5771 // Build a transpose permutation for the above transpose operation.
5772 //
5773 // Treat the composed map as having extra leading dimensions which are
5774 // the broadcasted dimensions, and treat the zeros as these new broadcasted
5775 // dimensions.
5776 SmallVector<unsigned> broadcastedDims = composedMap.getBroadcastDims();
5777 int64_t numBroadcastedDims = broadcastedDims.size();
5778 auto invPerm = llvm::to_vector_of<int64_t>(broadcastedDims);
5779 invPerm.resize(composedMap.getNumResults());
5780 for (auto [idx, expr] : llvm::enumerate(composedMap.getResults())) {
5781 if (auto dim = dyn_cast<AffineDimExpr>(expr)) {
5782 int64_t effectiveDim = dim.getPosition() + numBroadcastedDims;
5783 invPerm[effectiveDim] = idx;
5784 }
5785 }
5786 // Applying the inverse permutation on the readVecTy will give us the
5787 // broadcast result type.
5788 VectorType readVecTy = readOp.getVectorType();
5789 SmallVector<int64_t> permutation = invertPermutationVector(invPerm);
5790 auto broadcastedVecTy =
5791 VectorType::get(applyPermutation(readVecTy.getShape(), invPerm),
5792 readVecTy.getElementType(),
5793 applyPermutation(readVecTy.getScalableDims(), invPerm));
5794 // Build the transpose(broadcast) transformation.
5795 Value vec = defWrite.getVector();
5796 Location loc = readOp.getLoc();
5797 vec = vector::BroadcastOp::create(rewriter, loc, broadcastedVecTy, vec);
5798 rewriter.replaceOpWithNewOp<vector::TransposeOp>(readOp, vec, permutation);
5799 return success();
5800 }
5801};
5802} // namespace
5803
5804void TransferReadOp::getCanonicalizationPatterns(RewritePatternSet &results,
5805 MLIRContext *context) {
5806 results.add<TransferReadAfterWriteToBroadcast>(context);
5807}
5808
5809FailureOr<std::optional<SmallVector<Value>>>
5810TransferReadOp::bubbleDownCasts(OpBuilder &builder) {
5811 if (!hasPureBufferSemantics())
5812 return failure();
5814 getResult());
5815}
5816
5817//===----------------------------------------------------------------------===//
5818// TransferWriteOp
5819//===----------------------------------------------------------------------===//
5820
5821/// 1. Builder with type inference.
5822void TransferWriteOp::build(OpBuilder &builder, OperationState &result,
5823 Value vector, Value dest, ValueRange indices,
5824 AffineMapAttr permutationMapAttr,
5825 /*optional*/ Value mask,
5826 /*optional*/ ArrayAttr inBoundsAttr) {
5827 Type resultType = llvm::dyn_cast<RankedTensorType>(dest.getType());
5828 build(builder, result, resultType, vector, dest, indices, permutationMapAttr,
5829 mask, inBoundsAttr);
5830}
5831
5832/// 2. Builder with type inference that sets an empty mask (variant with attrs).
5833void TransferWriteOp::build(OpBuilder &builder, OperationState &result,
5834 Value vector, Value dest, ValueRange indices,
5835 AffineMapAttr permutationMapAttr,
5836 /*optional*/ ArrayAttr inBoundsAttr) {
5837 build(builder, result, vector, dest, indices, permutationMapAttr,
5838 /*mask=*/Value(), inBoundsAttr);
5839}
5840
5841/// 3. Builder with type inference that sets an empty mask (variant without
5842/// attrs). If `permutationMap` is null, a minor identity map is used.
5843void TransferWriteOp::build(OpBuilder &builder, OperationState &result,
5844 Value vector, Value dest, ValueRange indices,
5845 AffineMap permutationMap,
5846 std::optional<ArrayRef<bool>> inBounds) {
5847 if (!permutationMap)
5848 permutationMap =
5849 getTransferMinorIdentityMap(llvm::cast<ShapedType>(dest.getType()),
5850 llvm::cast<VectorType>(vector.getType()));
5851 auto permutationMapAttr = AffineMapAttr::get(permutationMap);
5852 auto inBoundsAttr =
5853 (inBounds && !inBounds.value().empty())
5854 ? builder.getBoolArrayAttr(inBounds.value())
5855 : builder.getBoolArrayAttr(SmallVector<bool>(
5856 llvm::cast<VectorType>(vector.getType()).getRank(), false));
5857 build(builder, result, vector, dest, indices, permutationMapAttr,
5858 /*mask=*/Value(), inBoundsAttr);
5859}
5860
5861/// 4. Builder with type inference that sets an empty mask and sets permutation
5862/// map to 'getMinorIdentityMap'.
5863void TransferWriteOp::build(OpBuilder &builder, OperationState &result,
5864 Value vector, Value dest, ValueRange indices,
5865 std::optional<ArrayRef<bool>> inBounds) {
5866 build(builder, result, vector, dest, indices, /*permutationMap=*/AffineMap(),
5867 inBounds);
5868}
5869
5870ParseResult TransferWriteOp::parse(OpAsmParser &parser,
5871 OperationState &result) {
5872 auto &builder = parser.getBuilder();
5873 SMLoc typesLoc;
5874 OpAsmParser::UnresolvedOperand vectorInfo, sourceInfo;
5875 SmallVector<OpAsmParser::UnresolvedOperand, 8> indexInfo;
5876 SmallVector<Type, 2> types;
5877 OpAsmParser::UnresolvedOperand maskInfo;
5878 if (parser.parseOperand(vectorInfo) || parser.parseComma() ||
5879 parser.parseOperand(sourceInfo) ||
5880 parser.parseOperandList(indexInfo, OpAsmParser::Delimiter::Square))
5881 return failure();
5882 ParseResult hasMask = parser.parseOptionalComma();
5883 if (hasMask.succeeded() && parser.parseOperand(maskInfo))
5884 return failure();
5885 if (parser.parseOptionalAttrDict(result.attributes) ||
5886 parser.getCurrentLocation(&typesLoc) || parser.parseColonTypeList(types))
5887 return failure();
5888 if (types.size() != 2)
5889 return parser.emitError(typesLoc, "requires two types");
5890 auto indexType = builder.getIndexType();
5891 VectorType vectorType = llvm::dyn_cast<VectorType>(types[0]);
5892 if (!vectorType)
5893 return parser.emitError(typesLoc, "requires vector type");
5894 ShapedType shapedType = llvm::dyn_cast<ShapedType>(types[1]);
5895 if (!shapedType || !llvm::isa<MemRefType, RankedTensorType>(shapedType))
5896 return parser.emitError(typesLoc, "requires memref or ranked tensor type");
5897 auto permMapAttrName =
5898 TransferWriteOp::getPermutationMapAttrName(result.name);
5899 auto permMapAttr = result.attributes.get(permMapAttrName);
5900 AffineMap permMap;
5901 if (!permMapAttr) {
5902 if (shapedType.getRank() <
5903 getEffectiveVectorRankForXferOp(shapedType, vectorType))
5904 return parser.emitError(typesLoc,
5905 "expected a custom permutation_map when "
5906 "rank(source) != rank(destination)");
5907 permMap = getTransferMinorIdentityMap(shapedType, vectorType);
5908 result.attributes.set(permMapAttrName, AffineMapAttr::get(permMap));
5909 } else {
5910 permMap = llvm::cast<AffineMapAttr>(permMapAttr).getValue();
5911 }
5912 auto inBoundsAttrName = TransferWriteOp::getInBoundsAttrName(result.name);
5913 Attribute inBoundsAttr = result.attributes.get(inBoundsAttrName);
5914 if (!inBoundsAttr) {
5915 result.addAttribute(inBoundsAttrName,
5916 builder.getBoolArrayAttr(
5917 SmallVector<bool>(permMap.getNumResults(), false)));
5918 }
5919 if (parser.resolveOperand(vectorInfo, vectorType, result.operands) ||
5920 parser.resolveOperand(sourceInfo, shapedType, result.operands) ||
5921 parser.resolveOperands(indexInfo, indexType, result.operands))
5922 return failure();
5923 if (hasMask.succeeded()) {
5924 if (llvm::dyn_cast<VectorType>(shapedType.getElementType()))
5925 return parser.emitError(
5926 maskInfo.location, "does not support masks with vector element type");
5927 if (vectorType.getRank() != permMap.getNumResults()) {
5928 return parser.emitError(typesLoc,
5929 "expected the same rank for the vector and the "
5930 "results of the permutation map");
5931 }
5932 auto maskType = inferTransferOpMaskType(vectorType, permMap);
5933 if (parser.resolveOperand(maskInfo, maskType, result.operands))
5934 return failure();
5935 }
5936 result.addAttribute(TransferWriteOp::getOperandSegmentSizeAttr(),
5937 builder.getDenseI32ArrayAttr(
5938 {1, 1, static_cast<int32_t>(indexInfo.size()),
5939 static_cast<int32_t>(hasMask.succeeded())}));
5940 return failure(llvm::isa<RankedTensorType>(shapedType) &&
5941 parser.addTypeToList(shapedType, result.types));
5942}
5943
5944void TransferWriteOp::print(OpAsmPrinter &p) {
5945 p << " " << getVector() << ", " << getBase() << "[" << getIndices() << "]";
5946 if (getMask())
5947 p << ", " << getMask();
5948 printTransferAttrs(p, *this);
5949 p << " : " << getVectorType() << ", " << getShapedType();
5950}
5951
5952LogicalResult TransferWriteOp::verify() {
5953 // Consistency of elemental types in shape and vector.
5954 ShapedType shapedType = getShapedType();
5955 VectorType vectorType = getVectorType();
5956 VectorType maskType = getMaskType();
5957 auto permutationMap = getPermutationMap();
5958 VectorType inferredMaskType =
5959 maskType ? inferTransferOpMaskType(vectorType, permutationMap)
5960 : VectorType();
5961
5962 if (llvm::size(getIndices()) != shapedType.getRank())
5963 return emitOpError("requires ") << shapedType.getRank() << " indices";
5964
5965 // We do not allow broadcast dimensions on TransferWriteOps for the moment,
5966 // as the semantics is unclear. This can be revisited later if necessary.
5967 if (hasBroadcastDim())
5968 return emitOpError("should not have broadcast dimensions");
5969
5970 if (failed(verifyTransferOp(cast<VectorTransferOpInterface>(getOperation()),
5971 shapedType, vectorType, maskType,
5972 inferredMaskType, permutationMap, getInBounds())))
5973 return failure();
5974
5975 return verifyPermutationMap(permutationMap,
5976 [&](Twine t) { return emitOpError(t); });
5977}
5978
5979//===----------------------------------------------------------------------===//
5980// TransferWriteOp: MaskableOpInterface methods.
5981//===----------------------------------------------------------------------===//
5982
5983/// Returns the mask type expected by this operation. Mostly used for
5984/// verification purposes.
5985Type TransferWriteOp::getExpectedMaskType() {
5986 return inferTransferOpMaskType(getVectorType(), getPermutationMap());
5987}
5988
5989//===----------------------------------------------------------------------===//
5990// TransferWriteOp: VectorTransferOpInterface methods.
5991//===----------------------------------------------------------------------===//
5992Value TransferWriteOp::getVector() { return getOperand(0); }
5993VectorType TransferWriteOp::getVectorType() {
5994 return cast<VectorType>(getValueToStore().getType());
5995}
5996
5997//===----------------------------------------------------------------------===//
5998// TransferWriteOp: fold methods.
5999//===----------------------------------------------------------------------===//
6000/// Fold:
6001/// ```
6002/// %t1 = ...
6003/// %v = vector.transfer_read %t0[%c0...], {in_bounds = [true...]} :
6004/// tensor<static_sizesxf32>, vector<static_sizesxf32>
6005/// %t2 = vector.transfer_write %v, %t1[%c0...] {in_bounds = [true...]} :
6006/// vector<static_sizesxf32>, tensor<static_sizesxf32>
6007/// ```
6008///
6009/// into:
6010///
6011/// ```
6012/// %t0
6013/// ```
6014///
6015/// The producer of t1 may or may not be DCE'd depending on whether it is a
6016/// block argument or has side effects.
6017static LogicalResult foldReadInitWrite(TransferWriteOp write,
6018 ArrayRef<Attribute>,
6019 SmallVectorImpl<OpFoldResult> &results) {
6020 // TODO: support 0-d corner case.
6021 if (write.getTransferRank() == 0)
6022 return failure();
6023 auto rankedTensorType =
6024 llvm::dyn_cast<RankedTensorType>(write.getBase().getType());
6025 // If not operating on tensors, bail.
6026 if (!rankedTensorType)
6027 return failure();
6028 // If no read, bail.
6029 auto read = write.getVector().getDefiningOp<vector::TransferReadOp>();
6030 if (!read)
6031 return failure();
6032 // TODO: support 0-d corner case.
6033 if (read.getTransferRank() == 0)
6034 return failure();
6035 // For now, only accept minor identity. Future: composition is minor identity.
6036 if (!read.getPermutationMap().isMinorIdentity() ||
6037 !write.getPermutationMap().isMinorIdentity())
6038 return failure();
6039 // Bail on mismatching ranks.
6040 if (read.getTransferRank() != write.getTransferRank())
6041 return failure();
6042 // Bail on potential out-of-bounds accesses.
6043 if (read.hasOutOfBoundsDim() || write.hasOutOfBoundsDim())
6044 return failure();
6045 // Masked transfers have padding/select semantics and are not identity folds.
6046 // This includes a write under an enclosing vector.mask.
6047 if (read.getMask() || write.getMask() || write.isMasked())
6048 return failure();
6049 // Tensor types must be the same.
6050 if (read.getBase().getType() != rankedTensorType)
6051 return failure();
6052 // Vector types must be the same.
6053 if (read.getVectorType() != write.getVectorType())
6054 return failure();
6055 // Vector and Tensor shapes must match.
6056 if (read.getVectorType().getShape() != rankedTensorType.getShape())
6057 return failure();
6058 // If any index is nonzero.
6059 auto isNotConstantZero = [](Value v) {
6060 auto cstOp = getConstantIntValue(v);
6061 return !cstOp.has_value() || cstOp.value() != 0;
6062 };
6063 if (llvm::any_of(read.getIndices(), isNotConstantZero) ||
6064 llvm::any_of(write.getIndices(), isNotConstantZero))
6065 return failure();
6066 // Success.
6067 results.push_back(read.getBase());
6068 return success();
6069}
6070
6071static bool checkSameValueWAR(vector::TransferReadOp read,
6072 vector::TransferWriteOp write) {
6073 return read.getBase() == write.getBase() &&
6074 read.getIndices() == write.getIndices() &&
6075 read.getPermutationMap() == write.getPermutationMap() &&
6076 read.getVectorType() == write.getVectorType() && !read.getMask() &&
6077 !write.getMask();
6078}
6079/// Fold transfer_write write after read:
6080/// ```
6081/// %t0 = ...
6082/// %v = vector.transfer_read %t0[%c0...] :
6083/// tensor<static_sizesxf32>, vector<static_sizesxf32>
6084/// %t1 = vector.transfer_write %v, %t0[%c0...] :
6085/// vector<static_sizesxf32>, tensor<static_sizesxf32>
6086/// ```
6087///
6088/// into:
6089///
6090/// ```
6091/// %t0
6092/// ```
6093static LogicalResult foldWAR(TransferWriteOp write,
6094 SmallVectorImpl<OpFoldResult> &results) {
6095 if (!llvm::isa<RankedTensorType>(write.getBase().getType()))
6096 return failure();
6097 auto read = write.getVector().getDefiningOp<vector::TransferReadOp>();
6098 if (!read)
6099 return failure();
6100
6101 if (!checkSameValueWAR(read, write))
6102 return failure();
6103 results.push_back(read.getBase());
6104 return success();
6105}
6106
6107LogicalResult TransferWriteOp::fold(FoldAdaptor adaptor,
6108 SmallVectorImpl<OpFoldResult> &results) {
6109 if (succeeded(foldReadInitWrite(*this, adaptor.getOperands(), results)))
6110 return success();
6111 if (succeeded(foldWAR(*this, results)))
6112 return success();
6113 if (succeeded(foldTransferInBoundsAttribute(*this)))
6114 return success();
6115 if (succeeded(foldTransferFullMask(*this)))
6116 return success();
6117 if (succeeded(foldSize1TransferPermutationMap(*this)))
6118 return success();
6119 return memref::foldMemRefCast(*this);
6120}
6121
6122//===----------------------------------------------------------------------===//
6123// TransferWriteOp: other methods.
6124//===----------------------------------------------------------------------===//
6125std::optional<SmallVector<int64_t, 4>>
6126TransferWriteOp::getIterationShapeToUnroll() {
6127 return llvm::to_vector<4>(getVectorType().getShape());
6128}
6129
6130void TransferWriteOp::getEffects(
6131 SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
6132 &effects) {
6133 if (llvm::isa<MemRefType>(getShapedType()))
6134 effects.emplace_back(MemoryEffects::Write::get(), &getBaseMutable(),
6135 SideEffects::DefaultResource::get());
6136}
6137
6138Speculation::Speculatability TransferWriteOp::getSpeculatability() {
6139 if (hasPureTensorSemantics())
6142}
6143
6144namespace {
6145/// Remove dead transfer write from the SSA chain so that it an be eliminated by
6146/// DCE
6147/// ```
6148/// %w0 = vector.transfer_write %v0, %arg0[%c1, %c0] {in_bounds = [true, true]}
6149/// : vector<1x4xf32>, tensor<4x4xf32>
6150/// %w1 = vector.transfer_write %v0, %w0[%c2, %c0] {in_bounds = [true, true]}
6151/// : vector<1x4xf32>, tensor<4x4xf32>
6152/// %w2 = vector.transfer_write %v1, %w1[%c1, %c0] {in_bounds = [true, true]}
6153/// : vector<1x4xf32>, tensor<4x4xf32>
6154/// ```
6155///
6156/// into:
6157///
6158/// ```
6159/// %w0 = vector.transfer_write %v0, %arg0[%c1, %c0] {in_bounds = [true, true]}
6160/// : vector<1x4xf32>, tensor<4x4xf32>
6161/// %w1 = vector.transfer_write %v0, %arg0[%c2, %c0] {in_bounds = [true, true]}
6162/// : vector<1x4xf32>, tensor<4x4xf32>
6163/// %w2 = vector.transfer_write %v1, %w1[%c1, %c0] {in_bounds = [true, true]}
6164/// : vector<1x4xf32>, tensor<4x4xf32>
6165/// ```
6166///
6167/// `%w0 = vector.transfer_write` op will be removed by DCE if it doesn't have
6168/// any other uses.
6169class FoldWaw final : public OpRewritePattern<TransferWriteOp> {
6170public:
6171 using Base::Base;
6172 LogicalResult matchAndRewrite(TransferWriteOp writeOp,
6173 PatternRewriter &rewriter) const override {
6174 if (!llvm::isa<RankedTensorType>(writeOp.getShapedType()))
6175 return failure();
6176 vector::TransferWriteOp writeToModify = writeOp;
6177
6178 auto defWrite = writeOp.getBase().getDefiningOp<vector::TransferWriteOp>();
6179 while (defWrite) {
6180 if (checkSameValueWAW(writeOp, defWrite)) {
6181 rewriter.modifyOpInPlace(writeToModify, [&]() {
6182 writeToModify.getBaseMutable().assign(defWrite.getBase());
6183 });
6184 return success();
6185 }
6187 cast<VectorTransferOpInterface>(defWrite.getOperation()),
6188 cast<VectorTransferOpInterface>(writeOp.getOperation())))
6189 break;
6190 // If the previous write op doesn't have any other use we an safely look
6191 // at the previous store to see if it can be removed.
6192 if (!defWrite->hasOneUse())
6193 break;
6194 writeToModify = defWrite;
6195 defWrite = defWrite.getBase().getDefiningOp<vector::TransferWriteOp>();
6196 }
6197 return failure();
6198 }
6199};
6200
6201/// Rewrite tensor::ExtractSliceOp(vector::TransferWriteOp) to
6202/// vector::TransferWriteOp(tensor::ExtractSliceOp) if the full slice is
6203/// overwritten and inserted into another tensor. After this rewrite, the
6204/// operations bufferize in-place since all of them work on the same slice.
6205///
6206/// For example:
6207/// ```mlir
6208/// %0 = vector.transfer_write %vec, %init_tensor[%c0, %c0]
6209/// : vector<8x16xf32>, tensor<8x16xf32>
6210/// %1 = tensor.extract_slice %0[0, 0] [%sz0, %sz1] [1, 1]
6211/// : tensor<8x16xf32> to tensor<?x?xf32>
6212/// %r = tensor.insert_slice %1 into %iter_arg[%iv0, %iv1] [%sz0, %sz1] [1, 1]
6213/// : tensor<?x?xf32> into tensor<27x37xf32>
6214/// ```
6215/// folds to
6216/// ```mlir
6217/// %0 = tensor.extract_slice %iter_arg[%iv0, %iv1] [%sz0, %sz1] [1, 1]
6218/// : tensor<27x37xf32> to tensor<?x?xf32>
6219/// %1 = vector.transfer_write %vec, %0[%c0, %c0]
6220/// : vector<8x16xf32>, tensor<?x?xf32>
6221/// %r = tensor.insert_slice %1 into %iter_arg[%iv0, %iv1] [%sz0, %sz1] [1, 1]
6222/// : tensor<?x?xf32> into tensor<27x37xf32>
6223/// ```
6224struct SwapExtractSliceOfTransferWrite
6225 : public OpRewritePattern<tensor::InsertSliceOp> {
6226public:
6227 using Base::Base;
6228
6229 LogicalResult matchAndRewrite(tensor::InsertSliceOp insertOp,
6230 PatternRewriter &rewriter) const override {
6231 if (!insertOp.hasUnitStride())
6232 return failure();
6233 auto extractOp =
6234 insertOp.getSource().getDefiningOp<tensor::ExtractSliceOp>();
6235 if (!extractOp || !extractOp.hasUnitStride() || !extractOp->hasOneUse())
6236 return failure();
6237 auto transferOp = extractOp.getSource().getDefiningOp<TransferWriteOp>();
6238 if (!transferOp || !transferOp->hasOneUse())
6239 return failure();
6240
6241 // Fail if vector::TransferWriteOp or tensor::ExtractSliceOp is
6242 // rank-reducing.
6243 if (insertOp.getSourceType().getRank() != transferOp.getTransferRank()) {
6244 return rewriter.notifyMatchFailure(insertOp,
6245 "use-def chain is rank-reducing");
6246 }
6247
6248 // Fail if tensor::ExtractSliceOp has non-zero offset.
6249 if (!extractOp.hasZeroOffset()) {
6250 return rewriter.notifyMatchFailure(insertOp,
6251 "ExtractSliceOp has non-zero offset");
6252 }
6253
6254 // Fail if tensor::TransferWriteOp has non-zero offset.
6255 if (!llvm::all_of(transferOp.getIndices(), [](Value value) {
6256 return getConstantIntValue(value) == static_cast<int64_t>(0);
6257 })) {
6258 return rewriter.notifyMatchFailure(insertOp,
6259 "TranferWriteOp has non-zero offset");
6260 }
6261
6262 // Fail if tensor::ExtractSliceOp and tensor::InsertSliceOp sizes differ.
6263 if (insertOp.getMixedSizes().size() != extractOp.getMixedSizes().size()) {
6264 return rewriter.notifyMatchFailure(
6265 insertOp, "InsertSliceOp and ExtractSliceOp ranks differ");
6266 }
6267
6268 for (auto [insertSize, extractSize] :
6269 llvm::zip_equal(insertOp.getMixedSizes(), extractOp.getMixedSizes())) {
6270 if (!isEqualConstantIntOrValue(insertSize, extractSize)) {
6271 return rewriter.notifyMatchFailure(
6272 insertOp, "InsertSliceOp and ExtractSliceOp sizes differ");
6273 }
6274 }
6275
6276 // Fail if the vector::TransferWriteOp may not overwrite the full tensor.
6277 assert(transferOp.getVectorType().hasStaticShape() &&
6278 "expected vector to have a static shape");
6279 ArrayRef<int64_t> vectorShape = transferOp.getVectorType().getShape();
6280 SmallVector<int64_t> resultShape = applyPermutationMap(
6281 transferOp.getPermutationMap(), transferOp.getShapedType().getShape());
6282 if (transferOp.getMask() || !vectorShape.equals(resultShape)) {
6283 return rewriter.notifyMatchFailure(
6284 insertOp, "TransferWriteOp may not write the full tensor.");
6285 }
6286
6287 // Swap the tensor::ExtractSliceOp in front of the vector::TransferWriteOp.
6288 // Set all in_bounds to false and let the folder infer them.
6289 SmallVector<bool> newInBounds(vectorShape.size(), false);
6290 auto newExtractOp = tensor::ExtractSliceOp::create(
6291 rewriter, extractOp.getLoc(), insertOp.getSourceType(),
6292 insertOp.getDest(), insertOp.getMixedOffsets(),
6293 insertOp.getMixedSizes(), insertOp.getMixedStrides());
6294 auto newTransferWriteOp = TransferWriteOp::create(
6295 rewriter, transferOp.getLoc(), transferOp.getVector(),
6296 newExtractOp.getResult(), transferOp.getIndices(),
6297 transferOp.getPermutationMapAttr(),
6298 rewriter.getBoolArrayAttr(newInBounds));
6299 rewriter.modifyOpInPlace(insertOp, [&]() {
6300 insertOp.getSourceMutable().assign(newTransferWriteOp.getResult());
6301 });
6302 return success();
6303 }
6304};
6305
6306} // namespace
6307
6308void TransferWriteOp::getCanonicalizationPatterns(RewritePatternSet &results,
6309 MLIRContext *context) {
6310 results.add<FoldWaw, SwapExtractSliceOfTransferWrite>(context);
6311}
6312
6313FailureOr<std::optional<SmallVector<Value>>>
6314TransferWriteOp::bubbleDownCasts(OpBuilder &builder) {
6315 if (!hasPureBufferSemantics())
6316 return failure();
6318 ValueRange());
6319}
6320
6321//===----------------------------------------------------------------------===//
6322// LoadOp
6323//===----------------------------------------------------------------------===//
6324
6325static ParseResult parseBoolAttr(OpAsmParser &parser, BoolAttr &result) {
6326 Attribute attr;
6327 if (parser.parseAttribute(attr))
6328 return failure();
6329 result = dyn_cast<BoolAttr>(attr);
6330 if (!result)
6331 return parser.emitError(parser.getCurrentLocation(),
6332 "expected boolean attribute");
6333 return success();
6334}
6335
6336static void printBoolAttr(OpAsmPrinter &printer, Operation *, BoolAttr attr) {
6337 printer.printAttribute(attr);
6338}
6339
6340bool vector::isValidLoadStoreMemRefLayout(VectorType vecTy,
6341 MemRefType memRefTy) {
6342 // If rank==0 or size==1 it's equivalent to scalar load/store, so we don't
6343 // need any strides limitations.
6344 if (!vecTy.isScalable() &&
6345 (vecTy.getRank() == 0 || vecTy.getNumElements() == 1))
6346 return true;
6347 return memRefTy.isLastDimUnitStride();
6348}
6349
6350static LogicalResult verifyLoadStoreMemRefLayout(Operation *op,
6351 VectorType vecTy,
6352 MemRefType memRefTy) {
6353 if (!isValidLoadStoreMemRefLayout(vecTy, memRefTy))
6354 return op->emitOpError("most minor memref dim must have unit stride");
6355 return success();
6356}
6357
6358LogicalResult vector::LoadOp::verify() {
6359 VectorType resVecTy = getVectorType();
6360 MemRefType memRefTy = getMemRefType();
6361
6362 if (failed(verifyLoadStoreMemRefLayout(*this, resVecTy, memRefTy)))
6363 return failure();
6364
6365 // Negative strides are not supported on vector.load. The lowering to LLVM
6366 // emits arithmetic operations (e.g., GEP, mul) with nuw flags that assume
6367 // non-negative strides to avoid undefined behavior.
6368 if (memref::hasNegativeStaticStride(memRefTy))
6369 return emitOpError("memref strides must be non-negative");
6370
6371 if (memRefTy.getRank() < resVecTy.getRank())
6372 return emitOpError(
6373 "destination memref has lower rank than the result vector");
6374
6375 // Checks for vector memrefs.
6376 Type memElemTy = memRefTy.getElementType();
6377 if (auto memVecTy = llvm::dyn_cast<VectorType>(memElemTy)) {
6378 if (memVecTy != resVecTy)
6379 return emitOpError("base memref and result vector types should match");
6380 memElemTy = memVecTy.getElementType();
6381 }
6382
6383 if (resVecTy.getElementType() != memElemTy)
6384 return emitOpError("base and result element types should match");
6385 if (llvm::size(getIndices()) != memRefTy.getRank())
6386 return emitOpError("requires ") << memRefTy.getRank() << " indices";
6387 return success();
6388}
6389
6390OpFoldResult LoadOp::fold(FoldAdaptor) {
6391 if (succeeded(memref::foldMemRefCast(*this)))
6392 return getResult();
6393 return OpFoldResult();
6394}
6395
6396FailureOr<std::optional<SmallVector<Value>>>
6397LoadOp::bubbleDownCasts(OpBuilder &builder) {
6399 getResult());
6400}
6401
6402//-----------------------------------------------------------------------------
6403// VectorUnrollOpInterface methods
6404//-----------------------------------------------------------------------------
6405std::optional<SmallVector<int64_t, 4>> LoadOp::getIterationShapeToUnroll() {
6406 return llvm::to_vector<4>(getVectorType().getShape());
6407}
6408
6409//===----------------------------------------------------------------------===//
6410// StoreOp
6411//===----------------------------------------------------------------------===//
6412
6413LogicalResult vector::StoreOp::verify() {
6414 VectorType valueVecTy = getVectorType();
6415 MemRefType memRefTy = getMemRefType();
6416
6417 if (failed(verifyLoadStoreMemRefLayout(*this, valueVecTy, memRefTy)))
6418 return failure();
6419
6420 // Negative strides are not supported on vector.store. The lowering to LLVM
6421 // emits arithmetic operations (e.g., GEP, mul) with nuw flags that assume
6422 // non-negative strides to avoid undefined behavior.
6423 if (memref::hasNegativeStaticStride(memRefTy))
6424 return emitOpError("memref strides must be non-negative");
6425
6426 if (memRefTy.getRank() < valueVecTy.getRank())
6427 return emitOpError("source memref has lower rank than the vector to store");
6428
6429 // Checks for vector memrefs.
6430 Type memElemTy = memRefTy.getElementType();
6431 if (auto memVecTy = llvm::dyn_cast<VectorType>(memElemTy)) {
6432 if (memVecTy != valueVecTy)
6433 return emitOpError(
6434 "base memref and valueToStore vector types should match");
6435 memElemTy = memVecTy.getElementType();
6436 }
6437
6438 if (valueVecTy.getElementType() != memElemTy)
6439 return emitOpError("base and valueToStore element type should match");
6440 if (llvm::size(getIndices()) != memRefTy.getRank())
6441 return emitOpError("requires ") << memRefTy.getRank() << " indices";
6442 return success();
6443}
6444
6445LogicalResult StoreOp::fold(FoldAdaptor adaptor,
6446 SmallVectorImpl<OpFoldResult> &results) {
6447 return memref::foldMemRefCast(*this);
6448}
6449
6450FailureOr<std::optional<SmallVector<Value>>>
6451StoreOp::bubbleDownCasts(OpBuilder &builder) {
6453 ValueRange());
6454}
6455
6456//-----------------------------------------------------------------------------
6457// VectorUnrollOpInterface methods
6458//-----------------------------------------------------------------------------
6459std::optional<SmallVector<int64_t, 4>> StoreOp::getIterationShapeToUnroll() {
6460 return llvm::to_vector<4>(getVectorType().getShape());
6461}
6462
6463//===----------------------------------------------------------------------===//
6464// MaskedLoadOp
6465//===----------------------------------------------------------------------===//
6466
6467LogicalResult MaskedLoadOp::verify() {
6468 VectorType maskVType = getMaskVectorType();
6469 VectorType passVType = getPassThruVectorType();
6470 VectorType resVType = getVectorType();
6471 MemRefType memType = getMemRefType();
6472
6473 if (failed(verifyLoadStoreMemRefLayout(*this, resVType, memType)))
6474 return failure();
6475
6476 // Negative strides are not supported on vector.maskedload. The lowering to
6477 // LLVM emits arithmetic operations (e.g., GEP, mul) with nuw flags that
6478 // assume non-negative strides to avoid undefined behavior.
6480 return emitOpError("memref strides must be non-negative");
6481
6482 if (failed(
6483 verifyElementTypesMatch(*this, memType, resVType, "base", "result")))
6484 return failure();
6485 if (llvm::size(getIndices()) != memType.getRank())
6486 return emitOpError("requires ") << memType.getRank() << " indices";
6487 if (resVType.getShape() != maskVType.getShape())
6488 return emitOpError("expected result shape to match mask shape");
6489 if (resVType != passVType)
6490 return emitOpError("expected pass_thru of same type as result type");
6491 return success();
6492}
6493
6494namespace {
6495class MaskedLoadFolder final : public OpRewritePattern<MaskedLoadOp> {
6496public:
6497 using Base::Base;
6498 LogicalResult matchAndRewrite(MaskedLoadOp load,
6499 PatternRewriter &rewriter) const override {
6500 switch (getMaskFormat(load.getMask())) {
6502 rewriter.replaceOpWithNewOp<vector::LoadOp>(
6503 load, load.getType(), load.getBase(), load.getIndices());
6504 return success();
6506 rewriter.replaceOp(load, load.getPassThru());
6507 return success();
6509 return failure();
6510 }
6511 llvm_unreachable("Unexpected 1DMaskFormat on MaskedLoad");
6512 }
6513};
6514} // namespace
6515
6516void MaskedLoadOp::getCanonicalizationPatterns(RewritePatternSet &results,
6517 MLIRContext *context) {
6518 results.add<MaskedLoadFolder>(context);
6519}
6520
6521OpFoldResult MaskedLoadOp::fold(FoldAdaptor) {
6522 if (succeeded(memref::foldMemRefCast(*this)))
6523 return getResult();
6524 return OpFoldResult();
6525}
6526
6527FailureOr<std::optional<SmallVector<Value>>>
6528MaskedLoadOp::bubbleDownCasts(OpBuilder &builder) {
6530 getResult());
6531}
6532
6533//===----------------------------------------------------------------------===//
6534// MaskedStoreOp
6535//===----------------------------------------------------------------------===//
6536
6537LogicalResult MaskedStoreOp::verify() {
6538 VectorType maskVType = getMaskVectorType();
6539 VectorType valueVType = getVectorType();
6540 MemRefType memType = getMemRefType();
6541
6542 if (failed(verifyLoadStoreMemRefLayout(*this, valueVType, memType)))
6543 return failure();
6544
6545 // Negative strides are not supported on vector.maskedstore. The lowering to
6546 // LLVM emits arithmetic operations (e.g., GEP, mul) with nuw flags that
6547 // assume non-negative strides to avoid undefined behavior.
6549 return emitOpError("memref strides must be non-negative");
6550
6551 if (failed(verifyElementTypesMatch(*this, memType, valueVType, "base",
6552 "valueToStore")))
6553 return failure();
6554 if (llvm::size(getIndices()) != memType.getRank())
6555 return emitOpError("requires ") << memType.getRank() << " indices";
6556 if (valueVType.getShape() != maskVType.getShape())
6557 return emitOpError("expected valueToStore shape to match mask shape");
6558 return success();
6559}
6560
6561namespace {
6562class MaskedStoreFolder final : public OpRewritePattern<MaskedStoreOp> {
6563public:
6564 using Base::Base;
6565 LogicalResult matchAndRewrite(MaskedStoreOp store,
6566 PatternRewriter &rewriter) const override {
6567 switch (getMaskFormat(store.getMask())) {
6569 rewriter.replaceOpWithNewOp<vector::StoreOp>(
6570 store, store.getValueToStore(), store.getBase(), store.getIndices());
6571 return success();
6573 rewriter.eraseOp(store);
6574 return success();
6576 return failure();
6577 }
6578 llvm_unreachable("Unexpected 1DMaskFormat on MaskedStore");
6579 }
6580};
6581} // namespace
6582
6583void MaskedStoreOp::getCanonicalizationPatterns(RewritePatternSet &results,
6584 MLIRContext *context) {
6585 results.add<MaskedStoreFolder>(context);
6586}
6587
6588LogicalResult MaskedStoreOp::fold(FoldAdaptor adaptor,
6589 SmallVectorImpl<OpFoldResult> &results) {
6590 return memref::foldMemRefCast(*this);
6591}
6592
6593FailureOr<std::optional<SmallVector<Value>>>
6594MaskedStoreOp::bubbleDownCasts(OpBuilder &builder) {
6596 ValueRange());
6597}
6598
6599//===----------------------------------------------------------------------===//
6600// GatherOp
6601//===----------------------------------------------------------------------===//
6602
6603LogicalResult GatherOp::verify() {
6604 VectorType indVType = getIndexVectorType();
6605 VectorType maskVType = getMaskVectorType();
6606 VectorType resVType = getVectorType();
6607 ShapedType baseType = getBaseType();
6608
6609 if (!llvm::isa<MemRefType, RankedTensorType>(baseType))
6610 return emitOpError("requires base to be a memref or ranked tensor type");
6611
6612 // Negative strides are not supported on vector.gather.
6613 // The lowering to LLVM emits arithmetic operations (e.g., GEP, mul) with nuw
6614 // flags that assume non-negative strides to avoid undefined behavior.
6615 if (auto memRefType = dyn_cast<MemRefType>(baseType))
6616 if (memref::hasNegativeStaticStride(memRefType))
6617 return emitOpError("memref strides must be non-negative");
6618
6619 if (failed(
6620 verifyElementTypesMatch(*this, baseType, resVType, "base", "result")))
6621 return failure();
6622 if (llvm::size(getOffsets()) != baseType.getRank())
6623 return emitOpError("requires ") << baseType.getRank() << " indices";
6624 if (resVType.getShape() != indVType.getShape())
6625 return emitOpError("expected result dim to match indices dim");
6626 if (resVType.getShape() != maskVType.getShape())
6627 return emitOpError("expected result dim to match mask dim");
6628 if (resVType != getPassThruVectorType())
6629 return emitOpError("expected pass_thru of same type as result type");
6630 if (getAlignmentAttr() && !isa<MemRefType>(baseType)) {
6631 return emitOpError(
6632 "alignment is only supported for memref bases, not tensor bases");
6633 }
6634 return success();
6635}
6636
6637//-----------------------------------------------------------------------------
6638// MaskableOpInterface methods.
6639//-----------------------------------------------------------------------------
6640/// Cheeck if `indexVec` is constant 1D vec of consecutive values [0, 1, 2, ...]
6641static LogicalResult isZeroBasedContiguousSeq(Value indexVec) {
6642 auto vecType = dyn_cast<VectorType>(indexVec.getType());
6643 if (!vecType || vecType.getRank() != 1 || vecType.isScalable())
6644 return failure();
6645
6646 if (indexVec.getDefiningOp<StepOp>())
6647 return success();
6648
6649 DenseIntElementsAttr elements;
6650 if (!matchPattern(indexVec, m_Constant(&elements)))
6651 return failure();
6652
6653 return success(
6654 llvm::equal(elements, llvm::seq<int64_t>(0, vecType.getNumElements())));
6655}
6656
6657//-----------------------------------------------------------------------------
6658// VectorUnrollOpInterface methods
6659//-----------------------------------------------------------------------------
6660std::optional<SmallVector<int64_t, 4>> GatherOp::getIterationShapeToUnroll() {
6661 return llvm::to_vector<4>(getVectorType().getShape());
6662}
6663
6664namespace {
6665class GatherFolder final : public OpRewritePattern<GatherOp> {
6666public:
6667 using Base::Base;
6668 LogicalResult matchAndRewrite(GatherOp gather,
6669 PatternRewriter &rewriter) const override {
6670 switch (getMaskFormat(gather.getMask())) {
6672 return failure(); // no unmasked equivalent
6674 rewriter.replaceOp(gather, gather.getPassThru());
6675 return success();
6677 return failure();
6678 }
6679 llvm_unreachable("Unexpected 1DMaskFormat on GatherFolder");
6680 }
6681};
6682
6683/// Fold gathers with consecutive offsets [0, 1, 2, ...] into contiguous
6684/// maskedload. Only 1D fixed vectors are supported for now.
6685class FoldContiguousGather final : public OpRewritePattern<GatherOp> {
6686public:
6687 using Base::Base;
6688 LogicalResult matchAndRewrite(GatherOp op,
6689 PatternRewriter &rewriter) const override {
6690 if (!isa<MemRefType>(op.getBase().getType()))
6691 return rewriter.notifyMatchFailure(op, "base must be of memref type");
6692
6693 if (failed(isZeroBasedContiguousSeq(op.getIndices())))
6694 return failure();
6695
6696 rewriter.replaceOpWithNewOp<MaskedLoadOp>(op, op.getType(), op.getBase(),
6697 op.getOffsets(), op.getMask(),
6698 op.getPassThru());
6699 return success();
6700 }
6701};
6702} // namespace
6703
6704void GatherOp::getCanonicalizationPatterns(RewritePatternSet &results,
6705 MLIRContext *context) {
6706 results.add<GatherFolder, FoldContiguousGather>(context);
6707}
6708
6709FailureOr<std::optional<SmallVector<Value>>>
6710GatherOp::bubbleDownCasts(OpBuilder &builder) {
6712 getResult());
6713}
6714
6715//===----------------------------------------------------------------------===//
6716// ScatterOp
6717//===----------------------------------------------------------------------===//
6718
6719LogicalResult ScatterOp::verify() {
6720 VectorType indVType = getIndexVectorType();
6721 VectorType maskVType = getMaskVectorType();
6722 VectorType valueVType = getVectorType();
6723 ShapedType baseType = getBaseType();
6724
6725 if (!llvm::isa<MemRefType, RankedTensorType>(baseType))
6726 return emitOpError("requires base to be a memref or ranked tensor type");
6727
6728 // Negative strides are not supported on vector.scatter.
6729 // The lowering to LLVM emits arithmetic operations (e.g., GEP, mul) with nuw
6730 // flags that assume non-negative strides to avoid undefined behavior.
6731 if (auto memRefType = dyn_cast<MemRefType>(baseType))
6732 if (memref::hasNegativeStaticStride(memRefType))
6733 return emitOpError("memref strides must be non-negative");
6734
6735 if (failed(verifyElementTypesMatch(*this, baseType, valueVType, "base",
6736 "valueToStore")))
6737 return failure();
6738 if (llvm::size(getOffsets()) != baseType.getRank())
6739 return emitOpError("requires ") << baseType.getRank() << " indices";
6740 if (valueVType.getShape() != indVType.getShape())
6741 return emitOpError("expected valueToStore dim to match indices dim");
6742 if (valueVType.getShape() != maskVType.getShape())
6743 return emitOpError("expected valueToStore dim to match mask dim");
6744 if (getAlignmentAttr() && !isa<MemRefType>(baseType)) {
6745 return emitOpError(
6746 "alignment is only supported for memref bases, not tensor bases");
6747 }
6748 return success();
6749}
6750namespace {
6751class ScatterFolder final : public OpRewritePattern<ScatterOp> {
6752public:
6753 using Base::Base;
6754 LogicalResult matchAndRewrite(ScatterOp scatter,
6755 PatternRewriter &rewriter) const override {
6756 ShapedType baseType = scatter.getBaseType();
6757 bool isMemRef = isa<MemRefType>(baseType);
6758 if (!isMemRef && !isa<RankedTensorType>(baseType))
6759 return failure();
6760
6761 // Memrefs have no result, so an all-false mask can simply erase the op.
6762 // Tensors carry the updated value, so we must replace uses with the
6763 // original base tensor instead of erasing.
6764 switch (getMaskFormat(scatter.getMask())) {
6766 return failure(); // no unmasked equivalent
6768 if (isMemRef)
6769 rewriter.eraseOp(scatter);
6770 else
6771 rewriter.replaceOp(scatter, scatter.getBase());
6772 return success();
6774 return failure();
6775 }
6776 llvm_unreachable("Unexpected 1DMaskFormat on ScatterFolder");
6777 }
6778};
6779
6780/// Fold scatters with consecutive offsets [0, 1, 2, ...] into contiguous
6781/// maskedstore. Only 1D fixed vectors are supported for now.
6782class FoldContiguousScatter final : public OpRewritePattern<ScatterOp> {
6783public:
6784 using Base::Base;
6785 LogicalResult matchAndRewrite(ScatterOp op,
6786 PatternRewriter &rewriter) const override {
6787 // Fold only for memrefs: the replacement uses maskedstore, which does not
6788 // support tensor bases. Tensor cases intentionally bail out.
6789 if (!isa<MemRefType>(op.getBase().getType()))
6790 return failure();
6791
6792 if (failed(isZeroBasedContiguousSeq(op.getIndices())))
6793 return failure();
6794
6795 rewriter.replaceOpWithNewOp<MaskedStoreOp>(
6796 op, op.getBase(), op.getOffsets(), op.getMask(), op.getValueToStore());
6797 return success();
6798 }
6799};
6800} // namespace
6801
6802void ScatterOp::getCanonicalizationPatterns(RewritePatternSet &results,
6803 MLIRContext *context) {
6804 results.add<ScatterFolder, FoldContiguousScatter>(context);
6805}
6806
6807FailureOr<std::optional<SmallVector<Value>>>
6808ScatterOp::bubbleDownCasts(OpBuilder &builder) {
6810 ValueRange());
6811}
6812
6813//===----------------------------------------------------------------------===//
6814// ExpandLoadOp
6815//===----------------------------------------------------------------------===//
6816
6817LogicalResult ExpandLoadOp::verify() {
6818 VectorType maskVType = getMaskVectorType();
6819 VectorType passVType = getPassThruVectorType();
6820 VectorType resVType = getVectorType();
6821 MemRefType memType = getMemRefType();
6822
6823 if (failed(verifyLoadStoreMemRefLayout(*this, resVType, memType)))
6824 return failure();
6825
6826 // Negative strides are not supported on vector.expandload. The lowering to
6827 // LLVM emits arithmetic operations (e.g., GEP, mul) with nuw flags that
6828 // assume non-negative strides to avoid undefined behavior.
6830 return emitOpError("memref strides must be non-negative");
6831
6832 if (failed(
6833 verifyElementTypesMatch(*this, memType, resVType, "base", "result")))
6834 return failure();
6835 if (llvm::size(getIndices()) != memType.getRank())
6836 return emitOpError("requires ") << memType.getRank() << " indices";
6837 if (resVType.getShape() != maskVType.getShape())
6838 return emitOpError("expected result shape to match mask shape");
6839 if (resVType.getScalableDims() != maskVType.getScalableDims())
6840 return emitOpError(
6841 "expected result scalable dims to match mask scalable dims");
6842 if (resVType != passVType)
6843 return emitOpError("expected pass_thru of same type as result type");
6844 return success();
6845}
6846
6847namespace {
6848class ExpandLoadFolder final : public OpRewritePattern<ExpandLoadOp> {
6849public:
6850 using Base::Base;
6851 LogicalResult matchAndRewrite(ExpandLoadOp expand,
6852 PatternRewriter &rewriter) const override {
6853 switch (getMaskFormat(expand.getMask())) {
6855 rewriter.replaceOpWithNewOp<vector::LoadOp>(
6856 expand, expand.getType(), expand.getBase(), expand.getIndices());
6857 return success();
6859 rewriter.replaceOp(expand, expand.getPassThru());
6860 return success();
6862 return failure();
6863 }
6864 llvm_unreachable("Unexpected 1DMaskFormat on ExpandLoadFolder");
6865 }
6866};
6867} // namespace
6868
6869void ExpandLoadOp::getCanonicalizationPatterns(RewritePatternSet &results,
6870 MLIRContext *context) {
6871 results.add<ExpandLoadFolder>(context);
6872}
6873
6874FailureOr<std::optional<SmallVector<Value>>>
6875ExpandLoadOp::bubbleDownCasts(OpBuilder &builder) {
6877 getResult());
6878}
6879
6880//===----------------------------------------------------------------------===//
6881// CompressStoreOp
6882//===----------------------------------------------------------------------===//
6883
6884LogicalResult CompressStoreOp::verify() {
6885 VectorType maskVType = getMaskVectorType();
6886 VectorType valueVType = getVectorType();
6887 MemRefType memType = getMemRefType();
6888
6889 if (failed(verifyLoadStoreMemRefLayout(*this, valueVType, memType)))
6890 return failure();
6891
6892 // Negative strides are not supported on vector.compressstore. The lowering
6893 // to LLVM emits arithmetic operations (e.g., GEP, mul) with nuw flags that
6894 // assume non-negative strides to avoid undefined behavior.
6896 return emitOpError("memref strides must be non-negative");
6897
6898 if (failed(verifyElementTypesMatch(*this, memType, valueVType, "base",
6899 "valueToStore")))
6900 return failure();
6901 if (llvm::size(getIndices()) != memType.getRank())
6902 return emitOpError("requires ") << memType.getRank() << " indices";
6903 if (valueVType.getShape() != maskVType.getShape())
6904 return emitOpError("expected valueToStore shape to match mask shape");
6905 if (valueVType.getScalableDims() != maskVType.getScalableDims())
6906 return emitOpError(
6907 "expected valueToStore scalable dims to match mask scalable dims");
6908 return success();
6909}
6910
6911namespace {
6912class CompressStoreFolder final : public OpRewritePattern<CompressStoreOp> {
6913public:
6914 using Base::Base;
6915 LogicalResult matchAndRewrite(CompressStoreOp compress,
6916 PatternRewriter &rewriter) const override {
6917 switch (getMaskFormat(compress.getMask())) {
6919 rewriter.replaceOpWithNewOp<vector::StoreOp>(
6920 compress, compress.getValueToStore(), compress.getBase(),
6921 compress.getIndices());
6922 return success();
6924 rewriter.eraseOp(compress);
6925 return success();
6927 return failure();
6928 }
6929 llvm_unreachable("Unexpected 1DMaskFormat on CompressStoreFolder");
6930 }
6931};
6932} // namespace
6933
6934void CompressStoreOp::getCanonicalizationPatterns(RewritePatternSet &results,
6935 MLIRContext *context) {
6936 results.add<CompressStoreFolder>(context);
6937}
6938
6939FailureOr<std::optional<SmallVector<Value>>>
6940CompressStoreOp::bubbleDownCasts(OpBuilder &builder) {
6942 ValueRange());
6943}
6944
6945//===----------------------------------------------------------------------===//
6946// ShapeCastOp
6947//===----------------------------------------------------------------------===//
6948
6949void ShapeCastOp::inferResultRanges(ArrayRef<ConstantIntRanges> argRanges,
6950 SetIntRangeFn setResultRanges) {
6951 setResultRanges(getResult(), argRanges.front());
6952}
6953
6954LogicalResult ShapeCastOp::verify() {
6955
6956 VectorType sourceType = getSourceVectorType();
6957 VectorType resultType = getResultVectorType();
6958
6959 // Check that element type is preserved
6960 if (failed(verifyElementTypesMatch(*this, sourceType, resultType, "source",
6961 "result")))
6962 return failure();
6963
6964 // Check that number of elements is preserved
6965 int64_t sourceNElms = sourceType.getNumElements();
6966 int64_t resultNElms = resultType.getNumElements();
6967 if (sourceNElms != resultNElms) {
6968 return emitOpError() << "has different number of elements at source ("
6969 << sourceNElms << ") and result (" << resultNElms
6970 << ")";
6971 }
6972
6973 // Check that (non-)scalability is preserved
6974 int64_t sourceNScalableDims = sourceType.getNumScalableDims();
6975 int64_t resultNScalableDims = resultType.getNumScalableDims();
6976 if (sourceNScalableDims != resultNScalableDims)
6977 return emitOpError() << "has different number of scalable dims at source ("
6978 << sourceNScalableDims << ") and result ("
6979 << resultNScalableDims << ")";
6980
6981 return success();
6982}
6983
6984/// Check whether this ShapeCastOp is effectively a BroadcastOp.
6985///
6986/// The only case in which this method can return `true` is when the underlying
6987/// op merely adds leading unit dimensions, e.g.:
6988/// %res = vector.shape_cast %src : vector<8x4xi32> to vector<1x8x4xi32>
6989///
6990bool ShapeCastOp::isBroadcastLike() {
6991 auto srcType = getSourceVectorType();
6992 auto resType = getResultVectorType();
6993
6994 // Is srcType broadcastable to resType?
6995 std::pair<VectorDim, VectorDim> mismatchingDims;
6996 if (isBroadcastableTo(srcType, resType, &mismatchingDims) !=
6997 BroadcastableToResult::Success)
6998 return false;
6999
7000 // Do ranks mismatch?
7001 //
7002 // The only case where ranks match and this ShapeCastOp is also a broadcast,
7003 // is when it's effectively a NOp, but that's an uninteresting edge case.
7004 size_t rankDiff = resType.getRank() - srcType.getRank();
7005 if (rankDiff == 0)
7006 return false;
7007
7008 // Are all newly added leading dims unit?
7009 if (!llvm::all_of(resType.getShape().take_front(rankDiff),
7010 [](int64_t dim) { return dim == 1; }))
7011 return false;
7012
7013 // Do all trailing dims match?
7014 return resType.getShape().take_back(srcType.getRank()) == srcType.getShape();
7015}
7016
7017/// Return true if `transpose` does not permute a pair of non-unit dims.
7018/// By `order preserving` we mean that the flattened versions of the input and
7019/// output vectors are (numerically) identical. In other words `transpose` is
7020/// effectively a shape cast.
7021static bool isOrderPreserving(TransposeOp transpose) {
7022 ArrayRef<int64_t> permutation = transpose.getPermutation();
7023 VectorType sourceType = transpose.getSourceVectorType();
7024 ArrayRef<int64_t> inShape = sourceType.getShape();
7025 ArrayRef<bool> inDimIsScalable = sourceType.getScalableDims();
7026 auto isNonScalableUnitDim = [&](int64_t dim) {
7027 return inShape[dim] == 1 && !inDimIsScalable[dim];
7028 };
7029 int64_t current = 0;
7030 for (auto p : permutation) {
7031 if (!isNonScalableUnitDim(p)) {
7032 if (p < current) {
7033 return false;
7034 }
7035 current = p;
7036 }
7037 }
7038 return true;
7039}
7040
7041OpFoldResult ShapeCastOp::fold(FoldAdaptor adaptor) {
7042
7043 VectorType resultType = getType();
7044
7045 // No-op shape cast.
7046 if (getSource().getType() == resultType)
7047 return getSource();
7048
7049 // shape_cast(shape_cast(x)) -> shape_cast(x)
7050 if (auto precedingShapeCast = getSource().getDefiningOp<ShapeCastOp>()) {
7051 setOperand(precedingShapeCast.getSource());
7052 return getResult();
7053 }
7054
7055 // shape_cast(transpose(x)) -> shape_cast(x)
7056 if (auto transpose = getSource().getDefiningOp<TransposeOp>()) {
7057 if (isOrderPreserving(transpose)) {
7058 setOperand(transpose.getVector());
7059 return getResult();
7060 }
7061 return {};
7062 }
7063
7064 // Y = shape_cast(broadcast(X))
7065 // -> X, if X and Y have same type
7066 if (auto bcastOp = getSource().getDefiningOp<BroadcastOp>()) {
7067 if (bcastOp.getSourceType() == resultType)
7068 return bcastOp.getSource();
7069 }
7070
7071 // shape_cast(constant) -> constant
7072 if (auto denseAttr =
7073 dyn_cast_if_present<DenseElementsAttr>(adaptor.getSource()))
7074 return denseAttr.reshape(getType());
7075
7076 // shape_cast(poison) -> poison
7077 if (matchPattern(adaptor.getSource(), ub::m_Poison()))
7078 return ub::PoisonAttr::get(getContext());
7079
7080 return {};
7081}
7082
7083//-----------------------------------------------------------------------------
7084// VectorUnrollOpInterface methods
7085//-----------------------------------------------------------------------------
7086std::optional<SmallVector<int64_t, 4>>
7087ShapeCastOp::getIterationShapeToUnroll() {
7088 return llvm::to_vector<4>(getResultVectorType().getShape());
7089}
7090
7091std::optional<SmallVector<int64_t>> ShapeCastOp::getDefaultUnrollTargetShape() {
7092 auto resultShape = this->getResultVectorType().getShape();
7093 // Special case with leading unit dims and different inner dim
7094 // for result and target shape.
7095 if (resultShape.size() == 2 && resultShape[0] == 1 && resultShape[1] == 32) {
7096 return SmallVector<int64_t>{1, 16};
7097 }
7098 if (resultShape.size() == 2 && resultShape[0] == 2 && resultShape[1] == 1) {
7099 return SmallVector<int64_t>{1, 1};
7100 }
7101 // Multi-group cases: tile contiguous per reassociation group
7102 // but strided in the whole result.
7103 auto sourceShape = this->getSourceVectorType().getShape();
7104 if (resultShape.size() == 3 && resultShape[0] == 8 && resultShape[1] == 1 &&
7105 resultShape[2] == 32) {
7106 return SmallVector<int64_t>{8, 1, 4};
7107 }
7108 if (sourceShape.size() == 3 && resultShape.size() == 2 &&
7109 resultShape[0] == 4 && resultShape[1] == 4) {
7110 return SmallVector<int64_t>{2, 2};
7111 }
7112 if (resultShape.size() == 3 && resultShape[0] == 2 && resultShape[1] == 8 &&
7113 resultShape[2] == 4) {
7114 return SmallVector<int64_t>{2, 2, 2};
7115 }
7116 // Default case: [2,4] for all tests.
7117 return SmallVector<int64_t>{2, 4};
7118}
7119
7120namespace {
7121
7122/// Helper function that computes a new vector type based on the input vector
7123/// type by removing the _trailing_ unit dims:
7124///
7125/// vector<4x1x1xi1> --> vector<4x1xi1>
7126///
7127static VectorType trimTrailingUnitDims(VectorType oldType) {
7128 ArrayRef<int64_t> oldShape = oldType.getShape();
7129 ArrayRef<int64_t> newShape = oldShape;
7130
7131 ArrayRef<bool> oldScalableDims = oldType.getScalableDims();
7132 ArrayRef<bool> newScalableDims = oldScalableDims;
7133
7134 while (!newShape.empty() && newShape.back() == 1 && !newScalableDims.back()) {
7135 newShape = newShape.drop_back(1);
7136 newScalableDims = newScalableDims.drop_back(1);
7137 }
7138
7139 // Make sure we have at least 1 dimension.
7140 // TODO: Add support for 0-D vectors.
7141 if (newShape.empty()) {
7142 newShape = oldShape.take_back();
7143 newScalableDims = oldScalableDims.take_back();
7144 }
7145
7146 return VectorType::get(newShape, oldType.getElementType(), newScalableDims);
7147}
7148
7149/// Helper function that computes a new vector type based on the input vector
7150/// type by removing the _leading_ unit dims:
7151///
7152/// vector<1x1x4xi1> --> vector<4x1xi1>
7153///
7154static VectorType trimLeadingUnitDims(VectorType oldType) {
7155 ArrayRef<int64_t> oldShape = oldType.getShape();
7156 ArrayRef<int64_t> newShape = oldShape;
7157
7158 ArrayRef<bool> oldScalableDims = oldType.getScalableDims();
7159 ArrayRef<bool> newScalableDims = oldScalableDims;
7160
7161 while (!newShape.empty() && newShape.front() == 1 &&
7162 !newScalableDims.front()) {
7163 newShape = newShape.drop_front(1);
7164 newScalableDims = newScalableDims.drop_front(1);
7165 }
7166
7167 // Make sure we have at least 1 dimension.
7168 // TODO: Add support for 0-D vectors.
7169 if (newShape.empty()) {
7170 newShape = oldShape.take_back();
7171 newScalableDims = oldScalableDims.take_back();
7172 }
7173
7174 return VectorType::get(newShape, oldType.getElementType(), newScalableDims);
7175}
7176
7177enum class UnitDimSide { Leading, Trailing };
7178
7179/// Folds qualifying shape_cast(create_mask) into a new create_mask
7180///
7181/// Looks at `vector.shape_cast` Ops that simply "drop" either the _trailing_ or
7182/// the _leading_unit dimension (configured with the template parameter). If the
7183/// input vector comes from `vector.create_mask` for which the corresponding
7184/// mask input value is 1 (e.g. `%c1` below), then it is safe to fold shape_cast
7185/// into create_mask.
7186///
7187/// EX 1 (trailing unit dims)
7188/// BEFORE:
7189/// %1 = vector.create_mask %c1, %dim, %c1, %c1 : vector<1x[4]x1x1xi1>
7190/// %2 = vector.shape_cast %1 : vector<1x[4]x1x1xi1> to vector<1x[4]xi1>
7191/// AFTER:
7192/// %0 = vector.create_mask %c1, %dim : vector<1x[4]xi1>
7193///
7194/// EX 2 (leading unit dims)
7195/// BEFORE:
7196/// %1 = vector.create_mask %c1, %c1, %dim, %c1 : vector<1x1x[4]x1xi1>
7197/// %2 = vector.shape_cast %1 : vector<1x1x[4]x1xi1> to vector<[4]x1xi1>
7198/// AFTER:
7199/// %0 = vector.create_mask %c1, %dim : vector<[4]xi1>
7200template <UnitDimSide Side>
7201class ShapeCastCreateMaskFolderBoundaryUnitDim final
7202 : public OpRewritePattern<ShapeCastOp> {
7203public:
7204 using Base::Base;
7205
7206 LogicalResult matchAndRewrite(ShapeCastOp shapeOp,
7207 PatternRewriter &rewriter) const override {
7208 Value shapeOpSrc = shapeOp->getOperand(0);
7209 auto createMaskOp = shapeOpSrc.getDefiningOp<vector::CreateMaskOp>();
7210 auto constantMaskOp = shapeOpSrc.getDefiningOp<vector::ConstantMaskOp>();
7211 if (!createMaskOp && !constantMaskOp)
7212 return failure();
7213
7214 VectorType shapeOpResTy = shapeOp.getResultVectorType();
7215 VectorType shapeOpSrcTy = shapeOp.getSourceVectorType();
7216
7217 VectorType newVecType = (Side == UnitDimSide::Trailing)
7218 ? trimTrailingUnitDims(shapeOpSrcTy)
7219 : trimLeadingUnitDims(shapeOpSrcTy);
7220
7221 if (newVecType != shapeOpResTy) {
7222 return (Side == UnitDimSide::Trailing)
7223 ? rewriter.notifyMatchFailure(
7224 shapeOp, "Non-trailing-unit-dim dropping shape_cast Op")
7225 : rewriter.notifyMatchFailure(
7226 shapeOp, "Non-leading-unit-dim dropping shape_cast Op");
7227 }
7228
7229 auto numDimsToDrop = shapeOpSrcTy.getRank() - shapeOpResTy.getRank();
7230
7231 // No unit dims to drop
7232 if (!numDimsToDrop) {
7233 return (Side == UnitDimSide::Trailing)
7234 ? rewriter.notifyMatchFailure(
7235 shapeOp, "Non-trailing-unit-dim dropping shape_cast Op")
7236 : rewriter.notifyMatchFailure(
7237 shapeOp, "Non-leading-unit-dim dropping shape_cast Op");
7238 }
7239
7240 if (createMaskOp) {
7241 auto maskOperands = createMaskOp.getOperands();
7242
7243 auto maskOperandsToDrop = (Side == UnitDimSide::Trailing)
7244 ? maskOperands.take_back(numDimsToDrop)
7245 : maskOperands.take_front(numDimsToDrop);
7246
7247 // Check that every mask-dim-size to-be-dropped is constant and == 1. We
7248 // could also check for == 0, but that's left as a TODO.
7249 if (llvm::any_of(maskOperandsToDrop, [](Value maskDim) {
7250 auto cst = maskDim.getDefiningOp<arith::ConstantIndexOp>();
7251 return !cst || (cst.value() != 1);
7252 }))
7253 return failure();
7254
7255 auto newMaskOperands = (Side == UnitDimSide::Trailing)
7256 ? maskOperands.drop_back(numDimsToDrop)
7257 : maskOperands.drop_front(numDimsToDrop);
7258 rewriter.replaceOpWithNewOp<vector::CreateMaskOp>(shapeOp, shapeOpResTy,
7259 newMaskOperands);
7260 return success();
7261 }
7262
7263 if (constantMaskOp) {
7264 auto maskDimSizes = constantMaskOp.getMaskDimSizes();
7265
7266 ArrayRef<int64_t> maskDimSizesToDrop =
7267 (Side == UnitDimSide::Trailing)
7268 ? maskDimSizes.take_back(numDimsToDrop)
7269 : maskDimSizes.take_front(numDimsToDrop);
7270
7271 // Check that every mask-dim-size to-be-dropped is constant and == 1. We
7272 // could also check for == 0, but that's left as a TODO.
7273 if (llvm::any_of(maskDimSizesToDrop,
7274 [](int64_t dim) { return dim != 1; }))
7275 return failure();
7276
7277 ArrayRef<int64_t> newMaskDimSizes =
7278 (Side == UnitDimSide::Trailing)
7279 ? maskDimSizes.drop_back(numDimsToDrop)
7280 : maskDimSizes.drop_front(numDimsToDrop);
7281 rewriter.replaceOpWithNewOp<vector::ConstantMaskOp>(shapeOp, shapeOpResTy,
7282 newMaskDimSizes);
7283 return success();
7284 }
7285
7286 return failure();
7287 }
7288};
7289
7290/// Pattern to rewrite Y = ShapeCast(Broadcast(X)) as Y = Broadcast(X)
7291class ShapeCastBroadcastFolder final : public OpRewritePattern<ShapeCastOp> {
7292public:
7293 using Base::Base;
7294
7295 LogicalResult matchAndRewrite(ShapeCastOp shapeCastOp,
7296 PatternRewriter &rewriter) const override {
7297 auto oldBcOp = shapeCastOp.getSource().getDefiningOp<vector::BroadcastOp>();
7298 if (!oldBcOp)
7299 return failure();
7300
7301 // Replace Y = ShapeCast(Broadcast(X)) with Y = Broadcast(X)
7302 // Example
7303 // %oldBc = vector.broadcast %src : vector<3xf32> to vector<2x4x3xf32>
7304 // %res = vector.shape_cast %oldBc : vector<2x4x3xf32> to vector<8x3xf32>
7305 // to
7306 // %newBc = vector.broadcast %src : vector<3xf32> to vector<8x3xf32>
7307 VectorType resVectorType = shapeCastOp.getResultVectorType();
7308
7309 // Limit this pattern to vectors with at most one scalable dimension for
7310 // now.
7311 if (resVectorType.getNumScalableDims() > 1)
7312 return failure();
7313
7314 auto srcVectorType = dyn_cast<VectorType>(oldBcOp.getSourceType());
7315 bool srcIsScalar = !srcVectorType;
7316
7317 if (!srcIsScalar) {
7318 if (isBroadcastableTo(srcVectorType, resVectorType) !=
7319 BroadcastableToResult::Success) {
7320 return failure();
7321 }
7322 // For a fixed source shape, the result strides determine which source
7323 // element supplies each linear position in the broadcast result (see the
7324 // `BroadcastOp` definition for the closed-form mapping). Since
7325 // `shape_cast` preserves the flattened 1-D (row-major) element order,
7326 // folding into `%newBc` is valid when every non-unit `%src` dimension has
7327 // the same stride (both static product and scalability) in `%oldBc` and
7328 // `%res`. Note that a scalable `[1]` has runtime size `vscale` and is not
7329 // a unit dimension.
7330 VectorType oldBcVectorType = oldBcOp.getResultVectorType();
7331 int64_t srcRank = srcVectorType.getRank();
7332 int64_t oldBcRank = oldBcVectorType.getRank();
7333 int64_t resRank = resVectorType.getRank();
7334 ArrayRef<int64_t> srcShape = srcVectorType.getShape();
7335 ArrayRef<int64_t> oldBcShape = oldBcVectorType.getShape();
7336 ArrayRef<int64_t> resShape = resVectorType.getShape();
7337 ArrayRef<bool> srcScalable = srcVectorType.getScalableDims();
7338 ArrayRef<bool> oldBcScalable = oldBcVectorType.getScalableDims();
7339 ArrayRef<bool> resScalable = resVectorType.getScalableDims();
7340
7341 // Iterate from the innermost (trailing) dimension outward, aligning each
7342 // `%src` dimension with the corresponding trailing dimension of `%oldBc`
7343 // and `%res`.
7344 int64_t oldBcStride = 1, resStride = 1;
7345 bool isOldBcStrideScalable = false, isResStrideScalable = false;
7346 for (int64_t i = 0; i < srcRank; ++i) {
7347 int64_t srcDim = srcRank - 1 - i;
7348 int64_t oldBcDim = oldBcRank - 1 - i;
7349 int64_t resDim = resRank - 1 - i;
7350
7351 bool isUnitDim = srcShape[srcDim] == 1 && !srcScalable[srcDim];
7352 if (!isUnitDim && (oldBcStride != resStride ||
7353 isOldBcStrideScalable != isResStrideScalable)) {
7354 return failure();
7355 }
7356
7357 oldBcStride *= oldBcShape[oldBcDim];
7358 resStride *= resShape[resDim];
7359 isOldBcStrideScalable |= oldBcScalable[oldBcDim];
7360 isResStrideScalable |= resScalable[resDim];
7361 }
7362 }
7363
7364 rewriter.replaceOpWithNewOp<vector::BroadcastOp>(shapeCastOp, resVectorType,
7365 oldBcOp.getSource());
7366 return success();
7367 }
7368};
7369
7370/// Pattern to rewrite Y = ShapeCast(FromElements(X)) as Y = FromElements(X)
7371///
7372/// BEFORE:
7373/// %1 = vector.from_elements %c1, %c2, %c3 : vector<3xf32>
7374/// %2 = vector.shape_cast %1 : vector<3xf32> to vector<1x3xf32>
7375/// AFTER:
7376/// %2 = vector.from_elements %c1, %c2, %c3 : vector<1x3xf32>
7377///
7378/// Note: this transformation is implemented as an OpRewritePattern, not as a
7379/// fold, because we have to create new op FromElementsOp with updated result
7380/// type. This cannot be done with a fold, because fold cannot create new ops
7381/// and the existing FromElementsOp result type differs from the ShapeCastOp
7382/// result type. Mutating the FromElementsOp (not root op) would violate the
7383/// fold contract and break other users.
7384class FoldShapeCastOfFromElements final : public OpRewritePattern<ShapeCastOp> {
7385public:
7386 using Base::Base;
7387
7388 LogicalResult matchAndRewrite(ShapeCastOp shapeCastOp,
7389 PatternRewriter &rewriter) const override {
7390 auto fromElements = shapeCastOp.getSource().getDefiningOp<FromElementsOp>();
7391 if (!fromElements)
7392 return failure();
7393
7394 rewriter.replaceOpWithNewOp<FromElementsOp>(
7395 shapeCastOp, shapeCastOp.getResultVectorType(),
7396 fromElements.getElements());
7397 return success();
7398 }
7399};
7400
7401} // namespace
7402
7403void ShapeCastOp::getCanonicalizationPatterns(RewritePatternSet &results,
7404 MLIRContext *context) {
7405 results.add<ShapeCastCreateMaskFolderBoundaryUnitDim<UnitDimSide::Leading>,
7406 ShapeCastCreateMaskFolderBoundaryUnitDim<UnitDimSide::Trailing>,
7407 ShapeCastBroadcastFolder, FoldShapeCastOfFromElements>(context);
7408}
7409
7410//===----------------------------------------------------------------------===//
7411// VectorBitCastOp
7412//===----------------------------------------------------------------------===//
7413
7414LogicalResult BitCastOp::verify() {
7415 auto sourceVectorType = getSourceVectorType();
7416 auto resultVectorType = getResultVectorType();
7417
7418 for (int64_t i = 0, e = sourceVectorType.getRank() - 1; i < e; i++) {
7419 if (sourceVectorType.getDimSize(i) != resultVectorType.getDimSize(i))
7420 return emitOpError("dimension size mismatch at: ") << i;
7421 }
7422
7423 DataLayout dataLayout = DataLayout::closest(*this);
7424 auto sourceElementBits =
7425 dataLayout.getTypeSizeInBits(sourceVectorType.getElementType());
7426 auto resultElementBits =
7427 dataLayout.getTypeSizeInBits(resultVectorType.getElementType());
7428
7429 if (sourceVectorType.getRank() == 0) {
7430 if (sourceElementBits != resultElementBits)
7431 return emitOpError("source/result bitwidth of the 0-D vector element "
7432 "types must be equal");
7433 } else if (sourceElementBits * sourceVectorType.getShape().back() !=
7434 resultElementBits * resultVectorType.getShape().back()) {
7435 return emitOpError(
7436 "source/result bitwidth of the minor 1-D vectors must be equal");
7437 }
7438
7439 return success();
7440}
7441
7442OpFoldResult BitCastOp::fold(FoldAdaptor adaptor) {
7443 // Nop cast.
7444 if (getSource().getType() == getResult().getType())
7445 return getSource();
7446
7447 // Canceling bitcasts.
7448 if (auto otherOp = getSource().getDefiningOp<BitCastOp>()) {
7449 if (getResult().getType() == otherOp.getSource().getType())
7450 return otherOp.getSource();
7451
7452 setOperand(otherOp.getSource());
7453 return getResult();
7454 }
7455
7456 Attribute sourceConstant = adaptor.getSource();
7457 if (!sourceConstant)
7458 return {};
7459
7460 Type srcElemType = getSourceVectorType().getElementType();
7461 Type dstElemType = getResultVectorType().getElementType();
7462
7463 if (auto floatPack = llvm::dyn_cast<DenseFPElementsAttr>(sourceConstant)) {
7464 if (floatPack.isSplat()) {
7465 auto splat = floatPack.getSplatValue<FloatAttr>();
7466
7467 // Casting fp16 into fp32.
7468 if (srcElemType.isF16() && dstElemType.isF32()) {
7469 uint32_t bits = static_cast<uint32_t>(
7470 splat.getValue().bitcastToAPInt().getZExtValue());
7471 // Duplicate the 16-bit pattern.
7472 bits = (bits << 16) | (bits & 0xffff);
7473 APInt intBits(32, bits);
7474 APFloat floatBits(llvm::APFloat::IEEEsingle(), intBits);
7475 return DenseElementsAttr::get(getResultVectorType(), floatBits);
7476 }
7477 }
7478 }
7479
7480 if (auto intPack = llvm::dyn_cast<DenseIntElementsAttr>(sourceConstant)) {
7481 if (intPack.isSplat()) {
7482 auto splat = intPack.getSplatValue<IntegerAttr>();
7483
7484 if (llvm::isa<IntegerType>(dstElemType) && srcElemType.isIntOrFloat()) {
7485 uint64_t srcBitWidth = srcElemType.getIntOrFloatBitWidth();
7486 uint64_t dstBitWidth = dstElemType.getIntOrFloatBitWidth();
7487
7488 // Casting to a larger integer bit width.
7489 if (dstBitWidth > srcBitWidth && dstBitWidth % srcBitWidth == 0) {
7490 APInt intBits = splat.getValue().zext(dstBitWidth);
7491
7492 // Duplicate the lower width element.
7493 for (uint64_t i = 0; i < dstBitWidth / srcBitWidth - 1; i++)
7494 intBits = (intBits << srcBitWidth) | intBits;
7495 return DenseElementsAttr::get(getResultVectorType(), intBits);
7496 }
7497 }
7498 }
7499 }
7500
7501 return {};
7502}
7503
7504//-----------------------------------------------------------------------------
7505// VectorUnrollOpInterface methods
7506//-----------------------------------------------------------------------------
7507std::optional<SmallVector<int64_t, 4>> BitCastOp::getIterationShapeToUnroll() {
7508 return llvm::to_vector<4>(getResultVectorType().getShape());
7509}
7510
7511std::optional<SmallVector<int64_t>> BitCastOp::getDefaultUnrollTargetShape() {
7512 return SmallVector<int64_t>{4, 4};
7513}
7514
7515//===----------------------------------------------------------------------===//
7516// TypeCastOp
7517//===----------------------------------------------------------------------===//
7518
7519static SmallVector<int64_t, 8> extractShape(MemRefType memRefType) {
7520 auto vectorType = llvm::dyn_cast<VectorType>(memRefType.getElementType());
7521 SmallVector<int64_t, 8> res(memRefType.getShape());
7522 if (vectorType)
7523 res.append(vectorType.getShape().begin(), vectorType.getShape().end());
7524 return res;
7525}
7526
7527/// Build the canonical memRefType with a single vector.
7528/// E.g. memref<4 x 5 x vector<6 x f32>> -> memref<vector<4 x 5 x 6 x f32>>.
7529void TypeCastOp::build(OpBuilder &builder, OperationState &result,
7530 Value source) {
7531 result.addOperands(source);
7532 MemRefType memRefType = llvm::cast<MemRefType>(source.getType());
7533 VectorType vectorType =
7534 VectorType::get(extractShape(memRefType),
7536 result.addTypes(MemRefType::get({}, vectorType, MemRefLayoutAttrInterface(),
7537 memRefType.getMemorySpace()));
7538}
7539
7540LogicalResult TypeCastOp::verify() {
7541 MemRefType canonicalType = getMemRefType().canonicalizeStridedLayout();
7542 if (!canonicalType.getLayout().isIdentity())
7543 return emitOpError("expects operand to be a memref with identity layout");
7544 if (!getResultMemRefType().getLayout().isIdentity())
7545 return emitOpError("expects result to be a memref with identity layout");
7546 if (getResultMemRefType().getMemorySpace() !=
7547 getMemRefType().getMemorySpace())
7548 return emitOpError("expects result in same memory space");
7549
7550 auto sourceType = getMemRefType();
7551 auto resultType = getResultMemRefType();
7552 if (getElementTypeOrSelf(getElementTypeOrSelf(sourceType)) !=
7554 return emitOpError(
7555 "expects result and operand with same underlying scalar type: ")
7556 << resultType;
7557 if (extractShape(sourceType) != extractShape(resultType))
7558 return emitOpError(
7559 "expects concatenated result and operand shapes to be equal: ")
7560 << resultType;
7561 return success();
7562}
7563
7564//===----------------------------------------------------------------------===//
7565// TransposeOp
7566//===----------------------------------------------------------------------===//
7567
7568void vector::TransposeOp::build(OpBuilder &builder, OperationState &result,
7569 Value vector, ArrayRef<int64_t> permutation) {
7570 VectorType vt = llvm::cast<VectorType>(vector.getType());
7571 SmallVector<int64_t, 4> transposedShape(vt.getRank());
7572 SmallVector<bool, 4> transposedScalableDims(vt.getRank());
7573 for (unsigned i = 0; i < permutation.size(); ++i) {
7574 transposedShape[i] = vt.getShape()[permutation[i]];
7575 transposedScalableDims[i] = vt.getScalableDims()[permutation[i]];
7576 }
7577
7578 result.addOperands(vector);
7579 result.addTypes(VectorType::get(transposedShape, vt.getElementType(),
7580 transposedScalableDims));
7581 result.addAttribute(TransposeOp::getPermutationAttrName(result.name),
7582 builder.getDenseI64ArrayAttr(permutation));
7583}
7584
7585OpFoldResult vector::TransposeOp::fold(FoldAdaptor adaptor) {
7586 // Eliminate splat constant transpose ops.
7587 if (auto splat =
7588 llvm::dyn_cast_if_present<SplatElementsAttr>(adaptor.getVector()))
7589 return splat.reshape(getResultVectorType());
7590
7591 // Eliminate poison transpose ops.
7592 if (matchPattern(adaptor.getVector(), ub::m_Poison()))
7593 return ub::PoisonAttr::get(getContext());
7594
7595 // Eliminate identity transposes, and more generally any transposes that
7596 // preserves the shape without permuting elements.
7597 //
7598 // Examples of what to fold:
7599 // %0 = vector.transpose %arg, [0, 1] : vector<1x1xi8> to vector<1x1xi8>
7600 // %0 = vector.transpose %arg, [0, 1] : vector<2x2xi8> to vector<2x2xi8>
7601 // %0 = vector.transpose %arg, [1, 0] : vector<1x1xi8> to vector<1x1xi8>
7602 //
7603 // Example of what NOT to fold:
7604 // %0 = vector.transpose %arg, [1, 0] : vector<2x2xi8> to vector<2x2xi8>
7605 //
7606 if (getSourceVectorType() == getResultVectorType() &&
7607 isOrderPreserving(*this))
7608 return getVector();
7609
7610 return {};
7611}
7612
7613LogicalResult vector::TransposeOp::verify() {
7614 VectorType vectorType = getSourceVectorType();
7615 VectorType resultType = getResultVectorType();
7616 int64_t rank = resultType.getRank();
7617 if (vectorType.getRank() != rank)
7618 return emitOpError("vector result rank mismatch: ") << rank;
7619 // Verify transposition array.
7620 ArrayRef<int64_t> perm = getPermutation();
7621 int64_t size = perm.size();
7622 if (rank != size)
7623 return emitOpError("transposition length mismatch: ") << size;
7624 SmallVector<bool, 8> seen(rank, false);
7625 for (const auto &ta : llvm::enumerate(perm)) {
7626 if (ta.value() < 0 || ta.value() >= rank)
7627 return emitOpError("transposition index out of range: ") << ta.value();
7628 if (seen[ta.value()])
7629 return emitOpError("duplicate position index: ") << ta.value();
7630 seen[ta.value()] = true;
7631 if (resultType.getDimSize(ta.index()) != vectorType.getDimSize(ta.value()))
7632 return emitOpError("dimension size mismatch at: ") << ta.value();
7633 }
7634 return success();
7635}
7636
7637void TransposeOp::inferResultRanges(ArrayRef<ConstantIntRanges> argRanges,
7638 SetIntRangeFn setResultRanges) {
7639 setResultRanges(getResult(), argRanges.front());
7640}
7641
7642//-----------------------------------------------------------------------------
7643// VectorUnrollOpInterface methods
7644//-----------------------------------------------------------------------------
7645std::optional<SmallVector<int64_t, 4>>
7646TransposeOp::getIterationShapeToUnroll() {
7647 return llvm::to_vector<4>(getResultVectorType().getShape());
7648}
7649
7650std::optional<SmallVector<int64_t>> TransposeOp::getDefaultUnrollTargetShape() {
7651 return SmallVector<int64_t>{1, 3, 4, 2};
7652}
7653
7654namespace {
7655
7656// Rewrites two back-to-back TransposeOp operations into a single TransposeOp.
7657class TransposeFolder final : public OpRewritePattern<vector::TransposeOp> {
7658public:
7659 using Base::Base;
7660
7661 LogicalResult matchAndRewrite(vector::TransposeOp transposeOp,
7662 PatternRewriter &rewriter) const override {
7663 // Composes two permutations: result[i] = permutation1[permutation2[i]].
7664 auto composePermutations = [](ArrayRef<int64_t> permutation1,
7665 ArrayRef<int64_t> permutation2) {
7666 SmallVector<int64_t, 4> result;
7667 for (auto index : permutation2)
7668 result.push_back(permutation1[index]);
7669 return result;
7670 };
7671
7672 // Return if the input of 'transposeOp' is not defined by another transpose.
7673 vector::TransposeOp parentTransposeOp =
7674 transposeOp.getVector().getDefiningOp<vector::TransposeOp>();
7675 if (!parentTransposeOp)
7676 return failure();
7677
7678 SmallVector<int64_t, 4> permutation = composePermutations(
7679 parentTransposeOp.getPermutation(), transposeOp.getPermutation());
7680 // Replace 'transposeOp' with a new transpose operation.
7681 rewriter.replaceOpWithNewOp<vector::TransposeOp>(
7682 transposeOp, transposeOp.getResult().getType(),
7683 parentTransposeOp.getVector(), permutation);
7684 return success();
7685 }
7686};
7687
7688/// Replace transpose(splat-like(v)) with broadcast(v)
7689class FoldTransposeSplat final : public OpRewritePattern<TransposeOp> {
7690public:
7691 using Base::Base;
7692
7693 LogicalResult matchAndRewrite(TransposeOp transposeOp,
7694 PatternRewriter &rewriter) const override {
7695 Value splat = getScalarSplatSource(transposeOp.getVector());
7696 if (!splat)
7697 return failure();
7698
7699 rewriter.replaceOpWithNewOp<vector::BroadcastOp>(
7700 transposeOp, transposeOp.getResultVectorType(), splat);
7701 return success();
7702 }
7703};
7704
7705/// Folds transpose(create_mask) into a new transposed create_mask.
7706class FoldTransposeCreateMask final : public OpRewritePattern<TransposeOp> {
7707public:
7708 using Base::Base;
7709
7710 LogicalResult matchAndRewrite(TransposeOp transpOp,
7711 PatternRewriter &rewriter) const override {
7712 Value transposeSrc = transpOp.getVector();
7713 auto createMaskOp = transposeSrc.getDefiningOp<vector::CreateMaskOp>();
7714 auto constantMaskOp = transposeSrc.getDefiningOp<vector::ConstantMaskOp>();
7715 if (!createMaskOp && !constantMaskOp)
7716 return failure();
7717
7718 // Get the transpose permutation and apply it to the vector.create_mask or
7719 // vector.constant_mask operands.
7720 ArrayRef<int64_t> permutation = transpOp.getPermutation();
7721
7722 if (createMaskOp) {
7723 auto maskOperands = createMaskOp.getOperands();
7724 SmallVector<Value> newOperands(maskOperands.begin(), maskOperands.end());
7725 applyPermutationToVector(newOperands, permutation);
7726
7727 rewriter.replaceOpWithNewOp<vector::CreateMaskOp>(
7728 transpOp, transpOp.getResultVectorType(), newOperands);
7729 return success();
7730 }
7731
7732 // ConstantMaskOp case.
7733 auto maskDimSizes = constantMaskOp.getMaskDimSizes();
7734 auto newMaskDimSizes = applyPermutation(maskDimSizes, permutation);
7735
7736 rewriter.replaceOpWithNewOp<vector::ConstantMaskOp>(
7737 transpOp, transpOp.getResultVectorType(), newMaskDimSizes);
7738 return success();
7739 }
7740};
7741
7742/// Folds transpose(shape_cast) into a new shape_cast.
7743class FoldTransposeShapeCast final : public OpRewritePattern<TransposeOp> {
7744public:
7745 using Base::Base;
7746
7747 LogicalResult matchAndRewrite(TransposeOp transposeOp,
7748 PatternRewriter &rewriter) const override {
7749 auto shapeCastOp =
7750 transposeOp.getVector().getDefiningOp<vector::ShapeCastOp>();
7751 if (!shapeCastOp)
7752 return failure();
7753 if (!isOrderPreserving(transposeOp))
7754 return failure();
7755
7756 VectorType resultType = transposeOp.getType();
7757
7758 // We don't need to check isValidShapeCast at this point, because it is
7759 // guaranteed that merging the transpose into the the shape_cast is a valid
7760 // shape_cast, because the transpose just inserts/removes ones.
7761
7762 rewriter.replaceOpWithNewOp<vector::ShapeCastOp>(transposeOp, resultType,
7763 shapeCastOp.getSource());
7764 return success();
7765 }
7766};
7767
7768/// Folds transpose(from_elements(...)) into a new from_elements with permuted
7769/// operands matching the transposed shape.
7770///
7771/// Example:
7772///
7773/// %v = vector.from_elements %a00, %a01, %a02, %a10, %a11, %a12 :
7774/// vector<2x3xi32> %t = vector.transpose %v, [1, 0] : vector<2x3xi32> to
7775/// vector<3x2xi32>
7776///
7777/// becomes ->
7778///
7779/// %r = vector.from_elements %a00, %a10, %a01, %a11, %a02, %a12 :
7780/// vector<3x2xi32>
7781///
7782class FoldTransposeFromElements final : public OpRewritePattern<TransposeOp> {
7783public:
7784 using Base::Base;
7785 LogicalResult matchAndRewrite(vector::TransposeOp transposeOp,
7786 PatternRewriter &rewriter) const override {
7787 auto fromElementsOp =
7788 transposeOp.getVector().getDefiningOp<vector::FromElementsOp>();
7789 if (!fromElementsOp)
7790 return failure();
7791
7792 VectorType srcTy = fromElementsOp.getResult().getType();
7793 VectorType dstTy = transposeOp.getType();
7794
7795 ArrayRef<int64_t> permutation = transposeOp.getPermutation();
7796 int64_t rank = srcTy.getRank();
7797
7798 // Build inverse permutation to map destination indices back to source.
7799 SmallVector<int64_t> inversePerm(rank, 0);
7800 for (int64_t i = 0; i < rank; ++i)
7801 inversePerm[permutation[i]] = i;
7802
7803 ArrayRef<int64_t> srcShape = srcTy.getShape();
7804 ArrayRef<int64_t> dstShape = dstTy.getShape();
7805 SmallVector<int64_t> srcIdx(rank, 0);
7806 SmallVector<int64_t> dstIdx(rank, 0);
7807 SmallVector<int64_t> srcStrides = computeStrides(srcShape);
7808 SmallVector<int64_t> dstStrides = computeStrides(dstShape);
7809
7810 auto elementsOld = fromElementsOp.getElements();
7811 SmallVector<Value> elementsNew;
7812 int64_t dstNumElements = dstTy.getNumElements();
7813 elementsNew.reserve(dstNumElements);
7814
7815 // For each element in destination row-major order, pick the corresponding
7816 // source element.
7817 for (int64_t linearIdx = 0; linearIdx < dstNumElements; ++linearIdx) {
7818 // Pick the destination element index.
7819 dstIdx = delinearize(linearIdx, dstStrides);
7820 // Map the destination element index to the source element index.
7821 for (int64_t j = 0; j < rank; ++j)
7822 srcIdx[j] = dstIdx[inversePerm[j]];
7823 // Linearize the source element index.
7824 int64_t srcLin = linearize(srcIdx, srcStrides);
7825 // Add the source element to the new elements.
7826 elementsNew.push_back(elementsOld[srcLin]);
7827 }
7828
7829 rewriter.replaceOpWithNewOp<FromElementsOp>(transposeOp, dstTy,
7830 elementsNew);
7831 return success();
7832 }
7833};
7834
7835/// Folds transpose(broadcast(x)) to broadcast(x) if the transpose is
7836/// 'order preserving', where 'order preserving' means the flattened
7837/// inputs and outputs of the transpose have identical (numerical) values.
7838///
7839/// Example:
7840/// ```
7841/// %0 = vector.broadcast %input : vector<1x1xi32> to vector<1x8xi32>
7842/// %1 = vector.transpose %0, [1, 0] : vector<1x8xi32>
7843/// to vector<8x1xi32>
7844/// ```
7845/// can be rewritten as the equivalent
7846/// ```
7847/// %0 = vector.broadcast %input : vector<1x1xi32> to vector<8x1xi32>.
7848/// ```
7849/// The algorithm works by partitioning dimensions into groups that can be
7850/// locally permuted while preserving order, and checks that the transpose
7851/// only permutes within these groups.
7852///
7853/// Groups are either contiguous sequences of 1s, or non-1s (1-element groups).
7854/// Consider broadcasting 4x1x1x7 to 2x3x4x5x6x7. This is equivalent to
7855/// broadcasting from 1x1x4x1x1x7.
7856/// ^^^ ^ ^^^ ^
7857/// groups: 0 1 2 3
7858/// Order preserving permutations for this example are ones that only permute
7859/// within the groups [0,1] and [3,4], like (1 0 2 4 3 5 6).
7860class FoldTransposeBroadcast : public OpRewritePattern<vector::TransposeOp> {
7861public:
7862 using Base::Base;
7863 FoldTransposeBroadcast(MLIRContext *context, PatternBenefit benefit = 1)
7864 : OpRewritePattern<vector::TransposeOp>(context, benefit) {}
7865
7866 LogicalResult matchAndRewrite(vector::TransposeOp transpose,
7867 PatternRewriter &rewriter) const override {
7868
7869 vector::BroadcastOp broadcast =
7870 transpose.getVector().getDefiningOp<vector::BroadcastOp>();
7871 if (!broadcast) {
7872 return rewriter.notifyMatchFailure(transpose,
7873 "not preceded by a broadcast");
7874 }
7875
7876 auto inputType = dyn_cast<VectorType>(broadcast.getSourceType());
7877 VectorType outputType = transpose.getResultVectorType();
7878
7879 // transpose(broadcast(scalar)) -> broadcast(scalar) is always valid
7880 bool inputIsScalar = !inputType;
7881 if (inputIsScalar) {
7882 rewriter.replaceOpWithNewOp<vector::BroadcastOp>(transpose, outputType,
7883 broadcast.getSource());
7884 return success();
7885 }
7886
7887 ArrayRef<int64_t> permutation = transpose.getPermutation();
7888 ArrayRef<int64_t> inputShape = inputType.getShape();
7889 int64_t inputRank = inputType.getRank();
7890 int64_t outputRank = transpose.getType().getRank();
7891 int64_t deltaRank = outputRank - inputRank;
7892
7893 int low = 0;
7894 for (int inputIndex = 0; inputIndex < inputRank; ++inputIndex) {
7895 bool notOne = inputShape[inputIndex] != 1;
7896 bool prevNotOne = (inputIndex != 0 && inputShape[inputIndex - 1] != 1);
7897 bool groupEndFound = notOne || prevNotOne;
7898 if (groupEndFound) {
7899 int high = inputIndex + deltaRank;
7900 // Return failure if not all permutation destinations for indices in
7901 // [low, high) are in [low, high), i.e. the permutation is not local to
7902 // the group.
7903 for (int i = low; i < high; ++i) {
7904 if (permutation[i] < low || permutation[i] >= high) {
7905 return rewriter.notifyMatchFailure(
7906 transpose, "permutation not local to group");
7907 }
7908 }
7909 low = high;
7910 }
7911 }
7912
7913 // We don't need to check the final group [low, outputRank) because if it is
7914 // not locally bound, there must be a preceding group that already failed
7915 // the check (impossible to have just 1 non-locally bound group).
7916
7917 // The preceding logic also ensures that at this point, the output of the
7918 // transpose is definitely broadcastable from the input shape, assert so:
7919 assert(vector::isBroadcastableTo(inputType, outputType) ==
7920 vector::BroadcastableToResult::Success &&
7921 "not broadcastable directly to transpose output");
7922
7923 rewriter.replaceOpWithNewOp<vector::BroadcastOp>(transpose, outputType,
7924 broadcast.getSource());
7925
7926 return success();
7927 }
7928};
7929
7930} // namespace
7931
7932void vector::TransposeOp::getCanonicalizationPatterns(
7933 RewritePatternSet &results, MLIRContext *context) {
7934 results.add<FoldTransposeCreateMask, FoldTransposeShapeCast, TransposeFolder,
7935 FoldTransposeSplat, FoldTransposeFromElements,
7936 FoldTransposeBroadcast>(context);
7937}
7938
7939//===----------------------------------------------------------------------===//
7940// ConstantMaskOp
7941//===----------------------------------------------------------------------===//
7942
7943void ConstantMaskOp::build(OpBuilder &builder, OperationState &result,
7944 VectorType type, ConstantMaskKind kind) {
7945 assert(kind == ConstantMaskKind::AllTrue ||
7946 kind == ConstantMaskKind::AllFalse);
7947 auto maskDimSizes = llvm::to_vector(type.getShape());
7948 if (maskDimSizes.empty())
7949 maskDimSizes.push_back(1);
7950 if (kind == ConstantMaskKind::AllFalse)
7951 maskDimSizes.assign(maskDimSizes.size(), 0);
7952 build(builder, result, type, maskDimSizes);
7953}
7954
7955LogicalResult ConstantMaskOp::verify() {
7956 auto resultType = llvm::cast<VectorType>(getResult().getType());
7957 // Check the corner case of 0-D vectors first.
7958 if (resultType.getRank() == 0) {
7959 if (getMaskDimSizes().size() != 1)
7960 return emitError("array attr must have length 1 for 0-D vectors");
7961 auto dim = getMaskDimSizes()[0];
7962 if (dim != 0 && dim != 1)
7963 return emitError("mask dim size must be either 0 or 1 for 0-D vectors");
7964 return success();
7965 }
7966
7967 // Verify that array attr size matches the rank of the vector result.
7968 if (static_cast<int64_t>(getMaskDimSizes().size()) != resultType.getRank())
7969 return emitOpError(
7970 "must specify array attr of size equal vector result rank");
7971 // Verify that each array attr element is in bounds of corresponding vector
7972 // result dimension size.
7973 auto resultShape = resultType.getShape();
7974 auto resultScalableDims = resultType.getScalableDims();
7975 ArrayRef<int64_t> maskDimSizes = getMaskDimSizes();
7976 for (const auto [index, maskDimSize] : llvm::enumerate(maskDimSizes)) {
7977 if (maskDimSize < 0 || maskDimSize > resultShape[index])
7978 return emitOpError(
7979 "array attr of size out of bounds of vector result dimension size");
7980 if (resultScalableDims[index] && maskDimSize != 0 &&
7981 maskDimSize != resultShape[index])
7982 return emitOpError(
7983 "only supports 'none set' or 'all set' scalable dimensions");
7984 }
7985 // Verify that if one mask dim size is zero, they all should be zero (because
7986 // the mask region is a conjunction of each mask dimension interval).
7987 bool anyZeros = llvm::is_contained(maskDimSizes, 0);
7988 bool allZeros = llvm::all_of(maskDimSizes, [](int64_t s) { return s == 0; });
7989 if (anyZeros && !allZeros)
7990 return emitOpError("expected all mask dim sizes to be zeros, "
7991 "as a result of conjunction with zero mask dim");
7992 return success();
7993}
7994
7995bool ConstantMaskOp::isAllOnesMask() {
7996 auto resultType = getVectorType();
7997 // Check the corner case of 0-D vectors first.
7998 if (resultType.getRank() == 0) {
7999 assert(getMaskDimSizes().size() == 1 && "invalid sizes for zero rank mask");
8000 return getMaskDimSizes()[0] == 1;
8001 }
8002 for (const auto [resultSize, maskDimSize] :
8003 llvm::zip_equal(resultType.getShape(), getMaskDimSizes())) {
8004 if (maskDimSize < resultSize)
8005 return false;
8006 }
8007 return true;
8008}
8009
8010OpFoldResult ConstantMaskOp::fold(FoldAdaptor adaptor) {
8011 ArrayRef<int64_t> bounds = getMaskDimSizes();
8012 ArrayRef<int64_t> vectorSizes = getVectorType().getShape();
8013
8014 auto createBoolSplat = [&](bool x) {
8015 return SplatElementsAttr::get(getVectorType(),
8017 };
8018
8019 // Check the corner case of 0-D vectors first.
8020 if (vectorSizes.empty()) {
8021 assert(bounds.size() == 1 && "invalid sizes for zero rank mask");
8022 return createBoolSplat(bounds[0] == 1);
8023 }
8024 // Fold vector.constant_mask to splat if possible.
8025 if (bounds == vectorSizes)
8026 return createBoolSplat(true);
8027 if (llvm::all_of(bounds, [](int64_t x) { return x == 0; }))
8028 return createBoolSplat(false);
8029 return OpFoldResult();
8030}
8031
8032std::optional<SmallVector<int64_t>>
8033ConstantMaskOp::getDefaultUnrollTargetShape() {
8035}
8036
8037//===----------------------------------------------------------------------===//
8038// CreateMaskOp
8039//===----------------------------------------------------------------------===//
8040
8041void CreateMaskOp::build(OpBuilder &builder, OperationState &result,
8042 VectorType type,
8043 ArrayRef<OpFoldResult> mixedOperands) {
8044 SmallVector<Value> operands =
8045 getValueOrCreateConstantIndexOp(builder, result.location, mixedOperands);
8046 build(builder, result, type, operands);
8047}
8048
8049LogicalResult CreateMaskOp::verify() {
8050 auto vectorType = llvm::cast<VectorType>(getResult().getType());
8051 // Verify that an operand was specified for each result vector each dimension.
8052 if (vectorType.getRank() == 0) {
8053 if (getNumOperands() != 1)
8054 return emitOpError(
8055 "must specify exactly one operand for 0-D create_mask");
8056 } else if (getNumOperands() !=
8057 llvm::cast<VectorType>(getResult().getType()).getRank()) {
8058 return emitOpError(
8059 "must specify an operand for each result vector dimension");
8060 }
8061 return success();
8062}
8063
8064std::optional<SmallVector<int64_t>>
8065CreateMaskOp::getDefaultUnrollTargetShape() {
8067}
8068
8069namespace {
8070
8071/// Pattern to rewrite a CreateMaskOp with a ConstantMaskOp.
8072///
8073/// Ex 1:
8074/// %c2 = arith.constant 2 : index
8075/// %c3 = arith.constant 3 : index
8076/// %0 = vector.create_mask %c3, %c2 : vector<4x3xi1>
8077/// Becomes:
8078/// vector.constant_mask [3, 2] : vector<4x3xi1>
8079///
8080/// Ex 2:
8081/// %c_neg_1 = arith.constant -1 : index
8082/// %0 = vector.create_mask %c_neg_1 : vector<[8]xi1>
8083/// becomes:
8084/// vector.constant_mask [0] : vector<[8]xi1>
8085///
8086/// Ex 3:
8087/// %c8 = arith.constant 8 : index
8088/// %c16 = arith.constant 16 : index
8089/// %0 = vector.vscale
8090/// %1 = arith.muli %0, %c16 : index
8091/// %10 = vector.create_mask %c8, %1 : vector<8x[16]xi1>
8092/// becomes:
8093/// %0 = vector.constant_mask [8, 16] : vector<8x[16]xi1>
8094class CreateMaskFolder final : public OpRewritePattern<CreateMaskOp> {
8095public:
8096 using Base::Base;
8097
8098 LogicalResult matchAndRewrite(CreateMaskOp createMaskOp,
8099 PatternRewriter &rewriter) const override {
8100 VectorType maskType = createMaskOp.getVectorType();
8101 ArrayRef<int64_t> maskTypeDimSizes = maskType.getShape();
8102 ArrayRef<bool> maskTypeDimScalableFlags = maskType.getScalableDims();
8103
8104 // Special case: Rank zero shape.
8105 constexpr std::array<int64_t, 1> rankZeroShape{1};
8106 constexpr std::array<bool, 1> rankZeroScalableDims{false};
8107 if (maskType.getRank() == 0) {
8108 maskTypeDimSizes = rankZeroShape;
8109 maskTypeDimScalableFlags = rankZeroScalableDims;
8110 }
8111
8112 // Determine if this CreateMaskOp can be folded to a ConstantMaskOp and
8113 // collect the `constantDims` (for the ConstantMaskOp).
8114 SmallVector<int64_t, 4> constantDims;
8115 for (auto [i, dimSize] : llvm::enumerate(createMaskOp.getOperands())) {
8116 if (auto intSize = getConstantIntValue(dimSize)) {
8117 // Constant value.
8118 // If the mask dim is non-scalable this can be any value.
8119 // If the mask dim is scalable only zero (all-false) is supported.
8120 if (maskTypeDimScalableFlags[i] && intSize >= 0)
8121 return failure();
8122 constantDims.push_back(*intSize);
8123 } else if (auto vscaleMultiplier = getConstantVscaleMultiplier(dimSize)) {
8124 // Constant vscale multiple (e.g. 4 x vscale).
8125 // Must be all-true to fold to a ConstantMask.
8126 if (vscaleMultiplier < maskTypeDimSizes[i])
8127 return failure();
8128 constantDims.push_back(*vscaleMultiplier);
8129 } else {
8130 return failure();
8131 }
8132 }
8133
8134 // Clamp values to constant_mask bounds.
8135 for (auto [value, maskDimSize] : llvm::zip(constantDims, maskTypeDimSizes))
8136 value = std::clamp<int64_t>(value, 0, maskDimSize);
8137
8138 // If one of dim sizes is zero, set all dims to zero.
8139 if (llvm::is_contained(constantDims, 0))
8140 constantDims.assign(constantDims.size(), 0);
8141
8142 // Replace 'createMaskOp' with ConstantMaskOp.
8143 rewriter.replaceOpWithNewOp<ConstantMaskOp>(createMaskOp, maskType,
8144 constantDims);
8145 return success();
8146 }
8147};
8148
8149} // namespace
8150
8151void CreateMaskOp::getCanonicalizationPatterns(RewritePatternSet &results,
8152 MLIRContext *context) {
8153 results.add<CreateMaskFolder>(context);
8154}
8155
8156//===----------------------------------------------------------------------===//
8157// MaskOp
8158//===----------------------------------------------------------------------===//
8159
8160void MaskOp::build(
8161 OpBuilder &builder, OperationState &result, Value mask,
8162 Operation *maskableOp,
8163 function_ref<void(OpBuilder &, Operation *)> maskRegionBuilder) {
8164 assert(maskRegionBuilder &&
8165 "builder callback for 'maskRegion' must be present");
8166
8167 result.addOperands(mask);
8168 OpBuilder::InsertionGuard guard(builder);
8169 Region *maskRegion = result.addRegion();
8170 builder.createBlock(maskRegion);
8171 maskRegionBuilder(builder, maskableOp);
8172}
8173
8174void MaskOp::build(
8175 OpBuilder &builder, OperationState &result, TypeRange resultTypes,
8176 Value mask, Operation *maskableOp,
8177 function_ref<void(OpBuilder &, Operation *)> maskRegionBuilder) {
8178 build(builder, result, resultTypes, mask, /*passthru=*/Value(), maskableOp,
8179 maskRegionBuilder);
8180}
8181
8182void MaskOp::build(
8183 OpBuilder &builder, OperationState &result, TypeRange resultTypes,
8184 Value mask, Value passthru, Operation *maskableOp,
8185 function_ref<void(OpBuilder &, Operation *)> maskRegionBuilder) {
8186 build(builder, result, mask, maskableOp, maskRegionBuilder);
8187 if (passthru)
8188 result.addOperands(passthru);
8189 result.addTypes(resultTypes);
8190}
8191
8192ParseResult MaskOp::parse(OpAsmParser &parser, OperationState &result) {
8193 // Create the op region.
8194 result.regions.reserve(1);
8195 Region &maskRegion = *result.addRegion();
8196
8197 auto &builder = parser.getBuilder();
8198
8199 // Parse all the operands.
8200 OpAsmParser::UnresolvedOperand mask;
8201 if (parser.parseOperand(mask))
8202 return failure();
8203
8204 // Optional passthru operand.
8205 OpAsmParser::UnresolvedOperand passthru;
8206 ParseResult parsePassthru = parser.parseOptionalComma();
8207 if (parsePassthru.succeeded() && parser.parseOperand(passthru))
8208 return failure();
8209
8210 // Parse op region.
8211 if (parser.parseRegion(maskRegion, /*arguments=*/{}, /*argTypes=*/{}))
8212 return failure();
8213
8214 MaskOp::ensureTerminator(maskRegion, builder, result.location);
8215
8216 // Parse the optional attribute list.
8217 if (parser.parseOptionalAttrDict(result.attributes))
8218 return failure();
8219
8220 // Parse all the types.
8221 Type maskType;
8222 if (parser.parseColonType(maskType))
8223 return failure();
8224
8225 SmallVector<Type> resultTypes;
8226 if (parser.parseOptionalArrowTypeList(resultTypes))
8227 return failure();
8228 result.types.append(resultTypes);
8229
8230 // Resolve operands.
8231 if (parser.resolveOperand(mask, maskType, result.operands))
8232 return failure();
8233
8234 if (parsePassthru.succeeded()) {
8235 if (resultTypes.empty())
8236 return parser.emitError(
8237 parser.getNameLoc(),
8238 "expects a result if passthru operand is provided");
8239
8240 if (parser.resolveOperand(passthru, resultTypes[0], result.operands))
8241 return failure();
8242 }
8243
8244 return success();
8245}
8246
8247void mlir::vector::MaskOp::print(OpAsmPrinter &p) {
8248 p << " " << getMask();
8249 if (getPassthru())
8250 p << ", " << getPassthru();
8251
8252 // Print single masked operation and skip terminator.
8253 p << " { ";
8254 Block *singleBlock = &getMaskRegion().getBlocks().front();
8255 if (singleBlock && !singleBlock->getOperations().empty())
8256 p.printCustomOrGenericOp(&singleBlock->front());
8257 p << " }";
8258
8260 getOperation()->getDiscardableAttrDictionary().getValue());
8261
8262 p << " : " << getMask().getType();
8263 if (getNumResults() > 0)
8264 p << " -> " << getResultTypes();
8265}
8266
8267void MaskOp::ensureTerminator(Region &region, Builder &builder, Location loc) {
8268 // 1. For an empty `vector.mask`, create a default terminator.
8269 if (region.empty() || region.front().empty()) {
8270 OpTrait::SingleBlockImplicitTerminator<vector::YieldOp>::Impl<
8271 MaskOp>::ensureTerminator(region, builder, loc);
8272 return;
8273 }
8274
8275 // 2. For a non-empty `vector.mask` with an explicit terminator, do nothing.
8276 Block &block = region.front();
8277 if (isa<vector::YieldOp>(block.back()))
8278 return;
8279
8280 // 3. For a non-empty `vector.mask` without an explicit terminator:
8281
8282 // Create default terminator if the number of masked operations is not
8283 // one. This case will trigger a verification failure.
8284 if (block.getOperations().size() != 1) {
8285 OpTrait::SingleBlockImplicitTerminator<vector::YieldOp>::Impl<
8286 MaskOp>::ensureTerminator(region, builder, loc);
8287 return;
8288 }
8289
8290 // Create a terminator that yields the results from the masked operation.
8291 OpBuilder opBuilder(builder.getContext());
8292 Operation *maskedOp = &block.front();
8293 opBuilder.setInsertionPointToEnd(&block);
8294 vector::YieldOp::create(opBuilder, loc, maskedOp->getResults());
8295}
8296
8297LogicalResult MaskOp::verify() {
8298 // Structural checks.
8299 Block &block = getMaskRegion().getBlocks().front();
8300 if (block.getOperations().empty())
8301 return emitOpError("expects a terminator within the mask region");
8302
8303 unsigned numMaskRegionOps = block.getOperations().size();
8304 if (numMaskRegionOps > 2)
8305 return emitOpError("expects only one operation to mask");
8306
8307 // Terminator checks.
8308 auto terminator = dyn_cast<vector::YieldOp>(block.back());
8309 if (!terminator)
8310 return emitOpError("expects a terminator within the mask region");
8311
8312 if (terminator->getNumOperands() != getNumResults())
8313 return emitOpError(
8314 "expects number of results to match mask region yielded values");
8315
8316 // Empty vector.mask. Nothing else to check.
8317 if (numMaskRegionOps == 1)
8318 return success();
8319
8320 auto maskableOp = dyn_cast<MaskableOpInterface>(block.front());
8321 if (!maskableOp)
8322 return emitOpError("expects a MaskableOpInterface within the mask region");
8323
8324 // Result checks.
8325 if (maskableOp->getNumResults() != getNumResults())
8326 return emitOpError("expects number of results to match maskable operation "
8327 "number of results");
8328
8329 if (!llvm::equal(maskableOp->getResults(), terminator.getOperands()))
8330 return emitOpError("expects all the results from the MaskableOpInterface "
8331 "to match all the values returned by the terminator");
8332
8333 if (!llvm::equal(maskableOp->getResultTypes(), getResultTypes()))
8334 return emitOpError(
8335 "expects result type to match maskable operation result type");
8336
8337 if (llvm::count_if(maskableOp->getResultTypes(),
8338 [](Type t) { return llvm::isa<VectorType>(t); }) > 1)
8339 return emitOpError("multiple vector results not supported");
8340
8341 // TODO: Remove once https://github.com/llvm/llvm-project/issues/239511 is
8342 // completed
8343 auto transferOp =
8344 dyn_cast<VectorTransferOpInterface>(maskableOp.getOperation());
8345 if (transferOp && transferOp.getMask())
8346 return emitOpError(
8347 "doesn't expect a mask operand for the masked transfer operation");
8348
8349 // TODO: This does not belong here, but there is just no good way to mask
8350 // transfer Ops with vector elements. Instead, cnsider removing support for
8351 // vector elements in XFer ops.
8352 if (transferOp &&
8353 isa<VectorType>(transferOp.getShapedType().getElementType()))
8354 return emitOpError("does not support masking a transfer operation on a "
8355 "source with vector element type");
8356
8357 // Mask checks.
8358 Type expectedMaskType = maskableOp.getExpectedMaskType();
8359 if (getMask().getType() != expectedMaskType)
8360 return emitOpError("expects a ")
8361 << expectedMaskType << " mask for the maskable operation";
8362
8363 // Passthru checks.
8364 Value passthru = getPassthru();
8365 if (passthru) {
8366 if (!maskableOp.supportsPassthru())
8367 return emitOpError(
8368 "doesn't expect a passthru argument for this maskable operation");
8369
8370 if (maskableOp->getNumResults() != 1)
8371 return emitOpError("expects result when passthru argument is provided");
8372
8373 if (passthru.getType() != maskableOp->getResultTypes()[0])
8374 return emitOpError("expects passthru type to match result type");
8375 }
8376
8377 return success();
8378}
8379
8380/// Folds empty `vector.mask` with no passthru operand and with or without
8381/// return values. For example:
8382///
8383/// %0 = vector.mask %mask { vector.yield %a : vector<8xf32> } :
8384/// vector<8xi1> -> vector<8xf32>
8385/// %1 = user_op %0 : vector<8xf32>
8386///
8387/// becomes:
8388///
8389/// %0 = user_op %a : vector<8xf32>
8390///
8391/// Empty `vector.mask` with passthru operand are handled by the canonicalizer
8392/// as it requires creating new operations.
8393
8394static LogicalResult foldEmptyMaskOp(MaskOp maskOp, MaskOp::FoldAdaptor adaptor,
8395 SmallVectorImpl<OpFoldResult> &results) {
8396 if (!maskOp.isEmpty() || maskOp.hasPassthru())
8397 return failure();
8398
8399 Block *block = maskOp.getMaskBlock();
8400 auto terminator = cast<vector::YieldOp>(block->front());
8401 if (terminator.getNumOperands() == 0)
8402 return failure();
8403
8404 // `vector.mask` has results, propagate the results.
8405 llvm::append_range(results, terminator.getOperands());
8406 return success();
8407}
8408
8409LogicalResult MaskOp::fold(FoldAdaptor adaptor,
8410 SmallVectorImpl<OpFoldResult> &results) {
8411 if (succeeded(foldEmptyMaskOp(*this, adaptor, results)))
8412 return success();
8413
8414 MaskFormat maskFormat = getMaskFormat(getMask());
8415 if (maskFormat != MaskFormat::AllTrue)
8416 return failure();
8417
8418 // Move maskable operation outside of the `vector.mask` region.
8419 // If there is no maskable op (empty body), the fold cannot proceed; the
8420 // canonicalizer handles this case instead.
8421 Operation *maskableOp = getMaskableOp();
8422 if (!maskableOp)
8423 return failure();
8424 maskableOp->dropAllUses();
8425 maskableOp->moveBefore(getOperation());
8426
8427 llvm::append_range(results, maskableOp->getResults());
8428 return success();
8429}
8430
8431/// Canonialize empty `vector.mask` operations that can't be handled in
8432/// `VectorMask::fold` as they require creating new operations.
8433///
8434/// Example 1: Empty `vector.mask` with passthru operand.
8435///
8436/// %0 = vector.mask %mask, %passthru { vector.yield %a : vector<8xf32> } :
8437/// vector<8xi1> -> vector<8xf32>
8438///
8439/// becomes:
8440///
8441/// %0 = arith.select %mask, %a, %passthru : vector<8xf32>
8442///
8443class CanonializeEmptyMaskOp : public OpRewritePattern<MaskOp> {
8444 using Base::Base;
8445
8446 LogicalResult matchAndRewrite(MaskOp maskOp,
8447 PatternRewriter &rewriter) const override {
8448 if (!maskOp.isEmpty())
8449 return failure();
8450
8451 if (!maskOp.hasPassthru())
8452 return failure();
8453
8454 // arith.select with a vector condition requires the value types to be
8455 // vectors of the same shape. Since vector.mask always has a vector mask
8456 // type, bail out when any result type doesn't match the mask shape to
8457 // avoid creating invalid IR.
8458 VectorType maskType = maskOp.getMask().getType();
8459 for (Type resultType : maskOp.getResultTypes()) {
8460 auto vecResultType = dyn_cast<VectorType>(resultType);
8461 if (!vecResultType || vecResultType.getShape() != maskType.getShape())
8462 return failure();
8463 }
8464
8465 Block *block = maskOp.getMaskBlock();
8466 auto terminator = cast<vector::YieldOp>(block->front());
8467 assert(terminator.getNumOperands() == 1 &&
8468 "expected one result when passthru is provided");
8469
8470 rewriter.replaceOpWithNewOp<arith::SelectOp>(
8471 maskOp, maskOp.getResultTypes(), maskOp.getMask(),
8472 terminator.getOperand(0), maskOp.getPassthru());
8473
8474 return success();
8475 }
8476};
8477
8478void MaskOp::getCanonicalizationPatterns(RewritePatternSet &results,
8479 MLIRContext *context) {
8480 results.add<CanonializeEmptyMaskOp>(context);
8481}
8482
8483// MaskingOpInterface definitions.
8484
8485/// Returns the operation masked by this 'vector.mask'.
8486Operation *MaskOp::getMaskableOp() {
8487 Block *block = getMaskBlock();
8488 if (block->getOperations().size() < 2)
8489 return nullptr;
8490
8491 return &block->front();
8492}
8493
8494/// Returns true if 'vector.mask' has a passthru value.
8495bool MaskOp::hasPassthru() { return getPassthru() != Value(); }
8496
8497//===----------------------------------------------------------------------===//
8498// ScanOp
8499//===----------------------------------------------------------------------===//
8500
8501LogicalResult ScanOp::verify() {
8502 VectorType srcType = getSourceType();
8503 VectorType initialType = getInitialValueType();
8504 // Check reduction dimension < rank.
8505 int64_t srcRank = srcType.getRank();
8506 int64_t reductionDim = getReductionDim();
8507 if (reductionDim >= srcRank)
8508 return emitOpError("reduction dimension ")
8509 << reductionDim << " has to be less than " << srcRank;
8510
8511 // Check that rank(initial_value) = rank(src) - 1.
8512 int64_t initialValueRank = initialType.getRank();
8513 if (initialValueRank != srcRank - 1)
8514 return emitOpError("initial value rank ")
8515 << initialValueRank << " has to be equal to " << srcRank - 1;
8516
8517 // Check shapes of initial value and src.
8518 ArrayRef<int64_t> srcShape = srcType.getShape();
8519 ArrayRef<int64_t> initialValueShapes = initialType.getShape();
8520 SmallVector<int64_t> expectedShape;
8521 for (int i = 0; i < srcRank; i++) {
8522 if (i != reductionDim)
8523 expectedShape.push_back(srcShape[i]);
8524 }
8525 if (!llvm::equal(initialValueShapes, expectedShape)) {
8526 return emitOpError("incompatible input/initial value shapes");
8527 }
8528
8529 // Verify supported reduction kind.
8530 Type eltType = getDestType().getElementType();
8531 if (!isSupportedCombiningKind(getKind(), eltType))
8532 return emitOpError("unsupported reduction type ")
8533 << eltType << " for kind '" << stringifyCombiningKind(getKind())
8534 << "'";
8535
8536 return success();
8537}
8538
8540 RewritePatternSet &patterns, PatternBenefit benefit) {
8541 patterns
8542 .add<CreateMaskFolder, MaskedLoadFolder, MaskedStoreFolder, GatherFolder,
8543 ScatterFolder, ExpandLoadFolder, CompressStoreFolder,
8544 StridedSliceConstantMaskFolder, TransposeFolder>(
8545 patterns.getContext(), benefit);
8546}
8547
8548Value mlir::vector::makeArithReduction(OpBuilder &b, Location loc,
8549 CombiningKind kind, Value v1, Value acc,
8550 arith::FastMathFlagsAttr fastmath,
8551 Value mask) {
8552 Type t1 = getElementTypeOrSelf(v1.getType());
8553 Type tAcc = getElementTypeOrSelf(acc.getType());
8554 Value result;
8555
8556 switch (kind) {
8557 case CombiningKind::ADD:
8558 if (t1.isIntOrIndex() && tAcc.isIntOrIndex())
8559 result = b.createOrFold<arith::AddIOp>(loc, v1, acc);
8560 else if (llvm::isa<FloatType>(t1) && llvm::isa<FloatType>(tAcc))
8561 result = b.createOrFold<arith::AddFOp>(loc, v1, acc, fastmath);
8562 else
8563 llvm_unreachable("invalid value types for ADD reduction");
8564 break;
8565 case CombiningKind::AND:
8566 assert(t1.isIntOrIndex() && tAcc.isIntOrIndex() && "expected int values");
8567 result = b.createOrFold<arith::AndIOp>(loc, v1, acc);
8568 break;
8569 case CombiningKind::MAXNUMF:
8570 assert(llvm::isa<FloatType>(t1) && llvm::isa<FloatType>(tAcc) &&
8571 "expected float values");
8572 result = b.createOrFold<arith::MaxNumFOp>(loc, v1, acc, fastmath);
8573 break;
8574 case CombiningKind::MAXIMUMNUMF:
8575 assert(llvm::isa<FloatType>(t1) && llvm::isa<FloatType>(tAcc) &&
8576 "expected float values");
8577 result = b.createOrFold<arith::MaximumNumFOp>(loc, v1, acc, fastmath);
8578 break;
8579 case CombiningKind::MAXIMUMF:
8580 assert(llvm::isa<FloatType>(t1) && llvm::isa<FloatType>(tAcc) &&
8581 "expected float values");
8582 result = b.createOrFold<arith::MaximumFOp>(loc, v1, acc, fastmath);
8583 break;
8584 case CombiningKind::MINNUMF:
8585 assert(llvm::isa<FloatType>(t1) && llvm::isa<FloatType>(tAcc) &&
8586 "expected float values");
8587 result = b.createOrFold<arith::MinNumFOp>(loc, v1, acc, fastmath);
8588 break;
8589 case CombiningKind::MINIMUMNUMF:
8590 assert(llvm::isa<FloatType>(t1) && llvm::isa<FloatType>(tAcc) &&
8591 "expected float values");
8592 result = b.createOrFold<arith::MinimumNumFOp>(loc, v1, acc, fastmath);
8593 break;
8594 case CombiningKind::MINIMUMF:
8595 assert(llvm::isa<FloatType>(t1) && llvm::isa<FloatType>(tAcc) &&
8596 "expected float values");
8597 result = b.createOrFold<arith::MinimumFOp>(loc, v1, acc, fastmath);
8598 break;
8599 case CombiningKind::MAXSI:
8600 assert(t1.isIntOrIndex() && tAcc.isIntOrIndex() && "expected int values");
8601 result = b.createOrFold<arith::MaxSIOp>(loc, v1, acc);
8602 break;
8603 case CombiningKind::MINSI:
8604 assert(t1.isIntOrIndex() && tAcc.isIntOrIndex() && "expected int values");
8605 result = b.createOrFold<arith::MinSIOp>(loc, v1, acc);
8606 break;
8607 case CombiningKind::MAXUI:
8608 assert(t1.isIntOrIndex() && tAcc.isIntOrIndex() && "expected int values");
8609 result = b.createOrFold<arith::MaxUIOp>(loc, v1, acc);
8610 break;
8611 case CombiningKind::MINUI:
8612 assert(t1.isIntOrIndex() && tAcc.isIntOrIndex() && "expected int values");
8613 result = b.createOrFold<arith::MinUIOp>(loc, v1, acc);
8614 break;
8615 case CombiningKind::MUL:
8616 if (t1.isIntOrIndex() && tAcc.isIntOrIndex())
8617 result = b.createOrFold<arith::MulIOp>(loc, v1, acc);
8618 else if (llvm::isa<FloatType>(t1) && llvm::isa<FloatType>(tAcc))
8619 result = b.createOrFold<arith::MulFOp>(loc, v1, acc, fastmath);
8620 else
8621 llvm_unreachable("invalid value types for MUL reduction");
8622 break;
8623 case CombiningKind::OR:
8624 assert(t1.isIntOrIndex() && tAcc.isIntOrIndex() && "expected int values");
8625 result = b.createOrFold<arith::OrIOp>(loc, v1, acc);
8626 break;
8627 case CombiningKind::XOR:
8628 assert(t1.isIntOrIndex() && tAcc.isIntOrIndex() && "expected int values");
8629 result = b.createOrFold<arith::XOrIOp>(loc, v1, acc);
8630 break;
8631 };
8632
8633 assert(result && "unknown CombiningKind");
8634 return selectPassthru(b, mask, result, acc);
8635}
8636
8637//===----------------------------------------------------------------------===//
8638// StepOp
8639//===----------------------------------------------------------------------===//
8640
8641void StepOp::inferResultRanges(ArrayRef<ConstantIntRanges> argRanges,
8642 SetIntRangeFn setResultRanges) {
8643 auto resultType = cast<VectorType>(getType());
8644 if (resultType.isScalable()) {
8645 return;
8646 }
8647 unsigned bitwidth = ConstantIntRanges::getStorageBitwidth(resultType);
8648 // The result holds the sequence [0, 1, ..., N-1], with each value truncated
8649 // to the result element type.
8650 uint64_t maxIndex = resultType.getDimSize(0) - 1;
8651 APInt umin = APInt::getZero(bitwidth);
8652 APInt umax = APInt::getMaxValue(bitwidth).ugt(maxIndex)
8653 ? APInt(bitwidth, maxIndex)
8654 : APInt::getMaxValue(bitwidth);
8655 setResultRanges(getResult(), ConstantIntRanges::fromUnsigned(umin, umax));
8656}
8657
8658std::optional<SmallVector<int64_t>> StepOp::getDefaultUnrollTargetShape() {
8659 return SmallVector<int64_t>{8};
8660}
8661
8662namespace {
8663
8664/// Fold `vector.step -> arith.cmpi` when the step value is compared to a
8665/// constant large enough such that the result is the same at all indices.
8666///
8667/// For example, rewrite the 'greater than' comparison below,
8668///
8669/// ```mlir
8670/// %cst = arith.constant dense<7> : vector<3xindex>
8671/// %stp = vector.step : vector<3xindex>
8672/// %out = arith.cmpi ugt, %stp, %cst : vector<3xindex>
8673/// ```
8674///
8675/// as,
8676///
8677/// ```mlir
8678/// %out = arith.constant dense<false> : vector<3xi1>.
8679/// ```
8680///
8681/// Above `[0, 1, 2] > [7, 7, 7]` => `[false, false, false]`. Because the result
8682/// is false at ALL indices we fold. If the constant was 1, then
8683/// `[0, 1, 2] > [1, 1, 1]` => `[false, false, true]` and we do fold,
8684/// conservatively preferring the 'compact' vector.step representation.
8685///
8686/// Note: this folder only works for the case where the constant (`%cst` above)
8687/// is the second operand of the comparison. The arith.cmpi canonicalizer will
8688/// ensure that constants are always second (on the right).
8689struct StepCompareFolder : public OpRewritePattern<StepOp> {
8690 using Base::Base;
8691
8692 LogicalResult matchAndRewrite(StepOp stepOp,
8693 PatternRewriter &rewriter) const override {
8694 const int64_t stepSize = stepOp.getResult().getType().getNumElements();
8695
8696 for (OpOperand &use : stepOp.getResult().getUses()) {
8697 auto cmpiOp = dyn_cast<arith::CmpIOp>(use.getOwner());
8698 if (!cmpiOp)
8699 continue;
8700
8701 // arith.cmpi canonicalizer makes constants final operands.
8702 const unsigned stepOperandNumber = use.getOperandNumber();
8703 if (stepOperandNumber != 0)
8704 continue;
8705
8706 // Check that operand 1 is a constant.
8707 unsigned constOperandNumber = 1;
8708 Value otherOperand = cmpiOp.getOperand(constOperandNumber);
8709 std::optional<int64_t> maybeConstValue =
8710 getConstantIntValue(otherOperand);
8711 if (!maybeConstValue.has_value())
8712 continue;
8713
8714 int64_t constValue = maybeConstValue.value();
8715 arith::CmpIPredicate pred = cmpiOp.getPredicate();
8716
8717 auto maybeSplat = [&]() -> std::optional<bool> {
8718 // Handle ult (unsigned less than) and uge (unsigned greater equal).
8719 if ((pred == arith::CmpIPredicate::ult ||
8720 pred == arith::CmpIPredicate::uge) &&
8721 stepSize <= constValue)
8722 return pred == arith::CmpIPredicate::ult;
8723
8724 // Handle ule and ugt.
8725 if ((pred == arith::CmpIPredicate::ule ||
8726 pred == arith::CmpIPredicate::ugt) &&
8727 stepSize - 1 <= constValue) {
8728 return pred == arith::CmpIPredicate::ule;
8729 }
8730
8731 // Handle eq and ne.
8732 if ((pred == arith::CmpIPredicate::eq ||
8733 pred == arith::CmpIPredicate::ne) &&
8734 stepSize <= constValue)
8735 return pred == arith::CmpIPredicate::ne;
8736
8737 return std::nullopt;
8738 }();
8739
8740 if (!maybeSplat.has_value())
8741 continue;
8742
8743 rewriter.setInsertionPointAfter(cmpiOp);
8744
8745 auto type = dyn_cast<VectorType>(cmpiOp.getResult().getType());
8746 if (!type)
8747 continue;
8748
8749 auto boolAttr = DenseElementsAttr::get(type, maybeSplat.value());
8750 Value splat = mlir::arith::ConstantOp::create(rewriter, cmpiOp.getLoc(),
8751 type, boolAttr);
8752
8753 rewriter.replaceOp(cmpiOp, splat);
8754 return success();
8755 }
8756
8757 return failure();
8758 }
8759};
8760} // namespace
8761
8762void StepOp::getCanonicalizationPatterns(RewritePatternSet &results,
8763 MLIRContext *context) {
8764 results.add<StepCompareFolder>(context);
8765}
8766
8767//===----------------------------------------------------------------------===//
8768// Vector Masking Utilities
8769//===----------------------------------------------------------------------===//
8770
8771/// Create the vector.yield-ended region of a vector.mask op with `maskableOp`
8772/// as masked operation.
8773void mlir::vector::createMaskOpRegion(OpBuilder &builder,
8774 Operation *maskableOp) {
8775 assert(maskableOp->getBlock() && "MaskableOp must be inserted into a block");
8776 Block *insBlock = builder.getInsertionBlock();
8777 // Create a block and move the op to that block.
8778 insBlock->getOperations().splice(
8779 insBlock->begin(), maskableOp->getBlock()->getOperations(), maskableOp);
8780 YieldOp::create(builder, maskableOp->getLoc(), maskableOp->getResults());
8781}
8782
8783/// Creates a vector.mask operation around a maskable operation. Returns the
8784/// vector.mask operation if the mask provided is valid. Otherwise, returns
8785/// the maskable operation itself.
8786Operation *mlir::vector::maskOperation(OpBuilder &builder,
8787 Operation *maskableOp, Value mask,
8788 Value passthru) {
8789 if (!mask)
8790 return maskableOp;
8791 if (passthru)
8792 return MaskOp::create(builder, maskableOp->getLoc(),
8793 maskableOp->getResultTypes(), mask, passthru,
8794 maskableOp, createMaskOpRegion);
8795 return MaskOp::create(builder, maskableOp->getLoc(),
8796 maskableOp->getResultTypes(), mask, maskableOp,
8798}
8799
8800/// Creates a vector select operation that picks values from `newValue` or
8801/// `passthru` for each result vector lane based on `mask`. This utility is used
8802/// to propagate the pass-thru value of vector.mask or for cases where only the
8803/// pass-thru value propagation is needed. VP intrinsics do not support
8804/// pass-thru values and every mask-out lane is set to poison. LLVM backends are
8805/// usually able to match op + select patterns and fold them into a native
8806/// target instructions.
8807Value mlir::vector::selectPassthru(OpBuilder &builder, Value mask,
8808 Value newValue, Value passthru) {
8809 if (!mask)
8810 return newValue;
8811
8812 return arith::SelectOp::create(builder, newValue.getLoc(), newValue.getType(),
8813 mask, newValue, passthru);
8814}
8815
8816//===----------------------------------------------------------------------===//
8817// InterleaveOp
8818//===----------------------------------------------------------------------===//
8819
8820namespace {
8821
8822/// This folder works on the following round-trip identity:
8823/// interleave(deinterleave(x).even, deinterleave(x).odd) -> x
8824struct InterleaveDeinterleaveFolder : public OpRewritePattern<InterleaveOp> {
8825 using Base::Base;
8826
8827 LogicalResult matchAndRewrite(InterleaveOp interleaveOp,
8828 PatternRewriter &rewriter) const override {
8829 auto lhsDefOp = interleaveOp.getLhs().getDefiningOp<DeinterleaveOp>();
8830 auto rhsDefOp = interleaveOp.getRhs().getDefiningOp<DeinterleaveOp>();
8831 if (!lhsDefOp || !rhsDefOp || lhsDefOp != rhsDefOp)
8832 return failure();
8833 for (auto [idx, operand] : llvm::enumerate(interleaveOp.getOperands())) {
8834 if (cast<OpResult>(operand).getResultNumber() != idx)
8835 return failure();
8836 }
8837 rewriter.replaceOp(interleaveOp, lhsDefOp.getSource());
8838 return success();
8839 }
8840};
8841} // namespace
8842
8843void InterleaveOp::getCanonicalizationPatterns(RewritePatternSet &results,
8844 MLIRContext *context) {
8845 results.add<InterleaveDeinterleaveFolder>(context);
8846}
8847
8848OpFoldResult InterleaveOp::fold(FoldAdaptor adaptor) {
8849 // interleave(splat(x), splat(x)) -> widened splat(x)
8850 auto splat = dyn_cast_if_present<SplatElementsAttr>(adaptor.getLhs());
8851 if (!splat || adaptor.getLhs() != adaptor.getRhs())
8852 return {};
8853 return SplatElementsAttr::get(getResultVectorType(),
8854 splat.getSplatValue<Attribute>());
8855}
8856
8857//-----------------------------------------------------------------------------
8858// VectorUnrollOpInterface methods
8859//-----------------------------------------------------------------------------
8860std::optional<SmallVector<int64_t, 4>>
8861InterleaveOp::getIterationShapeToUnroll() {
8862 return llvm::to_vector<4>(getResultVectorType().getShape());
8863}
8864
8865std::optional<SmallVector<int64_t>>
8866InterleaveOp::getDefaultUnrollTargetShape() {
8868}
8869
8870//===----------------------------------------------------------------------===//
8871// DeinterleaveOp
8872//===----------------------------------------------------------------------===//
8873//-----------------------------------------------------------------------------
8874// VectorUnrollOpInterface methods
8875//-----------------------------------------------------------------------------
8876
8877std::optional<SmallVector<int64_t, 4>>
8878DeinterleaveOp::getIterationShapeToUnroll() {
8879 return llvm::to_vector<4>(getResultVectorType().getShape());
8880}
8881std::optional<SmallVector<int64_t>>
8882DeinterleaveOp::getDefaultUnrollTargetShape() {
8884}
8885
8886//===----------------------------------------------------------------------===//
8887// VectorDialect canonicalization
8888//===----------------------------------------------------------------------===//
8889
8890namespace {
8891/// A broadcast of a scalar condition selects the same arm in every lane.
8892struct SelectBroadcastCondition : OpRewritePattern<arith::SelectOp> {
8893 using Base::Base;
8894
8895 LogicalResult matchAndRewrite(arith::SelectOp select,
8896 PatternRewriter &rewriter) const override {
8897 auto broadcast = select.getCondition().getDefiningOp<BroadcastOp>();
8898 if (!broadcast || !broadcast.getSourceType().isSignlessInteger(1))
8899 return failure();
8900 rewriter.modifyOpInPlace(select, [&] {
8901 select.getConditionMutable().assign(broadcast.getSource());
8902 });
8903 return success();
8904 }
8905};
8906} // namespace
8907
8908void VectorDialect::getCanonicalizationPatterns(
8909 RewritePatternSet &results) const {
8910 results.add<SelectBroadcastCondition>(getContext());
8911}
8912
8913//===----------------------------------------------------------------------===//
8914// TableGen'd op method definitions
8915//===----------------------------------------------------------------------===//
8916
8917#define GET_ATTRDEF_CLASSES
8918#include "mlir/Dialect/Vector/IR/VectorAttributes.cpp.inc"
8919
8920#define GET_OP_CLASSES
8921#include "mlir/Dialect/Vector/IR/VectorOps.cpp.inc"
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...
static void copy(Location loc, Value dst, Value src, Value size, OpBuilder &builder)
Copies the given number of bytes from src to dst pointers.
static Value getBase(Value v)
Looks through known "view-like" ops to find the base memref.
lhs
static bool isLegalToInline(InlinerInterface &interface, Region *src, Region *insertRegion, bool shouldCloneInlinedRegion, IRMapping &valueMapping)
Utility to check that all of the operations within 'src' can be inlined.
static SmallVector< unsigned > extractPosition(ArrayRef< int64_t > indices)
Convert the value of a DenseI64ArrayAttr to a vector of unsigned indices.
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
ArrayAttr()
if(!isCopyOut)
b getContext())
auto load
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
static ParseResult parseBoolAttr(OpAsmParser &parser, BoolAttr &result)
static void printBoolAttr(OpAsmPrinter &printer, Operation *, BoolAttr attr)
static std::optional< VectorShape > vectorShape(Type type)
static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound)
static Value min(ImplicitLocOpBuilder &builder, Value value, Value bound)
static void contract(RootOrderingGraph &graph, ArrayRef< Value > cycle, const DenseMap< Value, unsigned > &parentDepths, DenseMap< Value, Value > &actualSource, DenseMap< Value, Value > &actualTarget)
Contracts the specified cycle in the given graph in-place.
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
Definition SPIRVOps.cpp:230
static Value broadcast(Location loc, Value toBroadcast, unsigned numElements, const TypeConverter &typeConverter, ConversionPatternRewriter &rewriter)
Broadcasts the value to vector with numElements number of elements.
static VectorType getVectorType(Type scalarTy, const VectorizationStrategy *strategy)
Returns the vector type resulting from applying the provided vectorization strategy on the scalar typ...
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
Definition Traits.cpp:117
static SmallVector< Value > slice(OpBuilder &b, Location loc, Value value, VectorType nativeType)
static VectorType trimLeadingUnitDims(VectorType oldType, bool trimOnlyOneDim=false, bool allowRank0=false)
static MaskFormat getMaskFormat(Value mask)
Helper method to classify a mask value.
Definition VectorOps.cpp:86
static OpFoldResult foldShuffleIdentityMask(ShuffleOp op)
Fold shuffle V1, V2, [0, 1, 2, 3] : <4xi32>, <2xi32> -> V1.
static LogicalResult foldExtractOpFromExtractChain(ExtractOp extractOp)
Fold the result of chains of ExtractOp in place by simply concatenating the positions.
static OpFoldResult foldFromElementsToElements(FromElementsOp fromElementsOp)
Folds vector.from_elements(vector.to_elements(vector)) into vector.
static bool hasZeroDimVectors(Operation *op)
Returns true if the operation has a 0-D vector type operand or result.
static void printTransferAttrs(OpAsmPrinter &p, VectorTransferOpInterface op)
static Value foldScalarExtractFromFromElements(ExtractOp extractOp)
Try to fold the extraction of a scalar from a vector defined by vector.from_elements.
static Attribute convertNumericAttr(Attribute attr, Type expectedType)
Converts numeric attributes to the expected type.
static Value foldExtractFromExtractStrided(ExtractOp extractOp)
Fold an ExtractOp from ExtractStridedSliceOp.
static llvm::SetVector< int64_t > computeBroadcastedUnitDims(ArrayRef< int64_t > srcShape, ArrayRef< int64_t > dstShape)
Return the dimensions of the result vector that were formerly ones in the source tensor and thus corr...
static Value foldExtractFromBroadcast(ExtractOp extractOp)
Fold extract(broadcast(X)) to either extract(X) or just X.
static LogicalResult foldToElementsFromElements(ToElementsOp toElementsOp, SmallVectorImpl< OpFoldResult > &results)
Folds vector.to_elements(vector.from_elements(e0, e1, ...)) into (e0, e1, ...).
static Attribute foldPoisonSrcExtractOp(Attribute srcAttr)
Fold a vector extract from is a poison source.
static std::optional< int64_t > getOneSidedReductionDim(vector::ContractionOp *contract)
static LogicalResult foldBroadcastOfShapeCast(BroadcastOp broadcastOp)
static OpFoldResult foldShufflePoisonInputs(MLIRContext *context, Attribute v1Attr, Attribute v2Attr)
Fold shuffle poison, poison -> poison.
static bool isSupportedCombiningKind(CombiningKind combiningKind, Type elementType)
static Attribute foldPoisonIndexInsertExtractOp(MLIRContext *context, ArrayRef< int64_t > staticPos, int64_t poisonVal)
Fold an insert or extract operation into an poison value when a poison index is found at any dimensio...
MaskFormat
Helper enum to classify mask value.
Definition VectorOps.cpp:64
static ArrayAttr makeI64ArrayAttr(ArrayRef< int64_t > values, MLIRContext *context)
static unsigned getEffectiveVectorRankForXferOp(ShapedType shapedType, VectorType vectorType)
Returns the effective rank of the vector to read/write for Xfer Ops.
static OpFoldResult foldFromElementsToConstant(FromElementsOp fromElementsOp, ArrayRef< Attribute > elements)
Fold vector.from_elements to a constant when all operands are constants.
static LogicalResult incSlicePosition(MutableArrayRef< int64_t > position, ArrayRef< int64_t > shape, ArrayRef< int64_t > offsets)
static Value extractInsertFoldConstantOp(OpType op, AdaptorType adaptor, SmallVectorImpl< Value > &operands)
If the dynamic indices of extractOp or insertOp are in fact constants, then fold it.
static LogicalResult foldToElementsOfBroadcast(ToElementsOp toElementsOp, SmallVectorImpl< OpFoldResult > &results)
Folds vector.to_elements(vector.broadcast(x)) for the scalar case only.
static bool isStepIndexArray(ArrayRef< T > idxArr, uint64_t begin, size_t width)
static LogicalResult isIntegerArrayAttrConfinedToRange(OpType op, ArrayAttr arrayAttr, int64_t min, int64_t max, StringRef attrName, bool halfOpen=true)
static bool haveSameDefiningOp(OperandRange operands, Operation *defOp)
Returns true if all the operands are defined by defOp.
static int64_t getResultIndex(AffineMap map, AffineExpr targetExpr)
static LogicalResult isIntegerArrayAttrConfinedToShape(OpType op, ArrayAttr arrayAttr, ArrayRef< int64_t > shape, StringRef attrName, bool halfOpen=true, int64_t min=0)
static bool isSplatWriteConsistentWithMaskedRead(vector::TransferWriteOp write, vector::TransferReadOp read)
Check if write is of a constant splat and the masked read is padded with the same splat value – meani...
static LogicalResult isSumOfIntegerArrayAttrConfinedToShape(OpType op, ArrayAttr arrayAttr1, ArrayAttr arrayAttr2, ArrayRef< int64_t > shape, StringRef attrName1, StringRef attrName2, bool halfOpen=true, int64_t min=1)
static Attribute foldDenseElementsAttrDestInsertOp(InsertOp insertOp, Attribute srcAttr, Attribute dstAttr, int64_t maxVectorSizeFoldThreshold)
static LogicalResult foldTransferFullMask(TransferOp op)
static SmallVector< IntType > extractVector(ArrayAttr arrayAttr)
static bool isValidPositiveIndexOrPoison(int64_t index, int64_t poisonValue, int64_t maxIndex)
static OpFoldResult foldShuffleConstantInputs(ShuffleOp op, Attribute v1Attr, Attribute v2Attr)
Fold a shuffle of constant 1-D inputs by evaluating the mask.
static OpFoldResult foldExtractStridedSliceNonSplatConstant(ExtractStridedSliceOp op, Attribute foldInput)
static LogicalResult verifyPermutationMap(AffineMap permutationMap, EmitFun emitOpError)
static std::optional< SmallVector< int64_t > > getDefaultTargetMaskShapeForUnroll()
Definition VectorOps.cpp:72
static LogicalResult rewriteFromElementsAsBroadcast(FromElementsOp fromElementsOp, PatternRewriter &rewriter)
Rewrite vector.from_elements as vector.broadcast if the elements are the same.
static Value foldInsertUseChain(InsertOp insertOp)
Folder to replace the dest operand of the insert op with the root dest of the insert op use chain.
static bool isBroadcastLike(Operation *op)
All BroadcastOps, as well as ShapeCastOps that only prepend 1s, are considered to be 'broadcastlike'.
static LogicalResult isIntegerArrayAttrSmallerThanShape(OpType op, ArrayAttr arrayAttr, ArrayRef< int64_t > shape, StringRef attrName)
static Value foldExtractFromShapeCast(ExtractOp extractOp)
static LogicalResult verifyTransferOp(VectorTransferOpInterface op, ShapedType shapedType, VectorType vectorType, VectorType maskType, VectorType inferredMaskType, AffineMap permutationMap, ArrayAttr inBounds)
static bool isInBounds(TransferOp op, int64_t resultIdx, int64_t indicesIdx)
static LogicalResult verifyOutputShape(ContractionOp op, VectorType lhsType, VectorType rhsType, Type accType, Type resType, const std::vector< std::pair< int64_t, int64_t > > &contractingDimMap, const std::vector< std::pair< int64_t, int64_t > > &batchDimMap)
static bool verifyDimMap(VectorType lhsType, VectorType rhsType, const std::vector< std::pair< int64_t, int64_t > > &map)
static Type inferStridedSliceOpResultType(VectorType vectorType, ArrayAttr offsets, ArrayAttr sizes, ArrayAttr strides)
static OpFoldResult foldShufflePoisonOperandToMask(ShuffleOp op)
If a shuffle operand is poison, replace all mask indices that reference it with kPoisonIndex.
static LogicalResult foldSize1TransferPermutationMap(TransferOp op)
When the vector type is vector<1xT>, the permutation map is irrelevant: the single vector lane always...
static std::optional< SmallVector< int64_t > > getDefaultTargetInterleaveShapeForUnroll()
Definition VectorOps.cpp:78
static Value foldExtractFromShuffle(ExtractOp extractOp)
Fold extractOp coming from ShuffleOp.
static LogicalResult foldTransferInBoundsAttribute(TransferOp op)
static Value foldExtractStridedOpFromInsertChain(ExtractOp extractOp)
Fold extract_op fed from a chain of insertStridedSlice ops.
static int64_t calculateInsertPosition(VectorType destTy, ArrayRef< int64_t > positions)
static std::vector< std::pair< int64_t, int64_t > > getDimPairForIterTy(ContractionOp *contract, IteratorType targetIteratorType, bool oneSidedDim=false)
static Attribute foldDenseElementsAttrSrcExtractOp(ExtractOp extractOp, Attribute srcAttr)
Fold a vector extract extracting from a DenseElementsAttr.
static void populateFromInt64AttrArray(ArrayAttr arrayAttr, SmallVectorImpl< int64_t > &results)
#define mul(a, b)
Rewrite from_elements on multiple scalar extracts as a shape_cast on a single extract.
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 getMinorIdentityMap(unsigned dims, unsigned results, MLIRContext *context)
Returns an identity affine map (d0, ..., dn) -> (dp, ..., dn) on the most minor dimensions.
MLIRContext * getContext() const
bool isFunctionOfDim(unsigned position) const
Return true if any affine expression involves AffineDimExpr position.
Definition AffineMap.h:223
bool isMinorIdentity() const
Returns true if this affine map is a minor identity, i.e.
unsigned getDimPosition(unsigned idx) const
Extracts the position of the dimensional expression at the given result, when the caller knows it is ...
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 getNumSymbols() const
unsigned getNumDims() const
ArrayRef< AffineExpr > getResults() const
unsigned getNumResults() const
static SmallVector< AffineMap, 4 > inferFromExprList(ArrayRef< ArrayRef< AffineExpr > > exprsList, MLIRContext *context)
Returns a vector of AffineMaps; each with as many results as exprs.size(), as many dims as the larges...
unsigned getNumInputs() const
AffineExpr getResult(unsigned idx) const
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.
@ Square
Square brackets surrounding zero or more operands.
virtual ParseResult parseColonTypeList(SmallVectorImpl< Type > &result)=0
Parse a colon followed by a type list, which must have at least one type.
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
MLIRContext * getContext() const
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
ParseResult addTypeToList(Type type, SmallVectorImpl< Type > &result)
Add the specified type to the end of the specified type list and return success.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseOptionalComma()=0
Parse a , token if present.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseComma()=0
Parse a , token.
virtual ParseResult parseOptionalArrowTypeList(SmallVectorImpl< Type > &result)=0
Parse an optional arrow followed by a type list.
ParseResult parseKeywordType(const char *keyword, Type &result)
Parse a keyword followed by a type.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
virtual void printAttribute(Attribute attr)
Base storage class appearing in an attribute.
Attributes are known-constant values of operations.
Definition Attributes.h:25
Dialect & getDialect() const
Get the dialect this attribute is registered to.
Definition Attributes.h:58
bool empty()
Definition Block.h:173
OpListType & getOperations()
Definition Block.h:162
Operation & front()
Definition Block.h:178
Operation & back()
Definition Block.h:177
iterator begin()
Definition Block.h:168
static BoolAttr get(MLIRContext *context, bool value)
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
IntegerAttr getIndexAttr(int64_t value)
Definition Builders.cpp:116
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
Definition Builders.cpp:171
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition Builders.cpp:237
DenseI64ArrayAttr getDenseI64ArrayAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:175
IntegerAttr getI64IntegerAttr(int64_t value)
Definition Builders.cpp:120
IntegerType getIntegerType(unsigned width)
Definition Builders.cpp:75
TypedAttr getZeroAttr(Type type)
Definition Builders.cpp:333
IntegerType getI1Type()
Definition Builders.cpp:61
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
Definition Builders.cpp:275
MLIRContext * getContext() const
Definition Builders.h:56
ArrayAttr getI64ArrayAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:290
IndexType getIndexType()
Definition Builders.cpp:59
ArrayAttr getBoolArrayAttr(ArrayRef< bool > values)
Definition Builders.cpp:279
ArrayAttr getAffineMapArrayAttr(ArrayRef< AffineMap > values)
Definition Builders.cpp:327
static ConstantIntRanges fromUnsigned(const APInt &umin, const APInt &umax)
Create an ConstantIntRanges with the unsigned minimum and maximum equal to umin and umax and the sign...
static unsigned getStorageBitwidth(Type type)
Return the bitwidth that should be used for integer ranges describing type.
The main mechanism for performing data layout queries.
static DataLayout closest(Operation *op)
Returns the layout of the closest parent operation carrying layout info.
llvm::TypeSize getTypeSizeInBits(Type t) const
Returns the size in bits of the given type in the current scope.
An attribute that represents a reference to a dense vector or tensor object.
std::enable_if_t<!std::is_base_of< Attribute, T >::value||std::is_same< Attribute, T >::value, T > getSplatValue() const
Return the splat value for this attribute.
bool isSplat() const
Returns true if this attribute corresponds to a splat, i.e.
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
virtual Operation * materializeConstant(OpBuilder &builder, Attribute value, Type type, Location loc)
Registered hook to materialize a single constant operation from a given attribute value with the desi...
Definition Dialect.h:83
This is a utility class for mapping one set of IR entities to another.
Definition IRMapping.h:26
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
Definition IRMapping.h:30
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
NamedAttrList is array of NamedAttributes that tracks whether it is sorted and does some basic work t...
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual ParseResult parseRegion(Region &region, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region.
ParseResult parseTrailingOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None)
Parse zero or more trailing SSA comma-separated trailing operand references with a specified surround...
virtual ParseResult resolveOperand(const UnresolvedOperand &operand, Type type, SmallVectorImpl< Value > &result)=0
Resolve an operand to an SSA value, emitting an error on failure.
ParseResult resolveOperands(Operands &&operands, Type type, SmallVectorImpl< Value > &result)
Resolve a list of operands to SSA values, emitting an error on failure, or appending the results to t...
virtual ParseResult parseOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single SSA value operand name along with a result number if allowResultNumber is true.
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
virtual void printCustomOrGenericOp(Operation *op)=0
Prints the entire operation with the custom assembly form, if available, or the generic assembly form...
This class helps build Operations.
Definition Builders.h:210
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Definition Builders.cpp:439
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
Block * getInsertionBlock() const
Return the block the current insertion point belongs to.
Definition Builders.h:445
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
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition Builders.h:415
This class represents a single result from folding an operation.
This class implements the operand iterators for the Operation class.
Definition ValueRange.h:44
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Value getOperand(unsigned idx)
Definition Operation.h:377
void dropAllUses()
Drop all uses of results of this operation.
Definition Operation.h:888
void setOperand(unsigned idx, Value value)
Definition Operation.h:378
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
operand_type_range getOperandTypes()
Definition Operation.h:424
result_type_range getResultTypes()
Definition Operation.h:455
void moveBefore(Operation *existingOp)
Unlink this operation from its current block and insert it right before existingOp which may be in th...
result_range getResults()
Definition Operation.h:442
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
Block & front()
Definition Region.h:65
bool empty()
Definition Region.h:60
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.
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,...
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...
T * allocate()
Allocate an instance of the provided type.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isIntOrIndexOrFloat() const
Return true if this is an integer (of any signedness), index, or float type.
Definition Types.cpp:122
bool isF32() const
Definition Types.cpp:40
bool isIntOrIndex() const
Return true if this is an integer (of any signedness) or an index type.
Definition Types.cpp:114
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Definition Types.cpp:118
bool isF16() const
Definition Types.cpp:38
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition Types.cpp:124
static FailureOr< bool > areEqual(const Variable &var1, const Variable &var2)
Compute whether the given variables are equal.
static FailureOr< int64_t > computeConstantDelta(Value value1, Value value2, std::optional< int64_t > dim1=std::nullopt, std::optional< int64_t > dim2=std::nullopt)
Compute a constant delta between the given two values.
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
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
This is a builder type that keeps local references to arguments.
Builder & setElementType(Type newElementType)
Specialization of arith.constant op that returns an integer of index type.
Definition Arith.h:85
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:436
Speculatability
This enum is returned from the getSpeculatability method in the ConditionallySpeculatable op interfac...
constexpr auto Speculatable
constexpr auto NotSpeculatable
FailureOr< int64_t > fullyComposeAndComputeConstantDelta(Value value1, Value value2)
Compute a constant delta of the given two values.
AttrTypeReplacer.
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
Definition Matchers.h:344
FailureOr< std::optional< SmallVector< Value > > > bubbleDownInPlaceMemorySpaceCastImpl(OpOperand &operand, ValueRange results)
Tries to bubble-down inplace a MemorySpaceCastOpInterface operation referenced by operand.
bool hasNegativeStaticStride(MemRefType memRefTy)
Returns true if any stride of memRefTy is statically known to be negative.
LogicalResult foldMemRefCast(Operation *op, Value inner=nullptr)
This is a common utility used for patterns of the form "someop(memref.cast) -> someop".
Definition MemRefOps.cpp:48
Operation::operand_range getIndices(Operation *op)
Get the indices that the given load/store operation is operating on.
Definition Utils.cpp:18
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
MemRefType getMemRefType(T &&t)
Convenience method to abbreviate casting getType().
LogicalResult foldTensorCast(Operation *op)
Performs folding of any operand of op if it comes from a tensor::CastOp that can be folded.
detail::poison_attr_matcher m_Poison()
Matches a poison constant (any attribute implementing PoisonAttrInterface).
Definition UBMatchers.h:46
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.
ArrayAttr getVectorSubscriptAttr(Builder &b, ArrayRef< int64_t > values)
Returns an integer array attribute containing the given values using the integer type required for su...
Operation * maskOperation(OpBuilder &builder, Operation *maskableOp, Value mask, Value passthru=Value())
Creates a vector.mask operation around a maskable operation.
void buildTerminatedBody(OpBuilder &builder, Location loc)
Default callback to build a region with a 'vector.yield' terminator with no arguments.
std::optional< int64_t > getConstantVscaleMultiplier(Value value)
If value is a constant multiple of vector.vscale (e.g.
AffineMap getTransferMinorIdentityMap(ShapedType shapedType, VectorType vectorType)
Build the default minor identity map suitable for a vector transfer.
bool checkSameValueRAW(TransferWriteOp defWrite, TransferReadOp read)
Return true if the transfer_write fully writes the data accessed by the transfer_read.
ConstantMaskKind
Predefined constant_mask kinds.
Definition VectorOps.h:54
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....
VectorType inferTransferOpMaskType(VectorType vecType, AffineMap permMap)
Infers the mask type for a transfer op given its vector type and permutation map.
Value selectPassthru(OpBuilder &builder, Value mask, Value newValue, Value passthru)
Creates a vector select operation that picks values from newValue or passthru for each result vector ...
bool isDisjointTransferIndices(VectorTransferOpInterface transferA, VectorTransferOpInterface transferB, bool testDynamicValueUsingBounds=false)
Return true if we can prove that the transfer operations access disjoint memory, without requring the...
bool isDisjointTransferSet(VectorTransferOpInterface transferA, VectorTransferOpInterface transferB, bool testDynamicValueUsingBounds=false)
Return true if we can prove that the transfer operations access disjoint memory, requiring the operat...
bool checkSameValueWAW(TransferWriteOp write, TransferWriteOp priorWrite)
Return true if the write op fully over-write the priorWrite transfer_write op.
SmallVector< int64_t > getAsIntegers(ArrayRef< Value > values)
Returns the integer numbers in values.
void populateVectorToVectorCanonicalizationPatterns(RewritePatternSet &patterns, PatternBenefit benefit=1)
Collect a set of vector-to-vector canonicalization patterns.
bool isValidLoadStoreMemRefLayout(VectorType vecTy, MemRefType memRefTy)
Returns true if memRefTy has a valid layout for a vector.load/store of vecTy: the most minor memref d...
void createMaskOpRegion(OpBuilder &builder, Operation *maskableOp)
Create the vector.yield-ended region of a vector.mask op with maskableOp as masked operation.
SmallVector< Value > getAsValues(OpBuilder &builder, Location loc, ArrayRef< OpFoldResult > foldResults)
Convert foldResults into Values.
Value getVectorReductionOp(arith::AtomicRMWKind op, OpBuilder &builder, Location loc, Value vector)
Returns the value obtained by reducing the vector into a scalar using the operation kind associated w...
BroadcastableToResult
Models whether srcType can be broadcast to dstVectorType under the semantics of the vector....
Definition VectorOps.h:62
IntegerType getVectorSubscriptType(Builder &builder)
Returns the integer type required for subscripts in the vector dialect.
Include the generated interface declarations.
AffineMap simplifyAffineMap(AffineMap map)
Simplifies an affine map by simplifying its underlying AffineExpr results.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
llvm::function_ref< void(Value, const ConstantIntRanges &)> SetIntRangeFn
The type of the setResultRanges callback provided to ops implementing InferIntRangeInterface.
SmallVector< int64_t > computeStrides(ArrayRef< int64_t > sizes)
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
SmallVector< T > applyPermutation(ArrayRef< T > input, ArrayRef< int64_t > permutation)
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...
LogicalResult emitOptionalError(std::optional< Location > loc, Args &&...args)
Overloads of the above emission functions that take an optionally null location.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:125
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
AffineMap inversePermutation(AffineMap map)
Returns a map of codomain to domain dimensions such that the first codomain dimension for a particula...
StorageUniquer::StorageAllocator AttributeStorageAllocator
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
SmallVector< int64_t > getI64SubArray(ArrayAttr arrayAttr, unsigned dropFront=0, unsigned dropBack=0)
Helper to return a subset of arrayAttr as a vector of int64_t.
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 dispatchIndexOpFoldResults(ArrayRef< OpFoldResult > ofrs, SmallVectorImpl< Value > &dynamicVec, SmallVectorImpl< int64_t > &staticVec)
Helper function to dispatch multiple OpFoldResults according to the behavior of dispatchIndexOpFoldRe...
AffineMap compressUnusedDims(AffineMap map)
Drop the dims that are not used.
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)
LogicalResult verifyElementTypesMatch(Operation *op, ShapedType lhs, ShapedType rhs, StringRef lhsName, StringRef rhsName)
Verify that two shaped types have matching element types.
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)
int64_t linearize(ArrayRef< int64_t > offsets, ArrayRef< int64_t > basis)
Return the linearized index of 'offsets' w.r.t.
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.
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
std::pair< SmallVector< int64_t >, SmallVector< Value > > decomposeMixedValues(ArrayRef< OpFoldResult > mixedValues)
Decompose a vector of mixed static or dynamic values into the corresponding pair of arrays.
SmallVector< int64_t > invertPermutationVector(ArrayRef< int64_t > permutation)
Helper method to apply to inverse a permutation.
Return a fused vector::ContractionOp which represents a patterns such as:
LogicalResult matchAndRewrite(AddOpType addOp, PatternRewriter &rewriter) const override
Canonicalize vector.to_elements(vector.broadcast(v)) where v is a vector.
LogicalResult matchAndRewrite(ToElementsOp toElementsOp, PatternRewriter &rewriter) const override
This is the representation of an operand reference.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
OpRewritePattern Base
Type alias to allow derived classes to inherit constructors with using Base::Base;.
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
This represents an operation in an abstracted form, suitable for use with the builder APIs.
static BitmaskEnumStorage * construct(AttributeStorageAllocator &allocator, const KeyTy &key)
bool operator==(const KeyTy &key) const