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