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