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