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/SliceAnalysis.h"
14 #include "mlir/Dialect/Affine/Analysis/LoopAnalysis.h"
15 #include "mlir/Dialect/Affine/IR/AffineOps.h"
16 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
17 #include "mlir/Dialect/Func/IR/FuncOps.h"
18 #include "mlir/Dialect/Linalg/Analysis/DependenceAnalysis.h"
19 #include "mlir/Dialect/Linalg/IR/Linalg.h"
20 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
21 #include "mlir/Dialect/Linalg/Utils/Utils.h"
22 #include "mlir/Dialect/Tensor/IR/Tensor.h"
23 #include "mlir/Dialect/Utils/StructuredOpsUtils.h"
24 #include "mlir/Dialect/Vector/IR/VectorOps.h"
25 #include "mlir/Dialect/Vector/Transforms/VectorTransforms.h"
26 #include "mlir/IR/AffineExpr.h"
27 #include "mlir/IR/Matchers.h"
28 #include "mlir/IR/PatternMatch.h"
29 #include "mlir/Pass/Pass.h"
30 #include "mlir/Support/LLVM.h"
31 #include "mlir/Transforms/RegionUtils.h"
32 #include "llvm/ADT/ScopeExit.h"
33 #include "llvm/ADT/Sequence.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/TypeSwitch.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <type_traits>
39 
40 using namespace mlir;
41 using namespace mlir::linalg;
42 
43 #define DEBUG_TYPE "linalg-vectorization"
44 
45 #define DBGS() (llvm::dbgs() << '[' << DEBUG_TYPE << "] ")
46 #define LDBG(X) LLVM_DEBUG(DBGS() << X)
47 
48 /// Try to vectorize `convOp` as a convolution.
49 static FailureOr<Operation *> vectorizeConvolution(OpBuilder &b,
50                                                    LinalgOp convOp);
51 
52 /// Return the unique instance of OpType in `block` if it is indeed unique.
53 /// Return null if none or more than 1 instances exist.
54 template <typename OpType>
55 static OpType getSingleOpOfType(Block &block) {
56   OpType res;
57   block.walk([&](OpType op) {
58     if (res) {
59       res = nullptr;
60       return WalkResult::interrupt();
61     }
62     res = op;
63     return WalkResult::advance();
64   });
65   return res;
66 }
67 
68 /// Given an indexing `map` coming from a LinalgOp indexing, restricted to a
69 /// projectedPermutation, compress the unused dimensions to serve as a
70 /// permutation_map for a vector transfer operation.
71 /// For example, given a linalg op such as:
72 ///
73 /// ```
74 ///   %0 = linalg.generic {
75 ///        indexing_maps = affine_map<(d0, d1, d2, d3, d4) -> (d4, d0, d2)>,
76 ///        indexing_maps = affine_map<(d0, d1, d2, d3, d4) -> (d1, d3)>
77 ///      }
78 ///     ins(%0 : tensor<2x3x4xf32>)
79 ///    outs(%1 : tensor<5x6xf32>)
80 /// ```
81 ///
82 /// the iteration domain size of the linalg op is 3x5x4x6x2. The first affine
83 /// map is reindexed to `affine_map<(d0, d1, d2) -> (d2, d0, d1)>`, the second
84 /// affine map is reindexed to `affine_map<(d0, d1) -> (d0, d1)>`.
85 static AffineMap reindexIndexingMap(AffineMap map) {
86   assert(map.isProjectedPermutation(/*allowZeroInResults=*/true) &&
87          "expected projected permutation");
88   auto res = compressUnusedDims(map);
89   assert(res.getNumDims() == res.getNumResults() &&
90          "expected reindexed map with same number of dims and results");
91   return res;
92 }
93 
94 /// Helper data structure to represent the result of vectorization.
95 /// In certain specific cases, like terminators, we do not want to propagate/
96 enum VectorizationStatus {
97   /// Op failed to vectorize.
98   Failure = 0,
99   /// Op vectorized and custom function took care of replacement logic
100   NoReplace,
101   /// Op vectorized into a new Op whose results will replace original Op's
102   /// results.
103   NewOp
104   // TODO: support values if Op vectorized to Many-Ops whose results we need to
105   // aggregate for replacement.
106 };
107 struct VectorizationResult {
108   /// Return status from vectorizing the current op.
109   enum VectorizationStatus status = VectorizationStatus::Failure;
110   /// New vectorized operation to replace the current op.
111   /// Replacement behavior is specified by `status`.
112   Operation *newOp;
113 };
114 
115 llvm::Optional<vector::CombiningKind>
116 mlir::linalg::getCombinerOpKind(Operation *combinerOp) {
117   using ::mlir::vector::CombiningKind;
118 
119   if (!combinerOp)
120     return llvm::None;
121   return llvm::TypeSwitch<Operation *, llvm::Optional<CombiningKind>>(
122              combinerOp)
123       .Case<arith::AddIOp, arith::AddFOp>(
124           [&](auto op) { return CombiningKind::ADD; })
125       .Case<arith::AndIOp>([&](auto op) { return CombiningKind::AND; })
126       .Case<arith::MaxSIOp>([&](auto op) { return CombiningKind::MAXSI; })
127       .Case<arith::MaxFOp>([&](auto op) { return CombiningKind::MAXF; })
128       .Case<arith::MinSIOp>([&](auto op) { return CombiningKind::MINSI; })
129       .Case<arith::MinFOp>([&](auto op) { return CombiningKind::MINF; })
130       .Case<arith::MulIOp, arith::MulFOp>(
131           [&](auto op) { return CombiningKind::MUL; })
132       .Case<arith::OrIOp>([&](auto op) { return CombiningKind::OR; })
133       .Case<arith::XOrIOp>([&](auto op) { return CombiningKind::XOR; })
134       .Default([&](auto op) { return llvm::None; });
135 }
136 
137 /// Check whether `outputOperand` is a reduction with a single combiner
138 /// operation. Return the combiner operation of the reduction. Return
139 /// nullptr otherwise. Multiple reduction operations would impose an
140 /// ordering between reduction dimensions and is currently unsupported in
141 /// Linalg. This limitation is motivated by the fact that e.g. min(max(X)) !=
142 /// max(min(X))
143 // TODO: use in LinalgOp verification, there is a circular dependency atm.
144 static Operation *matchLinalgReduction(OpOperand *outputOperand) {
145   auto linalgOp = cast<LinalgOp>(outputOperand->getOwner());
146   unsigned outputPos =
147       outputOperand->getOperandNumber() - linalgOp.getNumInputs();
148   // Only single combiner operations are supported for now.
149   SmallVector<Operation *, 4> combinerOps;
150   if (!matchReduction(linalgOp.getRegionOutputArgs(), outputPos, combinerOps) ||
151       combinerOps.size() != 1)
152     return nullptr;
153 
154   // Return the combiner operation.
155   return combinerOps[0];
156 }
157 
158 /// Broadcast `value` to a vector of `shape` if possible. Return value
159 /// otherwise.
160 static Value broadcastIfNeeded(OpBuilder &b, Value value,
161                                ArrayRef<int64_t> shape) {
162   // If no shape to broadcast to, just return `value`.
163   if (shape.empty())
164     return value;
165   VectorType targetVectorType =
166       VectorType::get(shape, getElementTypeOrSelf(value));
167   if (vector::isBroadcastableTo(value.getType(), targetVectorType) !=
168       vector::BroadcastableToResult::Success)
169     return value;
170   Location loc = b.getInsertionPoint()->getLoc();
171   return b.createOrFold<vector::BroadcastOp>(loc, targetVectorType, value);
172 }
173 
174 /// Create MultiDimReductionOp to compute the reduction for `reductionOp`. This
175 /// assumes that `reductionOp` has two operands and one of them is the reduction
176 /// initial value.
177 static Value buildMultiDimReduce(OpBuilder &b, Operation *reduceOp,
178                                  Value valueToReduce,
179                                  const SmallVector<bool> &reductionMask) {
180   auto maybeKind = getCombinerOpKind(reduceOp);
181   assert(maybeKind && "Failed precondition: could not get reduction kind");
182   return b.create<vector::MultiDimReductionOp>(
183       reduceOp->getLoc(), valueToReduce, reductionMask, *maybeKind);
184 }
185 
186 static SmallVector<bool> getReductionMask(LinalgOp linalgOp) {
187   unsigned idx = 0;
188   SmallVector<bool> reductionMask(linalgOp.iterator_types().size(), false);
189   for (auto attr : linalgOp.iterator_types()) {
190     if (isReductionIterator(attr))
191       reductionMask[idx] = true;
192     ++idx;
193   }
194   return reductionMask;
195 }
196 
197 /// Build a vector.transfer_write of `value` into `outputOperand` at indices set
198 /// to all `0`; where `outputOperand` is an output operand of the LinalgOp
199 /// currently being vectorized. If `dest` has null rank, build an memref.store.
200 /// Return the produced value or null if no value is produced.
201 static Value buildVectorWrite(OpBuilder &b, Value value,
202                               OpOperand *outputOperand) {
203   Operation *write;
204   Location loc = value.getLoc();
205   auto linalgOp = cast<LinalgOp>(outputOperand->getOwner());
206   ArrayRef<int64_t> shape = linalgOp.getShape(outputOperand);
207   auto vectorType = VectorType::get(
208       shape, getElementTypeOrSelf(outputOperand->get().getType()));
209   if (vectorType.getRank() > 0) {
210     // 0-d case is still special: do not invert the reindexing map.
211     AffineMap map =
212         reindexIndexingMap(linalgOp.getTiedIndexingMap(outputOperand));
213     SmallVector<int64_t> transposeShape =
214         applyPermutationMap(inversePermutation(map), vectorType.getShape());
215     assert(!transposeShape.empty() && "unexpected empty transpose shape");
216     vectorType = VectorType::get(transposeShape, vectorType.getElementType());
217     SmallVector<Value> indices(linalgOp.getRank(outputOperand),
218                                b.create<arith::ConstantIndexOp>(loc, 0));
219     value = broadcastIfNeeded(b, value, vectorType.getShape());
220     write = b.create<vector::TransferWriteOp>(loc, value, outputOperand->get(),
221                                               indices, map);
222   } else {
223     if (!value.getType().isa<VectorType>())
224       value = b.create<vector::BroadcastOp>(loc, vectorType, value);
225     assert(value.getType() == vectorType && "incorrect type");
226     write = b.create<vector::TransferWriteOp>(loc, value, outputOperand->get(),
227                                               ValueRange{});
228   }
229   LDBG("vectorized op: " << *write);
230   if (!write->getResults().empty())
231     return write->getResult(0);
232   return Value();
233 }
234 
235 // Custom vectorization function type. Produce a vector form of Operation*
236 // assuming all its vectorized operands are already in the BlockAndValueMapping.
237 // Return nullptr if the Operation cannot be vectorized.
238 using CustomVectorizationHook = std::function<VectorizationResult(
239     Operation *, const BlockAndValueMapping &)>;
240 
241 /// Helper function to vectorize the terminator of a `linalgOp`. New result
242 /// vector values are appended to `newResults`. Return
243 /// VectorizationStatus::NoReplace to signal the vectorization algorithm that it
244 /// should not try to map produced operations and instead return the results
245 /// using the `newResults` vector making them available to the
246 /// vectorization algorithm for RAUW. This function is meant to be used as a
247 /// CustomVectorizationHook.
248 static VectorizationResult
249 vectorizeLinalgYield(OpBuilder &b, Operation *op,
250                      const BlockAndValueMapping &bvm, LinalgOp linalgOp,
251                      SmallVectorImpl<Value> &newResults) {
252   auto yieldOp = dyn_cast<linalg::YieldOp>(op);
253   if (!yieldOp)
254     return VectorizationResult{VectorizationStatus::Failure, nullptr};
255   for (const auto &outputs : llvm::enumerate(yieldOp.values())) {
256     // TODO: Scan for an opportunity for reuse.
257     // TODO: use a map.
258     Value vectorValue = bvm.lookup(outputs.value());
259     Value newResult = buildVectorWrite(
260         b, vectorValue, linalgOp.getOutputOperand(outputs.index()));
261     if (newResult)
262       newResults.push_back(newResult);
263   }
264   return VectorizationResult{VectorizationStatus::NoReplace, nullptr};
265 }
266 
267 /// Helper function to vectorize the index operations of a `linalgOp`. Return
268 /// VectorizationStatus::NewOp to signal the vectorization algorithm that it
269 /// should map the produced operations. This function is meant to be used as a
270 /// CustomVectorizationHook.
271 static VectorizationResult vectorizeLinalgIndex(OpBuilder &b, Operation *op,
272                                                 LinalgOp linalgOp) {
273   IndexOp indexOp = dyn_cast<linalg::IndexOp>(op);
274   if (!indexOp)
275     return VectorizationResult{VectorizationStatus::Failure, nullptr};
276   auto loc = indexOp.getLoc();
277   // Compute the static loop sizes of the index op.
278   auto targetShape = linalgOp.computeStaticLoopSizes();
279   // Compute a one-dimensional index vector for the index op dimension.
280   SmallVector<int64_t> constantSeq =
281       llvm::to_vector<16>(llvm::seq<int64_t>(0, targetShape[indexOp.dim()]));
282   auto constantOp =
283       b.create<arith::ConstantOp>(loc, b.getIndexVectorAttr(constantSeq));
284   // Return the one-dimensional index vector if it lives in the trailing
285   // dimension of the iteration space since the vectorization algorithm in this
286   // case can handle the broadcast.
287   if (indexOp.dim() == targetShape.size() - 1)
288     return VectorizationResult{VectorizationStatus::NewOp, constantOp};
289   // Otherwise permute the targetShape to move the index dimension last,
290   // broadcast the one-dimensional index vector to the permuted shape, and
291   // finally transpose the broadcasted index vector to undo the permutation.
292   std::swap(targetShape[indexOp.dim()], targetShape.back());
293   auto broadCastOp = b.create<vector::BroadcastOp>(
294       loc, VectorType::get(targetShape, b.getIndexType()), constantOp);
295   SmallVector<int64_t> transposition =
296       llvm::to_vector<16>(llvm::seq<int64_t>(0, linalgOp.getNumLoops()));
297   std::swap(transposition.back(), transposition[indexOp.dim()]);
298   auto transposeOp =
299       b.create<vector::TransposeOp>(loc, broadCastOp, transposition);
300   return VectorizationResult{VectorizationStatus::NewOp, transposeOp};
301 }
302 
303 /// Emit reduction operations if the shapes of the value to reduce is different
304 /// that the result shape.
305 static Operation *reduceIfNeeded(OpBuilder &b, LinalgOp linalgOp, Operation *op,
306                                  Value reduceValue, Value initialValue,
307                                  const BlockAndValueMapping &bvm) {
308   Value reduceVec = bvm.lookup(reduceValue);
309   Value outputVec = bvm.lookup(initialValue);
310   auto reduceType = reduceVec.getType().dyn_cast<VectorType>();
311   auto outputType = outputVec.getType().dyn_cast<VectorType>();
312   // Reduce only if needed as the value may already have been reduce for
313   // contraction vectorization.
314   if (!reduceType ||
315       (outputType && reduceType.getShape() == outputType.getShape()))
316     return nullptr;
317   SmallVector<bool> reductionMask = getReductionMask(linalgOp);
318   Value reduce = buildMultiDimReduce(b, op, reduceVec, reductionMask);
319   return b.create(op->getLoc(), op->getName().getIdentifier(),
320                   /*operands=*/{reduce, outputVec}, reduce.getType(),
321                   op->getAttrs());
322 }
323 
324 /// Generic vectorization for a single operation `op`, given already vectorized
325 /// operands carried by `bvm`. Vectorization occurs as follows:
326 ///   1. Try to apply any of the `customVectorizationHooks` and return its
327 ///   result on success.
328 ///   2. Clone any constant in the current scope without vectorization: each
329 ///   consumer of the constant will later determine the shape to which the
330 ///   constant needs to be broadcast to.
331 ///   3. Fail on any remaining non `ElementwiseMappable` op. It is the purpose
332 ///   of the `customVectorizationHooks` to cover such cases.
333 ///   4. Clone `op` in vector form to a vector of shape prescribed by the first
334 ///   operand of maximal rank. Other operands have smaller rank and are
335 ///   broadcast accordingly. It is assumed this broadcast is always legal,
336 ///   otherwise, it means one of the `customVectorizationHooks` is incorrect.
337 ///
338 /// This function assumes all operands of `op` have been vectorized and are in
339 /// the `bvm` mapping. As a consequence, this function is meant to be called on
340 /// a topologically-sorted list of ops.
341 /// This function does not update `bvm` but returns a VectorizationStatus that
342 /// instructs the caller what `bvm` update needs to occur.
343 static VectorizationResult
344 vectorizeOneOp(OpBuilder &b, LinalgOp linalgOp, Operation *op,
345                const BlockAndValueMapping &bvm,
346                ArrayRef<CustomVectorizationHook> customVectorizationHooks) {
347   LDBG("vectorize op " << *op);
348 
349   // 1. Try to apply any CustomVectorizationHook.
350   if (!customVectorizationHooks.empty()) {
351     for (auto &customFunc : customVectorizationHooks) {
352       VectorizationResult result = customFunc(op, bvm);
353       if (result.status == VectorizationStatus::Failure)
354         continue;
355       return result;
356     }
357   }
358 
359   // 2. Constant ops don't get vectorized but rather broadcasted at their users.
360   // Clone so that the constant is not confined to the linalgOp block .
361   if (isa<arith::ConstantOp, func::ConstantOp>(op))
362     return VectorizationResult{VectorizationStatus::NewOp, b.clone(*op)};
363 
364   // 3. Only ElementwiseMappable are allowed in the generic vectorization.
365   if (!OpTrait::hasElementwiseMappableTraits(op))
366     return VectorizationResult{VectorizationStatus::Failure, nullptr};
367 
368   // 4 . Check if the operation is a reduction.
369   SmallVector<std::pair<Value, Value>> reductionOperands;
370   for (Value operand : op->getOperands()) {
371     auto arg = operand.dyn_cast<BlockArgument>();
372     if (!arg || arg.getArgNumber() < linalgOp.getNumInputs())
373       continue;
374     SmallVector<Operation *> reductionOps;
375     Value reduceValue = matchReduction(
376         linalgOp.getRegionOutputArgs(),
377         arg.getArgNumber() - linalgOp.getNumInputs(), reductionOps);
378     if (!reduceValue)
379       continue;
380     reductionOperands.push_back(std::make_pair(reduceValue, operand));
381   }
382   if (!reductionOperands.empty()) {
383     assert(reductionOperands.size() == 1);
384     Operation *reduceOp =
385         reduceIfNeeded(b, linalgOp, op, reductionOperands[0].first,
386                        reductionOperands[0].second, bvm);
387     if (reduceOp)
388       return VectorizationResult{VectorizationStatus::NewOp, reduceOp};
389   }
390 
391   // 5. Generic vectorization path for ElementwiseMappable ops.
392   //   a. first get the first max ranked shape.
393   SmallVector<int64_t, 4> firstMaxRankedShape;
394   for (Value operand : op->getOperands()) {
395     auto vt = bvm.lookup(operand).getType().dyn_cast<VectorType>();
396     if (vt && firstMaxRankedShape.size() < vt.getShape().size())
397       firstMaxRankedShape.assign(vt.getShape().begin(), vt.getShape().end());
398   }
399   //   b. broadcast each op if needed.
400   auto vectorizedOperands = llvm::map_range(op->getOperands(), [&](Value v) {
401     return firstMaxRankedShape.empty()
402                ? bvm.lookup(v)
403                : broadcastIfNeeded(b, bvm.lookup(v), firstMaxRankedShape);
404   });
405   //   c. for elementwise, the result is the vector with the firstMaxRankedShape
406   auto returnTypes = llvm::map_range(op->getResultTypes(), [&](Type t) {
407     return firstMaxRankedShape.empty()
408                ? t
409                : VectorType::get(firstMaxRankedShape, t);
410   });
411 
412   // Build and return the new op.
413   return VectorizationResult{
414       VectorizationStatus::NewOp,
415       b.create(op->getLoc(), op->getName().getIdentifier(),
416                llvm::to_vector<4>(vectorizedOperands),
417                llvm::to_vector<4>(returnTypes), op->getAttrs())};
418 }
419 
420 /// Generic vectorization function that rewrites the body of a `linalgOp` into
421 /// vector form. Generic vectorization proceeds as follows:
422 ///   1. Verify the `linalgOp` has one non-empty region.
423 ///   2. Values defined above the region are mapped to themselves and will be
424 ///   broadcasted on a per-need basis by their consumers.
425 ///   3. Each region argument is vectorized into a vector.transfer_read (or 0-d
426 ///   load).
427 ///   TODO: Reuse opportunities for RAR dependencies.
428 ///   4a. Register CustomVectorizationHook for YieldOp to capture the results.
429 ///   4b. Register CustomVectorizationHook for IndexOp to access the iteration
430 ///   indices.
431 ///   5. Iteratively call vectorizeOneOp on the region operations.
432 ///
433 /// When `broadcastToMaximalCommonShape` is set to true, eager broadcasting is
434 /// performed to the maximal common vector size implied by the `linalgOp`
435 /// iteration space. This eager broadcasting is introduced in the
436 /// permutation_map of the vector.transfer_read operations. The eager
437 /// broadcasting makes it trivial to detrmine where broadcast, transposes and
438 /// reductions should occur, without any bookkeeping. The tradeoff is that, in
439 /// the absence of good canonicalizations, the amount of work increases.
440 /// This is not deemed a problem as we expect canonicalizations and foldings to
441 /// aggressively clean up the useless work.
442 static LogicalResult
443 vectorizeAsLinalgGeneric(OpBuilder &b, LinalgOp linalgOp,
444                          SmallVectorImpl<Value> &newResults) {
445   Block *block = linalgOp.getBlock();
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   Location loc = linalgOp.getLoc();
464   Value zero = b.create<arith::ConstantIndexOp>(loc, 0);
465   for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands()) {
466     BlockArgument bbarg = block->getArgument(opOperand->getOperandNumber());
467     if (linalgOp.isScalar(opOperand)) {
468       bvm.map(bbarg, opOperand->get());
469       continue;
470     }
471     VectorType readType;
472     AffineMap map;
473     // TODO: can we keep this simplification?
474     // if (linalgOp.getShape(opOperand).empty()) {
475     //   readType = VectorType::get({}, bbarg.getType());
476     // } else {
477     if (opOperand->getOperandNumber() < linalgOp.getNumInputs()) {
478       map = inverseAndBroadcastProjectedPermutation(
479           linalgOp.getTiedIndexingMap(opOperand));
480       readType = VectorType::get(commonVectorShape,
481                                  getElementTypeOrSelf(opOperand->get()));
482     } else {
483       map = inversePermutation(
484           reindexIndexingMap(linalgOp.getTiedIndexingMap(opOperand)));
485       readType = VectorType::get(map.compose(linalgOp.getShape(opOperand)),
486                                  getElementTypeOrSelf(opOperand->get()));
487     }
488     // }
489 
490     auto shape = linalgOp.getShape(opOperand);
491     SmallVector<Value> indices(shape.size(), zero);
492     Value readValue = b.create<vector::TransferReadOp>(
493         loc, readType, opOperand->get(), indices, map);
494     // Not all ops support 0-d vectors, extract the scalar for now.
495     // TODO: remove this.
496     if (readValue.getType().cast<VectorType>().getRank() == 0)
497       readValue = b.create<vector::ExtractElementOp>(loc, readValue);
498 
499     LDBG("new vectorized bbarg(" << bbarg.getArgNumber() << "): " << readValue);
500     bvm.map(bbarg, readValue);
501     bvm.map(opOperand->get(), readValue);
502   }
503 
504   SmallVector<CustomVectorizationHook> hooks;
505   // 4a. Register CustomVectorizationHook for yieldOp.
506   CustomVectorizationHook vectorizeYield =
507       [&](Operation *op,
508           const BlockAndValueMapping &bvm) -> VectorizationResult {
509     return vectorizeLinalgYield(b, op, bvm, linalgOp, newResults);
510   };
511   hooks.push_back(vectorizeYield);
512 
513   // 4b. Register CustomVectorizationHook for indexOp.
514   CustomVectorizationHook vectorizeIndex =
515       [&](Operation *op,
516           const BlockAndValueMapping &bvm) -> VectorizationResult {
517     return vectorizeLinalgIndex(b, op, linalgOp);
518   };
519   hooks.push_back(vectorizeIndex);
520 
521   // 5. Iteratively call `vectorizeOneOp` to each op in the slice.
522   for (Operation &op : block->getOperations()) {
523     VectorizationResult result = vectorizeOneOp(b, linalgOp, &op, bvm, hooks);
524     if (result.status == VectorizationStatus::Failure) {
525       LDBG("failed to vectorize: " << op);
526       return failure();
527     }
528     if (result.status == VectorizationStatus::NewOp) {
529       LDBG("new vector op: " << *result.newOp;);
530       bvm.map(op.getResults(), result.newOp->getResults());
531     }
532   }
533 
534   return success();
535 }
536 
537 // TODO: probably need some extra checks for reduction followed by consumer
538 // ops that may not commute (e.g. linear reduction + non-linear instructions).
539 static LogicalResult reductionPreconditions(LinalgOp op) {
540   if (llvm::none_of(op.iterator_types(), isReductionIterator)) {
541     LDBG("reduction precondition failed: no reduction iterator");
542     return failure();
543   }
544   for (OpOperand *opOperand : op.getOutputOperands()) {
545     Operation *reduceOp = matchLinalgReduction(opOperand);
546     if (!reduceOp || !getCombinerOpKind(reduceOp)) {
547       LDBG("reduction precondition failed: reduction detection failed");
548       return failure();
549     }
550   }
551   return success();
552 }
553 
554 static LogicalResult vectorizeStaticLinalgOpPrecondition(linalg::LinalgOp op) {
555   if (isElementwise(op))
556     return success();
557   // TODO: isaConvolutionOpInterface that can also infer from generic features.
558   // But we will still need stride/dilation attributes that will be annoying to
559   // reverse-engineer...
560   if (isa<ConvolutionOpInterface>(op.getOperation()))
561     return success();
562   // TODO: the common vector shape is equal to the static loop sizes only when
563   // all indexing maps are projected permutations. For convs and stencils the
564   // logic will need to evolve.
565   if (!allIndexingsAreProjectedPermutation(op)) {
566     LDBG("precondition failed: not projected permutations");
567     return failure();
568   }
569   if (failed(reductionPreconditions(op))) {
570     LDBG("precondition failed: reduction preconditions");
571     return failure();
572   }
573   return success();
574 }
575 
576 static LogicalResult vectorizeLinalgOpPrecondition(LinalgOp linalgOp) {
577   // All types must be static shape to go to vector.
578   if (linalgOp.hasDynamicShape()) {
579     LDBG("precondition failed: dynamic shape");
580     return failure();
581   }
582   return vectorizeStaticLinalgOpPrecondition(linalgOp);
583 }
584 
585 LogicalResult mlir::linalg::vectorize(RewriterBase &rewriter,
586                                       LinalgOp linalgOp) {
587   if (failed(vectorizeLinalgOpPrecondition(linalgOp)))
588     return failure();
589 
590   SmallVector<Value> results;
591   // TODO: isaConvolutionOpInterface that can also infer from generic
592   // features. Will require stride/dilation attributes inference.
593   FailureOr<Operation *> convOr = vectorizeConvolution(rewriter, linalgOp);
594   if (succeeded(convOr)) {
595     llvm::append_range(results, (*convOr)->getResults());
596   } else {
597     if (failed(vectorizeLinalgOpPrecondition(linalgOp)))
598       return failure();
599     LDBG("Vectorize generic by broadcasting to a common shape: " << linalgOp);
600     if (failed(vectorizeAsLinalgGeneric(rewriter, linalgOp, results)))
601       return failure();
602   }
603 
604   if (!results.empty())
605     rewriter.replaceOp(linalgOp, results);
606   else
607     rewriter.eraseOp(linalgOp);
608 
609   return success();
610 }
611 
612 LogicalResult mlir::linalg::vectorizeCopy(RewriterBase &rewriter,
613                                           memref::CopyOp copyOp) {
614 
615   auto srcType = copyOp.source().getType().cast<MemRefType>();
616   auto dstType = copyOp.target().getType().cast<MemRefType>();
617   if (!srcType.hasStaticShape() || !dstType.hasStaticShape())
618     return failure();
619 
620   auto readType =
621       VectorType::get(srcType.getShape(), getElementTypeOrSelf(srcType));
622   auto writeType =
623       VectorType::get(dstType.getShape(), getElementTypeOrSelf(dstType));
624 
625   Location loc = copyOp->getLoc();
626   Value zero = rewriter.create<arith::ConstantIndexOp>(loc, 0);
627   SmallVector<Value> indices(srcType.getRank(), zero);
628 
629   Value readValue = rewriter.create<vector::TransferReadOp>(
630       loc, readType, copyOp.source(), indices,
631       rewriter.getMultiDimIdentityMap(srcType.getRank()));
632   if (readValue.getType().cast<VectorType>().getRank() == 0) {
633     readValue = rewriter.create<vector::ExtractElementOp>(loc, readValue);
634     readValue = rewriter.create<vector::BroadcastOp>(loc, writeType, readValue);
635   }
636   Operation *writeValue = rewriter.create<vector::TransferWriteOp>(
637       loc, readValue, copyOp.target(), indices,
638       rewriter.getMultiDimIdentityMap(srcType.getRank()));
639   rewriter.replaceOp(copyOp, writeValue->getResults());
640   return success();
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.
653 /// IntegerAttrs are converted to ConstantIndexOps. Other attribute types are
654 /// not supported.
655 static SmallVector<Value> ofrToIndexValues(OpBuilder &builder, Location loc,
656                                            ArrayRef<OpFoldResult> ofrs) {
657   SmallVector<Value> result;
658   llvm::for_each(ofrs, [&](auto o) {
659     if (auto val = o.template dyn_cast<Value>()) {
660       result.push_back(val);
661     } else {
662       result.push_back(builder.create<arith::ConstantIndexOp>(
663           loc, getIntFromAttr(o.template get<Attribute>())));
664     }
665   });
666   return result;
667 }
668 
669 /// Rewrite a tensor::PadOp into a sequence of InitTensorOp, FillOp and
670 /// InsertSliceOp. For now, only constant padding values are supported.
671 /// If there is enough static type information, TransferReadOps and
672 /// TransferWriteOps may be generated instead of InsertSliceOps.
673 struct GenericPadOpVectorizationPattern : public GeneralizePadOpPattern {
674   GenericPadOpVectorizationPattern(MLIRContext *context,
675                                    PatternBenefit benefit = 1)
676       : GeneralizePadOpPattern(context, tryVectorizeCopy, benefit) {}
677   /// Vectorize the copying of a tensor::PadOp's source. This is possible if
678   /// each dimension size is statically know in the source type or the result
679   /// type (or both).
680   static LogicalResult tryVectorizeCopy(PatternRewriter &rewriter,
681                                         tensor::PadOp 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())
691         return failure();
692       // Create dummy padding value.
693       auto elemType = sourceType.getElementType();
694       padValue = rewriter.create<arith::ConstantOp>(
695           padOp.getLoc(), elemType, rewriter.getZeroAttr(elemType));
696     }
697 
698     SmallVector<int64_t> vecShape;
699     SmallVector<bool> readInBounds;
700     SmallVector<bool> writeInBounds;
701     for (unsigned i = 0; i < sourceType.getRank(); ++i) {
702       if (!sourceType.isDynamicDim(i)) {
703         vecShape.push_back(sourceType.getDimSize(i));
704         // Source shape is statically known: Neither read nor write are
705         // out-of- bounds.
706         readInBounds.push_back(true);
707         writeInBounds.push_back(true);
708       } else if (!resultType.isDynamicDim(i)) {
709         // Source shape is not statically known, but result shape is.
710         // Vectorize with size of result shape. This may be larger than the
711         // source size.
712         vecShape.push_back(resultType.getDimSize(i));
713         // Read may be out-of-bounds because the result size could be larger
714         // than the source size.
715         readInBounds.push_back(false);
716         // Write is out-of-bounds if low padding > 0.
717         writeInBounds.push_back(
718             getConstantIntValue(padOp.getMixedLowPad()[i]) ==
719             static_cast<int64_t>(0));
720       } else {
721         // Neither source nor result dim of padOp is static. Cannot vectorize
722         // the copy.
723         return failure();
724       }
725     }
726     auto vecType = VectorType::get(vecShape, sourceType.getElementType());
727 
728     // Generate TransferReadOp.
729     SmallVector<Value> readIndices(
730         vecType.getRank(),
731         rewriter.create<arith::ConstantIndexOp>(padOp.getLoc(), 0));
732     auto read = rewriter.create<vector::TransferReadOp>(
733         padOp.getLoc(), vecType, padOp.source(), readIndices, padValue,
734         ArrayRef<bool>{readInBounds});
735 
736     // If `dest` is a FillOp and the TransferWriteOp would overwrite the
737     // entire tensor, write directly to the FillOp's operand.
738     if (llvm::equal(vecShape, resultType.getShape()) &&
739         llvm::all_of(writeInBounds, [](bool b) { return b; }))
740       if (auto fill = dest.getDefiningOp<FillOp>())
741         dest = fill.output();
742 
743     // Generate TransferWriteOp.
744     auto writeIndices =
745         ofrToIndexValues(rewriter, padOp.getLoc(), padOp.getMixedLowPad());
746     rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
747         padOp, read, dest, writeIndices, ArrayRef<bool>{writeInBounds});
748 
749     return success();
750   }
751 };
752 
753 /// Base pattern for rewriting tensor::PadOps whose result is consumed by a
754 /// given operation type OpTy.
755 template <typename OpTy>
756 struct VectorizePadOpUserPattern : public OpRewritePattern<tensor::PadOp> {
757   using OpRewritePattern<tensor::PadOp>::OpRewritePattern;
758 
759   LogicalResult matchAndRewrite(tensor::PadOp padOp,
760                                 PatternRewriter &rewriter) const final {
761     bool changed = false;
762     // Insert users in vector, because some users may be replaced/removed.
763     for (auto *user : llvm::to_vector<4>(padOp->getUsers()))
764       if (auto op = dyn_cast<OpTy>(user))
765         changed |= rewriteUser(rewriter, padOp, op).succeeded();
766     return success(changed);
767   }
768 
769 protected:
770   virtual LogicalResult rewriteUser(PatternRewriter &rewriter,
771                                     tensor::PadOp padOp, OpTy op) const = 0;
772 };
773 
774 /// Rewrite use of tensor::PadOp result in TransferReadOp. E.g.:
775 /// ```
776 /// %0 = tensor.pad %src ... : tensor<?x?xf32> to tensor<17x5xf32>
777 /// %r = vector.transfer_read %0[%c0, %c0], %cst
778 ///     {in_bounds = [true, true]} : tensor<17x5xf32>, vector<17x5xf32>
779 /// ```
780 /// is rewritten to:
781 /// ```
782 /// %r = vector.transfer_read %src[%c0, %c0], %padding
783 ///     {in_bounds = [true, true]}
784 ///     : tensor<?x?xf32>, vector<17x5xf32>
785 /// ```
786 /// Note: By restricting this pattern to in-bounds TransferReadOps, we can be
787 /// sure that the original padding value %cst was never used.
788 ///
789 /// This rewrite is possible if:
790 /// - `xferOp` has no out-of-bounds dims or mask.
791 /// - Low padding is static 0.
792 /// - Single, scalar padding value.
793 struct PadOpVectorizationWithTransferReadPattern
794     : public VectorizePadOpUserPattern<vector::TransferReadOp> {
795   using VectorizePadOpUserPattern<
796       vector::TransferReadOp>::VectorizePadOpUserPattern;
797 
798   LogicalResult rewriteUser(PatternRewriter &rewriter, tensor::PadOp padOp,
799                             vector::TransferReadOp xferOp) const override {
800     // Low padding must be static 0.
801     if (!padOp.hasZeroLowPad())
802       return failure();
803     // Pad value must be a constant.
804     auto padValue = padOp.getConstantPaddingValue();
805     if (!padValue)
806       return failure();
807     // Padding value of existing `xferOp` is unused.
808     if (xferOp.hasOutOfBoundsDim() || xferOp.getMask())
809       return failure();
810 
811     rewriter.updateRootInPlace(xferOp, [&]() {
812       SmallVector<bool> inBounds(xferOp.getVectorType().getRank(), false);
813       xferOp->setAttr(xferOp.getInBoundsAttrName(),
814                       rewriter.getBoolArrayAttr(inBounds));
815       xferOp.getSourceMutable().assign(padOp.source());
816       xferOp.getPaddingMutable().assign(padValue);
817     });
818 
819     return success();
820   }
821 };
822 
823 /// Rewrite use of tensor::PadOp result in TransferWriteOp.
824 /// This pattern rewrites TransferWriteOps that write to a padded tensor
825 /// value, where the same amount of padding is immediately removed again after
826 /// the write. In such cases, the TransferWriteOp can write to the non-padded
827 /// tensor value and apply out-of-bounds masking. E.g.:
828 /// ```
829 /// %0 = tensor.extract_slice ...[...] [%s0, %s1] [1, 1]
830 ///     : tensor<...> to tensor<?x?xf32>
831 /// %1 = tensor.pad %0 ... : tensor<?x?xf32> to tensor<17x5xf32>
832 /// %2 = vector.transfer_write %vec, %1[...]
833 ///     : vector<17x5xf32>, tensor<17x5xf32>
834 /// %r = tensor.extract_slice %2[0, 0] [%s0, %s1] [1, 1]
835 ///     : tensor<17x5xf32> to tensor<?x?xf32>
836 /// ```
837 /// is rewritten to:
838 /// ```
839 /// %0 = tensor.extract_slice ...[...] [%s0, %s1] [1, 1]
840 ///     : tensor<...> to tensor<?x?xf32>
841 /// %r = vector.transfer_write %vec, %0[...] : vector<17x5xf32>,
842 /// tensor<?x?xf32>
843 /// ```
844 /// Note: It is important that the ExtractSliceOp %r resizes the result of the
845 /// TransferWriteOp to the same size as the input of the TensorPadOp (or an
846 /// even smaller size). Otherwise, %r's new (dynamic) dimensions would differ
847 /// from %r's old dimensions.
848 ///
849 /// This rewrite is possible if:
850 /// - Low padding is static 0.
851 /// - `xferOp` has exactly one use, which is an ExtractSliceOp. This
852 ///   ExtractSliceOp trims the same amount of padding that was added
853 ///   beforehand.
854 /// - Single, scalar padding value.
855 struct PadOpVectorizationWithTransferWritePattern
856     : public VectorizePadOpUserPattern<vector::TransferWriteOp> {
857   using VectorizePadOpUserPattern<
858       vector::TransferWriteOp>::VectorizePadOpUserPattern;
859 
860   LogicalResult rewriteUser(PatternRewriter &rewriter, tensor::PadOp padOp,
861                             vector::TransferWriteOp xferOp) const override {
862     // TODO: support 0-d corner case.
863     if (xferOp.getTransferRank() == 0)
864       return failure();
865 
866     // Low padding must be static 0.
867     if (!padOp.hasZeroLowPad())
868       return failure();
869     // Pad value must be a constant.
870     auto padValue = padOp.getConstantPaddingValue();
871     if (!padValue)
872       return failure();
873     // TransferWriteOp result must be directly consumed by an ExtractSliceOp.
874     if (!xferOp->hasOneUse())
875       return failure();
876     auto trimPadding = dyn_cast<tensor::ExtractSliceOp>(*xferOp->user_begin());
877     if (!trimPadding)
878       return failure();
879     // Only static zero offsets supported when trimming padding.
880     if (!trimPadding.hasZeroOffset())
881       return failure();
882     // trimPadding must remove the amount of padding that was added earlier.
883     if (!hasSameTensorSize(padOp.source(), trimPadding))
884       return failure();
885 
886     // Insert the new TransferWriteOp at position of the old TransferWriteOp.
887     rewriter.setInsertionPoint(xferOp);
888 
889     SmallVector<bool> inBounds(xferOp.getVectorType().getRank(), false);
890     auto newXferOp = rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
891         xferOp, padOp.source().getType(), xferOp.getVector(), padOp.source(),
892         xferOp.getIndices(), xferOp.getPermutationMapAttr(), xferOp.getMask(),
893         rewriter.getBoolArrayAttr(inBounds));
894     rewriter.replaceOp(trimPadding, newXferOp->getResult(0));
895 
896     return success();
897   }
898 
899   /// Check if `beforePadding` and `afterTrimming` have the same tensor size,
900   /// i.e., same dimensions.
901   ///
902   /// Dimensions may be static, dynamic or mix of both. In case of dynamic
903   /// dimensions, this function tries to infer the (static) tensor size by
904   /// looking at the defining op and utilizing op-specific knowledge.
905   ///
906   /// This is a conservative analysis. In case equal tensor sizes cannot be
907   /// proven statically, this analysis returns `false` even though the tensor
908   /// sizes may turn out to be equal at runtime.
909   bool hasSameTensorSize(Value beforePadding,
910                          tensor::ExtractSliceOp afterTrimming) const {
911     // If the input to tensor::PadOp is a CastOp, try with with both CastOp
912     // result and CastOp operand.
913     if (auto castOp = beforePadding.getDefiningOp<tensor::CastOp>())
914       if (hasSameTensorSize(castOp.source(), afterTrimming))
915         return true;
916 
917     auto t1 = beforePadding.getType().dyn_cast<RankedTensorType>();
918     auto t2 = afterTrimming.getType().dyn_cast<RankedTensorType>();
919     // Only RankedTensorType supported.
920     if (!t1 || !t2)
921       return false;
922     // Rank of both values must be the same.
923     if (t1.getRank() != t2.getRank())
924       return false;
925 
926     // All static dimensions must be the same. Mixed cases (e.g., dimension
927     // static in `t1` but dynamic in `t2`) are not supported.
928     for (unsigned i = 0; i < t1.getRank(); ++i) {
929       if (t1.isDynamicDim(i) != t2.isDynamicDim(i))
930         return false;
931       if (!t1.isDynamicDim(i) && t1.getDimSize(i) != t2.getDimSize(i))
932         return false;
933     }
934 
935     // Nothing more to check if all dimensions are static.
936     if (t1.getNumDynamicDims() == 0)
937       return true;
938 
939     // All dynamic sizes must be the same. The only supported case at the
940     // moment is when `beforePadding` is an ExtractSliceOp (or a cast
941     // thereof).
942 
943     // Apart from CastOp, only ExtractSliceOp is supported.
944     auto beforeSlice = beforePadding.getDefiningOp<tensor::ExtractSliceOp>();
945     if (!beforeSlice)
946       return false;
947 
948     assert(static_cast<size_t>(t1.getRank()) ==
949            beforeSlice.getMixedSizes().size());
950     assert(static_cast<size_t>(t2.getRank()) ==
951            afterTrimming.getMixedSizes().size());
952 
953     for (unsigned i = 0; i < t1.getRank(); ++i) {
954       // Skip static dimensions.
955       if (!t1.isDynamicDim(i))
956         continue;
957       auto size1 = beforeSlice.getMixedSizes()[i];
958       auto size2 = afterTrimming.getMixedSizes()[i];
959 
960       // Case 1: Same value or same constant int.
961       if (isEqualConstantIntOrValue(size1, size2))
962         continue;
963 
964       // Other cases: Take a deeper look at defining ops of values.
965       auto v1 = size1.dyn_cast<Value>();
966       auto v2 = size2.dyn_cast<Value>();
967       if (!v1 || !v2)
968         return false;
969 
970       // Case 2: Both values are identical AffineMinOps. (Should not happen if
971       // CSE is run.)
972       auto minOp1 = v1.getDefiningOp<AffineMinOp>();
973       auto minOp2 = v2.getDefiningOp<AffineMinOp>();
974       if (minOp1 && minOp2 && minOp1.getAffineMap() == minOp2.getAffineMap() &&
975           minOp1.operands() == minOp2.operands())
976         continue;
977 
978       // Add additional cases as needed.
979     }
980 
981     // All tests passed.
982     return true;
983   }
984 };
985 
986 /// Rewrite use of tensor::PadOp result in InsertSliceOp. E.g.:
987 /// ```
988 /// %0 = tensor.pad %src ... : tensor<?x?xf32> to tensor<17x5xf32>
989 /// %r = tensor.insert_slice %0
990 ///     into %dest[%a, %b, 0, 0] [1, 1, 17, 5] [1, 1, 1, 1]
991 ///     : tensor<17x5xf32> into tensor<?x?x17x5xf32>
992 /// ```
993 /// is rewritten to:
994 /// ```
995 /// %0 = vector.transfer_read %src[%c0, %c0], %padding
996 ///     : tensor<?x?xf32>, vector<17x5xf32>
997 /// %r = vector.transfer_write %0, %dest[%a, %b, %c0, %c0]
998 ///     {in_bounds = [true, true]} : vector<17x5xf32>, tensor<?x?x17x5xf32>
999 /// ```
1000 ///
1001 /// This rewrite is possible if:
1002 /// - Low padding is static 0.
1003 /// - `padOp` result shape is static.
1004 /// - The entire padded tensor is inserted.
1005 ///   (Implies that sizes of `insertOp` are all static.)
1006 /// - Only unit strides in `insertOp`.
1007 /// - Single, scalar padding value.
1008 /// - `padOp` result not used as destination.
1009 struct PadOpVectorizationWithInsertSlicePattern
1010     : public VectorizePadOpUserPattern<tensor::InsertSliceOp> {
1011   using VectorizePadOpUserPattern<
1012       tensor::InsertSliceOp>::VectorizePadOpUserPattern;
1013 
1014   LogicalResult rewriteUser(PatternRewriter &rewriter, tensor::PadOp padOp,
1015                             tensor::InsertSliceOp insertOp) const override {
1016     // Low padding must be static 0.
1017     if (!padOp.hasZeroLowPad())
1018       return failure();
1019     // Only unit stride supported.
1020     if (!insertOp.hasUnitStride())
1021       return failure();
1022     // Pad value must be a constant.
1023     auto padValue = padOp.getConstantPaddingValue();
1024     if (!padValue)
1025       return failure();
1026     // Dynamic shapes not supported.
1027     if (!padOp.result().getType().cast<ShapedType>().hasStaticShape())
1028       return failure();
1029     // Pad result not used as destination.
1030     if (insertOp.dest() == padOp.result())
1031       return failure();
1032 
1033     auto vecType = VectorType::get(padOp.getType().getShape(),
1034                                    padOp.getType().getElementType());
1035     unsigned vecRank = vecType.getRank();
1036     unsigned tensorRank = insertOp.getType().getRank();
1037 
1038     // Check if sizes match: Insert the entire tensor into most minor dims.
1039     // (No permutations allowed.)
1040     SmallVector<int64_t> expectedSizes(tensorRank - vecRank, 1);
1041     expectedSizes.append(vecType.getShape().begin(), vecType.getShape().end());
1042     if (!llvm::all_of(
1043             llvm::zip(insertOp.getMixedSizes(), expectedSizes), [](auto it) {
1044               return getConstantIntValue(std::get<0>(it)) == std::get<1>(it);
1045             }))
1046       return failure();
1047 
1048     // Insert the TransferReadOp and TransferWriteOp at the position of the
1049     // InsertSliceOp.
1050     rewriter.setInsertionPoint(insertOp);
1051 
1052     // Generate TransferReadOp: Read entire source tensor and add high
1053     // padding.
1054     SmallVector<Value> readIndices(
1055         vecRank, rewriter.create<arith::ConstantIndexOp>(padOp.getLoc(), 0));
1056     auto read = rewriter.create<vector::TransferReadOp>(
1057         padOp.getLoc(), vecType, padOp.source(), readIndices, padValue);
1058 
1059     // Generate TransferWriteOp: Write to InsertSliceOp's dest tensor at
1060     // specified offsets. Write is fully in-bounds because a InsertSliceOp's
1061     // source must fit into the destination at the specified offsets.
1062     auto writeIndices =
1063         ofrToIndexValues(rewriter, padOp.getLoc(), insertOp.getMixedOffsets());
1064     SmallVector<bool> inBounds(vecRank, true);
1065     rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
1066         insertOp, read, insertOp.dest(), writeIndices,
1067         ArrayRef<bool>{inBounds});
1068 
1069     return success();
1070   }
1071 };
1072 
1073 void mlir::linalg::populatePadOpVectorizationPatterns(
1074     RewritePatternSet &patterns, PatternBenefit baseBenefit) {
1075   patterns.add<GenericPadOpVectorizationPattern>(patterns.getContext(),
1076                                                  baseBenefit);
1077   // Try these specialized patterns first before resorting to the generic one.
1078   patterns.add<PadOpVectorizationWithTransferReadPattern,
1079                PadOpVectorizationWithTransferWritePattern,
1080                PadOpVectorizationWithInsertSlicePattern>(
1081       patterns.getContext(), baseBenefit.getBenefit() + 1);
1082 }
1083 
1084 //----------------------------------------------------------------------------//
1085 // Forwarding patterns
1086 //----------------------------------------------------------------------------//
1087 
1088 /// Check whether there is any interleaved use of any `values` between
1089 /// `firstOp` and `secondOp`. Conservatively return `true` if any op or value
1090 /// is in a different block.
1091 static bool mayExistInterleavedUses(Operation *firstOp, Operation *secondOp,
1092                                     ValueRange values) {
1093   if (firstOp->getBlock() != secondOp->getBlock() ||
1094       !firstOp->isBeforeInBlock(secondOp)) {
1095     LDBG("interleavedUses precondition failed, firstOp: "
1096          << *firstOp << ", second op: " << *secondOp);
1097     return true;
1098   }
1099   for (auto v : values) {
1100     for (auto &u : v.getUses()) {
1101       Operation *owner = u.getOwner();
1102       if (owner == firstOp || owner == secondOp)
1103         continue;
1104       // TODO: this is too conservative, use dominance info in the future.
1105       if (owner->getBlock() == firstOp->getBlock() &&
1106           (owner->isBeforeInBlock(firstOp) || secondOp->isBeforeInBlock(owner)))
1107         continue;
1108       LDBG(" found interleaved op " << *owner << ", firstOp: " << *firstOp
1109                                     << ", second op: " << *secondOp);
1110       return true;
1111     }
1112   }
1113   return false;
1114 }
1115 
1116 /// Return the unique subview use of `v` if it is indeed unique, null
1117 /// otherwise.
1118 static memref::SubViewOp getSubViewUseIfUnique(Value v) {
1119   memref::SubViewOp subViewOp;
1120   for (auto &u : v.getUses()) {
1121     if (auto newSubViewOp = dyn_cast<memref::SubViewOp>(u.getOwner())) {
1122       if (subViewOp)
1123         return memref::SubViewOp();
1124       subViewOp = newSubViewOp;
1125     }
1126   }
1127   return subViewOp;
1128 }
1129 
1130 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
1131 /// when available.
1132 LogicalResult LinalgCopyVTRForwardingPattern::matchAndRewrite(
1133     vector::TransferReadOp xferOp, PatternRewriter &rewriter) const {
1134 
1135   // TODO: support mask.
1136   if (xferOp.getMask())
1137     return failure();
1138 
1139   // Transfer into `view`.
1140   Value viewOrAlloc = xferOp.getSource();
1141   if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() &&
1142       !viewOrAlloc.getDefiningOp<memref::AllocOp>())
1143     return failure();
1144 
1145   LDBG(viewOrAlloc);
1146 
1147   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
1148   memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
1149   if (!subViewOp)
1150     return failure();
1151   Value subView = subViewOp.getResult();
1152   LDBG("with subView " << subView);
1153 
1154   // Find the copy into `subView` without interleaved uses.
1155   memref::CopyOp copyOp;
1156   for (auto &u : subView.getUses()) {
1157     if (auto newCopyOp = dyn_cast<memref::CopyOp>(u.getOwner())) {
1158       assert(newCopyOp.target().getType().isa<MemRefType>());
1159       if (newCopyOp.target() != subView)
1160         continue;
1161       LDBG("copy candidate " << *newCopyOp);
1162       if (mayExistInterleavedUses(newCopyOp, xferOp, {viewOrAlloc, subView}))
1163         continue;
1164       copyOp = newCopyOp;
1165       break;
1166     }
1167   }
1168   if (!copyOp)
1169     return failure();
1170   LDBG("with copy " << *copyOp);
1171 
1172   // Find the fill into `viewOrAlloc` without interleaved uses before the
1173   // copy.
1174   FillOp maybeFillOp;
1175   for (auto &u : viewOrAlloc.getUses()) {
1176     if (auto newFillOp = dyn_cast<FillOp>(u.getOwner())) {
1177       assert(newFillOp.output().getType().isa<MemRefType>());
1178       if (newFillOp.output() != viewOrAlloc)
1179         continue;
1180       LDBG("fill candidate " << *newFillOp);
1181       if (mayExistInterleavedUses(newFillOp, copyOp, {viewOrAlloc, subView}))
1182         continue;
1183       maybeFillOp = newFillOp;
1184       break;
1185     }
1186   }
1187   // Ensure padding matches.
1188   if (maybeFillOp && xferOp.getPadding() != maybeFillOp.value())
1189     return failure();
1190   if (maybeFillOp)
1191     LDBG("with maybeFillOp " << *maybeFillOp);
1192 
1193   // `in` is the subview that memref.copy reads. Replace it.
1194   Value in = copyOp.source();
1195 
1196   // memref.copy + linalg.fill can be used to create a padded local buffer.
1197   // The `masked` attribute is only valid on this padded buffer.
1198   // When forwarding to vector.transfer_read, the attribute must be reset
1199   // conservatively.
1200   Value res = rewriter.create<vector::TransferReadOp>(
1201       xferOp.getLoc(), xferOp.getVectorType(), in, xferOp.getIndices(),
1202       xferOp.getPermutationMapAttr(), xferOp.getPadding(), xferOp.getMask(),
1203       // in_bounds is explicitly reset
1204       /*inBoundsAttr=*/ArrayAttr());
1205 
1206   if (maybeFillOp)
1207     rewriter.eraseOp(maybeFillOp);
1208   rewriter.eraseOp(copyOp);
1209   rewriter.replaceOp(xferOp, res);
1210 
1211   return success();
1212 }
1213 
1214 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
1215 /// when available.
1216 LogicalResult LinalgCopyVTWForwardingPattern::matchAndRewrite(
1217     vector::TransferWriteOp xferOp, PatternRewriter &rewriter) const {
1218   // TODO: support mask.
1219   if (xferOp.getMask())
1220     return failure();
1221 
1222   // Transfer into `viewOrAlloc`.
1223   Value viewOrAlloc = xferOp.getSource();
1224   if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() &&
1225       !viewOrAlloc.getDefiningOp<memref::AllocOp>())
1226     return failure();
1227 
1228   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
1229   memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
1230   if (!subViewOp)
1231     return failure();
1232   Value subView = subViewOp.getResult();
1233 
1234   // Find the copy from `subView` without interleaved uses.
1235   memref::CopyOp copyOp;
1236   for (auto &u : subViewOp.getResult().getUses()) {
1237     if (auto newCopyOp = dyn_cast<memref::CopyOp>(u.getOwner())) {
1238       if (newCopyOp.source() != subView)
1239         continue;
1240       if (mayExistInterleavedUses(xferOp, newCopyOp, {viewOrAlloc, subView}))
1241         continue;
1242       copyOp = newCopyOp;
1243       break;
1244     }
1245   }
1246   if (!copyOp)
1247     return failure();
1248 
1249   // `out` is the subview copied into that we replace.
1250   assert(copyOp.target().getType().isa<MemRefType>());
1251   Value out = copyOp.target();
1252 
1253   // Forward vector.transfer into copy.
1254   // memref.copy + linalg.fill can be used to create a padded local buffer.
1255   // The `masked` attribute is only valid on this padded buffer.
1256   // When forwarding to vector.transfer_write, the attribute must be reset
1257   // conservatively.
1258   rewriter.create<vector::TransferWriteOp>(
1259       xferOp.getLoc(), xferOp.getVector(), out, xferOp.getIndices(),
1260       xferOp.getPermutationMapAttr(), xferOp.getMask(),
1261       // in_bounds is explicitly reset
1262       /*inBoundsAttr=*/ArrayAttr());
1263 
1264   rewriter.eraseOp(copyOp);
1265   rewriter.eraseOp(xferOp);
1266 
1267   return success();
1268 }
1269 
1270 //===----------------------------------------------------------------------===//
1271 // Convolution vectorization patterns
1272 //===----------------------------------------------------------------------===//
1273 
1274 template <int N>
1275 static void bindShapeDims(ShapedType shapedType) {}
1276 
1277 template <int N, typename IntTy, typename... IntTy2>
1278 static void bindShapeDims(ShapedType shapedType, IntTy &val, IntTy2 &...vals) {
1279   val = shapedType.getShape()[N];
1280   bindShapeDims<N + 1, IntTy2 &...>(shapedType, vals...);
1281 }
1282 
1283 /// Bind a pack of int& to the leading dimensions of shapedType.getShape().
1284 template <typename... IntTy>
1285 static void bindShapeDims(ShapedType shapedType, IntTy &...vals) {
1286   bindShapeDims<0>(shapedType, vals...);
1287 }
1288 
1289 namespace {
1290 /// Generate a vector implementation for either:
1291 /// ```
1292 ///   Op def: (     n,     w,     c,    kw,    f  )
1293 ///    Iters: ({Par(), Par(), Par(), Red(), Red()})
1294 ///   Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c, f}, {n, w, f}}
1295 /// ```
1296 /// kw is unrolled, w is unrolled iff dilationW > 1.
1297 ///
1298 /// or
1299 ///
1300 /// ```
1301 ///   Op def: (     n,     w,     c,    kw )
1302 ///    Iters: ({Par(), Par(), Par(), Red()})
1303 ///   Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c}, {n, w, c}}
1304 /// ```
1305 /// kw is unrolled, w is unrolled iff dilationW > 1.
1306 struct Conv1DNwcGenerator : public StructuredGenerator<LinalgOp> {
1307   Conv1DNwcGenerator(OpBuilder &builder, LinalgOp linalgOp, int strideW,
1308                      int dilationW)
1309       : StructuredGenerator<LinalgOp>(builder, linalgOp), strideW(strideW),
1310         dilationW(dilationW) {
1311     // Determine whether `linalgOp` can be generated with this generator
1312     if (linalgOp.getNumInputs() != 2 || linalgOp.getNumOutputs() != 1)
1313       return;
1314     lhsShaped = linalgOp.inputs()[0];
1315     rhsShaped = linalgOp.inputs()[1];
1316     resShaped = linalgOp.outputs()[0];
1317     lhsShapedType = lhsShaped.getType().dyn_cast<ShapedType>();
1318     rhsShapedType = rhsShaped.getType().dyn_cast<ShapedType>();
1319     resShapedType = resShaped.getType().dyn_cast<ShapedType>();
1320     if (!lhsShapedType || !rhsShapedType || !resShapedType)
1321       return;
1322     if (lhsShapedType.getRank() != 3 ||
1323         (rhsShapedType.getRank() != 2 && rhsShapedType.getRank() != 3) ||
1324         resShapedType.getRank() != 3)
1325       return;
1326 
1327     // Check for reduction `add` preceded by `mul`.
1328     Operation *reduceOp = matchLinalgReduction(linalgOp.getOutputOperand(0));
1329     if (!reduceOp)
1330       return;
1331     llvm::Optional<vector::CombiningKind> maybeKind;
1332     maybeKind = getCombinerOpKind(reduceOp);
1333     if (!maybeKind || *maybeKind != vector::CombiningKind::ADD)
1334       return;
1335     // Check for single `mul` predecessor. The `mul` operands must be block
1336     // arguments or extension of block arguments.
1337     Operation *mulOp = nullptr;
1338     for (Value operand : reduceOp->getOperands()) {
1339       if (operand.isa<BlockArgument>())
1340         continue;
1341       if (mulOp)
1342         return;
1343       mulOp = operand.getDefiningOp();
1344       if (!mulOp || !isa<arith::MulIOp, arith::MulFOp>(mulOp))
1345         return;
1346     }
1347     if (!mulOp)
1348       return;
1349     for (Value operand : mulOp->getOperands()) {
1350       if (Operation *def = operand.getDefiningOp()) {
1351         if (!isa<arith::ExtFOp>(def))
1352           return;
1353         operand = def->getOperand(0);
1354       }
1355       if (!operand.isa<BlockArgument>())
1356         return;
1357     }
1358     // The op is now known to be valid.
1359     valid = true;
1360   }
1361 
1362   /// Generate a vector implementation for:
1363   /// ```
1364   ///   Op def: (     n,     w,     c,    kw,    f  )
1365   ///    Iters: ({Par(), Par(), Par(), Red(), Red()})
1366   ///   Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c, f}, {n, w, f}}
1367   /// ```
1368   /// kw is always unrolled.
1369   /// TODO: w (resp. kw) is unrolled when the strideW ( resp. dilationW) is
1370   /// > 1.
1371   FailureOr<Operation *> conv() {
1372     if (!valid)
1373       return failure();
1374 
1375     int64_t nSize, wSize, cSize, kwSize, fSize;
1376     // kernel{kw, c, f}
1377     bindShapeDims(rhsShapedType, kwSize, cSize, fSize);
1378     // out{n, w, f}
1379     bindShapeDims(resShapedType, nSize, wSize);
1380 
1381     vector::TransferWriteOp write;
1382     Value zero = builder.create<arith::ConstantIndexOp>(loc, 0);
1383 
1384     // w is unrolled (i.e. wSizeStep == 1) iff strideW > 1.
1385     // When strideW == 1, we can batch the contiguous loads and avoid
1386     // unrolling
1387     int64_t wSizeStep = strideW == 1 ? wSize : 1;
1388 
1389     Type lhsEltType = lhsShapedType.getElementType();
1390     Type rhsEltType = rhsShapedType.getElementType();
1391     Type resEltType = resShapedType.getElementType();
1392     VectorType lhsType = VectorType::get(
1393         {nSize,
1394          // iw = ow * sw + kw *  dw - 1
1395          //   (i.e. 16 convolved with 3 (@stride 1 dilation 1) -> 14)
1396          // Perform the proper inclusive -> exclusive -> inclusive.
1397          ((wSize - 1) * strideW + 1) + ((kwSize - 1) * dilationW + 1) - 1,
1398          cSize},
1399         lhsEltType);
1400     VectorType rhsType = VectorType::get({kwSize, cSize, fSize}, rhsEltType);
1401     VectorType resType = VectorType::get({nSize, wSize, fSize}, resEltType);
1402 
1403     // Read lhs slice of size {w * strideW + kw * dilationW, c, f} @ [0, 0,
1404     // 0].
1405     Value lhs = builder.create<vector::TransferReadOp>(
1406         loc, lhsType, lhsShaped, ValueRange{zero, zero, zero});
1407     // Read rhs slice of size {kw, c, f} @ [0, 0, 0].
1408     Value rhs = builder.create<vector::TransferReadOp>(
1409         loc, rhsType, rhsShaped, ValueRange{zero, zero, zero});
1410     // Read res slice of size {n, w, f} @ [0, 0, 0].
1411     Value res = builder.create<vector::TransferReadOp>(
1412         loc, resType, resShaped, ValueRange{zero, zero, zero});
1413 
1414     //===------------------------------------------------------------------===//
1415     // Begin vector-only rewrite part
1416     //===------------------------------------------------------------------===//
1417     // Unroll along kw and read slices of lhs and rhs.
1418     SmallVector<Value> lhsVals, rhsVals, resVals;
1419     // Extract lhs slice of size {n, wSizeStep, c} @ [0, sw * w + dw * kw, 0].
1420     for (int64_t kw = 0; kw < kwSize; ++kw) {
1421       for (int64_t w = 0; w < wSize; w += wSizeStep) {
1422         lhsVals.push_back(builder.create<vector::ExtractStridedSliceOp>(
1423             loc, lhs,
1424             /*offsets=*/ArrayRef<int64_t>{0, w * strideW + kw * dilationW, 0},
1425             /*sizes=*/ArrayRef<int64_t>{nSize, wSizeStep, cSize},
1426             /*strides=*/ArrayRef<int64_t>{1, 1, 1}));
1427       }
1428     }
1429     // Extract rhs slice of size {c, f} @ [kw].
1430     for (int64_t kw = 0; kw < kwSize; ++kw) {
1431       rhsVals.push_back(builder.create<vector::ExtractOp>(
1432           loc, rhs, /*offsets=*/ArrayRef<int64_t>{kw}));
1433     }
1434     // Extract res slice: {n, wSizeStep, f} @ [0, w, 0].
1435     for (int64_t w = 0; w < wSize; w += wSizeStep) {
1436       resVals.push_back(builder.create<vector::ExtractStridedSliceOp>(
1437           loc, res,
1438           /*offsets=*/ArrayRef<int64_t>{0, w, 0},
1439           /*sizes=*/ArrayRef<int64_t>{nSize, wSizeStep, fSize},
1440           /*strides=*/ArrayRef<int64_t>{1, 1, 1}));
1441     }
1442 
1443     auto linearIndex = [&](int64_t kw, int64_t w) {
1444       return kw * (wSize / wSizeStep) + w;
1445     };
1446 
1447     // Compute contraction: O{n, w, f} += I{n, sw * w + dw * kw, c} * F{c, f}
1448     for (int64_t kw = 0; kw < kwSize; ++kw) {
1449       for (int64_t w = 0; w < wSize; w += wSizeStep) {
1450         resVals[w] = conv1dSliceAsContraction(
1451             builder, loc, lhsVals[linearIndex(kw, w)], rhsVals[kw], resVals[w]);
1452       }
1453     }
1454 
1455     // Write back res slice: {n, wSizeStep, f} @ [0, w, 0].
1456     // This does not depend on kw.
1457     for (int64_t w = 0; w < wSize; w += wSizeStep) {
1458       res = builder.create<vector::InsertStridedSliceOp>(
1459           loc, resVals[w], res,
1460           /*offsets=*/ArrayRef<int64_t>{0, w, 0},
1461           /*strides=*/ArrayRef<int64_t>{1, 1, 1});
1462     }
1463     //===------------------------------------------------------------------===//
1464     // End vector-only rewrite part
1465     //===------------------------------------------------------------------===//
1466 
1467     // Write back res slice of size {n, w, f} @ [0, 0, 0].
1468     return builder
1469         .create<vector::TransferWriteOp>(loc, res, resShaped,
1470                                          ValueRange{zero, zero, zero})
1471         .getOperation();
1472   }
1473 
1474   // Create a contraction: lhs{n, w, c} * rhs{c, f} -> res{n, w, f}
1475   Value conv1dSliceAsContraction(OpBuilder &b, Location loc, Value lhs,
1476                                  Value rhs, Value res) {
1477     StringRef par = Par().strRef, red = Red().strRef;
1478     AffineExpr n, w, f, c;
1479     bindDims(ctx, n, w, f, c);
1480     return builder.create<vector::ContractionOp>(
1481         loc, lhs, rhs, res,
1482         /*indexingMaps=*/MapList{{n, w, c}, {c, f}, {n, w, f}},
1483         /*iteratorTypes=*/ArrayRef<StringRef>{par, par, par, red});
1484   }
1485 
1486   /// Generate a vector implementation for:
1487   /// ```
1488   ///   Op def: (     n,     w,     c,    kw)
1489   ///    Iters: ({Par(), Par(), Par(), Red()})
1490   ///   Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c}, {n, w, c}}
1491   /// ```
1492   /// kw is always unrolled.
1493   /// TODO: w (resp. kw) is unrolled when the strideW ( resp. dilationW) is
1494   /// > 1.
1495   FailureOr<Operation *> depthwiseConv() {
1496     if (!valid)
1497       return failure();
1498 
1499     int64_t nSize, wSize, cSize, kwSize;
1500     // kernel{kw, c}
1501     bindShapeDims(rhsShapedType, kwSize, cSize);
1502     // out{n, w, c}
1503     bindShapeDims(resShapedType, nSize, wSize);
1504 
1505     vector::TransferWriteOp write;
1506     Value zero = builder.create<arith::ConstantIndexOp>(loc, 0);
1507 
1508     // w is unrolled (i.e. wSizeStep == 1) iff strideW > 1.
1509     // When strideW == 1, we can batch the contiguous loads and avoid
1510     // unrolling
1511     int64_t wSizeStep = strideW == 1 ? wSize : 1;
1512 
1513     Type lhsEltType = lhsShapedType.getElementType();
1514     Type rhsEltType = rhsShapedType.getElementType();
1515     Type resEltType = resShapedType.getElementType();
1516     VectorType lhsType = VectorType::get(
1517         {nSize,
1518          // iw = ow * sw + kw *  dw - 1
1519          //   (i.e. 16 convolved with 3 (@stride 1 dilation 1) -> 14)
1520          ((wSize - 1) * strideW + 1) + ((kwSize - 1) * dilationW + 1) - 1,
1521          cSize},
1522         lhsEltType);
1523     VectorType rhsType = VectorType::get({kwSize, cSize}, rhsEltType);
1524     VectorType resType = VectorType::get({nSize, wSize, cSize}, resEltType);
1525 
1526     // Read lhs slice of size {n, w * strideW + kw * dilationW, c} @ [0, 0,
1527     // 0].
1528     Value lhs = builder.create<vector::TransferReadOp>(
1529         loc, lhsType, lhsShaped, ValueRange{zero, zero, zero});
1530     // Read rhs slice of size {kw, c} @ [0, 0].
1531     Value rhs = builder.create<vector::TransferReadOp>(loc, rhsType, rhsShaped,
1532                                                        ValueRange{zero, zero});
1533     // Read res slice of size {n, w, c} @ [0, 0, 0].
1534     Value res = builder.create<vector::TransferReadOp>(
1535         loc, resType, resShaped, ValueRange{zero, zero, zero});
1536 
1537     //===------------------------------------------------------------------===//
1538     // Begin vector-only rewrite part
1539     //===------------------------------------------------------------------===//
1540     // Unroll along kw and read slices of lhs and rhs.
1541     SmallVector<Value> lhsVals, rhsVals, resVals;
1542     // Extract lhs slice of size {n, wSizeStep, c}
1543     //   @ [0, sw * w + dw * kw, 0].
1544     for (int64_t kw = 0; kw < kwSize; ++kw) {
1545       for (int64_t w = 0; w < wSize; w += wSizeStep) {
1546         lhsVals.push_back(builder.create<vector::ExtractStridedSliceOp>(
1547             loc, lhs,
1548             /*offsets=*/ArrayRef<int64_t>{0, w * strideW + kw * dilationW, 0},
1549             /*sizes=*/ArrayRef<int64_t>{nSize, wSizeStep, cSize},
1550             /*strides=*/ArrayRef<int64_t>{1, 1, 1}));
1551       }
1552     }
1553     // Extract rhs slice of size {c} @ [kw].
1554     for (int64_t kw = 0; kw < kwSize; ++kw) {
1555       rhsVals.push_back(builder.create<vector::ExtractOp>(
1556           loc, rhs, /*offsets=*/ArrayRef<int64_t>{kw}));
1557     }
1558     // Extract res slice: {n, wSizeStep, c} @ [0, w, 0].
1559     for (int64_t w = 0; w < wSize; w += wSizeStep) {
1560       resVals.push_back(builder.create<vector::ExtractStridedSliceOp>(
1561           loc, res,
1562           /*offsets=*/ArrayRef<int64_t>{0, w, 0},
1563           /*sizes=*/ArrayRef<int64_t>{nSize, wSizeStep, cSize},
1564           /*strides=*/ArrayRef<int64_t>{1, 1, 1}));
1565     }
1566 
1567     auto linearIndex = [&](int64_t kw, int64_t w) {
1568       return kw * (wSize / wSizeStep) + w;
1569     };
1570 
1571     // Compute contraction: O{n, w, c} += I{n, sw * w + dw * kw, c} * F{c}
1572     for (int64_t kw = 0; kw < kwSize; ++kw) {
1573       for (int64_t w = 0; w < wSize; w += wSizeStep) {
1574         resVals[w] = depthwiseConv1dSliceAsFma(
1575             builder, loc, lhsVals[linearIndex(kw, w)], rhsVals[kw], resVals[w]);
1576       }
1577     }
1578 
1579     // Write back res slice: {n, wSizeStep, c} @ [0, w, 0].
1580     // This does not depend on kw.
1581     for (int64_t w = 0; w < wSize; w += wSizeStep) {
1582       res = builder.create<vector::InsertStridedSliceOp>(
1583           loc, resVals[w], res,
1584           /*offsets=*/ArrayRef<int64_t>{0, w, 0},
1585           /*strides=*/ArrayRef<int64_t>{1, 1, 1});
1586     }
1587     //===------------------------------------------------------------------===//
1588     // End vector-only rewrite part
1589     //===------------------------------------------------------------------===//
1590 
1591     // Write back res slice of size {n, w, c} @ [0, 0, 0].
1592     return builder
1593         .create<vector::TransferWriteOp>(loc, res, resShaped,
1594                                          ValueRange{zero, zero, zero})
1595         .getOperation();
1596   }
1597 
1598   /// Lower lhs{n, w, c} * rhs{c} -> res{n, w, c} to fma.
1599   Value depthwiseConv1dSliceAsFma(OpBuilder &b, Location loc, Value lhs,
1600                                   Value rhs, Value res) {
1601     Value bcast = builder.create<vector::BroadcastOp>(loc, res.getType(), rhs);
1602     return b.create<vector::FMAOp>(loc, lhs, bcast, res);
1603   }
1604 
1605   /// Entry point that transposes into the common form:
1606   ///   {{n, strideW * w + dilationW * kw, c}, {kw, c, f}, {n, w, f}}
1607   FailureOr<Operation *> generateConv() {
1608     AffineExpr n, w, f, kw, c;
1609     bindDims(ctx, n, w, f, kw, c);
1610     if (!iters({Par(), Par(), Par(), Red(), Red()}))
1611       return failure();
1612 
1613     // No transposition needed.
1614     if (layout({/*lhsIndex*/ {n, strideW * w + dilationW * kw, c},
1615                 /*rhsIndex*/ {kw, c, f},
1616                 /*resIndex*/ {n, w, f}}))
1617       return conv();
1618     return failure();
1619   }
1620 
1621   /// Entry point that transposes into the common form:
1622   ///   {{n, strideW * w + dilationW * kw, c}, {kw, c}, {n, w, c}}
1623   FailureOr<Operation *> generateDilatedConv() {
1624     AffineExpr n, w, c, kw;
1625     bindDims(ctx, n, w, c, kw);
1626     if (!iters({Par(), Par(), Par(), Red()}))
1627       return failure();
1628 
1629     // No transposition needed.
1630     if (layout({/*lhsIndex*/ {n, strideW * w + dilationW * kw, c},
1631                 /*rhsIndex*/ {kw, c},
1632                 /*resIndex*/ {n, w, c}}))
1633       return depthwiseConv();
1634     return failure();
1635   }
1636 
1637 private:
1638   bool valid = false;
1639   int strideW, dilationW;
1640   Value lhsShaped, rhsShaped, resShaped;
1641   ShapedType lhsShapedType, rhsShapedType, resShapedType;
1642 };
1643 } // namespace
1644 
1645 /// Helper function to vectorize a LinalgOp with convolution semantics.
1646 // TODO: extend the generic vectorization to support windows and drop this.
1647 static FailureOr<Operation *> vectorizeConvolution(OpBuilder &b, LinalgOp op) {
1648   // The ConvolutionOpInterface gives us guarantees of existence for
1649   // strides/dilations. However, we do not need to rely on those, we can simply
1650   // use them if present, otherwise use the default and let the generic conv.
1651   // matcher in the ConvGenerator succeed or fail.
1652   auto strides = op->getAttrOfType<DenseIntElementsAttr>("strides");
1653   auto dilations = op->getAttrOfType<DenseIntElementsAttr>("dilations");
1654   auto stride = strides ? *strides.getValues<uint64_t>().begin() : 1;
1655   auto dilation = dilations ? *dilations.getValues<uint64_t>().begin() : 1;
1656   Conv1DNwcGenerator e(b, op, stride, dilation);
1657   auto res = e.generateConv();
1658   if (succeeded(res))
1659     return res;
1660   return e.generateDilatedConv();
1661 }
1662 
1663 struct VectorizeConvolution : public OpInterfaceRewritePattern<LinalgOp> {
1664   using OpInterfaceRewritePattern::OpInterfaceRewritePattern;
1665 
1666   LogicalResult matchAndRewrite(LinalgOp op,
1667                                 PatternRewriter &rewriter) const override {
1668     FailureOr<Operation *> resultOrFail = vectorizeConvolution(rewriter, op);
1669     if (failed(resultOrFail))
1670       return failure();
1671     Operation *newOp = *resultOrFail;
1672     if (newOp->getNumResults() == 0) {
1673       rewriter.eraseOp(op.getOperation());
1674       return success();
1675     }
1676     assert(newOp->getNumResults() == 1 && "expected single result");
1677     rewriter.replaceOp(op.getOperation(), newOp->getResult(0));
1678     return success();
1679   }
1680 };
1681 
1682 void mlir::linalg::populateConvolutionVectorizationPatterns(
1683     RewritePatternSet &patterns, PatternBenefit benefit) {
1684   patterns.add<VectorizeConvolution>(patterns.getContext(), benefit);
1685 }
1686