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/Dialect/Linalg/Analysis/DependenceAnalysis.h"
14 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
15 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
16 #include "mlir/Dialect/Linalg/Utils/Utils.h"
17 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h"
18 #include "mlir/Dialect/Utils/StructuredOpsUtils.h"
19 #include "mlir/Dialect/Vector/EDSC/Intrinsics.h"
20 #include "mlir/Dialect/Vector/VectorOps.h"
21 #include "mlir/IR/AffineExpr.h"
22 #include "mlir/IR/Matchers.h"
23 #include "mlir/IR/PatternMatch.h"
24 #include "mlir/Pass/Pass.h"
25 #include "mlir/Support/LLVM.h"
26 #include "mlir/Transforms/RegionUtils.h"
27 #include "llvm/ADT/ScopeExit.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <type_traits>
31 
32 using namespace mlir;
33 using namespace mlir::edsc;
34 using namespace mlir::edsc::intrinsics;
35 using namespace mlir::linalg;
36 
37 using llvm::dbgs;
38 
39 #define DEBUG_TYPE "linalg-vectorization"
40 
41 /// Return the unique instance of OpType in `block` if it is indeed unique.
42 /// Return null if none or more than 1 instances exist.
43 template <typename OpType>
44 static OpType getSingleOpOfType(Block &block) {
45   OpType res;
46   block.walk([&](OpType op) {
47     if (res) {
48       res = nullptr;
49       return WalkResult::interrupt();
50     }
51     res = op;
52     return WalkResult::advance();
53   });
54   return res;
55 }
56 
57 /// Helper data structure to represent the result of vectorization.
58 /// In certain specific cases, like terminators, we do not want to propagate/
59 enum VectorizationStatus {
60   /// Op failed to vectorize.
61   Failure = 0,
62   /// Op vectorized and custom function took care of replacement logic
63   NoReplace,
64   /// Op vectorized into a new Op whose results will replace original Op's
65   /// results.
66   NewOp
67   // TODO: support values if Op vectorized to Many-Ops whose results we need to
68   // aggregate for replacement.
69 };
70 struct VectorizationResult {
71   /// Return status from vectorizing the current op.
72   enum VectorizationStatus status = VectorizationStatus::Failure;
73   /// New vectorized operation to replace the current op.
74   /// Replacement behavior is specified by `status`.
75   Operation *newOp;
76 };
77 
78 /// Return a vector type of the same shape and element type as the (assumed)
79 /// ShapedType of `v`.
80 static VectorType extractVectorTypeFromShapedValue(Value v) {
81   auto st = v.getType().cast<ShapedType>();
82   if (st.isa<MemRefType>() && st.getShape().empty())
83     return VectorType();
84   return VectorType::get(st.getShape(), st.getElementType());
85 }
86 
87 /// Build a vector.transfer_read from `source` at indices set to all `0`.
88 /// If source has rank zero, build an std.load.
89 /// Return the produced value.
90 static Value buildVectorRead(OpBuilder &builder, Value source) {
91   edsc::ScopedContext scope(builder);
92   auto shapedType = source.getType().cast<ShapedType>();
93   if (VectorType vectorType = extractVectorTypeFromShapedValue(source)) {
94     SmallVector<Value> indices(shapedType.getRank(), std_constant_index(0));
95     return vector_transfer_read(vectorType, source, indices);
96   }
97   return std_load(source);
98 }
99 
100 /// Build a vector.transfer_write of `value` into `dest` at indices set to all
101 /// `0`. If `dest` has null rank, build an std.store.
102 /// Return the produced value or null if no value is produced.
103 static Value buildVectorWrite(OpBuilder &builder, Value value, Value dest) {
104   edsc::ScopedContext scope(builder);
105   Operation *write;
106   auto shapedType = dest.getType().cast<ShapedType>();
107   if (VectorType vectorType = extractVectorTypeFromShapedValue(dest)) {
108     SmallVector<Value> indices(shapedType.getRank(), std_constant_index(0));
109     if (vectorType != value.getType())
110       value = vector_broadcast(vectorType, value);
111     write = vector_transfer_write(value, dest, indices);
112   } else {
113     write = std_store(value, dest);
114   }
115   LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: vectorized op: " << *write);
116   if (!write->getResults().empty())
117     return write->getResult(0);
118   return Value();
119 }
120 
121 /// If value of assumed VectorType has a shape different than `shape`, buil and
122 /// return a new vector.broadcast to `shape`.
123 /// Otherwise, just return value.
124 static Value broadcastIfNeeded(OpBuilder &builder, Value value,
125                                ArrayRef<int64_t> shape) {
126   auto vecType = value.getType().dyn_cast<VectorType>();
127   if (shape.empty() || (vecType != nullptr && vecType.getShape() == shape))
128     return value;
129   auto newVecType = VectorType::get(shape, vecType ? vecType.getElementType()
130                                                    : value.getType());
131   return builder.create<vector::BroadcastOp>(
132       builder.getInsertionPoint()->getLoc(), newVecType, value);
133 }
134 
135 // Custom vectorization function type. Produce a vector form of Operation*
136 // assuming all its vectorized operands are already in the BlockAndValueMapping.
137 // Return nullptr if the Operation cannot be vectorized.
138 using CustomVectorizationHook = std::function<VectorizationResult(
139     Operation *, const BlockAndValueMapping &)>;
140 
141 /// Helper function to vectorize the terminator of a `linalgOp`. New result
142 /// vector values are appended to `results`.
143 /// Return VectorizationStatus::NoReplace to signal the vectorization algorithm
144 /// that it should not try to map produced operations: this is the purpose of
145 /// the `results` argument to capture such values and make them available for
146 /// RAUW to the vectorization algorithm.
147 /// This function is meant to be used as a CustomVectorizationHook.
148 static VectorizationResult
149 vectorizeLinalgYield(OpBuilder &builder, Operation *op,
150                      const BlockAndValueMapping &bvm, LinalgOp linalgOp,
151                      SmallVectorImpl<Value> &results) {
152   auto yieldOp = dyn_cast<linalg::YieldOp>(op);
153   if (!yieldOp)
154     return VectorizationResult{VectorizationStatus::Failure, nullptr};
155   for (auto outputs : llvm::enumerate(yieldOp.values())) {
156     // TODO: Scan for an opportunity for reuse.
157     // TODO: use a map.
158     Value vectorValue = bvm.lookup(outputs.value());
159     Value result = buildVectorWrite(builder, vectorValue,
160                                     linalgOp.getOutput(outputs.index()));
161     if (result)
162       results.push_back(result);
163   }
164   return VectorizationResult{VectorizationStatus::NoReplace, nullptr};
165 }
166 
167 /// Generic vectorization for a single operation `op`, given already vectorized
168 /// operands carried by `bvm`. Vectorization occurs as follows:
169 ///   1. Try to apply any of the `customVectorizationHooks` and return its
170 ///   result on success.
171 ///   2. Clone any constant in the current scope without vectorization: each
172 ///   consumer of the constant will later determine the shape to which the
173 ///   constant needs to be broadcast to.
174 ///   3. Fail on any remaining non `ElementwiseMappable` op. It is the purpose
175 ///   of the `customVectorizationHooks` to cover such cases.
176 ///   4. Clone `op` in vector form to a vector of shape prescribed by the first
177 ///   operand of maximal rank. Other operands have smaller rank and are
178 ///   broadcast accordingly. It is assumed this broadcast is always legal,
179 ///   otherwise, it means one of the `customVectorizationHooks` is incorrect.
180 ///
181 /// This function assumes all operands of `op` have been vectorized and are in
182 /// the `bvm` mapping. As a consequence, this function is meant to be called on
183 /// a topologically-sorted list of ops.
184 /// This function does not update `bvm` but returns a VectorizationStatus that
185 /// instructs the caller what `bvm` update needs to occur.
186 static VectorizationResult
187 vectorizeOneOp(OpBuilder &builder, Operation *op,
188                const BlockAndValueMapping &bvm,
189                ArrayRef<CustomVectorizationHook> customVectorizationHooks) {
190   LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: vectorize op " << *op);
191 
192   // 1. Try to apply any CustomVectorizationHook.
193   if (!customVectorizationHooks.empty()) {
194     for (auto &customFunc : customVectorizationHooks) {
195       VectorizationResult result = customFunc(op, bvm);
196       if (result.status == VectorizationStatus::Failure)
197         continue;
198       return result;
199     }
200   }
201 
202   // 2. Constant ops don't get vectorized but rather broadcasted at their users.
203   // Clone so that the constant is not confined to the linalgOp block .
204   if (isa<ConstantOp>(op))
205     return VectorizationResult{VectorizationStatus::NewOp, builder.clone(*op)};
206 
207   // 3. Only ElementwiseMappable are allowed in the generic vectorization.
208   if (!op->hasTrait<OpTrait::ElementwiseMappable>())
209     return VectorizationResult{VectorizationStatus::Failure, nullptr};
210 
211   // 4. Generic vectorization path for ElementwiseMappable ops.
212   //   a. first get the first max ranked shape.
213   SmallVector<int64_t, 4> firstMaxRankedShape;
214   for (Value operand : op->getOperands()) {
215     auto vt = bvm.lookup(operand).getType().dyn_cast<VectorType>();
216     if (vt && firstMaxRankedShape.size() < vt.getShape().size())
217       firstMaxRankedShape.assign(vt.getShape().begin(), vt.getShape().end());
218   }
219   //   b. broadcast each op if needed.
220   auto vectorizedOperands = llvm::map_range(op->getOperands(), [&](Value v) {
221     return firstMaxRankedShape.empty()
222                ? bvm.lookup(v)
223                : broadcastIfNeeded(builder, bvm.lookup(v), firstMaxRankedShape);
224   });
225   //   c. for elementwise, the result is the vector with the firstMaxRankedShape
226   auto returnTypes = llvm::map_range(op->getResultTypes(), [&](Type t) {
227     return firstMaxRankedShape.empty()
228                ? t
229                : VectorType::get(firstMaxRankedShape, t);
230   });
231 
232   // Build and return the new op.
233   OperationState state(op->getLoc(), op->getName());
234   state.addAttributes(op->getAttrs());
235   state.addOperands(llvm::to_vector<4>(vectorizedOperands));
236   state.addTypes(llvm::to_vector<4>(returnTypes));
237   return VectorizationResult{VectorizationStatus::NewOp,
238                              builder.createOperation(state)};
239 }
240 
241 /// Generic vectorization function that rewrites the body of a `linalgOp` into
242 /// vector form. Generic vectorization proceeds as follows:
243 ///   1. The region for the linalg op is created if necessary.
244 ///   2. Values defined above the region are mapped to themselves and will be
245 ///   broadcasted on a per-need basis by their consumers.
246 ///   3. Each region argument is vectorized into a vector.transfer_read (or 0-d
247 ///   load).
248 ///   TODO: Reuse opportunities for RAR dependencies.
249 ///   4. Register CustomVectorizationHook for YieldOp to capture the results.
250 ///   5. Iteratively call vectorizeOneOp on the region operations.
251 static Optional<VectorizedLinalgOp> vectorizeAsLinalgGeneric(
252     OpBuilder &builder, LinalgOp linalgOp,
253     ArrayRef<CustomVectorizationHook> customVectorizationHooks = {}) {
254   // 1. Certain Linalg ops do not have a region but only a region builder.
255   // If so, build the region so we can vectorize.
256   std::unique_ptr<Region> owningRegion;
257   Region *region;
258   if (linalgOp->getNumRegions() > 0) {
259     region = &linalgOp->getRegion(0);
260   } else {
261     // RAII avoid remaining in block.
262     OpBuilder::InsertionGuard g(builder);
263     owningRegion = std::make_unique<Region>();
264     region = owningRegion.get();
265     Block *block = builder.createBlock(region);
266     auto elementTypes = llvm::to_vector<4>(
267         llvm::map_range(linalgOp.getShapedOperandTypes(),
268                         [](ShapedType t) { return t.getElementType(); }));
269     block->addArguments(elementTypes);
270     linalgOp.getRegionBuilder()(*block);
271   }
272   Block *block = &region->front();
273 
274   BlockAndValueMapping bvm;
275   // 2. Values defined above the region can only be broadcast for now. Make them
276   // map to themselves.
277   llvm::SetVector<Value> valuesSet;
278   mlir::getUsedValuesDefinedAbove(*region, valuesSet);
279   bvm.map(valuesSet.getArrayRef(), valuesSet.getArrayRef());
280 
281   // 3. Turn all BBArgs into vector.transfer_read / load.
282   SmallVector<AffineMap> indexings;
283   for (auto bbarg : block->getArguments()) {
284     Value vectorArg = linalgOp.getShapedOperand(bbarg.getArgNumber());
285     Value vectorRead = buildVectorRead(builder, vectorArg);
286     LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: new vectorized bbarg("
287                       << bbarg.getArgNumber() << "): " << vectorRead);
288     bvm.map(bbarg, vectorRead);
289     bvm.map(vectorArg, vectorRead);
290   }
291 
292   // 4. Register CustomVectorizationHook for yieldOp.
293   SmallVector<Value> results;
294   CustomVectorizationHook vectorizeYield =
295       [&](Operation *op,
296           const BlockAndValueMapping &bvm) -> VectorizationResult {
297     return vectorizeLinalgYield(builder, op, bvm, linalgOp, results);
298   };
299   // Append the vectorizeYield hook.
300   auto hooks = llvm::to_vector<4>(customVectorizationHooks);
301   hooks.push_back(vectorizeYield);
302 
303   // 5. Iteratively call `vectorizeOneOp` to each op in the slice.
304   for (Operation &op : block->getOperations()) {
305     VectorizationResult result = vectorizeOneOp(builder, &op, bvm, hooks);
306     if (result.status == VectorizationStatus::Failure) {
307       LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: failed to vectorize: " << op);
308       return llvm::None;
309     }
310     if (result.status == VectorizationStatus::NewOp) {
311       LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: new vector op: "
312                         << *result.newOp;);
313       bvm.map(op.getResults(), result.newOp->getResults());
314     }
315   }
316 
317   return VectorizedLinalgOp{{results}};
318 }
319 
320 /// Detect whether `r` has only ConstantOp, ElementwiseMappable and YieldOp.
321 static bool hasOnlyScalarElementwiseOp(Region &r) {
322   if (!llvm::hasSingleElement(r))
323     return false;
324   for (Operation &op : r.front()) {
325     if (!(isa<ConstantOp, linalg::YieldOp>(op) ||
326           op.hasTrait<OpTrait::ElementwiseMappable>()) ||
327         llvm::any_of(op.getResultTypes(),
328                      [](Type type) { return !type.isIntOrIndexOrFloat(); }))
329       return false;
330   }
331   return true;
332 }
333 
334 // Return true if the op is an element-wise linalg op.
335 static bool isElementwise(Operation *op) {
336   auto genericOp = dyn_cast<linalg::GenericOp>(op);
337   if (!genericOp)
338     return false;
339   if (genericOp.getNumLoops() != genericOp.getNumParallelLoops())
340     return false;
341   // TODO: relax the restrictions on indexing map.
342   for (unsigned i = 0, e = genericOp.getNumOutputs(); i < e; i++) {
343     if (!genericOp.getOutputIndexingMap(i).isIdentity())
344       return false;
345   }
346   // Currently bound the input indexing map to minor identity as other
347   // permutations might require adding transpose ops to convert the vector read
348   // to the right shape.
349   for (unsigned i = 0, e = genericOp.getNumInputs(); i < e; i++) {
350     if (!genericOp.getInputIndexingMap(i).isMinorIdentity())
351       return false;
352   }
353   return hasOnlyScalarElementwiseOp(genericOp.getRegion());
354 }
355 
356 static Optional<VectorizedLinalgOp> vectorizeContraction(OpBuilder &builder,
357                                                          LinalgOp linalgOp) {
358   assert(isaContractionOpInterface(linalgOp) &&
359          "expected vectorizeContraction preconditions to be met");
360   Location loc = linalgOp.getLoc();
361   // Vectorize other ops as vector contraction.
362   // TODO: interface.
363   LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: "
364                     << "Rewrite linalg op as vector.contract: ";
365              linalgOp.dump());
366   // Special function that describes how to vectorize the multiplication op in a
367   // linalg contraction.
368   CustomVectorizationHook vectorizeContraction =
369       [&](Operation *op,
370           const BlockAndValueMapping &bvm) -> VectorizationResult {
371     if (!isa<MulIOp, MulFOp>(op))
372       return VectorizationResult{VectorizationStatus::Failure, nullptr};
373     auto outShape = linalgOp.getOutputShapedType(0).getShape();
374     auto vType = outShape.empty()
375                      ? op->getResult(0).getType()
376                      : VectorType::get(outShape, op->getResult(0).getType());
377     auto zero =
378         builder.create<ConstantOp>(loc, vType, builder.getZeroAttr(vType));
379     Operation *contract = builder.create<vector::ContractionOp>(
380         loc, bvm.lookup(op->getOperand(0)), bvm.lookup(op->getOperand(1)), zero,
381         linalgOp.indexing_maps(), linalgOp.iterator_types());
382     return VectorizationResult{VectorizationStatus::NewOp, contract};
383   };
384   return vectorizeAsLinalgGeneric(builder, linalgOp, {vectorizeContraction});
385 }
386 
387 LogicalResult mlir::linalg::vectorizeLinalgOpPrecondition(Operation *op) {
388   auto linalgOp = cast<linalg::LinalgOp>(op);
389   // All types must be static shape to go to vector.
390   for (Value operand : linalgOp.getShapedOperands())
391     if (!operand.getType().cast<ShapedType>().hasStaticShape())
392       return failure();
393   for (Type outputTensorType : linalgOp.getOutputTensorTypes())
394     if (!outputTensorType.cast<ShapedType>().hasStaticShape())
395       return failure();
396 
397   if (isa<linalg::FillOp, linalg::CopyOp>(op))
398     return success();
399   if (isElementwise(op))
400     return success();
401   return success(isaContractionOpInterface(linalgOp));
402 }
403 
404 Optional<VectorizedLinalgOp> mlir::linalg::vectorizeLinalgOp(OpBuilder &builder,
405                                                              Operation *op) {
406   if (failed(vectorizeLinalgOpPrecondition(op)))
407     return llvm::None;
408 
409   edsc::ScopedContext scope(builder, op->getLoc());
410   // In the case of 0-D memrefs, return null and special case to scalar load or
411   // store later.
412   if (auto fillOp = dyn_cast<linalg::FillOp>(op)) {
413     // Vectorize fill as a vector.broadcast.
414     LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: "
415                       << "Rewrite linalg.fill as vector.broadcast: " << *op);
416     VectorizedLinalgOp res;
417     if (Value v = buildVectorWrite(builder, fillOp.value(), fillOp.output()))
418       res.tensorResults.push_back(v);
419     return res;
420   }
421   if (auto copyOp = dyn_cast<linalg::CopyOp>(op)) {
422     // Vectorize copy as a vector.transfer_read+vector.transfer_write.
423     LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: "
424                       << "Rewrite linalg.copy as vector.transfer_read + "
425                          "vector.transfer_write: "
426                       << *op);
427     Value vector = buildVectorRead(builder, copyOp.input());
428     VectorizedLinalgOp res;
429     if (Value v = buildVectorWrite(builder, vector, copyOp.output()))
430       res.tensorResults.push_back(v);
431     return res;
432   }
433   if (isElementwise(op)) {
434     LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: "
435                       << "Vectorize linalg op as a generic: " << *op);
436     return vectorizeAsLinalgGeneric(builder, cast<LinalgOp>(op));
437   }
438 
439   // TODO: as soon as Copy and FillOp. get a region builder, replace all the
440   // above by:
441   // if (isa<FillOp, CopyOp>(op) || isElementwise(op)) {
442   //   LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: "
443   //                     << "Vectorize linalg op as a generic: " << *op);
444   //   return vectorizeAsLinalgGeneric(builder, cast<LinalgOp>(op));
445   // }
446 
447   return vectorizeContraction(builder, cast<LinalgOp>(op));
448 }
449 
450 //----------------------------------------------------------------------------//
451 // Misc. conv vectorization patterns.
452 //----------------------------------------------------------------------------//
453 // TODO: cleanup all this.
454 template <class ConvOp, int N>
455 LogicalResult ConvOpVectorization<ConvOp, N>::matchAndRewrite(
456     ConvOp op, PatternRewriter &rewriter) const {
457   Location loc = op.getLoc();
458   MLIRContext *context = op.getContext();
459   edsc::ScopedContext scope(rewriter, loc);
460 
461   ShapedType inShapeType = op.getInputShapedType(0);
462   ShapedType kShapeType = op.getInputShapedType(1);
463 
464   ArrayRef<int64_t> inShape = inShapeType.getShape();
465   ArrayRef<int64_t> kShape = kShapeType.getShape();
466 
467   if (!inShapeType.hasStaticShape() || !kShapeType.hasStaticShape())
468     return failure();
469 
470   SmallVector<AffineExpr, 4> mapping;
471   SmallVector<int64_t, 4> vectorDims;
472   // Fail to apply when the size of not vectorized dimension is not 1.
473   for (unsigned i = 0; i < N; i++) {
474     if (!mask[i] && (inShape[i] != 1 || kShape[i] != 1))
475       return failure();
476 
477     if (mask[i] && inShape[i] != kShape[i])
478       return failure();
479 
480     if (mask[i]) {
481       mapping.push_back(getAffineDimExpr(i, context));
482       vectorDims.push_back(inShape[i]);
483     }
484   }
485 
486   Value input = op.getInput(0);
487   Value kernel = op.getInput(1);
488   Value output = op.getOutputBuffer(0);
489 
490   unsigned rank = inShapeType.getRank();
491   unsigned numDims = mapping.size();
492   Type elemType = inShapeType.getElementType();
493 
494   auto map = AffineMap::get(rank, 0, mapping, context);
495   SmallVector<Value, 4> zeros(rank, std_constant_index(0));
496   auto vecType = VectorType::get(vectorDims, elemType);
497 
498   auto inputVec = vector_transfer_read(vecType, input, zeros, map);
499   auto kernelVec = vector_transfer_read(vecType, kernel, zeros, map);
500 
501   auto acc = std_constant(elemType, rewriter.getZeroAttr(elemType));
502 
503   std::array<AffineMap, 3> indexingMaps{
504       AffineMap::getMultiDimIdentityMap(numDims, context),
505       AffineMap::getMultiDimIdentityMap(numDims, context),
506       AffineMap::get(numDims, 0, {}, context)};
507 
508   std::vector<StringRef> iteratorTypes(numDims, "reduction");
509 
510   auto result = rewriter.create<vector::ContractionOp>(
511       loc, inputVec, kernelVec, acc,
512       rewriter.getAffineMapArrayAttr(indexingMaps),
513       rewriter.getStrArrayAttr(iteratorTypes));
514 
515   rewriter.create<StoreOp>(loc, result, output, ValueRange(zeros));
516   rewriter.eraseOp(op);
517   return success();
518 }
519 
520 using ConvOpConst = ConvOpVectorization<ConvWOp, 1>;
521 
522 /// Inserts tiling, promotion and vectorization pattern for ConvOp
523 /// conversion into corresponding pattern lists.
524 template <typename ConvOp, unsigned N>
525 static void
526 populateVectorizationPatterns(OwningRewritePatternList &tilingPatterns,
527                               OwningRewritePatternList &promotionPatterns,
528                               OwningRewritePatternList &vectorizationPatterns,
529                               ArrayRef<int64_t> tileSizes,
530                               MLIRContext *context) {
531   if (tileSizes.size() < N)
532     return;
533 
534   constexpr static StringRef kTiledMarker = "TILED";
535   constexpr static StringRef kPromotedMarker = "PROMOTED";
536   tilingPatterns.insert<LinalgTilingPattern<ConvOp>>(
537       context, LinalgTilingOptions().setTileSizes(tileSizes),
538       LinalgTransformationFilter(ArrayRef<Identifier>{},
539                                  Identifier::get(kTiledMarker, context)));
540 
541   promotionPatterns.insert<LinalgPromotionPattern<ConvOp>>(
542       context, LinalgPromotionOptions().setUseFullTileBuffersByDefault(true),
543       LinalgTransformationFilter(Identifier::get(kTiledMarker, context),
544                                  Identifier::get(kPromotedMarker, context)));
545 
546   SmallVector<bool, 4> mask(N);
547   int offset = tileSizes.size() - N;
548   std::transform(tileSizes.begin() + offset, tileSizes.end(), mask.begin(),
549                  [](int64_t i) -> bool { return i > 1; });
550 
551   vectorizationPatterns.insert<ConvOpVectorization<ConvOp, N>>(context, mask);
552 }
553 
554 void mlir::linalg::populateConvVectorizationPatterns(
555     MLIRContext *context, SmallVectorImpl<OwningRewritePatternList> &patterns,
556     ArrayRef<int64_t> tileSizes) {
557   OwningRewritePatternList tiling, promotion, vectorization;
558   populateVectorizationPatterns<ConvWOp, 1>(tiling, promotion, vectorization,
559                                             tileSizes, context);
560 
561   populateVectorizationPatterns<ConvNWCOp, 3>(tiling, promotion, vectorization,
562                                               tileSizes, context);
563 
564   populateVectorizationPatterns<ConvNCWOp, 3>(tiling, promotion, vectorization,
565                                               tileSizes, context);
566 
567   populateVectorizationPatterns<ConvHWOp, 2>(tiling, promotion, vectorization,
568                                              tileSizes, context);
569 
570   populateVectorizationPatterns<ConvNHWCOp, 4>(tiling, promotion, vectorization,
571                                                tileSizes, context);
572 
573   populateVectorizationPatterns<ConvNCHWOp, 4>(tiling, promotion, vectorization,
574                                                tileSizes, context);
575 
576   populateVectorizationPatterns<ConvDHWOp, 3>(tiling, promotion, vectorization,
577                                               tileSizes, context);
578 
579   populateVectorizationPatterns<ConvNDHWCOp, 5>(
580       tiling, promotion, vectorization, tileSizes, context);
581 
582   populateVectorizationPatterns<ConvNCDHWOp, 5>(
583       tiling, promotion, vectorization, tileSizes, context);
584 
585   patterns.push_back(std::move(tiling));
586   patterns.push_back(std::move(promotion));
587   patterns.push_back(std::move(vectorization));
588 }
589 
590 //----------------------------------------------------------------------------//
591 // Forwarding patterns
592 //----------------------------------------------------------------------------//
593 
594 /// Check whether there is any interleaved use of any `values` between `firstOp`
595 /// and `secondOp`. Conservatively return `true` if any op or value is in a
596 /// different block.
597 static bool mayExistInterleavedUses(Operation *firstOp, Operation *secondOp,
598                                     ValueRange values) {
599   if (firstOp->getBlock() != secondOp->getBlock() ||
600       !firstOp->isBeforeInBlock(secondOp)) {
601     LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
602                             << "interleavedUses precondition failed, firstOp: "
603                             << *firstOp << ", second op: " << *secondOp);
604     return true;
605   }
606   for (auto v : values) {
607     for (auto &u : v.getUses()) {
608       Operation *owner = u.getOwner();
609       if (owner == firstOp || owner == secondOp)
610         continue;
611       // TODO: this is too conservative, use dominance info in the future.
612       if (owner->getBlock() == firstOp->getBlock() &&
613           (owner->isBeforeInBlock(firstOp) || secondOp->isBeforeInBlock(owner)))
614         continue;
615       LLVM_DEBUG(llvm::dbgs()
616                  << "\n[" DEBUG_TYPE "]: "
617                  << " found interleaved op " << *owner
618                  << ", firstOp: " << *firstOp << ", second op: " << *secondOp);
619       return true;
620     }
621   }
622   return false;
623 }
624 
625 /// Return the unique subview use of `v` if it is indeed unique, null otherwise.
626 static SubViewOp getSubViewUseIfUnique(Value v) {
627   SubViewOp subViewOp;
628   for (auto &u : v.getUses()) {
629     if (auto newSubViewOp = dyn_cast<SubViewOp>(u.getOwner())) {
630       if (subViewOp)
631         return SubViewOp();
632       subViewOp = newSubViewOp;
633     }
634   }
635   return subViewOp;
636 }
637 
638 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
639 /// when available.
640 LogicalResult LinalgCopyVTRForwardingPattern::matchAndRewrite(
641     vector::TransferReadOp xferOp, PatternRewriter &rewriter) const {
642 
643   // Transfer into `view`.
644   Value viewOrAlloc = xferOp.source();
645   if (!viewOrAlloc.getDefiningOp<ViewOp>() &&
646       !viewOrAlloc.getDefiningOp<AllocOp>())
647     return failure();
648 
649   LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " << viewOrAlloc);
650 
651   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
652   SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
653   if (!subViewOp)
654     return failure();
655   Value subView = subViewOp.getResult();
656   LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
657                           << "with subView " << subView);
658 
659   // Find the copy into `subView` without interleaved uses.
660   CopyOp copyOp;
661   for (auto &u : subView.getUses()) {
662     if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) {
663       if (newCopyOp.getOutputBuffer(0) != subView)
664         continue;
665       LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
666                               << "copy candidate " << *newCopyOp);
667       if (mayExistInterleavedUses(newCopyOp, xferOp, {viewOrAlloc, subView}))
668         continue;
669       copyOp = newCopyOp;
670       break;
671     }
672   }
673   if (!copyOp)
674     return failure();
675   LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
676                           << "with copy " << *copyOp);
677 
678   // Find the fill into `viewOrAlloc` without interleaved uses before the copy.
679   FillOp maybeFillOp;
680   for (auto &u : viewOrAlloc.getUses()) {
681     if (auto newFillOp = dyn_cast<FillOp>(u.getOwner())) {
682       if (newFillOp.getOutputBuffer(0) != viewOrAlloc)
683         continue;
684       LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
685                               << "fill candidate " << *newFillOp);
686       if (mayExistInterleavedUses(newFillOp, copyOp, {viewOrAlloc, subView}))
687         continue;
688       maybeFillOp = newFillOp;
689       break;
690     }
691   }
692   // Ensure padding matches.
693   if (maybeFillOp && xferOp.padding() != maybeFillOp.value())
694     return failure();
695   if (maybeFillOp)
696     LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
697                             << "with maybeFillOp " << *maybeFillOp);
698 
699   // `in` is the subview that linalg.copy reads. Replace it.
700   Value in = copyOp.getInput(0);
701 
702   // linalg.copy + linalg.fill can be used to create a padded local buffer.
703   // The `masked` attribute is only valid on this padded buffer.
704   // When forwarding to vector.transfer_read, the attribute must be reset
705   // conservatively.
706   Value res = rewriter.create<vector::TransferReadOp>(
707       xferOp.getLoc(), xferOp.getVectorType(), in, xferOp.indices(),
708       xferOp.permutation_map(), xferOp.padding(), ArrayAttr());
709 
710   if (maybeFillOp)
711     rewriter.eraseOp(maybeFillOp);
712   rewriter.eraseOp(copyOp);
713   rewriter.replaceOp(xferOp, res);
714 
715   return success();
716 }
717 
718 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
719 /// when available.
720 LogicalResult LinalgCopyVTWForwardingPattern::matchAndRewrite(
721     vector::TransferWriteOp xferOp, PatternRewriter &rewriter) const {
722   // Transfer into `viewOrAlloc`.
723   Value viewOrAlloc = xferOp.source();
724   if (!viewOrAlloc.getDefiningOp<ViewOp>() &&
725       !viewOrAlloc.getDefiningOp<AllocOp>())
726     return failure();
727 
728   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
729   SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
730   if (!subViewOp)
731     return failure();
732   Value subView = subViewOp.getResult();
733 
734   // Find the copy from `subView` without interleaved uses.
735   CopyOp copyOp;
736   for (auto &u : subViewOp.getResult().getUses()) {
737     if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) {
738       if (newCopyOp.getInput(0) != subView)
739         continue;
740       if (mayExistInterleavedUses(xferOp, newCopyOp, {viewOrAlloc, subView}))
741         continue;
742       copyOp = newCopyOp;
743       break;
744     }
745   }
746   if (!copyOp)
747     return failure();
748 
749   // `out` is the subview copied into that we replace.
750   Value out = copyOp.getOutputBuffer(0);
751 
752   // Forward vector.transfer into copy.
753   // linalg.copy + linalg.fill can be used to create a padded local buffer.
754   // The `masked` attribute is only valid on this padded buffer.
755   // When forwarding to vector.transfer_write, the attribute must be reset
756   // conservatively.
757   rewriter.create<vector::TransferWriteOp>(
758       xferOp.getLoc(), xferOp.vector(), out, xferOp.indices(),
759       xferOp.permutation_map(), ArrayAttr());
760 
761   rewriter.eraseOp(copyOp);
762   rewriter.eraseOp(xferOp);
763 
764   return success();
765 }
766