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 /// Detect whether `r` has only ConstantOp, ElementwiseMappable and YieldOp.
421 static bool hasOnlyScalarElementwiseOp(Region &r) {
422   if (!llvm::hasSingleElement(r))
423     return false;
424   for (Operation &op : r.front()) {
425     if (!(isa<arith::ConstantOp, func::ConstantOp, linalg::YieldOp,
426               linalg::IndexOp>(op) ||
427           OpTrait::hasElementwiseMappableTraits(&op)) ||
428         llvm::any_of(op.getResultTypes(),
429                      [](Type type) { return !type.isIntOrIndexOrFloat(); }))
430       return false;
431   }
432   return true;
433 }
434 
435 // Return true if the op is an element-wise linalg op.
436 static bool isElementwise(Operation *op) {
437   auto linalgOp = dyn_cast<linalg::LinalgOp>(op);
438   if (!linalgOp)
439     return false;
440   if (linalgOp.getNumLoops() != linalgOp.getNumParallelLoops())
441     return false;
442   // TODO: relax the restrictions on indexing map.
443   for (OpOperand *opOperand : linalgOp.getOutputOperands()) {
444     if (!linalgOp.getTiedIndexingMap(opOperand).isPermutation())
445       return false;
446   }
447   return hasOnlyScalarElementwiseOp(linalgOp->getRegion(0));
448 }
449 
450 /// Generic vectorization function that rewrites the body of a `linalgOp` into
451 /// vector form. Generic vectorization proceeds as follows:
452 ///   1. Verify the `linalgOp` has one non-empty region.
453 ///   2. Values defined above the region are mapped to themselves and will be
454 ///   broadcasted on a per-need basis by their consumers.
455 ///   3. Each region argument is vectorized into a vector.transfer_read (or 0-d
456 ///   load).
457 ///   TODO: Reuse opportunities for RAR dependencies.
458 ///   4a. Register CustomVectorizationHook for YieldOp to capture the results.
459 ///   4b. Register CustomVectorizationHook for IndexOp to access the iteration
460 ///   indices.
461 ///   5. Iteratively call vectorizeOneOp on the region operations.
462 ///
463 /// When `broadcastToMaximalCommonShape` is set to true, eager broadcasting is
464 /// performed to the maximal common vector size implied by the `linalgOp`
465 /// iteration space. This eager broadcasting is introduced in the
466 /// permutation_map of the vector.transfer_read operations. The eager
467 /// broadcasting makes it trivial to detrmine where broadcast, transposes and
468 /// reductions should occur, without any bookkeeping. The tradeoff is that, in
469 /// the absence of good canonicalizations, the amount of work increases.
470 /// This is not deemed a problem as we expect canonicalizations and foldings to
471 /// aggressively clean up the useless work.
472 static LogicalResult
473 vectorizeAsLinalgGeneric(OpBuilder &b, LinalgOp linalgOp,
474                          SmallVectorImpl<Value> &newResults) {
475   Block *block = linalgOp.getBlock();
476 
477   // 2. Values defined above the region can only be broadcast for now. Make them
478   // map to themselves.
479   BlockAndValueMapping bvm;
480   SetVector<Value> valuesSet;
481   mlir::getUsedValuesDefinedAbove(linalgOp->getRegion(0), valuesSet);
482   bvm.map(valuesSet.getArrayRef(), valuesSet.getArrayRef());
483 
484   if (linalgOp.getNumOutputs() == 0)
485     return failure();
486 
487   // TODO: the common vector shape is equal to the static loop sizes only when
488   // all indexing maps are projected permutations. For convs and stencils the
489   // logic will need to evolve.
490   SmallVector<int64_t> commonVectorShape = linalgOp.computeStaticLoopSizes();
491 
492   // 3. Turn all BBArgs into vector.transfer_read / load.
493   Location loc = linalgOp.getLoc();
494   Value zero = b.create<arith::ConstantIndexOp>(loc, 0);
495   for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands()) {
496     BlockArgument bbarg = block->getArgument(opOperand->getOperandNumber());
497     if (linalgOp.isScalar(opOperand)) {
498       bvm.map(bbarg, opOperand->get());
499       continue;
500     }
501     VectorType readType;
502     AffineMap map;
503     // TODO: can we keep this simplification?
504     // if (linalgOp.getShape(opOperand).empty()) {
505     //   readType = VectorType::get({}, bbarg.getType());
506     // } else {
507     if (opOperand->getOperandNumber() < linalgOp.getNumInputs()) {
508       map = inverseAndBroadcastProjectedPermutation(
509           linalgOp.getTiedIndexingMap(opOperand));
510       readType = VectorType::get(commonVectorShape,
511                                  getElementTypeOrSelf(opOperand->get()));
512     } else {
513       map = inversePermutation(
514           reindexIndexingMap(linalgOp.getTiedIndexingMap(opOperand)));
515       readType = VectorType::get(map.compose(linalgOp.getShape(opOperand)),
516                                  getElementTypeOrSelf(opOperand->get()));
517     }
518     // }
519 
520     auto shape = linalgOp.getShape(opOperand);
521     SmallVector<Value> indices(shape.size(), zero);
522     Value readValue = b.create<vector::TransferReadOp>(
523         loc, readType, opOperand->get(), indices, map);
524     // Not all ops support 0-d vectors, extract the scalar for now.
525     // TODO: remove this.
526     if (readValue.getType().cast<VectorType>().getRank() == 0)
527       readValue = b.create<vector::ExtractElementOp>(loc, readValue);
528 
529     LDBG("new vectorized bbarg(" << bbarg.getArgNumber() << "): " << readValue);
530     bvm.map(bbarg, readValue);
531     bvm.map(opOperand->get(), readValue);
532   }
533 
534   SmallVector<CustomVectorizationHook> hooks;
535   // 4a. Register CustomVectorizationHook for yieldOp.
536   CustomVectorizationHook vectorizeYield =
537       [&](Operation *op,
538           const BlockAndValueMapping &bvm) -> VectorizationResult {
539     return vectorizeLinalgYield(b, op, bvm, linalgOp, newResults);
540   };
541   hooks.push_back(vectorizeYield);
542 
543   // 4b. Register CustomVectorizationHook for indexOp.
544   CustomVectorizationHook vectorizeIndex =
545       [&](Operation *op,
546           const BlockAndValueMapping &bvm) -> VectorizationResult {
547     return vectorizeLinalgIndex(b, op, linalgOp);
548   };
549   hooks.push_back(vectorizeIndex);
550 
551   // 5. Iteratively call `vectorizeOneOp` to each op in the slice.
552   for (Operation &op : block->getOperations()) {
553     VectorizationResult result = vectorizeOneOp(b, linalgOp, &op, bvm, hooks);
554     if (result.status == VectorizationStatus::Failure) {
555       LDBG("failed to vectorize: " << op);
556       return failure();
557     }
558     if (result.status == VectorizationStatus::NewOp) {
559       LDBG("new vector op: " << *result.newOp;);
560       bvm.map(op.getResults(), result.newOp->getResults());
561     }
562   }
563 
564   return success();
565 }
566 
567 /// Helper function to vectorize a `linalgOp` with contraction semantics in a
568 /// generic fashion.
569 /// This helper is needed atm because the truly generic implementation requires
570 /// good vector.multi_reduce folding patterns that are currently NYI.
571 // TODO: drop reliance on a specific pattern.
572 static bool allIndexingsAreProjectedPermutation(LinalgOp op) {
573   return llvm::all_of(op.getIndexingMaps(), [](AffineMap m) {
574     return m.isProjectedPermutation(/*allowZeroInResults=*/true);
575   });
576 }
577 
578 // TODO: probably need some extra checks for reduction followed by consumer
579 // ops that may not commute (e.g. linear reduction + non-linear instructions).
580 static LogicalResult reductionPreconditions(LinalgOp op) {
581   if (llvm::none_of(op.iterator_types(), isReductionIterator)) {
582     LDBG("reduction precondition failed: no reduction iterator");
583     return failure();
584   }
585   for (OpOperand *opOperand : op.getOutputOperands()) {
586     Operation *reduceOp = matchLinalgReduction(opOperand);
587     if (!reduceOp || !getCombinerOpKind(reduceOp)) {
588       LDBG("reduction precondition failed: reduction detection failed");
589       return failure();
590     }
591   }
592   return success();
593 }
594 
595 static LogicalResult vectorizeStaticLinalgOpPrecondition(linalg::LinalgOp op) {
596   if (isElementwise(op))
597     return success();
598   // TODO: isaConvolutionOpInterface that can also infer from generic features.
599   // But we will still need stride/dilation attributes that will be annoying to
600   // reverse-engineer...
601   if (isa<ConvolutionOpInterface>(op.getOperation()))
602     return success();
603   // TODO: the common vector shape is equal to the static loop sizes only when
604   // all indexing maps are projected permutations. For convs and stencils the
605   // logic will need to evolve.
606   if (!allIndexingsAreProjectedPermutation(op)) {
607     LDBG("precondition failed: not projected permutations");
608     return failure();
609   }
610   if (failed(reductionPreconditions(op))) {
611     LDBG("precondition failed: reduction preconditions");
612     return failure();
613   }
614   return success();
615 }
616 
617 static LogicalResult vectorizeLinalgOpPrecondition(LinalgOp linalgOp) {
618   // All types must be static shape to go to vector.
619   if (linalgOp.hasDynamicShape()) {
620     LDBG("precondition failed: dynamic shape");
621     return failure();
622   }
623   return vectorizeStaticLinalgOpPrecondition(linalgOp);
624 }
625 
626 LogicalResult mlir::linalg::vectorize(RewriterBase &rewriter,
627                                       LinalgOp linalgOp) {
628   if (failed(vectorizeLinalgOpPrecondition(linalgOp)))
629     return failure();
630 
631   SmallVector<Value> results;
632   // TODO: isaConvolutionOpInterface that can also infer from generic
633   // features. Will require stride/dilation attributes inference.
634   FailureOr<Operation *> convOr = vectorizeConvolution(rewriter, linalgOp);
635   if (succeeded(convOr)) {
636     llvm::append_range(results, (*convOr)->getResults());
637   } else {
638     if (failed(vectorizeLinalgOpPrecondition(linalgOp)))
639       return failure();
640     LDBG("Vectorize generic by broadcasting to a common shape: " << linalgOp);
641     if (failed(vectorizeAsLinalgGeneric(rewriter, linalgOp, results)))
642       return failure();
643   }
644 
645   if (!results.empty())
646     rewriter.replaceOp(linalgOp, results);
647   else
648     rewriter.eraseOp(linalgOp);
649 
650   return success();
651 }
652 
653 LogicalResult mlir::linalg::vectorizeCopy(RewriterBase &rewriter,
654                                           memref::CopyOp copyOp) {
655 
656   auto srcType = copyOp.source().getType().cast<MemRefType>();
657   auto dstType = copyOp.target().getType().cast<MemRefType>();
658   if (!srcType.hasStaticShape() || !dstType.hasStaticShape())
659     return failure();
660 
661   auto readType =
662       VectorType::get(srcType.getShape(), getElementTypeOrSelf(srcType));
663   auto writeType =
664       VectorType::get(dstType.getShape(), getElementTypeOrSelf(dstType));
665 
666   Location loc = copyOp->getLoc();
667   Value zero = rewriter.create<arith::ConstantIndexOp>(loc, 0);
668   SmallVector<Value> indices(srcType.getRank(), zero);
669 
670   Value readValue = rewriter.create<vector::TransferReadOp>(
671       loc, readType, copyOp.source(), indices,
672       rewriter.getMultiDimIdentityMap(srcType.getRank()));
673   if (readValue.getType().cast<VectorType>().getRank() == 0) {
674     readValue = rewriter.create<vector::ExtractElementOp>(loc, readValue);
675     readValue = rewriter.create<vector::BroadcastOp>(loc, writeType, readValue);
676   }
677   Operation *writeValue = rewriter.create<vector::TransferWriteOp>(
678       loc, readValue, copyOp.target(), indices,
679       rewriter.getMultiDimIdentityMap(srcType.getRank()));
680   rewriter.replaceOp(copyOp, writeValue->getResults());
681   return success();
682 }
683 
684 //----------------------------------------------------------------------------//
685 // Misc. vectorization patterns.
686 //----------------------------------------------------------------------------//
687 
688 /// Helper function that retrieves the value of an IntegerAttr.
689 static int64_t getIntFromAttr(Attribute attr) {
690   return attr.cast<IntegerAttr>().getInt();
691 }
692 
693 /// Given an ArrayRef of OpFoldResults, return a vector of Values.
694 /// IntegerAttrs are converted to ConstantIndexOps. Other attribute types are
695 /// not supported.
696 static SmallVector<Value> ofrToIndexValues(OpBuilder &builder, Location loc,
697                                            ArrayRef<OpFoldResult> ofrs) {
698   SmallVector<Value> result;
699   llvm::for_each(ofrs, [&](auto o) {
700     if (auto val = o.template dyn_cast<Value>()) {
701       result.push_back(val);
702     } else {
703       result.push_back(builder.create<arith::ConstantIndexOp>(
704           loc, getIntFromAttr(o.template get<Attribute>())));
705     }
706   });
707   return result;
708 }
709 
710 /// Rewrite a tensor::PadOp into a sequence of InitTensorOp, FillOp and
711 /// InsertSliceOp. For now, only constant padding values are supported.
712 /// If there is enough static type information, TransferReadOps and
713 /// TransferWriteOps may be generated instead of InsertSliceOps.
714 struct GenericPadOpVectorizationPattern : public GeneralizePadOpPattern {
715   GenericPadOpVectorizationPattern(MLIRContext *context,
716                                    PatternBenefit benefit = 1)
717       : GeneralizePadOpPattern(context, tryVectorizeCopy, benefit) {}
718   /// Vectorize the copying of a tensor::PadOp's source. This is possible if
719   /// each dimension size is statically know in the source type or the result
720   /// type (or both).
721   static LogicalResult tryVectorizeCopy(PatternRewriter &rewriter,
722                                         tensor::PadOp padOp, Value dest) {
723     auto sourceType = padOp.getSourceType();
724     auto resultType = padOp.getResultType();
725 
726     // Copy cannot be vectorized if pad value is non-constant and source shape
727     // is dynamic. In case of a dynamic source shape, padding must be appended
728     // by TransferReadOp, but TransferReadOp supports only constant padding.
729     auto padValue = padOp.getConstantPaddingValue();
730     if (!padValue) {
731       if (!sourceType.hasStaticShape())
732         return failure();
733       // Create dummy padding value.
734       auto elemType = sourceType.getElementType();
735       padValue = rewriter.create<arith::ConstantOp>(
736           padOp.getLoc(), elemType, rewriter.getZeroAttr(elemType));
737     }
738 
739     SmallVector<int64_t> vecShape;
740     SmallVector<bool> readInBounds;
741     SmallVector<bool> writeInBounds;
742     for (unsigned i = 0; i < sourceType.getRank(); ++i) {
743       if (!sourceType.isDynamicDim(i)) {
744         vecShape.push_back(sourceType.getDimSize(i));
745         // Source shape is statically known: Neither read nor write are
746         // out-of- bounds.
747         readInBounds.push_back(true);
748         writeInBounds.push_back(true);
749       } else if (!resultType.isDynamicDim(i)) {
750         // Source shape is not statically known, but result shape is.
751         // Vectorize with size of result shape. This may be larger than the
752         // source size.
753         vecShape.push_back(resultType.getDimSize(i));
754         // Read may be out-of-bounds because the result size could be larger
755         // than the source size.
756         readInBounds.push_back(false);
757         // Write is out-of-bounds if low padding > 0.
758         writeInBounds.push_back(
759             getConstantIntValue(padOp.getMixedLowPad()[i]) ==
760             static_cast<int64_t>(0));
761       } else {
762         // Neither source nor result dim of padOp is static. Cannot vectorize
763         // the copy.
764         return failure();
765       }
766     }
767     auto vecType = VectorType::get(vecShape, sourceType.getElementType());
768 
769     // Generate TransferReadOp.
770     SmallVector<Value> readIndices(
771         vecType.getRank(),
772         rewriter.create<arith::ConstantIndexOp>(padOp.getLoc(), 0));
773     auto read = rewriter.create<vector::TransferReadOp>(
774         padOp.getLoc(), vecType, padOp.source(), readIndices, padValue,
775         ArrayRef<bool>{readInBounds});
776 
777     // If `dest` is a FillOp and the TransferWriteOp would overwrite the
778     // entire tensor, write directly to the FillOp's operand.
779     if (llvm::equal(vecShape, resultType.getShape()) &&
780         llvm::all_of(writeInBounds, [](bool b) { return b; }))
781       if (auto fill = dest.getDefiningOp<FillOp>())
782         dest = fill.output();
783 
784     // Generate TransferWriteOp.
785     auto writeIndices =
786         ofrToIndexValues(rewriter, padOp.getLoc(), padOp.getMixedLowPad());
787     rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
788         padOp, read, dest, writeIndices, ArrayRef<bool>{writeInBounds});
789 
790     return success();
791   }
792 };
793 
794 /// Base pattern for rewriting tensor::PadOps whose result is consumed by a
795 /// given operation type OpTy.
796 template <typename OpTy>
797 struct VectorizePadOpUserPattern : public OpRewritePattern<tensor::PadOp> {
798   using OpRewritePattern<tensor::PadOp>::OpRewritePattern;
799 
800   LogicalResult matchAndRewrite(tensor::PadOp padOp,
801                                 PatternRewriter &rewriter) const final {
802     bool changed = false;
803     // Insert users in vector, because some users may be replaced/removed.
804     for (auto *user : llvm::to_vector<4>(padOp->getUsers()))
805       if (auto op = dyn_cast<OpTy>(user))
806         changed |= rewriteUser(rewriter, padOp, op).succeeded();
807     return success(changed);
808   }
809 
810 protected:
811   virtual LogicalResult rewriteUser(PatternRewriter &rewriter,
812                                     tensor::PadOp padOp, OpTy op) const = 0;
813 };
814 
815 /// Rewrite use of tensor::PadOp result in TransferReadOp. E.g.:
816 /// ```
817 /// %0 = tensor.pad %src ... : tensor<?x?xf32> to tensor<17x5xf32>
818 /// %r = vector.transfer_read %0[%c0, %c0], %cst
819 ///     {in_bounds = [true, true]} : tensor<17x5xf32>, vector<17x5xf32>
820 /// ```
821 /// is rewritten to:
822 /// ```
823 /// %r = vector.transfer_read %src[%c0, %c0], %padding
824 ///     {in_bounds = [true, true]}
825 ///     : tensor<?x?xf32>, vector<17x5xf32>
826 /// ```
827 /// Note: By restricting this pattern to in-bounds TransferReadOps, we can be
828 /// sure that the original padding value %cst was never used.
829 ///
830 /// This rewrite is possible if:
831 /// - `xferOp` has no out-of-bounds dims or mask.
832 /// - Low padding is static 0.
833 /// - Single, scalar padding value.
834 struct PadOpVectorizationWithTransferReadPattern
835     : public VectorizePadOpUserPattern<vector::TransferReadOp> {
836   using VectorizePadOpUserPattern<
837       vector::TransferReadOp>::VectorizePadOpUserPattern;
838 
839   LogicalResult rewriteUser(PatternRewriter &rewriter, tensor::PadOp padOp,
840                             vector::TransferReadOp xferOp) const override {
841     // Low padding must be static 0.
842     if (!padOp.hasZeroLowPad())
843       return failure();
844     // Pad value must be a constant.
845     auto padValue = padOp.getConstantPaddingValue();
846     if (!padValue)
847       return failure();
848     // Padding value of existing `xferOp` is unused.
849     if (xferOp.hasOutOfBoundsDim() || xferOp.getMask())
850       return failure();
851 
852     rewriter.updateRootInPlace(xferOp, [&]() {
853       SmallVector<bool> inBounds(xferOp.getVectorType().getRank(), false);
854       xferOp->setAttr(xferOp.getInBoundsAttrName(),
855                       rewriter.getBoolArrayAttr(inBounds));
856       xferOp.getSourceMutable().assign(padOp.source());
857       xferOp.getPaddingMutable().assign(padValue);
858     });
859 
860     return success();
861   }
862 };
863 
864 /// Rewrite use of tensor::PadOp result in TransferWriteOp.
865 /// This pattern rewrites TransferWriteOps that write to a padded tensor
866 /// value, where the same amount of padding is immediately removed again after
867 /// the write. In such cases, the TransferWriteOp can write to the non-padded
868 /// tensor value and apply out-of-bounds masking. E.g.:
869 /// ```
870 /// %0 = tensor.extract_slice ...[...] [%s0, %s1] [1, 1]
871 ///     : tensor<...> to tensor<?x?xf32>
872 /// %1 = tensor.pad %0 ... : tensor<?x?xf32> to tensor<17x5xf32>
873 /// %2 = vector.transfer_write %vec, %1[...]
874 ///     : vector<17x5xf32>, tensor<17x5xf32>
875 /// %r = tensor.extract_slice %2[0, 0] [%s0, %s1] [1, 1]
876 ///     : tensor<17x5xf32> to tensor<?x?xf32>
877 /// ```
878 /// is rewritten to:
879 /// ```
880 /// %0 = tensor.extract_slice ...[...] [%s0, %s1] [1, 1]
881 ///     : tensor<...> to tensor<?x?xf32>
882 /// %r = vector.transfer_write %vec, %0[...] : vector<17x5xf32>,
883 /// tensor<?x?xf32>
884 /// ```
885 /// Note: It is important that the ExtractSliceOp %r resizes the result of the
886 /// TransferWriteOp to the same size as the input of the TensorPadOp (or an
887 /// even smaller size). Otherwise, %r's new (dynamic) dimensions would differ
888 /// from %r's old dimensions.
889 ///
890 /// This rewrite is possible if:
891 /// - Low padding is static 0.
892 /// - `xferOp` has exactly one use, which is an ExtractSliceOp. This
893 ///   ExtractSliceOp trims the same amount of padding that was added
894 ///   beforehand.
895 /// - Single, scalar padding value.
896 struct PadOpVectorizationWithTransferWritePattern
897     : public VectorizePadOpUserPattern<vector::TransferWriteOp> {
898   using VectorizePadOpUserPattern<
899       vector::TransferWriteOp>::VectorizePadOpUserPattern;
900 
901   LogicalResult rewriteUser(PatternRewriter &rewriter, tensor::PadOp padOp,
902                             vector::TransferWriteOp xferOp) const override {
903     // TODO: support 0-d corner case.
904     if (xferOp.getTransferRank() == 0)
905       return failure();
906 
907     // Low padding must be static 0.
908     if (!padOp.hasZeroLowPad())
909       return failure();
910     // Pad value must be a constant.
911     auto padValue = padOp.getConstantPaddingValue();
912     if (!padValue)
913       return failure();
914     // TransferWriteOp result must be directly consumed by an ExtractSliceOp.
915     if (!xferOp->hasOneUse())
916       return failure();
917     auto trimPadding = dyn_cast<tensor::ExtractSliceOp>(*xferOp->user_begin());
918     if (!trimPadding)
919       return failure();
920     // Only static zero offsets supported when trimming padding.
921     if (!trimPadding.hasZeroOffset())
922       return failure();
923     // trimPadding must remove the amount of padding that was added earlier.
924     if (!hasSameTensorSize(padOp.source(), trimPadding))
925       return failure();
926 
927     // Insert the new TransferWriteOp at position of the old TransferWriteOp.
928     rewriter.setInsertionPoint(xferOp);
929 
930     SmallVector<bool> inBounds(xferOp.getVectorType().getRank(), false);
931     auto newXferOp = rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
932         xferOp, padOp.source().getType(), xferOp.getVector(), padOp.source(),
933         xferOp.getIndices(), xferOp.getPermutationMapAttr(), xferOp.getMask(),
934         rewriter.getBoolArrayAttr(inBounds));
935     rewriter.replaceOp(trimPadding, newXferOp->getResult(0));
936 
937     return success();
938   }
939 
940   /// Check if `beforePadding` and `afterTrimming` have the same tensor size,
941   /// i.e., same dimensions.
942   ///
943   /// Dimensions may be static, dynamic or mix of both. In case of dynamic
944   /// dimensions, this function tries to infer the (static) tensor size by
945   /// looking at the defining op and utilizing op-specific knowledge.
946   ///
947   /// This is a conservative analysis. In case equal tensor sizes cannot be
948   /// proven statically, this analysis returns `false` even though the tensor
949   /// sizes may turn out to be equal at runtime.
950   bool hasSameTensorSize(Value beforePadding,
951                          tensor::ExtractSliceOp afterTrimming) const {
952     // If the input to tensor::PadOp is a CastOp, try with with both CastOp
953     // result and CastOp operand.
954     if (auto castOp = beforePadding.getDefiningOp<tensor::CastOp>())
955       if (hasSameTensorSize(castOp.source(), afterTrimming))
956         return true;
957 
958     auto t1 = beforePadding.getType().dyn_cast<RankedTensorType>();
959     auto t2 = afterTrimming.getType().dyn_cast<RankedTensorType>();
960     // Only RankedTensorType supported.
961     if (!t1 || !t2)
962       return false;
963     // Rank of both values must be the same.
964     if (t1.getRank() != t2.getRank())
965       return false;
966 
967     // All static dimensions must be the same. Mixed cases (e.g., dimension
968     // static in `t1` but dynamic in `t2`) are not supported.
969     for (unsigned i = 0; i < t1.getRank(); ++i) {
970       if (t1.isDynamicDim(i) != t2.isDynamicDim(i))
971         return false;
972       if (!t1.isDynamicDim(i) && t1.getDimSize(i) != t2.getDimSize(i))
973         return false;
974     }
975 
976     // Nothing more to check if all dimensions are static.
977     if (t1.getNumDynamicDims() == 0)
978       return true;
979 
980     // All dynamic sizes must be the same. The only supported case at the
981     // moment is when `beforePadding` is an ExtractSliceOp (or a cast
982     // thereof).
983 
984     // Apart from CastOp, only ExtractSliceOp is supported.
985     auto beforeSlice = beforePadding.getDefiningOp<tensor::ExtractSliceOp>();
986     if (!beforeSlice)
987       return false;
988 
989     assert(static_cast<size_t>(t1.getRank()) ==
990            beforeSlice.getMixedSizes().size());
991     assert(static_cast<size_t>(t2.getRank()) ==
992            afterTrimming.getMixedSizes().size());
993 
994     for (unsigned i = 0; i < t1.getRank(); ++i) {
995       // Skip static dimensions.
996       if (!t1.isDynamicDim(i))
997         continue;
998       auto size1 = beforeSlice.getMixedSizes()[i];
999       auto size2 = afterTrimming.getMixedSizes()[i];
1000 
1001       // Case 1: Same value or same constant int.
1002       if (isEqualConstantIntOrValue(size1, size2))
1003         continue;
1004 
1005       // Other cases: Take a deeper look at defining ops of values.
1006       auto v1 = size1.dyn_cast<Value>();
1007       auto v2 = size2.dyn_cast<Value>();
1008       if (!v1 || !v2)
1009         return false;
1010 
1011       // Case 2: Both values are identical AffineMinOps. (Should not happen if
1012       // CSE is run.)
1013       auto minOp1 = v1.getDefiningOp<AffineMinOp>();
1014       auto minOp2 = v2.getDefiningOp<AffineMinOp>();
1015       if (minOp1 && minOp2 && minOp1.getAffineMap() == minOp2.getAffineMap() &&
1016           minOp1.operands() == minOp2.operands())
1017         continue;
1018 
1019       // Add additional cases as needed.
1020     }
1021 
1022     // All tests passed.
1023     return true;
1024   }
1025 };
1026 
1027 /// Rewrite use of tensor::PadOp result in InsertSliceOp. E.g.:
1028 /// ```
1029 /// %0 = tensor.pad %src ... : tensor<?x?xf32> to tensor<17x5xf32>
1030 /// %r = tensor.insert_slice %0
1031 ///     into %dest[%a, %b, 0, 0] [1, 1, 17, 5] [1, 1, 1, 1]
1032 ///     : tensor<17x5xf32> into tensor<?x?x17x5xf32>
1033 /// ```
1034 /// is rewritten to:
1035 /// ```
1036 /// %0 = vector.transfer_read %src[%c0, %c0], %padding
1037 ///     : tensor<?x?xf32>, vector<17x5xf32>
1038 /// %r = vector.transfer_write %0, %dest[%a, %b, %c0, %c0]
1039 ///     {in_bounds = [true, true]} : vector<17x5xf32>, tensor<?x?x17x5xf32>
1040 /// ```
1041 ///
1042 /// This rewrite is possible if:
1043 /// - Low padding is static 0.
1044 /// - `padOp` result shape is static.
1045 /// - The entire padded tensor is inserted.
1046 ///   (Implies that sizes of `insertOp` are all static.)
1047 /// - Only unit strides in `insertOp`.
1048 /// - Single, scalar padding value.
1049 /// - `padOp` result not used as destination.
1050 struct PadOpVectorizationWithInsertSlicePattern
1051     : public VectorizePadOpUserPattern<tensor::InsertSliceOp> {
1052   using VectorizePadOpUserPattern<
1053       tensor::InsertSliceOp>::VectorizePadOpUserPattern;
1054 
1055   LogicalResult rewriteUser(PatternRewriter &rewriter, tensor::PadOp padOp,
1056                             tensor::InsertSliceOp insertOp) const override {
1057     // Low padding must be static 0.
1058     if (!padOp.hasZeroLowPad())
1059       return failure();
1060     // Only unit stride supported.
1061     if (!insertOp.hasUnitStride())
1062       return failure();
1063     // Pad value must be a constant.
1064     auto padValue = padOp.getConstantPaddingValue();
1065     if (!padValue)
1066       return failure();
1067     // Dynamic shapes not supported.
1068     if (!padOp.result().getType().cast<ShapedType>().hasStaticShape())
1069       return failure();
1070     // Pad result not used as destination.
1071     if (insertOp.dest() == padOp.result())
1072       return failure();
1073 
1074     auto vecType = VectorType::get(padOp.getType().getShape(),
1075                                    padOp.getType().getElementType());
1076     unsigned vecRank = vecType.getRank();
1077     unsigned tensorRank = insertOp.getType().getRank();
1078 
1079     // Check if sizes match: Insert the entire tensor into most minor dims.
1080     // (No permutations allowed.)
1081     SmallVector<int64_t> expectedSizes(tensorRank - vecRank, 1);
1082     expectedSizes.append(vecType.getShape().begin(), vecType.getShape().end());
1083     if (!llvm::all_of(
1084             llvm::zip(insertOp.getMixedSizes(), expectedSizes), [](auto it) {
1085               return getConstantIntValue(std::get<0>(it)) == std::get<1>(it);
1086             }))
1087       return failure();
1088 
1089     // Insert the TransferReadOp and TransferWriteOp at the position of the
1090     // InsertSliceOp.
1091     rewriter.setInsertionPoint(insertOp);
1092 
1093     // Generate TransferReadOp: Read entire source tensor and add high
1094     // padding.
1095     SmallVector<Value> readIndices(
1096         vecRank, rewriter.create<arith::ConstantIndexOp>(padOp.getLoc(), 0));
1097     auto read = rewriter.create<vector::TransferReadOp>(
1098         padOp.getLoc(), vecType, padOp.source(), readIndices, padValue);
1099 
1100     // Generate TransferWriteOp: Write to InsertSliceOp's dest tensor at
1101     // specified offsets. Write is fully in-bounds because a InsertSliceOp's
1102     // source must fit into the destination at the specified offsets.
1103     auto writeIndices =
1104         ofrToIndexValues(rewriter, padOp.getLoc(), insertOp.getMixedOffsets());
1105     SmallVector<bool> inBounds(vecRank, true);
1106     rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(
1107         insertOp, read, insertOp.dest(), writeIndices,
1108         ArrayRef<bool>{inBounds});
1109 
1110     return success();
1111   }
1112 };
1113 
1114 void mlir::linalg::populatePadOpVectorizationPatterns(
1115     RewritePatternSet &patterns, PatternBenefit baseBenefit) {
1116   patterns.add<GenericPadOpVectorizationPattern>(patterns.getContext(),
1117                                                  baseBenefit);
1118   // Try these specialized patterns first before resorting to the generic one.
1119   patterns.add<PadOpVectorizationWithTransferReadPattern,
1120                PadOpVectorizationWithTransferWritePattern,
1121                PadOpVectorizationWithInsertSlicePattern>(
1122       patterns.getContext(), baseBenefit.getBenefit() + 1);
1123 }
1124 
1125 //----------------------------------------------------------------------------//
1126 // Forwarding patterns
1127 //----------------------------------------------------------------------------//
1128 
1129 /// Check whether there is any interleaved use of any `values` between
1130 /// `firstOp` and `secondOp`. Conservatively return `true` if any op or value
1131 /// is in a different block.
1132 static bool mayExistInterleavedUses(Operation *firstOp, Operation *secondOp,
1133                                     ValueRange values) {
1134   if (firstOp->getBlock() != secondOp->getBlock() ||
1135       !firstOp->isBeforeInBlock(secondOp)) {
1136     LDBG("interleavedUses precondition failed, firstOp: "
1137          << *firstOp << ", second op: " << *secondOp);
1138     return true;
1139   }
1140   for (auto v : values) {
1141     for (auto &u : v.getUses()) {
1142       Operation *owner = u.getOwner();
1143       if (owner == firstOp || owner == secondOp)
1144         continue;
1145       // TODO: this is too conservative, use dominance info in the future.
1146       if (owner->getBlock() == firstOp->getBlock() &&
1147           (owner->isBeforeInBlock(firstOp) || secondOp->isBeforeInBlock(owner)))
1148         continue;
1149       LDBG(" found interleaved op " << *owner << ", firstOp: " << *firstOp
1150                                     << ", second op: " << *secondOp);
1151       return true;
1152     }
1153   }
1154   return false;
1155 }
1156 
1157 /// Return the unique subview use of `v` if it is indeed unique, null
1158 /// otherwise.
1159 static memref::SubViewOp getSubViewUseIfUnique(Value v) {
1160   memref::SubViewOp subViewOp;
1161   for (auto &u : v.getUses()) {
1162     if (auto newSubViewOp = dyn_cast<memref::SubViewOp>(u.getOwner())) {
1163       if (subViewOp)
1164         return memref::SubViewOp();
1165       subViewOp = newSubViewOp;
1166     }
1167   }
1168   return subViewOp;
1169 }
1170 
1171 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
1172 /// when available.
1173 LogicalResult LinalgCopyVTRForwardingPattern::matchAndRewrite(
1174     vector::TransferReadOp xferOp, PatternRewriter &rewriter) const {
1175 
1176   // TODO: support mask.
1177   if (xferOp.getMask())
1178     return failure();
1179 
1180   // Transfer into `view`.
1181   Value viewOrAlloc = xferOp.getSource();
1182   if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() &&
1183       !viewOrAlloc.getDefiningOp<memref::AllocOp>())
1184     return failure();
1185 
1186   LDBG(viewOrAlloc);
1187 
1188   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
1189   memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
1190   if (!subViewOp)
1191     return failure();
1192   Value subView = subViewOp.getResult();
1193   LDBG("with subView " << subView);
1194 
1195   // Find the copy into `subView` without interleaved uses.
1196   memref::CopyOp copyOp;
1197   for (auto &u : subView.getUses()) {
1198     if (auto newCopyOp = dyn_cast<memref::CopyOp>(u.getOwner())) {
1199       assert(newCopyOp.target().getType().isa<MemRefType>());
1200       if (newCopyOp.target() != subView)
1201         continue;
1202       LDBG("copy candidate " << *newCopyOp);
1203       if (mayExistInterleavedUses(newCopyOp, xferOp, {viewOrAlloc, subView}))
1204         continue;
1205       copyOp = newCopyOp;
1206       break;
1207     }
1208   }
1209   if (!copyOp)
1210     return failure();
1211   LDBG("with copy " << *copyOp);
1212 
1213   // Find the fill into `viewOrAlloc` without interleaved uses before the
1214   // copy.
1215   FillOp maybeFillOp;
1216   for (auto &u : viewOrAlloc.getUses()) {
1217     if (auto newFillOp = dyn_cast<FillOp>(u.getOwner())) {
1218       assert(newFillOp.output().getType().isa<MemRefType>());
1219       if (newFillOp.output() != viewOrAlloc)
1220         continue;
1221       LDBG("fill candidate " << *newFillOp);
1222       if (mayExistInterleavedUses(newFillOp, copyOp, {viewOrAlloc, subView}))
1223         continue;
1224       maybeFillOp = newFillOp;
1225       break;
1226     }
1227   }
1228   // Ensure padding matches.
1229   if (maybeFillOp && xferOp.getPadding() != maybeFillOp.value())
1230     return failure();
1231   if (maybeFillOp)
1232     LDBG("with maybeFillOp " << *maybeFillOp);
1233 
1234   // `in` is the subview that memref.copy reads. Replace it.
1235   Value in = copyOp.source();
1236 
1237   // memref.copy + linalg.fill can be used to create a padded local buffer.
1238   // The `masked` attribute is only valid on this padded buffer.
1239   // When forwarding to vector.transfer_read, the attribute must be reset
1240   // conservatively.
1241   Value res = rewriter.create<vector::TransferReadOp>(
1242       xferOp.getLoc(), xferOp.getVectorType(), in, xferOp.getIndices(),
1243       xferOp.getPermutationMapAttr(), xferOp.getPadding(), xferOp.getMask(),
1244       // in_bounds is explicitly reset
1245       /*inBoundsAttr=*/ArrayAttr());
1246 
1247   if (maybeFillOp)
1248     rewriter.eraseOp(maybeFillOp);
1249   rewriter.eraseOp(copyOp);
1250   rewriter.replaceOp(xferOp, res);
1251 
1252   return success();
1253 }
1254 
1255 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
1256 /// when available.
1257 LogicalResult LinalgCopyVTWForwardingPattern::matchAndRewrite(
1258     vector::TransferWriteOp xferOp, PatternRewriter &rewriter) const {
1259   // TODO: support mask.
1260   if (xferOp.getMask())
1261     return failure();
1262 
1263   // Transfer into `viewOrAlloc`.
1264   Value viewOrAlloc = xferOp.getSource();
1265   if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() &&
1266       !viewOrAlloc.getDefiningOp<memref::AllocOp>())
1267     return failure();
1268 
1269   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
1270   memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
1271   if (!subViewOp)
1272     return failure();
1273   Value subView = subViewOp.getResult();
1274 
1275   // Find the copy from `subView` without interleaved uses.
1276   memref::CopyOp copyOp;
1277   for (auto &u : subViewOp.getResult().getUses()) {
1278     if (auto newCopyOp = dyn_cast<memref::CopyOp>(u.getOwner())) {
1279       if (newCopyOp.source() != subView)
1280         continue;
1281       if (mayExistInterleavedUses(xferOp, newCopyOp, {viewOrAlloc, subView}))
1282         continue;
1283       copyOp = newCopyOp;
1284       break;
1285     }
1286   }
1287   if (!copyOp)
1288     return failure();
1289 
1290   // `out` is the subview copied into that we replace.
1291   assert(copyOp.target().getType().isa<MemRefType>());
1292   Value out = copyOp.target();
1293 
1294   // Forward vector.transfer into copy.
1295   // memref.copy + linalg.fill can be used to create a padded local buffer.
1296   // The `masked` attribute is only valid on this padded buffer.
1297   // When forwarding to vector.transfer_write, the attribute must be reset
1298   // conservatively.
1299   rewriter.create<vector::TransferWriteOp>(
1300       xferOp.getLoc(), xferOp.getVector(), out, xferOp.getIndices(),
1301       xferOp.getPermutationMapAttr(), xferOp.getMask(),
1302       // in_bounds is explicitly reset
1303       /*inBoundsAttr=*/ArrayAttr());
1304 
1305   rewriter.eraseOp(copyOp);
1306   rewriter.eraseOp(xferOp);
1307 
1308   return success();
1309 }
1310 
1311 //===----------------------------------------------------------------------===//
1312 // Convolution vectorization patterns
1313 //===----------------------------------------------------------------------===//
1314 
1315 template <int N>
1316 static void bindShapeDims(ShapedType shapedType) {}
1317 
1318 template <int N, typename IntTy, typename... IntTy2>
1319 static void bindShapeDims(ShapedType shapedType, IntTy &val, IntTy2 &...vals) {
1320   val = shapedType.getShape()[N];
1321   bindShapeDims<N + 1, IntTy2 &...>(shapedType, vals...);
1322 }
1323 
1324 /// Bind a pack of int& to the leading dimensions of shapedType.getShape().
1325 template <typename... IntTy>
1326 static void bindShapeDims(ShapedType shapedType, IntTy &...vals) {
1327   bindShapeDims<0>(shapedType, vals...);
1328 }
1329 
1330 namespace {
1331 /// Generate a vector implementation for either:
1332 /// ```
1333 ///   Op def: (     n,     w,     c,    kw,    f  )
1334 ///    Iters: ({Par(), Par(), Par(), Red(), Red()})
1335 ///   Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c, f}, {n, w, f}}
1336 /// ```
1337 /// kw is unrolled, w is unrolled iff dilationW > 1.
1338 ///
1339 /// or
1340 ///
1341 /// ```
1342 ///   Op def: (     n,     w,     c,    kw )
1343 ///    Iters: ({Par(), Par(), Par(), Red()})
1344 ///   Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c}, {n, w, c}}
1345 /// ```
1346 /// kw is unrolled, w is unrolled iff dilationW > 1.
1347 struct Conv1DNwcGenerator : public StructuredGenerator<LinalgOp> {
1348   Conv1DNwcGenerator(OpBuilder &builder, LinalgOp linalgOp, int strideW,
1349                      int dilationW)
1350       : StructuredGenerator<LinalgOp>(builder, linalgOp), strideW(strideW),
1351         dilationW(dilationW) {
1352     // Determine whether `linalgOp` can be generated with this generator
1353     if (linalgOp.getNumInputs() != 2 || linalgOp.getNumOutputs() != 1)
1354       return;
1355     lhsShaped = linalgOp.inputs()[0];
1356     rhsShaped = linalgOp.inputs()[1];
1357     resShaped = linalgOp.outputs()[0];
1358     lhsShapedType = lhsShaped.getType().dyn_cast<ShapedType>();
1359     rhsShapedType = rhsShaped.getType().dyn_cast<ShapedType>();
1360     resShapedType = resShaped.getType().dyn_cast<ShapedType>();
1361     if (!lhsShapedType || !rhsShapedType || !resShapedType)
1362       return;
1363     if (lhsShapedType.getRank() != 3 ||
1364         (rhsShapedType.getRank() != 2 && rhsShapedType.getRank() != 3) ||
1365         resShapedType.getRank() != 3)
1366       return;
1367 
1368     // Check for reduction `add` preceded by `mul`.
1369     Operation *reduceOp = matchLinalgReduction(linalgOp.getOutputOperand(0));
1370     if (!reduceOp)
1371       return;
1372     llvm::Optional<vector::CombiningKind> maybeKind;
1373     maybeKind = getCombinerOpKind(reduceOp);
1374     if (!maybeKind || *maybeKind != vector::CombiningKind::ADD)
1375       return;
1376     maybeKind = getCombinerOpKind(&(linalgOp->getRegion(0).front().front()));
1377     if (!maybeKind || *maybeKind != vector::CombiningKind::MUL)
1378       return;
1379 
1380     // The op is now known to be valid.
1381     valid = true;
1382   }
1383 
1384   /// Generate a vector implementation for:
1385   /// ```
1386   ///   Op def: (     n,     w,     c,    kw,    f  )
1387   ///    Iters: ({Par(), Par(), Par(), Red(), Red()})
1388   ///   Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c, f}, {n, w, f}}
1389   /// ```
1390   /// kw is always unrolled.
1391   /// TODO: w (resp. kw) is unrolled when the strideW ( resp. dilationW) is
1392   /// > 1.
1393   FailureOr<Operation *> conv() {
1394     if (!valid)
1395       return failure();
1396 
1397     int64_t nSize, wSize, cSize, kwSize, fSize;
1398     // kernel{kw, c, f}
1399     bindShapeDims(rhsShapedType, kwSize, cSize, fSize);
1400     // out{n, w, f}
1401     bindShapeDims(resShapedType, nSize, wSize);
1402 
1403     vector::TransferWriteOp write;
1404     Value zero = builder.create<arith::ConstantIndexOp>(loc, 0);
1405 
1406     // w is unrolled (i.e. wSizeStep == 1) iff strideW > 1.
1407     // When strideW == 1, we can batch the contiguous loads and avoid
1408     // unrolling
1409     int64_t wSizeStep = strideW == 1 ? wSize : 1;
1410 
1411     Type lhsEltType = lhsShapedType.getElementType();
1412     Type rhsEltType = rhsShapedType.getElementType();
1413     Type resEltType = resShapedType.getElementType();
1414     VectorType lhsType = VectorType::get(
1415         {nSize,
1416          // iw = ow * sw + kw *  dw - 1
1417          //   (i.e. 16 convolved with 3 (@stride 1 dilation 1) -> 14)
1418          // Perform the proper inclusive -> exclusive -> inclusive.
1419          ((wSize - 1) * strideW + 1) + ((kwSize - 1) * dilationW + 1) - 1,
1420          cSize},
1421         lhsEltType);
1422     VectorType rhsType = VectorType::get({kwSize, cSize, fSize}, rhsEltType);
1423     VectorType resType = VectorType::get({nSize, wSize, fSize}, resEltType);
1424 
1425     // Read lhs slice of size {w * strideW + kw * dilationW, c, f} @ [0, 0,
1426     // 0].
1427     Value lhs = builder.create<vector::TransferReadOp>(
1428         loc, lhsType, lhsShaped, ValueRange{zero, zero, zero});
1429     // Read rhs slice of size {kw, c, f} @ [0, 0, 0].
1430     Value rhs = builder.create<vector::TransferReadOp>(
1431         loc, rhsType, rhsShaped, ValueRange{zero, zero, zero});
1432     // Read res slice of size {n, w, f} @ [0, 0, 0].
1433     Value res = builder.create<vector::TransferReadOp>(
1434         loc, resType, resShaped, ValueRange{zero, zero, zero});
1435 
1436     //===------------------------------------------------------------------===//
1437     // Begin vector-only rewrite part
1438     //===------------------------------------------------------------------===//
1439     // Unroll along kw and read slices of lhs and rhs.
1440     SmallVector<Value> lhsVals, rhsVals, resVals;
1441     // Extract lhs slice of size {n, wSizeStep, c} @ [0, sw * w + dw * kw, 0].
1442     for (int64_t kw = 0; kw < kwSize; ++kw) {
1443       for (int64_t w = 0; w < wSize; w += wSizeStep) {
1444         lhsVals.push_back(builder.create<vector::ExtractStridedSliceOp>(
1445             loc, lhs,
1446             /*offsets=*/ArrayRef<int64_t>{0, w * strideW + kw * dilationW, 0},
1447             /*sizes=*/ArrayRef<int64_t>{nSize, wSizeStep, cSize},
1448             /*strides=*/ArrayRef<int64_t>{1, 1, 1}));
1449       }
1450     }
1451     // Extract rhs slice of size {c, f} @ [kw].
1452     for (int64_t kw = 0; kw < kwSize; ++kw) {
1453       rhsVals.push_back(builder.create<vector::ExtractOp>(
1454           loc, rhs, /*offsets=*/ArrayRef<int64_t>{kw}));
1455     }
1456     // Extract res slice: {n, wSizeStep, f} @ [0, w, 0].
1457     for (int64_t w = 0; w < wSize; w += wSizeStep) {
1458       resVals.push_back(builder.create<vector::ExtractStridedSliceOp>(
1459           loc, res,
1460           /*offsets=*/ArrayRef<int64_t>{0, w, 0},
1461           /*sizes=*/ArrayRef<int64_t>{nSize, wSizeStep, fSize},
1462           /*strides=*/ArrayRef<int64_t>{1, 1, 1}));
1463     }
1464 
1465     auto linearIndex = [&](int64_t kw, int64_t w) {
1466       return kw * (wSize / wSizeStep) + w;
1467     };
1468 
1469     // Compute contraction: O{n, w, f} += I{n, sw * w + dw * kw, c} * F{c, f}
1470     for (int64_t kw = 0; kw < kwSize; ++kw) {
1471       for (int64_t w = 0; w < wSize; w += wSizeStep) {
1472         resVals[w] = conv1dSliceAsContraction(
1473             builder, loc, lhsVals[linearIndex(kw, w)], rhsVals[kw], resVals[w]);
1474       }
1475     }
1476 
1477     // Write back res slice: {n, wSizeStep, f} @ [0, w, 0].
1478     // This does not depend on kw.
1479     for (int64_t w = 0; w < wSize; w += wSizeStep) {
1480       res = builder.create<vector::InsertStridedSliceOp>(
1481           loc, resVals[w], res,
1482           /*offsets=*/ArrayRef<int64_t>{0, w, 0},
1483           /*strides=*/ArrayRef<int64_t>{1, 1, 1});
1484     }
1485     //===------------------------------------------------------------------===//
1486     // End vector-only rewrite part
1487     //===------------------------------------------------------------------===//
1488 
1489     // Write back res slice of size {n, w, f} @ [0, 0, 0].
1490     return builder
1491         .create<vector::TransferWriteOp>(loc, res, resShaped,
1492                                          ValueRange{zero, zero, zero})
1493         .getOperation();
1494   }
1495 
1496   // Create a contraction: lhs{n, w, c} * rhs{c, f} -> res{n, w, f}
1497   Value conv1dSliceAsContraction(OpBuilder &b, Location loc, Value lhs,
1498                                  Value rhs, Value res) {
1499     StringRef par = Par().strRef, red = Red().strRef;
1500     AffineExpr n, w, f, c;
1501     bindDims(ctx, n, w, f, c);
1502     return builder.create<vector::ContractionOp>(
1503         loc, lhs, rhs, res,
1504         /*indexingMaps=*/MapList{{n, w, c}, {c, f}, {n, w, f}},
1505         /*iteratorTypes=*/ArrayRef<StringRef>{par, par, par, red});
1506   }
1507 
1508   /// Generate a vector implementation for:
1509   /// ```
1510   ///   Op def: (     n,     w,     c,    kw)
1511   ///    Iters: ({Par(), Par(), Par(), Red()})
1512   ///   Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c}, {n, w, c}}
1513   /// ```
1514   /// kw is always unrolled.
1515   /// TODO: w (resp. kw) is unrolled when the strideW ( resp. dilationW) is
1516   /// > 1.
1517   FailureOr<Operation *> depthwiseConv() {
1518     if (!valid)
1519       return failure();
1520 
1521     int64_t nSize, wSize, cSize, kwSize;
1522     // kernel{kw, c}
1523     bindShapeDims(rhsShapedType, kwSize, cSize);
1524     // out{n, w, c}
1525     bindShapeDims(resShapedType, nSize, wSize);
1526 
1527     vector::TransferWriteOp write;
1528     Value zero = builder.create<arith::ConstantIndexOp>(loc, 0);
1529 
1530     // w is unrolled (i.e. wSizeStep == 1) iff strideW > 1.
1531     // When strideW == 1, we can batch the contiguous loads and avoid
1532     // unrolling
1533     int64_t wSizeStep = strideW == 1 ? wSize : 1;
1534 
1535     Type lhsEltType = lhsShapedType.getElementType();
1536     Type rhsEltType = rhsShapedType.getElementType();
1537     Type resEltType = resShapedType.getElementType();
1538     VectorType lhsType = VectorType::get(
1539         {nSize,
1540          // iw = ow * sw + kw *  dw - 1
1541          //   (i.e. 16 convolved with 3 (@stride 1 dilation 1) -> 14)
1542          ((wSize - 1) * strideW + 1) + ((kwSize - 1) * dilationW + 1) - 1,
1543          cSize},
1544         lhsEltType);
1545     VectorType rhsType = VectorType::get({kwSize, cSize}, rhsEltType);
1546     VectorType resType = VectorType::get({nSize, wSize, cSize}, resEltType);
1547 
1548     // Read lhs slice of size {n, w * strideW + kw * dilationW, c} @ [0, 0,
1549     // 0].
1550     Value lhs = builder.create<vector::TransferReadOp>(
1551         loc, lhsType, lhsShaped, ValueRange{zero, zero, zero});
1552     // Read rhs slice of size {kw, c} @ [0, 0].
1553     Value rhs = builder.create<vector::TransferReadOp>(loc, rhsType, rhsShaped,
1554                                                        ValueRange{zero, zero});
1555     // Read res slice of size {n, w, c} @ [0, 0, 0].
1556     Value res = builder.create<vector::TransferReadOp>(
1557         loc, resType, resShaped, ValueRange{zero, zero, zero});
1558 
1559     //===------------------------------------------------------------------===//
1560     // Begin vector-only rewrite part
1561     //===------------------------------------------------------------------===//
1562     // Unroll along kw and read slices of lhs and rhs.
1563     SmallVector<Value> lhsVals, rhsVals, resVals;
1564     // Extract lhs slice of size {n, wSizeStep, c}
1565     //   @ [0, sw * w + dw * kw, 0].
1566     for (int64_t kw = 0; kw < kwSize; ++kw) {
1567       for (int64_t w = 0; w < wSize; w += wSizeStep) {
1568         lhsVals.push_back(builder.create<vector::ExtractStridedSliceOp>(
1569             loc, lhs,
1570             /*offsets=*/ArrayRef<int64_t>{0, w * strideW + kw * dilationW, 0},
1571             /*sizes=*/ArrayRef<int64_t>{nSize, wSizeStep, cSize},
1572             /*strides=*/ArrayRef<int64_t>{1, 1, 1}));
1573       }
1574     }
1575     // Extract rhs slice of size {c} @ [kw].
1576     for (int64_t kw = 0; kw < kwSize; ++kw) {
1577       rhsVals.push_back(builder.create<vector::ExtractOp>(
1578           loc, rhs, /*offsets=*/ArrayRef<int64_t>{kw}));
1579     }
1580     // Extract res slice: {n, wSizeStep, c} @ [0, w, 0].
1581     for (int64_t w = 0; w < wSize; w += wSizeStep) {
1582       resVals.push_back(builder.create<vector::ExtractStridedSliceOp>(
1583           loc, res,
1584           /*offsets=*/ArrayRef<int64_t>{0, w, 0},
1585           /*sizes=*/ArrayRef<int64_t>{nSize, wSizeStep, cSize},
1586           /*strides=*/ArrayRef<int64_t>{1, 1, 1}));
1587     }
1588 
1589     auto linearIndex = [&](int64_t kw, int64_t w) {
1590       return kw * (wSize / wSizeStep) + w;
1591     };
1592 
1593     // Compute contraction: O{n, w, c} += I{n, sw * w + dw * kw, c} * F{c}
1594     for (int64_t kw = 0; kw < kwSize; ++kw) {
1595       for (int64_t w = 0; w < wSize; w += wSizeStep) {
1596         resVals[w] = depthwiseConv1dSliceAsFma(
1597             builder, loc, lhsVals[linearIndex(kw, w)], rhsVals[kw], resVals[w]);
1598       }
1599     }
1600 
1601     // Write back res slice: {n, wSizeStep, c} @ [0, w, 0].
1602     // This does not depend on kw.
1603     for (int64_t w = 0; w < wSize; w += wSizeStep) {
1604       res = builder.create<vector::InsertStridedSliceOp>(
1605           loc, resVals[w], res,
1606           /*offsets=*/ArrayRef<int64_t>{0, w, 0},
1607           /*strides=*/ArrayRef<int64_t>{1, 1, 1});
1608     }
1609     //===------------------------------------------------------------------===//
1610     // End vector-only rewrite part
1611     //===------------------------------------------------------------------===//
1612 
1613     // Write back res slice of size {n, w, c} @ [0, 0, 0].
1614     return builder
1615         .create<vector::TransferWriteOp>(loc, res, resShaped,
1616                                          ValueRange{zero, zero, zero})
1617         .getOperation();
1618   }
1619 
1620   /// Lower lhs{n, w, c} * rhs{c} -> res{n, w, c} to fma.
1621   Value depthwiseConv1dSliceAsFma(OpBuilder &b, Location loc, Value lhs,
1622                                   Value rhs, Value res) {
1623     Value bcast = builder.create<vector::BroadcastOp>(loc, res.getType(), rhs);
1624     return b.create<vector::FMAOp>(loc, lhs, bcast, res);
1625   }
1626 
1627   /// Entry point that transposes into the common form:
1628   ///   {{n, strideW * w + dilationW * kw, c}, {kw, c, f}, {n, w, f}}
1629   FailureOr<Operation *> generateConv() {
1630     AffineExpr n, w, f, kw, c;
1631     bindDims(ctx, n, w, f, kw, c);
1632     if (!iters({Par(), Par(), Par(), Red(), Red()}))
1633       return failure();
1634 
1635     // No transposition needed.
1636     if (layout({/*lhsIndex*/ {n, strideW * w + dilationW * kw, c},
1637                 /*rhsIndex*/ {kw, c, f},
1638                 /*resIndex*/ {n, w, f}}))
1639       return conv();
1640     return failure();
1641   }
1642 
1643   /// Entry point that transposes into the common form:
1644   ///   {{n, strideW * w + dilationW * kw, c}, {kw, c}, {n, w, c}}
1645   FailureOr<Operation *> generateDilatedConv() {
1646     AffineExpr n, w, c, kw;
1647     bindDims(ctx, n, w, c, kw);
1648     if (!iters({Par(), Par(), Par(), Red()}))
1649       return failure();
1650 
1651     // No transposition needed.
1652     if (layout({/*lhsIndex*/ {n, strideW * w + dilationW * kw, c},
1653                 /*rhsIndex*/ {kw, c},
1654                 /*resIndex*/ {n, w, c}}))
1655       return depthwiseConv();
1656     return failure();
1657   }
1658 
1659 private:
1660   bool valid = false;
1661   int strideW, dilationW;
1662   Value lhsShaped, rhsShaped, resShaped;
1663   ShapedType lhsShapedType, rhsShapedType, resShapedType;
1664 };
1665 } // namespace
1666 
1667 /// Helper function to vectorize a LinalgOp with convolution semantics.
1668 // TODO: extend the generic vectorization to support windows and drop this.
1669 static FailureOr<Operation *> vectorizeConvolution(OpBuilder &b, LinalgOp op) {
1670   // The ConvolutionOpInterface gives us guarantees of existence for
1671   // strides/dilations. However, we do not need to rely on those, we can simply
1672   // use them if present, otherwise use the default and let the generic conv.
1673   // matcher in the ConvGenerator succeed or fail.
1674   auto strides = op->getAttrOfType<DenseIntElementsAttr>("strides");
1675   auto dilations = op->getAttrOfType<DenseIntElementsAttr>("dilations");
1676   auto stride = strides ? *strides.getValues<uint64_t>().begin() : 1;
1677   auto dilation = dilations ? *dilations.getValues<uint64_t>().begin() : 1;
1678   Conv1DNwcGenerator e(b, op, stride, dilation);
1679   auto res = e.generateConv();
1680   if (succeeded(res))
1681     return res;
1682   return e.generateDilatedConv();
1683 }
1684 
1685 struct VectorizeConvolution : public OpInterfaceRewritePattern<LinalgOp> {
1686   using OpInterfaceRewritePattern::OpInterfaceRewritePattern;
1687 
1688   LogicalResult matchAndRewrite(LinalgOp op,
1689                                 PatternRewriter &rewriter) const override {
1690     FailureOr<Operation *> resultOrFail = vectorizeConvolution(rewriter, op);
1691     if (failed(resultOrFail))
1692       return failure();
1693     Operation *newOp = *resultOrFail;
1694     if (newOp->getNumResults() == 0) {
1695       rewriter.eraseOp(op.getOperation());
1696       return success();
1697     }
1698     assert(newOp->getNumResults() == 1 && "expected single result");
1699     rewriter.replaceOp(op.getOperation(), newOp->getResult(0));
1700     return success();
1701   }
1702 };
1703 
1704 void mlir::linalg::populateConvolutionVectorizationPatterns(
1705     RewritePatternSet &patterns, PatternBenefit benefit) {
1706   patterns.add<VectorizeConvolution>(patterns.getContext(), benefit);
1707 }
1708