1 //===- Vectorization.cpp - Implementation of linalg Vectorization ---------===//
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 the linalg dialect Vectorization transformations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Analysis/LoopAnalysis.h"
14 #include "mlir/Analysis/SliceAnalysis.h"
15 #include "mlir/Dialect/Linalg/Analysis/DependenceAnalysis.h"
16 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
17 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
18 #include "mlir/Dialect/Linalg/Utils/Utils.h"
19 #include "mlir/Dialect/Tensor/IR/Tensor.h"
20 #include "mlir/Dialect/Utils/StructuredOpsUtils.h"
21 #include "mlir/Dialect/Vector/VectorOps.h"
22 #include "mlir/IR/AffineExpr.h"
23 #include "mlir/IR/Matchers.h"
24 #include "mlir/IR/PatternMatch.h"
25 #include "mlir/Pass/Pass.h"
26 #include "mlir/Support/LLVM.h"
27 #include "mlir/Transforms/RegionUtils.h"
28 #include "llvm/ADT/ScopeExit.h"
29 #include "llvm/ADT/Sequence.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/TypeSwitch.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <type_traits>
35 
36 using namespace mlir;
37 using namespace mlir::linalg;
38 
39 using llvm::dbgs;
40 
41 #define DEBUG_TYPE "linalg-vectorization"
42 
43 /// Return the unique instance of OpType in `block` if it is indeed unique.
44 /// Return null if none or more than 1 instances exist.
45 template <typename OpType>
46 static OpType getSingleOpOfType(Block &block) {
47   OpType res;
48   block.walk([&](OpType op) {
49     if (res) {
50       res = nullptr;
51       return WalkResult::interrupt();
52     }
53     res = op;
54     return WalkResult::advance();
55   });
56   return res;
57 }
58 
59 /// Given an indexing `map` coming from a LinalgOp indexing, restricted to a
60 /// projectedPermutation, compress the unused dimensions to serve as a
61 /// permutation_map for a vector transfer operation.
62 /// For example, given a linalg op such as:
63 ///
64 /// ```
65 ///   %0 = linalg.generic {
66 ///        indexing_maps = affine_map<(d0, d1, d2, d3, d4) -> (d4, d0, d2)>,
67 ///        indexing_maps = affine_map<(d0, d1, d2, d3, d4) -> (d1, d3)>
68 ///      }
69 ///     ins(%0 : tensor<2x3x4xf32>)
70 ///    outs(%1 : tensor<5x6xf32>)
71 /// ```
72 ///
73 /// the iteration domain size of the linalg op is 3x5x4x6x2. The first affine
74 /// map is reindexed to `affine_map<(d0, d1, d2) -> (d2, d0, d1)>`, the second
75 /// affine map is reindexed to `affine_map<(d0, d1) -> (d0, d1)>`.
76 static AffineMap reindexIndexingMap(AffineMap map) {
77   assert(map.isProjectedPermutation() && "expected projected permutation");
78   auto res = compressUnusedDims(map);
79   assert(res.getNumDims() == res.getNumResults() &&
80          "expected reindexed map with same number of dims and results");
81   return res;
82 }
83 
84 /// Helper data structure to represent the result of vectorization.
85 /// In certain specific cases, like terminators, we do not want to propagate/
86 enum VectorizationStatus {
87   /// Op failed to vectorize.
88   Failure = 0,
89   /// Op vectorized and custom function took care of replacement logic
90   NoReplace,
91   /// Op vectorized into a new Op whose results will replace original Op's
92   /// results.
93   NewOp
94   // TODO: support values if Op vectorized to Many-Ops whose results we need to
95   // aggregate for replacement.
96 };
97 struct VectorizationResult {
98   /// Return status from vectorizing the current op.
99   enum VectorizationStatus status = VectorizationStatus::Failure;
100   /// New vectorized operation to replace the current op.
101   /// Replacement behavior is specified by `status`.
102   Operation *newOp;
103 };
104 
105 /// Return a vector type of the same shape and element type as the (assumed)
106 /// ShapedType of `v`.
107 static VectorType extractVectorTypeFromShapedValue(Value v) {
108   auto st = v.getType().cast<ShapedType>();
109   if (st.isa<MemRefType>() && st.getShape().empty())
110     return VectorType();
111   return VectorType::get(st.getShape(), st.getElementType());
112 }
113 
114 /// Check whether `outputOperand` is a reduction with a single combiner
115 /// operation. Return the combiner operation of the reduction, which is assumed
116 /// to be a binary operation. Multiple reduction operations would impose an
117 /// ordering between reduction dimensions and is currently unsupported in
118 /// Linalg. This limitation is motivated by the fact that e.g. min(max(X)) !=
119 /// max(min(X))
120 // TODO: use in LinalgOp verification, there is a circular dependency atm.
121 static Operation *getSingleBinaryOpAssumedReduction(OpOperand *outputOperand) {
122   auto linalgOp = cast<LinalgOp>(outputOperand->getOwner());
123   unsigned outputPos =
124       outputOperand->getOperandNumber() - linalgOp.getNumInputs();
125   SmallVector<Operation *, 4> combinerOps;
126   if (!matchReduction(linalgOp.getRegionOutputArgs(), outputPos, combinerOps) ||
127       combinerOps.size() != 1)
128     return nullptr;
129 
130   // TODO: also assert no other subsequent ops break the reduction.
131   return combinerOps[0];
132 }
133 
134 /// If `value` of assumed VectorType has a shape different than `shape`, try to
135 /// build and return a new vector.broadcast to `shape`.
136 /// Otherwise, just return `value`.
137 // TODO: this is best effort atm and there is currently no guarantee of
138 // correctness for the broadcast semantics.
139 static Value broadcastIfNeeded(OpBuilder &b, Value value,
140                                ArrayRef<int64_t> shape) {
141   unsigned numDimsGtOne = std::count_if(shape.begin(), shape.end(),
142                                         [](int64_t val) { return val > 1; });
143   auto vecType = value.getType().dyn_cast<VectorType>();
144   if (shape.empty() ||
145       (vecType != nullptr &&
146        (vecType.getShape() == shape || vecType.getRank() > numDimsGtOne)))
147     return value;
148   auto newVecType = VectorType::get(shape, vecType ? vecType.getElementType()
149                                                    : value.getType());
150   return b.create<vector::BroadcastOp>(b.getInsertionPoint()->getLoc(),
151                                        newVecType, value);
152 }
153 
154 static llvm::Optional<vector::CombiningKind>
155 getKindForOp(Operation *reductionOp) {
156   if (!reductionOp)
157     return llvm::None;
158   return llvm::TypeSwitch<Operation *, llvm::Optional<vector::CombiningKind>>(
159              reductionOp)
160       .Case<AddIOp, AddFOp>([&](auto op) {
161         return llvm::Optional<vector::CombiningKind>{
162             vector::CombiningKind::ADD};
163       })
164       .Default([&](auto op) { return llvm::None; });
165 }
166 
167 /// If value of assumed VectorType has a shape different than `shape`, build and
168 /// return a new vector.broadcast to `shape`.
169 /// Otherwise, just return value.
170 static Value reduceIfNeeded(OpBuilder &b, VectorType targetVectorType,
171                             Value value, OpOperand *outputOperand) {
172   auto linalgOp = cast<LinalgOp>(outputOperand->getOwner());
173   auto vecType = value.getType().dyn_cast<VectorType>();
174   if (!vecType || vecType.getShape() == targetVectorType.getShape())
175     return value;
176   // At this point, we know we need to reduce. Detect the reduction operator.
177   // TODO: Use the generic reduction detection util.
178   Operation *reductionOp = getSingleBinaryOpAssumedReduction(outputOperand);
179   unsigned pos = 0;
180   MLIRContext *ctx = b.getContext();
181   SmallVector<AffineExpr> exprs;
182   for (auto s : linalgOp.iterator_types())
183     if (isParallelIterator(s))
184       exprs.push_back(getAffineDimExpr(pos++, ctx));
185   auto loc = value.getLoc();
186   // TODO: reuse common CombiningKing logic and support more than add.
187   auto maybeKind = getKindForOp(reductionOp);
188   assert(maybeKind && "Failed precondition: could not get reduction kind");
189   unsigned idx = 0;
190   SmallVector<bool> reductionMask(linalgOp.iterator_types().size(), false);
191   for (auto attr : linalgOp.iterator_types()) {
192     if (isReductionIterator(attr))
193       reductionMask[idx] = true;
194     ++idx;
195   }
196   return b.create<vector::MultiDimReductionOp>(loc, value, reductionMask,
197                                                *maybeKind);
198 }
199 
200 /// Build a vector.transfer_read from `source` at indices set to all `0`.
201 /// If source has rank zero, build an memref.load.
202 /// Return the produced value.
203 static Value buildVectorRead(OpBuilder &b, Value source, VectorType vectorType,
204                              AffineMap map) {
205   Location loc = source.getLoc();
206   auto shapedType = source.getType().cast<ShapedType>();
207   SmallVector<Value> indices(shapedType.getRank(),
208                              b.create<ConstantIndexOp>(loc, 0));
209   return b.create<vector::TransferReadOp>(loc, vectorType, source, indices,
210                                           map);
211 }
212 
213 /// Build a vector.transfer_write of `value` into `outputOperand` at indices set
214 /// to all `0`; where `outputOperand` is an output operand of the LinalgOp
215 /// currently being vectorized. If `dest` has null rank, build an memref.store.
216 /// Return the produced value or null if no value is produced.
217 static Value buildVectorWrite(OpBuilder &b, Value value,
218                               OpOperand *outputOperand) {
219   Operation *write;
220   Location loc = value.getLoc();
221   if (VectorType vectorType =
222           extractVectorTypeFromShapedValue(outputOperand->get())) {
223     auto linalgOp = cast<LinalgOp>(outputOperand->getOwner());
224     AffineMap map =
225         reindexIndexingMap(linalgOp.getTiedIndexingMap(outputOperand));
226     SmallVector<int64_t> transposeShape =
227         applyPermutationMap(inversePermutation(map), vectorType.getShape());
228     vectorType = VectorType::get(transposeShape, vectorType.getElementType());
229     SmallVector<Value> indices(linalgOp.getRank(outputOperand),
230                                b.create<ConstantIndexOp>(loc, 0));
231     value = broadcastIfNeeded(b, value, vectorType.getShape());
232     value = reduceIfNeeded(b, vectorType, value, outputOperand);
233     write = b.create<vector::TransferWriteOp>(loc, value, outputOperand->get(),
234                                               indices, map);
235   } else {
236     write = b.create<memref::StoreOp>(loc, value, outputOperand->get());
237   }
238   LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: vectorized op: " << *write);
239   if (!write->getResults().empty())
240     return write->getResult(0);
241   return Value();
242 }
243 
244 // Custom vectorization function type. Produce a vector form of Operation*
245 // assuming all its vectorized operands are already in the BlockAndValueMapping.
246 // Return nullptr if the Operation cannot be vectorized.
247 using CustomVectorizationHook = std::function<VectorizationResult(
248     Operation *, const BlockAndValueMapping &)>;
249 
250 /// Helper function to vectorize the terminator of a `linalgOp`. New result
251 /// vector values are appended to `newResults`. Return
252 /// VectorizationStatus::NoReplace to signal the vectorization algorithm that it
253 /// should not try to map produced operations and instead return the results
254 /// using the `newResults` vector making them available to the
255 /// vectorization algorithm for RAUW. This function is meant to be used as a
256 /// CustomVectorizationHook.
257 static VectorizationResult
258 vectorizeLinalgYield(OpBuilder &b, Operation *op,
259                      const BlockAndValueMapping &bvm, LinalgOp linalgOp,
260                      SmallVectorImpl<Value> &newResults) {
261   auto yieldOp = dyn_cast<linalg::YieldOp>(op);
262   if (!yieldOp)
263     return VectorizationResult{VectorizationStatus::Failure, nullptr};
264   for (auto outputs : llvm::enumerate(yieldOp.values())) {
265     // TODO: Scan for an opportunity for reuse.
266     // TODO: use a map.
267     Value vectorValue = bvm.lookup(outputs.value());
268     Value newResult = buildVectorWrite(
269         b, vectorValue, linalgOp.getOutputOperand(outputs.index()));
270     if (newResult)
271       newResults.push_back(newResult);
272   }
273   return VectorizationResult{VectorizationStatus::NoReplace, nullptr};
274 }
275 
276 /// Helper function to vectorize the index operations of a `linalgOp`. Return
277 /// VectorizationStatus::NewOp to signal the vectorization algorithm that it
278 /// should map the produced operations. This function is meant to be used as a
279 /// CustomVectorizationHook.
280 static VectorizationResult vectorizeLinalgIndex(OpBuilder &b, Operation *op,
281                                                 LinalgOp linalgOp) {
282   IndexOp indexOp = dyn_cast<linalg::IndexOp>(op);
283   if (!indexOp)
284     return VectorizationResult{VectorizationStatus::Failure, nullptr};
285   auto loc = indexOp.getLoc();
286   // Compute the static loop sizes of the index op.
287   auto targetShape = linalgOp.computeStaticLoopSizes();
288   // Compute a one-dimensional index vector for the index op dimension.
289   SmallVector<int64_t> constantSeq =
290       llvm::to_vector<16>(llvm::seq<int64_t>(0, targetShape[indexOp.dim()]));
291   ConstantOp constantOp =
292       b.create<ConstantOp>(loc, b.getIndexVectorAttr(constantSeq));
293   // Return the one-dimensional index vector if it lives in the trailing
294   // dimension of the iteration space since the vectorization algorithm in this
295   // case can handle the broadcast.
296   if (indexOp.dim() == targetShape.size() - 1)
297     return VectorizationResult{VectorizationStatus::NewOp, constantOp};
298   // Otherwise permute the targetShape to move the index dimension last,
299   // broadcast the one-dimensional index vector to the permuted shape, and
300   // finally transpose the broadcasted index vector to undo the permutation.
301   std::swap(targetShape[indexOp.dim()], targetShape.back());
302   auto broadCastOp = b.create<vector::BroadcastOp>(
303       loc, VectorType::get(targetShape, b.getIndexType()), constantOp);
304   SmallVector<int64_t> transposition =
305       llvm::to_vector<16>(llvm::seq<int64_t>(0, linalgOp.getNumLoops()));
306   std::swap(transposition.back(), transposition[indexOp.dim()]);
307   auto transposeOp =
308       b.create<vector::TransposeOp>(loc, broadCastOp, transposition);
309   return VectorizationResult{VectorizationStatus::NewOp, transposeOp};
310 }
311 
312 /// Generic vectorization for a single operation `op`, given already vectorized
313 /// operands carried by `bvm`. Vectorization occurs as follows:
314 ///   1. Try to apply any of the `customVectorizationHooks` and return its
315 ///   result on success.
316 ///   2. Clone any constant in the current scope without vectorization: each
317 ///   consumer of the constant will later determine the shape to which the
318 ///   constant needs to be broadcast to.
319 ///   3. Fail on any remaining non `ElementwiseMappable` op. It is the purpose
320 ///   of the `customVectorizationHooks` to cover such cases.
321 ///   4. Clone `op` in vector form to a vector of shape prescribed by the first
322 ///   operand of maximal rank. Other operands have smaller rank and are
323 ///   broadcast accordingly. It is assumed this broadcast is always legal,
324 ///   otherwise, it means one of the `customVectorizationHooks` is incorrect.
325 ///
326 /// This function assumes all operands of `op` have been vectorized and are in
327 /// the `bvm` mapping. As a consequence, this function is meant to be called on
328 /// a topologically-sorted list of ops.
329 /// This function does not update `bvm` but returns a VectorizationStatus that
330 /// instructs the caller what `bvm` update needs to occur.
331 static VectorizationResult
332 vectorizeOneOp(OpBuilder &b, Operation *op, const BlockAndValueMapping &bvm,
333                ArrayRef<CustomVectorizationHook> customVectorizationHooks) {
334   LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: vectorize op " << *op);
335 
336   // 1. Try to apply any CustomVectorizationHook.
337   if (!customVectorizationHooks.empty()) {
338     for (auto &customFunc : customVectorizationHooks) {
339       VectorizationResult result = customFunc(op, bvm);
340       if (result.status == VectorizationStatus::Failure)
341         continue;
342       return result;
343     }
344   }
345 
346   // 2. Constant ops don't get vectorized but rather broadcasted at their users.
347   // Clone so that the constant is not confined to the linalgOp block .
348   if (isa<ConstantOp>(op))
349     return VectorizationResult{VectorizationStatus::NewOp, b.clone(*op)};
350 
351   // 3. Only ElementwiseMappable are allowed in the generic vectorization.
352   if (!OpTrait::hasElementwiseMappableTraits(op))
353     return VectorizationResult{VectorizationStatus::Failure, nullptr};
354 
355   // 4. Generic vectorization path for ElementwiseMappable ops.
356   //   a. first get the first max ranked shape.
357   SmallVector<int64_t, 4> firstMaxRankedShape;
358   for (Value operand : op->getOperands()) {
359     auto vt = bvm.lookup(operand).getType().dyn_cast<VectorType>();
360     if (vt && firstMaxRankedShape.size() < vt.getShape().size())
361       firstMaxRankedShape.assign(vt.getShape().begin(), vt.getShape().end());
362   }
363   //   b. broadcast each op if needed.
364   auto vectorizedOperands = llvm::map_range(op->getOperands(), [&](Value v) {
365     return firstMaxRankedShape.empty()
366                ? bvm.lookup(v)
367                : broadcastIfNeeded(b, bvm.lookup(v), firstMaxRankedShape);
368   });
369   //   c. for elementwise, the result is the vector with the firstMaxRankedShape
370   auto returnTypes = llvm::map_range(op->getResultTypes(), [&](Type t) {
371     return firstMaxRankedShape.empty()
372                ? t
373                : VectorType::get(firstMaxRankedShape, t);
374   });
375 
376   // Build and return the new op.
377   OperationState state(op->getLoc(), op->getName());
378   state.addAttributes(op->getAttrs());
379   state.addOperands(llvm::to_vector<4>(vectorizedOperands));
380   state.addTypes(llvm::to_vector<4>(returnTypes));
381   return VectorizationResult{VectorizationStatus::NewOp,
382                              b.createOperation(state)};
383 }
384 
385 /// Detect whether `r` has only ConstantOp, ElementwiseMappable and YieldOp.
386 static bool hasOnlyScalarElementwiseOp(Region &r) {
387   if (!llvm::hasSingleElement(r))
388     return false;
389   for (Operation &op : r.front()) {
390     if (!(isa<ConstantOp, linalg::YieldOp, linalg::IndexOp>(op) ||
391           OpTrait::hasElementwiseMappableTraits(&op)) ||
392         llvm::any_of(op.getResultTypes(),
393                      [](Type type) { return !type.isIntOrIndexOrFloat(); }))
394       return false;
395   }
396   return true;
397 }
398 
399 // Return true if the op is an element-wise linalg op.
400 static bool isElementwise(Operation *op) {
401   auto linalgOp = dyn_cast<linalg::LinalgOp>(op);
402   if (!linalgOp)
403     return false;
404   if (linalgOp.getNumLoops() != linalgOp.getNumParallelLoops())
405     return false;
406   // TODO: relax the restrictions on indexing map.
407   for (OpOperand *opOperand : linalgOp.getOutputOperands()) {
408     if (!linalgOp.getTiedIndexingMap(opOperand).isIdentity())
409       return false;
410   }
411   if (linalgOp->getNumRegions() != 1)
412     return false;
413   return hasOnlyScalarElementwiseOp(linalgOp->getRegion(0));
414 }
415 
416 /// Generic vectorization function that rewrites the body of a `linalgOp` into
417 /// vector form. Generic vectorization proceeds as follows:
418 ///   1. Verify the `linalgOp` has one non-empty region.
419 ///   2. Values defined above the region are mapped to themselves and will be
420 ///   broadcasted on a per-need basis by their consumers.
421 ///   3. Each region argument is vectorized into a vector.transfer_read (or 0-d
422 ///   load).
423 ///   TODO: Reuse opportunities for RAR dependencies.
424 ///   4a. Register CustomVectorizationHook for YieldOp to capture the results.
425 ///   4b. Register CustomVectorizationHook for IndexOp to access the iteration
426 ///   indices.
427 ///   5. Iteratively call vectorizeOneOp on the region operations.
428 ///
429 /// When `broadcastToMaximalCommonShape` is set to true, eager broadcasting is
430 /// performed to the maximal common vector size implied by the `linalgOp`
431 /// iteration space. This eager broadcasting is introduced in the
432 /// permutation_map of the vector.transfer_read operations. The eager
433 /// broadcasting makes it trivial to detrmine where broadcast, transposes and
434 /// reductions should occur, without any bookkeeping. The tradeoff is that, in
435 /// the absence of good canonicalizations, the amount of work increases.
436 /// This is not deemed a problem as we expect canonicalizations and foldings to
437 /// aggressively clean up the useless work.
438 LogicalResult vectorizeAsLinalgGeneric(
439     OpBuilder &b, LinalgOp linalgOp, SmallVectorImpl<Value> &newResults,
440     bool broadcastToMaximalCommonShape = false,
441     ArrayRef<CustomVectorizationHook> customVectorizationHooks = {}) {
442   // 1. Fail to vectorize if the operation does not have one non-empty region.
443   if (linalgOp->getNumRegions() != 1 || linalgOp->getRegion(0).empty())
444     return failure();
445   auto &block = linalgOp->getRegion(0).front();
446 
447   // 2. Values defined above the region can only be broadcast for now. Make them
448   // map to themselves.
449   BlockAndValueMapping bvm;
450   SetVector<Value> valuesSet;
451   mlir::getUsedValuesDefinedAbove(linalgOp->getRegion(0), valuesSet);
452   bvm.map(valuesSet.getArrayRef(), valuesSet.getArrayRef());
453 
454   if (linalgOp.getNumOutputs() == 0)
455     return failure();
456 
457   // TODO: the common vector shape is equal to the static loop sizes only when
458   // all indexing maps are projected permutations. For convs and stencils the
459   // logic will need to evolve.
460   SmallVector<int64_t> commonVectorShape = linalgOp.computeStaticLoopSizes();
461 
462   // 3. Turn all BBArgs into vector.transfer_read / load.
463   SmallVector<AffineMap> indexings;
464   for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands()) {
465     BlockArgument bbarg = block.getArgument(opOperand->getOperandNumber());
466     if (linalgOp.isScalar(opOperand)) {
467       bvm.map(bbarg, opOperand->get());
468       continue;
469     }
470     // TODO: 0-d vectors.
471     if (linalgOp.getShape(opOperand).empty()) {
472       Value loaded =
473           b.create<memref::LoadOp>(linalgOp.getLoc(), opOperand->get());
474       LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: new vectorized bbarg("
475                         << bbarg.getArgNumber() << "): " << loaded);
476       bvm.map(bbarg, loaded);
477       bvm.map(opOperand->get(), loaded);
478       continue;
479     }
480     AffineMap map;
481     VectorType vectorType;
482     if (broadcastToMaximalCommonShape) {
483       map = inverseAndBroadcastProjectedPermuation(
484           linalgOp.getTiedIndexingMap(opOperand));
485       vectorType = VectorType::get(commonVectorShape,
486                                    getElementTypeOrSelf(opOperand->get()));
487     } else {
488       map = inversePermutation(
489           reindexIndexingMap(linalgOp.getTiedIndexingMap(opOperand)));
490       vectorType = VectorType::get(map.compose(linalgOp.getShape(opOperand)),
491                                    getElementTypeOrSelf(opOperand->get()));
492     }
493     Value vectorRead = buildVectorRead(b, opOperand->get(), vectorType, map);
494     LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: new vectorized bbarg("
495                       << bbarg.getArgNumber() << "): " << vectorRead);
496     bvm.map(bbarg, vectorRead);
497     bvm.map(opOperand->get(), vectorRead);
498   }
499 
500   auto hooks = llvm::to_vector<4>(customVectorizationHooks);
501   // 4a. Register CustomVectorizationHook for yieldOp.
502   CustomVectorizationHook vectorizeYield =
503       [&](Operation *op,
504           const BlockAndValueMapping &bvm) -> VectorizationResult {
505     return vectorizeLinalgYield(b, op, bvm, linalgOp, newResults);
506   };
507   hooks.push_back(vectorizeYield);
508 
509   // 4b. Register CustomVectorizationHook for indexOp.
510   CustomVectorizationHook vectorizeIndex =
511       [&](Operation *op,
512           const BlockAndValueMapping &bvm) -> VectorizationResult {
513     return vectorizeLinalgIndex(b, op, linalgOp);
514   };
515   hooks.push_back(vectorizeIndex);
516 
517   // 5. Iteratively call `vectorizeOneOp` to each op in the slice.
518   for (Operation &op : block.getOperations()) {
519     VectorizationResult result = vectorizeOneOp(b, &op, bvm, hooks);
520     if (result.status == VectorizationStatus::Failure) {
521       LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: failed to vectorize: " << op);
522       return failure();
523     }
524     if (result.status == VectorizationStatus::NewOp) {
525       LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: new vector op: "
526                         << *result.newOp;);
527       bvm.map(op.getResults(), result.newOp->getResults());
528     }
529   }
530 
531   return success();
532 }
533 
534 static LogicalResult vectorizeContraction(OpBuilder &b, LinalgOp linalgOp,
535                                           SmallVectorImpl<Value> &newResults) {
536   assert(isaContractionOpInterface(linalgOp) &&
537          "expected vectorizeContraction preconditions to be met");
538   Location loc = linalgOp.getLoc();
539   // Vectorize other ops as vector contraction.
540   // TODO: interface.
541   LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: "
542                     << "Rewrite linalg op as vector.contract: ";
543              linalgOp.dump());
544   // Special function that describes how to vectorize the multiplication op in a
545   // linalg contraction.
546   CustomVectorizationHook vectorizeContraction =
547       [&](Operation *op,
548           const BlockAndValueMapping &bvm) -> VectorizationResult {
549     if (!isa<MulIOp, MulFOp>(op))
550       return VectorizationResult{VectorizationStatus::Failure, nullptr};
551     ArrayRef<int64_t> outShape =
552         linalgOp.getShape(linalgOp.getOutputOperand(0));
553     Type vType;
554     if (outShape.empty()) {
555       vType = op->getResult(0).getType();
556     } else {
557       SmallVector<int64_t> resultShape = applyPermutationMap(
558           inversePermutation(reindexIndexingMap(
559               linalgOp.getTiedIndexingMap(linalgOp.getOutputOperand(0)))),
560           outShape);
561       vType = VectorType::get(resultShape, op->getResult(0).getType());
562     }
563     auto zero = b.create<ConstantOp>(loc, vType, b.getZeroAttr(vType));
564     // Indexing maps at the time of vector.transfer_read are adjusted to order
565     // vector dimensions in the same order as the canonical linalg op iteration
566     // space order.
567     // The indexings for the contraction therefore need to be adjusted.
568     // TODO: consider dropping contraction special casing altogether, this will
569     // require more advanced canonicalizations involving vector.multi_reduction
570     // that are not yet available.
571     SmallVector<AffineMap> indexingMaps;
572     indexingMaps.reserve(linalgOp.getNumInputsAndOutputs());
573     llvm::transform(linalgOp.getIndexingMaps(),
574                     std::back_inserter(indexingMaps),
575                     [](AffineMap indexingMap) {
576                       return inversePermutation(reindexIndexingMap(indexingMap))
577                           .compose(indexingMap);
578                     });
579     Operation *contract = b.create<vector::ContractionOp>(
580         loc, bvm.lookup(op->getOperand(0)), bvm.lookup(op->getOperand(1)), zero,
581         b.getAffineMapArrayAttr(indexingMaps), linalgOp.iterator_types());
582     return VectorizationResult{VectorizationStatus::NewOp, contract};
583   };
584   return vectorizeAsLinalgGeneric(b, linalgOp, newResults,
585                                   /*broadcastToMaximalCommonShape=*/false,
586                                   {vectorizeContraction});
587 }
588 
589 static bool allIndexingsAreProjectedPermutation(LinalgOp op) {
590   return llvm::all_of(op.getIndexingMaps(),
591                       [](AffineMap m) { return m.isProjectedPermutation(); });
592 }
593 
594 // TODO: probably need some extra checks for reduction followed by consumer
595 // ops that may not commute (e.g. linear reduction + non-linear instructions).
596 static LogicalResult reductionPreconditions(LinalgOp op) {
597   if (llvm::none_of(op.iterator_types(), isReductionIterator))
598     return failure();
599   for (OpOperand *opOperand : op.getOutputOperands()) {
600     Operation *reductionOp = getSingleBinaryOpAssumedReduction(opOperand);
601     if (!getKindForOp(reductionOp))
602       return failure();
603   }
604   return success();
605 }
606 
607 LogicalResult mlir::linalg::vectorizeLinalgOpPrecondition(Operation *op) {
608   auto linalgOp = cast<linalg::LinalgOp>(op);
609   // All types must be static shape to go to vector.
610   if (linalgOp.hasDynamicShape())
611     return failure();
612   if (isElementwise(op))
613     return success();
614   if (isaContractionOpInterface(linalgOp))
615     return success();
616   // TODO: the common vector shape is equal to the static loop sizes only when
617   // all indexing maps are projected permutations. For convs and stencils the
618   // logic will need to evolve.
619   if (allIndexingsAreProjectedPermutation(linalgOp) &&
620       succeeded(reductionPreconditions(linalgOp)))
621     return success();
622   return failure();
623 }
624 
625 LogicalResult
626 mlir::linalg::vectorizeLinalgOp(OpBuilder &b, Operation *op,
627                                 SmallVectorImpl<Value> &newResults) {
628   if (failed(vectorizeLinalgOpPrecondition(op)))
629     return failure();
630 
631   auto linalgOp = cast<LinalgOp>(op);
632   if (isaContractionOpInterface(linalgOp))
633     return vectorizeContraction(b, linalgOp, newResults);
634 
635   LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: "
636                     << "Vectorize linalg op as a generic by broadcasting to "
637                        "maximal common shape: "
638                     << *op);
639   return vectorizeAsLinalgGeneric(b, linalgOp, newResults,
640                                   /*broadcastToMaximalCommonShape=*/true);
641 }
642 
643 //----------------------------------------------------------------------------//
644 // Misc. vectorization patterns.
645 //----------------------------------------------------------------------------//
646 
647 /// Helper function that retrieves the value of an IntegerAttr.
648 static int64_t getIntFromAttr(Attribute attr) {
649   return attr.cast<IntegerAttr>().getInt();
650 }
651 
652 /// Given an ArrayRef of OpFoldResults, return a vector of Values. IntegerAttrs
653 /// are converted to ConstantIndexOps. Other attribute types are not supported.
654 static SmallVector<Value> ofrToIndexValues(OpBuilder &builder, Location loc,
655                                            ArrayRef<OpFoldResult> ofrs) {
656   SmallVector<Value> result;
657   llvm::for_each(ofrs, [&](auto o) {
658     if (auto val = o.template dyn_cast<Value>()) {
659       result.push_back(val);
660     } else {
661       result.push_back(builder.create<ConstantIndexOp>(
662           loc, getIntFromAttr(o.template get<Attribute>())));
663     }
664   });
665   return result;
666 }
667 
668 /// Rewrite a PadTensorOp into a sequence of InitTensorOp, FillOp and
669 /// InsertSliceOp. For now, only constant padding values are supported.
670 /// If there is enough static type information, TransferReadOps and
671 /// TransferWriteOps may be generated instead of InsertSliceOps.
672 struct GenericPadTensorOpVectorizationPattern
673     : public GeneralizePadTensorOpPattern {
674   GenericPadTensorOpVectorizationPattern(MLIRContext *context,
675                                          PatternBenefit benefit = 1)
676       : GeneralizePadTensorOpPattern(context, tryVectorizeCopy, benefit) {}
677   /// Vectorize the copying of a PadTensorOp's source. This is possible if each
678   /// dimension size is statically know in the source type or the result type
679   /// (or both).
680   static LogicalResult tryVectorizeCopy(PatternRewriter &rewriter,
681                                         PadTensorOp padOp, Value dest) {
682     auto sourceType = padOp.getSourceType();
683     auto resultType = padOp.getResultType();
684 
685     // Copy cannot be vectorized if pad value is non-constant and source shape
686     // is dynamic. In case of a dynamic source shape, padding must be appended
687     // by TransferReadOp, but TransferReadOp supports only constant padding.
688     auto padValue = padOp.getConstantPaddingValue();
689     if (!padValue) {
690       if (!sourceType.hasStaticShape()) return failure();
691       // Create dummy padding value.
692       auto elemType = sourceType.getElementType();
693       padValue = rewriter.create<ConstantOp>(padOp.getLoc(), elemType,
694                                              rewriter.getZeroAttr(elemType));
695     }
696 
697     SmallVector<int64_t> vecShape;
698     SmallVector<bool> readInBounds;
699     SmallVector<bool> writeInBounds;
700     for (unsigned i = 0; i < sourceType.getRank(); ++i) {
701       if (!sourceType.isDynamicDim(i)) {
702         vecShape.push_back(sourceType.getDimSize(i));
703         // Source shape is statically known: Neither read nor write are out-of-
704         // bounds.
705         readInBounds.push_back(true);
706         writeInBounds.push_back(true);
707       } else if (!resultType.isDynamicDim(i)) {
708         // Source shape is not statically known, but result shape is. Vectorize
709         // with size of result shape. This may be larger than the source size.
710         vecShape.push_back(resultType.getDimSize(i));
711         // Read may be out-of-bounds because the result size could be larger
712         // than the source size.
713         readInBounds.push_back(false);
714         // Write is out-of-bounds if low padding > 0.
715         writeInBounds.push_back(
716             getConstantIntValue(padOp.getMixedLowPad()[i]) ==
717             static_cast<int64_t>(0));
718       } else {
719         // Neither source nor result dim of padOp is static. Cannot vectorize
720         // the copy.
721         return failure();
722       }
723     }
724     auto vecType = VectorType::get(vecShape, sourceType.getElementType());
725 
726     // Generate TransferReadOp.
727     SmallVector<Value> readIndices(
728         vecType.getRank(), rewriter.create<ConstantIndexOp>(padOp.getLoc(), 0));
729     auto read = rewriter.create<vector::TransferReadOp>(
730         padOp.getLoc(), vecType, padOp.source(), readIndices, padValue,
731         readInBounds);
732 
733     // If `dest` is a FillOp and the TransferWriteOp would overwrite the entire
734     // tensor, write directly to the FillOp's operand.
735     if (llvm::equal(vecShape, resultType.getShape())
736         && llvm::all_of(writeInBounds, [](bool b) { return b; }))
737       if (auto fill = dest.getDefiningOp<FillOp>())
738         dest = fill.output();
739 
740     // Generate TransferWriteOp.
741     auto writeIndices = ofrToIndexValues(
742         rewriter, padOp.getLoc(), padOp.getMixedLowPad());
743     rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
744         padOp, read, dest, writeIndices, writeInBounds);
745 
746     return success();
747   }
748 };
749 
750 /// Base pattern for rewriting PadTensorOps whose result is consumed by a given
751 /// operation type OpTy.
752 template <typename OpTy>
753 struct VectorizePadTensorOpUserPattern : public OpRewritePattern<PadTensorOp> {
754   using OpRewritePattern<PadTensorOp>::OpRewritePattern;
755 
756   LogicalResult matchAndRewrite(PadTensorOp padOp,
757                                 PatternRewriter &rewriter) const final {
758     bool changed = false;
759     // Insert users in vector, because some users may be replaced/removed.
760     for (auto *user : llvm::to_vector<4>(padOp->getUsers()))
761       if (auto op = dyn_cast<OpTy>(user))
762         changed |= rewriteUser(rewriter, padOp, op).succeeded();
763     return success(changed);
764   }
765 
766  protected:
767   virtual LogicalResult rewriteUser(
768       PatternRewriter &rewriter, PadTensorOp padOp, OpTy op) const = 0;
769 };
770 
771 /// Rewrite use of PadTensorOp result in TransferReadOp. E.g.:
772 /// ```
773 /// %0 = linalg.pad_tensor %src ... : tensor<?x?xf32> to tensor<17x5xf32>
774 /// %r = vector.transfer_read %0[%c0, %c0], %cst
775 ///     {in_bounds = [true, true]} : tensor<17x5xf32>, vector<17x5xf32>
776 /// ```
777 /// is rewritten to:
778 /// ```
779 /// %r = vector.transfer_read %src[%c0, %c0], %padding
780 ///     {in_bounds = [true, true]}
781 ///     : tensor<?x?xf32>, vector<17x5xf32>
782 /// ```
783 /// Note: By restricting this pattern to in-bounds TransferReadOps, we can be
784 /// sure that the original padding value %cst was never used.
785 ///
786 /// This rewrite is possible if:
787 /// - `xferOp` has no out-of-bounds dims or mask.
788 /// - Low padding is static 0.
789 /// - Single, scalar padding value.
790 struct PadTensorOpVectorizationWithTransferReadPattern
791     : public VectorizePadTensorOpUserPattern<vector::TransferReadOp> {
792   using VectorizePadTensorOpUserPattern<vector::TransferReadOp>
793       ::VectorizePadTensorOpUserPattern;
794 
795   LogicalResult rewriteUser(PatternRewriter &rewriter, PadTensorOp padOp,
796                             vector::TransferReadOp xferOp) const override {
797     // Low padding must be static 0.
798     if (!padOp.hasZeroLowPad()) return failure();
799     // Pad value must be a constant.
800     auto padValue = padOp.getConstantPaddingValue();
801     if (!padValue) return failure();
802     // Padding value of existing `xferOp` is unused.
803     if (xferOp.hasOutOfBoundsDim() || xferOp.mask()) return failure();
804 
805     rewriter.updateRootInPlace(xferOp, [&]() {
806       SmallVector<bool> inBounds(xferOp.getVectorType().getRank(), false);
807       xferOp->setAttr(xferOp.getInBoundsAttrName(),
808                       rewriter.getBoolArrayAttr(inBounds));
809       xferOp.sourceMutable().assign(padOp.source());
810       xferOp.paddingMutable().assign(padValue);
811     });
812 
813     return success();
814   }
815 };
816 
817 /// Rewrite use of PadTensorOp result in TransferWriteOp.
818 /// This pattern rewrites TransferWriteOps that write to a padded tensor value,
819 /// where the same amount of padding is immediately removed again after the
820 /// write. In such cases, the TransferWriteOp can write to the non-padded tensor
821 /// value and apply out-of-bounds masking. E.g.:
822 /// ```
823 /// %0 = tensor.extract_slice ...[...] [%s0, %s1] [1, 1]
824 ///     : tensor<...> to tensor<?x?xf32>
825 /// %1 = linalg.pad_tensor %0 ... : tensor<?x?xf32> to tensor<17x5xf32>
826 /// %2 = vector.transfer_write %vec, %1[...]
827 ///     : vector<17x5xf32>, tensor<17x5xf32>
828 /// %r = tensor.extract_slice %2[0, 0] [%s0, %s1] [1, 1]
829 ///     : tensor<17x5xf32> to tensor<?x?xf32>
830 /// ```
831 /// is rewritten to:
832 /// ```
833 /// %0 = tensor.extract_slice ...[...] [%s0, %s1] [1, 1]
834 ///     : tensor<...> to tensor<?x?xf32>
835 /// %r = vector.transfer_write %vec, %0[...] : vector<17x5xf32>, tensor<?x?xf32>
836 /// ```
837 /// Note: It is important that the ExtractSliceOp %r resizes the result of the
838 /// TransferWriteOp to the same size as the input of the TensorPadOp (or an even
839 /// smaller size). Otherwise, %r's new (dynamic) dimensions would differ from
840 /// %r's old dimensions.
841 ///
842 /// This rewrite is possible if:
843 /// - Low padding is static 0.
844 /// - `xferOp` has exactly one use, which is an ExtractSliceOp. This
845 ///   ExtractSliceOp trims the same amount of padding that was added beforehand.
846 /// - Single, scalar padding value.
847 struct PadTensorOpVectorizationWithTransferWritePattern
848     : public VectorizePadTensorOpUserPattern<vector::TransferWriteOp> {
849   using VectorizePadTensorOpUserPattern<vector::TransferWriteOp>
850       ::VectorizePadTensorOpUserPattern;
851 
852   LogicalResult rewriteUser(PatternRewriter &rewriter, PadTensorOp padOp,
853                             vector::TransferWriteOp xferOp) const override {
854     // Low padding must be static 0.
855     if (!padOp.hasZeroLowPad()) return failure();
856     // Pad value must be a constant.
857     auto padValue = padOp.getConstantPaddingValue();
858     if (!padValue) return failure();
859     // TransferWriteOp result must be directly consumed by an ExtractSliceOp.
860     if (!xferOp->hasOneUse()) return failure();
861     auto trimPadding = dyn_cast<tensor::ExtractSliceOp>(*xferOp->user_begin());
862     if (!trimPadding) return failure();
863     // Only static zero offsets supported when trimming padding.
864     if (!trimPadding.hasZeroOffset()) return failure();
865     // trimPadding must remove the amount of padding that was added earlier.
866     if (!hasSameTensorSize(padOp.source(), trimPadding)) return failure();
867 
868     // Insert the new TransferWriteOp at position of the old TransferWriteOp.
869     rewriter.setInsertionPoint(xferOp);
870 
871     SmallVector<bool> inBounds(xferOp.getVectorType().getRank(), false);
872     auto newXferOp = rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
873         xferOp, padOp.source().getType(), xferOp.vector(), padOp.source(),
874         xferOp.indices(), xferOp.permutation_mapAttr(), xferOp.mask(),
875         rewriter.getBoolArrayAttr(inBounds));
876     rewriter.replaceOp(trimPadding, newXferOp->getResult(0));
877 
878     return success();
879   }
880 
881   /// Check if `beforePadding` and `afterTrimming` have the same tensor size,
882   /// i.e., same dimensions.
883   ///
884   /// Dimensions may be static, dynamic or mix of both. In case of dynamic
885   /// dimensions, this function tries to infer the (static) tensor size by
886   /// looking at the defining op and utilizing op-specific knowledge.
887   ///
888   /// This is a conservative analysis. In case equal tensor sizes cannot be
889   /// proven statically, this analysis returns `false` even though the tensor
890   /// sizes may turn out to be equal at runtime.
891   bool hasSameTensorSize(Value beforePadding,
892                          tensor::ExtractSliceOp afterTrimming) const {
893     // If the input to PadTensorOp is a CastOp, try with with both CastOp result
894     // and CastOp operand.
895     if (auto castOp = beforePadding.getDefiningOp<tensor::CastOp>())
896       if (hasSameTensorSize(castOp.source(), afterTrimming)) return true;
897 
898     auto t1 = beforePadding.getType().dyn_cast<RankedTensorType>();
899     auto t2 = afterTrimming.getType().dyn_cast<RankedTensorType>();
900     // Only RankedTensorType supported.
901     if (!t1 || !t2) return false;
902     // Rank of both values must be the same.
903     if (t1.getRank() != t2.getRank()) return false;
904 
905     // All static dimensions must be the same. Mixed cases (e.g., dimension
906     // static in `t1` but dynamic in `t2`) are not supported.
907     for (unsigned i = 0; i < t1.getRank(); ++i) {
908       if (t1.isDynamicDim(i) != t2.isDynamicDim(i))
909         return false;
910       if (!t1.isDynamicDim(i) && t1.getDimSize(i) != t2.getDimSize(i))
911         return false;
912     }
913 
914     // Nothing more to check if all dimensions are static.
915     if (t1.getNumDynamicDims() == 0) return true;
916 
917     // All dynamic sizes must be the same. The only supported case at the moment
918     // is when `beforePadding` is an ExtractSliceOp (or a cast thereof).
919 
920     // Apart from CastOp, only ExtractSliceOp is supported.
921     auto beforeSlice = beforePadding.getDefiningOp<tensor::ExtractSliceOp>();
922     if (!beforeSlice)
923       return false;
924 
925     assert(static_cast<size_t>(t1.getRank()) ==
926            beforeSlice.getMixedSizes().size());
927     assert(static_cast<size_t>(t2.getRank())
928            == afterTrimming.getMixedSizes().size());
929 
930     for (unsigned i = 0; i < t1.getRank(); ++i) {
931       // Skip static dimensions.
932       if (!t1.isDynamicDim(i)) continue;
933       auto size1 = beforeSlice.getMixedSizes()[i];
934       auto size2 = afterTrimming.getMixedSizes()[i];
935 
936       // Case 1: Same value or same constant int.
937       if (isEqualConstantIntOrValue(size1, size2)) continue;
938 
939       // Other cases: Take a deeper look at defining ops of values.
940       auto v1 = size1.dyn_cast<Value>();
941       auto v2 = size2.dyn_cast<Value>();
942       if (!v1 || !v2) return false;
943 
944       // Case 2: Both values are identical AffineMinOps. (Should not happen if
945       // CSE is run.)
946       auto minOp1 = v1.getDefiningOp<AffineMinOp>();
947       auto minOp2 = v2.getDefiningOp<AffineMinOp>();
948       if (minOp1 && minOp2 && minOp1.getAffineMap() == minOp2.getAffineMap()
949           && minOp1.operands() == minOp2.operands()) continue;
950 
951       // Add additional cases as needed.
952     }
953 
954     // All tests passed.
955     return true;
956   }
957 };
958 
959 /// Rewrite use of PadTensorOp result in InsertSliceOp. E.g.:
960 /// ```
961 /// %0 = linalg.pad_tensor %src ... : tensor<?x?xf32> to tensor<17x5xf32>
962 /// %r = tensor.insert_slice %0
963 ///     into %dest[%a, %b, 0, 0] [1, 1, 17, 5] [1, 1, 1, 1]
964 ///     : tensor<17x5xf32> into tensor<?x?x17x5xf32>
965 /// ```
966 /// is rewritten to:
967 /// ```
968 /// %0 = vector.transfer_read %src[%c0, %c0], %padding
969 ///     : tensor<?x?xf32>, vector<17x5xf32>
970 /// %r = vector.transfer_write %0, %dest[%a, %b, %c0, %c0]
971 ///     {in_bounds = [true, true]} : vector<17x5xf32>, tensor<?x?x17x5xf32>
972 /// ```
973 ///
974 /// This rewrite is possible if:
975 /// - Low padding is static 0.
976 /// - `padOp` result shape is static.
977 /// - The entire padded tensor is inserted.
978 ///   (Implies that sizes of `insertOp` are all static.)
979 /// - Only unit strides in `insertOp`.
980 /// - Single, scalar padding value.
981 struct PadTensorOpVectorizationWithInsertSlicePattern
982     : public VectorizePadTensorOpUserPattern<tensor::InsertSliceOp> {
983   using VectorizePadTensorOpUserPattern<
984       tensor::InsertSliceOp>::VectorizePadTensorOpUserPattern;
985 
986   LogicalResult rewriteUser(PatternRewriter &rewriter, PadTensorOp padOp,
987                             tensor::InsertSliceOp insertOp) const override {
988     // Low padding must be static 0.
989     if (!padOp.hasZeroLowPad()) return failure();
990     // Only unit stride supported.
991     if (!insertOp.hasUnitStride()) return failure();
992     // Pad value must be a constant.
993     auto padValue = padOp.getConstantPaddingValue();
994     if (!padValue)
995       return failure();
996     // Dynamic shapes not supported.
997     if (!padOp.result().getType().cast<ShapedType>().hasStaticShape())
998       return failure();
999 
1000     auto vecType = VectorType::get(padOp.getType().getShape(),
1001                                    padOp.getType().getElementType());
1002     unsigned vecRank = vecType.getRank();
1003     unsigned tensorRank = insertOp.getType().getRank();
1004 
1005     // Check if sizes match: Insert the entire tensor into most minor dims.
1006     // (No permutations allowed.)
1007     SmallVector<int64_t> expectedSizes(tensorRank - vecRank, 1);
1008     expectedSizes.append(vecType.getShape().begin(), vecType.getShape().end());
1009     if (!llvm::all_of(
1010             llvm::zip(insertOp.getMixedSizes(), expectedSizes), [](auto it) {
1011               return getConstantIntValue(std::get<0>(it)) == std::get<1>(it);
1012             }))
1013       return failure();
1014 
1015     // Insert the TransferReadOp and TransferWriteOp at the position of the
1016     // InsertSliceOp.
1017     rewriter.setInsertionPoint(insertOp);
1018 
1019     // Generate TransferReadOp: Read entire source tensor and add high padding.
1020     SmallVector<Value> readIndices(
1021         vecRank, rewriter.create<ConstantIndexOp>(padOp.getLoc(), 0));
1022     auto read = rewriter.create<vector::TransferReadOp>(
1023         padOp.getLoc(), vecType, padOp.source(), readIndices, padValue);
1024 
1025     // Generate TransferWriteOp: Write to InsertSliceOp's dest tensor at
1026     // specified offsets. Write is fully in-bounds because a InsertSliceOp's
1027     // source must fit into the destination at the specified offsets.
1028     auto writeIndices =
1029         ofrToIndexValues(rewriter, padOp.getLoc(), insertOp.getMixedOffsets());
1030     SmallVector<bool> inBounds(vecRank, true);
1031     rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
1032         insertOp, read, insertOp.dest(), writeIndices, inBounds);
1033 
1034     return success();
1035   }
1036 };
1037 
1038 void mlir::linalg::populatePadTensorOpVectorizationPatterns(
1039     RewritePatternSet &patterns, PatternBenefit baseBenefit) {
1040   patterns.add<GenericPadTensorOpVectorizationPattern>(
1041       patterns.getContext(), baseBenefit);
1042   // Try these specialized patterns first before resorting to the generic one.
1043   patterns.add<PadTensorOpVectorizationWithTransferReadPattern,
1044                PadTensorOpVectorizationWithTransferWritePattern,
1045                PadTensorOpVectorizationWithInsertSlicePattern>(
1046       patterns.getContext(), baseBenefit.getBenefit() + 1);
1047 }
1048 
1049 // TODO: cleanup all the convolution vectorization patterns.
1050 template <class ConvOp, int N>
1051 LogicalResult ConvOpVectorization<ConvOp, N>::matchAndRewrite(
1052     ConvOp op, PatternRewriter &rewriter) const {
1053   Location loc = op.getLoc();
1054   MLIRContext *context = op.getContext();
1055 
1056   OpOperand *input = op.getInputOperand(0);
1057   OpOperand *kernel = op.getInputOperand(1);
1058   OpOperand *output = op.getOutputOperand(0);
1059   ArrayRef<int64_t> inShape = op.getShape(input);
1060   ArrayRef<int64_t> kShape = op.getShape(kernel);
1061 
1062   if (llvm::any_of(inShape, ShapedType::isDynamic) ||
1063       llvm::any_of(kShape, ShapedType::isDynamic))
1064     return failure();
1065 
1066   SmallVector<AffineExpr, 4> mapping;
1067   SmallVector<int64_t, 4> vectorDims;
1068   // Fail to apply when the size of not vectorized dimension is not 1.
1069   for (unsigned i = 0; i < N; i++) {
1070     if (!mask[i] && (inShape[i] != 1 || kShape[i] != 1))
1071       return failure();
1072 
1073     if (mask[i] && inShape[i] != kShape[i])
1074       return failure();
1075 
1076     if (mask[i]) {
1077       mapping.push_back(getAffineDimExpr(i, context));
1078       vectorDims.push_back(inShape[i]);
1079     }
1080   }
1081 
1082   int64_t rank = op.getRank(input);
1083   int64_t numDims = mapping.size();
1084   Type elemType = getElementTypeOrSelf(input->get());
1085 
1086   auto map = AffineMap::get(rank, 0, mapping, context);
1087   SmallVector<Value, 4> zeros(rank, rewriter.create<ConstantIndexOp>(loc, 0));
1088   auto vecType = VectorType::get(vectorDims, elemType);
1089 
1090   auto inputVec = rewriter.create<vector::TransferReadOp>(
1091       loc, vecType, input->get(), zeros, map);
1092   auto kernelVec = rewriter.create<vector::TransferReadOp>(
1093       loc, vecType, kernel->get(), zeros, map);
1094 
1095   auto acc = rewriter.create<ConstantOp>(loc, elemType,
1096                                          rewriter.getZeroAttr(elemType));
1097 
1098   std::array<AffineMap, 3> indexingMaps{
1099       AffineMap::getMultiDimIdentityMap(numDims, context),
1100       AffineMap::getMultiDimIdentityMap(numDims, context),
1101       AffineMap::get(numDims, 0, {}, context)};
1102 
1103   std::vector<StringRef> iteratorTypes(numDims, "reduction");
1104 
1105   auto result = rewriter.create<vector::ContractionOp>(
1106       loc, inputVec, kernelVec, acc,
1107       rewriter.getAffineMapArrayAttr(indexingMaps),
1108       rewriter.getStrArrayAttr(iteratorTypes));
1109 
1110   rewriter.create<memref::StoreOp>(loc, result, output->get(),
1111                                    ValueRange(zeros));
1112   rewriter.eraseOp(op);
1113   return success();
1114 }
1115 
1116 using ConvOpConst = ConvOpVectorization<Conv1DOp, 1>;
1117 
1118 /// Inserts tiling, promotion and vectorization pattern for ConvOp
1119 /// conversion into corresponding pattern lists.
1120 template <typename ConvOp, unsigned N>
1121 static void populateVectorizationPatterns(
1122     RewritePatternSet &tilingPatterns, RewritePatternSet &promotionPatterns,
1123     RewritePatternSet &vectorizationPatterns, ArrayRef<int64_t> tileSizes) {
1124   auto *context = tilingPatterns.getContext();
1125   if (tileSizes.size() < N)
1126     return;
1127 
1128   constexpr static StringRef kTiledMarker = "TILED";
1129   constexpr static StringRef kPromotedMarker = "PROMOTED";
1130   tilingPatterns.add<LinalgTilingPattern<ConvOp>>(
1131       context, LinalgTilingOptions().setTileSizes(tileSizes),
1132       LinalgTransformationFilter(ArrayRef<Identifier>{},
1133                                  Identifier::get(kTiledMarker, context)));
1134 
1135   promotionPatterns.add<LinalgPromotionPattern<ConvOp>>(
1136       context, LinalgPromotionOptions().setUseFullTileBuffersByDefault(true),
1137       LinalgTransformationFilter(Identifier::get(kTiledMarker, context),
1138                                  Identifier::get(kPromotedMarker, context)));
1139 
1140   SmallVector<bool, 4> mask(N);
1141   int offset = tileSizes.size() - N;
1142   std::transform(tileSizes.begin() + offset, tileSizes.end(), mask.begin(),
1143                  [](int64_t i) -> bool { return i > 1; });
1144 
1145   vectorizationPatterns.add<ConvOpVectorization<ConvOp, N>>(context, mask);
1146 }
1147 
1148 void mlir::linalg::populateConvVectorizationPatterns(
1149     MLIRContext *context, SmallVectorImpl<RewritePatternSet> &patterns,
1150     ArrayRef<int64_t> tileSizes) {
1151   RewritePatternSet tiling(context);
1152   RewritePatternSet promotion(context);
1153   RewritePatternSet vectorization(context);
1154   populateVectorizationPatterns<Conv1DOp, 1>(tiling, promotion, vectorization,
1155                                              tileSizes);
1156 
1157   populateVectorizationPatterns<Conv2DOp, 2>(tiling, promotion, vectorization,
1158                                              tileSizes);
1159 
1160   populateVectorizationPatterns<Conv3DOp, 3>(tiling, promotion, vectorization,
1161                                              tileSizes);
1162 
1163   populateVectorizationPatterns<Conv1DNwcWcfOp, 3>(tiling, promotion,
1164                                                    vectorization, tileSizes);
1165 
1166   populateVectorizationPatterns<Conv2DNhwcHwcfOp, 4>(tiling, promotion,
1167                                                      vectorization, tileSizes);
1168 
1169   populateVectorizationPatterns<Conv3DNdhwcDhwcfOp, 5>(
1170       tiling, promotion, vectorization, tileSizes);
1171 
1172   patterns.push_back(std::move(tiling));
1173   patterns.push_back(std::move(promotion));
1174   patterns.push_back(std::move(vectorization));
1175 }
1176 
1177 //----------------------------------------------------------------------------//
1178 // Forwarding patterns
1179 //----------------------------------------------------------------------------//
1180 
1181 /// Check whether there is any interleaved use of any `values` between `firstOp`
1182 /// and `secondOp`. Conservatively return `true` if any op or value is in a
1183 /// different block.
1184 static bool mayExistInterleavedUses(Operation *firstOp, Operation *secondOp,
1185                                     ValueRange values) {
1186   if (firstOp->getBlock() != secondOp->getBlock() ||
1187       !firstOp->isBeforeInBlock(secondOp)) {
1188     LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
1189                             << "interleavedUses precondition failed, firstOp: "
1190                             << *firstOp << ", second op: " << *secondOp);
1191     return true;
1192   }
1193   for (auto v : values) {
1194     for (auto &u : v.getUses()) {
1195       Operation *owner = u.getOwner();
1196       if (owner == firstOp || owner == secondOp)
1197         continue;
1198       // TODO: this is too conservative, use dominance info in the future.
1199       if (owner->getBlock() == firstOp->getBlock() &&
1200           (owner->isBeforeInBlock(firstOp) || secondOp->isBeforeInBlock(owner)))
1201         continue;
1202       LLVM_DEBUG(llvm::dbgs()
1203                  << "\n[" DEBUG_TYPE "]: "
1204                  << " found interleaved op " << *owner
1205                  << ", firstOp: " << *firstOp << ", second op: " << *secondOp);
1206       return true;
1207     }
1208   }
1209   return false;
1210 }
1211 
1212 /// Return the unique subview use of `v` if it is indeed unique, null otherwise.
1213 static memref::SubViewOp getSubViewUseIfUnique(Value v) {
1214   memref::SubViewOp subViewOp;
1215   for (auto &u : v.getUses()) {
1216     if (auto newSubViewOp = dyn_cast<memref::SubViewOp>(u.getOwner())) {
1217       if (subViewOp)
1218         return memref::SubViewOp();
1219       subViewOp = newSubViewOp;
1220     }
1221   }
1222   return subViewOp;
1223 }
1224 
1225 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
1226 /// when available.
1227 LogicalResult LinalgCopyVTRForwardingPattern::matchAndRewrite(
1228     vector::TransferReadOp xferOp, PatternRewriter &rewriter) const {
1229 
1230   // Transfer into `view`.
1231   Value viewOrAlloc = xferOp.source();
1232   if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() &&
1233       !viewOrAlloc.getDefiningOp<memref::AllocOp>())
1234     return failure();
1235 
1236   LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " << viewOrAlloc);
1237 
1238   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
1239   memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
1240   if (!subViewOp)
1241     return failure();
1242   Value subView = subViewOp.getResult();
1243   LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
1244                           << "with subView " << subView);
1245 
1246   // Find the copy into `subView` without interleaved uses.
1247   CopyOp copyOp;
1248   for (auto &u : subView.getUses()) {
1249     if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) {
1250       assert(newCopyOp.output().getType().isa<MemRefType>());
1251       if (newCopyOp.output() != subView)
1252         continue;
1253       LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
1254                               << "copy candidate " << *newCopyOp);
1255       if (mayExistInterleavedUses(newCopyOp, xferOp, {viewOrAlloc, subView}))
1256         continue;
1257       copyOp = newCopyOp;
1258       break;
1259     }
1260   }
1261   if (!copyOp)
1262     return failure();
1263   LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
1264                           << "with copy " << *copyOp);
1265 
1266   // Find the fill into `viewOrAlloc` without interleaved uses before the copy.
1267   FillOp maybeFillOp;
1268   for (auto &u : viewOrAlloc.getUses()) {
1269     if (auto newFillOp = dyn_cast<FillOp>(u.getOwner())) {
1270       assert(newFillOp.output().getType().isa<MemRefType>());
1271       if (newFillOp.output() != viewOrAlloc)
1272         continue;
1273       LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
1274                               << "fill candidate " << *newFillOp);
1275       if (mayExistInterleavedUses(newFillOp, copyOp, {viewOrAlloc, subView}))
1276         continue;
1277       maybeFillOp = newFillOp;
1278       break;
1279     }
1280   }
1281   // Ensure padding matches.
1282   if (maybeFillOp && xferOp.padding() != maybeFillOp.value())
1283     return failure();
1284   if (maybeFillOp)
1285     LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
1286                             << "with maybeFillOp " << *maybeFillOp);
1287 
1288   // `in` is the subview that linalg.copy reads. Replace it.
1289   Value in = copyOp.input();
1290 
1291   // linalg.copy + linalg.fill can be used to create a padded local buffer.
1292   // The `masked` attribute is only valid on this padded buffer.
1293   // When forwarding to vector.transfer_read, the attribute must be reset
1294   // conservatively.
1295   Value res = rewriter.create<vector::TransferReadOp>(
1296       xferOp.getLoc(), xferOp.getVectorType(), in, xferOp.indices(),
1297       xferOp.permutation_map(), xferOp.padding(), ArrayAttr());
1298 
1299   if (maybeFillOp)
1300     rewriter.eraseOp(maybeFillOp);
1301   rewriter.eraseOp(copyOp);
1302   rewriter.replaceOp(xferOp, res);
1303 
1304   return success();
1305 }
1306 
1307 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
1308 /// when available.
1309 LogicalResult LinalgCopyVTWForwardingPattern::matchAndRewrite(
1310     vector::TransferWriteOp xferOp, PatternRewriter &rewriter) const {
1311   // Transfer into `viewOrAlloc`.
1312   Value viewOrAlloc = xferOp.source();
1313   if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() &&
1314       !viewOrAlloc.getDefiningOp<memref::AllocOp>())
1315     return failure();
1316 
1317   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
1318   memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
1319   if (!subViewOp)
1320     return failure();
1321   Value subView = subViewOp.getResult();
1322 
1323   // Find the copy from `subView` without interleaved uses.
1324   CopyOp copyOp;
1325   for (auto &u : subViewOp.getResult().getUses()) {
1326     if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) {
1327       if (newCopyOp.getInputOperand(0)->get() != subView)
1328         continue;
1329       if (mayExistInterleavedUses(xferOp, newCopyOp, {viewOrAlloc, subView}))
1330         continue;
1331       copyOp = newCopyOp;
1332       break;
1333     }
1334   }
1335   if (!copyOp)
1336     return failure();
1337 
1338   // `out` is the subview copied into that we replace.
1339   assert(copyOp.output().getType().isa<MemRefType>());
1340   Value out = copyOp.output();
1341 
1342   // Forward vector.transfer into copy.
1343   // linalg.copy + linalg.fill can be used to create a padded local buffer.
1344   // The `masked` attribute is only valid on this padded buffer.
1345   // When forwarding to vector.transfer_write, the attribute must be reset
1346   // conservatively.
1347   rewriter.create<vector::TransferWriteOp>(
1348       xferOp.getLoc(), xferOp.vector(), out, xferOp.indices(),
1349       xferOp.permutation_map(), ArrayAttr());
1350 
1351   rewriter.eraseOp(copyOp);
1352   rewriter.eraseOp(xferOp);
1353 
1354   return success();
1355 }
1356