1307cfdf5SNicolas Vasilache //===- Vectorization.cpp - Implementation of linalg Vectorization ---------===//
2307cfdf5SNicolas Vasilache //
3307cfdf5SNicolas Vasilache // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4307cfdf5SNicolas Vasilache // See https://llvm.org/LICENSE.txt for license information.
5307cfdf5SNicolas Vasilache // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6307cfdf5SNicolas Vasilache //
7307cfdf5SNicolas Vasilache //===----------------------------------------------------------------------===//
8307cfdf5SNicolas Vasilache //
9307cfdf5SNicolas Vasilache // This file implements the linalg dialect Vectorization transformations.
10307cfdf5SNicolas Vasilache //
11307cfdf5SNicolas Vasilache //===----------------------------------------------------------------------===//
12307cfdf5SNicolas Vasilache 
13307cfdf5SNicolas Vasilache #include "mlir/Dialect/Linalg/Analysis/DependenceAnalysis.h"
14307cfdf5SNicolas Vasilache #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
15307cfdf5SNicolas Vasilache #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
16307cfdf5SNicolas Vasilache #include "mlir/Dialect/Linalg/Utils/Utils.h"
17307cfdf5SNicolas Vasilache #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h"
18307cfdf5SNicolas Vasilache #include "mlir/Dialect/Utils/StructuredOpsUtils.h"
19307cfdf5SNicolas Vasilache #include "mlir/Dialect/Vector/EDSC/Intrinsics.h"
20307cfdf5SNicolas Vasilache #include "mlir/Dialect/Vector/VectorOps.h"
21307cfdf5SNicolas Vasilache #include "mlir/IR/AffineExpr.h"
22307cfdf5SNicolas Vasilache #include "mlir/IR/Matchers.h"
23307cfdf5SNicolas Vasilache #include "mlir/IR/PatternMatch.h"
24307cfdf5SNicolas Vasilache #include "mlir/Pass/Pass.h"
25307cfdf5SNicolas Vasilache #include "mlir/Support/LLVM.h"
26307cfdf5SNicolas Vasilache #include "llvm/Support/Debug.h"
27307cfdf5SNicolas Vasilache #include "llvm/Support/raw_ostream.h"
28307cfdf5SNicolas Vasilache #include <type_traits>
29307cfdf5SNicolas Vasilache 
30307cfdf5SNicolas Vasilache using namespace mlir;
31307cfdf5SNicolas Vasilache using namespace mlir::edsc;
32307cfdf5SNicolas Vasilache using namespace mlir::edsc::intrinsics;
33307cfdf5SNicolas Vasilache using namespace mlir::linalg;
34307cfdf5SNicolas Vasilache 
35307cfdf5SNicolas Vasilache using llvm::dbgs;
36307cfdf5SNicolas Vasilache 
37307cfdf5SNicolas Vasilache #define DEBUG_TYPE "linalg-vectorization"
38307cfdf5SNicolas Vasilache 
3956c638b5SNicolas Vasilache static bool hasMultiplyAddBody(Region &r) {
40307cfdf5SNicolas Vasilache   if (!llvm::hasSingleElement(r))
41307cfdf5SNicolas Vasilache     return false;
42307cfdf5SNicolas Vasilache   if (!llvm::hasNItems(r.front().begin(), r.front().end(), 3))
43307cfdf5SNicolas Vasilache     return false;
44307cfdf5SNicolas Vasilache 
45307cfdf5SNicolas Vasilache   using mlir::matchers::m_Val;
46706d992cSRahul Joshi   auto a = m_Val(r.getArgument(0));
47706d992cSRahul Joshi   auto b = m_Val(r.getArgument(1));
48706d992cSRahul Joshi   auto c = m_Val(r.getArgument(2));
49307cfdf5SNicolas Vasilache   // TODO: Update this detection once we have  matcher support for specifying
50307cfdf5SNicolas Vasilache   // that any permutation of operands matches.
51136eb79aSFrederik Gossen   auto pattern1 = m_Op<linalg::YieldOp>(m_Op<AddFOp>(m_Op<MulFOp>(a, b), c));
52136eb79aSFrederik Gossen   auto pattern2 = m_Op<linalg::YieldOp>(m_Op<AddFOp>(c, m_Op<MulFOp>(a, b)));
53136eb79aSFrederik Gossen   auto pattern3 = m_Op<linalg::YieldOp>(m_Op<AddFOp>(m_Op<MulFOp>(b, a), c));
54136eb79aSFrederik Gossen   auto pattern4 = m_Op<linalg::YieldOp>(m_Op<AddFOp>(c, m_Op<MulFOp>(b, a)));
55136eb79aSFrederik Gossen   auto pattern5 = m_Op<linalg::YieldOp>(m_Op<AddIOp>(m_Op<MulIOp>(a, b), c));
56136eb79aSFrederik Gossen   auto pattern6 = m_Op<linalg::YieldOp>(m_Op<AddIOp>(c, m_Op<MulIOp>(a, b)));
57136eb79aSFrederik Gossen   auto pattern7 = m_Op<linalg::YieldOp>(m_Op<AddIOp>(m_Op<MulIOp>(b, a), c));
58136eb79aSFrederik Gossen   auto pattern8 = m_Op<linalg::YieldOp>(m_Op<AddIOp>(c, m_Op<MulIOp>(b, a)));
59307cfdf5SNicolas Vasilache   return pattern1.match(&r.front().back()) ||
60307cfdf5SNicolas Vasilache          pattern2.match(&r.front().back()) ||
61bf561dd2SBenjamin Kramer          pattern3.match(&r.front().back()) ||
62bf561dd2SBenjamin Kramer          pattern4.match(&r.front().back()) ||
63bf561dd2SBenjamin Kramer          pattern5.match(&r.front().back()) ||
64bf561dd2SBenjamin Kramer          pattern6.match(&r.front().back()) ||
65bf561dd2SBenjamin Kramer          pattern7.match(&r.front().back()) || pattern8.match(&r.front().back());
66307cfdf5SNicolas Vasilache }
67307cfdf5SNicolas Vasilache 
68307cfdf5SNicolas Vasilache // TODO: Should be Tablegen'd from a single source that generates the op itself.
6956c638b5SNicolas Vasilache static LogicalResult isContraction(Operation *op) {
7056c638b5SNicolas Vasilache   // TODO: interface for named ops.
7156c638b5SNicolas Vasilache   if (isa<linalg::BatchMatmulOp, linalg::MatmulOp, linalg::MatvecOp,
7256c638b5SNicolas Vasilache           linalg::DotOp>(op))
7356c638b5SNicolas Vasilache     return success();
7456c638b5SNicolas Vasilache 
7556c638b5SNicolas Vasilache   auto genericOp = dyn_cast<linalg::GenericOp>(op);
7656c638b5SNicolas Vasilache   if (!genericOp)
7756c638b5SNicolas Vasilache     return failure();
7856c638b5SNicolas Vasilache 
79d289a97fSRiver Riddle   auto mapRange = genericOp.indexing_maps().getAsValueRange<AffineMapAttr>();
8056c638b5SNicolas Vasilache   return success(
8156c638b5SNicolas Vasilache       genericOp.getNumInputs() == 2 && genericOp.getNumOutputs() == 1 &&
8256c638b5SNicolas Vasilache       llvm::all_of(mapRange,
8356c638b5SNicolas Vasilache                    [](AffineMap m) { return m.isProjectedPermutation(); }) &&
8456c638b5SNicolas Vasilache       hasMultiplyAddBody(genericOp.region()));
85307cfdf5SNicolas Vasilache }
86307cfdf5SNicolas Vasilache 
87307cfdf5SNicolas Vasilache LogicalResult mlir::linalg::vectorizeLinalgOpPrecondition(Operation *op) {
88307cfdf5SNicolas Vasilache   auto linalgOp = cast<linalg::LinalgOp>(op);
89307cfdf5SNicolas Vasilache   // All types must be static shape to go to vector.
90307cfdf5SNicolas Vasilache   for (Value operand : linalgOp.getInputsAndOutputBuffers())
91307cfdf5SNicolas Vasilache     if (!operand.getType().cast<ShapedType>().hasStaticShape())
92307cfdf5SNicolas Vasilache       return failure();
93307cfdf5SNicolas Vasilache   for (Type outputTensorType : linalgOp.getOutputTensorTypes())
94307cfdf5SNicolas Vasilache     if (!outputTensorType.cast<ShapedType>().hasStaticShape())
95307cfdf5SNicolas Vasilache       return failure();
9656c638b5SNicolas Vasilache 
97a1b9fb22SThomas Raoux   if (isa<linalg::FillOp, linalg::CopyOp>(op))
98307cfdf5SNicolas Vasilache     return success();
99307cfdf5SNicolas Vasilache 
10056c638b5SNicolas Vasilache   return isContraction(op);
101307cfdf5SNicolas Vasilache }
102307cfdf5SNicolas Vasilache 
103307cfdf5SNicolas Vasilache void mlir::linalg::vectorizeLinalgOp(OpBuilder &builder, Operation *op) {
104307cfdf5SNicolas Vasilache   assert(succeeded(vectorizeLinalgOpPrecondition(op)));
105307cfdf5SNicolas Vasilache 
1061ee11432SNicolas Vasilache   StringRef dbgPref = "\n[" DEBUG_TYPE "]: ";
1071ee11432SNicolas Vasilache   (void)dbgPref;
108307cfdf5SNicolas Vasilache   edsc::ScopedContext scope(builder, op->getLoc());
109307cfdf5SNicolas Vasilache   if (auto fillOp = dyn_cast<linalg::FillOp>(op)) {
110307cfdf5SNicolas Vasilache     // Vectorize fill as a vector.broadcast.
1111ee11432SNicolas Vasilache     LLVM_DEBUG(dbgs() << dbgPref
1121ee11432SNicolas Vasilache                       << "Rewrite linalg.fill as vector.broadcast: " << *op);
113307cfdf5SNicolas Vasilache     Value memref = vector_type_cast(fillOp.getOutputBuffer(0));
114307cfdf5SNicolas Vasilache     Value dst = std_load(memref);
115307cfdf5SNicolas Vasilache     Value res = vector_broadcast(dst.getType(), fillOp.value());
116307cfdf5SNicolas Vasilache     std_store(res, memref);
117307cfdf5SNicolas Vasilache     return;
118307cfdf5SNicolas Vasilache   }
119307cfdf5SNicolas Vasilache 
12056c638b5SNicolas Vasilache   // In the case of 0-D memrefs, return null and special case to scalar load or
12156c638b5SNicolas Vasilache   // store later.
1229534192cSNicolas Vasilache   auto extractVectorTypeFromScalarView = [](Value v) {
1239534192cSNicolas Vasilache     MemRefType mt = v.getType().cast<MemRefType>();
12456c638b5SNicolas Vasilache     return mt.getShape().empty()
12556c638b5SNicolas Vasilache                ? VectorType()
12656c638b5SNicolas Vasilache                : VectorType::get(mt.getShape(), mt.getElementType());
1279534192cSNicolas Vasilache   };
128a1b9fb22SThomas Raoux 
129a1b9fb22SThomas Raoux   if (auto copyOp = dyn_cast<linalg::CopyOp>(op)) {
130a1b9fb22SThomas Raoux     // Vectorize copy as a vector.transfer_read+vector.transfer_write.
131a1b9fb22SThomas Raoux     LLVM_DEBUG(dbgs() << dbgPref
132a1b9fb22SThomas Raoux                       << "Rewrite linalg.copy as vector.transfer_read + "
133a1b9fb22SThomas Raoux                          "vector.transfer_write: "
134a1b9fb22SThomas Raoux                       << *op);
135a1b9fb22SThomas Raoux     Value zero = std_constant_index(0);
136a1b9fb22SThomas Raoux     Value viewInput = copyOp.input();
137a1b9fb22SThomas Raoux     Value viewOutput = copyOp.output();
138a1b9fb22SThomas Raoux     Value vector;
139a1b9fb22SThomas Raoux     if (VectorType inputType = extractVectorTypeFromScalarView(viewInput)) {
140a1b9fb22SThomas Raoux       SmallVector<Value, 4> indicesInput(inputType.getRank(), zero);
141a1b9fb22SThomas Raoux       if (copyOp.inputPermutation())
142a1b9fb22SThomas Raoux         vector = vector_transfer_read(
143a1b9fb22SThomas Raoux             extractVectorTypeFromScalarView(viewInput), viewInput, indicesInput,
144a1b9fb22SThomas Raoux             copyOp.inputPermutation().getValue());
145a1b9fb22SThomas Raoux       else
146a1b9fb22SThomas Raoux         vector =
147a1b9fb22SThomas Raoux             vector_transfer_read(extractVectorTypeFromScalarView(viewInput),
148a1b9fb22SThomas Raoux                                  viewInput, indicesInput);
149a1b9fb22SThomas Raoux     } else {
150a1b9fb22SThomas Raoux       vector = std_load(viewInput).value;
151a1b9fb22SThomas Raoux     }
152a1b9fb22SThomas Raoux     if (VectorType outputType = extractVectorTypeFromScalarView(viewOutput)) {
153a1b9fb22SThomas Raoux       SmallVector<Value, 4> indicesOutput(outputType.getRank(), zero);
154a1b9fb22SThomas Raoux       if (copyOp.outputPermutation())
155a1b9fb22SThomas Raoux         vector_transfer_write(vector, viewOutput, indicesOutput,
156a1b9fb22SThomas Raoux                               copyOp.outputPermutation().getValue());
157a1b9fb22SThomas Raoux       else
158a1b9fb22SThomas Raoux         vector_transfer_write(vector, viewOutput, indicesOutput);
159a1b9fb22SThomas Raoux     } else {
160a1b9fb22SThomas Raoux       std_store(vector, viewOutput);
161a1b9fb22SThomas Raoux     }
162a1b9fb22SThomas Raoux     return;
163a1b9fb22SThomas Raoux   }
164a1b9fb22SThomas Raoux 
165a1b9fb22SThomas Raoux   assert(succeeded(isContraction(op)) && "Expected contraction");
166a1b9fb22SThomas Raoux 
167a1b9fb22SThomas Raoux   // Vectorize other ops as vector contraction.
168a1b9fb22SThomas Raoux   // TODO: interface.
169a1b9fb22SThomas Raoux   LLVM_DEBUG(dbgs() << dbgPref
170a1b9fb22SThomas Raoux                     << "Rewrite linalg op as vector.contract: " << *op);
171307cfdf5SNicolas Vasilache   auto linalgOp = cast<linalg::LinalgOp>(op);
1729534192cSNicolas Vasilache   Value viewA = linalgOp.getInput(0);
1739534192cSNicolas Vasilache   Value viewB = linalgOp.getInput(1);
1749534192cSNicolas Vasilache   Value viewC = linalgOp.getOutputBuffer(0);
17556c638b5SNicolas Vasilache   VectorType vtA = extractVectorTypeFromScalarView(viewA);
17656c638b5SNicolas Vasilache   VectorType vtB = extractVectorTypeFromScalarView(viewB);
17756c638b5SNicolas Vasilache   VectorType vtC = extractVectorTypeFromScalarView(viewC);
1789534192cSNicolas Vasilache   Value zero = std_constant_index(0);
17956c638b5SNicolas Vasilache   SmallVector<Value, 4> indicesA, indicesB, indicesC;
18056c638b5SNicolas Vasilache   if (vtA)
18156c638b5SNicolas Vasilache     indicesA = SmallVector<Value, 4>(vtA.getRank(), zero);
18256c638b5SNicolas Vasilache   if (vtB)
18356c638b5SNicolas Vasilache     indicesB = SmallVector<Value, 4>(vtB.getRank(), zero);
18456c638b5SNicolas Vasilache   if (vtC)
18556c638b5SNicolas Vasilache     indicesC = SmallVector<Value, 4>(vtC.getRank(), zero);
18656c638b5SNicolas Vasilache   Value a = vtA ? vector_transfer_read(vtA, viewA, indicesA).value
18756c638b5SNicolas Vasilache                 : std_load(viewA, indicesA).value;
18856c638b5SNicolas Vasilache   Value b = vtB ? vector_transfer_read(vtB, viewB, indicesB).value
18956c638b5SNicolas Vasilache                 : std_load(viewB, indicesB).value;
19056c638b5SNicolas Vasilache   Value c = vtC ? vector_transfer_read(vtC, viewC, indicesC).value
19156c638b5SNicolas Vasilache                 : std_load(viewC, indicesC).value;
192307cfdf5SNicolas Vasilache   Value res = vector_contract(a, b, c, linalgOp.indexing_maps(),
193307cfdf5SNicolas Vasilache                               linalgOp.iterator_types());
19456c638b5SNicolas Vasilache   if (vtC)
1959534192cSNicolas Vasilache     vector_transfer_write(res, viewC, indicesC);
19656c638b5SNicolas Vasilache   else
19756c638b5SNicolas Vasilache     std_store(res, viewC, indicesC);
198307cfdf5SNicolas Vasilache }
1991ee11432SNicolas Vasilache 
2001ee11432SNicolas Vasilache /// Check whether there is any interleaved use of any `values` between `firstOp`
2011ee11432SNicolas Vasilache /// and `secondOp`. Conservatively return `true` if any op or value is in a
2021ee11432SNicolas Vasilache /// different block.
2031ee11432SNicolas Vasilache static bool mayExistInterleavedUses(Operation *firstOp, Operation *secondOp,
2041ee11432SNicolas Vasilache                                     ValueRange values) {
2051ee11432SNicolas Vasilache   StringRef dbgPref = "\n[" DEBUG_TYPE "]: ";
2061ee11432SNicolas Vasilache   (void)dbgPref;
2071ee11432SNicolas Vasilache   if (firstOp->getBlock() != secondOp->getBlock() ||
2081ee11432SNicolas Vasilache       !firstOp->isBeforeInBlock(secondOp)) {
2091ee11432SNicolas Vasilache     LLVM_DEBUG(llvm::dbgs()
2101ee11432SNicolas Vasilache                << dbgPref << "interleavedUses precondition failed, firstOp: "
2111ee11432SNicolas Vasilache                << *firstOp << ", second op: " << *secondOp);
2121ee11432SNicolas Vasilache     return true;
2131ee11432SNicolas Vasilache   }
2141ee11432SNicolas Vasilache   for (auto v : values) {
2151ee11432SNicolas Vasilache     for (auto &u : v.getUses()) {
2161ee11432SNicolas Vasilache       Operation *owner = u.getOwner();
2171ee11432SNicolas Vasilache       if (owner == firstOp || owner == secondOp)
2181ee11432SNicolas Vasilache         continue;
2191ee11432SNicolas Vasilache       // TODO: this is too conservative, use dominance info in the future.
2201ee11432SNicolas Vasilache       if (owner->getBlock() == firstOp->getBlock() &&
2211ee11432SNicolas Vasilache           (owner->isBeforeInBlock(firstOp) || secondOp->isBeforeInBlock(owner)))
2221ee11432SNicolas Vasilache         continue;
2231ee11432SNicolas Vasilache       LLVM_DEBUG(llvm::dbgs()
2241ee11432SNicolas Vasilache                  << dbgPref << " found interleaved op " << *owner
2251ee11432SNicolas Vasilache                  << ", firstOp: " << *firstOp << ", second op: " << *secondOp);
2261ee11432SNicolas Vasilache       return true;
2271ee11432SNicolas Vasilache     }
2281ee11432SNicolas Vasilache   }
2291ee11432SNicolas Vasilache   return false;
2301ee11432SNicolas Vasilache }
2311ee11432SNicolas Vasilache 
2321ee11432SNicolas Vasilache /// Return the unique subview use of `v` if it is indeed unique, null otherwise.
2331ee11432SNicolas Vasilache static SubViewOp getSubViewUseIfUnique(Value v) {
2341ee11432SNicolas Vasilache   SubViewOp subViewOp;
2351ee11432SNicolas Vasilache   for (auto &u : v.getUses()) {
2361ee11432SNicolas Vasilache     if (auto newSubViewOp = dyn_cast<SubViewOp>(u.getOwner())) {
2371ee11432SNicolas Vasilache       if (subViewOp)
2381ee11432SNicolas Vasilache         return SubViewOp();
2391ee11432SNicolas Vasilache       subViewOp = newSubViewOp;
2401ee11432SNicolas Vasilache     }
2411ee11432SNicolas Vasilache   }
2421ee11432SNicolas Vasilache   return subViewOp;
2431ee11432SNicolas Vasilache }
2441ee11432SNicolas Vasilache 
2451ee11432SNicolas Vasilache /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
2461ee11432SNicolas Vasilache /// when available.
2471ee11432SNicolas Vasilache LogicalResult LinalgCopyVTRForwardingPattern::matchAndRewrite(
2481ee11432SNicolas Vasilache     vector::TransferReadOp xferOp, PatternRewriter &rewriter) const {
2491ee11432SNicolas Vasilache 
2501ee11432SNicolas Vasilache   // Transfer into `view`.
2511ee11432SNicolas Vasilache   Value viewOrAlloc = xferOp.memref();
2521ee11432SNicolas Vasilache   if (!viewOrAlloc.getDefiningOp<ViewOp>() &&
2531ee11432SNicolas Vasilache       !viewOrAlloc.getDefiningOp<AllocOp>())
2541ee11432SNicolas Vasilache     return failure();
2551ee11432SNicolas Vasilache 
2561ee11432SNicolas Vasilache   StringRef dbgPref = "\n[" DEBUG_TYPE "]: VTRForwarding: ";
2571ee11432SNicolas Vasilache   (void)dbgPref;
2581ee11432SNicolas Vasilache   LLVM_DEBUG(llvm::dbgs() << dbgPref << viewOrAlloc);
2591ee11432SNicolas Vasilache 
2601ee11432SNicolas Vasilache   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
2611ee11432SNicolas Vasilache   SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
2621ee11432SNicolas Vasilache   if (!subViewOp)
2631ee11432SNicolas Vasilache     return failure();
2641ee11432SNicolas Vasilache   Value subView = subViewOp.getResult();
2651ee11432SNicolas Vasilache   LLVM_DEBUG(llvm::dbgs() << dbgPref << "with subView " << subView);
2661ee11432SNicolas Vasilache 
2671ee11432SNicolas Vasilache   // Find the copy into `subView` without interleaved uses.
2681ee11432SNicolas Vasilache   CopyOp copyOp;
2691ee11432SNicolas Vasilache   for (auto &u : subView.getUses()) {
2701ee11432SNicolas Vasilache     if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) {
2711ee11432SNicolas Vasilache       if (newCopyOp.getOutputBuffer(0) != subView)
2721ee11432SNicolas Vasilache         continue;
2731ee11432SNicolas Vasilache       LLVM_DEBUG(llvm::dbgs() << dbgPref << "copy candidate " << *newCopyOp);
2741ee11432SNicolas Vasilache       if (mayExistInterleavedUses(newCopyOp, xferOp, {viewOrAlloc, subView}))
2751ee11432SNicolas Vasilache         continue;
2761ee11432SNicolas Vasilache       copyOp = newCopyOp;
2771ee11432SNicolas Vasilache       break;
2781ee11432SNicolas Vasilache     }
2791ee11432SNicolas Vasilache   }
2801ee11432SNicolas Vasilache   if (!copyOp)
2811ee11432SNicolas Vasilache     return failure();
2821ee11432SNicolas Vasilache   LLVM_DEBUG(llvm::dbgs() << dbgPref << "with copy " << *copyOp);
2831ee11432SNicolas Vasilache 
2841ee11432SNicolas Vasilache   // Find the fill into `viewOrAlloc` without interleaved uses before the copy.
2851ee11432SNicolas Vasilache   FillOp maybeFillOp;
2861ee11432SNicolas Vasilache   for (auto &u : viewOrAlloc.getUses()) {
2871ee11432SNicolas Vasilache     if (auto newFillOp = dyn_cast<FillOp>(u.getOwner())) {
2881ee11432SNicolas Vasilache       if (newFillOp.getOutputBuffer(0) != viewOrAlloc)
2891ee11432SNicolas Vasilache         continue;
2901ee11432SNicolas Vasilache       LLVM_DEBUG(llvm::dbgs() << dbgPref << "fill candidate " << *newFillOp);
2911ee11432SNicolas Vasilache       if (mayExistInterleavedUses(newFillOp, copyOp, {viewOrAlloc, subView}))
2921ee11432SNicolas Vasilache         continue;
2931ee11432SNicolas Vasilache       maybeFillOp = newFillOp;
2941ee11432SNicolas Vasilache       break;
2951ee11432SNicolas Vasilache     }
2961ee11432SNicolas Vasilache   }
2971ee11432SNicolas Vasilache   // Ensure padding matches.
2981ee11432SNicolas Vasilache   if (maybeFillOp && xferOp.padding() != maybeFillOp.value())
2991ee11432SNicolas Vasilache     return failure();
3001ee11432SNicolas Vasilache   if (maybeFillOp)
3011ee11432SNicolas Vasilache     LLVM_DEBUG(llvm::dbgs() << dbgPref << "with maybeFillOp " << *maybeFillOp);
3021ee11432SNicolas Vasilache 
3031ee11432SNicolas Vasilache   // `in` is the subview that linalg.copy reads. Replace it.
3041ee11432SNicolas Vasilache   Value in = copyOp.getInput(0);
3051ee11432SNicolas Vasilache 
306512da70bSNicolas Vasilache   // linalg.copy + linalg.fill can be used to create a padded local buffer.
307512da70bSNicolas Vasilache   // The `masked` attribute is only valid on this padded buffer.
308512da70bSNicolas Vasilache   // When forwarding to vector.transfer_read, the attribute must be reset
309512da70bSNicolas Vasilache   // conservatively.
3101ee11432SNicolas Vasilache   Value res = rewriter.create<vector::TransferReadOp>(
3111ee11432SNicolas Vasilache       xferOp.getLoc(), xferOp.getVectorType(), in, xferOp.indices(),
312512da70bSNicolas Vasilache       xferOp.permutation_map(), xferOp.padding(), ArrayAttr());
3131ee11432SNicolas Vasilache 
3141ee11432SNicolas Vasilache   if (maybeFillOp)
3151ee11432SNicolas Vasilache     rewriter.eraseOp(maybeFillOp);
3161ee11432SNicolas Vasilache   rewriter.eraseOp(copyOp);
3171ee11432SNicolas Vasilache   rewriter.replaceOp(xferOp, res);
3181ee11432SNicolas Vasilache 
3191ee11432SNicolas Vasilache   return success();
3201ee11432SNicolas Vasilache }
3211ee11432SNicolas Vasilache 
3221ee11432SNicolas Vasilache /// TODO: use interfaces, side-effects and aliasing analysis as appropriate,
3231ee11432SNicolas Vasilache /// when available.
3241ee11432SNicolas Vasilache LogicalResult LinalgCopyVTWForwardingPattern::matchAndRewrite(
3251ee11432SNicolas Vasilache     vector::TransferWriteOp xferOp, PatternRewriter &rewriter) const {
3261ee11432SNicolas Vasilache   // Transfer into `viewOrAlloc`.
3271ee11432SNicolas Vasilache   Value viewOrAlloc = xferOp.memref();
3281ee11432SNicolas Vasilache   if (!viewOrAlloc.getDefiningOp<ViewOp>() &&
3291ee11432SNicolas Vasilache       !viewOrAlloc.getDefiningOp<AllocOp>())
3301ee11432SNicolas Vasilache     return failure();
3311ee11432SNicolas Vasilache 
3321ee11432SNicolas Vasilache   // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`.
3331ee11432SNicolas Vasilache   SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc);
3341ee11432SNicolas Vasilache   if (!subViewOp)
3351ee11432SNicolas Vasilache     return failure();
3361ee11432SNicolas Vasilache   Value subView = subViewOp.getResult();
3371ee11432SNicolas Vasilache 
3381ee11432SNicolas Vasilache   // Find the copy from `subView` without interleaved uses.
3391ee11432SNicolas Vasilache   CopyOp copyOp;
3401ee11432SNicolas Vasilache   for (auto &u : subViewOp.getResult().getUses()) {
3411ee11432SNicolas Vasilache     if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) {
3421ee11432SNicolas Vasilache       if (newCopyOp.getInput(0) != subView)
3431ee11432SNicolas Vasilache         continue;
3441ee11432SNicolas Vasilache       if (mayExistInterleavedUses(xferOp, newCopyOp, {viewOrAlloc, subView}))
3451ee11432SNicolas Vasilache         continue;
3461ee11432SNicolas Vasilache       copyOp = newCopyOp;
3471ee11432SNicolas Vasilache       break;
3481ee11432SNicolas Vasilache     }
3491ee11432SNicolas Vasilache   }
3501ee11432SNicolas Vasilache   if (!copyOp)
3511ee11432SNicolas Vasilache     return failure();
3521ee11432SNicolas Vasilache 
3531ee11432SNicolas Vasilache   // `out` is the subview copied into that we replace.
3541ee11432SNicolas Vasilache   Value out = copyOp.getOutputBuffer(0);
3551ee11432SNicolas Vasilache 
3561ee11432SNicolas Vasilache   // Forward vector.transfer into copy.
357512da70bSNicolas Vasilache   // linalg.copy + linalg.fill can be used to create a padded local buffer.
358512da70bSNicolas Vasilache   // The `masked` attribute is only valid on this padded buffer.
359512da70bSNicolas Vasilache   // When forwarding to vector.transfer_write, the attribute must be reset
360512da70bSNicolas Vasilache   // conservatively.
3611ee11432SNicolas Vasilache   rewriter.create<vector::TransferWriteOp>(
3621ee11432SNicolas Vasilache       xferOp.getLoc(), xferOp.vector(), out, xferOp.indices(),
363512da70bSNicolas Vasilache       xferOp.permutation_map(), ArrayAttr());
3641ee11432SNicolas Vasilache 
3651ee11432SNicolas Vasilache   rewriter.eraseOp(copyOp);
3661ee11432SNicolas Vasilache   rewriter.eraseOp(xferOp);
3671ee11432SNicolas Vasilache 
3681ee11432SNicolas Vasilache   return success();
3691ee11432SNicolas Vasilache }
37067b37f57SJakub Lichman 
37167b37f57SJakub Lichman template <class ConvOp, int N>
37267b37f57SJakub Lichman LogicalResult ConvOpVectorization<ConvOp, N>::matchAndRewrite(
37367b37f57SJakub Lichman     ConvOp op, PatternRewriter &rewriter) const {
374*83d82d1fSJakub Lichman   const unsigned dimSize = 3;
37567b37f57SJakub Lichman   Location loc = op.getLoc();
37667b37f57SJakub Lichman   MLIRContext *context = op.getContext();
37767b37f57SJakub Lichman   edsc::ScopedContext scope(rewriter, loc);
37867b37f57SJakub Lichman 
37967b37f57SJakub Lichman   ShapedType inShapeType = op.getInputShapedType(0);
38067b37f57SJakub Lichman   ShapedType kShapeType = op.getInputShapedType(1);
38167b37f57SJakub Lichman 
38267b37f57SJakub Lichman   ArrayRef<int64_t> inShape = inShapeType.getShape();
38367b37f57SJakub Lichman   ArrayRef<int64_t> kShape = kShapeType.getShape();
38467b37f57SJakub Lichman 
38567b37f57SJakub Lichman   if (!inShapeType.hasStaticShape() || !kShapeType.hasStaticShape())
38667b37f57SJakub Lichman     return failure();
38767b37f57SJakub Lichman 
38867b37f57SJakub Lichman   SmallVector<AffineExpr, 4> mapping;
38967b37f57SJakub Lichman   // Fail to apply when the size of not vectorized dimension is not 1 or
39067b37f57SJakub Lichman   // when the size of vectorized dimension is not dimSize.
39167b37f57SJakub Lichman   for (unsigned i = 0; i < N; i++) {
39267b37f57SJakub Lichman     if (!mask[i] && (inShape[i] != 1 || kShape[i] != 1))
39367b37f57SJakub Lichman       return failure();
39467b37f57SJakub Lichman     if (mask[i] && (inShape[i] != dimSize || kShape[i] != dimSize))
39567b37f57SJakub Lichman       return failure();
39667b37f57SJakub Lichman 
39767b37f57SJakub Lichman     if (mask[i])
39867b37f57SJakub Lichman       mapping.push_back(getAffineDimExpr(i, context));
39967b37f57SJakub Lichman   }
40067b37f57SJakub Lichman 
40167b37f57SJakub Lichman   Value input = op.getInput(0);
40267b37f57SJakub Lichman   Value kernel = op.getInput(1);
40367b37f57SJakub Lichman   Value output = op.getOutputBuffer(0);
40467b37f57SJakub Lichman 
405*83d82d1fSJakub Lichman   unsigned rank = inShapeType.getRank();
406*83d82d1fSJakub Lichman   unsigned numDims = mapping.size();
40767b37f57SJakub Lichman   Type elemType = inShapeType.getElementType();
40867b37f57SJakub Lichman 
40967b37f57SJakub Lichman   auto map = AffineMap::get(rank, 0, mapping, context);
41067b37f57SJakub Lichman   SmallVector<Value, 4> zeros(rank, std_constant_index(0));
41167b37f57SJakub Lichman   auto vecType =
41267b37f57SJakub Lichman       VectorType::get(SmallVector<int64_t, 4>(numDims, dimSize), elemType);
41367b37f57SJakub Lichman 
41467b37f57SJakub Lichman   auto inputVec = vector_transfer_read(vecType, input, zeros, map);
41567b37f57SJakub Lichman   auto kernelVec = vector_transfer_read(vecType, kernel, zeros, map);
41667b37f57SJakub Lichman 
41767b37f57SJakub Lichman   auto acc = std_constant(elemType, rewriter.getZeroAttr(elemType));
41867b37f57SJakub Lichman 
41967b37f57SJakub Lichman   std::array<AffineMap, 3> indexingMaps{
42067b37f57SJakub Lichman       AffineMap::getMultiDimIdentityMap(numDims, context),
42167b37f57SJakub Lichman       AffineMap::getMultiDimIdentityMap(numDims, context),
42267b37f57SJakub Lichman       AffineMap::get(numDims, 0, {}, context)};
42367b37f57SJakub Lichman 
42467b37f57SJakub Lichman   std::vector<StringRef> iteratorTypes(numDims, "reduction");
42567b37f57SJakub Lichman 
42667b37f57SJakub Lichman   auto result = rewriter.create<vector::ContractionOp>(
42767b37f57SJakub Lichman       loc, inputVec, kernelVec, acc,
42867b37f57SJakub Lichman       rewriter.getAffineMapArrayAttr(indexingMaps),
42967b37f57SJakub Lichman       rewriter.getStrArrayAttr(iteratorTypes));
43067b37f57SJakub Lichman 
43167b37f57SJakub Lichman   rewriter.create<StoreOp>(loc, result, output, ValueRange(zeros));
43267b37f57SJakub Lichman   rewriter.eraseOp(op);
43367b37f57SJakub Lichman   return success();
43467b37f57SJakub Lichman }
43567b37f57SJakub Lichman 
43667b37f57SJakub Lichman void mlir::linalg::populateConvVectorizationPatterns(
43767b37f57SJakub Lichman     MLIRContext *context, OwningRewritePatternList &patterns) {
43867b37f57SJakub Lichman   patterns.insert<ConvOpVectorization<linalg::ConvWOp, 1>>(
43967b37f57SJakub Lichman       context, SmallVector<bool, 4>{true});
44067b37f57SJakub Lichman 
44167b37f57SJakub Lichman   patterns.insert<ConvOpVectorization<linalg::ConvNWCOp, 3>>(
44267b37f57SJakub Lichman       context, SmallVector<bool, 4>{false, true, true});
44367b37f57SJakub Lichman 
44467b37f57SJakub Lichman   patterns.insert<ConvOpVectorization<linalg::ConvNCWOp, 3>>(
44567b37f57SJakub Lichman       context, SmallVector<bool, 4>{false, true, true});
44667b37f57SJakub Lichman 
44767b37f57SJakub Lichman   patterns.insert<ConvOpVectorization<linalg::ConvHWOp, 2>>(
44867b37f57SJakub Lichman       context, SmallVector<bool, 4>{true, true});
44967b37f57SJakub Lichman 
45067b37f57SJakub Lichman   patterns.insert<ConvOpVectorization<linalg::ConvNHWCOp, 4>>(
45167b37f57SJakub Lichman       context, SmallVector<bool, 4>{false, true, true, true});
45267b37f57SJakub Lichman 
45367b37f57SJakub Lichman   patterns.insert<ConvOpVectorization<linalg::ConvNCHWOp, 4>>(
45467b37f57SJakub Lichman       context, SmallVector<bool, 4>{false, true, true, true});
45567b37f57SJakub Lichman 
45667b37f57SJakub Lichman   patterns.insert<ConvOpVectorization<linalg::ConvDHWOp, 3>>(
45767b37f57SJakub Lichman       context, SmallVector<bool, 4>{true, true, true});
45867b37f57SJakub Lichman 
45967b37f57SJakub Lichman   patterns.insert<ConvOpVectorization<linalg::ConvNDHWCOp, 5>>(
46067b37f57SJakub Lichman       context, SmallVector<bool, 4>{false, true, true, true, true});
46167b37f57SJakub Lichman 
46267b37f57SJakub Lichman   patterns.insert<ConvOpVectorization<linalg::ConvNCDHWOp, 5>>(
46367b37f57SJakub Lichman       context, SmallVector<bool, 4>{false, true, true, true, true});
46467b37f57SJakub Lichman }
465