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 `newResults`. Return
143 /// VectorizationStatus::NoReplace to signal the vectorization algorithm that it
144 /// should not try to map produced operations and instead return the results
145 /// using the `newResults` vector making them available to the
146 /// vectorization algorithm for RAUW. This function is meant to be used as a
147 /// CustomVectorizationHook.
148 static VectorizationResult
149 vectorizeLinalgYield(OpBuilder &builder, Operation *op,
150                      const BlockAndValueMapping &bvm, LinalgOp linalgOp,
151                      SmallVectorImpl<Value> &newResults) {
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 newResult = buildVectorWrite(builder, vectorValue,
160                                        linalgOp.getOutput(outputs.index()));
161     if (newResult)
162       newResults.push_back(newResult);
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 (!OpTrait::hasElementwiseMappableTraits(op))
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 LogicalResult vectorizeAsLinalgGeneric(
252     OpBuilder &builder, LinalgOp linalgOp, SmallVectorImpl<Value> &newResults,
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, /*captures=*/{});
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   CustomVectorizationHook vectorizeYield =
294       [&](Operation *op,
295           const BlockAndValueMapping &bvm) -> VectorizationResult {
296     return vectorizeLinalgYield(builder, op, bvm, linalgOp, newResults);
297   };
298   // Append the vectorizeYield hook.
299   auto hooks = llvm::to_vector<4>(customVectorizationHooks);
300   hooks.push_back(vectorizeYield);
301 
302   // 5. Iteratively call `vectorizeOneOp` to each op in the slice.
303   for (Operation &op : block->getOperations()) {
304     VectorizationResult result = vectorizeOneOp(builder, &op, bvm, hooks);
305     if (result.status == VectorizationStatus::Failure) {
306       LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: failed to vectorize: " << op);
307       return failure();
308     }
309     if (result.status == VectorizationStatus::NewOp) {
310       LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: new vector op: "
311                         << *result.newOp;);
312       bvm.map(op.getResults(), result.newOp->getResults());
313     }
314   }
315 
316   return success();
317 }
318 
319 /// Detect whether `r` has only ConstantOp, ElementwiseMappable and YieldOp.
320 static bool hasOnlyScalarElementwiseOp(Region &r) {
321   if (!llvm::hasSingleElement(r))
322     return false;
323   for (Operation &op : r.front()) {
324     if (!(isa<ConstantOp, linalg::YieldOp>(op) ||
325           OpTrait::hasElementwiseMappableTraits(&op)) ||
326         llvm::any_of(op.getResultTypes(),
327                      [](Type type) { return !type.isIntOrIndexOrFloat(); }))
328       return false;
329   }
330   return true;
331 }
332 
333 // Return true if the op is an element-wise linalg op.
334 static bool isElementwise(Operation *op) {
335   auto linalgOp = dyn_cast<linalg::LinalgOp>(op);
336   if (!linalgOp)
337     return false;
338   if (linalgOp.getNumLoops() != linalgOp.getNumParallelLoops())
339     return false;
340   // TODO: relax the restrictions on indexing map.
341   for (unsigned i = 0, e = linalgOp.getNumOutputs(); i < e; i++) {
342     if (!linalgOp.getOutputIndexingMap(i).isIdentity())
343       return false;
344   }
345   // Currently bound the input indexing map to minor identity as other
346   // permutations might require adding transpose ops to convert the vector read
347   // to the right shape.
348   for (unsigned i = 0, e = linalgOp.getNumInputs(); i < e; i++) {
349     if (!linalgOp.getInputIndexingMap(i).isMinorIdentity())
350       return false;
351   }
352   if (linalgOp->getNumRegions() != 1)
353     return false;
354   return hasOnlyScalarElementwiseOp(linalgOp->getRegion(0));
355 }
356 
357 static LogicalResult vectorizeContraction(OpBuilder &builder, LinalgOp linalgOp,
358                                           SmallVectorImpl<Value> &newResults) {
359   assert(isaContractionOpInterface(linalgOp) &&
360          "expected vectorizeContraction preconditions to be met");
361   Location loc = linalgOp.getLoc();
362   // Vectorize other ops as vector contraction.
363   // TODO: interface.
364   LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: "
365                     << "Rewrite linalg op as vector.contract: ";
366              linalgOp.dump());
367   // Special function that describes how to vectorize the multiplication op in a
368   // linalg contraction.
369   CustomVectorizationHook vectorizeContraction =
370       [&](Operation *op,
371           const BlockAndValueMapping &bvm) -> VectorizationResult {
372     if (!isa<MulIOp, MulFOp>(op))
373       return VectorizationResult{VectorizationStatus::Failure, nullptr};
374     auto outShape = linalgOp.getOutputShapedType(0).getShape();
375     auto vType = outShape.empty()
376                      ? op->getResult(0).getType()
377                      : VectorType::get(outShape, op->getResult(0).getType());
378     auto zero =
379         builder.create<ConstantOp>(loc, vType, builder.getZeroAttr(vType));
380     Operation *contract = builder.create<vector::ContractionOp>(
381         loc, bvm.lookup(op->getOperand(0)), bvm.lookup(op->getOperand(1)), zero,
382         linalgOp.indexing_maps(), linalgOp.iterator_types());
383     return VectorizationResult{VectorizationStatus::NewOp, contract};
384   };
385   return vectorizeAsLinalgGeneric(builder, linalgOp, newResults,
386                                   {vectorizeContraction});
387 }
388 
389 LogicalResult mlir::linalg::vectorizeLinalgOpPrecondition(Operation *op) {
390   auto linalgOp = cast<linalg::LinalgOp>(op);
391   // All types must be static shape to go to vector.
392   for (Value operand : linalgOp.getShapedOperands())
393     if (!operand.getType().cast<ShapedType>().hasStaticShape())
394       return failure();
395   for (Type outputTensorType : linalgOp.getOutputTensorTypes())
396     if (!outputTensorType.cast<ShapedType>().hasStaticShape())
397       return failure();
398   if (isElementwise(op))
399     return success();
400   return success(isaContractionOpInterface(linalgOp));
401 }
402 
403 LogicalResult
404 mlir::linalg::vectorizeLinalgOp(OpBuilder &builder, Operation *op,
405                                 SmallVectorImpl<Value> &newResults) {
406   if (failed(vectorizeLinalgOpPrecondition(op)))
407     return failure();
408 
409   edsc::ScopedContext scope(builder, op->getLoc());
410   if (isElementwise(op)) {
411     LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: "
412                       << "Vectorize linalg op as a generic: " << *op);
413     return vectorizeAsLinalgGeneric(builder, cast<LinalgOp>(op), newResults);
414   }
415 
416   return vectorizeContraction(builder, cast<LinalgOp>(op), newResults);
417 }
418 
419 //----------------------------------------------------------------------------//
420 // Misc. vectorization patterns.
421 //----------------------------------------------------------------------------//
422 
423 /// Rewrite a PadTensorOp into a sequence of InitTensorOp, TransferReadOp and
424 /// TransferWriteOp. For now, this only applies when all low and high paddings
425 /// are determined to be zero.
426 LogicalResult PadTensorOpVectorizationPattern::matchAndRewrite(
427     linalg::PadTensorOp padOp, PatternRewriter &rewriter) const {
428   // Helper function to determine whether an OpFoldResult is not a zero Index.
429   auto isNotZeroIndex = [](OpFoldResult ofr) {
430     if (Attribute attr = ofr.dyn_cast<Attribute>())
431       return attr.cast<IntegerAttr>().getInt() != 0;
432     Value v = ofr.get<Value>();
433     if (auto constOp = v.getDefiningOp<ConstantOp>())
434       if (auto intAttr = constOp.getValue().dyn_cast<IntegerAttr>())
435         return intAttr.getValue().getSExtValue() != 0;
436     return true;
437   };
438 
439   auto resultShapedType = padOp.result().getType().cast<ShapedType>();
440   // Bail on non-static shapes.
441   if (!resultShapedType.hasStaticShape())
442     return failure();
443 
444   // If any pad_low is not a static 0, needs a mask. Bail for now.
445   if (llvm::any_of(padOp.getMixedLowPad(), isNotZeroIndex))
446     return failure();
447   VectorType vectorType = extractVectorTypeFromShapedValue(padOp.result());
448   if (!vectorType)
449     return failure();
450 
451   // Only support padding with a constant for now, i.e. either:
452   //   1. A BBarg from a different block.
453   //   2. A value defined outside of the current block.
454   Block &block = padOp.region().front();
455   auto yieldOp = cast<YieldOp>(block.getTerminator());
456   assert(yieldOp.getNumOperands() == 1 && "expected single operand yield");
457   Value padValue = yieldOp.values().front();
458   Operation *definingOp = padValue.getDefiningOp();
459   if (definingOp && definingOp->getBlock() == &block)
460     return failure();
461   if (!definingOp && padValue.cast<BlockArgument>().getOwner() == &block)
462     return failure();
463 
464   // TODO: if any pad_high is not a static 0, needs a mask. For now, just bail.
465   if (llvm::any_of(padOp.getMixedHighPad(),
466                    [&](OpFoldResult ofr) { return isNotZeroIndex(ofr); }))
467     return failure();
468 
469   // Now we can rewrite as InitTensorOp + TransferReadOp@[0..0] +
470   // TransferWriteOp@[0..0].
471   SmallVector<Value> indices(
472       resultShapedType.getRank(),
473       rewriter.create<ConstantIndexOp>(padOp.getLoc(), 0));
474   Value read = rewriter.create<vector::TransferReadOp>(
475       padOp.getLoc(), vectorType, padOp.source(), indices, padValue);
476   Value init =
477       rewriter.create<InitTensorOp>(padOp.getLoc(), resultShapedType.getShape(),
478                                     resultShapedType.getElementType());
479   rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(padOp, read, init,
480                                                        indices);
481 
482   return success();
483 }
484 
485 // TODO: cleanup all the convolution vectorization patterns.
486 template <class ConvOp, int N>
487 LogicalResult ConvOpVectorization<ConvOp, N>::matchAndRewrite(
488     ConvOp op, PatternRewriter &rewriter) const {
489   Location loc = op.getLoc();
490   MLIRContext *context = op.getContext();
491   edsc::ScopedContext scope(rewriter, loc);
492 
493   ShapedType inShapeType = op.getInputShapedType(0);
494   ShapedType kShapeType = op.getInputShapedType(1);
495 
496   ArrayRef<int64_t> inShape = inShapeType.getShape();
497   ArrayRef<int64_t> kShape = kShapeType.getShape();
498 
499   if (!inShapeType.hasStaticShape() || !kShapeType.hasStaticShape())
500     return failure();
501 
502   SmallVector<AffineExpr, 4> mapping;
503   SmallVector<int64_t, 4> vectorDims;
504   // Fail to apply when the size of not vectorized dimension is not 1.
505   for (unsigned i = 0; i < N; i++) {
506     if (!mask[i] && (inShape[i] != 1 || kShape[i] != 1))
507       return failure();
508 
509     if (mask[i] && inShape[i] != kShape[i])
510       return failure();
511 
512     if (mask[i]) {
513       mapping.push_back(getAffineDimExpr(i, context));
514       vectorDims.push_back(inShape[i]);
515     }
516   }
517 
518   Value input = op.getInput(0);
519   Value kernel = op.getInput(1);
520   Value output = op.getOutputBuffer(0);
521 
522   unsigned rank = inShapeType.getRank();
523   unsigned numDims = mapping.size();
524   Type elemType = inShapeType.getElementType();
525 
526   auto map = AffineMap::get(rank, 0, mapping, context);
527   SmallVector<Value, 4> zeros(rank, std_constant_index(0));
528   auto vecType = VectorType::get(vectorDims, elemType);
529 
530   auto inputVec = vector_transfer_read(vecType, input, zeros, map);
531   auto kernelVec = vector_transfer_read(vecType, kernel, zeros, map);
532 
533   auto acc = std_constant(elemType, rewriter.getZeroAttr(elemType));
534 
535   std::array<AffineMap, 3> indexingMaps{
536       AffineMap::getMultiDimIdentityMap(numDims, context),
537       AffineMap::getMultiDimIdentityMap(numDims, context),
538       AffineMap::get(numDims, 0, {}, context)};
539 
540   std::vector<StringRef> iteratorTypes(numDims, "reduction");
541 
542   auto result = rewriter.create<vector::ContractionOp>(
543       loc, inputVec, kernelVec, acc,
544       rewriter.getAffineMapArrayAttr(indexingMaps),
545       rewriter.getStrArrayAttr(iteratorTypes));
546 
547   rewriter.create<StoreOp>(loc, result, output, ValueRange(zeros));
548   rewriter.eraseOp(op);
549   return success();
550 }
551 
552 using ConvOpConst = ConvOpVectorization<ConvWOp, 1>;
553 
554 /// Inserts tiling, promotion and vectorization pattern for ConvOp
555 /// conversion into corresponding pattern lists.
556 template <typename ConvOp, unsigned N>
557 static void
558 populateVectorizationPatterns(OwningRewritePatternList &tilingPatterns,
559                               OwningRewritePatternList &promotionPatterns,
560                               OwningRewritePatternList &vectorizationPatterns,
561                               ArrayRef<int64_t> tileSizes,
562                               MLIRContext *context) {
563   if (tileSizes.size() < N)
564     return;
565 
566   constexpr static StringRef kTiledMarker = "TILED";
567   constexpr static StringRef kPromotedMarker = "PROMOTED";
568   tilingPatterns.insert<LinalgTilingPattern<ConvOp>>(
569       context, LinalgTilingOptions().setTileSizes(tileSizes),
570       LinalgTransformationFilter(ArrayRef<Identifier>{},
571                                  Identifier::get(kTiledMarker, context)));
572 
573   promotionPatterns.insert<LinalgPromotionPattern<ConvOp>>(
574       context, LinalgPromotionOptions().setUseFullTileBuffersByDefault(true),
575       LinalgTransformationFilter(Identifier::get(kTiledMarker, context),
576                                  Identifier::get(kPromotedMarker, context)));
577 
578   SmallVector<bool, 4> mask(N);
579   int offset = tileSizes.size() - N;
580   std::transform(tileSizes.begin() + offset, tileSizes.end(), mask.begin(),
581                  [](int64_t i) -> bool { return i > 1; });
582 
583   vectorizationPatterns.insert<ConvOpVectorization<ConvOp, N>>(context, mask);
584 }
585 
586 void mlir::linalg::populateConvVectorizationPatterns(
587     MLIRContext *context, SmallVectorImpl<OwningRewritePatternList> &patterns,
588     ArrayRef<int64_t> tileSizes) {
589   OwningRewritePatternList tiling, promotion, vectorization;
590   populateVectorizationPatterns<ConvWOp, 1>(tiling, promotion, vectorization,
591                                             tileSizes, context);
592 
593   populateVectorizationPatterns<ConvNWCOp, 3>(tiling, promotion, vectorization,
594                                               tileSizes, context);
595   populateVectorizationPatterns<ConvInputNWCFilterWCFOp, 3>(
596       tiling, promotion, vectorization, tileSizes, context);
597 
598   populateVectorizationPatterns<ConvNCWOp, 3>(tiling, promotion, vectorization,
599                                               tileSizes, context);
600   populateVectorizationPatterns<ConvInputNCWFilterWCFOp, 3>(
601       tiling, promotion, vectorization, tileSizes, context);
602 
603   populateVectorizationPatterns<ConvHWOp, 2>(tiling, promotion, vectorization,
604                                              tileSizes, context);
605 
606   populateVectorizationPatterns<ConvNHWCOp, 4>(tiling, promotion, vectorization,
607                                                tileSizes, context);
608   populateVectorizationPatterns<ConvInputNHWCFilterHWCFOp, 4>(
609       tiling, promotion, vectorization, tileSizes, context);
610 
611   populateVectorizationPatterns<ConvNCHWOp, 4>(tiling, promotion, vectorization,
612                                                tileSizes, context);
613   populateVectorizationPatterns<ConvInputNCHWFilterHWCFOp, 4>(
614       tiling, promotion, vectorization, tileSizes, context);
615 
616   populateVectorizationPatterns<ConvDHWOp, 3>(tiling, promotion, vectorization,
617                                               tileSizes, context);
618 
619   populateVectorizationPatterns<ConvNDHWCOp, 5>(
620       tiling, promotion, vectorization, tileSizes, context);
621   populateVectorizationPatterns<ConvInputNDHWCFilterDHWCFOp, 5>(
622       tiling, promotion, vectorization, tileSizes, context);
623 
624   populateVectorizationPatterns<ConvNCDHWOp, 5>(
625       tiling, promotion, vectorization, tileSizes, context);
626   populateVectorizationPatterns<ConvInputNCDHWFilterDHWCFOp, 5>(
627       tiling, promotion, vectorization, tileSizes, context);
628 
629   patterns.push_back(std::move(tiling));
630   patterns.push_back(std::move(promotion));
631   patterns.push_back(std::move(vectorization));
632 }
633 
634 //----------------------------------------------------------------------------//
635 // Forwarding patterns
636 //----------------------------------------------------------------------------//
637 
638 /// Check whether there is any interleaved use of any `values` between `firstOp`
639 /// and `secondOp`. Conservatively return `true` if any op or value is in a
640 /// different block.
641 static bool mayExistInterleavedUses(Operation *firstOp, Operation *secondOp,
642                                     ValueRange values) {
643   if (firstOp->getBlock() != secondOp->getBlock() ||
644       !firstOp->isBeforeInBlock(secondOp)) {
645     LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
646                             << "interleavedUses precondition failed, firstOp: "
647                             << *firstOp << ", second op: " << *secondOp);
648     return true;
649   }
650   for (auto v : values) {
651     for (auto &u : v.getUses()) {
652       Operation *owner = u.getOwner();
653       if (owner == firstOp || owner == secondOp)
654         continue;
655       // TODO: this is too conservative, use dominance info in the future.
656       if (owner->getBlock() == firstOp->getBlock() &&
657           (owner->isBeforeInBlock(firstOp) || secondOp->isBeforeInBlock(owner)))
658         continue;
659       LLVM_DEBUG(llvm::dbgs()
660                  << "\n[" DEBUG_TYPE "]: "
661                  << " found interleaved op " << *owner
662                  << ", firstOp: " << *firstOp << ", second op: " << *secondOp);
663       return true;
664     }
665   }
666   return false;
667 }
668 
669 /// Return the unique subview use of `v` if it is indeed unique, null otherwise.
670 static SubViewOp getSubViewUseIfUnique(Value v) {
671   SubViewOp subViewOp;
672   for (auto &u : v.getUses()) {
673     if (auto newSubViewOp = dyn_cast<SubViewOp>(u.getOwner())) {
674       if (subViewOp)
675         return SubViewOp();
676       subViewOp = newSubViewOp;
677     }
678   }
679   return subViewOp;
680 }
681 
682 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
683 /// when available.
684 LogicalResult LinalgCopyVTRForwardingPattern::matchAndRewrite(
685     vector::TransferReadOp xferOp, PatternRewriter &rewriter) const {
686 
687   // Transfer into `view`.
688   Value viewOrAlloc = xferOp.source();
689   if (!viewOrAlloc.getDefiningOp<ViewOp>() &&
690       !viewOrAlloc.getDefiningOp<AllocOp>())
691     return failure();
692 
693   LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " << viewOrAlloc);
694 
695   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
696   SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
697   if (!subViewOp)
698     return failure();
699   Value subView = subViewOp.getResult();
700   LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
701                           << "with subView " << subView);
702 
703   // Find the copy into `subView` without interleaved uses.
704   CopyOp copyOp;
705   for (auto &u : subView.getUses()) {
706     if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) {
707       if (newCopyOp.getOutputBuffer(0) != subView)
708         continue;
709       LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
710                               << "copy candidate " << *newCopyOp);
711       if (mayExistInterleavedUses(newCopyOp, xferOp, {viewOrAlloc, subView}))
712         continue;
713       copyOp = newCopyOp;
714       break;
715     }
716   }
717   if (!copyOp)
718     return failure();
719   LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
720                           << "with copy " << *copyOp);
721 
722   // Find the fill into `viewOrAlloc` without interleaved uses before the copy.
723   FillOp maybeFillOp;
724   for (auto &u : viewOrAlloc.getUses()) {
725     if (auto newFillOp = dyn_cast<FillOp>(u.getOwner())) {
726       if (newFillOp.getOutputBuffer(0) != viewOrAlloc)
727         continue;
728       LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
729                               << "fill candidate " << *newFillOp);
730       if (mayExistInterleavedUses(newFillOp, copyOp, {viewOrAlloc, subView}))
731         continue;
732       maybeFillOp = newFillOp;
733       break;
734     }
735   }
736   // Ensure padding matches.
737   if (maybeFillOp && xferOp.padding() != maybeFillOp.value())
738     return failure();
739   if (maybeFillOp)
740     LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: "
741                             << "with maybeFillOp " << *maybeFillOp);
742 
743   // `in` is the subview that linalg.copy reads. Replace it.
744   Value in = copyOp.getInput(0);
745 
746   // linalg.copy + linalg.fill can be used to create a padded local buffer.
747   // The `masked` attribute is only valid on this padded buffer.
748   // When forwarding to vector.transfer_read, the attribute must be reset
749   // conservatively.
750   Value res = rewriter.create<vector::TransferReadOp>(
751       xferOp.getLoc(), xferOp.getVectorType(), in, xferOp.indices(),
752       xferOp.permutation_map(), xferOp.padding(), ArrayAttr());
753 
754   if (maybeFillOp)
755     rewriter.eraseOp(maybeFillOp);
756   rewriter.eraseOp(copyOp);
757   rewriter.replaceOp(xferOp, res);
758 
759   return success();
760 }
761 
762 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
763 /// when available.
764 LogicalResult LinalgCopyVTWForwardingPattern::matchAndRewrite(
765     vector::TransferWriteOp xferOp, PatternRewriter &rewriter) const {
766   // Transfer into `viewOrAlloc`.
767   Value viewOrAlloc = xferOp.source();
768   if (!viewOrAlloc.getDefiningOp<ViewOp>() &&
769       !viewOrAlloc.getDefiningOp<AllocOp>())
770     return failure();
771 
772   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
773   SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
774   if (!subViewOp)
775     return failure();
776   Value subView = subViewOp.getResult();
777 
778   // Find the copy from `subView` without interleaved uses.
779   CopyOp copyOp;
780   for (auto &u : subViewOp.getResult().getUses()) {
781     if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) {
782       if (newCopyOp.getInput(0) != subView)
783         continue;
784       if (mayExistInterleavedUses(xferOp, newCopyOp, {viewOrAlloc, subView}))
785         continue;
786       copyOp = newCopyOp;
787       break;
788     }
789   }
790   if (!copyOp)
791     return failure();
792 
793   // `out` is the subview copied into that we replace.
794   Value out = copyOp.getOutputBuffer(0);
795 
796   // Forward vector.transfer into copy.
797   // linalg.copy + linalg.fill can be used to create a padded local buffer.
798   // The `masked` attribute is only valid on this padded buffer.
799   // When forwarding to vector.transfer_write, the attribute must be reset
800   // conservatively.
801   rewriter.create<vector::TransferWriteOp>(
802       xferOp.getLoc(), xferOp.vector(), out, xferOp.indices(),
803       xferOp.permutation_map(), ArrayAttr());
804 
805   rewriter.eraseOp(copyOp);
806   rewriter.eraseOp(xferOp);
807 
808   return success();
809 }
810