15c0c51a9SNicolas Vasilache //===- VectorToLLVM.cpp - Conversion from Vector to the LLVM dialect ------===//
25c0c51a9SNicolas Vasilache //
330857107SMehdi Amini // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
456222a06SMehdi Amini // See https://llvm.org/LICENSE.txt for license information.
556222a06SMehdi Amini // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65c0c51a9SNicolas Vasilache //
756222a06SMehdi Amini //===----------------------------------------------------------------------===//
85c0c51a9SNicolas Vasilache 
965678d93SNicolas Vasilache #include "mlir/Conversion/VectorToLLVM/ConvertVectorToLLVM.h"
10870c1fd4SAlex Zinenko 
115c0c51a9SNicolas Vasilache #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVM.h"
125c0c51a9SNicolas Vasilache #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h"
135c0c51a9SNicolas Vasilache #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
1469d757c0SRob Suderman #include "mlir/Dialect/StandardOps/IR/Ops.h"
155c0c51a9SNicolas Vasilache #include "mlir/Dialect/VectorOps/VectorOps.h"
165c0c51a9SNicolas Vasilache #include "mlir/IR/Attributes.h"
175c0c51a9SNicolas Vasilache #include "mlir/IR/Builders.h"
185c0c51a9SNicolas Vasilache #include "mlir/IR/MLIRContext.h"
195c0c51a9SNicolas Vasilache #include "mlir/IR/Module.h"
205c0c51a9SNicolas Vasilache #include "mlir/IR/Operation.h"
215c0c51a9SNicolas Vasilache #include "mlir/IR/PatternMatch.h"
225c0c51a9SNicolas Vasilache #include "mlir/IR/StandardTypes.h"
235c0c51a9SNicolas Vasilache #include "mlir/IR/Types.h"
245c0c51a9SNicolas Vasilache #include "mlir/Pass/Pass.h"
255c0c51a9SNicolas Vasilache #include "mlir/Pass/PassManager.h"
265c0c51a9SNicolas Vasilache #include "mlir/Transforms/DialectConversion.h"
275c0c51a9SNicolas Vasilache #include "mlir/Transforms/Passes.h"
285c0c51a9SNicolas Vasilache #include "llvm/IR/DerivedTypes.h"
295c0c51a9SNicolas Vasilache #include "llvm/IR/Module.h"
305c0c51a9SNicolas Vasilache #include "llvm/IR/Type.h"
315c0c51a9SNicolas Vasilache #include "llvm/Support/Allocator.h"
325c0c51a9SNicolas Vasilache #include "llvm/Support/ErrorHandling.h"
335c0c51a9SNicolas Vasilache 
345c0c51a9SNicolas Vasilache using namespace mlir;
3565678d93SNicolas Vasilache using namespace mlir::vector;
365c0c51a9SNicolas Vasilache 
375c0c51a9SNicolas Vasilache template <typename T>
385c0c51a9SNicolas Vasilache static LLVM::LLVMType getPtrToElementType(T containerType,
390f04384dSAlex Zinenko                                           LLVMTypeConverter &typeConverter) {
400f04384dSAlex Zinenko   return typeConverter.convertType(containerType.getElementType())
415c0c51a9SNicolas Vasilache       .template cast<LLVM::LLVMType>()
425c0c51a9SNicolas Vasilache       .getPointerTo();
435c0c51a9SNicolas Vasilache }
445c0c51a9SNicolas Vasilache 
459826fe5cSAart Bik // Helper to reduce vector type by one rank at front.
469826fe5cSAart Bik static VectorType reducedVectorTypeFront(VectorType tp) {
479826fe5cSAart Bik   assert((tp.getRank() > 1) && "unlowerable vector type");
489826fe5cSAart Bik   return VectorType::get(tp.getShape().drop_front(), tp.getElementType());
499826fe5cSAart Bik }
509826fe5cSAart Bik 
519826fe5cSAart Bik // Helper to reduce vector type by *all* but one rank at back.
529826fe5cSAart Bik static VectorType reducedVectorTypeBack(VectorType tp) {
539826fe5cSAart Bik   assert((tp.getRank() > 1) && "unlowerable vector type");
549826fe5cSAart Bik   return VectorType::get(tp.getShape().take_back(), tp.getElementType());
559826fe5cSAart Bik }
569826fe5cSAart Bik 
571c81adf3SAart Bik // Helper that picks the proper sequence for inserting.
58e62a6956SRiver Riddle static Value insertOne(ConversionPatternRewriter &rewriter,
590f04384dSAlex Zinenko                        LLVMTypeConverter &typeConverter, Location loc,
600f04384dSAlex Zinenko                        Value val1, Value val2, Type llvmType, int64_t rank,
610f04384dSAlex Zinenko                        int64_t pos) {
621c81adf3SAart Bik   if (rank == 1) {
631c81adf3SAart Bik     auto idxType = rewriter.getIndexType();
641c81adf3SAart Bik     auto constant = rewriter.create<LLVM::ConstantOp>(
650f04384dSAlex Zinenko         loc, typeConverter.convertType(idxType),
661c81adf3SAart Bik         rewriter.getIntegerAttr(idxType, pos));
671c81adf3SAart Bik     return rewriter.create<LLVM::InsertElementOp>(loc, llvmType, val1, val2,
681c81adf3SAart Bik                                                   constant);
691c81adf3SAart Bik   }
701c81adf3SAart Bik   return rewriter.create<LLVM::InsertValueOp>(loc, llvmType, val1, val2,
711c81adf3SAart Bik                                               rewriter.getI64ArrayAttr(pos));
721c81adf3SAart Bik }
731c81adf3SAart Bik 
742d515e49SNicolas Vasilache // Helper that picks the proper sequence for inserting.
752d515e49SNicolas Vasilache static Value insertOne(PatternRewriter &rewriter, Location loc, Value from,
762d515e49SNicolas Vasilache                        Value into, int64_t offset) {
772d515e49SNicolas Vasilache   auto vectorType = into.getType().cast<VectorType>();
782d515e49SNicolas Vasilache   if (vectorType.getRank() > 1)
792d515e49SNicolas Vasilache     return rewriter.create<InsertOp>(loc, from, into, offset);
802d515e49SNicolas Vasilache   return rewriter.create<vector::InsertElementOp>(
812d515e49SNicolas Vasilache       loc, vectorType, from, into,
822d515e49SNicolas Vasilache       rewriter.create<ConstantIndexOp>(loc, offset));
832d515e49SNicolas Vasilache }
842d515e49SNicolas Vasilache 
851c81adf3SAart Bik // Helper that picks the proper sequence for extracting.
86e62a6956SRiver Riddle static Value extractOne(ConversionPatternRewriter &rewriter,
870f04384dSAlex Zinenko                         LLVMTypeConverter &typeConverter, Location loc,
880f04384dSAlex Zinenko                         Value val, Type llvmType, int64_t rank, int64_t pos) {
891c81adf3SAart Bik   if (rank == 1) {
901c81adf3SAart Bik     auto idxType = rewriter.getIndexType();
911c81adf3SAart Bik     auto constant = rewriter.create<LLVM::ConstantOp>(
920f04384dSAlex Zinenko         loc, typeConverter.convertType(idxType),
931c81adf3SAart Bik         rewriter.getIntegerAttr(idxType, pos));
941c81adf3SAart Bik     return rewriter.create<LLVM::ExtractElementOp>(loc, llvmType, val,
951c81adf3SAart Bik                                                    constant);
961c81adf3SAart Bik   }
971c81adf3SAart Bik   return rewriter.create<LLVM::ExtractValueOp>(loc, llvmType, val,
981c81adf3SAart Bik                                                rewriter.getI64ArrayAttr(pos));
991c81adf3SAart Bik }
1001c81adf3SAart Bik 
1012d515e49SNicolas Vasilache // Helper that picks the proper sequence for extracting.
1022d515e49SNicolas Vasilache static Value extractOne(PatternRewriter &rewriter, Location loc, Value vector,
1032d515e49SNicolas Vasilache                         int64_t offset) {
1042d515e49SNicolas Vasilache   auto vectorType = vector.getType().cast<VectorType>();
1052d515e49SNicolas Vasilache   if (vectorType.getRank() > 1)
1062d515e49SNicolas Vasilache     return rewriter.create<ExtractOp>(loc, vector, offset);
1072d515e49SNicolas Vasilache   return rewriter.create<vector::ExtractElementOp>(
1082d515e49SNicolas Vasilache       loc, vectorType.getElementType(), vector,
1092d515e49SNicolas Vasilache       rewriter.create<ConstantIndexOp>(loc, offset));
1102d515e49SNicolas Vasilache }
1112d515e49SNicolas Vasilache 
1122d515e49SNicolas Vasilache // Helper that returns a subset of `arrayAttr` as a vector of int64_t.
1132d515e49SNicolas Vasilache // TODO(rriddle): Better support for attribute subtype forwarding + slicing.
1142d515e49SNicolas Vasilache static SmallVector<int64_t, 4> getI64SubArray(ArrayAttr arrayAttr,
1152d515e49SNicolas Vasilache                                               unsigned dropFront = 0,
1162d515e49SNicolas Vasilache                                               unsigned dropBack = 0) {
1172d515e49SNicolas Vasilache   assert(arrayAttr.size() > dropFront + dropBack && "Out of bounds");
1182d515e49SNicolas Vasilache   auto range = arrayAttr.getAsRange<IntegerAttr>();
1192d515e49SNicolas Vasilache   SmallVector<int64_t, 4> res;
1202d515e49SNicolas Vasilache   res.reserve(arrayAttr.size() - dropFront - dropBack);
1212d515e49SNicolas Vasilache   for (auto it = range.begin() + dropFront, eit = range.end() - dropBack;
1222d515e49SNicolas Vasilache        it != eit; ++it)
1232d515e49SNicolas Vasilache     res.push_back((*it).getValue().getSExtValue());
1242d515e49SNicolas Vasilache   return res;
1252d515e49SNicolas Vasilache }
1262d515e49SNicolas Vasilache 
12790c01357SBenjamin Kramer namespace {
128e83b7b99Saartbik 
129870c1fd4SAlex Zinenko class VectorBroadcastOpConversion : public ConvertToLLVMPattern {
130b36aaeafSAart Bik public:
131b36aaeafSAart Bik   explicit VectorBroadcastOpConversion(MLIRContext *context,
132b36aaeafSAart Bik                                        LLVMTypeConverter &typeConverter)
133870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::BroadcastOp::getOperationName(), context,
134b36aaeafSAart Bik                              typeConverter) {}
135b36aaeafSAart Bik 
136b36aaeafSAart Bik   PatternMatchResult
137e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
138b36aaeafSAart Bik                   ConversionPatternRewriter &rewriter) const override {
139b36aaeafSAart Bik     auto broadcastOp = cast<vector::BroadcastOp>(op);
140b36aaeafSAart Bik     VectorType dstVectorType = broadcastOp.getVectorType();
1410f04384dSAlex Zinenko     if (typeConverter.convertType(dstVectorType) == nullptr)
142b36aaeafSAart Bik       return matchFailure();
143b36aaeafSAart Bik     // Rewrite when the full vector type can be lowered (which
144b36aaeafSAart Bik     // implies all 'reduced' types can be lowered too).
1451c81adf3SAart Bik     auto adaptor = vector::BroadcastOpOperandAdaptor(operands);
146b36aaeafSAart Bik     VectorType srcVectorType =
147b36aaeafSAart Bik         broadcastOp.getSourceType().dyn_cast<VectorType>();
148b36aaeafSAart Bik     rewriter.replaceOp(
1491c81adf3SAart Bik         op, expandRanks(adaptor.source(), // source value to be expanded
150b36aaeafSAart Bik                         op->getLoc(),     // location of original broadcast
151b36aaeafSAart Bik                         srcVectorType, dstVectorType, rewriter));
152b36aaeafSAart Bik     return matchSuccess();
153b36aaeafSAart Bik   }
154b36aaeafSAart Bik 
155b36aaeafSAart Bik private:
156b36aaeafSAart Bik   // Expands the given source value over all the ranks, as defined
157b36aaeafSAart Bik   // by the source and destination type (a null source type denotes
158b36aaeafSAart Bik   // expansion from a scalar value into a vector).
159b36aaeafSAart Bik   //
160b36aaeafSAart Bik   // TODO(ajcbik): consider replacing this one-pattern lowering
161b36aaeafSAart Bik   //               with a two-pattern lowering using other vector
162b36aaeafSAart Bik   //               ops once all insert/extract/shuffle operations
163fc817b09SKazuaki Ishizaki   //               are available with lowering implementation.
164b36aaeafSAart Bik   //
165e62a6956SRiver Riddle   Value expandRanks(Value value, Location loc, VectorType srcVectorType,
166b36aaeafSAart Bik                     VectorType dstVectorType,
167b36aaeafSAart Bik                     ConversionPatternRewriter &rewriter) const {
168b36aaeafSAart Bik     assert((dstVectorType != nullptr) && "invalid result type in broadcast");
169b36aaeafSAart Bik     // Determine rank of source and destination.
170b36aaeafSAart Bik     int64_t srcRank = srcVectorType ? srcVectorType.getRank() : 0;
171b36aaeafSAart Bik     int64_t dstRank = dstVectorType.getRank();
172b36aaeafSAart Bik     int64_t curDim = dstVectorType.getDimSize(0);
173b36aaeafSAart Bik     if (srcRank < dstRank)
174b36aaeafSAart Bik       // Duplicate this rank.
175b36aaeafSAart Bik       return duplicateOneRank(value, loc, srcVectorType, dstVectorType, dstRank,
176b36aaeafSAart Bik                               curDim, rewriter);
177b36aaeafSAart Bik     // If all trailing dimensions are the same, the broadcast consists of
178b36aaeafSAart Bik     // simply passing through the source value and we are done. Otherwise,
179b36aaeafSAart Bik     // any non-matching dimension forces a stretch along this rank.
180b36aaeafSAart Bik     assert((srcVectorType != nullptr) && (srcRank > 0) &&
181b36aaeafSAart Bik            (srcRank == dstRank) && "invalid rank in broadcast");
182b36aaeafSAart Bik     for (int64_t r = 0; r < dstRank; r++) {
183b36aaeafSAart Bik       if (srcVectorType.getDimSize(r) != dstVectorType.getDimSize(r)) {
184b36aaeafSAart Bik         return stretchOneRank(value, loc, srcVectorType, dstVectorType, dstRank,
185b36aaeafSAart Bik                               curDim, rewriter);
186b36aaeafSAart Bik       }
187b36aaeafSAart Bik     }
188b36aaeafSAart Bik     return value;
189b36aaeafSAart Bik   }
190b36aaeafSAart Bik 
191b36aaeafSAart Bik   // Picks the best way to duplicate a single rank. For the 1-D case, a
192b36aaeafSAart Bik   // single insert-elt/shuffle is the most efficient expansion. For higher
193b36aaeafSAart Bik   // dimensions, however, we need dim x insert-values on a new broadcast
194b36aaeafSAart Bik   // with one less leading dimension, which will be lowered "recursively"
195b36aaeafSAart Bik   // to matching LLVM IR.
196b36aaeafSAart Bik   // For example:
197b36aaeafSAart Bik   //   v = broadcast s : f32 to vector<4x2xf32>
198b36aaeafSAart Bik   // becomes:
199b36aaeafSAart Bik   //   x = broadcast s : f32 to vector<2xf32>
200b36aaeafSAart Bik   //   v = [x,x,x,x]
201b36aaeafSAart Bik   // becomes:
202b36aaeafSAart Bik   //   x = [s,s]
203b36aaeafSAart Bik   //   v = [x,x,x,x]
204e62a6956SRiver Riddle   Value duplicateOneRank(Value value, Location loc, VectorType srcVectorType,
205e62a6956SRiver Riddle                          VectorType dstVectorType, int64_t rank, int64_t dim,
206b36aaeafSAart Bik                          ConversionPatternRewriter &rewriter) const {
2070f04384dSAlex Zinenko     Type llvmType = typeConverter.convertType(dstVectorType);
208b36aaeafSAart Bik     assert((llvmType != nullptr) && "unlowerable vector type");
209b36aaeafSAart Bik     if (rank == 1) {
210e62a6956SRiver Riddle       Value undef = rewriter.create<LLVM::UndefOp>(loc, llvmType);
2110f04384dSAlex Zinenko       Value expand = insertOne(rewriter, typeConverter, loc, undef, value,
2120f04384dSAlex Zinenko                                llvmType, rank, 0);
213b36aaeafSAart Bik       SmallVector<int32_t, 4> zeroValues(dim, 0);
214b36aaeafSAart Bik       return rewriter.create<LLVM::ShuffleVectorOp>(
215b36aaeafSAart Bik           loc, expand, undef, rewriter.getI32ArrayAttr(zeroValues));
216b36aaeafSAart Bik     }
217e62a6956SRiver Riddle     Value expand = expandRanks(value, loc, srcVectorType,
2189826fe5cSAart Bik                                reducedVectorTypeFront(dstVectorType), rewriter);
219e62a6956SRiver Riddle     Value result = rewriter.create<LLVM::UndefOp>(loc, llvmType);
220b36aaeafSAart Bik     for (int64_t d = 0; d < dim; ++d) {
2210f04384dSAlex Zinenko       result = insertOne(rewriter, typeConverter, loc, result, expand, llvmType,
2220f04384dSAlex Zinenko                          rank, d);
223b36aaeafSAart Bik     }
224b36aaeafSAart Bik     return result;
225b36aaeafSAart Bik   }
226b36aaeafSAart Bik 
227b36aaeafSAart Bik   // Picks the best way to stretch a single rank. For the 1-D case, a
228b36aaeafSAart Bik   // single insert-elt/shuffle is the most efficient expansion when at
229b36aaeafSAart Bik   // a stretch. Otherwise, every dimension needs to be expanded
230b36aaeafSAart Bik   // individually and individually inserted in the resulting vector.
231b36aaeafSAart Bik   // For example:
232b36aaeafSAart Bik   //   v = broadcast w : vector<4x1x2xf32> to vector<4x2x2xf32>
233b36aaeafSAart Bik   // becomes:
234b36aaeafSAart Bik   //   a = broadcast w[0] : vector<1x2xf32> to vector<2x2xf32>
235b36aaeafSAart Bik   //   b = broadcast w[1] : vector<1x2xf32> to vector<2x2xf32>
236b36aaeafSAart Bik   //   c = broadcast w[2] : vector<1x2xf32> to vector<2x2xf32>
237b36aaeafSAart Bik   //   d = broadcast w[3] : vector<1x2xf32> to vector<2x2xf32>
238b36aaeafSAart Bik   //   v = [a,b,c,d]
239b36aaeafSAart Bik   // becomes:
240b36aaeafSAart Bik   //   x = broadcast w[0][0] : vector<2xf32> to vector <2x2xf32>
241b36aaeafSAart Bik   //   y = broadcast w[1][0] : vector<2xf32> to vector <2x2xf32>
242b36aaeafSAart Bik   //   a = [x, y]
243b36aaeafSAart Bik   //   etc.
244e62a6956SRiver Riddle   Value stretchOneRank(Value value, Location loc, VectorType srcVectorType,
245e62a6956SRiver Riddle                        VectorType dstVectorType, int64_t rank, int64_t dim,
246b36aaeafSAart Bik                        ConversionPatternRewriter &rewriter) const {
2470f04384dSAlex Zinenko     Type llvmType = typeConverter.convertType(dstVectorType);
248b36aaeafSAart Bik     assert((llvmType != nullptr) && "unlowerable vector type");
249e62a6956SRiver Riddle     Value result = rewriter.create<LLVM::UndefOp>(loc, llvmType);
250b36aaeafSAart Bik     bool atStretch = dim != srcVectorType.getDimSize(0);
251b36aaeafSAart Bik     if (rank == 1) {
2521c81adf3SAart Bik       assert(atStretch);
2530f04384dSAlex Zinenko       Type redLlvmType =
2540f04384dSAlex Zinenko           typeConverter.convertType(dstVectorType.getElementType());
255e62a6956SRiver Riddle       Value one =
2560f04384dSAlex Zinenko           extractOne(rewriter, typeConverter, loc, value, redLlvmType, rank, 0);
2570f04384dSAlex Zinenko       Value expand = insertOne(rewriter, typeConverter, loc, result, one,
2580f04384dSAlex Zinenko                                llvmType, rank, 0);
259b36aaeafSAart Bik       SmallVector<int32_t, 4> zeroValues(dim, 0);
260b36aaeafSAart Bik       return rewriter.create<LLVM::ShuffleVectorOp>(
261b36aaeafSAart Bik           loc, expand, result, rewriter.getI32ArrayAttr(zeroValues));
262b36aaeafSAart Bik     }
2639826fe5cSAart Bik     VectorType redSrcType = reducedVectorTypeFront(srcVectorType);
2649826fe5cSAart Bik     VectorType redDstType = reducedVectorTypeFront(dstVectorType);
2650f04384dSAlex Zinenko     Type redLlvmType = typeConverter.convertType(redSrcType);
266b36aaeafSAart Bik     for (int64_t d = 0; d < dim; ++d) {
267b36aaeafSAart Bik       int64_t pos = atStretch ? 0 : d;
2680f04384dSAlex Zinenko       Value one = extractOne(rewriter, typeConverter, loc, value, redLlvmType,
2690f04384dSAlex Zinenko                              rank, pos);
270e62a6956SRiver Riddle       Value expand = expandRanks(one, loc, redSrcType, redDstType, rewriter);
2710f04384dSAlex Zinenko       result = insertOne(rewriter, typeConverter, loc, result, expand, llvmType,
2720f04384dSAlex Zinenko                          rank, d);
273b36aaeafSAart Bik     }
274b36aaeafSAart Bik     return result;
275b36aaeafSAart Bik   }
2761c81adf3SAart Bik };
277b36aaeafSAart Bik 
27863b683a8SNicolas Vasilache /// Conversion pattern for a vector.matrix_multiply.
27963b683a8SNicolas Vasilache /// This is lowered directly to the proper llvm.intr.matrix.multiply.
28063b683a8SNicolas Vasilache class VectorMatmulOpConversion : public ConvertToLLVMPattern {
28163b683a8SNicolas Vasilache public:
28263b683a8SNicolas Vasilache   explicit VectorMatmulOpConversion(MLIRContext *context,
28363b683a8SNicolas Vasilache                                     LLVMTypeConverter &typeConverter)
28463b683a8SNicolas Vasilache       : ConvertToLLVMPattern(vector::MatmulOp::getOperationName(), context,
28563b683a8SNicolas Vasilache                              typeConverter) {}
28663b683a8SNicolas Vasilache 
28763b683a8SNicolas Vasilache   PatternMatchResult
28863b683a8SNicolas Vasilache   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
28963b683a8SNicolas Vasilache                   ConversionPatternRewriter &rewriter) const override {
29063b683a8SNicolas Vasilache     auto matmulOp = cast<vector::MatmulOp>(op);
29163b683a8SNicolas Vasilache     auto adaptor = vector::MatmulOpOperandAdaptor(operands);
29263b683a8SNicolas Vasilache     rewriter.replaceOpWithNewOp<LLVM::MatrixMultiplyOp>(
29363b683a8SNicolas Vasilache         op, typeConverter.convertType(matmulOp.res().getType()), adaptor.lhs(),
29463b683a8SNicolas Vasilache         adaptor.rhs(), matmulOp.lhs_rows(), matmulOp.lhs_columns(),
29563b683a8SNicolas Vasilache         matmulOp.rhs_columns());
29663b683a8SNicolas Vasilache     return matchSuccess();
29763b683a8SNicolas Vasilache   }
29863b683a8SNicolas Vasilache };
29963b683a8SNicolas Vasilache 
300870c1fd4SAlex Zinenko class VectorReductionOpConversion : public ConvertToLLVMPattern {
301e83b7b99Saartbik public:
302e83b7b99Saartbik   explicit VectorReductionOpConversion(MLIRContext *context,
303e83b7b99Saartbik                                        LLVMTypeConverter &typeConverter)
304870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::ReductionOp::getOperationName(), context,
305e83b7b99Saartbik                              typeConverter) {}
306e83b7b99Saartbik 
307e83b7b99Saartbik   PatternMatchResult
308e83b7b99Saartbik   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
309e83b7b99Saartbik                   ConversionPatternRewriter &rewriter) const override {
310e83b7b99Saartbik     auto reductionOp = cast<vector::ReductionOp>(op);
311e83b7b99Saartbik     auto kind = reductionOp.kind();
312e83b7b99Saartbik     Type eltType = reductionOp.dest().getType();
3130f04384dSAlex Zinenko     Type llvmType = typeConverter.convertType(eltType);
31435b68527SLei Zhang     if (eltType.isSignlessInteger(32) || eltType.isSignlessInteger(64)) {
315e83b7b99Saartbik       // Integer reductions: add/mul/min/max/and/or/xor.
316e83b7b99Saartbik       if (kind == "add")
317e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_add>(
318e83b7b99Saartbik             op, llvmType, operands[0]);
319e83b7b99Saartbik       else if (kind == "mul")
320e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_mul>(
321e83b7b99Saartbik             op, llvmType, operands[0]);
322e83b7b99Saartbik       else if (kind == "min")
323e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_smin>(
324e83b7b99Saartbik             op, llvmType, operands[0]);
325e83b7b99Saartbik       else if (kind == "max")
326e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_smax>(
327e83b7b99Saartbik             op, llvmType, operands[0]);
328e83b7b99Saartbik       else if (kind == "and")
329e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_and>(
330e83b7b99Saartbik             op, llvmType, operands[0]);
331e83b7b99Saartbik       else if (kind == "or")
332e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_or>(
333e83b7b99Saartbik             op, llvmType, operands[0]);
334e83b7b99Saartbik       else if (kind == "xor")
335e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_xor>(
336e83b7b99Saartbik             op, llvmType, operands[0]);
337e83b7b99Saartbik       else
338e83b7b99Saartbik         return matchFailure();
339e83b7b99Saartbik       return matchSuccess();
340e83b7b99Saartbik 
341e83b7b99Saartbik     } else if (eltType.isF32() || eltType.isF64()) {
342e83b7b99Saartbik       // Floating-point reductions: add/mul/min/max
343e83b7b99Saartbik       if (kind == "add") {
3440d924700Saartbik         // Optional accumulator (or zero).
3450d924700Saartbik         Value acc = operands.size() > 1 ? operands[1]
3460d924700Saartbik                                         : rewriter.create<LLVM::ConstantOp>(
3470d924700Saartbik                                               op->getLoc(), llvmType,
3480d924700Saartbik                                               rewriter.getZeroAttr(eltType));
349e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_v2_fadd>(
3500d924700Saartbik             op, llvmType, acc, operands[0]);
351e83b7b99Saartbik       } else if (kind == "mul") {
3520d924700Saartbik         // Optional accumulator (or one).
3530d924700Saartbik         Value acc = operands.size() > 1
3540d924700Saartbik                         ? operands[1]
3550d924700Saartbik                         : rewriter.create<LLVM::ConstantOp>(
3560d924700Saartbik                               op->getLoc(), llvmType,
3570d924700Saartbik                               rewriter.getFloatAttr(eltType, 1.0));
358e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_v2_fmul>(
3590d924700Saartbik             op, llvmType, acc, operands[0]);
360e83b7b99Saartbik       } else if (kind == "min")
361e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_fmin>(
362e83b7b99Saartbik             op, llvmType, operands[0]);
363e83b7b99Saartbik       else if (kind == "max")
364e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_fmax>(
365e83b7b99Saartbik             op, llvmType, operands[0]);
366e83b7b99Saartbik       else
367e83b7b99Saartbik         return matchFailure();
368e83b7b99Saartbik       return matchSuccess();
369e83b7b99Saartbik     }
370e83b7b99Saartbik     return matchFailure();
371e83b7b99Saartbik   }
372e83b7b99Saartbik };
373e83b7b99Saartbik 
374870c1fd4SAlex Zinenko class VectorShuffleOpConversion : public ConvertToLLVMPattern {
3751c81adf3SAart Bik public:
3761c81adf3SAart Bik   explicit VectorShuffleOpConversion(MLIRContext *context,
3771c81adf3SAart Bik                                      LLVMTypeConverter &typeConverter)
378870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::ShuffleOp::getOperationName(), context,
3791c81adf3SAart Bik                              typeConverter) {}
3801c81adf3SAart Bik 
3811c81adf3SAart Bik   PatternMatchResult
382e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
3831c81adf3SAart Bik                   ConversionPatternRewriter &rewriter) const override {
3841c81adf3SAart Bik     auto loc = op->getLoc();
3851c81adf3SAart Bik     auto adaptor = vector::ShuffleOpOperandAdaptor(operands);
3861c81adf3SAart Bik     auto shuffleOp = cast<vector::ShuffleOp>(op);
3871c81adf3SAart Bik     auto v1Type = shuffleOp.getV1VectorType();
3881c81adf3SAart Bik     auto v2Type = shuffleOp.getV2VectorType();
3891c81adf3SAart Bik     auto vectorType = shuffleOp.getVectorType();
3900f04384dSAlex Zinenko     Type llvmType = typeConverter.convertType(vectorType);
3911c81adf3SAart Bik     auto maskArrayAttr = shuffleOp.mask();
3921c81adf3SAart Bik 
3931c81adf3SAart Bik     // Bail if result type cannot be lowered.
3941c81adf3SAart Bik     if (!llvmType)
3951c81adf3SAart Bik       return matchFailure();
3961c81adf3SAart Bik 
3971c81adf3SAart Bik     // Get rank and dimension sizes.
3981c81adf3SAart Bik     int64_t rank = vectorType.getRank();
3991c81adf3SAart Bik     assert(v1Type.getRank() == rank);
4001c81adf3SAart Bik     assert(v2Type.getRank() == rank);
4011c81adf3SAart Bik     int64_t v1Dim = v1Type.getDimSize(0);
4021c81adf3SAart Bik 
4031c81adf3SAart Bik     // For rank 1, where both operands have *exactly* the same vector type,
4041c81adf3SAart Bik     // there is direct shuffle support in LLVM. Use it!
4051c81adf3SAart Bik     if (rank == 1 && v1Type == v2Type) {
406e62a6956SRiver Riddle       Value shuffle = rewriter.create<LLVM::ShuffleVectorOp>(
4071c81adf3SAart Bik           loc, adaptor.v1(), adaptor.v2(), maskArrayAttr);
4081c81adf3SAart Bik       rewriter.replaceOp(op, shuffle);
4091c81adf3SAart Bik       return matchSuccess();
410b36aaeafSAart Bik     }
411b36aaeafSAart Bik 
4121c81adf3SAart Bik     // For all other cases, insert the individual values individually.
413e62a6956SRiver Riddle     Value insert = rewriter.create<LLVM::UndefOp>(loc, llvmType);
4141c81adf3SAart Bik     int64_t insPos = 0;
4151c81adf3SAart Bik     for (auto en : llvm::enumerate(maskArrayAttr)) {
4161c81adf3SAart Bik       int64_t extPos = en.value().cast<IntegerAttr>().getInt();
417e62a6956SRiver Riddle       Value value = adaptor.v1();
4181c81adf3SAart Bik       if (extPos >= v1Dim) {
4191c81adf3SAart Bik         extPos -= v1Dim;
4201c81adf3SAart Bik         value = adaptor.v2();
421b36aaeafSAart Bik       }
4220f04384dSAlex Zinenko       Value extract = extractOne(rewriter, typeConverter, loc, value, llvmType,
4230f04384dSAlex Zinenko                                  rank, extPos);
4240f04384dSAlex Zinenko       insert = insertOne(rewriter, typeConverter, loc, insert, extract,
4250f04384dSAlex Zinenko                          llvmType, rank, insPos++);
4261c81adf3SAart Bik     }
4271c81adf3SAart Bik     rewriter.replaceOp(op, insert);
4281c81adf3SAart Bik     return matchSuccess();
429b36aaeafSAart Bik   }
430b36aaeafSAart Bik };
431b36aaeafSAart Bik 
432870c1fd4SAlex Zinenko class VectorExtractElementOpConversion : public ConvertToLLVMPattern {
433cd5dab8aSAart Bik public:
434cd5dab8aSAart Bik   explicit VectorExtractElementOpConversion(MLIRContext *context,
435cd5dab8aSAart Bik                                             LLVMTypeConverter &typeConverter)
436870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::ExtractElementOp::getOperationName(),
437870c1fd4SAlex Zinenko                              context, typeConverter) {}
438cd5dab8aSAart Bik 
439cd5dab8aSAart Bik   PatternMatchResult
440e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
441cd5dab8aSAart Bik                   ConversionPatternRewriter &rewriter) const override {
442cd5dab8aSAart Bik     auto adaptor = vector::ExtractElementOpOperandAdaptor(operands);
443cd5dab8aSAart Bik     auto extractEltOp = cast<vector::ExtractElementOp>(op);
444cd5dab8aSAart Bik     auto vectorType = extractEltOp.getVectorType();
4450f04384dSAlex Zinenko     auto llvmType = typeConverter.convertType(vectorType.getElementType());
446cd5dab8aSAart Bik 
447cd5dab8aSAart Bik     // Bail if result type cannot be lowered.
448cd5dab8aSAart Bik     if (!llvmType)
449cd5dab8aSAart Bik       return matchFailure();
450cd5dab8aSAart Bik 
451cd5dab8aSAart Bik     rewriter.replaceOpWithNewOp<LLVM::ExtractElementOp>(
452cd5dab8aSAart Bik         op, llvmType, adaptor.vector(), adaptor.position());
453cd5dab8aSAart Bik     return matchSuccess();
454cd5dab8aSAart Bik   }
455cd5dab8aSAart Bik };
456cd5dab8aSAart Bik 
457870c1fd4SAlex Zinenko class VectorExtractOpConversion : public ConvertToLLVMPattern {
4585c0c51a9SNicolas Vasilache public:
4599826fe5cSAart Bik   explicit VectorExtractOpConversion(MLIRContext *context,
4605c0c51a9SNicolas Vasilache                                      LLVMTypeConverter &typeConverter)
461870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::ExtractOp::getOperationName(), context,
4625c0c51a9SNicolas Vasilache                              typeConverter) {}
4635c0c51a9SNicolas Vasilache 
4645c0c51a9SNicolas Vasilache   PatternMatchResult
465e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
4665c0c51a9SNicolas Vasilache                   ConversionPatternRewriter &rewriter) const override {
4675c0c51a9SNicolas Vasilache     auto loc = op->getLoc();
468d37f2725SAart Bik     auto adaptor = vector::ExtractOpOperandAdaptor(operands);
469d37f2725SAart Bik     auto extractOp = cast<vector::ExtractOp>(op);
4709826fe5cSAart Bik     auto vectorType = extractOp.getVectorType();
4712bdf33ccSRiver Riddle     auto resultType = extractOp.getResult().getType();
4720f04384dSAlex Zinenko     auto llvmResultType = typeConverter.convertType(resultType);
4735c0c51a9SNicolas Vasilache     auto positionArrayAttr = extractOp.position();
4749826fe5cSAart Bik 
4759826fe5cSAart Bik     // Bail if result type cannot be lowered.
4769826fe5cSAart Bik     if (!llvmResultType)
4779826fe5cSAart Bik       return matchFailure();
4789826fe5cSAart Bik 
4795c0c51a9SNicolas Vasilache     // One-shot extraction of vector from array (only requires extractvalue).
4805c0c51a9SNicolas Vasilache     if (resultType.isa<VectorType>()) {
481e62a6956SRiver Riddle       Value extracted = rewriter.create<LLVM::ExtractValueOp>(
4825c0c51a9SNicolas Vasilache           loc, llvmResultType, adaptor.vector(), positionArrayAttr);
4835c0c51a9SNicolas Vasilache       rewriter.replaceOp(op, extracted);
4845c0c51a9SNicolas Vasilache       return matchSuccess();
4855c0c51a9SNicolas Vasilache     }
4865c0c51a9SNicolas Vasilache 
4879826fe5cSAart Bik     // Potential extraction of 1-D vector from array.
4885c0c51a9SNicolas Vasilache     auto *context = op->getContext();
489e62a6956SRiver Riddle     Value extracted = adaptor.vector();
4905c0c51a9SNicolas Vasilache     auto positionAttrs = positionArrayAttr.getValue();
4915c0c51a9SNicolas Vasilache     if (positionAttrs.size() > 1) {
4929826fe5cSAart Bik       auto oneDVectorType = reducedVectorTypeBack(vectorType);
4935c0c51a9SNicolas Vasilache       auto nMinusOnePositionAttrs =
4945c0c51a9SNicolas Vasilache           ArrayAttr::get(positionAttrs.drop_back(), context);
4955c0c51a9SNicolas Vasilache       extracted = rewriter.create<LLVM::ExtractValueOp>(
4960f04384dSAlex Zinenko           loc, typeConverter.convertType(oneDVectorType), extracted,
4975c0c51a9SNicolas Vasilache           nMinusOnePositionAttrs);
4985c0c51a9SNicolas Vasilache     }
4995c0c51a9SNicolas Vasilache 
5005c0c51a9SNicolas Vasilache     // Remaining extraction of element from 1-D LLVM vector
5015c0c51a9SNicolas Vasilache     auto position = positionAttrs.back().cast<IntegerAttr>();
5020f04384dSAlex Zinenko     auto i64Type = LLVM::LLVMType::getInt64Ty(typeConverter.getDialect());
5031d47564aSAart Bik     auto constant = rewriter.create<LLVM::ConstantOp>(loc, i64Type, position);
5045c0c51a9SNicolas Vasilache     extracted =
5055c0c51a9SNicolas Vasilache         rewriter.create<LLVM::ExtractElementOp>(loc, extracted, constant);
5065c0c51a9SNicolas Vasilache     rewriter.replaceOp(op, extracted);
5075c0c51a9SNicolas Vasilache 
5085c0c51a9SNicolas Vasilache     return matchSuccess();
5095c0c51a9SNicolas Vasilache   }
5105c0c51a9SNicolas Vasilache };
5115c0c51a9SNicolas Vasilache 
512681f929fSNicolas Vasilache /// Conversion pattern that turns a vector.fma on a 1-D vector
513681f929fSNicolas Vasilache /// into an llvm.intr.fmuladd. This is a trivial 1-1 conversion.
514681f929fSNicolas Vasilache /// This does not match vectors of n >= 2 rank.
515681f929fSNicolas Vasilache ///
516681f929fSNicolas Vasilache /// Example:
517681f929fSNicolas Vasilache /// ```
518681f929fSNicolas Vasilache ///  vector.fma %a, %a, %a : vector<8xf32>
519681f929fSNicolas Vasilache /// ```
520681f929fSNicolas Vasilache /// is converted to:
521681f929fSNicolas Vasilache /// ```
522681f929fSNicolas Vasilache ///  llvm.intr.fma %va, %va, %va:
523681f929fSNicolas Vasilache ///    (!llvm<"<8 x float>">, !llvm<"<8 x float>">, !llvm<"<8 x float>">)
524681f929fSNicolas Vasilache ///    -> !llvm<"<8 x float>">
525681f929fSNicolas Vasilache /// ```
526870c1fd4SAlex Zinenko class VectorFMAOp1DConversion : public ConvertToLLVMPattern {
527681f929fSNicolas Vasilache public:
528681f929fSNicolas Vasilache   explicit VectorFMAOp1DConversion(MLIRContext *context,
529681f929fSNicolas Vasilache                                    LLVMTypeConverter &typeConverter)
530870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::FMAOp::getOperationName(), context,
531681f929fSNicolas Vasilache                              typeConverter) {}
532681f929fSNicolas Vasilache 
533681f929fSNicolas Vasilache   PatternMatchResult
534681f929fSNicolas Vasilache   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
535681f929fSNicolas Vasilache                   ConversionPatternRewriter &rewriter) const override {
536681f929fSNicolas Vasilache     auto adaptor = vector::FMAOpOperandAdaptor(operands);
537681f929fSNicolas Vasilache     vector::FMAOp fmaOp = cast<vector::FMAOp>(op);
538681f929fSNicolas Vasilache     VectorType vType = fmaOp.getVectorType();
539681f929fSNicolas Vasilache     if (vType.getRank() != 1)
540681f929fSNicolas Vasilache       return matchFailure();
541681f929fSNicolas Vasilache     rewriter.replaceOpWithNewOp<LLVM::FMAOp>(op, adaptor.lhs(), adaptor.rhs(),
542681f929fSNicolas Vasilache                                              adaptor.acc());
543681f929fSNicolas Vasilache     return matchSuccess();
544681f929fSNicolas Vasilache   }
545681f929fSNicolas Vasilache };
546681f929fSNicolas Vasilache 
547870c1fd4SAlex Zinenko class VectorInsertElementOpConversion : public ConvertToLLVMPattern {
548cd5dab8aSAart Bik public:
549cd5dab8aSAart Bik   explicit VectorInsertElementOpConversion(MLIRContext *context,
550cd5dab8aSAart Bik                                            LLVMTypeConverter &typeConverter)
551870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::InsertElementOp::getOperationName(),
552870c1fd4SAlex Zinenko                              context, typeConverter) {}
553cd5dab8aSAart Bik 
554cd5dab8aSAart Bik   PatternMatchResult
555e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
556cd5dab8aSAart Bik                   ConversionPatternRewriter &rewriter) const override {
557cd5dab8aSAart Bik     auto adaptor = vector::InsertElementOpOperandAdaptor(operands);
558cd5dab8aSAart Bik     auto insertEltOp = cast<vector::InsertElementOp>(op);
559cd5dab8aSAart Bik     auto vectorType = insertEltOp.getDestVectorType();
5600f04384dSAlex Zinenko     auto llvmType = typeConverter.convertType(vectorType);
561cd5dab8aSAart Bik 
562cd5dab8aSAart Bik     // Bail if result type cannot be lowered.
563cd5dab8aSAart Bik     if (!llvmType)
564cd5dab8aSAart Bik       return matchFailure();
565cd5dab8aSAart Bik 
566cd5dab8aSAart Bik     rewriter.replaceOpWithNewOp<LLVM::InsertElementOp>(
567cd5dab8aSAart Bik         op, llvmType, adaptor.dest(), adaptor.source(), adaptor.position());
568cd5dab8aSAart Bik     return matchSuccess();
569cd5dab8aSAart Bik   }
570cd5dab8aSAart Bik };
571cd5dab8aSAart Bik 
572870c1fd4SAlex Zinenko class VectorInsertOpConversion : public ConvertToLLVMPattern {
5739826fe5cSAart Bik public:
5749826fe5cSAart Bik   explicit VectorInsertOpConversion(MLIRContext *context,
5759826fe5cSAart Bik                                     LLVMTypeConverter &typeConverter)
576870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::InsertOp::getOperationName(), context,
5779826fe5cSAart Bik                              typeConverter) {}
5789826fe5cSAart Bik 
5799826fe5cSAart Bik   PatternMatchResult
580e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
5819826fe5cSAart Bik                   ConversionPatternRewriter &rewriter) const override {
5829826fe5cSAart Bik     auto loc = op->getLoc();
5839826fe5cSAart Bik     auto adaptor = vector::InsertOpOperandAdaptor(operands);
5849826fe5cSAart Bik     auto insertOp = cast<vector::InsertOp>(op);
5859826fe5cSAart Bik     auto sourceType = insertOp.getSourceType();
5869826fe5cSAart Bik     auto destVectorType = insertOp.getDestVectorType();
5870f04384dSAlex Zinenko     auto llvmResultType = typeConverter.convertType(destVectorType);
5889826fe5cSAart Bik     auto positionArrayAttr = insertOp.position();
5899826fe5cSAart Bik 
5909826fe5cSAart Bik     // Bail if result type cannot be lowered.
5919826fe5cSAart Bik     if (!llvmResultType)
5929826fe5cSAart Bik       return matchFailure();
5939826fe5cSAart Bik 
5949826fe5cSAart Bik     // One-shot insertion of a vector into an array (only requires insertvalue).
5959826fe5cSAart Bik     if (sourceType.isa<VectorType>()) {
596e62a6956SRiver Riddle       Value inserted = rewriter.create<LLVM::InsertValueOp>(
5979826fe5cSAart Bik           loc, llvmResultType, adaptor.dest(), adaptor.source(),
5989826fe5cSAart Bik           positionArrayAttr);
5999826fe5cSAart Bik       rewriter.replaceOp(op, inserted);
6009826fe5cSAart Bik       return matchSuccess();
6019826fe5cSAart Bik     }
6029826fe5cSAart Bik 
6039826fe5cSAart Bik     // Potential extraction of 1-D vector from array.
6049826fe5cSAart Bik     auto *context = op->getContext();
605e62a6956SRiver Riddle     Value extracted = adaptor.dest();
6069826fe5cSAart Bik     auto positionAttrs = positionArrayAttr.getValue();
6079826fe5cSAart Bik     auto position = positionAttrs.back().cast<IntegerAttr>();
6089826fe5cSAart Bik     auto oneDVectorType = destVectorType;
6099826fe5cSAart Bik     if (positionAttrs.size() > 1) {
6109826fe5cSAart Bik       oneDVectorType = reducedVectorTypeBack(destVectorType);
6119826fe5cSAart Bik       auto nMinusOnePositionAttrs =
6129826fe5cSAart Bik           ArrayAttr::get(positionAttrs.drop_back(), context);
6139826fe5cSAart Bik       extracted = rewriter.create<LLVM::ExtractValueOp>(
6140f04384dSAlex Zinenko           loc, typeConverter.convertType(oneDVectorType), extracted,
6159826fe5cSAart Bik           nMinusOnePositionAttrs);
6169826fe5cSAart Bik     }
6179826fe5cSAart Bik 
6189826fe5cSAart Bik     // Insertion of an element into a 1-D LLVM vector.
6190f04384dSAlex Zinenko     auto i64Type = LLVM::LLVMType::getInt64Ty(typeConverter.getDialect());
6201d47564aSAart Bik     auto constant = rewriter.create<LLVM::ConstantOp>(loc, i64Type, position);
621e62a6956SRiver Riddle     Value inserted = rewriter.create<LLVM::InsertElementOp>(
6220f04384dSAlex Zinenko         loc, typeConverter.convertType(oneDVectorType), extracted,
6230f04384dSAlex Zinenko         adaptor.source(), constant);
6249826fe5cSAart Bik 
6259826fe5cSAart Bik     // Potential insertion of resulting 1-D vector into array.
6269826fe5cSAart Bik     if (positionAttrs.size() > 1) {
6279826fe5cSAart Bik       auto nMinusOnePositionAttrs =
6289826fe5cSAart Bik           ArrayAttr::get(positionAttrs.drop_back(), context);
6299826fe5cSAart Bik       inserted = rewriter.create<LLVM::InsertValueOp>(loc, llvmResultType,
6309826fe5cSAart Bik                                                       adaptor.dest(), inserted,
6319826fe5cSAart Bik                                                       nMinusOnePositionAttrs);
6329826fe5cSAart Bik     }
6339826fe5cSAart Bik 
6349826fe5cSAart Bik     rewriter.replaceOp(op, inserted);
6359826fe5cSAart Bik     return matchSuccess();
6369826fe5cSAart Bik   }
6379826fe5cSAart Bik };
6389826fe5cSAart Bik 
639681f929fSNicolas Vasilache /// Rank reducing rewrite for n-D FMA into (n-1)-D FMA where n > 1.
640681f929fSNicolas Vasilache ///
641681f929fSNicolas Vasilache /// Example:
642681f929fSNicolas Vasilache /// ```
643681f929fSNicolas Vasilache ///   %d = vector.fma %a, %b, %c : vector<2x4xf32>
644681f929fSNicolas Vasilache /// ```
645681f929fSNicolas Vasilache /// is rewritten into:
646681f929fSNicolas Vasilache /// ```
647681f929fSNicolas Vasilache ///  %r = splat %f0: vector<2x4xf32>
648681f929fSNicolas Vasilache ///  %va = vector.extractvalue %a[0] : vector<2x4xf32>
649681f929fSNicolas Vasilache ///  %vb = vector.extractvalue %b[0] : vector<2x4xf32>
650681f929fSNicolas Vasilache ///  %vc = vector.extractvalue %c[0] : vector<2x4xf32>
651681f929fSNicolas Vasilache ///  %vd = vector.fma %va, %vb, %vc : vector<4xf32>
652681f929fSNicolas Vasilache ///  %r2 = vector.insertvalue %vd, %r[0] : vector<4xf32> into vector<2x4xf32>
653681f929fSNicolas Vasilache ///  %va2 = vector.extractvalue %a2[1] : vector<2x4xf32>
654681f929fSNicolas Vasilache ///  %vb2 = vector.extractvalue %b2[1] : vector<2x4xf32>
655681f929fSNicolas Vasilache ///  %vc2 = vector.extractvalue %c2[1] : vector<2x4xf32>
656681f929fSNicolas Vasilache ///  %vd2 = vector.fma %va2, %vb2, %vc2 : vector<4xf32>
657681f929fSNicolas Vasilache ///  %r3 = vector.insertvalue %vd2, %r2[1] : vector<4xf32> into vector<2x4xf32>
658681f929fSNicolas Vasilache ///  // %r3 holds the final value.
659681f929fSNicolas Vasilache /// ```
660681f929fSNicolas Vasilache class VectorFMAOpNDRewritePattern : public OpRewritePattern<FMAOp> {
661681f929fSNicolas Vasilache public:
662681f929fSNicolas Vasilache   using OpRewritePattern<FMAOp>::OpRewritePattern;
663681f929fSNicolas Vasilache 
664681f929fSNicolas Vasilache   PatternMatchResult matchAndRewrite(FMAOp op,
665681f929fSNicolas Vasilache                                      PatternRewriter &rewriter) const override {
666681f929fSNicolas Vasilache     auto vType = op.getVectorType();
667681f929fSNicolas Vasilache     if (vType.getRank() < 2)
668681f929fSNicolas Vasilache       return matchFailure();
669681f929fSNicolas Vasilache 
670681f929fSNicolas Vasilache     auto loc = op.getLoc();
671681f929fSNicolas Vasilache     auto elemType = vType.getElementType();
672681f929fSNicolas Vasilache     Value zero = rewriter.create<ConstantOp>(loc, elemType,
673681f929fSNicolas Vasilache                                              rewriter.getZeroAttr(elemType));
674681f929fSNicolas Vasilache     Value desc = rewriter.create<SplatOp>(loc, vType, zero);
675681f929fSNicolas Vasilache     for (int64_t i = 0, e = vType.getShape().front(); i != e; ++i) {
676681f929fSNicolas Vasilache       Value extrLHS = rewriter.create<ExtractOp>(loc, op.lhs(), i);
677681f929fSNicolas Vasilache       Value extrRHS = rewriter.create<ExtractOp>(loc, op.rhs(), i);
678681f929fSNicolas Vasilache       Value extrACC = rewriter.create<ExtractOp>(loc, op.acc(), i);
679681f929fSNicolas Vasilache       Value fma = rewriter.create<FMAOp>(loc, extrLHS, extrRHS, extrACC);
680681f929fSNicolas Vasilache       desc = rewriter.create<InsertOp>(loc, fma, desc, i);
681681f929fSNicolas Vasilache     }
682681f929fSNicolas Vasilache     rewriter.replaceOp(op, desc);
683681f929fSNicolas Vasilache     return matchSuccess();
684681f929fSNicolas Vasilache   }
685681f929fSNicolas Vasilache };
686681f929fSNicolas Vasilache 
6872d515e49SNicolas Vasilache // When ranks are different, InsertStridedSlice needs to extract a properly
6882d515e49SNicolas Vasilache // ranked vector from the destination vector into which to insert. This pattern
6892d515e49SNicolas Vasilache // only takes care of this part and forwards the rest of the conversion to
6902d515e49SNicolas Vasilache // another pattern that converts InsertStridedSlice for operands of the same
6912d515e49SNicolas Vasilache // rank.
6922d515e49SNicolas Vasilache //
6932d515e49SNicolas Vasilache // RewritePattern for InsertStridedSliceOp where source and destination vectors
6942d515e49SNicolas Vasilache // have different ranks. In this case:
6952d515e49SNicolas Vasilache //   1. the proper subvector is extracted from the destination vector
6962d515e49SNicolas Vasilache //   2. a new InsertStridedSlice op is created to insert the source in the
6972d515e49SNicolas Vasilache //   destination subvector
6982d515e49SNicolas Vasilache //   3. the destination subvector is inserted back in the proper place
6992d515e49SNicolas Vasilache //   4. the op is replaced by the result of step 3.
7002d515e49SNicolas Vasilache // The new InsertStridedSlice from step 2. will be picked up by a
7012d515e49SNicolas Vasilache // `VectorInsertStridedSliceOpSameRankRewritePattern`.
7022d515e49SNicolas Vasilache class VectorInsertStridedSliceOpDifferentRankRewritePattern
7032d515e49SNicolas Vasilache     : public OpRewritePattern<InsertStridedSliceOp> {
7042d515e49SNicolas Vasilache public:
7052d515e49SNicolas Vasilache   using OpRewritePattern<InsertStridedSliceOp>::OpRewritePattern;
7062d515e49SNicolas Vasilache 
7072d515e49SNicolas Vasilache   PatternMatchResult matchAndRewrite(InsertStridedSliceOp op,
7082d515e49SNicolas Vasilache                                      PatternRewriter &rewriter) const override {
7092d515e49SNicolas Vasilache     auto srcType = op.getSourceVectorType();
7102d515e49SNicolas Vasilache     auto dstType = op.getDestVectorType();
7112d515e49SNicolas Vasilache 
7122d515e49SNicolas Vasilache     if (op.offsets().getValue().empty())
7132d515e49SNicolas Vasilache       return matchFailure();
7142d515e49SNicolas Vasilache 
7152d515e49SNicolas Vasilache     auto loc = op.getLoc();
7162d515e49SNicolas Vasilache     int64_t rankDiff = dstType.getRank() - srcType.getRank();
7172d515e49SNicolas Vasilache     assert(rankDiff >= 0);
7182d515e49SNicolas Vasilache     if (rankDiff == 0)
7192d515e49SNicolas Vasilache       return matchFailure();
7202d515e49SNicolas Vasilache 
7212d515e49SNicolas Vasilache     int64_t rankRest = dstType.getRank() - rankDiff;
7222d515e49SNicolas Vasilache     // Extract / insert the subvector of matching rank and InsertStridedSlice
7232d515e49SNicolas Vasilache     // on it.
7242d515e49SNicolas Vasilache     Value extracted =
7252d515e49SNicolas Vasilache         rewriter.create<ExtractOp>(loc, op.dest(),
7262d515e49SNicolas Vasilache                                    getI64SubArray(op.offsets(), /*dropFront=*/0,
7272d515e49SNicolas Vasilache                                                   /*dropFront=*/rankRest));
7282d515e49SNicolas Vasilache     // A different pattern will kick in for InsertStridedSlice with matching
7292d515e49SNicolas Vasilache     // ranks.
7302d515e49SNicolas Vasilache     auto stridedSliceInnerOp = rewriter.create<InsertStridedSliceOp>(
7312d515e49SNicolas Vasilache         loc, op.source(), extracted,
7322d515e49SNicolas Vasilache         getI64SubArray(op.offsets(), /*dropFront=*/rankDiff),
733c8fc76a9Saartbik         getI64SubArray(op.strides(), /*dropFront=*/0));
7342d515e49SNicolas Vasilache     rewriter.replaceOpWithNewOp<InsertOp>(
7352d515e49SNicolas Vasilache         op, stridedSliceInnerOp.getResult(), op.dest(),
7362d515e49SNicolas Vasilache         getI64SubArray(op.offsets(), /*dropFront=*/0,
7372d515e49SNicolas Vasilache                        /*dropFront=*/rankRest));
7382d515e49SNicolas Vasilache     return matchSuccess();
7392d515e49SNicolas Vasilache   }
7402d515e49SNicolas Vasilache };
7412d515e49SNicolas Vasilache 
7422d515e49SNicolas Vasilache // RewritePattern for InsertStridedSliceOp where source and destination vectors
7432d515e49SNicolas Vasilache // have the same rank. In this case, we reduce
7442d515e49SNicolas Vasilache //   1. the proper subvector is extracted from the destination vector
7452d515e49SNicolas Vasilache //   2. a new InsertStridedSlice op is created to insert the source in the
7462d515e49SNicolas Vasilache //   destination subvector
7472d515e49SNicolas Vasilache //   3. the destination subvector is inserted back in the proper place
7482d515e49SNicolas Vasilache //   4. the op is replaced by the result of step 3.
7492d515e49SNicolas Vasilache // The new InsertStridedSlice from step 2. will be picked up by a
7502d515e49SNicolas Vasilache // `VectorInsertStridedSliceOpSameRankRewritePattern`.
7512d515e49SNicolas Vasilache class VectorInsertStridedSliceOpSameRankRewritePattern
7522d515e49SNicolas Vasilache     : public OpRewritePattern<InsertStridedSliceOp> {
7532d515e49SNicolas Vasilache public:
7542d515e49SNicolas Vasilache   using OpRewritePattern<InsertStridedSliceOp>::OpRewritePattern;
7552d515e49SNicolas Vasilache 
7562d515e49SNicolas Vasilache   PatternMatchResult matchAndRewrite(InsertStridedSliceOp op,
7572d515e49SNicolas Vasilache                                      PatternRewriter &rewriter) const override {
7582d515e49SNicolas Vasilache     auto srcType = op.getSourceVectorType();
7592d515e49SNicolas Vasilache     auto dstType = op.getDestVectorType();
7602d515e49SNicolas Vasilache 
7612d515e49SNicolas Vasilache     if (op.offsets().getValue().empty())
7622d515e49SNicolas Vasilache       return matchFailure();
7632d515e49SNicolas Vasilache 
7642d515e49SNicolas Vasilache     int64_t rankDiff = dstType.getRank() - srcType.getRank();
7652d515e49SNicolas Vasilache     assert(rankDiff >= 0);
7662d515e49SNicolas Vasilache     if (rankDiff != 0)
7672d515e49SNicolas Vasilache       return matchFailure();
7682d515e49SNicolas Vasilache 
7692d515e49SNicolas Vasilache     if (srcType == dstType) {
7702d515e49SNicolas Vasilache       rewriter.replaceOp(op, op.source());
7712d515e49SNicolas Vasilache       return matchSuccess();
7722d515e49SNicolas Vasilache     }
7732d515e49SNicolas Vasilache 
7742d515e49SNicolas Vasilache     int64_t offset =
7752d515e49SNicolas Vasilache         op.offsets().getValue().front().cast<IntegerAttr>().getInt();
7762d515e49SNicolas Vasilache     int64_t size = srcType.getShape().front();
7772d515e49SNicolas Vasilache     int64_t stride =
7782d515e49SNicolas Vasilache         op.strides().getValue().front().cast<IntegerAttr>().getInt();
7792d515e49SNicolas Vasilache 
7802d515e49SNicolas Vasilache     auto loc = op.getLoc();
7812d515e49SNicolas Vasilache     Value res = op.dest();
7822d515e49SNicolas Vasilache     // For each slice of the source vector along the most major dimension.
7832d515e49SNicolas Vasilache     for (int64_t off = offset, e = offset + size * stride, idx = 0; off < e;
7842d515e49SNicolas Vasilache          off += stride, ++idx) {
7852d515e49SNicolas Vasilache       // 1. extract the proper subvector (or element) from source
7862d515e49SNicolas Vasilache       Value extractedSource = extractOne(rewriter, loc, op.source(), idx);
7872d515e49SNicolas Vasilache       if (extractedSource.getType().isa<VectorType>()) {
7882d515e49SNicolas Vasilache         // 2. If we have a vector, extract the proper subvector from destination
7892d515e49SNicolas Vasilache         // Otherwise we are at the element level and no need to recurse.
7902d515e49SNicolas Vasilache         Value extractedDest = extractOne(rewriter, loc, op.dest(), off);
7912d515e49SNicolas Vasilache         // 3. Reduce the problem to lowering a new InsertStridedSlice op with
7922d515e49SNicolas Vasilache         // smaller rank.
7932d515e49SNicolas Vasilache         InsertStridedSliceOp insertStridedSliceOp =
7942d515e49SNicolas Vasilache             rewriter.create<InsertStridedSliceOp>(
7952d515e49SNicolas Vasilache                 loc, extractedSource, extractedDest,
7962d515e49SNicolas Vasilache                 getI64SubArray(op.offsets(), /* dropFront=*/1),
7972d515e49SNicolas Vasilache                 getI64SubArray(op.strides(), /* dropFront=*/1));
7982d515e49SNicolas Vasilache         // Call matchAndRewrite recursively from within the pattern. This
7992d515e49SNicolas Vasilache         // circumvents the current limitation that a given pattern cannot
8002d515e49SNicolas Vasilache         // be called multiple times by the PatternRewrite infrastructure (to
8012d515e49SNicolas Vasilache         // avoid infinite recursion, but in this case, infinite recursion
8022d515e49SNicolas Vasilache         // cannot happen because the rank is strictly decreasing).
8032d515e49SNicolas Vasilache         // TODO(rriddle, nicolasvasilache) Implement something like a hook for
8042d515e49SNicolas Vasilache         // a potential function that must decrease and allow the same pattern
8052d515e49SNicolas Vasilache         // multiple times.
8062d515e49SNicolas Vasilache         auto success = matchAndRewrite(insertStridedSliceOp, rewriter);
8072d515e49SNicolas Vasilache         (void)success;
8082d515e49SNicolas Vasilache         assert(success && "Unexpected failure");
8092d515e49SNicolas Vasilache         extractedSource = insertStridedSliceOp;
8102d515e49SNicolas Vasilache       }
8112d515e49SNicolas Vasilache       // 4. Insert the extractedSource into the res vector.
8122d515e49SNicolas Vasilache       res = insertOne(rewriter, loc, extractedSource, res, off);
8132d515e49SNicolas Vasilache     }
8142d515e49SNicolas Vasilache 
8152d515e49SNicolas Vasilache     rewriter.replaceOp(op, res);
8162d515e49SNicolas Vasilache     return matchSuccess();
8172d515e49SNicolas Vasilache   }
8182d515e49SNicolas Vasilache };
8192d515e49SNicolas Vasilache 
820870c1fd4SAlex Zinenko class VectorTypeCastOpConversion : public ConvertToLLVMPattern {
8215c0c51a9SNicolas Vasilache public:
8225c0c51a9SNicolas Vasilache   explicit VectorTypeCastOpConversion(MLIRContext *context,
8235c0c51a9SNicolas Vasilache                                       LLVMTypeConverter &typeConverter)
824870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::TypeCastOp::getOperationName(), context,
8255c0c51a9SNicolas Vasilache                              typeConverter) {}
8265c0c51a9SNicolas Vasilache 
8275c0c51a9SNicolas Vasilache   PatternMatchResult
828e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
8295c0c51a9SNicolas Vasilache                   ConversionPatternRewriter &rewriter) const override {
8305c0c51a9SNicolas Vasilache     auto loc = op->getLoc();
8315c0c51a9SNicolas Vasilache     vector::TypeCastOp castOp = cast<vector::TypeCastOp>(op);
8325c0c51a9SNicolas Vasilache     MemRefType sourceMemRefType =
8332bdf33ccSRiver Riddle         castOp.getOperand().getType().cast<MemRefType>();
8345c0c51a9SNicolas Vasilache     MemRefType targetMemRefType =
8352bdf33ccSRiver Riddle         castOp.getResult().getType().cast<MemRefType>();
8365c0c51a9SNicolas Vasilache 
8375c0c51a9SNicolas Vasilache     // Only static shape casts supported atm.
8385c0c51a9SNicolas Vasilache     if (!sourceMemRefType.hasStaticShape() ||
8395c0c51a9SNicolas Vasilache         !targetMemRefType.hasStaticShape())
8405c0c51a9SNicolas Vasilache       return matchFailure();
8415c0c51a9SNicolas Vasilache 
8425c0c51a9SNicolas Vasilache     auto llvmSourceDescriptorTy =
8432bdf33ccSRiver Riddle         operands[0].getType().dyn_cast<LLVM::LLVMType>();
8445c0c51a9SNicolas Vasilache     if (!llvmSourceDescriptorTy || !llvmSourceDescriptorTy.isStructTy())
8455c0c51a9SNicolas Vasilache       return matchFailure();
8465c0c51a9SNicolas Vasilache     MemRefDescriptor sourceMemRef(operands[0]);
8475c0c51a9SNicolas Vasilache 
8480f04384dSAlex Zinenko     auto llvmTargetDescriptorTy = typeConverter.convertType(targetMemRefType)
8495c0c51a9SNicolas Vasilache                                       .dyn_cast_or_null<LLVM::LLVMType>();
8505c0c51a9SNicolas Vasilache     if (!llvmTargetDescriptorTy || !llvmTargetDescriptorTy.isStructTy())
8515c0c51a9SNicolas Vasilache       return matchFailure();
8525c0c51a9SNicolas Vasilache 
8535c0c51a9SNicolas Vasilache     int64_t offset;
8545c0c51a9SNicolas Vasilache     SmallVector<int64_t, 4> strides;
8555c0c51a9SNicolas Vasilache     auto successStrides =
8565c0c51a9SNicolas Vasilache         getStridesAndOffset(sourceMemRefType, strides, offset);
8575c0c51a9SNicolas Vasilache     bool isContiguous = (strides.back() == 1);
8585c0c51a9SNicolas Vasilache     if (isContiguous) {
8595c0c51a9SNicolas Vasilache       auto sizes = sourceMemRefType.getShape();
8605c0c51a9SNicolas Vasilache       for (int index = 0, e = strides.size() - 2; index < e; ++index) {
8615c0c51a9SNicolas Vasilache         if (strides[index] != strides[index + 1] * sizes[index + 1]) {
8625c0c51a9SNicolas Vasilache           isContiguous = false;
8635c0c51a9SNicolas Vasilache           break;
8645c0c51a9SNicolas Vasilache         }
8655c0c51a9SNicolas Vasilache       }
8665c0c51a9SNicolas Vasilache     }
8675c0c51a9SNicolas Vasilache     // Only contiguous source tensors supported atm.
8685c0c51a9SNicolas Vasilache     if (failed(successStrides) || !isContiguous)
8695c0c51a9SNicolas Vasilache       return matchFailure();
8705c0c51a9SNicolas Vasilache 
8710f04384dSAlex Zinenko     auto int64Ty = LLVM::LLVMType::getInt64Ty(typeConverter.getDialect());
8725c0c51a9SNicolas Vasilache 
8735c0c51a9SNicolas Vasilache     // Create descriptor.
8745c0c51a9SNicolas Vasilache     auto desc = MemRefDescriptor::undef(rewriter, loc, llvmTargetDescriptorTy);
8755c0c51a9SNicolas Vasilache     Type llvmTargetElementTy = desc.getElementType();
8765c0c51a9SNicolas Vasilache     // Set allocated ptr.
877e62a6956SRiver Riddle     Value allocated = sourceMemRef.allocatedPtr(rewriter, loc);
8785c0c51a9SNicolas Vasilache     allocated =
8795c0c51a9SNicolas Vasilache         rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, allocated);
8805c0c51a9SNicolas Vasilache     desc.setAllocatedPtr(rewriter, loc, allocated);
8815c0c51a9SNicolas Vasilache     // Set aligned ptr.
882e62a6956SRiver Riddle     Value ptr = sourceMemRef.alignedPtr(rewriter, loc);
8835c0c51a9SNicolas Vasilache     ptr = rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, ptr);
8845c0c51a9SNicolas Vasilache     desc.setAlignedPtr(rewriter, loc, ptr);
8855c0c51a9SNicolas Vasilache     // Fill offset 0.
8865c0c51a9SNicolas Vasilache     auto attr = rewriter.getIntegerAttr(rewriter.getIndexType(), 0);
8875c0c51a9SNicolas Vasilache     auto zero = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, attr);
8885c0c51a9SNicolas Vasilache     desc.setOffset(rewriter, loc, zero);
8895c0c51a9SNicolas Vasilache 
8905c0c51a9SNicolas Vasilache     // Fill size and stride descriptors in memref.
8915c0c51a9SNicolas Vasilache     for (auto indexedSize : llvm::enumerate(targetMemRefType.getShape())) {
8925c0c51a9SNicolas Vasilache       int64_t index = indexedSize.index();
8935c0c51a9SNicolas Vasilache       auto sizeAttr =
8945c0c51a9SNicolas Vasilache           rewriter.getIntegerAttr(rewriter.getIndexType(), indexedSize.value());
8955c0c51a9SNicolas Vasilache       auto size = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, sizeAttr);
8965c0c51a9SNicolas Vasilache       desc.setSize(rewriter, loc, index, size);
8975c0c51a9SNicolas Vasilache       auto strideAttr =
8985c0c51a9SNicolas Vasilache           rewriter.getIntegerAttr(rewriter.getIndexType(), strides[index]);
8995c0c51a9SNicolas Vasilache       auto stride = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, strideAttr);
9005c0c51a9SNicolas Vasilache       desc.setStride(rewriter, loc, index, stride);
9015c0c51a9SNicolas Vasilache     }
9025c0c51a9SNicolas Vasilache 
9035c0c51a9SNicolas Vasilache     rewriter.replaceOp(op, {desc});
9045c0c51a9SNicolas Vasilache     return matchSuccess();
9055c0c51a9SNicolas Vasilache   }
9065c0c51a9SNicolas Vasilache };
9075c0c51a9SNicolas Vasilache 
908870c1fd4SAlex Zinenko class VectorPrintOpConversion : public ConvertToLLVMPattern {
909d9b500d3SAart Bik public:
910d9b500d3SAart Bik   explicit VectorPrintOpConversion(MLIRContext *context,
911d9b500d3SAart Bik                                    LLVMTypeConverter &typeConverter)
912870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::PrintOp::getOperationName(), context,
913d9b500d3SAart Bik                              typeConverter) {}
914d9b500d3SAart Bik 
915d9b500d3SAart Bik   // Proof-of-concept lowering implementation that relies on a small
916d9b500d3SAart Bik   // runtime support library, which only needs to provide a few
917d9b500d3SAart Bik   // printing methods (single value for all data types, opening/closing
918d9b500d3SAart Bik   // bracket, comma, newline). The lowering fully unrolls a vector
919d9b500d3SAart Bik   // in terms of these elementary printing operations. The advantage
920d9b500d3SAart Bik   // of this approach is that the library can remain unaware of all
921d9b500d3SAart Bik   // low-level implementation details of vectors while still supporting
922d9b500d3SAart Bik   // output of any shaped and dimensioned vector. Due to full unrolling,
923d9b500d3SAart Bik   // this approach is less suited for very large vectors though.
924d9b500d3SAart Bik   //
925d9b500d3SAart Bik   // TODO(ajcbik): rely solely on libc in future? something else?
926d9b500d3SAart Bik   //
927d9b500d3SAart Bik   PatternMatchResult
928e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
929d9b500d3SAart Bik                   ConversionPatternRewriter &rewriter) const override {
930d9b500d3SAart Bik     auto printOp = cast<vector::PrintOp>(op);
931d9b500d3SAart Bik     auto adaptor = vector::PrintOpOperandAdaptor(operands);
932d9b500d3SAart Bik     Type printType = printOp.getPrintType();
933d9b500d3SAart Bik 
9340f04384dSAlex Zinenko     if (typeConverter.convertType(printType) == nullptr)
935d9b500d3SAart Bik       return matchFailure();
936d9b500d3SAart Bik 
937d9b500d3SAart Bik     // Make sure element type has runtime support (currently just Float/Double).
938d9b500d3SAart Bik     VectorType vectorType = printType.dyn_cast<VectorType>();
939d9b500d3SAart Bik     Type eltType = vectorType ? vectorType.getElementType() : printType;
940d9b500d3SAart Bik     int64_t rank = vectorType ? vectorType.getRank() : 0;
941d9b500d3SAart Bik     Operation *printer;
94235b68527SLei Zhang     if (eltType.isSignlessInteger(32))
943e52414b1Saartbik       printer = getPrintI32(op);
94435b68527SLei Zhang     else if (eltType.isSignlessInteger(64))
945e52414b1Saartbik       printer = getPrintI64(op);
946e52414b1Saartbik     else if (eltType.isF32())
947d9b500d3SAart Bik       printer = getPrintFloat(op);
948d9b500d3SAart Bik     else if (eltType.isF64())
949d9b500d3SAart Bik       printer = getPrintDouble(op);
950d9b500d3SAart Bik     else
951d9b500d3SAart Bik       return matchFailure();
952d9b500d3SAart Bik 
953d9b500d3SAart Bik     // Unroll vector into elementary print calls.
954d9b500d3SAart Bik     emitRanks(rewriter, op, adaptor.source(), vectorType, printer, rank);
955d9b500d3SAart Bik     emitCall(rewriter, op->getLoc(), getPrintNewline(op));
956d9b500d3SAart Bik     rewriter.eraseOp(op);
957d9b500d3SAart Bik     return matchSuccess();
958d9b500d3SAart Bik   }
959d9b500d3SAart Bik 
960d9b500d3SAart Bik private:
961d9b500d3SAart Bik   void emitRanks(ConversionPatternRewriter &rewriter, Operation *op,
962e62a6956SRiver Riddle                  Value value, VectorType vectorType, Operation *printer,
963d9b500d3SAart Bik                  int64_t rank) const {
964d9b500d3SAart Bik     Location loc = op->getLoc();
965d9b500d3SAart Bik     if (rank == 0) {
966d9b500d3SAart Bik       emitCall(rewriter, loc, printer, value);
967d9b500d3SAart Bik       return;
968d9b500d3SAart Bik     }
969d9b500d3SAart Bik 
970d9b500d3SAart Bik     emitCall(rewriter, loc, getPrintOpen(op));
971d9b500d3SAart Bik     Operation *printComma = getPrintComma(op);
972d9b500d3SAart Bik     int64_t dim = vectorType.getDimSize(0);
973d9b500d3SAart Bik     for (int64_t d = 0; d < dim; ++d) {
974d9b500d3SAart Bik       auto reducedType =
975d9b500d3SAart Bik           rank > 1 ? reducedVectorTypeFront(vectorType) : nullptr;
9760f04384dSAlex Zinenko       auto llvmType = typeConverter.convertType(
977d9b500d3SAart Bik           rank > 1 ? reducedType : vectorType.getElementType());
978e62a6956SRiver Riddle       Value nestedVal =
9790f04384dSAlex Zinenko           extractOne(rewriter, typeConverter, loc, value, llvmType, rank, d);
980d9b500d3SAart Bik       emitRanks(rewriter, op, nestedVal, reducedType, printer, rank - 1);
981d9b500d3SAart Bik       if (d != dim - 1)
982d9b500d3SAart Bik         emitCall(rewriter, loc, printComma);
983d9b500d3SAart Bik     }
984d9b500d3SAart Bik     emitCall(rewriter, loc, getPrintClose(op));
985d9b500d3SAart Bik   }
986d9b500d3SAart Bik 
987d9b500d3SAart Bik   // Helper to emit a call.
988d9b500d3SAart Bik   static void emitCall(ConversionPatternRewriter &rewriter, Location loc,
989d9b500d3SAart Bik                        Operation *ref, ValueRange params = ValueRange()) {
990d9b500d3SAart Bik     rewriter.create<LLVM::CallOp>(loc, ArrayRef<Type>{},
991d9b500d3SAart Bik                                   rewriter.getSymbolRefAttr(ref), params);
992d9b500d3SAart Bik   }
993d9b500d3SAart Bik 
994d9b500d3SAart Bik   // Helper for printer method declaration (first hit) and lookup.
995d9b500d3SAart Bik   static Operation *getPrint(Operation *op, LLVM::LLVMDialect *dialect,
996d9b500d3SAart Bik                              StringRef name, ArrayRef<LLVM::LLVMType> params) {
997d9b500d3SAart Bik     auto module = op->getParentOfType<ModuleOp>();
998d9b500d3SAart Bik     auto func = module.lookupSymbol<LLVM::LLVMFuncOp>(name);
999d9b500d3SAart Bik     if (func)
1000d9b500d3SAart Bik       return func;
1001d9b500d3SAart Bik     OpBuilder moduleBuilder(module.getBodyRegion());
1002d9b500d3SAart Bik     return moduleBuilder.create<LLVM::LLVMFuncOp>(
1003d9b500d3SAart Bik         op->getLoc(), name,
1004d9b500d3SAart Bik         LLVM::LLVMType::getFunctionTy(LLVM::LLVMType::getVoidTy(dialect),
1005d9b500d3SAart Bik                                       params, /*isVarArg=*/false));
1006d9b500d3SAart Bik   }
1007d9b500d3SAart Bik 
1008d9b500d3SAart Bik   // Helpers for method names.
1009e52414b1Saartbik   Operation *getPrintI32(Operation *op) const {
10100f04384dSAlex Zinenko     LLVM::LLVMDialect *dialect = typeConverter.getDialect();
1011e52414b1Saartbik     return getPrint(op, dialect, "print_i32",
1012e52414b1Saartbik                     LLVM::LLVMType::getInt32Ty(dialect));
1013e52414b1Saartbik   }
1014e52414b1Saartbik   Operation *getPrintI64(Operation *op) const {
10150f04384dSAlex Zinenko     LLVM::LLVMDialect *dialect = typeConverter.getDialect();
1016e52414b1Saartbik     return getPrint(op, dialect, "print_i64",
1017e52414b1Saartbik                     LLVM::LLVMType::getInt64Ty(dialect));
1018e52414b1Saartbik   }
1019d9b500d3SAart Bik   Operation *getPrintFloat(Operation *op) const {
10200f04384dSAlex Zinenko     LLVM::LLVMDialect *dialect = typeConverter.getDialect();
1021d9b500d3SAart Bik     return getPrint(op, dialect, "print_f32",
1022d9b500d3SAart Bik                     LLVM::LLVMType::getFloatTy(dialect));
1023d9b500d3SAart Bik   }
1024d9b500d3SAart Bik   Operation *getPrintDouble(Operation *op) const {
10250f04384dSAlex Zinenko     LLVM::LLVMDialect *dialect = typeConverter.getDialect();
1026d9b500d3SAart Bik     return getPrint(op, dialect, "print_f64",
1027d9b500d3SAart Bik                     LLVM::LLVMType::getDoubleTy(dialect));
1028d9b500d3SAart Bik   }
1029d9b500d3SAart Bik   Operation *getPrintOpen(Operation *op) const {
10300f04384dSAlex Zinenko     return getPrint(op, typeConverter.getDialect(), "print_open", {});
1031d9b500d3SAart Bik   }
1032d9b500d3SAart Bik   Operation *getPrintClose(Operation *op) const {
10330f04384dSAlex Zinenko     return getPrint(op, typeConverter.getDialect(), "print_close", {});
1034d9b500d3SAart Bik   }
1035d9b500d3SAart Bik   Operation *getPrintComma(Operation *op) const {
10360f04384dSAlex Zinenko     return getPrint(op, typeConverter.getDialect(), "print_comma", {});
1037d9b500d3SAart Bik   }
1038d9b500d3SAart Bik   Operation *getPrintNewline(Operation *op) const {
10390f04384dSAlex Zinenko     return getPrint(op, typeConverter.getDialect(), "print_newline", {});
1040d9b500d3SAart Bik   }
1041d9b500d3SAart Bik };
1042d9b500d3SAart Bik 
104365678d93SNicolas Vasilache /// Progressive lowering of StridedSliceOp to either:
104465678d93SNicolas Vasilache ///   1. extractelement + insertelement for the 1-D case
104565678d93SNicolas Vasilache ///   2. extract + optional strided_slice + insert for the n-D case.
10462d515e49SNicolas Vasilache class VectorStridedSliceOpConversion : public OpRewritePattern<StridedSliceOp> {
104765678d93SNicolas Vasilache public:
104865678d93SNicolas Vasilache   using OpRewritePattern<StridedSliceOp>::OpRewritePattern;
104965678d93SNicolas Vasilache 
105065678d93SNicolas Vasilache   PatternMatchResult matchAndRewrite(StridedSliceOp op,
105165678d93SNicolas Vasilache                                      PatternRewriter &rewriter) const override {
105265678d93SNicolas Vasilache     auto dstType = op.getResult().getType().cast<VectorType>();
105365678d93SNicolas Vasilache 
105465678d93SNicolas Vasilache     assert(!op.offsets().getValue().empty() && "Unexpected empty offsets");
105565678d93SNicolas Vasilache 
105665678d93SNicolas Vasilache     int64_t offset =
105765678d93SNicolas Vasilache         op.offsets().getValue().front().cast<IntegerAttr>().getInt();
105865678d93SNicolas Vasilache     int64_t size = op.sizes().getValue().front().cast<IntegerAttr>().getInt();
105965678d93SNicolas Vasilache     int64_t stride =
106065678d93SNicolas Vasilache         op.strides().getValue().front().cast<IntegerAttr>().getInt();
106165678d93SNicolas Vasilache 
106265678d93SNicolas Vasilache     auto loc = op.getLoc();
106365678d93SNicolas Vasilache     auto elemType = dstType.getElementType();
106435b68527SLei Zhang     assert(elemType.isSignlessIntOrIndexOrFloat());
106565678d93SNicolas Vasilache     Value zero = rewriter.create<ConstantOp>(loc, elemType,
106665678d93SNicolas Vasilache                                              rewriter.getZeroAttr(elemType));
106765678d93SNicolas Vasilache     Value res = rewriter.create<SplatOp>(loc, dstType, zero);
106865678d93SNicolas Vasilache     for (int64_t off = offset, e = offset + size * stride, idx = 0; off < e;
106965678d93SNicolas Vasilache          off += stride, ++idx) {
107065678d93SNicolas Vasilache       Value extracted = extractOne(rewriter, loc, op.vector(), off);
107165678d93SNicolas Vasilache       if (op.offsets().getValue().size() > 1) {
107265678d93SNicolas Vasilache         StridedSliceOp stridedSliceOp = rewriter.create<StridedSliceOp>(
107365678d93SNicolas Vasilache             loc, extracted, getI64SubArray(op.offsets(), /* dropFront=*/1),
107465678d93SNicolas Vasilache             getI64SubArray(op.sizes(), /* dropFront=*/1),
107565678d93SNicolas Vasilache             getI64SubArray(op.strides(), /* dropFront=*/1));
107665678d93SNicolas Vasilache         // Call matchAndRewrite recursively from within the pattern. This
107765678d93SNicolas Vasilache         // circumvents the current limitation that a given pattern cannot
107865678d93SNicolas Vasilache         // be called multiple times by the PatternRewrite infrastructure (to
107965678d93SNicolas Vasilache         // avoid infinite recursion, but in this case, infinite recursion
108065678d93SNicolas Vasilache         // cannot happen because the rank is strictly decreasing).
108165678d93SNicolas Vasilache         // TODO(rriddle, nicolasvasilache) Implement something like a hook for
108265678d93SNicolas Vasilache         // a potential function that must decrease and allow the same pattern
108365678d93SNicolas Vasilache         // multiple times.
108465678d93SNicolas Vasilache         auto success = matchAndRewrite(stridedSliceOp, rewriter);
108565678d93SNicolas Vasilache         (void)success;
108665678d93SNicolas Vasilache         assert(success && "Unexpected failure");
108765678d93SNicolas Vasilache         extracted = stridedSliceOp;
108865678d93SNicolas Vasilache       }
108965678d93SNicolas Vasilache       res = insertOne(rewriter, loc, extracted, res, idx);
109065678d93SNicolas Vasilache     }
109165678d93SNicolas Vasilache     rewriter.replaceOp(op, {res});
109265678d93SNicolas Vasilache     return matchSuccess();
109365678d93SNicolas Vasilache   }
109465678d93SNicolas Vasilache };
109565678d93SNicolas Vasilache 
1096df186507SBenjamin Kramer } // namespace
1097df186507SBenjamin Kramer 
10985c0c51a9SNicolas Vasilache /// Populate the given list with patterns that convert from Vector to LLVM.
10995c0c51a9SNicolas Vasilache void mlir::populateVectorToLLVMConversionPatterns(
11005c0c51a9SNicolas Vasilache     LLVMTypeConverter &converter, OwningRewritePatternList &patterns) {
110165678d93SNicolas Vasilache   MLIRContext *ctx = converter.getDialect()->getContext();
1102681f929fSNicolas Vasilache   patterns.insert<VectorFMAOpNDRewritePattern,
1103681f929fSNicolas Vasilache                   VectorInsertStridedSliceOpDifferentRankRewritePattern,
11042d515e49SNicolas Vasilache                   VectorInsertStridedSliceOpSameRankRewritePattern,
11052d515e49SNicolas Vasilache                   VectorStridedSliceOpConversion>(ctx);
1106e83b7b99Saartbik   patterns.insert<VectorBroadcastOpConversion, VectorReductionOpConversion,
11070d924700Saartbik                   VectorShuffleOpConversion, VectorExtractElementOpConversion,
11080d924700Saartbik                   VectorExtractOpConversion, VectorFMAOp1DConversion,
11090d924700Saartbik                   VectorInsertElementOpConversion, VectorInsertOpConversion,
1110a213ece3Saartbik                   VectorTypeCastOpConversion, VectorPrintOpConversion>(
1111a213ece3Saartbik       ctx, converter);
11125c0c51a9SNicolas Vasilache }
11135c0c51a9SNicolas Vasilache 
111463b683a8SNicolas Vasilache void mlir::populateVectorToLLVMMatrixConversionPatterns(
111563b683a8SNicolas Vasilache     LLVMTypeConverter &converter, OwningRewritePatternList &patterns) {
111663b683a8SNicolas Vasilache   MLIRContext *ctx = converter.getDialect()->getContext();
111763b683a8SNicolas Vasilache   patterns.insert<VectorMatmulOpConversion>(ctx, converter);
111863b683a8SNicolas Vasilache }
111963b683a8SNicolas Vasilache 
11205c0c51a9SNicolas Vasilache namespace {
11215c0c51a9SNicolas Vasilache struct LowerVectorToLLVMPass : public ModulePass<LowerVectorToLLVMPass> {
11225c0c51a9SNicolas Vasilache   void runOnModule() override;
11235c0c51a9SNicolas Vasilache };
11245c0c51a9SNicolas Vasilache } // namespace
11255c0c51a9SNicolas Vasilache 
11265c0c51a9SNicolas Vasilache void LowerVectorToLLVMPass::runOnModule() {
1127078776a6Saartbik   // Perform progressive lowering of operations on slices and
1128b21c7999Saartbik   // all contraction operations. Also applies folding and DCE.
1129459cf6e5Saartbik   {
11305c0c51a9SNicolas Vasilache     OwningRewritePatternList patterns;
1131459cf6e5Saartbik     populateVectorSlicesLoweringPatterns(patterns, &getContext());
1132b21c7999Saartbik     populateVectorContractLoweringPatterns(patterns, &getContext());
1133459cf6e5Saartbik     applyPatternsGreedily(getModule(), patterns);
1134459cf6e5Saartbik   }
1135459cf6e5Saartbik 
1136459cf6e5Saartbik   // Convert to the LLVM IR dialect.
11375c0c51a9SNicolas Vasilache   LLVMTypeConverter converter(&getContext());
1138459cf6e5Saartbik   OwningRewritePatternList patterns;
113963b683a8SNicolas Vasilache   populateVectorToLLVMMatrixConversionPatterns(converter, patterns);
11405c0c51a9SNicolas Vasilache   populateVectorToLLVMConversionPatterns(converter, patterns);
1141*bbf3ef85SNicolas Vasilache   populateVectorToLLVMMatrixConversionPatterns(converter, patterns);
11425c0c51a9SNicolas Vasilache   populateStdToLLVMConversionPatterns(converter, patterns);
11435c0c51a9SNicolas Vasilache 
11442a00ae39STim Shen   LLVMConversionTarget target(getContext());
11455c0c51a9SNicolas Vasilache   target.addDynamicallyLegalOp<FuncOp>(
11465c0c51a9SNicolas Vasilache       [&](FuncOp op) { return converter.isSignatureLegal(op.getType()); });
11475c0c51a9SNicolas Vasilache   if (failed(
11485c0c51a9SNicolas Vasilache           applyPartialConversion(getModule(), target, patterns, &converter))) {
11495c0c51a9SNicolas Vasilache     signalPassFailure();
11505c0c51a9SNicolas Vasilache   }
11515c0c51a9SNicolas Vasilache }
11525c0c51a9SNicolas Vasilache 
11535c0c51a9SNicolas Vasilache OpPassBase<ModuleOp> *mlir::createLowerVectorToLLVMPass() {
11545c0c51a9SNicolas Vasilache   return new LowerVectorToLLVMPass();
11555c0c51a9SNicolas Vasilache }
11565c0c51a9SNicolas Vasilache 
11575c0c51a9SNicolas Vasilache static PassRegistration<LowerVectorToLLVMPass>
11585c0c51a9SNicolas Vasilache     pass("convert-vector-to-llvm",
11595c0c51a9SNicolas Vasilache          "Lower the operations from the vector dialect into the LLVM dialect");
1160