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