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 
14 #include "mlir/Dialect/Vector/IR/VectorOps.h"
15 
16 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
17 #include "mlir/Dialect/Arithmetic/Utils/Utils.h"
18 #include "mlir/Dialect/MemRef/IR/MemRef.h"
19 #include "mlir/Dialect/Tensor/IR/Tensor.h"
20 #include "mlir/Dialect/Utils/IndexingUtils.h"
21 #include "mlir/Dialect/Utils/StructuredOpsUtils.h"
22 #include "mlir/IR/AffineExpr.h"
23 #include "mlir/IR/AffineMap.h"
24 #include "mlir/IR/BlockAndValueMapping.h"
25 #include "mlir/IR/Builders.h"
26 #include "mlir/IR/BuiltinOps.h"
27 #include "mlir/IR/BuiltinTypes.h"
28 #include "mlir/IR/DialectImplementation.h"
29 #include "mlir/IR/OpImplementation.h"
30 #include "mlir/IR/PatternMatch.h"
31 #include "mlir/IR/TypeUtilities.h"
32 #include "mlir/Support/LLVM.h"
33 #include "mlir/Support/MathExtras.h"
34 #include "llvm/ADT/StringSet.h"
35 #include "llvm/ADT/bit.h"
36 #include <numeric>
37 
38 #include "mlir/Dialect/Vector/IR/VectorOpsDialect.cpp.inc"
39 // Pull in all enum type and utility function definitions.
40 #include "mlir/Dialect/Vector/IR/VectorOpsEnums.cpp.inc"
41 
42 using namespace mlir;
43 using namespace mlir::vector;
44 
45 /// Helper enum to classify mask value.
46 enum class MaskFormat {
47   AllTrue = 0,
48   AllFalse = 1,
49   Unknown = 2,
50 };
51 
52 /// Helper method to classify a 1-D mask value. Currently, the method
53 /// looks "under the hood" of a constant value with dense attributes
54 /// and a constant mask operation (since the client may be called at
55 /// various stages during progressive lowering).
56 static MaskFormat get1DMaskFormat(Value mask) {
57   if (auto c = mask.getDefiningOp<arith::ConstantOp>()) {
58     // Inspect constant dense values. We count up for bits that
59     // are set, count down for bits that are cleared, and bail
60     // when a mix is detected.
61     if (auto denseElts = c.getValue().dyn_cast<DenseIntElementsAttr>()) {
62       int64_t val = 0;
63       for (bool b : denseElts.getValues<bool>())
64         if (b && val >= 0)
65           val++;
66         else if (!b && val <= 0)
67           val--;
68         else
69           return MaskFormat::Unknown;
70       if (val > 0)
71         return MaskFormat::AllTrue;
72       if (val < 0)
73         return MaskFormat::AllFalse;
74     }
75   } else if (auto m = mask.getDefiningOp<ConstantMaskOp>()) {
76     // Inspect constant mask index. If the index exceeds the
77     // dimension size, all bits are set. If the index is zero
78     // or less, no bits are set.
79     ArrayAttr masks = m.mask_dim_sizes();
80     assert(masks.size() == 1);
81     int64_t i = masks[0].cast<IntegerAttr>().getInt();
82     int64_t u = m.getType().getDimSize(0);
83     if (i >= u)
84       return MaskFormat::AllTrue;
85     if (i <= 0)
86       return MaskFormat::AllFalse;
87   }
88   return MaskFormat::Unknown;
89 }
90 
91 // Helper for verifying combining kinds in contractions and reductions.
92 static bool isSupportedCombiningKind(CombiningKind combiningKind,
93                                      Type elementType) {
94   switch (combiningKind) {
95   case CombiningKind::ADD:
96   case CombiningKind::MUL:
97     return elementType.isIntOrIndexOrFloat();
98   case CombiningKind::MINUI:
99   case CombiningKind::MINSI:
100   case CombiningKind::MAXUI:
101   case CombiningKind::MAXSI:
102   case CombiningKind::AND:
103   case CombiningKind::OR:
104   case CombiningKind::XOR:
105     return elementType.isIntOrIndex();
106   case CombiningKind::MINF:
107   case CombiningKind::MAXF:
108     return elementType.isa<FloatType>();
109   }
110   return false;
111 }
112 
113 /// Return true if the last dimension of the MemRefType has unit stride. Also
114 /// return true for memrefs with no strides.
115 bool mlir::vector::isLastMemrefDimUnitStride(MemRefType type) {
116   int64_t offset;
117   SmallVector<int64_t> strides;
118   auto successStrides = getStridesAndOffset(type, strides, offset);
119   return succeeded(successStrides) && (strides.empty() || strides.back() == 1);
120 }
121 
122 AffineMap mlir::vector::getTransferMinorIdentityMap(ShapedType shapedType,
123                                                     VectorType vectorType) {
124   int64_t elementVectorRank = 0;
125   VectorType elementVectorType =
126       shapedType.getElementType().dyn_cast<VectorType>();
127   if (elementVectorType)
128     elementVectorRank += elementVectorType.getRank();
129   // 0-d transfers are to/from tensor<t>/memref<t> and vector<1xt>.
130   // TODO: replace once we have 0-d vectors.
131   if (shapedType.getRank() == 0 &&
132       vectorType.getShape() == ArrayRef<int64_t>{1})
133     return AffineMap::get(
134         /*numDims=*/0, /*numSymbols=*/0,
135         getAffineConstantExpr(0, shapedType.getContext()));
136   return AffineMap::getMinorIdentityMap(
137       shapedType.getRank(), vectorType.getRank() - elementVectorRank,
138       shapedType.getContext());
139 }
140 
141 bool mlir::vector::checkSameValueRAW(vector::TransferWriteOp defWrite,
142                                      vector::TransferReadOp read) {
143   return !defWrite.hasOutOfBoundsDim() && !defWrite.mask() && !read.mask() &&
144          defWrite.indices() == read.indices() &&
145          defWrite.getVectorType() == read.getVectorType() &&
146          defWrite.permutation_map() == read.permutation_map();
147 }
148 
149 bool mlir::vector::checkSameValueWAW(vector::TransferWriteOp write,
150                                      vector::TransferWriteOp priorWrite) {
151   return priorWrite.indices() == write.indices() &&
152          priorWrite.mask() == write.mask() &&
153          priorWrite.getVectorType() == write.getVectorType() &&
154          priorWrite.permutation_map() == write.permutation_map();
155 }
156 
157 bool mlir::vector::isDisjointTransferIndices(
158     VectorTransferOpInterface transferA, VectorTransferOpInterface transferB) {
159   // For simplicity only look at transfer of same type.
160   if (transferA.getVectorType() != transferB.getVectorType())
161     return false;
162   unsigned rankOffset = transferA.getLeadingShapedRank();
163   for (unsigned i = 0, e = transferA.indices().size(); i < e; i++) {
164     auto indexA = transferA.indices()[i].getDefiningOp<arith::ConstantOp>();
165     auto indexB = transferB.indices()[i].getDefiningOp<arith::ConstantOp>();
166     // If any of the indices are dynamic we cannot prove anything.
167     if (!indexA || !indexB)
168       continue;
169 
170     if (i < rankOffset) {
171       // For leading dimensions, if we can prove that index are different we
172       // know we are accessing disjoint slices.
173       if (indexA.getValue().cast<IntegerAttr>().getInt() !=
174           indexB.getValue().cast<IntegerAttr>().getInt())
175         return true;
176     } else {
177       // For this dimension, we slice a part of the memref we need to make sure
178       // the intervals accessed don't overlap.
179       int64_t distance =
180           std::abs(indexA.getValue().cast<IntegerAttr>().getInt() -
181                    indexB.getValue().cast<IntegerAttr>().getInt());
182       if (distance >= transferA.getVectorType().getDimSize(i - rankOffset))
183         return true;
184     }
185   }
186   return false;
187 }
188 
189 bool mlir::vector::isDisjointTransferSet(VectorTransferOpInterface transferA,
190                                          VectorTransferOpInterface transferB) {
191   if (transferA.source() != transferB.source())
192     return false;
193   return isDisjointTransferIndices(transferA, transferB);
194 }
195 
196 //===----------------------------------------------------------------------===//
197 // CombiningKindAttr
198 //===----------------------------------------------------------------------===//
199 
200 namespace mlir {
201 namespace vector {
202 namespace detail {
203 struct BitmaskEnumStorage : public AttributeStorage {
204   using KeyTy = uint64_t;
205 
206   BitmaskEnumStorage(KeyTy val) : value(val) {}
207 
208   bool operator==(const KeyTy &key) const { return value == key; }
209 
210   static BitmaskEnumStorage *construct(AttributeStorageAllocator &allocator,
211                                        const KeyTy &key) {
212     return new (allocator.allocate<BitmaskEnumStorage>())
213         BitmaskEnumStorage(key);
214   }
215 
216   KeyTy value = 0;
217 };
218 } // namespace detail
219 } // namespace vector
220 } // namespace mlir
221 
222 CombiningKindAttr CombiningKindAttr::get(CombiningKind kind,
223                                          MLIRContext *context) {
224   return Base::get(context, static_cast<uint64_t>(kind));
225 }
226 
227 CombiningKind CombiningKindAttr::getKind() const {
228   return static_cast<CombiningKind>(getImpl()->value);
229 }
230 
231 static constexpr const CombiningKind combiningKindsList[] = {
232     // clang-format off
233     CombiningKind::ADD,
234     CombiningKind::MUL,
235     CombiningKind::MINUI,
236     CombiningKind::MINSI,
237     CombiningKind::MINF,
238     CombiningKind::MAXUI,
239     CombiningKind::MAXSI,
240     CombiningKind::MAXF,
241     CombiningKind::AND,
242     CombiningKind::OR,
243     CombiningKind::XOR,
244     // clang-format on
245 };
246 
247 void CombiningKindAttr::print(AsmPrinter &printer) const {
248   printer << "<";
249   auto kinds = llvm::make_filter_range(combiningKindsList, [&](auto kind) {
250     return bitEnumContains(this->getKind(), kind);
251   });
252   llvm::interleaveComma(kinds, printer,
253                         [&](auto kind) { printer << stringifyEnum(kind); });
254   printer << ">";
255 }
256 
257 Attribute CombiningKindAttr::parse(AsmParser &parser, Type type) {
258   if (failed(parser.parseLess()))
259     return {};
260 
261   StringRef elemName;
262   if (failed(parser.parseKeyword(&elemName)))
263     return {};
264 
265   auto kind = symbolizeCombiningKind(elemName);
266   if (!kind) {
267     parser.emitError(parser.getNameLoc(), "Unknown combining kind: ")
268         << elemName;
269     return {};
270   }
271 
272   if (failed(parser.parseGreater()))
273     return {};
274 
275   return CombiningKindAttr::get(kind.getValue(), parser.getContext());
276 }
277 
278 Attribute VectorDialect::parseAttribute(DialectAsmParser &parser,
279                                         Type type) const {
280   StringRef attrKind;
281   if (parser.parseKeyword(&attrKind))
282     return {};
283 
284   if (attrKind == "kind")
285     return CombiningKindAttr::parse(parser, {});
286 
287   parser.emitError(parser.getNameLoc(), "Unknown attribute type: ") << attrKind;
288   return {};
289 }
290 
291 void VectorDialect::printAttribute(Attribute attr,
292                                    DialectAsmPrinter &os) const {
293   if (auto ck = attr.dyn_cast<CombiningKindAttr>()) {
294     os << "kind";
295     ck.print(os);
296     return;
297   }
298   llvm_unreachable("Unknown attribute type");
299 }
300 
301 //===----------------------------------------------------------------------===//
302 // VectorDialect
303 //===----------------------------------------------------------------------===//
304 
305 void VectorDialect::initialize() {
306   addAttributes<CombiningKindAttr>();
307 
308   addOperations<
309 #define GET_OP_LIST
310 #include "mlir/Dialect/Vector/IR/VectorOps.cpp.inc"
311       >();
312 }
313 
314 /// Materialize a single constant operation from a given attribute value with
315 /// the desired resultant type.
316 Operation *VectorDialect::materializeConstant(OpBuilder &builder,
317                                               Attribute value, Type type,
318                                               Location loc) {
319   return builder.create<arith::ConstantOp>(loc, type, value);
320 }
321 
322 IntegerType vector::getVectorSubscriptType(Builder &builder) {
323   return builder.getIntegerType(64);
324 }
325 
326 ArrayAttr vector::getVectorSubscriptAttr(Builder &builder,
327                                          ArrayRef<int64_t> values) {
328   return builder.getI64ArrayAttr(values);
329 }
330 
331 //===----------------------------------------------------------------------===//
332 // MultiDimReductionOp
333 //===----------------------------------------------------------------------===//
334 
335 void vector::MultiDimReductionOp::build(OpBuilder &builder,
336                                         OperationState &result, Value source,
337                                         ArrayRef<bool> reductionMask,
338                                         CombiningKind kind) {
339   result.addOperands(source);
340   auto sourceVectorType = source.getType().cast<VectorType>();
341   auto targetType = MultiDimReductionOp::inferDestType(
342       sourceVectorType.getShape(), reductionMask,
343       sourceVectorType.getElementType());
344   result.addTypes(targetType);
345 
346   SmallVector<int64_t> reductionDims;
347   for (const auto &en : llvm::enumerate(reductionMask))
348     if (en.value())
349       reductionDims.push_back(en.index());
350   result.addAttribute(getReductionDimsAttrStrName(),
351                       builder.getI64ArrayAttr(reductionDims));
352   result.addAttribute(getKindAttrStrName(),
353                       CombiningKindAttr::get(kind, builder.getContext()));
354 }
355 
356 LogicalResult MultiDimReductionOp::verify() {
357   auto reductionMask = getReductionMask();
358   auto targetType = MultiDimReductionOp::inferDestType(
359       getSourceVectorType().getShape(), reductionMask,
360       getSourceVectorType().getElementType());
361   // TODO: update to support 0-d vectors when available.
362   if (targetType != getDestType())
363     return emitError("invalid output vector type: ")
364            << getDestType() << " (expected: " << targetType << ")";
365   return success();
366 }
367 
368 OpFoldResult MultiDimReductionOp::fold(ArrayRef<Attribute> operands) {
369   // Single parallel dim, this is a noop.
370   if (getSourceVectorType().getRank() == 1 && !isReducedDim(0))
371     return source();
372   return {};
373 }
374 
375 //===----------------------------------------------------------------------===//
376 // ReductionOp
377 //===----------------------------------------------------------------------===//
378 
379 void vector::ReductionOp::build(OpBuilder &builder, OperationState &result,
380                                 CombiningKind kind, Value vector) {
381   build(builder, result, kind, vector, /*acc=*/Value());
382 }
383 
384 void vector::ReductionOp::build(OpBuilder &builder, OperationState &result,
385                                 CombiningKind kind, Value vector, Value acc) {
386   build(builder, result, vector.getType().cast<VectorType>().getElementType(),
387         kind, vector, acc);
388 }
389 
390 LogicalResult ReductionOp::verify() {
391   // Verify for 1-D vector.
392   int64_t rank = getVectorType().getRank();
393   if (rank != 1)
394     return emitOpError("unsupported reduction rank: ") << rank;
395 
396   // Verify supported reduction kind.
397   Type eltType = dest().getType();
398   if (!isSupportedCombiningKind(kind(), eltType))
399     return emitOpError("unsupported reduction type '")
400            << eltType << "' for kind '" << stringifyCombiningKind(kind())
401            << "'";
402 
403   // Verify optional accumulator.
404   if (acc()) {
405     if (kind() != CombiningKind::ADD && kind() != CombiningKind::MUL)
406       return emitOpError("no accumulator for reduction kind: ")
407              << stringifyCombiningKind(kind());
408     if (!eltType.isa<FloatType>())
409       return emitOpError("no accumulator for type: ") << eltType;
410   }
411 
412   return success();
413 }
414 
415 ParseResult ReductionOp::parse(OpAsmParser &parser, OperationState &result) {
416   SmallVector<OpAsmParser::OperandType, 2> operandsInfo;
417   Type redType;
418   Type resType;
419   CombiningKindAttr kindAttr;
420   if (parser.parseCustomAttributeWithFallback(kindAttr, Type{}, "kind",
421                                               result.attributes) ||
422       parser.parseComma() || parser.parseOperandList(operandsInfo) ||
423       parser.parseColonType(redType) ||
424       parser.parseKeywordType("into", resType) ||
425       (!operandsInfo.empty() &&
426        parser.resolveOperand(operandsInfo[0], redType, result.operands)) ||
427       (operandsInfo.size() > 1 &&
428        parser.resolveOperand(operandsInfo[1], resType, result.operands)) ||
429       parser.addTypeToList(resType, result.types))
430     return failure();
431   if (operandsInfo.empty() || operandsInfo.size() > 2)
432     return parser.emitError(parser.getNameLoc(),
433                             "unsupported number of operands");
434   return success();
435 }
436 
437 void ReductionOp::print(OpAsmPrinter &p) {
438   p << " ";
439   kindAttr().print(p);
440   p << ", " << vector();
441   if (acc())
442     p << ", " << acc();
443   p << " : " << vector().getType() << " into " << dest().getType();
444 }
445 
446 Value mlir::vector::getVectorReductionOp(arith::AtomicRMWKind op,
447                                          OpBuilder &builder, Location loc,
448                                          Value vector) {
449   switch (op) {
450   case arith::AtomicRMWKind::addf:
451   case arith::AtomicRMWKind::addi:
452     return builder.create<vector::ReductionOp>(vector.getLoc(),
453                                                CombiningKind::ADD, vector);
454   case arith::AtomicRMWKind::mulf:
455   case arith::AtomicRMWKind::muli:
456     return builder.create<vector::ReductionOp>(vector.getLoc(),
457                                                CombiningKind::MUL, vector);
458   case arith::AtomicRMWKind::minf:
459     return builder.create<vector::ReductionOp>(vector.getLoc(),
460                                                CombiningKind::MINF, vector);
461   case arith::AtomicRMWKind::mins:
462     return builder.create<vector::ReductionOp>(vector.getLoc(),
463                                                CombiningKind::MINSI, vector);
464   case arith::AtomicRMWKind::minu:
465     return builder.create<vector::ReductionOp>(vector.getLoc(),
466                                                CombiningKind::MINUI, vector);
467   case arith::AtomicRMWKind::maxf:
468     return builder.create<vector::ReductionOp>(vector.getLoc(),
469                                                CombiningKind::MAXF, vector);
470   case arith::AtomicRMWKind::maxs:
471     return builder.create<vector::ReductionOp>(vector.getLoc(),
472                                                CombiningKind::MAXSI, vector);
473   case arith::AtomicRMWKind::maxu:
474     return builder.create<vector::ReductionOp>(vector.getLoc(),
475                                                CombiningKind::MAXUI, vector);
476   // TODO: Add remaining reduction operations.
477   default:
478     (void)emitOptionalError(loc, "Reduction operation type not supported");
479     break;
480   }
481   return nullptr;
482 }
483 
484 //===----------------------------------------------------------------------===//
485 // ContractionOp
486 //===----------------------------------------------------------------------===//
487 
488 void vector::ContractionOp::build(OpBuilder &builder, OperationState &result,
489                                   Value lhs, Value rhs, Value acc,
490                                   ArrayRef<ArrayRef<AffineExpr>> indexingExprs,
491                                   ArrayRef<StringRef> iteratorTypes) {
492   result.addOperands({lhs, rhs, acc});
493   result.addTypes(acc.getType());
494   result.addAttribute(::mlir::getIndexingMapsAttrName(),
495                       builder.getAffineMapArrayAttr(
496                           AffineMap::inferFromExprList(indexingExprs)));
497   result.addAttribute(::mlir::getIteratorTypesAttrName(),
498                       builder.getStrArrayAttr(iteratorTypes));
499 }
500 
501 void vector::ContractionOp::build(OpBuilder &builder, OperationState &result,
502                                   Value lhs, Value rhs, Value acc,
503                                   ArrayAttr indexingMaps,
504                                   ArrayAttr iteratorTypes) {
505   build(builder, result, lhs, rhs, acc, indexingMaps, iteratorTypes,
506         ContractionOp::getDefaultKind());
507 }
508 
509 void vector::ContractionOp::build(OpBuilder &builder, OperationState &result,
510                                   Value lhs, Value rhs, Value acc,
511                                   ArrayAttr indexingMaps,
512                                   ArrayAttr iteratorTypes, CombiningKind kind) {
513   result.addOperands({lhs, rhs, acc});
514   result.addTypes(acc.getType());
515   result.addAttribute(::mlir::getIndexingMapsAttrName(), indexingMaps);
516   result.addAttribute(::mlir::getIteratorTypesAttrName(), iteratorTypes);
517   result.addAttribute(ContractionOp::getKindAttrStrName(),
518                       CombiningKindAttr::get(kind, builder.getContext()));
519 }
520 
521 ParseResult ContractionOp::parse(OpAsmParser &parser, OperationState &result) {
522   OpAsmParser::OperandType lhsInfo;
523   OpAsmParser::OperandType rhsInfo;
524   OpAsmParser::OperandType accInfo;
525   SmallVector<OpAsmParser::OperandType, 2> masksInfo;
526   SmallVector<Type, 2> types;
527   Type resultType;
528   auto loc = parser.getCurrentLocation();
529   DictionaryAttr dictAttr;
530   // TODO: Unify linalg op attribute parsing.
531   if (parser.parseAttribute(dictAttr, "_", result.attributes) ||
532       parser.parseOperand(lhsInfo) || parser.parseComma() ||
533       parser.parseOperand(rhsInfo) || parser.parseComma() ||
534       parser.parseOperand(accInfo) ||
535       parser.parseTrailingOperandList(masksInfo) ||
536       parser.parseOptionalAttrDict(result.attributes) ||
537       parser.parseColonTypeList(types) ||
538       parser.parseKeywordType("into", resultType) ||
539       parser.resolveOperand(lhsInfo, types[0], result.operands) ||
540       parser.resolveOperand(rhsInfo, types[1], result.operands) ||
541       parser.resolveOperand(accInfo, resultType, result.operands) ||
542       parser.addTypeToList(resultType, result.types))
543     return failure();
544   result.attributes.assign(dictAttr.getValue().begin(),
545                            dictAttr.getValue().end());
546   if (!result.attributes.get(ContractionOp::getKindAttrStrName())) {
547     result.addAttribute(ContractionOp::getKindAttrStrName(),
548                         CombiningKindAttr::get(ContractionOp::getDefaultKind(),
549                                                result.getContext()));
550   }
551   if (masksInfo.empty())
552     return success();
553   if (masksInfo.size() != 2)
554     return parser.emitError(parser.getNameLoc(),
555                             "expected zero or exactly 2 vector mask operands");
556   auto lhsType = types[0].cast<VectorType>();
557   auto rhsType = types[1].cast<VectorType>();
558   auto maskElementType = parser.getBuilder().getI1Type();
559   std::array<Type, 2> maskTypes = {
560       VectorType::Builder(lhsType).setElementType(maskElementType),
561       VectorType::Builder(rhsType).setElementType(maskElementType)};
562   if (parser.resolveOperands(masksInfo, maskTypes, loc, result.operands))
563     return failure();
564   return success();
565 }
566 
567 void ContractionOp::print(OpAsmPrinter &p) {
568   // TODO: Unify printing code with linalg ops.
569   auto attrNames = getTraitAttrNames();
570   llvm::StringSet<> traitAttrsSet;
571   traitAttrsSet.insert(attrNames.begin(), attrNames.end());
572   SmallVector<NamedAttribute, 8> attrs;
573   for (auto attr : (*this)->getAttrs())
574     if (traitAttrsSet.count(attr.getName().strref()) > 0)
575       attrs.push_back(attr);
576 
577   auto dictAttr = DictionaryAttr::get(getContext(), attrs);
578   p << " " << dictAttr << " " << lhs() << ", ";
579   p << rhs() << ", " << acc();
580   if (masks().size() == 2)
581     p << ", " << masks();
582 
583   p.printOptionalAttrDict((*this)->getAttrs(), attrNames);
584   p << " : " << lhs().getType() << ", " << rhs().getType() << " into "
585     << getResultType();
586 }
587 
588 static bool verifyDimMap(VectorType lhsType, VectorType rhsType,
589                          const std::vector<std::pair<int64_t, int64_t>> &map) {
590   for (auto &dimPair : map) {
591     if (dimPair.first < 0 || dimPair.first >= lhsType.getRank() ||
592         dimPair.second < 0 || dimPair.second >= rhsType.getRank() ||
593         lhsType.getDimSize(dimPair.first) != rhsType.getDimSize(dimPair.second))
594       return false;
595   }
596   return true;
597 }
598 
599 static LogicalResult verifyOutputShape(
600     ContractionOp op, VectorType lhsType, VectorType rhsType, Type accType,
601     Type resType,
602     const std::vector<std::pair<int64_t, int64_t>> &contractingDimMap,
603     const std::vector<std::pair<int64_t, int64_t>> &batchDimMap) {
604   DenseSet<int64_t> lhsContractingDimSet;
605   DenseSet<int64_t> rhsContractingDimSet;
606   for (auto &dimPair : contractingDimMap) {
607     lhsContractingDimSet.insert(dimPair.first);
608     rhsContractingDimSet.insert(dimPair.second);
609   }
610   DenseSet<int64_t> rhsBatchDimSet;
611   for (auto &dimPair : batchDimMap)
612     rhsBatchDimSet.insert(dimPair.second);
613 
614   // Add free and batch dimensions from 'lhsType' to 'expectedResultDims'.
615   SmallVector<int64_t, 4> expectedResultDims;
616   for (int64_t i = 0, e = lhsType.getRank(); i < e; ++i) {
617     if (lhsContractingDimSet.count(i) > 0)
618       continue;
619     expectedResultDims.push_back(lhsType.getDimSize(i));
620   }
621 
622   // Add free dimensions from 'rhsType' to 'expectedResultDims'.
623   for (int64_t i = 0, e = rhsType.getRank(); i < e; ++i) {
624     if (rhsContractingDimSet.count(i) > 0 || rhsBatchDimSet.count(i) > 0)
625       continue;
626     expectedResultDims.push_back(rhsType.getDimSize(i));
627   }
628 
629   // Verify 'expectedResultDims'.
630   if (expectedResultDims.empty()) {
631     // No batch or free dimension implies a scalar result.
632     if (resType.isa<VectorType>() || accType.isa<VectorType>())
633       return op.emitOpError("invalid accumulator/result vector shape");
634   } else {
635     // At least one batch or free dimension implies a vector result.
636     auto resVectorType = resType.dyn_cast<VectorType>();
637     auto accVectorType = accType.dyn_cast<VectorType>();
638     if (!resVectorType || !accVectorType)
639       return op.emitOpError("invalid accumulator/result vector shape");
640 
641     // Infer expected result vector type. Lhs + rhs map and lhs + rhs vector
642     // types fully define the result vector type. This assumes the affine maps
643     // are well-formed, which must have been verified already.
644     MLIRContext *ctx = op.getContext();
645     AffineMap lhsMap = op.getIndexingMaps()[0];
646     AffineMap rhsMap = op.getIndexingMaps()[1];
647     SmallVector<AffineExpr, 4> extents(lhsMap.getNumInputs());
648     for (auto pair :
649          {std::make_pair(lhsType, lhsMap), std::make_pair(rhsType, rhsMap)}) {
650       VectorType v = pair.first;
651       auto map = pair.second;
652       for (unsigned idx = 0, e = v.getRank(); idx < e; ++idx) {
653         unsigned pos = map.getDimPosition(idx);
654         if (!extents[pos])
655           extents[pos] = getAffineConstantExpr(v.getShape()[idx], ctx);
656       }
657     }
658     assert(llvm::all_of(extents, [](AffineExpr e) { return e; }) &&
659            "expected extent along all dimensions.");
660 
661     AffineMap resMap = op.getIndexingMaps()[2];
662     auto extentsMap = AffineMap::get(/*dimCount=*/extents.size(),
663                                      /*symCount=*/0, extents, ctx);
664     // Compose the resMap with the extentsMap, which is a constant map.
665     AffineMap expectedMap = simplifyAffineMap(resMap.compose(extentsMap));
666     assert(llvm::all_of(
667                expectedMap.getResults(),
668                [](AffineExpr e) { return e.isa<AffineConstantExpr>(); }) &&
669            "expected constant extent along all dimensions.");
670     // Extract the expected shape and build the type.
671     auto expectedShape = llvm::to_vector<4>(
672         llvm::map_range(expectedMap.getResults(), [](AffineExpr e) {
673           return e.cast<AffineConstantExpr>().getValue();
674         }));
675     auto expected =
676         VectorType::get(expectedShape, resVectorType.getElementType());
677     if (resVectorType != expected || accVectorType != expected)
678       return op.emitOpError(
679                  "invalid accumulator/result vector shape, expected: ")
680              << expected;
681   }
682   return success();
683 }
684 
685 LogicalResult ContractionOp::verify() {
686   auto lhsType = getLhsType();
687   auto rhsType = getRhsType();
688   auto accType = getAccType();
689   auto resType = getResultType();
690 
691   // Verify that an indexing map was specified for each vector operand.
692   if (indexing_maps().size() != 3)
693     return emitOpError("expected an indexing map for each vector operand");
694 
695   // Verify that each index map has 'numIterators' inputs, no symbols, and
696   // that the number of map outputs equals the rank of its associated
697   // vector operand.
698   unsigned numIterators = iterator_types().getValue().size();
699   for (const auto &it : llvm::enumerate(indexing_maps())) {
700     auto index = it.index();
701     auto map = it.value();
702     if (map.getNumSymbols() != 0)
703       return emitOpError("expected indexing map ")
704              << index << " to have no symbols";
705     auto vectorType = getOperand(index).getType().dyn_cast<VectorType>();
706     unsigned rank = vectorType ? vectorType.getShape().size() : 0;
707     // Verify that the map has the right number of inputs, outputs, and indices.
708     // This also correctly accounts for (..) -> () for rank-0 results.
709     if (map.getNumDims() != numIterators)
710       return emitOpError("expected indexing map ")
711              << index << " to have " << numIterators << " number of inputs";
712     if (map.getNumResults() != rank)
713       return emitOpError("expected indexing map ")
714              << index << " to have " << rank << " number of outputs";
715     if (!map.isProjectedPermutation())
716       return emitOpError("expected indexing map ")
717              << index << " to be a projected permutation of its inputs";
718   }
719 
720   auto contractingDimMap = getContractingDimMap();
721   auto batchDimMap = getBatchDimMap();
722 
723   // Verify at least one contracting dimension pair was specified.
724   if (contractingDimMap.empty())
725     return emitOpError("expected at least one contracting dimension pair");
726 
727   // Verify contracting dimension map was properly constructed.
728   if (!verifyDimMap(lhsType, rhsType, contractingDimMap))
729     return emitOpError("invalid contracting dimension map");
730 
731   // Verify batch dimension map was properly constructed.
732   if (!verifyDimMap(lhsType, rhsType, batchDimMap))
733     return emitOpError("invalid batch dimension map");
734 
735   // Verify 'accType' and 'resType' shape.
736   if (failed(verifyOutputShape(*this, lhsType, rhsType, accType, resType,
737                                contractingDimMap, batchDimMap)))
738     return failure();
739 
740   // Verify that either two vector masks are set or none are set.
741   auto lhsMaskType = getLHSVectorMaskType();
742   auto rhsMaskType = getRHSVectorMaskType();
743   if ((lhsMaskType && !rhsMaskType) || (!lhsMaskType && rhsMaskType))
744     return emitOpError("invalid number of vector masks specified");
745   if (lhsMaskType && rhsMaskType) {
746     // Verify mask rank == argument rank.
747     if (lhsMaskType.getShape().size() != lhsType.getShape().size() ||
748         rhsMaskType.getShape().size() != rhsType.getShape().size())
749       return emitOpError("invalid vector mask rank");
750   }
751 
752   // Verify supported combining kind.
753   auto vectorType = resType.dyn_cast<VectorType>();
754   auto elementType = vectorType ? vectorType.getElementType() : resType;
755   if (!isSupportedCombiningKind(kind(), elementType))
756     return emitOpError("unsupported contraction type");
757 
758   return success();
759 }
760 
761 ArrayRef<StringRef> ContractionOp::getTraitAttrNames() {
762   static constexpr StringRef names[3] = {::mlir::getIndexingMapsAttrName(),
763                                          ::mlir::getIteratorTypesAttrName(),
764                                          ContractionOp::getKindAttrStrName()};
765   return llvm::makeArrayRef(names);
766 }
767 
768 static int64_t getResultIndex(AffineMap map, AffineExpr targetExpr) {
769   for (int64_t i = 0, e = map.getNumResults(); i < e; ++i)
770     if (targetExpr == map.getResult(i))
771       return i;
772   return -1;
773 }
774 
775 static std::vector<std::pair<int64_t, int64_t>>
776 getDimMap(ArrayRef<AffineMap> indexingMaps, ArrayAttr iteratorTypes,
777           StringRef targetIteratorTypeName, MLIRContext *context) {
778   std::vector<std::pair<int64_t, int64_t>> dimMap;
779   for (const auto &it : llvm::enumerate(iteratorTypes)) {
780     auto iteratorTypeName = it.value().cast<StringAttr>().getValue();
781     if (iteratorTypeName != targetIteratorTypeName)
782       continue;
783     // Search lhs/rhs map results for 'targetExpr'.
784     auto targetExpr = getAffineDimExpr(it.index(), context);
785     int64_t lhsDim = getResultIndex(indexingMaps[0], targetExpr);
786     int64_t rhsDim = getResultIndex(indexingMaps[1], targetExpr);
787     if (lhsDim >= 0 && rhsDim >= 0)
788       dimMap.emplace_back(lhsDim, rhsDim);
789   }
790   return dimMap;
791 }
792 
793 void ContractionOp::getIterationBounds(
794     SmallVectorImpl<int64_t> &iterationBounds) {
795   auto lhsShape = getLhsType().getShape();
796   auto resVectorType = getResultType().dyn_cast<VectorType>();
797   SmallVector<AffineMap, 4> indexingMaps(getIndexingMaps());
798   SmallVector<int64_t, 2> iterationShape;
799   for (const auto &it : llvm::enumerate(iterator_types())) {
800     // Search lhs/rhs map results for 'targetExpr'.
801     auto targetExpr = getAffineDimExpr(it.index(), getContext());
802     auto iteratorTypeName = it.value().cast<StringAttr>().getValue();
803     if (iteratorTypeName == getReductionIteratorTypeName()) {
804       // Get reduction dim size from lhs shape (same size in rhsShape).
805       int64_t lhsDimIndex = getResultIndex(indexingMaps[0], targetExpr);
806       assert(lhsDimIndex >= 0);
807       iterationBounds.push_back(lhsShape[lhsDimIndex]);
808       continue;
809     }
810     // Get parallel dimension size from result shape.
811     int64_t resDimIndex = getResultIndex(indexingMaps[2], targetExpr);
812     assert(resDimIndex >= 0);
813     assert(resVectorType != nullptr);
814     iterationBounds.push_back(resVectorType.getShape()[resDimIndex]);
815   }
816 }
817 
818 void ContractionOp::getIterationIndexMap(
819     std::vector<DenseMap<int64_t, int64_t>> &iterationIndexMap) {
820   unsigned numMaps = indexing_maps().size();
821   iterationIndexMap.resize(numMaps);
822   for (const auto &it : llvm::enumerate(indexing_maps())) {
823     auto index = it.index();
824     auto map = it.value();
825     for (unsigned i = 0, e = map.getNumResults(); i < e; ++i) {
826       auto dim = map.getResult(i).cast<AffineDimExpr>();
827       iterationIndexMap[index][dim.getPosition()] = i;
828     }
829   }
830 }
831 
832 std::vector<std::pair<int64_t, int64_t>> ContractionOp::getContractingDimMap() {
833   SmallVector<AffineMap, 4> indexingMaps(getIndexingMaps());
834   return getDimMap(indexingMaps, iterator_types(),
835                    getReductionIteratorTypeName(), getContext());
836 }
837 
838 std::vector<std::pair<int64_t, int64_t>> ContractionOp::getBatchDimMap() {
839   SmallVector<AffineMap, 4> indexingMaps(getIndexingMaps());
840   return getDimMap(indexingMaps, iterator_types(),
841                    getParallelIteratorTypeName(), getContext());
842 }
843 
844 Optional<SmallVector<int64_t, 4>> ContractionOp::getShapeForUnroll() {
845   SmallVector<int64_t, 4> shape;
846   getIterationBounds(shape);
847   return shape;
848 }
849 
850 /// Return a fused vector::ContractionOp which represents a patterns such as:
851 ///
852 /// ```mlir
853 ///    %c0 = vector.constant 0: ...
854 ///    %c = vector.contract %a, %b, %c0: ...
855 ///    %e = add %c, %d: ...
856 /// ```
857 ///
858 /// by:
859 ///
860 /// ```mlir
861 ///    %e = vector.contract %a, %b, %d: ...
862 /// ```
863 ///
864 /// Return null if the canonicalization does not apply.
865 // TODO: This should be a folding of Add into Contract in core but while they
866 // live in different dialects, it is not possible without unnatural
867 // dependencies.
868 template <typename AddOpType>
869 struct CanonicalizeContractAdd : public OpRewritePattern<AddOpType> {
870   using OpRewritePattern<AddOpType>::OpRewritePattern;
871 
872   LogicalResult matchAndRewrite(AddOpType addOp,
873                                 PatternRewriter &rewriter) const override {
874     auto canonicalize = [&](Value maybeContraction,
875                             Value otherOperand) -> vector::ContractionOp {
876       vector::ContractionOp contractionOp =
877           dyn_cast_or_null<vector::ContractionOp>(
878               maybeContraction.getDefiningOp());
879       if (!contractionOp)
880         return vector::ContractionOp();
881       if (auto maybeZero = dyn_cast_or_null<arith::ConstantOp>(
882               contractionOp.acc().getDefiningOp())) {
883         if (maybeZero.getValue() ==
884             rewriter.getZeroAttr(contractionOp.acc().getType())) {
885           BlockAndValueMapping bvm;
886           bvm.map(contractionOp.acc(), otherOperand);
887           auto newContraction =
888               cast<vector::ContractionOp>(rewriter.clone(*contractionOp, bvm));
889           rewriter.replaceOp(addOp, newContraction.getResult());
890           return newContraction;
891         }
892       }
893       return vector::ContractionOp();
894     };
895 
896     Value a = addOp->getOperand(0), b = addOp->getOperand(1);
897     vector::ContractionOp contract = canonicalize(a, b);
898     contract = contract ? contract : canonicalize(b, a);
899     return contract ? success() : failure();
900   }
901 };
902 
903 void ContractionOp::getCanonicalizationPatterns(RewritePatternSet &results,
904                                                 MLIRContext *context) {
905   results.add<CanonicalizeContractAdd<arith::AddIOp>,
906               CanonicalizeContractAdd<arith::AddFOp>>(context);
907 }
908 
909 //===----------------------------------------------------------------------===//
910 // ExtractElementOp
911 //===----------------------------------------------------------------------===//
912 
913 void vector::ExtractElementOp::build(OpBuilder &builder, OperationState &result,
914                                      Value source) {
915   result.addOperands({source});
916   result.addTypes(source.getType().cast<VectorType>().getElementType());
917 }
918 
919 void vector::ExtractElementOp::build(OpBuilder &builder, OperationState &result,
920                                      Value source, Value position) {
921   result.addOperands({source, position});
922   result.addTypes(source.getType().cast<VectorType>().getElementType());
923 }
924 
925 LogicalResult vector::ExtractElementOp::verify() {
926   VectorType vectorType = getVectorType();
927   if (vectorType.getRank() == 0) {
928     if (position())
929       return emitOpError("expected position to be empty with 0-D vector");
930     return success();
931   }
932   if (vectorType.getRank() != 1)
933     return emitOpError("unexpected >1 vector rank");
934   if (!position())
935     return emitOpError("expected position for 1-D vector");
936   return success();
937 }
938 
939 //===----------------------------------------------------------------------===//
940 // ExtractOp
941 //===----------------------------------------------------------------------===//
942 
943 static Type inferExtractOpResultType(VectorType vectorType,
944                                      ArrayAttr position) {
945   if (static_cast<int64_t>(position.size()) == vectorType.getRank())
946     return vectorType.getElementType();
947   return VectorType::get(vectorType.getShape().drop_front(position.size()),
948                          vectorType.getElementType());
949 }
950 
951 void vector::ExtractOp::build(OpBuilder &builder, OperationState &result,
952                               Value source, ArrayRef<int64_t> position) {
953   result.addOperands(source);
954   auto positionAttr = getVectorSubscriptAttr(builder, position);
955   result.addTypes(inferExtractOpResultType(source.getType().cast<VectorType>(),
956                                            positionAttr));
957   result.addAttribute(getPositionAttrStrName(), positionAttr);
958 }
959 
960 // Convenience builder which assumes the values are constant indices.
961 void vector::ExtractOp::build(OpBuilder &builder, OperationState &result,
962                               Value source, ValueRange position) {
963   SmallVector<int64_t, 4> positionConstants =
964       llvm::to_vector<4>(llvm::map_range(position, [](Value pos) {
965         return pos.getDefiningOp<arith::ConstantIndexOp>().value();
966       }));
967   build(builder, result, source, positionConstants);
968 }
969 
970 void vector::ExtractOp::print(OpAsmPrinter &p) {
971   p << " " << vector() << position();
972   p.printOptionalAttrDict((*this)->getAttrs(), {"position"});
973   p << " : " << vector().getType();
974 }
975 
976 ParseResult vector::ExtractOp::parse(OpAsmParser &parser,
977                                      OperationState &result) {
978   SMLoc attributeLoc, typeLoc;
979   NamedAttrList attrs;
980   OpAsmParser::OperandType vector;
981   Type type;
982   Attribute attr;
983   if (parser.parseOperand(vector) || parser.getCurrentLocation(&attributeLoc) ||
984       parser.parseAttribute(attr, "position", attrs) ||
985       parser.parseOptionalAttrDict(attrs) ||
986       parser.getCurrentLocation(&typeLoc) || parser.parseColonType(type))
987     return failure();
988 
989   auto vectorType = type.dyn_cast<VectorType>();
990   if (!vectorType)
991     return parser.emitError(typeLoc, "expected vector type");
992 
993   auto positionAttr = attr.dyn_cast<ArrayAttr>();
994   if (!positionAttr ||
995       static_cast<int64_t>(positionAttr.size()) > vectorType.getRank())
996     return parser.emitError(
997         attributeLoc,
998         "expected position attribute of rank smaller than vector rank");
999 
1000   Type resType = inferExtractOpResultType(vectorType, positionAttr);
1001   result.attributes = attrs;
1002   return failure(parser.resolveOperand(vector, type, result.operands) ||
1003                  parser.addTypeToList(resType, result.types));
1004 }
1005 
1006 LogicalResult vector::ExtractOp::verify() {
1007   auto positionAttr = position().getValue();
1008   if (positionAttr.size() > static_cast<unsigned>(getVectorType().getRank()))
1009     return emitOpError(
1010         "expected position attribute of rank smaller than vector rank");
1011   for (const auto &en : llvm::enumerate(positionAttr)) {
1012     auto attr = en.value().dyn_cast<IntegerAttr>();
1013     if (!attr || attr.getInt() < 0 ||
1014         attr.getInt() >= getVectorType().getDimSize(en.index()))
1015       return emitOpError("expected position attribute #")
1016              << (en.index() + 1)
1017              << " to be a non-negative integer smaller than the corresponding "
1018                 "vector dimension";
1019   }
1020   return success();
1021 }
1022 
1023 template <typename IntType>
1024 static SmallVector<IntType> extractVector(ArrayAttr arrayAttr) {
1025   return llvm::to_vector<4>(llvm::map_range(
1026       arrayAttr.getAsRange<IntegerAttr>(),
1027       [](IntegerAttr attr) { return static_cast<IntType>(attr.getInt()); }));
1028 }
1029 
1030 /// Fold the result of chains of ExtractOp in place by simply concatenating the
1031 /// positions.
1032 static LogicalResult foldExtractOpFromExtractChain(ExtractOp extractOp) {
1033   if (!extractOp.vector().getDefiningOp<ExtractOp>())
1034     return failure();
1035 
1036   SmallVector<int64_t, 4> globalPosition;
1037   ExtractOp currentOp = extractOp;
1038   auto extrPos = extractVector<int64_t>(currentOp.position());
1039   globalPosition.append(extrPos.rbegin(), extrPos.rend());
1040   while (ExtractOp nextOp = currentOp.vector().getDefiningOp<ExtractOp>()) {
1041     currentOp = nextOp;
1042     auto extrPos = extractVector<int64_t>(currentOp.position());
1043     globalPosition.append(extrPos.rbegin(), extrPos.rend());
1044   }
1045   extractOp.setOperand(currentOp.vector());
1046   // OpBuilder is only used as a helper to build an I64ArrayAttr.
1047   OpBuilder b(extractOp.getContext());
1048   std::reverse(globalPosition.begin(), globalPosition.end());
1049   extractOp->setAttr(ExtractOp::getPositionAttrStrName(),
1050                      b.getI64ArrayAttr(globalPosition));
1051   return success();
1052 }
1053 
1054 namespace {
1055 /// Fold an ExtractOp that is fed by a chain of InsertOps and TransposeOps.
1056 /// Walk back a chain of InsertOp/TransposeOp until we hit a match.
1057 /// Compose TransposeOp permutations as we walk back.
1058 /// This helper class keeps an updated extraction position `extractPosition`
1059 /// with extra trailing sentinels.
1060 /// The sentinels encode the internal transposition status of the result vector.
1061 /// As we iterate, extractPosition is permuted and updated.
1062 class ExtractFromInsertTransposeChainState {
1063 public:
1064   ExtractFromInsertTransposeChainState(ExtractOp e);
1065 
1066   /// Iterate over producing insert and transpose ops until we find a fold.
1067   Value fold();
1068 
1069 private:
1070   /// Return true if the vector at position `a` is contained within the vector
1071   /// at position `b`. Under insert/extract semantics, this is the same as `a`
1072   /// is a prefix of `b`.
1073   template <typename ContainerA, typename ContainerB>
1074   bool isContainedWithin(const ContainerA &a, const ContainerB &b) {
1075     return a.size() <= b.size() &&
1076            std::equal(a.begin(), a.begin() + a.size(), b.begin());
1077   }
1078 
1079   /// Return true if the vector at position `a` intersects the vector at
1080   /// position `b`. Under insert/extract semantics, this is the same as equality
1081   /// of all entries of `a` that are >=0 with the corresponding entries of b.
1082   /// Comparison is on the common prefix (i.e. zip).
1083   template <typename ContainerA, typename ContainerB>
1084   bool intersectsWhereNonNegative(const ContainerA &a, const ContainerB &b) {
1085     for (auto it : llvm::zip(a, b)) {
1086       if (std::get<0>(it) < 0 || std::get<0>(it) < 0)
1087         continue;
1088       if (std::get<0>(it) != std::get<1>(it))
1089         return false;
1090     }
1091     return true;
1092   }
1093 
1094   /// Folding is only possible in the absence of an internal permutation in the
1095   /// result vector.
1096   bool canFold() {
1097     return (sentinels ==
1098             makeArrayRef(extractPosition).drop_front(extractedRank));
1099   }
1100 
1101   // Helper to get the next defining op of interest.
1102   void updateStateForNextIteration(Value v) {
1103     nextInsertOp = v.getDefiningOp<vector::InsertOp>();
1104     nextTransposeOp = v.getDefiningOp<vector::TransposeOp>();
1105   };
1106 
1107   // Case 1. If we hit a transpose, just compose the map and iterate.
1108   // Invariant: insert + transpose do not change rank, we can always compose.
1109   LogicalResult handleTransposeOp();
1110 
1111   // Case 2: the insert position matches extractPosition exactly, early return.
1112   LogicalResult handleInsertOpWithMatchingPos(Value &res);
1113 
1114   /// Case 3: if the insert position is a prefix of extractPosition, extract a
1115   /// portion of the source of the insert.
1116   /// Example:
1117   /// ```
1118   /// %ins = vector.insert %source, %vest[1]: vector<3x4> into vector<2x3x4x5>
1119   /// // extractPosition == [1, 2, 3]
1120   /// %ext = vector.extract %ins[1, 0]: vector<3x4x5>
1121   /// // can fold to vector.extract %source[0, 3]
1122   /// %ext = vector.extract %source[3]: vector<5x6>
1123   /// ```
1124   /// To traverse through %source, we need to set the leading dims to 0 and
1125   /// drop the extra leading dims.
1126   /// This method updates the internal state.
1127   LogicalResult handleInsertOpWithPrefixPos(Value &res);
1128 
1129   /// Try to fold in place to extract(source, extractPosition) and return the
1130   /// folded result. Return null if folding is not possible (e.g. due to an
1131   /// internal tranposition in the result).
1132   Value tryToFoldExtractOpInPlace(Value source);
1133 
1134   ExtractOp extractOp;
1135   int64_t vectorRank;
1136   int64_t extractedRank;
1137 
1138   InsertOp nextInsertOp;
1139   TransposeOp nextTransposeOp;
1140 
1141   /// Sentinel values that encode the internal permutation status of the result.
1142   /// They are set to (-1, ... , -k) at the beginning and appended to
1143   /// `extractPosition`.
1144   /// In the end, the tail of `extractPosition` must be exactly `sentinels` to
1145   /// ensure that there is no internal transposition.
1146   /// Internal transposition cannot be accounted for with a folding pattern.
1147   // TODO: We could relax the internal transposition with an extra transposition
1148   // operation in a future canonicalizer.
1149   SmallVector<int64_t> sentinels;
1150   SmallVector<int64_t> extractPosition;
1151 };
1152 } // namespace
1153 
1154 ExtractFromInsertTransposeChainState::ExtractFromInsertTransposeChainState(
1155     ExtractOp e)
1156     : extractOp(e), vectorRank(extractOp.getVectorType().getRank()),
1157       extractedRank(extractOp.position().size()) {
1158   assert(vectorRank >= extractedRank && "extracted pos overflow");
1159   sentinels.reserve(vectorRank - extractedRank);
1160   for (int64_t i = 0, e = vectorRank - extractedRank; i < e; ++i)
1161     sentinels.push_back(-(i + 1));
1162   extractPosition = extractVector<int64_t>(extractOp.position());
1163   llvm::append_range(extractPosition, sentinels);
1164 }
1165 
1166 // Case 1. If we hit a transpose, just compose the map and iterate.
1167 // Invariant: insert + transpose do not change rank, we can always compose.
1168 LogicalResult ExtractFromInsertTransposeChainState::handleTransposeOp() {
1169   if (!nextTransposeOp)
1170     return failure();
1171   auto permutation = extractVector<unsigned>(nextTransposeOp.transp());
1172   AffineMap m = inversePermutation(
1173       AffineMap::getPermutationMap(permutation, extractOp.getContext()));
1174   extractPosition = applyPermutationMap(m, makeArrayRef(extractPosition));
1175   return success();
1176 }
1177 
1178 // Case 2: the insert position matches extractPosition exactly, early return.
1179 LogicalResult
1180 ExtractFromInsertTransposeChainState::handleInsertOpWithMatchingPos(
1181     Value &res) {
1182   auto insertedPos = extractVector<int64_t>(nextInsertOp.position());
1183   if (makeArrayRef(insertedPos) !=
1184       llvm::makeArrayRef(extractPosition).take_front(extractedRank))
1185     return failure();
1186   // Case 2.a. early-exit fold.
1187   res = nextInsertOp.source();
1188   // Case 2.b. if internal transposition is present, canFold will be false.
1189   return success();
1190 }
1191 
1192 /// Case 3: if inserted position is a prefix of extractPosition,
1193 /// extract a portion of the source of the insertion.
1194 /// This method updates the internal state.
1195 LogicalResult
1196 ExtractFromInsertTransposeChainState::handleInsertOpWithPrefixPos(Value &res) {
1197   auto insertedPos = extractVector<int64_t>(nextInsertOp.position());
1198   if (!isContainedWithin(insertedPos, extractPosition))
1199     return failure();
1200   // Set leading dims to zero.
1201   std::fill_n(extractPosition.begin(), insertedPos.size(), 0);
1202   // Drop extra leading dims.
1203   extractPosition.erase(extractPosition.begin(),
1204                         extractPosition.begin() + insertedPos.size());
1205   extractedRank = extractPosition.size() - sentinels.size();
1206   // Case 3.a. early-exit fold (break and delegate to post-while path).
1207   res = nextInsertOp.source();
1208   // Case 3.b. if internal transposition is present, canFold will be false.
1209   return success();
1210 }
1211 
1212 /// Try to fold in place to extract(source, extractPosition) and return the
1213 /// folded result. Return null if folding is not possible (e.g. due to an
1214 /// internal tranposition in the result).
1215 Value ExtractFromInsertTransposeChainState::tryToFoldExtractOpInPlace(
1216     Value source) {
1217   // If we can't fold (either internal transposition, or nothing to fold), bail.
1218   bool nothingToFold = (source == extractOp.vector());
1219   if (nothingToFold || !canFold())
1220     return Value();
1221   // Otherwise, fold by updating the op inplace and return its result.
1222   OpBuilder b(extractOp.getContext());
1223   extractOp->setAttr(
1224       extractOp.positionAttrName(),
1225       b.getI64ArrayAttr(
1226           makeArrayRef(extractPosition).take_front(extractedRank)));
1227   extractOp.vectorMutable().assign(source);
1228   return extractOp.getResult();
1229 }
1230 
1231 /// Iterate over producing insert and transpose ops until we find a fold.
1232 Value ExtractFromInsertTransposeChainState::fold() {
1233   Value valueToExtractFrom = extractOp.vector();
1234   updateStateForNextIteration(valueToExtractFrom);
1235   while (nextInsertOp || nextTransposeOp) {
1236     // Case 1. If we hit a transpose, just compose the map and iterate.
1237     // Invariant: insert + transpose do not change rank, we can always compose.
1238     if (succeeded(handleTransposeOp())) {
1239       valueToExtractFrom = nextTransposeOp.vector();
1240       updateStateForNextIteration(valueToExtractFrom);
1241       continue;
1242     }
1243 
1244     Value result;
1245     // Case 2: the position match exactly.
1246     if (succeeded(handleInsertOpWithMatchingPos(result)))
1247       return result;
1248 
1249     // Case 3: if the inserted position is a prefix of extractPosition, we can
1250     // just extract a portion of the source of the insert.
1251     if (succeeded(handleInsertOpWithPrefixPos(result)))
1252       return tryToFoldExtractOpInPlace(result);
1253 
1254     // Case 4: extractPositionRef intersects insertedPosRef on non-sentinel
1255     // values. This is a more difficult case and we bail.
1256     auto insertedPos = extractVector<int64_t>(nextInsertOp.position());
1257     if (isContainedWithin(extractPosition, insertedPos) ||
1258         intersectsWhereNonNegative(extractPosition, insertedPos))
1259       return Value();
1260 
1261     // Case 5: No intersection, we forward the extract to insertOp.dest().
1262     valueToExtractFrom = nextInsertOp.dest();
1263     updateStateForNextIteration(valueToExtractFrom);
1264   }
1265   // If after all this we can fold, go for it.
1266   return tryToFoldExtractOpInPlace(valueToExtractFrom);
1267 }
1268 
1269 /// Fold extractOp with scalar result coming from BroadcastOp or SplatOp.
1270 static Value foldExtractFromBroadcast(ExtractOp extractOp) {
1271   Operation *defOp = extractOp.vector().getDefiningOp();
1272   if (!defOp || !isa<vector::BroadcastOp, SplatOp>(defOp))
1273     return Value();
1274   Value source = defOp->getOperand(0);
1275   if (extractOp.getType() == source.getType())
1276     return source;
1277   auto getRank = [](Type type) {
1278     return type.isa<VectorType>() ? type.cast<VectorType>().getRank() : 0;
1279   };
1280   unsigned broadcastSrcRank = getRank(source.getType());
1281   unsigned extractResultRank = getRank(extractOp.getType());
1282   if (extractResultRank < broadcastSrcRank) {
1283     auto extractPos = extractVector<int64_t>(extractOp.position());
1284     unsigned rankDiff = broadcastSrcRank - extractResultRank;
1285     extractPos.erase(
1286         extractPos.begin(),
1287         std::next(extractPos.begin(), extractPos.size() - rankDiff));
1288     extractOp.setOperand(source);
1289     // OpBuilder is only used as a helper to build an I64ArrayAttr.
1290     OpBuilder b(extractOp.getContext());
1291     extractOp->setAttr(ExtractOp::getPositionAttrStrName(),
1292                        b.getI64ArrayAttr(extractPos));
1293     return extractOp.getResult();
1294   }
1295   return Value();
1296 }
1297 
1298 // Fold extractOp with source coming from ShapeCast op.
1299 static Value foldExtractFromShapeCast(ExtractOp extractOp) {
1300   auto shapeCastOp = extractOp.vector().getDefiningOp<vector::ShapeCastOp>();
1301   if (!shapeCastOp)
1302     return Value();
1303   // Get the nth dimension size starting from lowest dimension.
1304   auto getDimReverse = [](VectorType type, int64_t n) {
1305     return type.getShape().take_back(n + 1).front();
1306   };
1307   int64_t destinationRank =
1308       extractOp.getType().isa<VectorType>()
1309           ? extractOp.getType().cast<VectorType>().getRank()
1310           : 0;
1311   if (destinationRank > shapeCastOp.getSourceVectorType().getRank())
1312     return Value();
1313   if (destinationRank > 0) {
1314     auto destinationType = extractOp.getResult().getType().cast<VectorType>();
1315     for (int64_t i = 0; i < destinationRank; i++) {
1316       // The lowest dimension of of the destination must match the lowest
1317       // dimension of the shapecast op source.
1318       // TODO: This case could be support in a canonicalization pattern.
1319       if (getDimReverse(shapeCastOp.getSourceVectorType(), i) !=
1320           getDimReverse(destinationType, i))
1321         return Value();
1322     }
1323   }
1324   // Extract the strides associated with the extract op vector source. Then use
1325   // this to calculate a linearized position for the extract.
1326   auto extractedPos = extractVector<int64_t>(extractOp.position());
1327   std::reverse(extractedPos.begin(), extractedPos.end());
1328   SmallVector<int64_t, 4> strides;
1329   int64_t stride = 1;
1330   for (int64_t i = 0, e = extractedPos.size(); i < e; i++) {
1331     strides.push_back(stride);
1332     stride *= getDimReverse(extractOp.getVectorType(), i + destinationRank);
1333   }
1334 
1335   int64_t position = linearize(extractedPos, strides);
1336   // Then extract the strides associated to the shapeCast op vector source and
1337   // delinearize the position using those strides.
1338   SmallVector<int64_t, 4> newStrides;
1339   int64_t numDimension =
1340       shapeCastOp.getSourceVectorType().getRank() - destinationRank;
1341   stride = 1;
1342   for (int64_t i = 0; i < numDimension; i++) {
1343     newStrides.push_back(stride);
1344     stride *=
1345         getDimReverse(shapeCastOp.getSourceVectorType(), i + destinationRank);
1346   }
1347   std::reverse(newStrides.begin(), newStrides.end());
1348   SmallVector<int64_t, 4> newPosition = delinearize(newStrides, position);
1349   // OpBuilder is only used as a helper to build an I64ArrayAttr.
1350   OpBuilder b(extractOp.getContext());
1351   extractOp->setAttr(ExtractOp::getPositionAttrStrName(),
1352                      b.getI64ArrayAttr(newPosition));
1353   extractOp.setOperand(shapeCastOp.source());
1354   return extractOp.getResult();
1355 }
1356 
1357 /// Fold an ExtractOp from ExtractStridedSliceOp.
1358 static Value foldExtractFromExtractStrided(ExtractOp extractOp) {
1359   auto extractStridedSliceOp =
1360       extractOp.vector().getDefiningOp<vector::ExtractStridedSliceOp>();
1361   if (!extractStridedSliceOp)
1362     return Value();
1363   // Return if 'extractStridedSliceOp' has non-unit strides.
1364   if (extractStridedSliceOp.hasNonUnitStrides())
1365     return Value();
1366 
1367   // Trim offsets for dimensions fully extracted.
1368   auto sliceOffsets = extractVector<int64_t>(extractStridedSliceOp.offsets());
1369   while (!sliceOffsets.empty()) {
1370     size_t lastOffset = sliceOffsets.size() - 1;
1371     if (sliceOffsets.back() != 0 ||
1372         extractStridedSliceOp.getType().getDimSize(lastOffset) !=
1373             extractStridedSliceOp.getVectorType().getDimSize(lastOffset))
1374       break;
1375     sliceOffsets.pop_back();
1376   }
1377   unsigned destinationRank = 0;
1378   if (auto vecType = extractOp.getType().dyn_cast<VectorType>())
1379     destinationRank = vecType.getRank();
1380   // The dimensions of the result need to be untouched by the
1381   // extractStridedSlice op.
1382   if (destinationRank >
1383       extractStridedSliceOp.getVectorType().getRank() - sliceOffsets.size())
1384     return Value();
1385   auto extractedPos = extractVector<int64_t>(extractOp.position());
1386   assert(extractedPos.size() >= sliceOffsets.size());
1387   for (size_t i = 0, e = sliceOffsets.size(); i < e; i++)
1388     extractedPos[i] = extractedPos[i] + sliceOffsets[i];
1389   extractOp.vectorMutable().assign(extractStridedSliceOp.vector());
1390   // OpBuilder is only used as a helper to build an I64ArrayAttr.
1391   OpBuilder b(extractOp.getContext());
1392   extractOp->setAttr(ExtractOp::getPositionAttrStrName(),
1393                      b.getI64ArrayAttr(extractedPos));
1394   return extractOp.getResult();
1395 }
1396 
1397 /// Fold extract_op fed from a chain of insertStridedSlice ops.
1398 static Value foldExtractStridedOpFromInsertChain(ExtractOp op) {
1399   int64_t destinationRank = op.getType().isa<VectorType>()
1400                                 ? op.getType().cast<VectorType>().getRank()
1401                                 : 0;
1402   auto insertOp = op.vector().getDefiningOp<InsertStridedSliceOp>();
1403   while (insertOp) {
1404     int64_t insertRankDiff = insertOp.getDestVectorType().getRank() -
1405                              insertOp.getSourceVectorType().getRank();
1406     if (destinationRank > insertOp.getSourceVectorType().getRank())
1407       return Value();
1408     auto insertOffsets = extractVector<int64_t>(insertOp.offsets());
1409     auto extractOffsets = extractVector<int64_t>(op.position());
1410 
1411     if (llvm::any_of(insertOp.strides(), [](Attribute attr) {
1412           return attr.cast<IntegerAttr>().getInt() != 1;
1413         }))
1414       return Value();
1415     bool disjoint = false;
1416     SmallVector<int64_t, 4> offsetDiffs;
1417     for (unsigned dim = 0, e = extractOffsets.size(); dim < e; ++dim) {
1418       int64_t start = insertOffsets[dim];
1419       int64_t size =
1420           (dim < insertRankDiff)
1421               ? 1
1422               : insertOp.getSourceVectorType().getDimSize(dim - insertRankDiff);
1423       int64_t end = start + size;
1424       int64_t offset = extractOffsets[dim];
1425       // Check if the start of the extract offset is in the interval inserted.
1426       if (start <= offset && offset < end) {
1427         if (dim >= insertRankDiff)
1428           offsetDiffs.push_back(offset - start);
1429         continue;
1430       }
1431       disjoint = true;
1432       break;
1433     }
1434     // The extract element chunk overlap with the vector inserted.
1435     if (!disjoint) {
1436       // If any of the inner dimensions are only partially inserted we have a
1437       // partial overlap.
1438       int64_t srcRankDiff =
1439           insertOp.getSourceVectorType().getRank() - destinationRank;
1440       for (int64_t i = 0; i < destinationRank; i++) {
1441         if (insertOp.getSourceVectorType().getDimSize(i + srcRankDiff) !=
1442             insertOp.getDestVectorType().getDimSize(i + srcRankDiff +
1443                                                     insertRankDiff))
1444           return Value();
1445       }
1446       op.vectorMutable().assign(insertOp.source());
1447       // OpBuilder is only used as a helper to build an I64ArrayAttr.
1448       OpBuilder b(op.getContext());
1449       op->setAttr(ExtractOp::getPositionAttrStrName(),
1450                   b.getI64ArrayAttr(offsetDiffs));
1451       return op.getResult();
1452     }
1453     // If the chunk extracted is disjoint from the chunk inserted, keep
1454     // looking in the insert chain.
1455     insertOp = insertOp.dest().getDefiningOp<InsertStridedSliceOp>();
1456   }
1457   return Value();
1458 }
1459 
1460 OpFoldResult ExtractOp::fold(ArrayRef<Attribute>) {
1461   if (position().empty())
1462     return vector();
1463   if (succeeded(foldExtractOpFromExtractChain(*this)))
1464     return getResult();
1465   if (auto res = ExtractFromInsertTransposeChainState(*this).fold())
1466     return res;
1467   if (auto res = foldExtractFromBroadcast(*this))
1468     return res;
1469   if (auto res = foldExtractFromShapeCast(*this))
1470     return res;
1471   if (auto val = foldExtractFromExtractStrided(*this))
1472     return val;
1473   if (auto val = foldExtractStridedOpFromInsertChain(*this))
1474     return val;
1475   return OpFoldResult();
1476 }
1477 
1478 namespace {
1479 
1480 // Pattern to rewrite a ExtractOp(Broadcast) -> Broadcast.
1481 class ExtractOpFromBroadcast final : public OpRewritePattern<ExtractOp> {
1482 public:
1483   using OpRewritePattern<ExtractOp>::OpRewritePattern;
1484 
1485   LogicalResult matchAndRewrite(ExtractOp extractOp,
1486                                 PatternRewriter &rewriter) const override {
1487     Operation *defOp = extractOp.vector().getDefiningOp();
1488     if (!defOp || !isa<vector::BroadcastOp, SplatOp>(defOp))
1489       return failure();
1490     Value source = defOp->getOperand(0);
1491     if (extractOp.getType() == source.getType())
1492       return failure();
1493     auto getRank = [](Type type) {
1494       return type.isa<VectorType>() ? type.cast<VectorType>().getRank() : 0;
1495     };
1496     unsigned broadcastSrcRank = getRank(source.getType());
1497     unsigned extractResultRank = getRank(extractOp.getType());
1498     // We only consider the case where the rank of the source is smaller than
1499     // the rank of the extract dst. The other cases are handled in the folding
1500     // patterns.
1501     if (extractResultRank <= broadcastSrcRank)
1502       return failure();
1503     rewriter.replaceOpWithNewOp<vector::BroadcastOp>(
1504         extractOp, extractOp.getType(), source);
1505     return success();
1506   }
1507 };
1508 
1509 // Pattern to rewrite a ExtractOp(splat ConstantOp) -> ConstantOp.
1510 class ExtractOpConstantFolder final : public OpRewritePattern<ExtractOp> {
1511 public:
1512   using OpRewritePattern<ExtractOp>::OpRewritePattern;
1513 
1514   LogicalResult matchAndRewrite(ExtractOp extractOp,
1515                                 PatternRewriter &rewriter) const override {
1516     // Return if 'extractStridedSliceOp' operand is not defined by a
1517     // ConstantOp.
1518     auto constantOp = extractOp.vector().getDefiningOp<arith::ConstantOp>();
1519     if (!constantOp)
1520       return failure();
1521     auto dense = constantOp.getValue().dyn_cast<SplatElementsAttr>();
1522     if (!dense)
1523       return failure();
1524     Attribute newAttr = dense.getSplatValue<Attribute>();
1525     if (auto vecDstType = extractOp.getType().dyn_cast<VectorType>())
1526       newAttr = DenseElementsAttr::get(vecDstType, newAttr);
1527     rewriter.replaceOpWithNewOp<arith::ConstantOp>(extractOp, newAttr);
1528     return success();
1529   }
1530 };
1531 
1532 } // namespace
1533 
1534 void ExtractOp::getCanonicalizationPatterns(RewritePatternSet &results,
1535                                             MLIRContext *context) {
1536   results.add<ExtractOpConstantFolder, ExtractOpFromBroadcast>(context);
1537 }
1538 
1539 static void populateFromInt64AttrArray(ArrayAttr arrayAttr,
1540                                        SmallVectorImpl<int64_t> &results) {
1541   for (auto attr : arrayAttr)
1542     results.push_back(attr.cast<IntegerAttr>().getInt());
1543 }
1544 
1545 //===----------------------------------------------------------------------===//
1546 // ExtractMapOp
1547 //===----------------------------------------------------------------------===//
1548 
1549 void ExtractMapOp::build(OpBuilder &builder, OperationState &result,
1550                          Value vector, ValueRange ids,
1551                          ArrayRef<int64_t> multiplicity,
1552                          AffineMap permutationMap) {
1553   assert(ids.size() == multiplicity.size() &&
1554          ids.size() == permutationMap.getNumResults());
1555   assert(permutationMap.isProjectedPermutation());
1556   VectorType type = vector.getType().cast<VectorType>();
1557   SmallVector<int64_t, 4> newShape(type.getShape().begin(),
1558                                    type.getShape().end());
1559   for (unsigned i = 0, e = permutationMap.getNumResults(); i < e; i++) {
1560     AffineExpr expr = permutationMap.getResult(i);
1561     auto dim = expr.cast<AffineDimExpr>();
1562     newShape[dim.getPosition()] = newShape[dim.getPosition()] / multiplicity[i];
1563   }
1564   VectorType resultType = VectorType::get(newShape, type.getElementType());
1565   ExtractMapOp::build(builder, result, resultType, vector, ids);
1566 }
1567 
1568 LogicalResult ExtractMapOp::verify() {
1569   if (getSourceVectorType().getRank() != getResultType().getRank())
1570     return emitOpError("expected source and destination vectors of same rank");
1571   unsigned numId = 0;
1572   for (unsigned i = 0, e = getSourceVectorType().getRank(); i < e; ++i) {
1573     if (getSourceVectorType().getDimSize(i) % getResultType().getDimSize(i) !=
1574         0)
1575       return emitOpError("source vector dimensions must be a multiple of "
1576                          "destination vector dimensions");
1577     if (getSourceVectorType().getDimSize(i) != getResultType().getDimSize(i))
1578       numId++;
1579   }
1580   if (numId != ids().size())
1581     return emitOpError("expected number of ids must match the number of "
1582                        "dimensions distributed");
1583   return success();
1584 }
1585 
1586 OpFoldResult ExtractMapOp::fold(ArrayRef<Attribute> operands) {
1587   auto insert = vector().getDefiningOp<vector::InsertMapOp>();
1588   if (insert == nullptr || getType() != insert.vector().getType() ||
1589       ids() != insert.ids())
1590     return {};
1591   return insert.vector();
1592 }
1593 
1594 void ExtractMapOp::getMultiplicity(SmallVectorImpl<int64_t> &multiplicity) {
1595   assert(multiplicity.empty());
1596   for (unsigned i = 0, e = getSourceVectorType().getRank(); i < e; i++) {
1597     if (getSourceVectorType().getDimSize(i) != getResultType().getDimSize(i))
1598       multiplicity.push_back(getSourceVectorType().getDimSize(i) /
1599                              getResultType().getDimSize(i));
1600   }
1601 }
1602 
1603 template <typename MapOp>
1604 AffineMap calculateImplicitMap(MapOp op) {
1605   SmallVector<AffineExpr, 4> perm;
1606   // Check which dimension have a multiplicity greater than 1 and associated
1607   // them to the IDs in order.
1608   for (unsigned i = 0, e = op.getSourceVectorType().getRank(); i < e; i++) {
1609     if (op.getSourceVectorType().getDimSize(i) !=
1610         op.getResultType().getDimSize(i))
1611       perm.push_back(getAffineDimExpr(i, op.getContext()));
1612   }
1613   auto map = AffineMap::get(op.getSourceVectorType().getRank(), 0, perm,
1614                             op.getContext());
1615   return map;
1616 }
1617 
1618 AffineMap ExtractMapOp::map() { return calculateImplicitMap(*this); }
1619 
1620 //===----------------------------------------------------------------------===//
1621 // FmaOp
1622 //===----------------------------------------------------------------------===//
1623 
1624 Optional<SmallVector<int64_t, 4>> FMAOp::getShapeForUnroll() {
1625   return llvm::to_vector<4>(getVectorType().getShape());
1626 }
1627 
1628 //===----------------------------------------------------------------------===//
1629 // BroadcastOp
1630 //===----------------------------------------------------------------------===//
1631 
1632 BroadcastableToResult
1633 mlir::vector::isBroadcastableTo(Type srcType, VectorType dstVectorType,
1634                                 std::pair<int, int> *mismatchingDims) {
1635   // Broadcast scalar to vector of the same element type.
1636   if (srcType.isIntOrIndexOrFloat() && dstVectorType &&
1637       getElementTypeOrSelf(srcType) == getElementTypeOrSelf(dstVectorType))
1638     return BroadcastableToResult::Success;
1639   // From now on, only vectors broadcast.
1640   VectorType srcVectorType = srcType.dyn_cast<VectorType>();
1641   if (!srcVectorType)
1642     return BroadcastableToResult::SourceTypeNotAVector;
1643 
1644   int64_t srcRank = srcVectorType.getRank();
1645   int64_t dstRank = dstVectorType.getRank();
1646   if (srcRank > dstRank)
1647     return BroadcastableToResult::SourceRankHigher;
1648   // Source has an exact match or singleton value for all trailing dimensions
1649   // (all leading dimensions are simply duplicated).
1650   int64_t lead = dstRank - srcRank;
1651   for (int64_t r = 0; r < srcRank; ++r) {
1652     int64_t srcDim = srcVectorType.getDimSize(r);
1653     int64_t dstDim = dstVectorType.getDimSize(lead + r);
1654     if (srcDim != 1 && srcDim != dstDim) {
1655       if (mismatchingDims) {
1656         mismatchingDims->first = srcDim;
1657         mismatchingDims->second = dstDim;
1658       }
1659       return BroadcastableToResult::DimensionMismatch;
1660     }
1661   }
1662 
1663   return BroadcastableToResult::Success;
1664 }
1665 
1666 LogicalResult BroadcastOp::verify() {
1667   std::pair<int, int> mismatchingDims;
1668   BroadcastableToResult res =
1669       isBroadcastableTo(getSourceType(), getVectorType(), &mismatchingDims);
1670   if (res == BroadcastableToResult::Success)
1671     return success();
1672   if (res == BroadcastableToResult::SourceRankHigher)
1673     return emitOpError("source rank higher than destination rank");
1674   if (res == BroadcastableToResult::DimensionMismatch)
1675     return emitOpError("dimension mismatch (")
1676            << mismatchingDims.first << " vs. " << mismatchingDims.second << ")";
1677   if (res == BroadcastableToResult::SourceTypeNotAVector)
1678     return emitOpError("source type is not a vector");
1679   llvm_unreachable("unexpected vector.broadcast op error");
1680 }
1681 
1682 OpFoldResult BroadcastOp::fold(ArrayRef<Attribute> operands) {
1683   if (getSourceType() == getVectorType())
1684     return source();
1685   if (!operands[0])
1686     return {};
1687   auto vectorType = getVectorType();
1688   if (operands[0].getType().isIntOrIndexOrFloat())
1689     return DenseElementsAttr::get(vectorType, operands[0]);
1690   if (auto attr = operands[0].dyn_cast<SplatElementsAttr>())
1691     return DenseElementsAttr::get(vectorType, attr.getSplatValue<Attribute>());
1692   return {};
1693 }
1694 
1695 namespace {
1696 
1697 // Fold broadcast1(broadcast2(x)) into broadcast1(x).
1698 struct BroadcastFolder : public OpRewritePattern<BroadcastOp> {
1699   using OpRewritePattern<BroadcastOp>::OpRewritePattern;
1700 
1701   LogicalResult matchAndRewrite(BroadcastOp broadcastOp,
1702                                 PatternRewriter &rewriter) const override {
1703     auto srcBroadcast = broadcastOp.source().getDefiningOp<BroadcastOp>();
1704     if (!srcBroadcast)
1705       return failure();
1706     rewriter.replaceOpWithNewOp<BroadcastOp>(
1707         broadcastOp, broadcastOp.getVectorType(), srcBroadcast.source());
1708     return success();
1709   }
1710 };
1711 } // namespace
1712 
1713 void BroadcastOp::getCanonicalizationPatterns(RewritePatternSet &results,
1714                                               MLIRContext *context) {
1715   // BroadcastToShapeCast is not a default canonicalization, it is opt-in by
1716   // calling `populateCastAwayVectorLeadingOneDimPatterns`
1717   results.add<BroadcastFolder>(context);
1718 }
1719 
1720 //===----------------------------------------------------------------------===//
1721 // ShuffleOp
1722 //===----------------------------------------------------------------------===//
1723 
1724 void ShuffleOp::build(OpBuilder &builder, OperationState &result, Value v1,
1725                       Value v2, ArrayRef<int64_t> mask) {
1726   build(builder, result, v1, v2, getVectorSubscriptAttr(builder, mask));
1727 }
1728 
1729 LogicalResult ShuffleOp::verify() {
1730   VectorType resultType = getVectorType();
1731   VectorType v1Type = getV1VectorType();
1732   VectorType v2Type = getV2VectorType();
1733   // Verify ranks.
1734   int64_t resRank = resultType.getRank();
1735   int64_t v1Rank = v1Type.getRank();
1736   int64_t v2Rank = v2Type.getRank();
1737   if (resRank != v1Rank || v1Rank != v2Rank)
1738     return emitOpError("rank mismatch");
1739   // Verify all but leading dimension sizes.
1740   for (int64_t r = 1; r < v1Rank; ++r) {
1741     int64_t resDim = resultType.getDimSize(r);
1742     int64_t v1Dim = v1Type.getDimSize(r);
1743     int64_t v2Dim = v2Type.getDimSize(r);
1744     if (resDim != v1Dim || v1Dim != v2Dim)
1745       return emitOpError("dimension mismatch");
1746   }
1747   // Verify mask length.
1748   auto maskAttr = mask().getValue();
1749   int64_t maskLength = maskAttr.size();
1750   if (maskLength <= 0)
1751     return emitOpError("invalid mask length");
1752   if (maskLength != resultType.getDimSize(0))
1753     return emitOpError("mask length mismatch");
1754   // Verify all indices.
1755   int64_t indexSize = v1Type.getDimSize(0) + v2Type.getDimSize(0);
1756   for (const auto &en : llvm::enumerate(maskAttr)) {
1757     auto attr = en.value().dyn_cast<IntegerAttr>();
1758     if (!attr || attr.getInt() < 0 || attr.getInt() >= indexSize)
1759       return emitOpError("mask index #") << (en.index() + 1) << " out of range";
1760   }
1761   return success();
1762 }
1763 
1764 LogicalResult
1765 ShuffleOp::inferReturnTypes(MLIRContext *, Optional<Location>,
1766                             ValueRange operands, DictionaryAttr attributes,
1767                             RegionRange,
1768                             SmallVectorImpl<Type> &inferredReturnTypes) {
1769   ShuffleOp::Adaptor op(operands, attributes);
1770   auto v1Type = op.v1().getType().cast<VectorType>();
1771   // Construct resulting type: leading dimension matches mask length,
1772   // all trailing dimensions match the operands.
1773   SmallVector<int64_t, 4> shape;
1774   shape.reserve(v1Type.getRank());
1775   shape.push_back(std::max<size_t>(1, op.mask().size()));
1776   llvm::append_range(shape, v1Type.getShape().drop_front());
1777   inferredReturnTypes.push_back(
1778       VectorType::get(shape, v1Type.getElementType()));
1779   return success();
1780 }
1781 
1782 OpFoldResult vector::ShuffleOp::fold(ArrayRef<Attribute> operands) {
1783   Attribute lhs = operands.front(), rhs = operands.back();
1784   if (!lhs || !rhs)
1785     return {};
1786 
1787   auto lhsType = lhs.getType().cast<VectorType>();
1788   // Only support 1-D for now to avoid complicated n-D DenseElementsAttr
1789   // manipulation.
1790   if (lhsType.getRank() != 1)
1791     return {};
1792   int64_t lhsSize = lhsType.getDimSize(0);
1793 
1794   SmallVector<Attribute> results;
1795   auto lhsElements = lhs.cast<DenseElementsAttr>().getValues<Attribute>();
1796   auto rhsElements = rhs.cast<DenseElementsAttr>().getValues<Attribute>();
1797   for (const auto &index : this->mask().getAsValueRange<IntegerAttr>()) {
1798     int64_t i = index.getZExtValue();
1799     if (i >= lhsSize) {
1800       results.push_back(rhsElements[i - lhsSize]);
1801     } else {
1802       results.push_back(lhsElements[i]);
1803     }
1804   }
1805 
1806   return DenseElementsAttr::get(getVectorType(), results);
1807 }
1808 
1809 //===----------------------------------------------------------------------===//
1810 // InsertElementOp
1811 //===----------------------------------------------------------------------===//
1812 
1813 void InsertElementOp::build(OpBuilder &builder, OperationState &result,
1814                             Value source, Value dest) {
1815   build(builder, result, source, dest, {});
1816 }
1817 
1818 LogicalResult InsertElementOp::verify() {
1819   auto dstVectorType = getDestVectorType();
1820   if (dstVectorType.getRank() == 0) {
1821     if (position())
1822       return emitOpError("expected position to be empty with 0-D vector");
1823     return success();
1824   }
1825   if (dstVectorType.getRank() != 1)
1826     return emitOpError("unexpected >1 vector rank");
1827   if (!position())
1828     return emitOpError("expected position for 1-D vector");
1829   return success();
1830 }
1831 
1832 //===----------------------------------------------------------------------===//
1833 // InsertOp
1834 //===----------------------------------------------------------------------===//
1835 
1836 void InsertOp::build(OpBuilder &builder, OperationState &result, Value source,
1837                      Value dest, ArrayRef<int64_t> position) {
1838   result.addOperands({source, dest});
1839   auto positionAttr = getVectorSubscriptAttr(builder, position);
1840   result.addTypes(dest.getType());
1841   result.addAttribute(getPositionAttrStrName(), positionAttr);
1842 }
1843 
1844 // Convenience builder which assumes the values are constant indices.
1845 void InsertOp::build(OpBuilder &builder, OperationState &result, Value source,
1846                      Value dest, ValueRange position) {
1847   SmallVector<int64_t, 4> positionConstants =
1848       llvm::to_vector<4>(llvm::map_range(position, [](Value pos) {
1849         return pos.getDefiningOp<arith::ConstantIndexOp>().value();
1850       }));
1851   build(builder, result, source, dest, positionConstants);
1852 }
1853 
1854 LogicalResult InsertOp::verify() {
1855   auto positionAttr = position().getValue();
1856   auto destVectorType = getDestVectorType();
1857   if (positionAttr.size() > static_cast<unsigned>(destVectorType.getRank()))
1858     return emitOpError(
1859         "expected position attribute of rank smaller than dest vector rank");
1860   auto srcVectorType = getSourceType().dyn_cast<VectorType>();
1861   if (srcVectorType &&
1862       (static_cast<unsigned>(srcVectorType.getRank()) + positionAttr.size() !=
1863        static_cast<unsigned>(destVectorType.getRank())))
1864     return emitOpError("expected position attribute rank + source rank to "
1865                           "match dest vector rank");
1866   if (!srcVectorType &&
1867       (positionAttr.size() != static_cast<unsigned>(destVectorType.getRank())))
1868     return emitOpError(
1869         "expected position attribute rank to match the dest vector rank");
1870   for (const auto &en : llvm::enumerate(positionAttr)) {
1871     auto attr = en.value().dyn_cast<IntegerAttr>();
1872     if (!attr || attr.getInt() < 0 ||
1873         attr.getInt() >= destVectorType.getDimSize(en.index()))
1874       return emitOpError("expected position attribute #")
1875              << (en.index() + 1)
1876              << " to be a non-negative integer smaller than the corresponding "
1877                 "dest vector dimension";
1878   }
1879   return success();
1880 }
1881 
1882 namespace {
1883 
1884 // If insertOp is only inserting unit dimensions it can be transformed to a
1885 // broadcast.
1886 class InsertToBroadcast final : public OpRewritePattern<InsertOp> {
1887 public:
1888   using OpRewritePattern<InsertOp>::OpRewritePattern;
1889 
1890   LogicalResult matchAndRewrite(InsertOp insertOp,
1891                                 PatternRewriter &rewriter) const override {
1892     auto srcVecType = insertOp.getSourceType().dyn_cast<VectorType>();
1893     if (!srcVecType || insertOp.getDestVectorType().getNumElements() !=
1894                            srcVecType.getNumElements())
1895       return failure();
1896     rewriter.replaceOpWithNewOp<BroadcastOp>(
1897         insertOp, insertOp.getDestVectorType(), insertOp.source());
1898     return success();
1899   }
1900 };
1901 
1902 } // namespace
1903 
1904 void InsertOp::getCanonicalizationPatterns(RewritePatternSet &results,
1905                                            MLIRContext *context) {
1906   results.add<InsertToBroadcast, BroadcastFolder>(context);
1907 }
1908 
1909 // Eliminates insert operations that produce values identical to their source
1910 // value. This happens when the source and destination vectors have identical
1911 // sizes.
1912 OpFoldResult vector::InsertOp::fold(ArrayRef<Attribute> operands) {
1913   if (position().empty())
1914     return source();
1915   return {};
1916 }
1917 
1918 //===----------------------------------------------------------------------===//
1919 // InsertMapOp
1920 //===----------------------------------------------------------------------===//
1921 
1922 void InsertMapOp::build(OpBuilder &builder, OperationState &result,
1923                         Value vector, Value dest, ValueRange ids) {
1924   InsertMapOp::build(builder, result, dest.getType(), vector, dest, ids);
1925 }
1926 
1927 LogicalResult InsertMapOp::verify() {
1928   if (getSourceVectorType().getRank() != getResultType().getRank())
1929     return emitOpError("expected source and destination vectors of same rank");
1930   unsigned numId = 0;
1931   for (unsigned i = 0, e = getResultType().getRank(); i < e; i++) {
1932     if (getResultType().getDimSize(i) % getSourceVectorType().getDimSize(i) !=
1933         0)
1934       return emitOpError(
1935           "destination vector size must be a multiple of source vector size");
1936     if (getResultType().getDimSize(i) != getSourceVectorType().getDimSize(i))
1937       numId++;
1938   }
1939   if (numId != ids().size())
1940     return emitOpError("expected number of ids must match the number of "
1941                        "dimensions distributed");
1942   return success();
1943 }
1944 
1945 AffineMap InsertMapOp::map() { return calculateImplicitMap(*this); }
1946 
1947 //===----------------------------------------------------------------------===//
1948 // InsertStridedSliceOp
1949 //===----------------------------------------------------------------------===//
1950 
1951 void InsertStridedSliceOp::build(OpBuilder &builder, OperationState &result,
1952                                  Value source, Value dest,
1953                                  ArrayRef<int64_t> offsets,
1954                                  ArrayRef<int64_t> strides) {
1955   result.addOperands({source, dest});
1956   auto offsetsAttr = getVectorSubscriptAttr(builder, offsets);
1957   auto stridesAttr = getVectorSubscriptAttr(builder, strides);
1958   result.addTypes(dest.getType());
1959   result.addAttribute(getOffsetsAttrStrName(), offsetsAttr);
1960   result.addAttribute(getStridesAttrStrName(), stridesAttr);
1961 }
1962 
1963 // TODO: Should be moved to Tablegen Confined attributes.
1964 template <typename OpType>
1965 static LogicalResult isIntegerArrayAttrSmallerThanShape(OpType op,
1966                                                         ArrayAttr arrayAttr,
1967                                                         ArrayRef<int64_t> shape,
1968                                                         StringRef attrName) {
1969   if (arrayAttr.size() > shape.size())
1970     return op.emitOpError("expected ")
1971            << attrName << " attribute of rank smaller than vector rank";
1972   return success();
1973 }
1974 
1975 // Returns true if all integers in `arrayAttr` are in the half-open [min, max}
1976 // interval. If `halfOpen` is true then the admissible interval is [min, max).
1977 // Otherwise, the admissible interval is [min, max].
1978 template <typename OpType>
1979 static LogicalResult
1980 isIntegerArrayAttrConfinedToRange(OpType op, ArrayAttr arrayAttr, int64_t min,
1981                                   int64_t max, StringRef attrName,
1982                                   bool halfOpen = true) {
1983   for (auto attr : arrayAttr) {
1984     auto val = attr.cast<IntegerAttr>().getInt();
1985     auto upper = max;
1986     if (!halfOpen)
1987       upper += 1;
1988     if (val < min || val >= upper)
1989       return op.emitOpError("expected ") << attrName << " to be confined to ["
1990                                          << min << ", " << upper << ")";
1991   }
1992   return success();
1993 }
1994 
1995 // Returns true if all integers in `arrayAttr` are in the half-open [min, max}
1996 // interval. If `halfOpen` is true then the admissible interval is [min, max).
1997 // Otherwise, the admissible interval is [min, max].
1998 template <typename OpType>
1999 static LogicalResult
2000 isIntegerArrayAttrConfinedToShape(OpType op, ArrayAttr arrayAttr,
2001                                   ArrayRef<int64_t> shape, StringRef attrName,
2002                                   bool halfOpen = true, int64_t min = 0) {
2003   assert(arrayAttr.size() <= shape.size());
2004   unsigned index = 0;
2005   for (auto it : llvm::zip(arrayAttr, shape)) {
2006     auto val = std::get<0>(it).cast<IntegerAttr>().getInt();
2007     auto max = std::get<1>(it);
2008     if (!halfOpen)
2009       max += 1;
2010     if (val < min || val >= max)
2011       return op.emitOpError("expected ")
2012              << attrName << " dimension " << index << " to be confined to ["
2013              << min << ", " << max << ")";
2014     ++index;
2015   }
2016   return success();
2017 }
2018 
2019 // Returns true if all integers in `arrayAttr` are in the interval [min, max}.
2020 // interval. If `halfOpen` is true then the admissible interval is [min, max).
2021 // Otherwise, the admissible interval is [min, max].
2022 template <typename OpType>
2023 static LogicalResult isSumOfIntegerArrayAttrConfinedToShape(
2024     OpType op, ArrayAttr arrayAttr1, ArrayAttr arrayAttr2,
2025     ArrayRef<int64_t> shape, StringRef attrName1, StringRef attrName2,
2026     bool halfOpen = true, int64_t min = 1) {
2027   assert(arrayAttr1.size() <= shape.size());
2028   assert(arrayAttr2.size() <= shape.size());
2029   unsigned index = 0;
2030   for (auto it : llvm::zip(arrayAttr1, arrayAttr2, shape)) {
2031     auto val1 = std::get<0>(it).cast<IntegerAttr>().getInt();
2032     auto val2 = std::get<1>(it).cast<IntegerAttr>().getInt();
2033     auto max = std::get<2>(it);
2034     if (!halfOpen)
2035       max += 1;
2036     if (val1 + val2 < 0 || val1 + val2 >= max)
2037       return op.emitOpError("expected sum(")
2038              << attrName1 << ", " << attrName2 << ") dimension " << index
2039              << " to be confined to [" << min << ", " << max << ")";
2040     ++index;
2041   }
2042   return success();
2043 }
2044 
2045 static ArrayAttr makeI64ArrayAttr(ArrayRef<int64_t> values,
2046                                   MLIRContext *context) {
2047   auto attrs = llvm::map_range(values, [context](int64_t v) -> Attribute {
2048     return IntegerAttr::get(IntegerType::get(context, 64), APInt(64, v));
2049   });
2050   return ArrayAttr::get(context, llvm::to_vector<8>(attrs));
2051 }
2052 
2053 LogicalResult InsertStridedSliceOp::verify() {
2054   auto sourceVectorType = getSourceVectorType();
2055   auto destVectorType = getDestVectorType();
2056   auto offsets = offsetsAttr();
2057   auto strides = stridesAttr();
2058   if (offsets.size() != static_cast<unsigned>(destVectorType.getRank()))
2059     return emitOpError(
2060         "expected offsets of same size as destination vector rank");
2061   if (strides.size() != static_cast<unsigned>(sourceVectorType.getRank()))
2062     return emitOpError("expected strides of same size as source vector rank");
2063   if (sourceVectorType.getRank() > destVectorType.getRank())
2064     return emitOpError(
2065         "expected source rank to be smaller than destination rank");
2066 
2067   auto sourceShape = sourceVectorType.getShape();
2068   auto destShape = destVectorType.getShape();
2069   SmallVector<int64_t, 4> sourceShapeAsDestShape(
2070       destShape.size() - sourceShape.size(), 0);
2071   sourceShapeAsDestShape.append(sourceShape.begin(), sourceShape.end());
2072   auto offName = InsertStridedSliceOp::getOffsetsAttrName();
2073   auto stridesName = InsertStridedSliceOp::getStridesAttrName();
2074   if (failed(isIntegerArrayAttrConfinedToShape(*this, offsets, destShape,
2075                                                offName)) ||
2076       failed(isIntegerArrayAttrConfinedToRange(*this, strides, 1, 1,
2077                                                stridesName,
2078                                                /*halfOpen=*/false)) ||
2079       failed(isSumOfIntegerArrayAttrConfinedToShape(
2080           *this, offsets,
2081           makeI64ArrayAttr(sourceShapeAsDestShape, getContext()), destShape,
2082           offName, "source vector shape",
2083           /*halfOpen=*/false, /*min=*/1)))
2084     return failure();
2085 
2086   return success();
2087 }
2088 
2089 OpFoldResult InsertStridedSliceOp::fold(ArrayRef<Attribute> operands) {
2090   if (getSourceVectorType() == getDestVectorType())
2091     return source();
2092   return {};
2093 }
2094 
2095 //===----------------------------------------------------------------------===//
2096 // OuterProductOp
2097 //===----------------------------------------------------------------------===//
2098 
2099 /// Build an op without mask, use the type of `acc` as the return type.
2100 void OuterProductOp::build(OpBuilder &builder, OperationState &result,
2101                            Value lhs, Value rhs, Value acc) {
2102   result.addOperands({lhs, rhs, acc});
2103   result.addTypes(acc.getType());
2104 }
2105 
2106 void OuterProductOp::print(OpAsmPrinter &p) {
2107   p << " " << lhs() << ", " << rhs();
2108   if (!acc().empty()) {
2109     p << ", " << acc();
2110     p.printOptionalAttrDict((*this)->getAttrs());
2111   }
2112   p << " : " << lhs().getType() << ", " << rhs().getType();
2113 }
2114 
2115 ParseResult OuterProductOp::parse(OpAsmParser &parser, OperationState &result) {
2116   SmallVector<OpAsmParser::OperandType, 3> operandsInfo;
2117   Type tLHS, tRHS;
2118   if (parser.parseOperandList(operandsInfo) ||
2119       parser.parseOptionalAttrDict(result.attributes) ||
2120       parser.parseColonType(tLHS) || parser.parseComma() ||
2121       parser.parseType(tRHS))
2122     return failure();
2123   if (operandsInfo.size() < 2)
2124     return parser.emitError(parser.getNameLoc(),
2125                             "expected at least 2 operands");
2126   VectorType vLHS = tLHS.dyn_cast<VectorType>();
2127   VectorType vRHS = tRHS.dyn_cast<VectorType>();
2128   if (!vLHS)
2129     return parser.emitError(parser.getNameLoc(),
2130                             "expected vector type for operand #1");
2131   VectorType resType =
2132       vRHS ? VectorType::get({vLHS.getDimSize(0), vRHS.getDimSize(0)},
2133                              vLHS.getElementType())
2134            : VectorType::get({vLHS.getDimSize(0)}, vLHS.getElementType());
2135 
2136   if (!result.attributes.get(OuterProductOp::getKindAttrStrName())) {
2137     result.attributes.append(
2138         OuterProductOp::getKindAttrStrName(),
2139         CombiningKindAttr::get(OuterProductOp::getDefaultKind(),
2140                                result.getContext()));
2141   }
2142 
2143   return failure(
2144       parser.resolveOperand(operandsInfo[0], tLHS, result.operands) ||
2145       parser.resolveOperand(operandsInfo[1], tRHS, result.operands) ||
2146       (operandsInfo.size() > 2 &&
2147        parser.resolveOperand(operandsInfo[2], resType, result.operands)) ||
2148       parser.addTypeToList(resType, result.types));
2149 }
2150 
2151 LogicalResult OuterProductOp::verify() {
2152   Type tRHS = getOperandTypeRHS();
2153   VectorType vLHS = getOperandVectorTypeLHS(),
2154              vRHS = tRHS.dyn_cast<VectorType>(),
2155              vACC = getOperandVectorTypeACC(), vRES = getVectorType();
2156 
2157   if (vLHS.getRank() != 1)
2158     return emitOpError("expected 1-d vector for operand #1");
2159 
2160   if (vRHS) {
2161     // Proper OUTER operation.
2162     if (vRHS.getRank() != 1)
2163       return emitOpError("expected 1-d vector for operand #2");
2164     if (vRES.getRank() != 2)
2165       return emitOpError("expected 2-d vector result");
2166     if (vLHS.getDimSize(0) != vRES.getDimSize(0))
2167       return emitOpError("expected #1 operand dim to match result dim #1");
2168     if (vRHS.getDimSize(0) != vRES.getDimSize(1))
2169       return emitOpError("expected #2 operand dim to match result dim #2");
2170   } else {
2171     // An AXPY operation.
2172     if (vRES.getRank() != 1)
2173       return emitOpError("expected 1-d vector result");
2174     if (vLHS.getDimSize(0) != vRES.getDimSize(0))
2175       return emitOpError("expected #1 operand dim to match result dim #1");
2176   }
2177 
2178   if (vACC && vACC != vRES)
2179     return emitOpError("expected operand #3 of same type as result type");
2180 
2181   // Verify supported combining kind.
2182   if (!isSupportedCombiningKind(kind(), vRES.getElementType()))
2183     return emitOpError("unsupported outerproduct type");
2184 
2185   return success();
2186 }
2187 
2188 //===----------------------------------------------------------------------===//
2189 // ReshapeOp
2190 //===----------------------------------------------------------------------===//
2191 
2192 LogicalResult ReshapeOp::verify() {
2193   // Verify that rank(numInputs/outputs) + numFixedVec dim matches vec rank.
2194   auto inputVectorType = getInputVectorType();
2195   auto outputVectorType = getOutputVectorType();
2196   int64_t inputShapeRank = getNumInputShapeSizes();
2197   int64_t outputShapeRank = getNumOutputShapeSizes();
2198   SmallVector<int64_t, 4> fixedVectorSizes;
2199   getFixedVectorSizes(fixedVectorSizes);
2200   int64_t numFixedVectorSizes = fixedVectorSizes.size();
2201 
2202   if (inputVectorType.getRank() != inputShapeRank + numFixedVectorSizes)
2203     return emitError("invalid input shape for vector type ")
2204            << inputVectorType;
2205 
2206   if (outputVectorType.getRank() != outputShapeRank + numFixedVectorSizes)
2207     return emitError("invalid output shape for vector type ")
2208            << outputVectorType;
2209 
2210   // Verify that the 'fixedVectorSizes' match an input/output vector shape
2211   // suffix.
2212   unsigned inputVectorRank = inputVectorType.getRank();
2213   for (unsigned i = 0; i < numFixedVectorSizes; ++i) {
2214     unsigned index = inputVectorRank - numFixedVectorSizes - i;
2215     if (fixedVectorSizes[i] != inputVectorType.getShape()[index])
2216       return emitError("fixed vector size must match input vector for dim ")
2217              << i;
2218   }
2219 
2220   unsigned outputVectorRank = outputVectorType.getRank();
2221   for (unsigned i = 0; i < numFixedVectorSizes; ++i) {
2222     unsigned index = outputVectorRank - numFixedVectorSizes - i;
2223     if (fixedVectorSizes[i] != outputVectorType.getShape()[index])
2224       return emitError("fixed vector size must match output vector for dim ")
2225              << i;
2226   }
2227 
2228   // If all shape operands are produced by constant ops, verify that product
2229   // of dimensions for input/output shape match.
2230   auto isDefByConstant = [](Value operand) {
2231     return isa_and_nonnull<arith::ConstantIndexOp>(operand.getDefiningOp());
2232   };
2233   if (llvm::all_of(input_shape(), isDefByConstant) &&
2234       llvm::all_of(output_shape(), isDefByConstant)) {
2235     int64_t numInputElements = 1;
2236     for (auto operand : input_shape())
2237       numInputElements *=
2238           cast<arith::ConstantIndexOp>(operand.getDefiningOp()).value();
2239     int64_t numOutputElements = 1;
2240     for (auto operand : output_shape())
2241       numOutputElements *=
2242           cast<arith::ConstantIndexOp>(operand.getDefiningOp()).value();
2243     if (numInputElements != numOutputElements)
2244       return emitError("product of input and output shape sizes must match");
2245   }
2246   return success();
2247 }
2248 
2249 void ReshapeOp::getFixedVectorSizes(SmallVectorImpl<int64_t> &results) {
2250   populateFromInt64AttrArray(fixed_vector_sizes(), results);
2251 }
2252 
2253 //===----------------------------------------------------------------------===//
2254 // ExtractStridedSliceOp
2255 //===----------------------------------------------------------------------===//
2256 
2257 // Inference works as follows:
2258 //   1. Add 'sizes' from prefix of dims in 'offsets'.
2259 //   2. Add sizes from 'vectorType' for remaining dims.
2260 static Type inferStridedSliceOpResultType(VectorType vectorType,
2261                                           ArrayAttr offsets, ArrayAttr sizes,
2262                                           ArrayAttr strides) {
2263   assert(offsets.size() == sizes.size() && offsets.size() == strides.size());
2264   SmallVector<int64_t, 4> shape;
2265   shape.reserve(vectorType.getRank());
2266   unsigned idx = 0;
2267   for (unsigned e = offsets.size(); idx < e; ++idx)
2268     shape.push_back(sizes[idx].cast<IntegerAttr>().getInt());
2269   for (unsigned e = vectorType.getShape().size(); idx < e; ++idx)
2270     shape.push_back(vectorType.getShape()[idx]);
2271 
2272   return VectorType::get(shape, vectorType.getElementType());
2273 }
2274 
2275 void ExtractStridedSliceOp::build(OpBuilder &builder, OperationState &result,
2276                                   Value source, ArrayRef<int64_t> offsets,
2277                                   ArrayRef<int64_t> sizes,
2278                                   ArrayRef<int64_t> strides) {
2279   result.addOperands(source);
2280   auto offsetsAttr = getVectorSubscriptAttr(builder, offsets);
2281   auto sizesAttr = getVectorSubscriptAttr(builder, sizes);
2282   auto stridesAttr = getVectorSubscriptAttr(builder, strides);
2283   result.addTypes(
2284       inferStridedSliceOpResultType(source.getType().cast<VectorType>(),
2285                                     offsetsAttr, sizesAttr, stridesAttr));
2286   result.addAttribute(getOffsetsAttrStrName(), offsetsAttr);
2287   result.addAttribute(getSizesAttrStrName(), sizesAttr);
2288   result.addAttribute(getStridesAttrStrName(), stridesAttr);
2289 }
2290 
2291 LogicalResult ExtractStridedSliceOp::verify() {
2292   auto type = getVectorType();
2293   auto offsets = offsetsAttr();
2294   auto sizes = sizesAttr();
2295   auto strides = stridesAttr();
2296   if (offsets.size() != sizes.size() || offsets.size() != strides.size())
2297     return emitOpError("expected offsets, sizes and strides attributes of same size");
2298 
2299   auto shape = type.getShape();
2300   auto offName = getOffsetsAttrName();
2301   auto sizesName = getSizesAttrName();
2302   auto stridesName = getStridesAttrName();
2303   if (failed(isIntegerArrayAttrSmallerThanShape(*this, offsets, shape, offName)) ||
2304       failed(isIntegerArrayAttrSmallerThanShape(*this, sizes, shape, sizesName)) ||
2305       failed(isIntegerArrayAttrSmallerThanShape(*this, strides, shape,
2306                                                 stridesName)) ||
2307       failed(isIntegerArrayAttrConfinedToShape(*this, offsets, shape, offName)) ||
2308       failed(isIntegerArrayAttrConfinedToShape(*this, sizes, shape, sizesName,
2309                                                /*halfOpen=*/false,
2310                                                /*min=*/1)) ||
2311       failed(isIntegerArrayAttrConfinedToRange(*this, strides, 1, 1, stridesName,
2312                                                /*halfOpen=*/false)) ||
2313       failed(isSumOfIntegerArrayAttrConfinedToShape(*this, offsets, sizes, shape,
2314                                                     offName, sizesName,
2315                                                     /*halfOpen=*/false)))
2316     return failure();
2317 
2318   auto resultType =
2319       inferStridedSliceOpResultType(getVectorType(), offsets, sizes, strides);
2320   if (getResult().getType() != resultType)
2321     return emitOpError("expected result type to be ") << resultType;
2322 
2323   return success();
2324 }
2325 
2326 // When the source of ExtractStrided comes from a chain of InsertStrided ops try
2327 // to use the source of the InsertStrided ops if we can detect that the
2328 // extracted vector is a subset of one of the vector inserted.
2329 static LogicalResult
2330 foldExtractStridedOpFromInsertChain(ExtractStridedSliceOp op) {
2331   // Helper to extract integer out of ArrayAttr.
2332   auto getElement = [](ArrayAttr array, int idx) {
2333     return array[idx].cast<IntegerAttr>().getInt();
2334   };
2335   ArrayAttr extractOffsets = op.offsets();
2336   ArrayAttr extractStrides = op.strides();
2337   ArrayAttr extractSizes = op.sizes();
2338   auto insertOp = op.vector().getDefiningOp<InsertStridedSliceOp>();
2339   while (insertOp) {
2340     if (op.getVectorType().getRank() !=
2341         insertOp.getSourceVectorType().getRank())
2342       return failure();
2343     ArrayAttr insertOffsets = insertOp.offsets();
2344     ArrayAttr insertStrides = insertOp.strides();
2345     // If the rank of extract is greater than the rank of insert, we are likely
2346     // extracting a partial chunk of the vector inserted.
2347     if (extractOffsets.size() > insertOffsets.size())
2348       return failure();
2349     bool patialoverlap = false;
2350     bool disjoint = false;
2351     SmallVector<int64_t, 4> offsetDiffs;
2352     for (unsigned dim = 0, e = extractOffsets.size(); dim < e; ++dim) {
2353       if (getElement(extractStrides, dim) != getElement(insertStrides, dim))
2354         return failure();
2355       int64_t start = getElement(insertOffsets, dim);
2356       int64_t end = start + insertOp.getSourceVectorType().getDimSize(dim);
2357       int64_t offset = getElement(extractOffsets, dim);
2358       int64_t size = getElement(extractSizes, dim);
2359       // Check if the start of the extract offset is in the interval inserted.
2360       if (start <= offset && offset < end) {
2361         // If the extract interval overlaps but is not fully included we may
2362         // have a partial overlap that will prevent any folding.
2363         if (offset + size > end)
2364           patialoverlap = true;
2365         offsetDiffs.push_back(offset - start);
2366         continue;
2367       }
2368       disjoint = true;
2369       break;
2370     }
2371     // The extract element chunk is a subset of the insert element.
2372     if (!disjoint && !patialoverlap) {
2373       op.setOperand(insertOp.source());
2374       // OpBuilder is only used as a helper to build an I64ArrayAttr.
2375       OpBuilder b(op.getContext());
2376       op->setAttr(ExtractStridedSliceOp::getOffsetsAttrStrName(),
2377                   b.getI64ArrayAttr(offsetDiffs));
2378       return success();
2379     }
2380     // If the chunk extracted is disjoint from the chunk inserted, keep looking
2381     // in the insert chain.
2382     if (disjoint)
2383       insertOp = insertOp.dest().getDefiningOp<InsertStridedSliceOp>();
2384     else {
2385       // The extracted vector partially overlap the inserted vector, we cannot
2386       // fold.
2387       return failure();
2388     }
2389   }
2390   return failure();
2391 }
2392 
2393 OpFoldResult ExtractStridedSliceOp::fold(ArrayRef<Attribute> operands) {
2394   if (getVectorType() == getResult().getType())
2395     return vector();
2396   if (succeeded(foldExtractStridedOpFromInsertChain(*this)))
2397     return getResult();
2398   return {};
2399 }
2400 
2401 void ExtractStridedSliceOp::getOffsets(SmallVectorImpl<int64_t> &results) {
2402   populateFromInt64AttrArray(offsets(), results);
2403 }
2404 
2405 namespace {
2406 
2407 // Pattern to rewrite an ExtractStridedSliceOp(ConstantMaskOp) to
2408 // ConstantMaskOp.
2409 class StridedSliceConstantMaskFolder final
2410     : public OpRewritePattern<ExtractStridedSliceOp> {
2411 public:
2412   using OpRewritePattern<ExtractStridedSliceOp>::OpRewritePattern;
2413 
2414   LogicalResult matchAndRewrite(ExtractStridedSliceOp extractStridedSliceOp,
2415                                 PatternRewriter &rewriter) const override {
2416     // Return if 'extractStridedSliceOp' operand is not defined by a
2417     // ConstantMaskOp.
2418     auto *defOp = extractStridedSliceOp.vector().getDefiningOp();
2419     auto constantMaskOp = dyn_cast_or_null<ConstantMaskOp>(defOp);
2420     if (!constantMaskOp)
2421       return failure();
2422     // Return if 'extractStridedSliceOp' has non-unit strides.
2423     if (extractStridedSliceOp.hasNonUnitStrides())
2424       return failure();
2425     // Gather constant mask dimension sizes.
2426     SmallVector<int64_t, 4> maskDimSizes;
2427     populateFromInt64AttrArray(constantMaskOp.mask_dim_sizes(), maskDimSizes);
2428     // Gather strided slice offsets and sizes.
2429     SmallVector<int64_t, 4> sliceOffsets;
2430     populateFromInt64AttrArray(extractStridedSliceOp.offsets(), sliceOffsets);
2431     SmallVector<int64_t, 4> sliceSizes;
2432     populateFromInt64AttrArray(extractStridedSliceOp.sizes(), sliceSizes);
2433 
2434     // Compute slice of vector mask region.
2435     SmallVector<int64_t, 4> sliceMaskDimSizes;
2436     assert(sliceOffsets.size() == maskDimSizes.size());
2437     for (auto it : llvm::zip(maskDimSizes, sliceOffsets, sliceSizes)) {
2438       int64_t maskDimSize = std::get<0>(it);
2439       int64_t sliceOffset = std::get<1>(it);
2440       int64_t sliceSize = std::get<2>(it);
2441       int64_t sliceMaskDimSize = std::max(
2442           static_cast<int64_t>(0),
2443           std::min(sliceOffset + sliceSize, maskDimSize) - sliceOffset);
2444       sliceMaskDimSizes.push_back(sliceMaskDimSize);
2445     }
2446     // If any of 'sliceMaskDimSizes' are zero, then set all to zero (masked
2447     // region is a conjunction of mask dim intervals).
2448     if (llvm::is_contained(sliceMaskDimSizes, 0))
2449       sliceMaskDimSizes.assign(maskDimSizes.size(), 0);
2450 
2451     // Replace 'extractStridedSliceOp' with ConstantMaskOp with sliced mask
2452     // region.
2453     rewriter.replaceOpWithNewOp<ConstantMaskOp>(
2454         extractStridedSliceOp, extractStridedSliceOp.getResult().getType(),
2455         vector::getVectorSubscriptAttr(rewriter, sliceMaskDimSizes));
2456     return success();
2457   }
2458 };
2459 
2460 // Pattern to rewrite a ExtractStridedSliceOp(splat ConstantOp) -> ConstantOp.
2461 class StridedSliceConstantFolder final
2462     : public OpRewritePattern<ExtractStridedSliceOp> {
2463 public:
2464   using OpRewritePattern<ExtractStridedSliceOp>::OpRewritePattern;
2465 
2466   LogicalResult matchAndRewrite(ExtractStridedSliceOp extractStridedSliceOp,
2467                                 PatternRewriter &rewriter) const override {
2468     // Return if 'extractStridedSliceOp' operand is not defined by a
2469     // ConstantOp.
2470     auto constantOp =
2471         extractStridedSliceOp.vector().getDefiningOp<arith::ConstantOp>();
2472     if (!constantOp)
2473       return failure();
2474     auto dense = constantOp.getValue().dyn_cast<SplatElementsAttr>();
2475     if (!dense)
2476       return failure();
2477     auto newAttr = DenseElementsAttr::get(extractStridedSliceOp.getType(),
2478                                           dense.getSplatValue<Attribute>());
2479     rewriter.replaceOpWithNewOp<arith::ConstantOp>(extractStridedSliceOp,
2480                                                    newAttr);
2481     return success();
2482   }
2483 };
2484 
2485 // Pattern to rewrite an ExtractStridedSliceOp(BroadcastOp) to
2486 // BroadcastOp(ExtractStrideSliceOp).
2487 class StridedSliceBroadcast final
2488     : public OpRewritePattern<ExtractStridedSliceOp> {
2489 public:
2490   using OpRewritePattern<ExtractStridedSliceOp>::OpRewritePattern;
2491 
2492   LogicalResult matchAndRewrite(ExtractStridedSliceOp op,
2493                                 PatternRewriter &rewriter) const override {
2494     auto broadcast = op.vector().getDefiningOp<BroadcastOp>();
2495     if (!broadcast)
2496       return failure();
2497     auto srcVecType = broadcast.source().getType().dyn_cast<VectorType>();
2498     unsigned srcRrank = srcVecType ? srcVecType.getRank() : 0;
2499     auto dstVecType = op.getType().cast<VectorType>();
2500     unsigned dstRank = dstVecType.getRank();
2501     unsigned rankDiff = dstRank - srcRrank;
2502     // Check if the most inner dimensions of the source of the broadcast are the
2503     // same as the destination of the extract. If this is the case we can just
2504     // use a broadcast as the original dimensions are untouched.
2505     bool lowerDimMatch = true;
2506     for (unsigned i = 0; i < srcRrank; i++) {
2507       if (srcVecType.getDimSize(i) != dstVecType.getDimSize(i + rankDiff)) {
2508         lowerDimMatch = false;
2509         break;
2510       }
2511     }
2512     Value source = broadcast.source();
2513     if (!lowerDimMatch) {
2514       // The inner dimensions don't match, it means we need to extract from the
2515       // source of the orignal broadcast and then broadcast the extracted value.
2516       source = rewriter.create<ExtractStridedSliceOp>(
2517           op->getLoc(), source,
2518           getI64SubArray(op.offsets(), /* dropFront=*/rankDiff),
2519           getI64SubArray(op.sizes(), /* dropFront=*/rankDiff),
2520           getI64SubArray(op.strides(), /* dropFront=*/rankDiff));
2521     }
2522     rewriter.replaceOpWithNewOp<BroadcastOp>(op, op.getType(), source);
2523     return success();
2524   }
2525 };
2526 
2527 /// Pattern to rewrite an ExtractStridedSliceOp(SplatOp) to SplatOp.
2528 class StridedSliceSplat final : public OpRewritePattern<ExtractStridedSliceOp> {
2529 public:
2530   using OpRewritePattern<ExtractStridedSliceOp>::OpRewritePattern;
2531 
2532   LogicalResult matchAndRewrite(ExtractStridedSliceOp op,
2533                                 PatternRewriter &rewriter) const override {
2534     auto splat = op.vector().getDefiningOp<SplatOp>();
2535     if (!splat)
2536       return failure();
2537     rewriter.replaceOpWithNewOp<SplatOp>(op, op.getType(), splat.input());
2538     return success();
2539   }
2540 };
2541 
2542 } // namespace
2543 
2544 void ExtractStridedSliceOp::getCanonicalizationPatterns(
2545     RewritePatternSet &results, MLIRContext *context) {
2546   // Pattern to rewrite a ExtractStridedSliceOp(ConstantMaskOp) ->
2547   // ConstantMaskOp and ExtractStridedSliceOp(ConstantOp) -> ConstantOp.
2548   results.add<StridedSliceConstantMaskFolder, StridedSliceConstantFolder,
2549               StridedSliceBroadcast, StridedSliceSplat>(context);
2550 }
2551 
2552 //===----------------------------------------------------------------------===//
2553 // TransferReadOp
2554 //===----------------------------------------------------------------------===//
2555 
2556 /// 1. Builder that sets padding to zero and an empty mask (variant with attrs).
2557 void TransferReadOp::build(OpBuilder &builder, OperationState &result,
2558                            VectorType vectorType, Value source,
2559                            ValueRange indices, AffineMapAttr permutationMapAttr,
2560                            /*optional*/ ArrayAttr inBoundsAttr) {
2561   Type elemType = source.getType().cast<ShapedType>().getElementType();
2562   Value padding = builder.create<arith::ConstantOp>(
2563       result.location, elemType, builder.getZeroAttr(elemType));
2564   build(builder, result, vectorType, source, indices, permutationMapAttr,
2565         padding, /*mask=*/Value(), inBoundsAttr);
2566 }
2567 
2568 /// 2. Builder that sets padding to zero an empty mask (variant without attrs).
2569 void TransferReadOp::build(OpBuilder &builder, OperationState &result,
2570                            VectorType vectorType, Value source,
2571                            ValueRange indices, AffineMap permutationMap,
2572                            Optional<ArrayRef<bool>> inBounds) {
2573   auto permutationMapAttr = AffineMapAttr::get(permutationMap);
2574   auto inBoundsAttr = (inBounds && !inBounds.getValue().empty())
2575                           ? builder.getBoolArrayAttr(inBounds.getValue())
2576                           : ArrayAttr();
2577   build(builder, result, vectorType, source, indices, permutationMapAttr,
2578         inBoundsAttr);
2579 }
2580 
2581 /// 3. Builder that sets permutation map to 'getMinorIdentityMap'.
2582 void TransferReadOp::build(OpBuilder &builder, OperationState &result,
2583                            VectorType vectorType, Value source,
2584                            ValueRange indices, Value padding,
2585                            Optional<ArrayRef<bool>> inBounds) {
2586   AffineMap permutationMap = getTransferMinorIdentityMap(
2587       source.getType().cast<ShapedType>(), vectorType);
2588   auto permutationMapAttr = AffineMapAttr::get(permutationMap);
2589   auto inBoundsAttr = (inBounds && !inBounds.getValue().empty())
2590                           ? builder.getBoolArrayAttr(inBounds.getValue())
2591                           : ArrayAttr();
2592   build(builder, result, vectorType, source, indices, permutationMapAttr,
2593         padding,
2594         /*mask=*/Value(), inBoundsAttr);
2595 }
2596 
2597 /// 4. Builder that sets padding to zero and permutation map to
2598 /// 'getMinorIdentityMap'.
2599 void TransferReadOp::build(OpBuilder &builder, OperationState &result,
2600                            VectorType vectorType, Value source,
2601                            ValueRange indices,
2602                            Optional<ArrayRef<bool>> inBounds) {
2603   Type elemType = source.getType().cast<ShapedType>().getElementType();
2604   Value padding = builder.create<arith::ConstantOp>(
2605       result.location, elemType, builder.getZeroAttr(elemType));
2606   build(builder, result, vectorType, source, indices, padding, inBounds);
2607 }
2608 
2609 template <typename EmitFun>
2610 static LogicalResult verifyPermutationMap(AffineMap permutationMap,
2611                                           EmitFun emitOpError) {
2612   SmallVector<bool, 8> seen(permutationMap.getNumInputs(), false);
2613   for (auto expr : permutationMap.getResults()) {
2614     auto dim = expr.dyn_cast<AffineDimExpr>();
2615     auto zero = expr.dyn_cast<AffineConstantExpr>();
2616     if (zero) {
2617       if (zero.getValue() != 0) {
2618         return emitOpError(
2619             "requires a projected permutation_map (at most one dim or the zero "
2620             "constant can appear in each result)");
2621       }
2622       continue;
2623     }
2624     if (!dim) {
2625       return emitOpError("requires a projected permutation_map (at most one "
2626                          "dim or the zero constant can appear in each result)");
2627     }
2628     if (seen[dim.getPosition()]) {
2629       return emitOpError(
2630           "requires a permutation_map that is a permutation (found one dim "
2631           "used more than once)");
2632     }
2633     seen[dim.getPosition()] = true;
2634   }
2635   return success();
2636 }
2637 
2638 static LogicalResult
2639 verifyTransferOp(VectorTransferOpInterface op, ShapedType shapedType,
2640                  VectorType vectorType, VectorType maskType,
2641                  AffineMap permutationMap, ArrayAttr inBounds) {
2642   if (op->hasAttr("masked")) {
2643     return op->emitOpError("masked attribute has been removed. "
2644                            "Use in_bounds instead.");
2645   }
2646 
2647   if (!shapedType.isa<MemRefType, RankedTensorType>())
2648     return op->emitOpError(
2649         "requires source to be a memref or ranked tensor type");
2650 
2651   auto elementType = shapedType.getElementType();
2652   DataLayout dataLayout = DataLayout::closest(op);
2653   if (auto vectorElementType = elementType.dyn_cast<VectorType>()) {
2654     // Memref or tensor has vector element type.
2655     unsigned sourceVecSize =
2656         dataLayout.getTypeSizeInBits(vectorElementType.getElementType()) *
2657         vectorElementType.getShape().back();
2658     unsigned resultVecSize =
2659         dataLayout.getTypeSizeInBits(vectorType.getElementType()) *
2660         vectorType.getShape().back();
2661     if (resultVecSize % sourceVecSize != 0)
2662       return op->emitOpError(
2663           "requires the bitwidth of the minor 1-D vector to be an integral "
2664           "multiple of the bitwidth of the minor 1-D vector of the source");
2665 
2666     unsigned sourceVecEltRank = vectorElementType.getRank();
2667     unsigned resultVecRank = vectorType.getRank();
2668     if (sourceVecEltRank > resultVecRank)
2669       return op->emitOpError(
2670           "requires source vector element and vector result ranks to match.");
2671     unsigned rankOffset = resultVecRank - sourceVecEltRank;
2672     // Check that permutation map results match 'rankOffset' of vector type.
2673     if (permutationMap.getNumResults() != rankOffset)
2674       return op->emitOpError("requires a permutation_map with result dims of "
2675                              "the same rank as the vector type");
2676 
2677     if (maskType)
2678       return op->emitOpError("does not support masks with vector element type");
2679   } else {
2680     // Memref or tensor has scalar element type.
2681     unsigned minorSize =
2682         vectorType.getRank() == 0 ? 1 : vectorType.getShape().back();
2683     unsigned resultVecSize =
2684         dataLayout.getTypeSizeInBits(vectorType.getElementType()) * minorSize;
2685     if (resultVecSize % dataLayout.getTypeSizeInBits(elementType) != 0)
2686       return op->emitOpError(
2687           "requires the bitwidth of the minor 1-D vector to be an integral "
2688           "multiple of the bitwidth of the source element type");
2689 
2690     // Check that permutation map results match rank of vector type.
2691     if (permutationMap.getNumResults() != vectorType.getRank())
2692       return op->emitOpError("requires a permutation_map with result dims of "
2693                              "the same rank as the vector type");
2694 
2695     VectorType expectedMaskType =
2696         vector::detail::transferMaskType(vectorType, permutationMap);
2697     if (maskType && expectedMaskType != maskType)
2698       return op->emitOpError("expects mask type consistent with permutation "
2699                              "map: ")
2700              << maskType;
2701   }
2702 
2703   if (permutationMap.getNumSymbols() != 0)
2704     return op->emitOpError("requires permutation_map without symbols");
2705 
2706   if (permutationMap.getNumInputs() != shapedType.getRank())
2707     return op->emitOpError("requires a permutation_map with input dims of the "
2708                            "same rank as the source type");
2709 
2710   if (inBounds) {
2711     if (permutationMap.getNumResults() != static_cast<int64_t>(inBounds.size()))
2712       return op->emitOpError("expects the optional in_bounds attr of same rank "
2713                              "as permutation_map results: ")
2714              << AffineMapAttr::get(permutationMap)
2715              << " vs inBounds of size: " << inBounds.size();
2716     for (unsigned int i = 0; i < permutationMap.getNumResults(); ++i)
2717       if (permutationMap.getResult(i).isa<AffineConstantExpr>() &&
2718           !inBounds.getValue()[i].cast<BoolAttr>().getValue())
2719         return op->emitOpError("requires broadcast dimensions to be in-bounds");
2720   }
2721 
2722   return success();
2723 }
2724 
2725 static void printTransferAttrs(OpAsmPrinter &p, VectorTransferOpInterface op) {
2726   SmallVector<StringRef, 3> elidedAttrs;
2727   elidedAttrs.push_back(TransferReadOp::getOperandSegmentSizeAttr());
2728   if (op.permutation_map().isMinorIdentity())
2729     elidedAttrs.push_back(op.getPermutationMapAttrStrName());
2730   bool elideInBounds = true;
2731   if (auto inBounds = op.in_bounds()) {
2732     for (auto attr : *inBounds) {
2733       if (attr.template cast<BoolAttr>().getValue()) {
2734         elideInBounds = false;
2735         break;
2736       }
2737     }
2738   }
2739   if (elideInBounds)
2740     elidedAttrs.push_back(op.getInBoundsAttrStrName());
2741   p.printOptionalAttrDict(op->getAttrs(), elidedAttrs);
2742 }
2743 
2744 void TransferReadOp::print(OpAsmPrinter &p) {
2745   p << " " << source() << "[" << indices() << "], " << padding();
2746   if (mask())
2747     p << ", " << mask();
2748   printTransferAttrs(p, *this);
2749   p << " : " << getShapedType() << ", " << getVectorType();
2750 }
2751 
2752 ParseResult TransferReadOp::parse(OpAsmParser &parser, OperationState &result) {
2753   auto &builder = parser.getBuilder();
2754   SMLoc typesLoc;
2755   OpAsmParser::OperandType sourceInfo;
2756   SmallVector<OpAsmParser::OperandType, 8> indexInfo;
2757   OpAsmParser::OperandType paddingInfo;
2758   SmallVector<Type, 2> types;
2759   OpAsmParser::OperandType maskInfo;
2760   // Parsing with support for paddingValue.
2761   if (parser.parseOperand(sourceInfo) ||
2762       parser.parseOperandList(indexInfo, OpAsmParser::Delimiter::Square) ||
2763       parser.parseComma() || parser.parseOperand(paddingInfo))
2764     return failure();
2765   ParseResult hasMask = parser.parseOptionalComma();
2766   if (hasMask.succeeded()) {
2767     parser.parseOperand(maskInfo);
2768   }
2769   if (parser.parseOptionalAttrDict(result.attributes) ||
2770       parser.getCurrentLocation(&typesLoc) || parser.parseColonTypeList(types))
2771     return failure();
2772   if (types.size() != 2)
2773     return parser.emitError(typesLoc, "requires two types");
2774   auto indexType = builder.getIndexType();
2775   auto shapedType = types[0].dyn_cast<ShapedType>();
2776   if (!shapedType || !shapedType.isa<MemRefType, RankedTensorType>())
2777     return parser.emitError(typesLoc, "requires memref or ranked tensor type");
2778   VectorType vectorType = types[1].dyn_cast<VectorType>();
2779   if (!vectorType)
2780     return parser.emitError(typesLoc, "requires vector type");
2781   auto permutationAttrName = TransferReadOp::getPermutationMapAttrStrName();
2782   Attribute mapAttr = result.attributes.get(permutationAttrName);
2783   if (!mapAttr) {
2784     auto permMap = getTransferMinorIdentityMap(shapedType, vectorType);
2785     // Update `mapAttr` that is used later to determine mask type.
2786     mapAttr = AffineMapAttr::get(permMap);
2787     result.attributes.set(permutationAttrName, mapAttr);
2788   }
2789   if (parser.resolveOperand(sourceInfo, shapedType, result.operands) ||
2790       parser.resolveOperands(indexInfo, indexType, result.operands) ||
2791       parser.resolveOperand(paddingInfo, shapedType.getElementType(),
2792                             result.operands))
2793     return failure();
2794   if (hasMask.succeeded()) {
2795     if (shapedType.getElementType().dyn_cast<VectorType>())
2796       return parser.emitError(
2797           maskInfo.location, "does not support masks with vector element type");
2798     auto map = mapAttr.dyn_cast<AffineMapAttr>().getValue();
2799     // Instead of adding the mask type as an op type, compute it based on the
2800     // vector type and the permutation map (to keep the type signature small).
2801     auto maskType = mlir::vector::detail::transferMaskType(vectorType, map);
2802     if (parser.resolveOperand(maskInfo, maskType, result.operands))
2803       return failure();
2804   }
2805   result.addAttribute(
2806       TransferReadOp::getOperandSegmentSizeAttr(),
2807       builder.getI32VectorAttr({1, static_cast<int32_t>(indexInfo.size()), 1,
2808                                 static_cast<int32_t>(hasMask.succeeded())}));
2809   return parser.addTypeToList(vectorType, result.types);
2810 }
2811 
2812 LogicalResult TransferReadOp::verify() {
2813   // Consistency of elemental types in source and vector.
2814   ShapedType shapedType = getShapedType();
2815   VectorType vectorType = getVectorType();
2816   VectorType maskType = getMaskType();
2817   auto paddingType = padding().getType();
2818   auto permutationMap = permutation_map();
2819   auto sourceElementType = shapedType.getElementType();
2820 
2821   if (static_cast<int64_t>(indices().size()) != shapedType.getRank())
2822     return emitOpError("requires ") << shapedType.getRank() << " indices";
2823 
2824   if (failed(verifyTransferOp(cast<VectorTransferOpInterface>(getOperation()),
2825                               shapedType, vectorType, maskType, permutationMap,
2826                               in_bounds() ? *in_bounds() : ArrayAttr())))
2827     return failure();
2828 
2829   if (auto sourceVectorElementType = sourceElementType.dyn_cast<VectorType>()) {
2830     // Source has vector element type.
2831     // Check that 'sourceVectorElementType' and 'paddingType' types match.
2832     if (sourceVectorElementType != paddingType)
2833       return emitOpError(
2834           "requires source element type and padding type to match.");
2835 
2836   } else {
2837     // Check that 'paddingType' is valid to store in a vector type.
2838     if (!VectorType::isValidElementType(paddingType))
2839       return emitOpError("requires valid padding vector elemental type");
2840 
2841     // Check that padding type and vector element types match.
2842     if (paddingType != sourceElementType)
2843       return emitOpError(
2844           "requires formal padding and source of the same elemental type");
2845   }
2846 
2847   return verifyPermutationMap(permutationMap,
2848                               [&](Twine t) { return emitOpError(t); });
2849 }
2850 
2851 /// This is a common class used for patterns of the form
2852 /// ```
2853 ///    someop(memrefcast) -> someop
2854 /// ```
2855 /// It folds the source of the memref.cast into the root operation directly.
2856 static LogicalResult foldMemRefCast(Operation *op) {
2857   bool folded = false;
2858   for (OpOperand &operand : op->getOpOperands()) {
2859     auto castOp = operand.get().getDefiningOp<memref::CastOp>();
2860     if (castOp && memref::CastOp::canFoldIntoConsumerOp(castOp)) {
2861       operand.set(castOp.getOperand());
2862       folded = true;
2863     }
2864   }
2865   return success(folded);
2866 }
2867 
2868 static LogicalResult foldTensorCast(Operation *op) {
2869   bool folded = false;
2870   for (OpOperand &operand : op->getOpOperands()) {
2871     auto castOp = operand.get().getDefiningOp<tensor::CastOp>();
2872     if (castOp && tensor::canFoldIntoConsumerOp(castOp)) {
2873       operand.set(castOp.getOperand());
2874       folded = true;
2875     }
2876   }
2877   return success(folded);
2878 }
2879 
2880 template <typename TransferOp>
2881 static bool isInBounds(TransferOp op, int64_t resultIdx, int64_t indicesIdx) {
2882   // TODO: support more aggressive createOrFold on:
2883   // `op.indices()[indicesIdx] + vectorType < dim(op.source(), indicesIdx)`
2884   if (op.getShapedType().isDynamicDim(indicesIdx))
2885     return false;
2886   Value index = op.indices()[indicesIdx];
2887   auto cstOp = index.getDefiningOp<arith::ConstantIndexOp>();
2888   if (!cstOp)
2889     return false;
2890 
2891   int64_t sourceSize = op.getShapedType().getDimSize(indicesIdx);
2892   int64_t vectorSize = op.getVectorType().getDimSize(resultIdx);
2893 
2894   return cstOp.value() + vectorSize <= sourceSize;
2895 }
2896 
2897 template <typename TransferOp>
2898 static LogicalResult foldTransferInBoundsAttribute(TransferOp op) {
2899   // TODO: support 0-d corner case.
2900   // TODO: Be less conservative.
2901   if (op.getTransferRank() == 0)
2902     return failure();
2903   AffineMap permutationMap = op.permutation_map();
2904   bool changed = false;
2905   SmallVector<bool, 4> newInBounds;
2906   newInBounds.reserve(op.getTransferRank());
2907   for (unsigned i = 0; i < op.getTransferRank(); ++i) {
2908     // Already marked as in-bounds, nothing to see here.
2909     if (op.isDimInBounds(i)) {
2910       newInBounds.push_back(true);
2911       continue;
2912     }
2913     // Currently out-of-bounds, check whether we can statically determine it is
2914     // inBounds.
2915     auto dimExpr = permutationMap.getResult(i).dyn_cast<AffineDimExpr>();
2916     assert(dimExpr && "Broadcast dims must be in-bounds");
2917     auto inBounds =
2918         isInBounds(op, /*resultIdx=*/i, /*indicesIdx=*/dimExpr.getPosition());
2919     newInBounds.push_back(inBounds);
2920     // We commit the pattern if it is "more inbounds".
2921     changed |= inBounds;
2922   }
2923   if (!changed)
2924     return failure();
2925   // OpBuilder is only used as a helper to build an I64ArrayAttr.
2926   OpBuilder b(op.getContext());
2927   op->setAttr(TransferOp::getInBoundsAttrStrName(),
2928               b.getBoolArrayAttr(newInBounds));
2929   return success();
2930 }
2931 
2932 ///  ```
2933 ///  %w0 = vector.transfer_write %v0, %arg0[%c1, %c0] {in_bounds = [true, true]}
2934 ///    : vector<1x4xf32>, tensor<4x4xf32>
2935 ///  %0 = vector.transfer_read %w0[%c1, %c0], %cf0 {in_bounds = [true, true]}
2936 ///    : tensor<4x4xf32>, vector<1x4xf32>
2937 ///  ```
2938 ///  -> Folds into
2939 ///  ```
2940 ///  %v0
2941 ///  ```
2942 static Value foldRAW(TransferReadOp readOp) {
2943   if (!readOp.getShapedType().isa<RankedTensorType>())
2944     return {};
2945   auto defWrite = readOp.source().getDefiningOp<vector::TransferWriteOp>();
2946   while (defWrite) {
2947     if (checkSameValueRAW(defWrite, readOp))
2948       return defWrite.vector();
2949     if (!isDisjointTransferIndices(
2950             cast<VectorTransferOpInterface>(defWrite.getOperation()),
2951             cast<VectorTransferOpInterface>(readOp.getOperation())))
2952       break;
2953     defWrite = defWrite.source().getDefiningOp<vector::TransferWriteOp>();
2954   }
2955   return {};
2956 }
2957 
2958 OpFoldResult TransferReadOp::fold(ArrayRef<Attribute>) {
2959   if (Value vec = foldRAW(*this))
2960     return vec;
2961   /// transfer_read(memrefcast) -> transfer_read
2962   if (succeeded(foldTransferInBoundsAttribute(*this)))
2963     return getResult();
2964   if (succeeded(foldMemRefCast(*this)))
2965     return getResult();
2966   if (succeeded(foldTensorCast(*this)))
2967     return getResult();
2968   return OpFoldResult();
2969 }
2970 
2971 Optional<SmallVector<int64_t, 4>> TransferReadOp::getShapeForUnroll() {
2972   return llvm::to_vector<4>(getVectorType().getShape());
2973 }
2974 
2975 void TransferReadOp::getEffects(
2976     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
2977         &effects) {
2978   if (getShapedType().isa<MemRefType>())
2979     effects.emplace_back(MemoryEffects::Read::get(), source(),
2980                          SideEffects::DefaultResource::get());
2981 }
2982 
2983 namespace {
2984 /// Fold transfer_reads of a tensor.extract_slice op. E.g.:
2985 ///
2986 /// ```
2987 /// %0 = tensor.extract_slice %t[%a, %b] [%c, %d] [1, 1]
2988 ///     : tensor<?x?xf32> to tensor<?x?xf32>
2989 /// %1 = vector.transfer_read %0[%e, %f], %cst {in_bounds = [true, true]}
2990 ///     : tensor<?x?xf32>, vector<4x5xf32>
2991 /// ```
2992 /// is rewritten to:
2993 /// ```
2994 /// %p0 = arith.addi %a, %e : index
2995 /// %p1 = arith.addi %b, %f : index
2996 /// %1 = vector.transfer_read %t[%p0, %p1], %cst {in_bounds = [true, true]}
2997 ///     : tensor<?x?xf32>, vector<4x5xf32>
2998 /// ```
2999 struct FoldExtractSliceIntoTransferRead
3000     : public OpRewritePattern<TransferReadOp> {
3001 public:
3002   using OpRewritePattern<TransferReadOp>::OpRewritePattern;
3003 
3004   LogicalResult matchAndRewrite(TransferReadOp xferOp,
3005                                 PatternRewriter &rewriter) const override {
3006     // TODO: support 0-d corner case.
3007     if (xferOp.getTransferRank() == 0)
3008       return failure();
3009     if (xferOp.hasOutOfBoundsDim())
3010       return failure();
3011     if (!xferOp.permutation_map().isIdentity())
3012       return failure();
3013     if (xferOp.mask())
3014       return failure();
3015     auto extractOp = xferOp.source().getDefiningOp<tensor::ExtractSliceOp>();
3016     if (!extractOp)
3017       return failure();
3018     if (!extractOp.hasUnitStride())
3019       return failure();
3020 
3021     // Bail on illegal rank-reduction: we need to check that the rank-reduced
3022     // dims are exactly the leading dims. I.e. the following is illegal:
3023     // ```
3024     //    %0 = tensor.extract_slice %t[0,0,0][2,1,4][1,1,1] :
3025     //      tensor<2x1x4xf32> to tensor<2x4xf32>
3026     //    %1 = vector.transfer_read %0[0,0], %cst :
3027     //      tensor<2x4xf32>, vector<2x4xf32>
3028     // ```
3029     //
3030     // Cannot fold into:
3031     // ```
3032     //    %0 = vector.transfer_read %t[0,0,0], %cst :
3033     //      tensor<2x1x4xf32>, vector<2x4xf32>
3034     // ```
3035     // For this, check the trailing `vectorRank` dims of the extract_slice
3036     // result tensor match the trailing dims of the inferred result tensor.
3037     int64_t rankReduced =
3038         extractOp.getSourceType().getRank() - extractOp.getType().getRank();
3039     int64_t vectorRank = xferOp.getVectorType().getRank();
3040     RankedTensorType inferredDestTensorType =
3041         tensor::ExtractSliceOp::inferResultType(
3042             extractOp.getSourceType(), extractOp.getMixedOffsets(),
3043             extractOp.getMixedSizes(), extractOp.getMixedStrides());
3044     auto actualDestTensorShape = extractOp.getType().getShape();
3045     if (rankReduced > 0 &&
3046         actualDestTensorShape.take_back(vectorRank) !=
3047             inferredDestTensorType.getShape().take_back(vectorRank))
3048       return failure();
3049 
3050     SmallVector<Value> newIndices;
3051     // In case this is a rank-reducing ExtractSliceOp, copy rank-reduced
3052     // indices first.
3053     for (int64_t i = 0; i < rankReduced; ++i) {
3054       OpFoldResult offset = extractOp.getMixedOffsets()[i];
3055       newIndices.push_back(getValueOrCreateConstantIndexOp(
3056           rewriter, extractOp.getLoc(), offset));
3057     }
3058     for (const auto &it : llvm::enumerate(xferOp.indices())) {
3059       OpFoldResult offset =
3060           extractOp.getMixedOffsets()[it.index() + rankReduced];
3061       newIndices.push_back(rewriter.create<arith::AddIOp>(
3062           xferOp->getLoc(), it.value(),
3063           getValueOrCreateConstantIndexOp(rewriter, extractOp.getLoc(),
3064                                           offset)));
3065     }
3066     SmallVector<bool> inBounds(xferOp.getTransferRank(), true);
3067     rewriter.replaceOpWithNewOp<TransferReadOp>(
3068         xferOp, xferOp.getVectorType(), extractOp.source(), newIndices,
3069         xferOp.padding(), ArrayRef<bool>{inBounds});
3070 
3071     return success();
3072   }
3073 };
3074 } // namespace
3075 
3076 void TransferReadOp::getCanonicalizationPatterns(RewritePatternSet &results,
3077                                                  MLIRContext *context) {
3078   results.add<FoldExtractSliceIntoTransferRead>(context);
3079 }
3080 
3081 //===----------------------------------------------------------------------===//
3082 // TransferWriteOp
3083 //===----------------------------------------------------------------------===//
3084 
3085 /// 1. Builder with type inference.
3086 void TransferWriteOp::build(OpBuilder &builder, OperationState &result,
3087                             Value vector, Value dest, ValueRange indices,
3088                             AffineMapAttr permutationMapAttr,
3089                             /*optional*/ Value mask,
3090                             /*optional*/ ArrayAttr inBoundsAttr) {
3091   Type resultType = dest.getType().dyn_cast<RankedTensorType>();
3092   build(builder, result, resultType, vector, dest, indices, permutationMapAttr,
3093         mask, inBoundsAttr);
3094 }
3095 
3096 /// 2. Builder with type inference that sets an empty mask (variant with attrs).
3097 void TransferWriteOp::build(OpBuilder &builder, OperationState &result,
3098                             Value vector, Value dest, ValueRange indices,
3099                             AffineMapAttr permutationMapAttr,
3100                             /*optional*/ ArrayAttr inBoundsAttr) {
3101   build(builder, result, vector, dest, indices, permutationMapAttr,
3102         /*mask=*/Value(), inBoundsAttr);
3103 }
3104 
3105 /// 3. Builder with type inference that sets an empty mask (variant without
3106 /// attrs)
3107 void TransferWriteOp::build(OpBuilder &builder, OperationState &result,
3108                             Value vector, Value dest, ValueRange indices,
3109                             AffineMap permutationMap,
3110                             Optional<ArrayRef<bool>> inBounds) {
3111   auto permutationMapAttr = AffineMapAttr::get(permutationMap);
3112   auto inBoundsAttr = (inBounds && !inBounds.getValue().empty())
3113                           ? builder.getBoolArrayAttr(inBounds.getValue())
3114                           : ArrayAttr();
3115   build(builder, result, vector, dest, indices, permutationMapAttr,
3116         /*mask=*/Value(), inBoundsAttr);
3117 }
3118 
3119 /// 4. Builder with type inference that sets an empty mask and sets permutation
3120 ///    map to 'getMinorIdentityMap'.
3121 void TransferWriteOp::build(OpBuilder &builder, OperationState &result,
3122                             Value vector, Value dest, ValueRange indices,
3123                             Optional<ArrayRef<bool>> inBounds) {
3124   auto vectorType = vector.getType().cast<VectorType>();
3125   AffineMap permutationMap = getTransferMinorIdentityMap(
3126       dest.getType().cast<ShapedType>(), vectorType);
3127   build(builder, result, vector, dest, indices, permutationMap, inBounds);
3128 }
3129 
3130 ParseResult TransferWriteOp::parse(OpAsmParser &parser,
3131                                    OperationState &result) {
3132   auto &builder = parser.getBuilder();
3133   SMLoc typesLoc;
3134   OpAsmParser::OperandType vectorInfo, sourceInfo;
3135   SmallVector<OpAsmParser::OperandType, 8> indexInfo;
3136   SmallVector<Type, 2> types;
3137   OpAsmParser::OperandType maskInfo;
3138   if (parser.parseOperand(vectorInfo) || parser.parseComma() ||
3139       parser.parseOperand(sourceInfo) ||
3140       parser.parseOperandList(indexInfo, OpAsmParser::Delimiter::Square))
3141     return failure();
3142   ParseResult hasMask = parser.parseOptionalComma();
3143   if (hasMask.succeeded() && parser.parseOperand(maskInfo))
3144     return failure();
3145   if (parser.parseOptionalAttrDict(result.attributes) ||
3146       parser.getCurrentLocation(&typesLoc) || parser.parseColonTypeList(types))
3147     return failure();
3148   if (types.size() != 2)
3149     return parser.emitError(typesLoc, "requires two types");
3150   auto indexType = builder.getIndexType();
3151   VectorType vectorType = types[0].dyn_cast<VectorType>();
3152   if (!vectorType)
3153     return parser.emitError(typesLoc, "requires vector type");
3154   ShapedType shapedType = types[1].dyn_cast<ShapedType>();
3155   if (!shapedType || !shapedType.isa<MemRefType, RankedTensorType>())
3156     return parser.emitError(typesLoc, "requires memref or ranked tensor type");
3157   auto permutationAttrName = TransferWriteOp::getPermutationMapAttrStrName();
3158   auto attr = result.attributes.get(permutationAttrName);
3159   if (!attr) {
3160     auto permMap = getTransferMinorIdentityMap(shapedType, vectorType);
3161     result.attributes.set(permutationAttrName, AffineMapAttr::get(permMap));
3162   }
3163   if (parser.resolveOperand(vectorInfo, vectorType, result.operands) ||
3164       parser.resolveOperand(sourceInfo, shapedType, result.operands) ||
3165       parser.resolveOperands(indexInfo, indexType, result.operands))
3166     return failure();
3167   if (hasMask.succeeded()) {
3168     if (shapedType.getElementType().dyn_cast<VectorType>())
3169       return parser.emitError(
3170           maskInfo.location, "does not support masks with vector element type");
3171     auto maskType = VectorType::get(vectorType.getShape(), builder.getI1Type());
3172     if (parser.resolveOperand(maskInfo, maskType, result.operands))
3173       return failure();
3174   }
3175   result.addAttribute(
3176       TransferWriteOp::getOperandSegmentSizeAttr(),
3177       builder.getI32VectorAttr({1, 1, static_cast<int32_t>(indexInfo.size()),
3178                                 static_cast<int32_t>(hasMask.succeeded())}));
3179   return failure(shapedType.isa<RankedTensorType>() &&
3180                  parser.addTypeToList(shapedType, result.types));
3181 }
3182 
3183 void TransferWriteOp::print(OpAsmPrinter &p) {
3184   p << " " << vector() << ", " << source() << "[" << indices() << "]";
3185   if (mask())
3186     p << ", " << mask();
3187   printTransferAttrs(p, *this);
3188   p << " : " << getVectorType() << ", " << getShapedType();
3189 }
3190 
3191 LogicalResult TransferWriteOp::verify() {
3192   // Consistency of elemental types in shape and vector.
3193   ShapedType shapedType = getShapedType();
3194   VectorType vectorType = getVectorType();
3195   VectorType maskType = getMaskType();
3196   auto permutationMap = permutation_map();
3197 
3198   if (llvm::size(indices()) != shapedType.getRank())
3199     return emitOpError("requires ") << shapedType.getRank() << " indices";
3200 
3201   // We do not allow broadcast dimensions on TransferWriteOps for the moment,
3202   // as the semantics is unclear. This can be revisited later if necessary.
3203   if (hasBroadcastDim())
3204     return emitOpError("should not have broadcast dimensions");
3205 
3206   if (failed(verifyTransferOp(cast<VectorTransferOpInterface>(getOperation()),
3207                               shapedType, vectorType, maskType, permutationMap,
3208                               in_bounds() ? *in_bounds() : ArrayAttr())))
3209     return failure();
3210 
3211   return verifyPermutationMap(permutationMap,
3212                               [&](Twine t) { return emitOpError(t); });
3213 }
3214 
3215 /// Fold:
3216 /// ```
3217 ///    %t1 = ...
3218 ///    %v = vector.transfer_read %t0[%c0...], {in_bounds = [true...]} :
3219 ///      tensor<static_sizesxf32>, vector<static_sizesxf32>
3220 ///    %t2 = vector.transfer_write %v, %t1[%c0...] {in_bounds = [true...]} :
3221 ///      vector<static_sizesxf32>, tensor<static_sizesxf32>
3222 /// ```
3223 ///
3224 /// into:
3225 ///
3226 /// ```
3227 ///    %t0
3228 /// ```
3229 ///
3230 /// The producer of t1 may or may not be DCE'd depending on whether it is a
3231 /// block argument or has side effects.
3232 static LogicalResult foldReadInitWrite(TransferWriteOp write,
3233                                        ArrayRef<Attribute>,
3234                                        SmallVectorImpl<OpFoldResult> &results) {
3235   // TODO: support 0-d corner case.
3236   if (write.getTransferRank() == 0)
3237     return failure();
3238   auto rankedTensorType = write.source().getType().dyn_cast<RankedTensorType>();
3239   // If not operating on tensors, bail.
3240   if (!rankedTensorType)
3241     return failure();
3242   // If no read, bail.
3243   auto read = write.vector().getDefiningOp<vector::TransferReadOp>();
3244   if (!read)
3245     return failure();
3246   // TODO: support 0-d corner case.
3247   if (read.getTransferRank() == 0)
3248     return failure();
3249   // For now, only accept minor identity. Future: composition is minor identity.
3250   if (!read.permutation_map().isMinorIdentity() ||
3251       !write.permutation_map().isMinorIdentity())
3252     return failure();
3253   // Bail on mismatching ranks.
3254   if (read.getTransferRank() != write.getTransferRank())
3255     return failure();
3256   // Bail on potential out-of-bounds accesses.
3257   if (read.hasOutOfBoundsDim() || write.hasOutOfBoundsDim())
3258     return failure();
3259   // Tensor types must be the same.
3260   if (read.source().getType() != rankedTensorType)
3261     return failure();
3262   // Vector types must be the same.
3263   if (read.getVectorType() != write.getVectorType())
3264     return failure();
3265   // Vector and Tensor shapes must match.
3266   if (read.getVectorType().getShape() != rankedTensorType.getShape())
3267     return failure();
3268   // If any index is nonzero.
3269   auto isNotConstantZero = [](Value v) {
3270     auto cstOp = v.getDefiningOp<arith::ConstantIndexOp>();
3271     return !cstOp || cstOp.value() != 0;
3272   };
3273   if (llvm::any_of(read.indices(), isNotConstantZero) ||
3274       llvm::any_of(write.indices(), isNotConstantZero))
3275     return failure();
3276   // Success.
3277   results.push_back(read.source());
3278   return success();
3279 }
3280 
3281 static bool checkSameValueWAR(vector::TransferReadOp read,
3282                               vector::TransferWriteOp write) {
3283   return read.source() == write.source() && read.indices() == write.indices() &&
3284          read.permutation_map() == write.permutation_map() &&
3285          read.getVectorType() == write.getVectorType() && !read.mask() &&
3286          !write.mask();
3287 }
3288 /// Fold transfer_write write after read:
3289 /// ```
3290 ///    %t0 = ...
3291 ///    %v = vector.transfer_read %t0[%c0...] :
3292 ///      tensor<static_sizesxf32>, vector<static_sizesxf32>
3293 ///    %t1 = vector.transfer_write %v, %t0[%c0...] :
3294 ///      vector<static_sizesxf32>, tensor<static_sizesxf32>
3295 /// ```
3296 ///
3297 /// into:
3298 ///
3299 /// ```
3300 ///    %t0
3301 /// ```
3302 static LogicalResult foldWAR(TransferWriteOp write,
3303                              SmallVectorImpl<OpFoldResult> &results) {
3304   if (!write.source().getType().isa<RankedTensorType>())
3305     return failure();
3306   auto read = write.vector().getDefiningOp<vector::TransferReadOp>();
3307   if (!read)
3308     return failure();
3309 
3310   if (!checkSameValueWAR(read, write))
3311     return failure();
3312   results.push_back(read.source());
3313   return success();
3314 }
3315 
3316 LogicalResult TransferWriteOp::fold(ArrayRef<Attribute> operands,
3317                                     SmallVectorImpl<OpFoldResult> &results) {
3318   if (succeeded(foldReadInitWrite(*this, operands, results)))
3319     return success();
3320   if (succeeded(foldWAR(*this, results)))
3321     return success();
3322   if (succeeded(foldTransferInBoundsAttribute(*this)))
3323     return success();
3324   return foldMemRefCast(*this);
3325 }
3326 
3327 Optional<SmallVector<int64_t, 4>> TransferWriteOp::getShapeForUnroll() {
3328   return llvm::to_vector<4>(getVectorType().getShape());
3329 }
3330 
3331 void TransferWriteOp::getEffects(
3332     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
3333         &effects) {
3334   if (getShapedType().isa<MemRefType>())
3335     effects.emplace_back(MemoryEffects::Write::get(), source(),
3336                          SideEffects::DefaultResource::get());
3337 }
3338 
3339 namespace {
3340 /// Remove dead transfer write from the SSA chain so that it an be eliminated by
3341 /// DCE
3342 /// ```
3343 ///  %w0 = vector.transfer_write %v0, %arg0[%c1, %c0] {in_bounds = [true, true]}
3344 ///    : vector<1x4xf32>, tensor<4x4xf32>
3345 ///  %w1 = vector.transfer_write %v0, %w0[%c2, %c0] {in_bounds = [true, true]}
3346 ///    : vector<1x4xf32>, tensor<4x4xf32>
3347 ///  %w2 = vector.transfer_write %v1, %w1[%c1, %c0] {in_bounds = [true, true]}
3348 ///    : vector<1x4xf32>, tensor<4x4xf32>
3349 /// ```
3350 ///
3351 /// into:
3352 ///
3353 /// ```
3354 ///  %w0 = vector.transfer_write %v0, %arg0[%c1, %c0] {in_bounds = [true, true]}
3355 ///    : vector<1x4xf32>, tensor<4x4xf32>
3356 ///  %w1 = vector.transfer_write %v0, %arg0[%c2, %c0] {in_bounds = [true, true]}
3357 ///    : vector<1x4xf32>, tensor<4x4xf32>
3358 ///  %w2 = vector.transfer_write %v1, %w1[%c1, %c0] {in_bounds = [true, true]}
3359 ///    : vector<1x4xf32>, tensor<4x4xf32>
3360 /// ```
3361 ///
3362 /// `%w0 = vector.transfer_write` op will be removed by DCE if it doesn't have
3363 /// any other uses.
3364 class FoldWaw final : public OpRewritePattern<TransferWriteOp> {
3365 public:
3366   using OpRewritePattern<TransferWriteOp>::OpRewritePattern;
3367   LogicalResult matchAndRewrite(TransferWriteOp writeOp,
3368                                 PatternRewriter &rewriter) const override {
3369     if (!writeOp.getShapedType().isa<RankedTensorType>())
3370       return failure();
3371     vector::TransferWriteOp writeToModify = writeOp;
3372 
3373     auto defWrite = writeOp.source().getDefiningOp<vector::TransferWriteOp>();
3374     while (defWrite) {
3375       if (checkSameValueWAW(writeOp, defWrite)) {
3376         writeToModify.sourceMutable().assign(defWrite.source());
3377         return success();
3378       }
3379       if (!isDisjointTransferIndices(
3380               cast<VectorTransferOpInterface>(defWrite.getOperation()),
3381               cast<VectorTransferOpInterface>(writeOp.getOperation())))
3382         break;
3383       // If the previous write op doesn't have any other use we an safely look
3384       // at the previous store to see if it can be removed.
3385       if (!defWrite->hasOneUse())
3386         break;
3387       writeToModify = defWrite;
3388       defWrite = defWrite.source().getDefiningOp<vector::TransferWriteOp>();
3389     }
3390     return failure();
3391   }
3392 };
3393 
3394 /// Fold tensor.insert_slice into vector.transfer_write if the transfer_write
3395 /// could directly write to the insert_slice's destination. E.g.:
3396 ///
3397 /// ```
3398 /// %0 = vector.transfer_write %v, %t1[%c0, %c0] {in_bounds = [true, true]}
3399 ///     : vector<4x5xf32>, tensor<4x5xf32>
3400 /// %1 = tensor.insert_slice %0 into %t2[%a, %b] [4, 5] [1, 1]
3401 ///     : tensor<4x5xf32> into tensor<?x?xf32>
3402 /// ```
3403 /// is rewritten to:
3404 /// ```
3405 /// %1 = vector.transfer_write %v, %t2[%a, %b] {in_bounds = [true, true]}
3406 ///     : vector<4x5xf32>, tensor<?x?xf32>
3407 /// ```
3408 struct FoldInsertSliceIntoTransferWrite
3409     : public OpRewritePattern<tensor::InsertSliceOp> {
3410 public:
3411   using OpRewritePattern<tensor::InsertSliceOp>::OpRewritePattern;
3412 
3413   LogicalResult matchAndRewrite(tensor::InsertSliceOp insertOp,
3414                                 PatternRewriter &rewriter) const override {
3415     if (!insertOp.hasUnitStride())
3416       return failure();
3417 
3418     auto xferOp = insertOp.source().getDefiningOp<TransferWriteOp>();
3419     if (!xferOp)
3420       return failure();
3421     // TODO: support 0-d corner case.
3422     if (xferOp.getTransferRank() == 0)
3423       return failure();
3424 
3425     if (xferOp.hasOutOfBoundsDim())
3426       return failure();
3427     if (xferOp.getVectorType().getRank() != xferOp.getShapedType().getRank())
3428       return failure();
3429     if (xferOp.mask())
3430       return failure();
3431     // Fold only if the TransferWriteOp completely overwrites the `source` with
3432     // a vector. I.e., the result of the TransferWriteOp is a new tensor whose
3433     // content is the data of the vector.
3434     if (!llvm::equal(xferOp.getVectorType().getShape(),
3435                      xferOp.getShapedType().getShape()))
3436       return failure();
3437     if (!xferOp.permutation_map().isIdentity())
3438       return failure();
3439 
3440     // Bail on illegal rank-reduction: we need to check that the rank-reduced
3441     // dims are exactly the leading dims. I.e. the following is illegal:
3442     // ```
3443     //    %0 = vector.transfer_write %v, %t[0,0], %cst :
3444     //      vector<2x4xf32>, tensor<2x4xf32>
3445     //    %1 = tensor.insert_slice %0 into %tt[0,0,0][2,1,4][1,1,1] :
3446     //      tensor<2x4xf32> into tensor<2x1x4xf32>
3447     // ```
3448     //
3449     // Cannot fold into:
3450     // ```
3451     //    %0 = vector.transfer_write %v, %t[0,0,0], %cst :
3452     //      vector<2x4xf32>, tensor<2x1x4xf32>
3453     // ```
3454     // For this, check the trailing `vectorRank` dims of the insert_slice result
3455     // tensor match the trailing dims of the inferred result tensor.
3456     int64_t rankReduced =
3457         insertOp.getType().getRank() - insertOp.getSourceType().getRank();
3458     int64_t vectorRank = xferOp.getVectorType().getRank();
3459     RankedTensorType inferredSourceTensorType =
3460         tensor::ExtractSliceOp::inferResultType(
3461             insertOp.getType(), insertOp.getMixedOffsets(),
3462             insertOp.getMixedSizes(), insertOp.getMixedStrides());
3463     auto actualSourceTensorShape = insertOp.getSourceType().getShape();
3464     if (rankReduced > 0 &&
3465         actualSourceTensorShape.take_back(vectorRank) !=
3466             inferredSourceTensorType.getShape().take_back(vectorRank))
3467       return failure();
3468 
3469     SmallVector<Value> indices = getValueOrCreateConstantIndexOp(
3470         rewriter, insertOp.getLoc(), insertOp.getMixedOffsets());
3471     SmallVector<bool> inBounds(xferOp.getTransferRank(), true);
3472     rewriter.replaceOpWithNewOp<TransferWriteOp>(insertOp, xferOp.vector(),
3473                                                  insertOp.dest(), indices,
3474                                                  ArrayRef<bool>{inBounds});
3475     return success();
3476   }
3477 };
3478 } // namespace
3479 
3480 void TransferWriteOp::getCanonicalizationPatterns(RewritePatternSet &results,
3481                                                   MLIRContext *context) {
3482   results.add<FoldWaw, FoldInsertSliceIntoTransferWrite>(context);
3483 }
3484 
3485 //===----------------------------------------------------------------------===//
3486 // LoadOp
3487 //===----------------------------------------------------------------------===//
3488 
3489 static LogicalResult verifyLoadStoreMemRefLayout(Operation *op,
3490                                                  MemRefType memRefTy) {
3491   if (!isLastMemrefDimUnitStride(memRefTy))
3492     return op->emitOpError("most minor memref dim must have unit stride");
3493   return success();
3494 }
3495 
3496 LogicalResult vector::LoadOp::verify() {
3497   VectorType resVecTy = getVectorType();
3498   MemRefType memRefTy = getMemRefType();
3499 
3500   if (failed(verifyLoadStoreMemRefLayout(*this, memRefTy)))
3501     return failure();
3502 
3503   // Checks for vector memrefs.
3504   Type memElemTy = memRefTy.getElementType();
3505   if (auto memVecTy = memElemTy.dyn_cast<VectorType>()) {
3506     if (memVecTy != resVecTy)
3507       return emitOpError("base memref and result vector types should match");
3508     memElemTy = memVecTy.getElementType();
3509   }
3510 
3511   if (resVecTy.getElementType() != memElemTy)
3512     return emitOpError("base and result element types should match");
3513   if (llvm::size(indices()) != memRefTy.getRank())
3514     return emitOpError("requires ") << memRefTy.getRank() << " indices";
3515   return success();
3516 }
3517 
3518 OpFoldResult LoadOp::fold(ArrayRef<Attribute>) {
3519   if (succeeded(foldMemRefCast(*this)))
3520     return getResult();
3521   return OpFoldResult();
3522 }
3523 
3524 //===----------------------------------------------------------------------===//
3525 // StoreOp
3526 //===----------------------------------------------------------------------===//
3527 
3528 LogicalResult vector::StoreOp::verify() {
3529   VectorType valueVecTy = getVectorType();
3530   MemRefType memRefTy = getMemRefType();
3531 
3532   if (failed(verifyLoadStoreMemRefLayout(*this, memRefTy)))
3533     return failure();
3534 
3535   // Checks for vector memrefs.
3536   Type memElemTy = memRefTy.getElementType();
3537   if (auto memVecTy = memElemTy.dyn_cast<VectorType>()) {
3538     if (memVecTy != valueVecTy)
3539       return emitOpError(
3540           "base memref and valueToStore vector types should match");
3541     memElemTy = memVecTy.getElementType();
3542   }
3543 
3544   if (valueVecTy.getElementType() != memElemTy)
3545     return emitOpError("base and valueToStore element type should match");
3546   if (llvm::size(indices()) != memRefTy.getRank())
3547     return emitOpError("requires ") << memRefTy.getRank() << " indices";
3548   return success();
3549 }
3550 
3551 LogicalResult StoreOp::fold(ArrayRef<Attribute> operands,
3552                             SmallVectorImpl<OpFoldResult> &results) {
3553   return foldMemRefCast(*this);
3554 }
3555 
3556 //===----------------------------------------------------------------------===//
3557 // MaskedLoadOp
3558 //===----------------------------------------------------------------------===//
3559 
3560 LogicalResult MaskedLoadOp::verify() {
3561   VectorType maskVType = getMaskVectorType();
3562   VectorType passVType = getPassThruVectorType();
3563   VectorType resVType = getVectorType();
3564   MemRefType memType = getMemRefType();
3565 
3566   if (resVType.getElementType() != memType.getElementType())
3567     return emitOpError("base and result element type should match");
3568   if (llvm::size(indices()) != memType.getRank())
3569     return emitOpError("requires ") << memType.getRank() << " indices";
3570   if (resVType.getDimSize(0) != maskVType.getDimSize(0))
3571     return emitOpError("expected result dim to match mask dim");
3572   if (resVType != passVType)
3573     return emitOpError("expected pass_thru of same type as result type");
3574   return success();
3575 }
3576 
3577 namespace {
3578 class MaskedLoadFolder final : public OpRewritePattern<MaskedLoadOp> {
3579 public:
3580   using OpRewritePattern<MaskedLoadOp>::OpRewritePattern;
3581   LogicalResult matchAndRewrite(MaskedLoadOp load,
3582                                 PatternRewriter &rewriter) const override {
3583     switch (get1DMaskFormat(load.mask())) {
3584     case MaskFormat::AllTrue:
3585       rewriter.replaceOpWithNewOp<vector::LoadOp>(load, load.getType(),
3586                                                   load.base(), load.indices());
3587       return success();
3588     case MaskFormat::AllFalse:
3589       rewriter.replaceOp(load, load.pass_thru());
3590       return success();
3591     case MaskFormat::Unknown:
3592       return failure();
3593     }
3594     llvm_unreachable("Unexpected 1DMaskFormat on MaskedLoad");
3595   }
3596 };
3597 } // namespace
3598 
3599 void MaskedLoadOp::getCanonicalizationPatterns(RewritePatternSet &results,
3600                                                MLIRContext *context) {
3601   results.add<MaskedLoadFolder>(context);
3602 }
3603 
3604 OpFoldResult MaskedLoadOp::fold(ArrayRef<Attribute>) {
3605   if (succeeded(foldMemRefCast(*this)))
3606     return getResult();
3607   return OpFoldResult();
3608 }
3609 
3610 //===----------------------------------------------------------------------===//
3611 // MaskedStoreOp
3612 //===----------------------------------------------------------------------===//
3613 
3614 LogicalResult MaskedStoreOp::verify() {
3615   VectorType maskVType = getMaskVectorType();
3616   VectorType valueVType = getVectorType();
3617   MemRefType memType = getMemRefType();
3618 
3619   if (valueVType.getElementType() != memType.getElementType())
3620     return emitOpError("base and valueToStore element type should match");
3621   if (llvm::size(indices()) != memType.getRank())
3622     return emitOpError("requires ") << memType.getRank() << " indices";
3623   if (valueVType.getDimSize(0) != maskVType.getDimSize(0))
3624     return emitOpError("expected valueToStore dim to match mask dim");
3625   return success();
3626 }
3627 
3628 namespace {
3629 class MaskedStoreFolder final : public OpRewritePattern<MaskedStoreOp> {
3630 public:
3631   using OpRewritePattern<MaskedStoreOp>::OpRewritePattern;
3632   LogicalResult matchAndRewrite(MaskedStoreOp store,
3633                                 PatternRewriter &rewriter) const override {
3634     switch (get1DMaskFormat(store.mask())) {
3635     case MaskFormat::AllTrue:
3636       rewriter.replaceOpWithNewOp<vector::StoreOp>(
3637           store, store.valueToStore(), store.base(), store.indices());
3638       return success();
3639     case MaskFormat::AllFalse:
3640       rewriter.eraseOp(store);
3641       return success();
3642     case MaskFormat::Unknown:
3643       return failure();
3644     }
3645     llvm_unreachable("Unexpected 1DMaskFormat on MaskedStore");
3646   }
3647 };
3648 } // namespace
3649 
3650 void MaskedStoreOp::getCanonicalizationPatterns(RewritePatternSet &results,
3651                                                 MLIRContext *context) {
3652   results.add<MaskedStoreFolder>(context);
3653 }
3654 
3655 LogicalResult MaskedStoreOp::fold(ArrayRef<Attribute> operands,
3656                                   SmallVectorImpl<OpFoldResult> &results) {
3657   return foldMemRefCast(*this);
3658 }
3659 
3660 //===----------------------------------------------------------------------===//
3661 // GatherOp
3662 //===----------------------------------------------------------------------===//
3663 
3664 LogicalResult GatherOp::verify() {
3665   VectorType indVType = getIndexVectorType();
3666   VectorType maskVType = getMaskVectorType();
3667   VectorType resVType = getVectorType();
3668   MemRefType memType = getMemRefType();
3669 
3670   if (resVType.getElementType() != memType.getElementType())
3671     return emitOpError("base and result element type should match");
3672   if (llvm::size(indices()) != memType.getRank())
3673     return emitOpError("requires ") << memType.getRank() << " indices";
3674   if (resVType.getDimSize(0) != indVType.getDimSize(0))
3675     return emitOpError("expected result dim to match indices dim");
3676   if (resVType.getDimSize(0) != maskVType.getDimSize(0))
3677     return emitOpError("expected result dim to match mask dim");
3678   if (resVType != getPassThruVectorType())
3679     return emitOpError("expected pass_thru of same type as result type");
3680   return success();
3681 }
3682 
3683 namespace {
3684 class GatherFolder final : public OpRewritePattern<GatherOp> {
3685 public:
3686   using OpRewritePattern<GatherOp>::OpRewritePattern;
3687   LogicalResult matchAndRewrite(GatherOp gather,
3688                                 PatternRewriter &rewriter) const override {
3689     switch (get1DMaskFormat(gather.mask())) {
3690     case MaskFormat::AllTrue:
3691       return failure(); // no unmasked equivalent
3692     case MaskFormat::AllFalse:
3693       rewriter.replaceOp(gather, gather.pass_thru());
3694       return success();
3695     case MaskFormat::Unknown:
3696       return failure();
3697     }
3698     llvm_unreachable("Unexpected 1DMaskFormat on GatherFolder");
3699   }
3700 };
3701 } // namespace
3702 
3703 void GatherOp::getCanonicalizationPatterns(RewritePatternSet &results,
3704                                            MLIRContext *context) {
3705   results.add<GatherFolder>(context);
3706 }
3707 
3708 //===----------------------------------------------------------------------===//
3709 // ScatterOp
3710 //===----------------------------------------------------------------------===//
3711 
3712 LogicalResult ScatterOp::verify() {
3713   VectorType indVType = getIndexVectorType();
3714   VectorType maskVType = getMaskVectorType();
3715   VectorType valueVType = getVectorType();
3716   MemRefType memType = getMemRefType();
3717 
3718   if (valueVType.getElementType() != memType.getElementType())
3719     return emitOpError("base and valueToStore element type should match");
3720   if (llvm::size(indices()) != memType.getRank())
3721     return emitOpError("requires ") << memType.getRank() << " indices";
3722   if (valueVType.getDimSize(0) != indVType.getDimSize(0))
3723     return emitOpError("expected valueToStore dim to match indices dim");
3724   if (valueVType.getDimSize(0) != maskVType.getDimSize(0))
3725     return emitOpError("expected valueToStore dim to match mask dim");
3726   return success();
3727 }
3728 
3729 namespace {
3730 class ScatterFolder final : public OpRewritePattern<ScatterOp> {
3731 public:
3732   using OpRewritePattern<ScatterOp>::OpRewritePattern;
3733   LogicalResult matchAndRewrite(ScatterOp scatter,
3734                                 PatternRewriter &rewriter) const override {
3735     switch (get1DMaskFormat(scatter.mask())) {
3736     case MaskFormat::AllTrue:
3737       return failure(); // no unmasked equivalent
3738     case MaskFormat::AllFalse:
3739       rewriter.eraseOp(scatter);
3740       return success();
3741     case MaskFormat::Unknown:
3742       return failure();
3743     }
3744     llvm_unreachable("Unexpected 1DMaskFormat on ScatterFolder");
3745   }
3746 };
3747 } // namespace
3748 
3749 void ScatterOp::getCanonicalizationPatterns(RewritePatternSet &results,
3750                                             MLIRContext *context) {
3751   results.add<ScatterFolder>(context);
3752 }
3753 
3754 //===----------------------------------------------------------------------===//
3755 // ExpandLoadOp
3756 //===----------------------------------------------------------------------===//
3757 
3758 LogicalResult ExpandLoadOp::verify() {
3759   VectorType maskVType = getMaskVectorType();
3760   VectorType passVType = getPassThruVectorType();
3761   VectorType resVType = getVectorType();
3762   MemRefType memType = getMemRefType();
3763 
3764   if (resVType.getElementType() != memType.getElementType())
3765     return emitOpError("base and result element type should match");
3766   if (llvm::size(indices()) != memType.getRank())
3767     return emitOpError("requires ") << memType.getRank() << " indices";
3768   if (resVType.getDimSize(0) != maskVType.getDimSize(0))
3769     return emitOpError("expected result dim to match mask dim");
3770   if (resVType != passVType)
3771     return emitOpError("expected pass_thru of same type as result type");
3772   return success();
3773 }
3774 
3775 namespace {
3776 class ExpandLoadFolder final : public OpRewritePattern<ExpandLoadOp> {
3777 public:
3778   using OpRewritePattern<ExpandLoadOp>::OpRewritePattern;
3779   LogicalResult matchAndRewrite(ExpandLoadOp expand,
3780                                 PatternRewriter &rewriter) const override {
3781     switch (get1DMaskFormat(expand.mask())) {
3782     case MaskFormat::AllTrue:
3783       rewriter.replaceOpWithNewOp<vector::LoadOp>(
3784           expand, expand.getType(), expand.base(), expand.indices());
3785       return success();
3786     case MaskFormat::AllFalse:
3787       rewriter.replaceOp(expand, expand.pass_thru());
3788       return success();
3789     case MaskFormat::Unknown:
3790       return failure();
3791     }
3792     llvm_unreachable("Unexpected 1DMaskFormat on ExpandLoadFolder");
3793   }
3794 };
3795 } // namespace
3796 
3797 void ExpandLoadOp::getCanonicalizationPatterns(RewritePatternSet &results,
3798                                                MLIRContext *context) {
3799   results.add<ExpandLoadFolder>(context);
3800 }
3801 
3802 //===----------------------------------------------------------------------===//
3803 // CompressStoreOp
3804 //===----------------------------------------------------------------------===//
3805 
3806 LogicalResult CompressStoreOp::verify() {
3807   VectorType maskVType = getMaskVectorType();
3808   VectorType valueVType = getVectorType();
3809   MemRefType memType = getMemRefType();
3810 
3811   if (valueVType.getElementType() != memType.getElementType())
3812     return emitOpError("base and valueToStore element type should match");
3813   if (llvm::size(indices()) != memType.getRank())
3814     return emitOpError("requires ") << memType.getRank() << " indices";
3815   if (valueVType.getDimSize(0) != maskVType.getDimSize(0))
3816     return emitOpError("expected valueToStore dim to match mask dim");
3817   return success();
3818 }
3819 
3820 namespace {
3821 class CompressStoreFolder final : public OpRewritePattern<CompressStoreOp> {
3822 public:
3823   using OpRewritePattern<CompressStoreOp>::OpRewritePattern;
3824   LogicalResult matchAndRewrite(CompressStoreOp compress,
3825                                 PatternRewriter &rewriter) const override {
3826     switch (get1DMaskFormat(compress.mask())) {
3827     case MaskFormat::AllTrue:
3828       rewriter.replaceOpWithNewOp<vector::StoreOp>(
3829           compress, compress.valueToStore(), compress.base(),
3830           compress.indices());
3831       return success();
3832     case MaskFormat::AllFalse:
3833       rewriter.eraseOp(compress);
3834       return success();
3835     case MaskFormat::Unknown:
3836       return failure();
3837     }
3838     llvm_unreachable("Unexpected 1DMaskFormat on CompressStoreFolder");
3839   }
3840 };
3841 } // namespace
3842 
3843 void CompressStoreOp::getCanonicalizationPatterns(RewritePatternSet &results,
3844                                                   MLIRContext *context) {
3845   results.add<CompressStoreFolder>(context);
3846 }
3847 
3848 //===----------------------------------------------------------------------===//
3849 // ShapeCastOp
3850 //===----------------------------------------------------------------------===//
3851 
3852 /// Returns true if each element of 'a' is equal to the product of a contiguous
3853 /// sequence of the elements of 'b'. Returns false otherwise.
3854 static bool isValidShapeCast(ArrayRef<int64_t> a, ArrayRef<int64_t> b) {
3855   unsigned rankA = a.size();
3856   unsigned rankB = b.size();
3857   assert(rankA < rankB);
3858 
3859   unsigned i = 0;
3860   unsigned j = 0;
3861   while (i < rankA && j < rankB) {
3862     int64_t dimA = a[i];
3863     int64_t dimB = 1;
3864     while (dimB < dimA && j < rankB)
3865       dimB *= b[j++];
3866     if (dimA != dimB)
3867       break;
3868     ++i;
3869 
3870     // Handle the case when trailing dimensions are of size 1.
3871     // Include them into the contiguous sequence.
3872     auto isOne = [](int64_t v) { return v == 1; };
3873     if (i < rankA && llvm::all_of(a.slice(i), isOne))
3874       i = rankA;
3875     if (j < rankB && llvm::all_of(b.slice(j), isOne))
3876       j = rankB;
3877   }
3878 
3879   return i == rankA && j == rankB;
3880 }
3881 
3882 static LogicalResult verifyVectorShapeCast(Operation *op,
3883                                            VectorType sourceVectorType,
3884                                            VectorType resultVectorType) {
3885   // Check that element type is the same.
3886   if (sourceVectorType.getElementType() != resultVectorType.getElementType())
3887     return op->emitOpError("source/result vectors must have same element type");
3888   auto sourceShape = sourceVectorType.getShape();
3889   auto resultShape = resultVectorType.getShape();
3890 
3891   // Check that product of source dim sizes matches product of result dim sizes.
3892   int64_t sourceDimProduct = std::accumulate(
3893       sourceShape.begin(), sourceShape.end(), 1LL, std::multiplies<int64_t>{});
3894   int64_t resultDimProduct = std::accumulate(
3895       resultShape.begin(), resultShape.end(), 1LL, std::multiplies<int64_t>{});
3896   if (sourceDimProduct != resultDimProduct)
3897     return op->emitOpError("source/result number of elements must match");
3898 
3899   // Check that expanding/contracting rank cases.
3900   unsigned sourceRank = sourceVectorType.getRank();
3901   unsigned resultRank = resultVectorType.getRank();
3902   if (sourceRank < resultRank) {
3903     if (!isValidShapeCast(sourceShape, resultShape))
3904       return op->emitOpError("invalid shape cast");
3905   } else if (sourceRank > resultRank) {
3906     if (!isValidShapeCast(resultShape, sourceShape))
3907       return op->emitOpError("invalid shape cast");
3908   }
3909   return success();
3910 }
3911 
3912 LogicalResult ShapeCastOp::verify() {
3913   auto sourceVectorType = source().getType().dyn_cast_or_null<VectorType>();
3914   auto resultVectorType = result().getType().dyn_cast_or_null<VectorType>();
3915 
3916   // Check if source/result are of vector type.
3917   if (sourceVectorType && resultVectorType)
3918     return verifyVectorShapeCast(*this, sourceVectorType, resultVectorType);
3919 
3920   return success();
3921 }
3922 
3923 OpFoldResult ShapeCastOp::fold(ArrayRef<Attribute> operands) {
3924   // Nop shape cast.
3925   if (source().getType() == result().getType())
3926     return source();
3927 
3928   // Canceling shape casts.
3929   if (auto otherOp = source().getDefiningOp<ShapeCastOp>()) {
3930     if (result().getType() == otherOp.source().getType())
3931       return otherOp.source();
3932 
3933     // Only allows valid transitive folding.
3934     VectorType srcType = otherOp.source().getType().cast<VectorType>();
3935     VectorType resultType = getResult().getType().cast<VectorType>();
3936     if (srcType.getRank() < resultType.getRank()) {
3937       if (!isValidShapeCast(srcType.getShape(), resultType.getShape()))
3938         return {};
3939     } else if (srcType.getRank() > resultType.getRank()) {
3940       if (!isValidShapeCast(resultType.getShape(), srcType.getShape()))
3941         return {};
3942     } else {
3943       return {};
3944     }
3945 
3946     setOperand(otherOp.source());
3947     return getResult();
3948   }
3949   return {};
3950 }
3951 
3952 namespace {
3953 // Pattern to rewrite a ShapeCast(splat ConstantOp) -> ConstantOp.
3954 class ShapeCastConstantFolder final : public OpRewritePattern<ShapeCastOp> {
3955 public:
3956   using OpRewritePattern<ShapeCastOp>::OpRewritePattern;
3957 
3958   LogicalResult matchAndRewrite(ShapeCastOp shapeCastOp,
3959                                 PatternRewriter &rewriter) const override {
3960     auto constantOp = shapeCastOp.source().getDefiningOp<arith::ConstantOp>();
3961     if (!constantOp)
3962       return failure();
3963     // Only handle splat for now.
3964     auto dense = constantOp.getValue().dyn_cast<SplatElementsAttr>();
3965     if (!dense)
3966       return failure();
3967     auto newAttr =
3968         DenseElementsAttr::get(shapeCastOp.getType().cast<VectorType>(),
3969                                dense.getSplatValue<Attribute>());
3970     rewriter.replaceOpWithNewOp<arith::ConstantOp>(shapeCastOp, newAttr);
3971     return success();
3972   }
3973 };
3974 
3975 } // namespace
3976 
3977 void ShapeCastOp::getCanonicalizationPatterns(RewritePatternSet &results,
3978                                               MLIRContext *context) {
3979   // Pattern to rewrite a ShapeCastOp(ConstantOp) -> ConstantOp.
3980   results.add<ShapeCastConstantFolder>(context);
3981 }
3982 
3983 //===----------------------------------------------------------------------===//
3984 // VectorBitCastOp
3985 //===----------------------------------------------------------------------===//
3986 
3987 LogicalResult BitCastOp::verify() {
3988   auto sourceVectorType = getSourceVectorType();
3989   auto resultVectorType = getResultVectorType();
3990 
3991   for (int64_t i = 0, e = sourceVectorType.getRank() - 1; i < e; i++) {
3992     if (sourceVectorType.getDimSize(i) != resultVectorType.getDimSize(i))
3993       return emitOpError("dimension size mismatch at: ") << i;
3994   }
3995 
3996   DataLayout dataLayout = DataLayout::closest(*this);
3997   auto sourceElementBits =
3998       dataLayout.getTypeSizeInBits(sourceVectorType.getElementType());
3999   auto resultElementBits =
4000       dataLayout.getTypeSizeInBits(resultVectorType.getElementType());
4001 
4002   if (sourceVectorType.getRank() == 0) {
4003     if (sourceElementBits != resultElementBits)
4004       return emitOpError("source/result bitwidth of the 0-D vector element "
4005                             "types must be equal");
4006   } else if (sourceElementBits * sourceVectorType.getShape().back() !=
4007              resultElementBits * resultVectorType.getShape().back()) {
4008     return emitOpError(
4009         "source/result bitwidth of the minor 1-D vectors must be equal");
4010   }
4011 
4012   return success();
4013 }
4014 
4015 OpFoldResult BitCastOp::fold(ArrayRef<Attribute> operands) {
4016   // Nop cast.
4017   if (source().getType() == result().getType())
4018     return source();
4019 
4020   // Canceling bitcasts.
4021   if (auto otherOp = source().getDefiningOp<BitCastOp>())
4022     if (result().getType() == otherOp.source().getType())
4023       return otherOp.source();
4024 
4025   Attribute sourceConstant = operands.front();
4026   if (!sourceConstant)
4027     return {};
4028 
4029   Type srcElemType = getSourceVectorType().getElementType();
4030   Type dstElemType = getResultVectorType().getElementType();
4031 
4032   if (auto floatPack = sourceConstant.dyn_cast<DenseFPElementsAttr>()) {
4033     if (floatPack.isSplat()) {
4034       auto splat = floatPack.getSplatValue<FloatAttr>();
4035 
4036       // Casting fp16 into fp32.
4037       if (srcElemType.isF16() && dstElemType.isF32()) {
4038         uint32_t bits = static_cast<uint32_t>(
4039             splat.getValue().bitcastToAPInt().getZExtValue());
4040         // Duplicate the 16-bit pattern.
4041         bits = (bits << 16) | (bits & 0xffff);
4042         APInt intBits(32, bits);
4043         APFloat floatBits(llvm::APFloat::IEEEsingle(), intBits);
4044         return DenseElementsAttr::get(getResultVectorType(), floatBits);
4045       }
4046     }
4047   }
4048 
4049   return {};
4050 }
4051 
4052 //===----------------------------------------------------------------------===//
4053 // TypeCastOp
4054 //===----------------------------------------------------------------------===//
4055 
4056 static SmallVector<int64_t, 8> extractShape(MemRefType memRefType) {
4057   auto vectorType = memRefType.getElementType().dyn_cast<VectorType>();
4058   SmallVector<int64_t, 8> res(memRefType.getShape().begin(),
4059                               memRefType.getShape().end());
4060   if (vectorType)
4061     res.append(vectorType.getShape().begin(), vectorType.getShape().end());
4062   return res;
4063 }
4064 
4065 /// Build the canonical memRefType with a single vector.
4066 /// E.g. memref<4 x 5 x vector<6 x f32>> -> memref<vector<4 x 5 x 6 x f32>>.
4067 void TypeCastOp::build(OpBuilder &builder, OperationState &result,
4068                        Value source) {
4069   result.addOperands(source);
4070   MemRefType memRefType = source.getType().cast<MemRefType>();
4071   VectorType vectorType =
4072       VectorType::get(extractShape(memRefType),
4073                       getElementTypeOrSelf(getElementTypeOrSelf(memRefType)));
4074   result.addTypes(MemRefType::get({}, vectorType, MemRefLayoutAttrInterface(),
4075                                   memRefType.getMemorySpace()));
4076 }
4077 
4078 LogicalResult TypeCastOp::verify() {
4079   MemRefType canonicalType = canonicalizeStridedLayout(getMemRefType());
4080   if (!canonicalType.getLayout().isIdentity())
4081     return emitOpError("expects operand to be a memref with identity layout");
4082   if (!getResultMemRefType().getLayout().isIdentity())
4083     return emitOpError("expects result to be a memref with identity layout");
4084   if (getResultMemRefType().getMemorySpace() !=
4085       getMemRefType().getMemorySpace())
4086     return emitOpError("expects result in same memory space");
4087 
4088   auto sourceType = getMemRefType();
4089   auto resultType = getResultMemRefType();
4090   if (getElementTypeOrSelf(getElementTypeOrSelf(sourceType)) !=
4091       getElementTypeOrSelf(getElementTypeOrSelf(resultType)))
4092     return emitOpError(
4093                "expects result and operand with same underlying scalar type: ")
4094            << resultType;
4095   if (extractShape(sourceType) != extractShape(resultType))
4096     return emitOpError(
4097                "expects concatenated result and operand shapes to be equal: ")
4098            << resultType;
4099   return success();
4100 }
4101 
4102 //===----------------------------------------------------------------------===//
4103 // TransposeOp
4104 //===----------------------------------------------------------------------===//
4105 
4106 void vector::TransposeOp::build(OpBuilder &builder, OperationState &result,
4107                                 Value vector, ArrayRef<int64_t> transp) {
4108   VectorType vt = vector.getType().cast<VectorType>();
4109   SmallVector<int64_t, 4> transposedShape(vt.getRank());
4110   for (unsigned i = 0; i < transp.size(); ++i)
4111     transposedShape[i] = vt.getShape()[transp[i]];
4112 
4113   result.addOperands(vector);
4114   result.addTypes(VectorType::get(transposedShape, vt.getElementType()));
4115   result.addAttribute(getTranspAttrStrName(), builder.getI64ArrayAttr(transp));
4116 }
4117 
4118 // Eliminates transpose operations, which produce values identical to their
4119 // input values. This happens when the dimensions of the input vector remain in
4120 // their original order after the transpose operation.
4121 OpFoldResult vector::TransposeOp::fold(ArrayRef<Attribute> operands) {
4122   SmallVector<int64_t, 4> transp;
4123   getTransp(transp);
4124 
4125   // Check if the permutation of the dimensions contains sequential values:
4126   // {0, 1, 2, ...}.
4127   for (int64_t i = 0, e = transp.size(); i < e; i++) {
4128     if (transp[i] != i)
4129       return {};
4130   }
4131 
4132   return vector();
4133 }
4134 
4135 LogicalResult vector::TransposeOp::verify() {
4136   VectorType vectorType = getVectorType();
4137   VectorType resultType = getResultType();
4138   int64_t rank = resultType.getRank();
4139   if (vectorType.getRank() != rank)
4140     return emitOpError("vector result rank mismatch: ") << rank;
4141   // Verify transposition array.
4142   auto transpAttr = transp().getValue();
4143   int64_t size = transpAttr.size();
4144   if (rank != size)
4145     return emitOpError("transposition length mismatch: ") << size;
4146   SmallVector<bool, 8> seen(rank, false);
4147   for (const auto &ta : llvm::enumerate(transpAttr)) {
4148     int64_t i = ta.value().cast<IntegerAttr>().getInt();
4149     if (i < 0 || i >= rank)
4150       return emitOpError("transposition index out of range: ") << i;
4151     if (seen[i])
4152       return emitOpError("duplicate position index: ") << i;
4153     seen[i] = true;
4154     if (resultType.getDimSize(ta.index()) != vectorType.getDimSize(i))
4155       return emitOpError("dimension size mismatch at: ") << i;
4156   }
4157   return success();
4158 }
4159 
4160 namespace {
4161 
4162 // Rewrites two back-to-back TransposeOp operations into a single TransposeOp.
4163 class TransposeFolder final : public OpRewritePattern<vector::TransposeOp> {
4164 public:
4165   using OpRewritePattern<vector::TransposeOp>::OpRewritePattern;
4166 
4167   LogicalResult matchAndRewrite(vector::TransposeOp transposeOp,
4168                                 PatternRewriter &rewriter) const override {
4169     // Wrapper around vector::TransposeOp::getTransp() for cleaner code.
4170     auto getPermutation = [](vector::TransposeOp transpose) {
4171       SmallVector<int64_t, 4> permutation;
4172       transpose.getTransp(permutation);
4173       return permutation;
4174     };
4175 
4176     // Composes two permutations: result[i] = permutation1[permutation2[i]].
4177     auto composePermutations = [](ArrayRef<int64_t> permutation1,
4178                                   ArrayRef<int64_t> permutation2) {
4179       SmallVector<int64_t, 4> result;
4180       for (auto index : permutation2)
4181         result.push_back(permutation1[index]);
4182       return result;
4183     };
4184 
4185     // Return if the input of 'transposeOp' is not defined by another transpose.
4186     vector::TransposeOp parentTransposeOp =
4187         transposeOp.vector().getDefiningOp<vector::TransposeOp>();
4188     if (!parentTransposeOp)
4189       return failure();
4190 
4191     SmallVector<int64_t, 4> permutation = composePermutations(
4192         getPermutation(parentTransposeOp), getPermutation(transposeOp));
4193     // Replace 'transposeOp' with a new transpose operation.
4194     rewriter.replaceOpWithNewOp<vector::TransposeOp>(
4195         transposeOp, transposeOp.getResult().getType(),
4196         parentTransposeOp.vector(),
4197         vector::getVectorSubscriptAttr(rewriter, permutation));
4198     return success();
4199   }
4200 };
4201 
4202 } // namespace
4203 
4204 void vector::TransposeOp::getCanonicalizationPatterns(
4205     RewritePatternSet &results, MLIRContext *context) {
4206   results.add<TransposeFolder>(context);
4207 }
4208 
4209 void vector::TransposeOp::getTransp(SmallVectorImpl<int64_t> &results) {
4210   populateFromInt64AttrArray(transp(), results);
4211 }
4212 
4213 //===----------------------------------------------------------------------===//
4214 // ConstantMaskOp
4215 //===----------------------------------------------------------------------===//
4216 
4217 LogicalResult ConstantMaskOp::verify() {
4218   auto resultType = getResult().getType().cast<VectorType>();
4219   // Check the corner case of 0-D vectors first.
4220   if (resultType.getRank() == 0) {
4221     if (mask_dim_sizes().size() != 1)
4222       return emitError("array attr must have length 1 for 0-D vectors");
4223     auto dim = mask_dim_sizes()[0].cast<IntegerAttr>().getInt();
4224     if (dim != 0 && dim != 1)
4225       return emitError("mask dim size must be either 0 or 1 for 0-D vectors");
4226     return success();
4227   }
4228 
4229   // Verify that array attr size matches the rank of the vector result.
4230   if (static_cast<int64_t>(mask_dim_sizes().size()) != resultType.getRank())
4231     return emitOpError(
4232         "must specify array attr of size equal vector result rank");
4233   // Verify that each array attr element is in bounds of corresponding vector
4234   // result dimension size.
4235   auto resultShape = resultType.getShape();
4236   SmallVector<int64_t, 4> maskDimSizes;
4237   for (const auto &it : llvm::enumerate(mask_dim_sizes())) {
4238     int64_t attrValue = it.value().cast<IntegerAttr>().getInt();
4239     if (attrValue < 0 || attrValue > resultShape[it.index()])
4240       return emitOpError(
4241           "array attr of size out of bounds of vector result dimension size");
4242     maskDimSizes.push_back(attrValue);
4243   }
4244   // Verify that if one mask dim size is zero, they all should be zero (because
4245   // the mask region is a conjunction of each mask dimension interval).
4246   bool anyZeros = llvm::is_contained(maskDimSizes, 0);
4247   bool allZeros = llvm::all_of(maskDimSizes, [](int64_t s) { return s == 0; });
4248   if (anyZeros && !allZeros)
4249     return emitOpError("expected all mask dim sizes to be zeros, "
4250                        "as a result of conjunction with zero mask dim");
4251   return success();
4252 }
4253 
4254 //===----------------------------------------------------------------------===//
4255 // CreateMaskOp
4256 //===----------------------------------------------------------------------===//
4257 
4258 LogicalResult CreateMaskOp::verify() {
4259   auto vectorType = getResult().getType().cast<VectorType>();
4260   // Verify that an operand was specified for each result vector each dimension.
4261   if (vectorType.getRank() == 0) {
4262     if (getNumOperands() != 1)
4263       return emitOpError(
4264           "must specify exactly one operand for 0-D create_mask");
4265   } else if (getNumOperands() !=
4266              getResult().getType().cast<VectorType>().getRank()) {
4267     return emitOpError(
4268         "must specify an operand for each result vector dimension");
4269   }
4270   return success();
4271 }
4272 
4273 namespace {
4274 
4275 // Pattern to rewrite a CreateMaskOp with a ConstantMaskOp.
4276 class CreateMaskFolder final : public OpRewritePattern<CreateMaskOp> {
4277 public:
4278   using OpRewritePattern<CreateMaskOp>::OpRewritePattern;
4279 
4280   LogicalResult matchAndRewrite(CreateMaskOp createMaskOp,
4281                                 PatternRewriter &rewriter) const override {
4282     // Return if any of 'createMaskOp' operands are not defined by a constant.
4283     auto isNotDefByConstant = [](Value operand) {
4284       return !isa_and_nonnull<arith::ConstantIndexOp>(operand.getDefiningOp());
4285     };
4286     if (llvm::any_of(createMaskOp.operands(), isNotDefByConstant))
4287       return failure();
4288     // Gather constant mask dimension sizes.
4289     SmallVector<int64_t, 4> maskDimSizes;
4290     for (auto it : llvm::zip(createMaskOp.operands(),
4291                              createMaskOp.getType().getShape())) {
4292       auto *defOp = std::get<0>(it).getDefiningOp();
4293       int64_t maxDimSize = std::get<1>(it);
4294       int64_t dimSize = cast<arith::ConstantIndexOp>(defOp).value();
4295       dimSize = std::min(dimSize, maxDimSize);
4296       // If one of dim sizes is zero, set all dims to zero.
4297       if (dimSize <= 0) {
4298         maskDimSizes.assign(createMaskOp.getType().getRank(), 0);
4299         break;
4300       }
4301       maskDimSizes.push_back(dimSize);
4302     }
4303     // Replace 'createMaskOp' with ConstantMaskOp.
4304     rewriter.replaceOpWithNewOp<ConstantMaskOp>(
4305         createMaskOp, createMaskOp.getResult().getType(),
4306         vector::getVectorSubscriptAttr(rewriter, maskDimSizes));
4307     return success();
4308   }
4309 };
4310 
4311 } // namespace
4312 
4313 void CreateMaskOp::getCanonicalizationPatterns(RewritePatternSet &results,
4314                                                MLIRContext *context) {
4315   results.add<CreateMaskFolder>(context);
4316 }
4317 
4318 //===----------------------------------------------------------------------===//
4319 // ScanOp
4320 //===----------------------------------------------------------------------===//
4321 
4322 LogicalResult ScanOp::verify() {
4323   VectorType srcType = getSourceType();
4324   VectorType initialType = getInitialValueType();
4325   // Check reduction dimension < rank.
4326   int64_t srcRank = srcType.getRank();
4327   int64_t reductionDim = reduction_dim();
4328   if (reductionDim >= srcRank)
4329     return emitOpError("reduction dimension ")
4330            << reductionDim << " has to be less than " << srcRank;
4331 
4332   // Check that rank(initial_value) = rank(src) - 1.
4333   int64_t initialValueRank = initialType.getRank();
4334   if (initialValueRank != srcRank - 1)
4335     return emitOpError("initial value rank ")
4336            << initialValueRank << " has to be equal to " << srcRank - 1;
4337 
4338   // Check shapes of initial value and src.
4339   ArrayRef<int64_t> srcShape = srcType.getShape();
4340   ArrayRef<int64_t> initialValueShapes = initialType.getShape();
4341   SmallVector<int64_t> expectedShape;
4342   for (int i = 0; i < srcRank; i++) {
4343     if (i != reductionDim)
4344       expectedShape.push_back(srcShape[i]);
4345   }
4346   if (llvm::any_of(llvm::zip(initialValueShapes, expectedShape),
4347                    [](std::tuple<int64_t, int64_t> s) {
4348                      return std::get<0>(s) != std::get<1>(s);
4349                    })) {
4350     return emitOpError("incompatible input/initial value shapes");
4351   }
4352 
4353   return success();
4354 }
4355 
4356 void mlir::vector::populateVectorToVectorCanonicalizationPatterns(
4357     RewritePatternSet &patterns) {
4358   patterns
4359       .add<CreateMaskFolder, MaskedLoadFolder, MaskedStoreFolder, GatherFolder,
4360            ScatterFolder, ExpandLoadFolder, CompressStoreFolder,
4361            StridedSliceConstantMaskFolder, TransposeFolder>(
4362           patterns.getContext());
4363 }
4364 
4365 //===----------------------------------------------------------------------===//
4366 // SplatOp
4367 //===----------------------------------------------------------------------===//
4368 
4369 OpFoldResult SplatOp::fold(ArrayRef<Attribute> operands) {
4370   auto constOperand = operands.front();
4371   if (!constOperand.isa_and_nonnull<IntegerAttr, FloatAttr>())
4372     return {};
4373 
4374   // SplatElementsAttr::get treats single value for second arg as being a splat.
4375   return SplatElementsAttr::get(getType(), {constOperand});
4376 }
4377 
4378 //===----------------------------------------------------------------------===//
4379 // TableGen'd op method definitions
4380 //===----------------------------------------------------------------------===//
4381 
4382 #define GET_OP_CLASSES
4383 #include "mlir/Dialect/Vector/IR/VectorOps.cpp.inc"
4384