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 ///   6. RAUW the linalg op by the results captured vectorizing the YieldOp.
252 static LogicalResult vectorizeAsLinalgGeneric(
253     OpBuilder &builder, LinalgOp linalgOp,
254     ArrayRef<CustomVectorizationHook> customVectorizationHooks = {}) {
255   // 1. Certain Linalg ops do not have a region but only a region builder.
256   // If so, build the region so we can vectorize.
257   std::unique_ptr<Region> owningRegion;
258   Region *region;
259   if (linalgOp->getNumRegions() > 0) {
260     region = &linalgOp->getRegion(0);
261   } else {
262     // RAII avoid remaining in block.
263     OpBuilder::InsertionGuard g(builder);
264     owningRegion = std::make_unique<Region>();
265     region = owningRegion.get();
266     Block *block = builder.createBlock(region);
267     auto elementTypes = llvm::to_vector<4>(
268         llvm::map_range(linalgOp.getShapedOperandTypes(),
269                         [](ShapedType t) { return t.getElementType(); }));
270     block->addArguments(elementTypes);
271     linalgOp.getRegionBuilder()(*block);
272   }
273   Block *block = &region->front();
274 
275   BlockAndValueMapping bvm;
276   // 2. Values defined above the region can only be broadcast for now. Make them
277   // map to themselves.
278   llvm::SetVector<Value> valuesSet;
279   mlir::getUsedValuesDefinedAbove(*region, valuesSet);
280   bvm.map(valuesSet.getArrayRef(), valuesSet.getArrayRef());
281 
282   // 3. Turn all BBArgs into vector.transfer_read / load.
283   SmallVector<AffineMap> indexings;
284   for (auto bbarg : block->getArguments()) {
285     Value vectorArg = linalgOp.getShapedOperand(bbarg.getArgNumber());
286     Value vectorRead = buildVectorRead(builder, vectorArg);
287     LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: new vectorized bbarg("
288                       << bbarg.getArgNumber() << "): " << vectorRead);
289     bvm.map(bbarg, vectorRead);
290     bvm.map(vectorArg, vectorRead);
291   }
292 
293   // 4. Register CustomVectorizationHook for yieldOp.
294   SmallVector<Value> results;
295   CustomVectorizationHook vectorizeYield =
296       [&](Operation *op,
297           const BlockAndValueMapping &bvm) -> VectorizationResult {
298     return vectorizeLinalgYield(builder, op, bvm, linalgOp, results);
299   };
300   // Append the vectorizeYield hook.
301   auto hooks = llvm::to_vector<4>(customVectorizationHooks);
302   hooks.push_back(vectorizeYield);
303 
304   // 5. Iteratively call `vectorizeOneOp` to each op in the slice.
305   for (Operation &op : block->getOperations()) {
306     VectorizationResult result = vectorizeOneOp(builder, &op, bvm, hooks);
307     if (result.status == VectorizationStatus::Failure) {
308       LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: failed to vectorize: " << op);
309       return failure();
310     }
311     if (result.status == VectorizationStatus::NewOp) {
312       LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: new vector op: "
313                         << *result.newOp;);
314       bvm.map(op.getResults(), result.newOp->getResults());
315     }
316   }
317 
318   // 6. RAUW the linalg op by the results captured vectorizing the YieldOp.
319   if (!results.empty())
320     linalgOp->replaceAllUsesWith(results);
321   return success();
322 }
323 
324 /// Detect whether `r` has only ConstantOp, ElementwiseMappable and YieldOp.
325 static bool hasOnlyScalarElementwiseOp(Region &r) {
326   if (!llvm::hasSingleElement(r))
327     return false;
328   for (Operation &op : r.front()) {
329     if (!(isa<ConstantOp, linalg::YieldOp>(op) ||
330           op.hasTrait<OpTrait::ElementwiseMappable>()) ||
331         llvm::any_of(op.getResultTypes(),
332                      [](Type type) { return !type.isIntOrIndexOrFloat(); }))
333       return false;
334   }
335   return true;
336 }
337 
338 // Return true if the op is an element-wise linalg op.
339 static bool isElementwise(Operation *op) {
340   auto genericOp = dyn_cast<linalg::GenericOp>(op);
341   if (!genericOp)
342     return false;
343   if (genericOp.getNumLoops() != genericOp.getNumParallelLoops())
344     return false;
345   // TODO: relax the restrictions on indexing map.
346   for (unsigned i = 0, e = genericOp.getNumOutputs(); i < e; i++) {
347     if (!genericOp.getOutputIndexingMap(i).isIdentity())
348       return false;
349   }
350   // Currently bound the input indexing map to minor identity as other
351   // permutations might require adding transpose ops to convert the vector read
352   // to the right shape.
353   for (unsigned i = 0, e = genericOp.getNumInputs(); i < e; i++) {
354     if (!genericOp.getInputIndexingMap(i).isMinorIdentity())
355       return false;
356   }
357   return hasOnlyScalarElementwiseOp(genericOp.getRegion());
358 }
359 
360 static void vectorizeContraction(OpBuilder &builder, LinalgOp linalgOp) {
361   assert(isaContractionOpInterface(linalgOp) &&
362          "expected vectorizeContraction preconditions to be met");
363   Location loc = linalgOp.getLoc();
364   // Vectorize other ops as vector contraction.
365   // TODO: interface.
366   LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: "
367                     << "Rewrite linalg op as vector.contract: ";
368              linalgOp.dump());
369   // Special function that describes how to vectorize the multiplication op in a
370   // linalg contraction.
371   CustomVectorizationHook vectorizeContraction =
372       [&](Operation *op,
373           const BlockAndValueMapping &bvm) -> VectorizationResult {
374     if (!isa<MulIOp, MulFOp>(op))
375       return VectorizationResult{VectorizationStatus::Failure, nullptr};
376     auto outShape = linalgOp.getOutputShapedType(0).getShape();
377     auto vType = outShape.empty()
378                      ? op->getResult(0).getType()
379                      : VectorType::get(outShape, op->getResult(0).getType());
380     auto zero =
381         builder.create<ConstantOp>(loc, vType, builder.getZeroAttr(vType));
382     Operation *contract = builder.create<vector::ContractionOp>(
383         loc, bvm.lookup(op->getOperand(0)), bvm.lookup(op->getOperand(1)), zero,
384         linalgOp.indexing_maps(), linalgOp.iterator_types());
385     return VectorizationResult{VectorizationStatus::NewOp, contract};
386   };
387   auto status =
388       vectorizeAsLinalgGeneric(builder, linalgOp, {vectorizeContraction});
389   (void)status;
390   assert(succeeded(status) &&
391          "Unexpected vectorization failed despite preconditions");
392 }
393 
394 LogicalResult mlir::linalg::vectorizeLinalgOpPrecondition(Operation *op) {
395   auto linalgOp = cast<linalg::LinalgOp>(op);
396   // All types must be static shape to go to vector.
397   for (Value operand : linalgOp.getShapedOperands())
398     if (!operand.getType().cast<ShapedType>().hasStaticShape())
399       return failure();
400   for (Type outputTensorType : linalgOp.getOutputTensorTypes())
401     if (!outputTensorType.cast<ShapedType>().hasStaticShape())
402       return failure();
403 
404   if (isa<linalg::FillOp, linalg::CopyOp>(op))
405     return success();
406   if (isElementwise(op))
407     return success();
408   return success(isaContractionOpInterface(linalgOp));
409 }
410 
411 void mlir::linalg::vectorizeLinalgOp(OpBuilder &builder, Operation *op) {
412   assert(succeeded(vectorizeLinalgOpPrecondition(op)));
413 
414   edsc::ScopedContext scope(builder, op->getLoc());
415   // In the case of 0-D memrefs, return null and special case to scalar load or
416   // store later.
417   if (auto fillOp = dyn_cast<linalg::FillOp>(op)) {
418     // Vectorize fill as a vector.broadcast.
419     LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: "
420                       << "Rewrite linalg.fill as vector.broadcast: " << *op);
421     buildVectorWrite(builder, fillOp.value(), fillOp.output());
422     return;
423   }
424   if (auto copyOp = dyn_cast<linalg::CopyOp>(op)) {
425     // Vectorize copy as a vector.transfer_read+vector.transfer_write.
426     LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: "
427                       << "Rewrite linalg.copy as vector.transfer_read + "
428                          "vector.transfer_write: "
429                       << *op);
430     Value vector = buildVectorRead(builder, copyOp.input());
431     buildVectorWrite(builder, vector, copyOp.output());
432     return;
433   }
434 
435   if (isElementwise(op)) {
436     LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: "
437                       << "Rewrite linalg op as vector.transfer_read + " << *op);
438     auto status = vectorizeAsLinalgGeneric(builder, cast<LinalgOp>(op));
439     (void)status;
440     assert(succeeded(status) &&
441            "Unexpected vectorization failed despite preconditions");
442     return;
443   }
444 
445   vectorizeContraction(builder, cast<LinalgOp>(op));
446 }
447 
448 //----------------------------------------------------------------------------//
449 // Misc. conv vectorization patterns.
450 //----------------------------------------------------------------------------//
451 // TODO: cleanup all this.
452 template <class ConvOp, int N>
453 LogicalResult ConvOpVectorization<ConvOp, N>::matchAndRewrite(
454     ConvOp op, PatternRewriter &rewriter) const {
455   Location loc = op.getLoc();
456   MLIRContext *context = op.getContext();
457   edsc::ScopedContext scope(rewriter, loc);
458 
459   ShapedType inShapeType = op.getInputShapedType(0);
460   ShapedType kShapeType = op.getInputShapedType(1);
461 
462   ArrayRef<int64_t> inShape = inShapeType.getShape();
463   ArrayRef<int64_t> kShape = kShapeType.getShape();
464 
465   if (!inShapeType.hasStaticShape() || !kShapeType.hasStaticShape())
466     return failure();
467 
468   SmallVector<AffineExpr, 4> mapping;
469   SmallVector<int64_t, 4> vectorDims;
470   // Fail to apply when the size of not vectorized dimension is not 1.
471   for (unsigned i = 0; i < N; i++) {
472     if (!mask[i] && (inShape[i] != 1 || kShape[i] != 1))
473       return failure();
474 
475     if (mask[i] && inShape[i] != kShape[i])
476       return failure();
477 
478     if (mask[i]) {
479       mapping.push_back(getAffineDimExpr(i, context));
480       vectorDims.push_back(inShape[i]);
481     }
482   }
483 
484   Value input = op.getInput(0);
485   Value kernel = op.getInput(1);
486   Value output = op.getOutputBuffer(0);
487 
488   unsigned rank = inShapeType.getRank();
489   unsigned numDims = mapping.size();
490   Type elemType = inShapeType.getElementType();
491 
492   auto map = AffineMap::get(rank, 0, mapping, context);
493   SmallVector<Value, 4> zeros(rank, std_constant_index(0));
494   auto vecType = VectorType::get(vectorDims, elemType);
495 
496   auto inputVec = vector_transfer_read(vecType, input, zeros, map);
497   auto kernelVec = vector_transfer_read(vecType, kernel, zeros, map);
498 
499   auto acc = std_constant(elemType, rewriter.getZeroAttr(elemType));
500 
501   std::array<AffineMap, 3> indexingMaps{
502       AffineMap::getMultiDimIdentityMap(numDims, context),
503       AffineMap::getMultiDimIdentityMap(numDims, context),
504       AffineMap::get(numDims, 0, {}, context)};
505 
506   std::vector<StringRef> iteratorTypes(numDims, "reduction");
507 
508   auto result = rewriter.create<vector::ContractionOp>(
509       loc, inputVec, kernelVec, acc,
510       rewriter.getAffineMapArrayAttr(indexingMaps),
511       rewriter.getStrArrayAttr(iteratorTypes));
512 
513   rewriter.create<StoreOp>(loc, result, output, ValueRange(zeros));
514   rewriter.eraseOp(op);
515   return success();
516 }
517 
518 using ConvOpConst = ConvOpVectorization<ConvWOp, 1>;
519 
520 /// Inserts tiling, promotion and vectorization pattern for ConvOp
521 /// conversion into corresponding pattern lists.
522 template <typename ConvOp, unsigned N>
523 static void
524 populateVectorizationPatterns(OwningRewritePatternList &tilingPatterns,
525                               OwningRewritePatternList &promotionPatterns,
526                               OwningRewritePatternList &vectorizationPatterns,
527                               ArrayRef<int64_t> tileSizes,
528                               MLIRContext *context) {
529   if (tileSizes.size() < N)
530     return;
531 
532   constexpr static StringRef kTiledMarker = "TILED";
533   constexpr static StringRef kPromotedMarker = "PROMOTED";
534   tilingPatterns.insert<LinalgTilingPattern<ConvOp>>(
535       context, LinalgTilingOptions().setTileSizes(tileSizes),
536       LinalgTransformationFilter(ArrayRef<Identifier>{},
537                                  Identifier::get(kTiledMarker, context)));
538 
539   promotionPatterns.insert<LinalgPromotionPattern<ConvOp>>(
540       context, LinalgPromotionOptions().setUseFullTileBuffersByDefault(true),
541       LinalgTransformationFilter(Identifier::get(kTiledMarker, context),
542                                  Identifier::get(kPromotedMarker, context)));
543 
544   SmallVector<bool, 4> mask(N);
545   int offset = tileSizes.size() - N;
546   std::transform(tileSizes.begin() + offset, tileSizes.end(), mask.begin(),
547                  [](int64_t i) -> bool { return i > 1; });
548 
549   vectorizationPatterns.insert<ConvOpVectorization<ConvOp, N>>(context, mask);
550 }
551 
552 void mlir::linalg::populateConvVectorizationPatterns(
553     MLIRContext *context, SmallVectorImpl<OwningRewritePatternList> &patterns,
554     ArrayRef<int64_t> tileSizes) {
555   OwningRewritePatternList tiling, promotion, vectorization;
556   populateVectorizationPatterns<ConvWOp, 1>(tiling, promotion, vectorization,
557                                             tileSizes, context);
558 
559   populateVectorizationPatterns<ConvNWCOp, 3>(tiling, promotion, vectorization,
560                                               tileSizes, context);
561 
562   populateVectorizationPatterns<ConvNCWOp, 3>(tiling, promotion, vectorization,
563                                               tileSizes, context);
564 
565   populateVectorizationPatterns<ConvHWOp, 2>(tiling, promotion, vectorization,
566                                              tileSizes, context);
567 
568   populateVectorizationPatterns<ConvNHWCOp, 4>(tiling, promotion, vectorization,
569                                                tileSizes, context);
570 
571   populateVectorizationPatterns<ConvNCHWOp, 4>(tiling, promotion, vectorization,
572                                                tileSizes, context);
573 
574   populateVectorizationPatterns<ConvDHWOp, 3>(tiling, promotion, vectorization,
575                                               tileSizes, context);
576 
577   populateVectorizationPatterns<ConvNDHWCOp, 5>(
578       tiling, promotion, vectorization, tileSizes, context);
579 
580   populateVectorizationPatterns<ConvNCDHWOp, 5>(
581       tiling, promotion, vectorization, tileSizes, context);
582 
583   patterns.push_back(std::move(tiling));
584   patterns.push_back(std::move(promotion));
585   patterns.push_back(std::move(vectorization));
586 }
587 
588 //----------------------------------------------------------------------------//
589 // Forwarding patterns
590 //----------------------------------------------------------------------------//
591 
592 /// Check whether there is any interleaved use of any `values` between `firstOp`
593 /// and `secondOp`. Conservatively return `true` if any op or value is in a
594 /// different block.
595 static bool mayExistInterleavedUses(Operation *firstOp, Operation *secondOp,
596                                     ValueRange values) {
597   if (firstOp->getBlock() != secondOp->getBlock() ||
598       !firstOp->isBeforeInBlock(secondOp)) {
599     LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
600                             << "interleavedUses precondition failed, firstOp: "
601                             << *firstOp << ", second op: " << *secondOp);
602     return true;
603   }
604   for (auto v : values) {
605     for (auto &u : v.getUses()) {
606       Operation *owner = u.getOwner();
607       if (owner == firstOp || owner == secondOp)
608         continue;
609       // TODO: this is too conservative, use dominance info in the future.
610       if (owner->getBlock() == firstOp->getBlock() &&
611           (owner->isBeforeInBlock(firstOp) || secondOp->isBeforeInBlock(owner)))
612         continue;
613       LLVM_DEBUG(llvm::dbgs()
614                  << "\n[" DEBUG_TYPE "]: "
615                  << " found interleaved op " << *owner
616                  << ", firstOp: " << *firstOp << ", second op: " << *secondOp);
617       return true;
618     }
619   }
620   return false;
621 }
622 
623 /// Return the unique subview use of `v` if it is indeed unique, null otherwise.
624 static SubViewOp getSubViewUseIfUnique(Value v) {
625   SubViewOp subViewOp;
626   for (auto &u : v.getUses()) {
627     if (auto newSubViewOp = dyn_cast<SubViewOp>(u.getOwner())) {
628       if (subViewOp)
629         return SubViewOp();
630       subViewOp = newSubViewOp;
631     }
632   }
633   return subViewOp;
634 }
635 
636 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
637 /// when available.
638 LogicalResult LinalgCopyVTRForwardingPattern::matchAndRewrite(
639     vector::TransferReadOp xferOp, PatternRewriter &rewriter) const {
640 
641   // Transfer into `view`.
642   Value viewOrAlloc = xferOp.source();
643   if (!viewOrAlloc.getDefiningOp<ViewOp>() &&
644       !viewOrAlloc.getDefiningOp<AllocOp>())
645     return failure();
646 
647   LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " << viewOrAlloc);
648 
649   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
650   SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
651   if (!subViewOp)
652     return failure();
653   Value subView = subViewOp.getResult();
654   LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
655                           << "with subView " << subView);
656 
657   // Find the copy into `subView` without interleaved uses.
658   CopyOp copyOp;
659   for (auto &u : subView.getUses()) {
660     if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) {
661       if (newCopyOp.getOutputBuffer(0) != subView)
662         continue;
663       LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
664                               << "copy candidate " << *newCopyOp);
665       if (mayExistInterleavedUses(newCopyOp, xferOp, {viewOrAlloc, subView}))
666         continue;
667       copyOp = newCopyOp;
668       break;
669     }
670   }
671   if (!copyOp)
672     return failure();
673   LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
674                           << "with copy " << *copyOp);
675 
676   // Find the fill into `viewOrAlloc` without interleaved uses before the copy.
677   FillOp maybeFillOp;
678   for (auto &u : viewOrAlloc.getUses()) {
679     if (auto newFillOp = dyn_cast<FillOp>(u.getOwner())) {
680       if (newFillOp.getOutputBuffer(0) != viewOrAlloc)
681         continue;
682       LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
683                               << "fill candidate " << *newFillOp);
684       if (mayExistInterleavedUses(newFillOp, copyOp, {viewOrAlloc, subView}))
685         continue;
686       maybeFillOp = newFillOp;
687       break;
688     }
689   }
690   // Ensure padding matches.
691   if (maybeFillOp && xferOp.padding() != maybeFillOp.value())
692     return failure();
693   if (maybeFillOp)
694     LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
695                             << "with maybeFillOp " << *maybeFillOp);
696 
697   // `in` is the subview that linalg.copy reads. Replace it.
698   Value in = copyOp.getInput(0);
699 
700   // linalg.copy + linalg.fill can be used to create a padded local buffer.
701   // The `masked` attribute is only valid on this padded buffer.
702   // When forwarding to vector.transfer_read, the attribute must be reset
703   // conservatively.
704   Value res = rewriter.create<vector::TransferReadOp>(
705       xferOp.getLoc(), xferOp.getVectorType(), in, xferOp.indices(),
706       xferOp.permutation_map(), xferOp.padding(), ArrayAttr());
707 
708   if (maybeFillOp)
709     rewriter.eraseOp(maybeFillOp);
710   rewriter.eraseOp(copyOp);
711   rewriter.replaceOp(xferOp, res);
712 
713   return success();
714 }
715 
716 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
717 /// when available.
718 LogicalResult LinalgCopyVTWForwardingPattern::matchAndRewrite(
719     vector::TransferWriteOp xferOp, PatternRewriter &rewriter) const {
720   // Transfer into `viewOrAlloc`.
721   Value viewOrAlloc = xferOp.source();
722   if (!viewOrAlloc.getDefiningOp<ViewOp>() &&
723       !viewOrAlloc.getDefiningOp<AllocOp>())
724     return failure();
725 
726   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
727   SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
728   if (!subViewOp)
729     return failure();
730   Value subView = subViewOp.getResult();
731 
732   // Find the copy from `subView` without interleaved uses.
733   CopyOp copyOp;
734   for (auto &u : subViewOp.getResult().getUses()) {
735     if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) {
736       if (newCopyOp.getInput(0) != subView)
737         continue;
738       if (mayExistInterleavedUses(xferOp, newCopyOp, {viewOrAlloc, subView}))
739         continue;
740       copyOp = newCopyOp;
741       break;
742     }
743   }
744   if (!copyOp)
745     return failure();
746 
747   // `out` is the subview copied into that we replace.
748   Value out = copyOp.getOutputBuffer(0);
749 
750   // Forward vector.transfer into copy.
751   // linalg.copy + linalg.fill can be used to create a padded local buffer.
752   // The `masked` attribute is only valid on this padded buffer.
753   // When forwarding to vector.transfer_write, the attribute must be reset
754   // conservatively.
755   rewriter.create<vector::TransferWriteOp>(
756       xferOp.getLoc(), xferOp.vector(), out, xferOp.indices(),
757       xferOp.permutation_map(), ArrayAttr());
758 
759   rewriter.eraseOp(copyOp);
760   rewriter.eraseOp(xferOp);
761 
762   return success();
763 }
764