15c0c51a9SNicolas Vasilache //===- VectorToLLVM.cpp - Conversion from Vector to the LLVM dialect ------===//
25c0c51a9SNicolas Vasilache //
356222a06SMehdi Amini // Part of the MLIR 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"
105c0c51a9SNicolas Vasilache #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVM.h"
115c0c51a9SNicolas Vasilache #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h"
125c0c51a9SNicolas Vasilache #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
1365678d93SNicolas Vasilache #include "mlir/Dialect/StandardOps/Ops.h"
145c0c51a9SNicolas Vasilache #include "mlir/Dialect/VectorOps/VectorOps.h"
155c0c51a9SNicolas Vasilache #include "mlir/IR/Attributes.h"
165c0c51a9SNicolas Vasilache #include "mlir/IR/Builders.h"
175c0c51a9SNicolas Vasilache #include "mlir/IR/MLIRContext.h"
185c0c51a9SNicolas Vasilache #include "mlir/IR/Module.h"
195c0c51a9SNicolas Vasilache #include "mlir/IR/Operation.h"
205c0c51a9SNicolas Vasilache #include "mlir/IR/PatternMatch.h"
215c0c51a9SNicolas Vasilache #include "mlir/IR/StandardTypes.h"
225c0c51a9SNicolas Vasilache #include "mlir/IR/Types.h"
235c0c51a9SNicolas Vasilache #include "mlir/Pass/Pass.h"
245c0c51a9SNicolas Vasilache #include "mlir/Pass/PassManager.h"
255c0c51a9SNicolas Vasilache #include "mlir/Transforms/DialectConversion.h"
265c0c51a9SNicolas Vasilache #include "mlir/Transforms/Passes.h"
275c0c51a9SNicolas Vasilache 
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,
395c0c51a9SNicolas Vasilache                                           LLVMTypeConverter &lowering) {
405c0c51a9SNicolas Vasilache   return lowering.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,
59e62a6956SRiver Riddle                        LLVMTypeConverter &lowering, Location loc, Value val1,
60e62a6956SRiver Riddle                        Value val2, Type llvmType, int64_t rank, int64_t pos) {
611c81adf3SAart Bik   if (rank == 1) {
621c81adf3SAart Bik     auto idxType = rewriter.getIndexType();
631c81adf3SAart Bik     auto constant = rewriter.create<LLVM::ConstantOp>(
641c81adf3SAart Bik         loc, lowering.convertType(idxType),
651c81adf3SAart Bik         rewriter.getIntegerAttr(idxType, pos));
661c81adf3SAart Bik     return rewriter.create<LLVM::InsertElementOp>(loc, llvmType, val1, val2,
671c81adf3SAart Bik                                                   constant);
681c81adf3SAart Bik   }
691c81adf3SAart Bik   return rewriter.create<LLVM::InsertValueOp>(loc, llvmType, val1, val2,
701c81adf3SAart Bik                                               rewriter.getI64ArrayAttr(pos));
711c81adf3SAart Bik }
721c81adf3SAart Bik 
732d515e49SNicolas Vasilache // Helper that picks the proper sequence for inserting.
742d515e49SNicolas Vasilache static Value insertOne(PatternRewriter &rewriter, Location loc, Value from,
752d515e49SNicolas Vasilache                        Value into, int64_t offset) {
762d515e49SNicolas Vasilache   auto vectorType = into.getType().cast<VectorType>();
772d515e49SNicolas Vasilache   if (vectorType.getRank() > 1)
782d515e49SNicolas Vasilache     return rewriter.create<InsertOp>(loc, from, into, offset);
792d515e49SNicolas Vasilache   return rewriter.create<vector::InsertElementOp>(
802d515e49SNicolas Vasilache       loc, vectorType, from, into,
812d515e49SNicolas Vasilache       rewriter.create<ConstantIndexOp>(loc, offset));
822d515e49SNicolas Vasilache }
832d515e49SNicolas Vasilache 
841c81adf3SAart Bik // Helper that picks the proper sequence for extracting.
85e62a6956SRiver Riddle static Value extractOne(ConversionPatternRewriter &rewriter,
86e62a6956SRiver Riddle                         LLVMTypeConverter &lowering, Location loc, Value val,
87e62a6956SRiver Riddle                         Type llvmType, int64_t rank, int64_t pos) {
881c81adf3SAart Bik   if (rank == 1) {
891c81adf3SAart Bik     auto idxType = rewriter.getIndexType();
901c81adf3SAart Bik     auto constant = rewriter.create<LLVM::ConstantOp>(
911c81adf3SAart Bik         loc, lowering.convertType(idxType),
921c81adf3SAart Bik         rewriter.getIntegerAttr(idxType, pos));
931c81adf3SAart Bik     return rewriter.create<LLVM::ExtractElementOp>(loc, llvmType, val,
941c81adf3SAart Bik                                                    constant);
951c81adf3SAart Bik   }
961c81adf3SAart Bik   return rewriter.create<LLVM::ExtractValueOp>(loc, llvmType, val,
971c81adf3SAart Bik                                                rewriter.getI64ArrayAttr(pos));
981c81adf3SAart Bik }
991c81adf3SAart Bik 
1002d515e49SNicolas Vasilache // Helper that picks the proper sequence for extracting.
1012d515e49SNicolas Vasilache static Value extractOne(PatternRewriter &rewriter, Location loc, Value vector,
1022d515e49SNicolas Vasilache                         int64_t offset) {
1032d515e49SNicolas Vasilache   auto vectorType = vector.getType().cast<VectorType>();
1042d515e49SNicolas Vasilache   if (vectorType.getRank() > 1)
1052d515e49SNicolas Vasilache     return rewriter.create<ExtractOp>(loc, vector, offset);
1062d515e49SNicolas Vasilache   return rewriter.create<vector::ExtractElementOp>(
1072d515e49SNicolas Vasilache       loc, vectorType.getElementType(), vector,
1082d515e49SNicolas Vasilache       rewriter.create<ConstantIndexOp>(loc, offset));
1092d515e49SNicolas Vasilache }
1102d515e49SNicolas Vasilache 
1112d515e49SNicolas Vasilache // Helper that returns a subset of `arrayAttr` as a vector of int64_t.
1122d515e49SNicolas Vasilache // TODO(rriddle): Better support for attribute subtype forwarding + slicing.
1132d515e49SNicolas Vasilache static SmallVector<int64_t, 4> getI64SubArray(ArrayAttr arrayAttr,
1142d515e49SNicolas Vasilache                                               unsigned dropFront = 0,
1152d515e49SNicolas Vasilache                                               unsigned dropBack = 0) {
1162d515e49SNicolas Vasilache   assert(arrayAttr.size() > dropFront + dropBack && "Out of bounds");
1172d515e49SNicolas Vasilache   auto range = arrayAttr.getAsRange<IntegerAttr>();
1182d515e49SNicolas Vasilache   SmallVector<int64_t, 4> res;
1192d515e49SNicolas Vasilache   res.reserve(arrayAttr.size() - dropFront - dropBack);
1202d515e49SNicolas Vasilache   for (auto it = range.begin() + dropFront, eit = range.end() - dropBack;
1212d515e49SNicolas Vasilache        it != eit; ++it)
1222d515e49SNicolas Vasilache     res.push_back((*it).getValue().getSExtValue());
1232d515e49SNicolas Vasilache   return res;
1242d515e49SNicolas Vasilache }
1252d515e49SNicolas Vasilache 
126b36aaeafSAart Bik class VectorBroadcastOpConversion : public LLVMOpLowering {
127b36aaeafSAart Bik public:
128b36aaeafSAart Bik   explicit VectorBroadcastOpConversion(MLIRContext *context,
129b36aaeafSAart Bik                                        LLVMTypeConverter &typeConverter)
130b36aaeafSAart Bik       : LLVMOpLowering(vector::BroadcastOp::getOperationName(), context,
131b36aaeafSAart Bik                        typeConverter) {}
132b36aaeafSAart Bik 
133b36aaeafSAart Bik   PatternMatchResult
134e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
135b36aaeafSAart Bik                   ConversionPatternRewriter &rewriter) const override {
136b36aaeafSAart Bik     auto broadcastOp = cast<vector::BroadcastOp>(op);
137b36aaeafSAart Bik     VectorType dstVectorType = broadcastOp.getVectorType();
138b36aaeafSAart Bik     if (lowering.convertType(dstVectorType) == nullptr)
139b36aaeafSAart Bik       return matchFailure();
140b36aaeafSAart Bik     // Rewrite when the full vector type can be lowered (which
141b36aaeafSAart Bik     // implies all 'reduced' types can be lowered too).
1421c81adf3SAart Bik     auto adaptor = vector::BroadcastOpOperandAdaptor(operands);
143b36aaeafSAart Bik     VectorType srcVectorType =
144b36aaeafSAart Bik         broadcastOp.getSourceType().dyn_cast<VectorType>();
145b36aaeafSAart Bik     rewriter.replaceOp(
1461c81adf3SAart Bik         op, expandRanks(adaptor.source(), // source value to be expanded
147b36aaeafSAart Bik                         op->getLoc(),     // location of original broadcast
148b36aaeafSAart Bik                         srcVectorType, dstVectorType, rewriter));
149b36aaeafSAart Bik     return matchSuccess();
150b36aaeafSAart Bik   }
151b36aaeafSAart Bik 
152b36aaeafSAart Bik private:
153b36aaeafSAart Bik   // Expands the given source value over all the ranks, as defined
154b36aaeafSAart Bik   // by the source and destination type (a null source type denotes
155b36aaeafSAart Bik   // expansion from a scalar value into a vector).
156b36aaeafSAart Bik   //
157b36aaeafSAart Bik   // TODO(ajcbik): consider replacing this one-pattern lowering
158b36aaeafSAart Bik   //               with a two-pattern lowering using other vector
159b36aaeafSAart Bik   //               ops once all insert/extract/shuffle operations
160b36aaeafSAart Bik   //               are available with lowering implemention.
161b36aaeafSAart Bik   //
162e62a6956SRiver Riddle   Value expandRanks(Value value, Location loc, VectorType srcVectorType,
163b36aaeafSAart Bik                     VectorType dstVectorType,
164b36aaeafSAart Bik                     ConversionPatternRewriter &rewriter) const {
165b36aaeafSAart Bik     assert((dstVectorType != nullptr) && "invalid result type in broadcast");
166b36aaeafSAart Bik     // Determine rank of source and destination.
167b36aaeafSAart Bik     int64_t srcRank = srcVectorType ? srcVectorType.getRank() : 0;
168b36aaeafSAart Bik     int64_t dstRank = dstVectorType.getRank();
169b36aaeafSAart Bik     int64_t curDim = dstVectorType.getDimSize(0);
170b36aaeafSAart Bik     if (srcRank < dstRank)
171b36aaeafSAart Bik       // Duplicate this rank.
172b36aaeafSAart Bik       return duplicateOneRank(value, loc, srcVectorType, dstVectorType, dstRank,
173b36aaeafSAart Bik                               curDim, rewriter);
174b36aaeafSAart Bik     // If all trailing dimensions are the same, the broadcast consists of
175b36aaeafSAart Bik     // simply passing through the source value and we are done. Otherwise,
176b36aaeafSAart Bik     // any non-matching dimension forces a stretch along this rank.
177b36aaeafSAart Bik     assert((srcVectorType != nullptr) && (srcRank > 0) &&
178b36aaeafSAart Bik            (srcRank == dstRank) && "invalid rank in broadcast");
179b36aaeafSAart Bik     for (int64_t r = 0; r < dstRank; r++) {
180b36aaeafSAart Bik       if (srcVectorType.getDimSize(r) != dstVectorType.getDimSize(r)) {
181b36aaeafSAart Bik         return stretchOneRank(value, loc, srcVectorType, dstVectorType, dstRank,
182b36aaeafSAart Bik                               curDim, rewriter);
183b36aaeafSAart Bik       }
184b36aaeafSAart Bik     }
185b36aaeafSAart Bik     return value;
186b36aaeafSAart Bik   }
187b36aaeafSAart Bik 
188b36aaeafSAart Bik   // Picks the best way to duplicate a single rank. For the 1-D case, a
189b36aaeafSAart Bik   // single insert-elt/shuffle is the most efficient expansion. For higher
190b36aaeafSAart Bik   // dimensions, however, we need dim x insert-values on a new broadcast
191b36aaeafSAart Bik   // with one less leading dimension, which will be lowered "recursively"
192b36aaeafSAart Bik   // to matching LLVM IR.
193b36aaeafSAart Bik   // For example:
194b36aaeafSAart Bik   //   v = broadcast s : f32 to vector<4x2xf32>
195b36aaeafSAart Bik   // becomes:
196b36aaeafSAart Bik   //   x = broadcast s : f32 to vector<2xf32>
197b36aaeafSAart Bik   //   v = [x,x,x,x]
198b36aaeafSAart Bik   // becomes:
199b36aaeafSAart Bik   //   x = [s,s]
200b36aaeafSAart Bik   //   v = [x,x,x,x]
201e62a6956SRiver Riddle   Value duplicateOneRank(Value value, Location loc, VectorType srcVectorType,
202e62a6956SRiver Riddle                          VectorType dstVectorType, int64_t rank, int64_t dim,
203b36aaeafSAart Bik                          ConversionPatternRewriter &rewriter) const {
204b36aaeafSAart Bik     Type llvmType = lowering.convertType(dstVectorType);
205b36aaeafSAart Bik     assert((llvmType != nullptr) && "unlowerable vector type");
206b36aaeafSAart Bik     if (rank == 1) {
207e62a6956SRiver Riddle       Value undef = rewriter.create<LLVM::UndefOp>(loc, llvmType);
208e62a6956SRiver Riddle       Value expand =
2091c81adf3SAart Bik           insertOne(rewriter, lowering, loc, undef, value, llvmType, rank, 0);
210b36aaeafSAart Bik       SmallVector<int32_t, 4> zeroValues(dim, 0);
211b36aaeafSAart Bik       return rewriter.create<LLVM::ShuffleVectorOp>(
212b36aaeafSAart Bik           loc, expand, undef, rewriter.getI32ArrayAttr(zeroValues));
213b36aaeafSAart Bik     }
214e62a6956SRiver Riddle     Value expand = expandRanks(value, loc, srcVectorType,
2159826fe5cSAart Bik                                reducedVectorTypeFront(dstVectorType), rewriter);
216e62a6956SRiver Riddle     Value result = rewriter.create<LLVM::UndefOp>(loc, llvmType);
217b36aaeafSAart Bik     for (int64_t d = 0; d < dim; ++d) {
2181c81adf3SAart Bik       result =
2191c81adf3SAart Bik           insertOne(rewriter, lowering, loc, result, expand, llvmType, rank, d);
220b36aaeafSAart Bik     }
221b36aaeafSAart Bik     return result;
222b36aaeafSAart Bik   }
223b36aaeafSAart Bik 
224b36aaeafSAart Bik   // Picks the best way to stretch a single rank. For the 1-D case, a
225b36aaeafSAart Bik   // single insert-elt/shuffle is the most efficient expansion when at
226b36aaeafSAart Bik   // a stretch. Otherwise, every dimension needs to be expanded
227b36aaeafSAart Bik   // individually and individually inserted in the resulting vector.
228b36aaeafSAart Bik   // For example:
229b36aaeafSAart Bik   //   v = broadcast w : vector<4x1x2xf32> to vector<4x2x2xf32>
230b36aaeafSAart Bik   // becomes:
231b36aaeafSAart Bik   //   a = broadcast w[0] : vector<1x2xf32> to vector<2x2xf32>
232b36aaeafSAart Bik   //   b = broadcast w[1] : vector<1x2xf32> to vector<2x2xf32>
233b36aaeafSAart Bik   //   c = broadcast w[2] : vector<1x2xf32> to vector<2x2xf32>
234b36aaeafSAart Bik   //   d = broadcast w[3] : vector<1x2xf32> to vector<2x2xf32>
235b36aaeafSAart Bik   //   v = [a,b,c,d]
236b36aaeafSAart Bik   // becomes:
237b36aaeafSAart Bik   //   x = broadcast w[0][0] : vector<2xf32> to vector <2x2xf32>
238b36aaeafSAart Bik   //   y = broadcast w[1][0] : vector<2xf32> to vector <2x2xf32>
239b36aaeafSAart Bik   //   a = [x, y]
240b36aaeafSAart Bik   //   etc.
241e62a6956SRiver Riddle   Value stretchOneRank(Value value, Location loc, VectorType srcVectorType,
242e62a6956SRiver Riddle                        VectorType dstVectorType, int64_t rank, int64_t dim,
243b36aaeafSAart Bik                        ConversionPatternRewriter &rewriter) const {
244b36aaeafSAart Bik     Type llvmType = lowering.convertType(dstVectorType);
245b36aaeafSAart Bik     assert((llvmType != nullptr) && "unlowerable vector type");
246e62a6956SRiver Riddle     Value result = rewriter.create<LLVM::UndefOp>(loc, llvmType);
247b36aaeafSAart Bik     bool atStretch = dim != srcVectorType.getDimSize(0);
248b36aaeafSAart Bik     if (rank == 1) {
2491c81adf3SAart Bik       assert(atStretch);
250b36aaeafSAart Bik       Type redLlvmType = lowering.convertType(dstVectorType.getElementType());
251e62a6956SRiver Riddle       Value one =
2521c81adf3SAart Bik           extractOne(rewriter, lowering, loc, value, redLlvmType, rank, 0);
253e62a6956SRiver Riddle       Value expand =
2541c81adf3SAart Bik           insertOne(rewriter, lowering, loc, result, one, llvmType, rank, 0);
255b36aaeafSAart Bik       SmallVector<int32_t, 4> zeroValues(dim, 0);
256b36aaeafSAart Bik       return rewriter.create<LLVM::ShuffleVectorOp>(
257b36aaeafSAart Bik           loc, expand, result, rewriter.getI32ArrayAttr(zeroValues));
258b36aaeafSAart Bik     }
2599826fe5cSAart Bik     VectorType redSrcType = reducedVectorTypeFront(srcVectorType);
2609826fe5cSAart Bik     VectorType redDstType = reducedVectorTypeFront(dstVectorType);
261b36aaeafSAart Bik     Type redLlvmType = lowering.convertType(redSrcType);
262b36aaeafSAart Bik     for (int64_t d = 0; d < dim; ++d) {
263b36aaeafSAart Bik       int64_t pos = atStretch ? 0 : d;
264e62a6956SRiver Riddle       Value one =
2651c81adf3SAart Bik           extractOne(rewriter, lowering, loc, value, redLlvmType, rank, pos);
266e62a6956SRiver Riddle       Value expand = expandRanks(one, loc, redSrcType, redDstType, rewriter);
2671c81adf3SAart Bik       result =
2681c81adf3SAart Bik           insertOne(rewriter, lowering, loc, result, expand, llvmType, rank, d);
269b36aaeafSAart Bik     }
270b36aaeafSAart Bik     return result;
271b36aaeafSAart Bik   }
2721c81adf3SAart Bik };
273b36aaeafSAart Bik 
2741c81adf3SAart Bik class VectorShuffleOpConversion : public LLVMOpLowering {
2751c81adf3SAart Bik public:
2761c81adf3SAart Bik   explicit VectorShuffleOpConversion(MLIRContext *context,
2771c81adf3SAart Bik                                      LLVMTypeConverter &typeConverter)
2781c81adf3SAart Bik       : LLVMOpLowering(vector::ShuffleOp::getOperationName(), context,
2791c81adf3SAart Bik                        typeConverter) {}
2801c81adf3SAart Bik 
2811c81adf3SAart Bik   PatternMatchResult
282e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
2831c81adf3SAart Bik                   ConversionPatternRewriter &rewriter) const override {
2841c81adf3SAart Bik     auto loc = op->getLoc();
2851c81adf3SAart Bik     auto adaptor = vector::ShuffleOpOperandAdaptor(operands);
2861c81adf3SAart Bik     auto shuffleOp = cast<vector::ShuffleOp>(op);
2871c81adf3SAart Bik     auto v1Type = shuffleOp.getV1VectorType();
2881c81adf3SAart Bik     auto v2Type = shuffleOp.getV2VectorType();
2891c81adf3SAart Bik     auto vectorType = shuffleOp.getVectorType();
2901c81adf3SAart Bik     Type llvmType = lowering.convertType(vectorType);
2911c81adf3SAart Bik     auto maskArrayAttr = shuffleOp.mask();
2921c81adf3SAart Bik 
2931c81adf3SAart Bik     // Bail if result type cannot be lowered.
2941c81adf3SAart Bik     if (!llvmType)
2951c81adf3SAart Bik       return matchFailure();
2961c81adf3SAart Bik 
2971c81adf3SAart Bik     // Get rank and dimension sizes.
2981c81adf3SAart Bik     int64_t rank = vectorType.getRank();
2991c81adf3SAart Bik     assert(v1Type.getRank() == rank);
3001c81adf3SAart Bik     assert(v2Type.getRank() == rank);
3011c81adf3SAart Bik     int64_t v1Dim = v1Type.getDimSize(0);
3021c81adf3SAart Bik 
3031c81adf3SAart Bik     // For rank 1, where both operands have *exactly* the same vector type,
3041c81adf3SAart Bik     // there is direct shuffle support in LLVM. Use it!
3051c81adf3SAart Bik     if (rank == 1 && v1Type == v2Type) {
306e62a6956SRiver Riddle       Value shuffle = rewriter.create<LLVM::ShuffleVectorOp>(
3071c81adf3SAart Bik           loc, adaptor.v1(), adaptor.v2(), maskArrayAttr);
3081c81adf3SAart Bik       rewriter.replaceOp(op, shuffle);
3091c81adf3SAart Bik       return matchSuccess();
310b36aaeafSAart Bik     }
311b36aaeafSAart Bik 
3121c81adf3SAart Bik     // For all other cases, insert the individual values individually.
313e62a6956SRiver Riddle     Value insert = rewriter.create<LLVM::UndefOp>(loc, llvmType);
3141c81adf3SAart Bik     int64_t insPos = 0;
3151c81adf3SAart Bik     for (auto en : llvm::enumerate(maskArrayAttr)) {
3161c81adf3SAart Bik       int64_t extPos = en.value().cast<IntegerAttr>().getInt();
317e62a6956SRiver Riddle       Value value = adaptor.v1();
3181c81adf3SAart Bik       if (extPos >= v1Dim) {
3191c81adf3SAart Bik         extPos -= v1Dim;
3201c81adf3SAart Bik         value = adaptor.v2();
321b36aaeafSAart Bik       }
322e62a6956SRiver Riddle       Value extract =
3231c81adf3SAart Bik           extractOne(rewriter, lowering, loc, value, llvmType, rank, extPos);
3241c81adf3SAart Bik       insert = insertOne(rewriter, lowering, loc, insert, extract, llvmType,
3251c81adf3SAart Bik                          rank, insPos++);
3261c81adf3SAart Bik     }
3271c81adf3SAart Bik     rewriter.replaceOp(op, insert);
3281c81adf3SAart Bik     return matchSuccess();
329b36aaeafSAart Bik   }
330b36aaeafSAart Bik };
331b36aaeafSAart Bik 
332cd5dab8aSAart Bik class VectorExtractElementOpConversion : public LLVMOpLowering {
333cd5dab8aSAart Bik public:
334cd5dab8aSAart Bik   explicit VectorExtractElementOpConversion(MLIRContext *context,
335cd5dab8aSAart Bik                                             LLVMTypeConverter &typeConverter)
336cd5dab8aSAart Bik       : LLVMOpLowering(vector::ExtractElementOp::getOperationName(), context,
337cd5dab8aSAart Bik                        typeConverter) {}
338cd5dab8aSAart Bik 
339cd5dab8aSAart Bik   PatternMatchResult
340e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
341cd5dab8aSAart Bik                   ConversionPatternRewriter &rewriter) const override {
342cd5dab8aSAart Bik     auto adaptor = vector::ExtractElementOpOperandAdaptor(operands);
343cd5dab8aSAart Bik     auto extractEltOp = cast<vector::ExtractElementOp>(op);
344cd5dab8aSAart Bik     auto vectorType = extractEltOp.getVectorType();
345cd5dab8aSAart Bik     auto llvmType = lowering.convertType(vectorType.getElementType());
346cd5dab8aSAart Bik 
347cd5dab8aSAart Bik     // Bail if result type cannot be lowered.
348cd5dab8aSAart Bik     if (!llvmType)
349cd5dab8aSAart Bik       return matchFailure();
350cd5dab8aSAart Bik 
351cd5dab8aSAart Bik     rewriter.replaceOpWithNewOp<LLVM::ExtractElementOp>(
352cd5dab8aSAart Bik         op, llvmType, adaptor.vector(), adaptor.position());
353cd5dab8aSAart Bik     return matchSuccess();
354cd5dab8aSAart Bik   }
355cd5dab8aSAart Bik };
356cd5dab8aSAart Bik 
3579826fe5cSAart Bik class VectorExtractOpConversion : public LLVMOpLowering {
3585c0c51a9SNicolas Vasilache public:
3599826fe5cSAart Bik   explicit VectorExtractOpConversion(MLIRContext *context,
3605c0c51a9SNicolas Vasilache                                      LLVMTypeConverter &typeConverter)
361d37f2725SAart Bik       : LLVMOpLowering(vector::ExtractOp::getOperationName(), context,
3625c0c51a9SNicolas Vasilache                        typeConverter) {}
3635c0c51a9SNicolas Vasilache 
3645c0c51a9SNicolas Vasilache   PatternMatchResult
365e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
3665c0c51a9SNicolas Vasilache                   ConversionPatternRewriter &rewriter) const override {
3675c0c51a9SNicolas Vasilache     auto loc = op->getLoc();
368d37f2725SAart Bik     auto adaptor = vector::ExtractOpOperandAdaptor(operands);
369d37f2725SAart Bik     auto extractOp = cast<vector::ExtractOp>(op);
3709826fe5cSAart Bik     auto vectorType = extractOp.getVectorType();
371*2bdf33ccSRiver Riddle     auto resultType = extractOp.getResult().getType();
3725c0c51a9SNicolas Vasilache     auto llvmResultType = lowering.convertType(resultType);
3735c0c51a9SNicolas Vasilache     auto positionArrayAttr = extractOp.position();
3749826fe5cSAart Bik 
3759826fe5cSAart Bik     // Bail if result type cannot be lowered.
3769826fe5cSAart Bik     if (!llvmResultType)
3779826fe5cSAart Bik       return matchFailure();
3789826fe5cSAart Bik 
3795c0c51a9SNicolas Vasilache     // One-shot extraction of vector from array (only requires extractvalue).
3805c0c51a9SNicolas Vasilache     if (resultType.isa<VectorType>()) {
381e62a6956SRiver Riddle       Value extracted = rewriter.create<LLVM::ExtractValueOp>(
3825c0c51a9SNicolas Vasilache           loc, llvmResultType, adaptor.vector(), positionArrayAttr);
3835c0c51a9SNicolas Vasilache       rewriter.replaceOp(op, extracted);
3845c0c51a9SNicolas Vasilache       return matchSuccess();
3855c0c51a9SNicolas Vasilache     }
3865c0c51a9SNicolas Vasilache 
3879826fe5cSAart Bik     // Potential extraction of 1-D vector from array.
3885c0c51a9SNicolas Vasilache     auto *context = op->getContext();
389e62a6956SRiver Riddle     Value extracted = adaptor.vector();
3905c0c51a9SNicolas Vasilache     auto positionAttrs = positionArrayAttr.getValue();
3915c0c51a9SNicolas Vasilache     if (positionAttrs.size() > 1) {
3929826fe5cSAart Bik       auto oneDVectorType = reducedVectorTypeBack(vectorType);
3935c0c51a9SNicolas Vasilache       auto nMinusOnePositionAttrs =
3945c0c51a9SNicolas Vasilache           ArrayAttr::get(positionAttrs.drop_back(), context);
3955c0c51a9SNicolas Vasilache       extracted = rewriter.create<LLVM::ExtractValueOp>(
3965c0c51a9SNicolas Vasilache           loc, lowering.convertType(oneDVectorType), extracted,
3975c0c51a9SNicolas Vasilache           nMinusOnePositionAttrs);
3985c0c51a9SNicolas Vasilache     }
3995c0c51a9SNicolas Vasilache 
4005c0c51a9SNicolas Vasilache     // Remaining extraction of element from 1-D LLVM vector
4015c0c51a9SNicolas Vasilache     auto position = positionAttrs.back().cast<IntegerAttr>();
4021d47564aSAart Bik     auto i64Type = LLVM::LLVMType::getInt64Ty(lowering.getDialect());
4031d47564aSAart Bik     auto constant = rewriter.create<LLVM::ConstantOp>(loc, i64Type, position);
4045c0c51a9SNicolas Vasilache     extracted =
4055c0c51a9SNicolas Vasilache         rewriter.create<LLVM::ExtractElementOp>(loc, extracted, constant);
4065c0c51a9SNicolas Vasilache     rewriter.replaceOp(op, extracted);
4075c0c51a9SNicolas Vasilache 
4085c0c51a9SNicolas Vasilache     return matchSuccess();
4095c0c51a9SNicolas Vasilache   }
4105c0c51a9SNicolas Vasilache };
4115c0c51a9SNicolas Vasilache 
412cd5dab8aSAart Bik class VectorInsertElementOpConversion : public LLVMOpLowering {
413cd5dab8aSAart Bik public:
414cd5dab8aSAart Bik   explicit VectorInsertElementOpConversion(MLIRContext *context,
415cd5dab8aSAart Bik                                            LLVMTypeConverter &typeConverter)
416cd5dab8aSAart Bik       : LLVMOpLowering(vector::InsertElementOp::getOperationName(), context,
417cd5dab8aSAart Bik                        typeConverter) {}
418cd5dab8aSAart Bik 
419cd5dab8aSAart Bik   PatternMatchResult
420e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
421cd5dab8aSAart Bik                   ConversionPatternRewriter &rewriter) const override {
422cd5dab8aSAart Bik     auto adaptor = vector::InsertElementOpOperandAdaptor(operands);
423cd5dab8aSAart Bik     auto insertEltOp = cast<vector::InsertElementOp>(op);
424cd5dab8aSAart Bik     auto vectorType = insertEltOp.getDestVectorType();
425cd5dab8aSAart Bik     auto llvmType = lowering.convertType(vectorType);
426cd5dab8aSAart Bik 
427cd5dab8aSAart Bik     // Bail if result type cannot be lowered.
428cd5dab8aSAart Bik     if (!llvmType)
429cd5dab8aSAart Bik       return matchFailure();
430cd5dab8aSAart Bik 
431cd5dab8aSAart Bik     rewriter.replaceOpWithNewOp<LLVM::InsertElementOp>(
432cd5dab8aSAart Bik         op, llvmType, adaptor.dest(), adaptor.source(), adaptor.position());
433cd5dab8aSAart Bik     return matchSuccess();
434cd5dab8aSAart Bik   }
435cd5dab8aSAart Bik };
436cd5dab8aSAart Bik 
4379826fe5cSAart Bik class VectorInsertOpConversion : public LLVMOpLowering {
4389826fe5cSAart Bik public:
4399826fe5cSAart Bik   explicit VectorInsertOpConversion(MLIRContext *context,
4409826fe5cSAart Bik                                     LLVMTypeConverter &typeConverter)
4419826fe5cSAart Bik       : LLVMOpLowering(vector::InsertOp::getOperationName(), context,
4429826fe5cSAart Bik                        typeConverter) {}
4439826fe5cSAart Bik 
4449826fe5cSAart Bik   PatternMatchResult
445e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
4469826fe5cSAart Bik                   ConversionPatternRewriter &rewriter) const override {
4479826fe5cSAart Bik     auto loc = op->getLoc();
4489826fe5cSAart Bik     auto adaptor = vector::InsertOpOperandAdaptor(operands);
4499826fe5cSAart Bik     auto insertOp = cast<vector::InsertOp>(op);
4509826fe5cSAart Bik     auto sourceType = insertOp.getSourceType();
4519826fe5cSAart Bik     auto destVectorType = insertOp.getDestVectorType();
4529826fe5cSAart Bik     auto llvmResultType = lowering.convertType(destVectorType);
4539826fe5cSAart Bik     auto positionArrayAttr = insertOp.position();
4549826fe5cSAart Bik 
4559826fe5cSAart Bik     // Bail if result type cannot be lowered.
4569826fe5cSAart Bik     if (!llvmResultType)
4579826fe5cSAart Bik       return matchFailure();
4589826fe5cSAart Bik 
4599826fe5cSAart Bik     // One-shot insertion of a vector into an array (only requires insertvalue).
4609826fe5cSAart Bik     if (sourceType.isa<VectorType>()) {
461e62a6956SRiver Riddle       Value inserted = rewriter.create<LLVM::InsertValueOp>(
4629826fe5cSAart Bik           loc, llvmResultType, adaptor.dest(), adaptor.source(),
4639826fe5cSAart Bik           positionArrayAttr);
4649826fe5cSAart Bik       rewriter.replaceOp(op, inserted);
4659826fe5cSAart Bik       return matchSuccess();
4669826fe5cSAart Bik     }
4679826fe5cSAart Bik 
4689826fe5cSAart Bik     // Potential extraction of 1-D vector from array.
4699826fe5cSAart Bik     auto *context = op->getContext();
470e62a6956SRiver Riddle     Value extracted = adaptor.dest();
4719826fe5cSAart Bik     auto positionAttrs = positionArrayAttr.getValue();
4729826fe5cSAart Bik     auto position = positionAttrs.back().cast<IntegerAttr>();
4739826fe5cSAart Bik     auto oneDVectorType = destVectorType;
4749826fe5cSAart Bik     if (positionAttrs.size() > 1) {
4759826fe5cSAart Bik       oneDVectorType = reducedVectorTypeBack(destVectorType);
4769826fe5cSAart Bik       auto nMinusOnePositionAttrs =
4779826fe5cSAart Bik           ArrayAttr::get(positionAttrs.drop_back(), context);
4789826fe5cSAart Bik       extracted = rewriter.create<LLVM::ExtractValueOp>(
4799826fe5cSAart Bik           loc, lowering.convertType(oneDVectorType), extracted,
4809826fe5cSAart Bik           nMinusOnePositionAttrs);
4819826fe5cSAart Bik     }
4829826fe5cSAart Bik 
4839826fe5cSAart Bik     // Insertion of an element into a 1-D LLVM vector.
4841d47564aSAart Bik     auto i64Type = LLVM::LLVMType::getInt64Ty(lowering.getDialect());
4851d47564aSAart Bik     auto constant = rewriter.create<LLVM::ConstantOp>(loc, i64Type, position);
486e62a6956SRiver Riddle     Value inserted = rewriter.create<LLVM::InsertElementOp>(
4879826fe5cSAart Bik         loc, lowering.convertType(oneDVectorType), extracted, adaptor.source(),
4889826fe5cSAart Bik         constant);
4899826fe5cSAart Bik 
4909826fe5cSAart Bik     // Potential insertion of resulting 1-D vector into array.
4919826fe5cSAart Bik     if (positionAttrs.size() > 1) {
4929826fe5cSAart Bik       auto nMinusOnePositionAttrs =
4939826fe5cSAart Bik           ArrayAttr::get(positionAttrs.drop_back(), context);
4949826fe5cSAart Bik       inserted = rewriter.create<LLVM::InsertValueOp>(loc, llvmResultType,
4959826fe5cSAart Bik                                                       adaptor.dest(), inserted,
4969826fe5cSAart Bik                                                       nMinusOnePositionAttrs);
4979826fe5cSAart Bik     }
4989826fe5cSAart Bik 
4999826fe5cSAart Bik     rewriter.replaceOp(op, inserted);
5009826fe5cSAart Bik     return matchSuccess();
5019826fe5cSAart Bik   }
5029826fe5cSAart Bik };
5039826fe5cSAart Bik 
5042d515e49SNicolas Vasilache // When ranks are different, InsertStridedSlice needs to extract a properly
5052d515e49SNicolas Vasilache // ranked vector from the destination vector into which to insert. This pattern
5062d515e49SNicolas Vasilache // only takes care of this part and forwards the rest of the conversion to
5072d515e49SNicolas Vasilache // another pattern that converts InsertStridedSlice for operands of the same
5082d515e49SNicolas Vasilache // rank.
5092d515e49SNicolas Vasilache //
5102d515e49SNicolas Vasilache // RewritePattern for InsertStridedSliceOp where source and destination vectors
5112d515e49SNicolas Vasilache // have different ranks. In this case:
5122d515e49SNicolas Vasilache //   1. the proper subvector is extracted from the destination vector
5132d515e49SNicolas Vasilache //   2. a new InsertStridedSlice op is created to insert the source in the
5142d515e49SNicolas Vasilache //   destination subvector
5152d515e49SNicolas Vasilache //   3. the destination subvector is inserted back in the proper place
5162d515e49SNicolas Vasilache //   4. the op is replaced by the result of step 3.
5172d515e49SNicolas Vasilache // The new InsertStridedSlice from step 2. will be picked up by a
5182d515e49SNicolas Vasilache // `VectorInsertStridedSliceOpSameRankRewritePattern`.
5192d515e49SNicolas Vasilache class VectorInsertStridedSliceOpDifferentRankRewritePattern
5202d515e49SNicolas Vasilache     : public OpRewritePattern<InsertStridedSliceOp> {
5212d515e49SNicolas Vasilache public:
5222d515e49SNicolas Vasilache   using OpRewritePattern<InsertStridedSliceOp>::OpRewritePattern;
5232d515e49SNicolas Vasilache 
5242d515e49SNicolas Vasilache   PatternMatchResult matchAndRewrite(InsertStridedSliceOp op,
5252d515e49SNicolas Vasilache                                      PatternRewriter &rewriter) const override {
5262d515e49SNicolas Vasilache     auto srcType = op.getSourceVectorType();
5272d515e49SNicolas Vasilache     auto dstType = op.getDestVectorType();
5282d515e49SNicolas Vasilache 
5292d515e49SNicolas Vasilache     if (op.offsets().getValue().empty())
5302d515e49SNicolas Vasilache       return matchFailure();
5312d515e49SNicolas Vasilache 
5322d515e49SNicolas Vasilache     auto loc = op.getLoc();
5332d515e49SNicolas Vasilache     int64_t rankDiff = dstType.getRank() - srcType.getRank();
5342d515e49SNicolas Vasilache     assert(rankDiff >= 0);
5352d515e49SNicolas Vasilache     if (rankDiff == 0)
5362d515e49SNicolas Vasilache       return matchFailure();
5372d515e49SNicolas Vasilache 
5382d515e49SNicolas Vasilache     int64_t rankRest = dstType.getRank() - rankDiff;
5392d515e49SNicolas Vasilache     // Extract / insert the subvector of matching rank and InsertStridedSlice
5402d515e49SNicolas Vasilache     // on it.
5412d515e49SNicolas Vasilache     Value extracted =
5422d515e49SNicolas Vasilache         rewriter.create<ExtractOp>(loc, op.dest(),
5432d515e49SNicolas Vasilache                                    getI64SubArray(op.offsets(), /*dropFront=*/0,
5442d515e49SNicolas Vasilache                                                   /*dropFront=*/rankRest));
5452d515e49SNicolas Vasilache     // A different pattern will kick in for InsertStridedSlice with matching
5462d515e49SNicolas Vasilache     // ranks.
5472d515e49SNicolas Vasilache     auto stridedSliceInnerOp = rewriter.create<InsertStridedSliceOp>(
5482d515e49SNicolas Vasilache         loc, op.source(), extracted,
5492d515e49SNicolas Vasilache         getI64SubArray(op.offsets(), /*dropFront=*/rankDiff),
5502d515e49SNicolas Vasilache         getI64SubArray(op.strides(), /*dropFront=*/rankDiff));
5512d515e49SNicolas Vasilache     rewriter.replaceOpWithNewOp<InsertOp>(
5522d515e49SNicolas Vasilache         op, stridedSliceInnerOp.getResult(), op.dest(),
5532d515e49SNicolas Vasilache         getI64SubArray(op.offsets(), /*dropFront=*/0,
5542d515e49SNicolas Vasilache                        /*dropFront=*/rankRest));
5552d515e49SNicolas Vasilache     return matchSuccess();
5562d515e49SNicolas Vasilache   }
5572d515e49SNicolas Vasilache };
5582d515e49SNicolas Vasilache 
5592d515e49SNicolas Vasilache // RewritePattern for InsertStridedSliceOp where source and destination vectors
5602d515e49SNicolas Vasilache // have the same rank. In this case, we reduce
5612d515e49SNicolas Vasilache //   1. the proper subvector is extracted from the destination vector
5622d515e49SNicolas Vasilache //   2. a new InsertStridedSlice op is created to insert the source in the
5632d515e49SNicolas Vasilache //   destination subvector
5642d515e49SNicolas Vasilache //   3. the destination subvector is inserted back in the proper place
5652d515e49SNicolas Vasilache //   4. the op is replaced by the result of step 3.
5662d515e49SNicolas Vasilache // The new InsertStridedSlice from step 2. will be picked up by a
5672d515e49SNicolas Vasilache // `VectorInsertStridedSliceOpSameRankRewritePattern`.
5682d515e49SNicolas Vasilache class VectorInsertStridedSliceOpSameRankRewritePattern
5692d515e49SNicolas Vasilache     : public OpRewritePattern<InsertStridedSliceOp> {
5702d515e49SNicolas Vasilache public:
5712d515e49SNicolas Vasilache   using OpRewritePattern<InsertStridedSliceOp>::OpRewritePattern;
5722d515e49SNicolas Vasilache 
5732d515e49SNicolas Vasilache   PatternMatchResult matchAndRewrite(InsertStridedSliceOp op,
5742d515e49SNicolas Vasilache                                      PatternRewriter &rewriter) const override {
5752d515e49SNicolas Vasilache     auto srcType = op.getSourceVectorType();
5762d515e49SNicolas Vasilache     auto dstType = op.getDestVectorType();
5772d515e49SNicolas Vasilache 
5782d515e49SNicolas Vasilache     if (op.offsets().getValue().empty())
5792d515e49SNicolas Vasilache       return matchFailure();
5802d515e49SNicolas Vasilache 
5812d515e49SNicolas Vasilache     int64_t rankDiff = dstType.getRank() - srcType.getRank();
5822d515e49SNicolas Vasilache     assert(rankDiff >= 0);
5832d515e49SNicolas Vasilache     if (rankDiff != 0)
5842d515e49SNicolas Vasilache       return matchFailure();
5852d515e49SNicolas Vasilache 
5862d515e49SNicolas Vasilache     if (srcType == dstType) {
5872d515e49SNicolas Vasilache       rewriter.replaceOp(op, op.source());
5882d515e49SNicolas Vasilache       return matchSuccess();
5892d515e49SNicolas Vasilache     }
5902d515e49SNicolas Vasilache 
5912d515e49SNicolas Vasilache     int64_t offset =
5922d515e49SNicolas Vasilache         op.offsets().getValue().front().cast<IntegerAttr>().getInt();
5932d515e49SNicolas Vasilache     int64_t size = srcType.getShape().front();
5942d515e49SNicolas Vasilache     int64_t stride =
5952d515e49SNicolas Vasilache         op.strides().getValue().front().cast<IntegerAttr>().getInt();
5962d515e49SNicolas Vasilache 
5972d515e49SNicolas Vasilache     auto loc = op.getLoc();
5982d515e49SNicolas Vasilache     Value res = op.dest();
5992d515e49SNicolas Vasilache     // For each slice of the source vector along the most major dimension.
6002d515e49SNicolas Vasilache     for (int64_t off = offset, e = offset + size * stride, idx = 0; off < e;
6012d515e49SNicolas Vasilache          off += stride, ++idx) {
6022d515e49SNicolas Vasilache       // 1. extract the proper subvector (or element) from source
6032d515e49SNicolas Vasilache       Value extractedSource = extractOne(rewriter, loc, op.source(), idx);
6042d515e49SNicolas Vasilache       if (extractedSource.getType().isa<VectorType>()) {
6052d515e49SNicolas Vasilache         // 2. If we have a vector, extract the proper subvector from destination
6062d515e49SNicolas Vasilache         // Otherwise we are at the element level and no need to recurse.
6072d515e49SNicolas Vasilache         Value extractedDest = extractOne(rewriter, loc, op.dest(), off);
6082d515e49SNicolas Vasilache         // 3. Reduce the problem to lowering a new InsertStridedSlice op with
6092d515e49SNicolas Vasilache         // smaller rank.
6102d515e49SNicolas Vasilache         InsertStridedSliceOp insertStridedSliceOp =
6112d515e49SNicolas Vasilache             rewriter.create<InsertStridedSliceOp>(
6122d515e49SNicolas Vasilache                 loc, extractedSource, extractedDest,
6132d515e49SNicolas Vasilache                 getI64SubArray(op.offsets(), /* dropFront=*/1),
6142d515e49SNicolas Vasilache                 getI64SubArray(op.strides(), /* dropFront=*/1));
6152d515e49SNicolas Vasilache         // Call matchAndRewrite recursively from within the pattern. This
6162d515e49SNicolas Vasilache         // circumvents the current limitation that a given pattern cannot
6172d515e49SNicolas Vasilache         // be called multiple times by the PatternRewrite infrastructure (to
6182d515e49SNicolas Vasilache         // avoid infinite recursion, but in this case, infinite recursion
6192d515e49SNicolas Vasilache         // cannot happen because the rank is strictly decreasing).
6202d515e49SNicolas Vasilache         // TODO(rriddle, nicolasvasilache) Implement something like a hook for
6212d515e49SNicolas Vasilache         // a potential function that must decrease and allow the same pattern
6222d515e49SNicolas Vasilache         // multiple times.
6232d515e49SNicolas Vasilache         auto success = matchAndRewrite(insertStridedSliceOp, rewriter);
6242d515e49SNicolas Vasilache         (void)success;
6252d515e49SNicolas Vasilache         assert(success && "Unexpected failure");
6262d515e49SNicolas Vasilache         extractedSource = insertStridedSliceOp;
6272d515e49SNicolas Vasilache       }
6282d515e49SNicolas Vasilache       // 4. Insert the extractedSource into the res vector.
6292d515e49SNicolas Vasilache       res = insertOne(rewriter, loc, extractedSource, res, off);
6302d515e49SNicolas Vasilache     }
6312d515e49SNicolas Vasilache 
6322d515e49SNicolas Vasilache     rewriter.replaceOp(op, res);
6332d515e49SNicolas Vasilache     return matchSuccess();
6342d515e49SNicolas Vasilache   }
6352d515e49SNicolas Vasilache };
6362d515e49SNicolas Vasilache 
6375c0c51a9SNicolas Vasilache class VectorOuterProductOpConversion : public LLVMOpLowering {
6385c0c51a9SNicolas Vasilache public:
6395c0c51a9SNicolas Vasilache   explicit VectorOuterProductOpConversion(MLIRContext *context,
6405c0c51a9SNicolas Vasilache                                           LLVMTypeConverter &typeConverter)
6415c0c51a9SNicolas Vasilache       : LLVMOpLowering(vector::OuterProductOp::getOperationName(), context,
6425c0c51a9SNicolas Vasilache                        typeConverter) {}
6435c0c51a9SNicolas Vasilache 
6445c0c51a9SNicolas Vasilache   PatternMatchResult
645e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
6465c0c51a9SNicolas Vasilache                   ConversionPatternRewriter &rewriter) const override {
6475c0c51a9SNicolas Vasilache     auto loc = op->getLoc();
6485c0c51a9SNicolas Vasilache     auto adaptor = vector::OuterProductOpOperandAdaptor(operands);
6495c0c51a9SNicolas Vasilache     auto *ctx = op->getContext();
650*2bdf33ccSRiver Riddle     auto vLHS = adaptor.lhs().getType().cast<LLVM::LLVMType>();
651*2bdf33ccSRiver Riddle     auto vRHS = adaptor.rhs().getType().cast<LLVM::LLVMType>();
6525c0c51a9SNicolas Vasilache     auto rankLHS = vLHS.getUnderlyingType()->getVectorNumElements();
6535c0c51a9SNicolas Vasilache     auto rankRHS = vRHS.getUnderlyingType()->getVectorNumElements();
6545c0c51a9SNicolas Vasilache     auto llvmArrayOfVectType = lowering.convertType(
655*2bdf33ccSRiver Riddle         cast<vector::OuterProductOp>(op).getResult().getType());
656e62a6956SRiver Riddle     Value desc = rewriter.create<LLVM::UndefOp>(loc, llvmArrayOfVectType);
657e62a6956SRiver Riddle     Value a = adaptor.lhs(), b = adaptor.rhs();
658e62a6956SRiver Riddle     Value acc = adaptor.acc().empty() ? nullptr : adaptor.acc().front();
659e62a6956SRiver Riddle     SmallVector<Value, 8> lhs, accs;
6605c0c51a9SNicolas Vasilache     lhs.reserve(rankLHS);
6615c0c51a9SNicolas Vasilache     accs.reserve(rankLHS);
6625c0c51a9SNicolas Vasilache     for (unsigned d = 0, e = rankLHS; d < e; ++d) {
6635c0c51a9SNicolas Vasilache       // shufflevector explicitly requires i32.
6645c0c51a9SNicolas Vasilache       auto attr = rewriter.getI32IntegerAttr(d);
6655c0c51a9SNicolas Vasilache       SmallVector<Attribute, 4> bcastAttr(rankRHS, attr);
6665c0c51a9SNicolas Vasilache       auto bcastArrayAttr = ArrayAttr::get(bcastAttr, ctx);
667e62a6956SRiver Riddle       Value aD = nullptr, accD = nullptr;
6685c0c51a9SNicolas Vasilache       // 1. Broadcast the element a[d] into vector aD.
6695c0c51a9SNicolas Vasilache       aD = rewriter.create<LLVM::ShuffleVectorOp>(loc, a, a, bcastArrayAttr);
6705c0c51a9SNicolas Vasilache       // 2. If acc is present, extract 1-d vector acc[d] into accD.
6715c0c51a9SNicolas Vasilache       if (acc)
6725c0c51a9SNicolas Vasilache         accD = rewriter.create<LLVM::ExtractValueOp>(
6735c0c51a9SNicolas Vasilache             loc, vRHS, acc, rewriter.getI64ArrayAttr(d));
6745c0c51a9SNicolas Vasilache       // 3. Compute aD outer b (plus accD, if relevant).
675e62a6956SRiver Riddle       Value aOuterbD =
6765c0c51a9SNicolas Vasilache           accD ? rewriter.create<LLVM::FMulAddOp>(loc, vRHS, aD, b, accD)
6775c0c51a9SNicolas Vasilache                      .getResult()
6785c0c51a9SNicolas Vasilache                : rewriter.create<LLVM::FMulOp>(loc, aD, b).getResult();
6795c0c51a9SNicolas Vasilache       // 4. Insert as value `d` in the descriptor.
6805c0c51a9SNicolas Vasilache       desc = rewriter.create<LLVM::InsertValueOp>(loc, llvmArrayOfVectType,
6815c0c51a9SNicolas Vasilache                                                   desc, aOuterbD,
6825c0c51a9SNicolas Vasilache                                                   rewriter.getI64ArrayAttr(d));
6835c0c51a9SNicolas Vasilache     }
6845c0c51a9SNicolas Vasilache     rewriter.replaceOp(op, desc);
6855c0c51a9SNicolas Vasilache     return matchSuccess();
6865c0c51a9SNicolas Vasilache   }
6875c0c51a9SNicolas Vasilache };
6885c0c51a9SNicolas Vasilache 
6895c0c51a9SNicolas Vasilache class VectorTypeCastOpConversion : public LLVMOpLowering {
6905c0c51a9SNicolas Vasilache public:
6915c0c51a9SNicolas Vasilache   explicit VectorTypeCastOpConversion(MLIRContext *context,
6925c0c51a9SNicolas Vasilache                                       LLVMTypeConverter &typeConverter)
6935c0c51a9SNicolas Vasilache       : LLVMOpLowering(vector::TypeCastOp::getOperationName(), context,
6945c0c51a9SNicolas Vasilache                        typeConverter) {}
6955c0c51a9SNicolas Vasilache 
6965c0c51a9SNicolas Vasilache   PatternMatchResult
697e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
6985c0c51a9SNicolas Vasilache                   ConversionPatternRewriter &rewriter) const override {
6995c0c51a9SNicolas Vasilache     auto loc = op->getLoc();
7005c0c51a9SNicolas Vasilache     vector::TypeCastOp castOp = cast<vector::TypeCastOp>(op);
7015c0c51a9SNicolas Vasilache     MemRefType sourceMemRefType =
702*2bdf33ccSRiver Riddle         castOp.getOperand().getType().cast<MemRefType>();
7035c0c51a9SNicolas Vasilache     MemRefType targetMemRefType =
704*2bdf33ccSRiver Riddle         castOp.getResult().getType().cast<MemRefType>();
7055c0c51a9SNicolas Vasilache 
7065c0c51a9SNicolas Vasilache     // Only static shape casts supported atm.
7075c0c51a9SNicolas Vasilache     if (!sourceMemRefType.hasStaticShape() ||
7085c0c51a9SNicolas Vasilache         !targetMemRefType.hasStaticShape())
7095c0c51a9SNicolas Vasilache       return matchFailure();
7105c0c51a9SNicolas Vasilache 
7115c0c51a9SNicolas Vasilache     auto llvmSourceDescriptorTy =
712*2bdf33ccSRiver Riddle         operands[0].getType().dyn_cast<LLVM::LLVMType>();
7135c0c51a9SNicolas Vasilache     if (!llvmSourceDescriptorTy || !llvmSourceDescriptorTy.isStructTy())
7145c0c51a9SNicolas Vasilache       return matchFailure();
7155c0c51a9SNicolas Vasilache     MemRefDescriptor sourceMemRef(operands[0]);
7165c0c51a9SNicolas Vasilache 
7175c0c51a9SNicolas Vasilache     auto llvmTargetDescriptorTy = lowering.convertType(targetMemRefType)
7185c0c51a9SNicolas Vasilache                                       .dyn_cast_or_null<LLVM::LLVMType>();
7195c0c51a9SNicolas Vasilache     if (!llvmTargetDescriptorTy || !llvmTargetDescriptorTy.isStructTy())
7205c0c51a9SNicolas Vasilache       return matchFailure();
7215c0c51a9SNicolas Vasilache 
7225c0c51a9SNicolas Vasilache     int64_t offset;
7235c0c51a9SNicolas Vasilache     SmallVector<int64_t, 4> strides;
7245c0c51a9SNicolas Vasilache     auto successStrides =
7255c0c51a9SNicolas Vasilache         getStridesAndOffset(sourceMemRefType, strides, offset);
7265c0c51a9SNicolas Vasilache     bool isContiguous = (strides.back() == 1);
7275c0c51a9SNicolas Vasilache     if (isContiguous) {
7285c0c51a9SNicolas Vasilache       auto sizes = sourceMemRefType.getShape();
7295c0c51a9SNicolas Vasilache       for (int index = 0, e = strides.size() - 2; index < e; ++index) {
7305c0c51a9SNicolas Vasilache         if (strides[index] != strides[index + 1] * sizes[index + 1]) {
7315c0c51a9SNicolas Vasilache           isContiguous = false;
7325c0c51a9SNicolas Vasilache           break;
7335c0c51a9SNicolas Vasilache         }
7345c0c51a9SNicolas Vasilache       }
7355c0c51a9SNicolas Vasilache     }
7365c0c51a9SNicolas Vasilache     // Only contiguous source tensors supported atm.
7375c0c51a9SNicolas Vasilache     if (failed(successStrides) || !isContiguous)
7385c0c51a9SNicolas Vasilache       return matchFailure();
7395c0c51a9SNicolas Vasilache 
7405c0c51a9SNicolas Vasilache     auto int64Ty = LLVM::LLVMType::getInt64Ty(lowering.getDialect());
7415c0c51a9SNicolas Vasilache 
7425c0c51a9SNicolas Vasilache     // Create descriptor.
7435c0c51a9SNicolas Vasilache     auto desc = MemRefDescriptor::undef(rewriter, loc, llvmTargetDescriptorTy);
7445c0c51a9SNicolas Vasilache     Type llvmTargetElementTy = desc.getElementType();
7455c0c51a9SNicolas Vasilache     // Set allocated ptr.
746e62a6956SRiver Riddle     Value allocated = sourceMemRef.allocatedPtr(rewriter, loc);
7475c0c51a9SNicolas Vasilache     allocated =
7485c0c51a9SNicolas Vasilache         rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, allocated);
7495c0c51a9SNicolas Vasilache     desc.setAllocatedPtr(rewriter, loc, allocated);
7505c0c51a9SNicolas Vasilache     // Set aligned ptr.
751e62a6956SRiver Riddle     Value ptr = sourceMemRef.alignedPtr(rewriter, loc);
7525c0c51a9SNicolas Vasilache     ptr = rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, ptr);
7535c0c51a9SNicolas Vasilache     desc.setAlignedPtr(rewriter, loc, ptr);
7545c0c51a9SNicolas Vasilache     // Fill offset 0.
7555c0c51a9SNicolas Vasilache     auto attr = rewriter.getIntegerAttr(rewriter.getIndexType(), 0);
7565c0c51a9SNicolas Vasilache     auto zero = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, attr);
7575c0c51a9SNicolas Vasilache     desc.setOffset(rewriter, loc, zero);
7585c0c51a9SNicolas Vasilache 
7595c0c51a9SNicolas Vasilache     // Fill size and stride descriptors in memref.
7605c0c51a9SNicolas Vasilache     for (auto indexedSize : llvm::enumerate(targetMemRefType.getShape())) {
7615c0c51a9SNicolas Vasilache       int64_t index = indexedSize.index();
7625c0c51a9SNicolas Vasilache       auto sizeAttr =
7635c0c51a9SNicolas Vasilache           rewriter.getIntegerAttr(rewriter.getIndexType(), indexedSize.value());
7645c0c51a9SNicolas Vasilache       auto size = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, sizeAttr);
7655c0c51a9SNicolas Vasilache       desc.setSize(rewriter, loc, index, size);
7665c0c51a9SNicolas Vasilache       auto strideAttr =
7675c0c51a9SNicolas Vasilache           rewriter.getIntegerAttr(rewriter.getIndexType(), strides[index]);
7685c0c51a9SNicolas Vasilache       auto stride = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, strideAttr);
7695c0c51a9SNicolas Vasilache       desc.setStride(rewriter, loc, index, stride);
7705c0c51a9SNicolas Vasilache     }
7715c0c51a9SNicolas Vasilache 
7725c0c51a9SNicolas Vasilache     rewriter.replaceOp(op, {desc});
7735c0c51a9SNicolas Vasilache     return matchSuccess();
7745c0c51a9SNicolas Vasilache   }
7755c0c51a9SNicolas Vasilache };
7765c0c51a9SNicolas Vasilache 
777d9b500d3SAart Bik class VectorPrintOpConversion : public LLVMOpLowering {
778d9b500d3SAart Bik public:
779d9b500d3SAart Bik   explicit VectorPrintOpConversion(MLIRContext *context,
780d9b500d3SAart Bik                                    LLVMTypeConverter &typeConverter)
781d9b500d3SAart Bik       : LLVMOpLowering(vector::PrintOp::getOperationName(), context,
782d9b500d3SAart Bik                        typeConverter) {}
783d9b500d3SAart Bik 
784d9b500d3SAart Bik   // Proof-of-concept lowering implementation that relies on a small
785d9b500d3SAart Bik   // runtime support library, which only needs to provide a few
786d9b500d3SAart Bik   // printing methods (single value for all data types, opening/closing
787d9b500d3SAart Bik   // bracket, comma, newline). The lowering fully unrolls a vector
788d9b500d3SAart Bik   // in terms of these elementary printing operations. The advantage
789d9b500d3SAart Bik   // of this approach is that the library can remain unaware of all
790d9b500d3SAart Bik   // low-level implementation details of vectors while still supporting
791d9b500d3SAart Bik   // output of any shaped and dimensioned vector. Due to full unrolling,
792d9b500d3SAart Bik   // this approach is less suited for very large vectors though.
793d9b500d3SAart Bik   //
794d9b500d3SAart Bik   // TODO(ajcbik): rely solely on libc in future? something else?
795d9b500d3SAart Bik   //
796d9b500d3SAart Bik   PatternMatchResult
797e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
798d9b500d3SAart Bik                   ConversionPatternRewriter &rewriter) const override {
799d9b500d3SAart Bik     auto printOp = cast<vector::PrintOp>(op);
800d9b500d3SAart Bik     auto adaptor = vector::PrintOpOperandAdaptor(operands);
801d9b500d3SAart Bik     Type printType = printOp.getPrintType();
802d9b500d3SAart Bik 
803d9b500d3SAart Bik     if (lowering.convertType(printType) == nullptr)
804d9b500d3SAart Bik       return matchFailure();
805d9b500d3SAart Bik 
806d9b500d3SAart Bik     // Make sure element type has runtime support (currently just Float/Double).
807d9b500d3SAart Bik     VectorType vectorType = printType.dyn_cast<VectorType>();
808d9b500d3SAart Bik     Type eltType = vectorType ? vectorType.getElementType() : printType;
809d9b500d3SAart Bik     int64_t rank = vectorType ? vectorType.getRank() : 0;
810d9b500d3SAart Bik     Operation *printer;
811d9b500d3SAart Bik     if (eltType.isF32())
812d9b500d3SAart Bik       printer = getPrintFloat(op);
813d9b500d3SAart Bik     else if (eltType.isF64())
814d9b500d3SAart Bik       printer = getPrintDouble(op);
815d9b500d3SAart Bik     else
816d9b500d3SAart Bik       return matchFailure();
817d9b500d3SAart Bik 
818d9b500d3SAart Bik     // Unroll vector into elementary print calls.
819d9b500d3SAart Bik     emitRanks(rewriter, op, adaptor.source(), vectorType, printer, rank);
820d9b500d3SAart Bik     emitCall(rewriter, op->getLoc(), getPrintNewline(op));
821d9b500d3SAart Bik     rewriter.eraseOp(op);
822d9b500d3SAart Bik     return matchSuccess();
823d9b500d3SAart Bik   }
824d9b500d3SAart Bik 
825d9b500d3SAart Bik private:
826d9b500d3SAart Bik   void emitRanks(ConversionPatternRewriter &rewriter, Operation *op,
827e62a6956SRiver Riddle                  Value value, VectorType vectorType, Operation *printer,
828d9b500d3SAart Bik                  int64_t rank) const {
829d9b500d3SAart Bik     Location loc = op->getLoc();
830d9b500d3SAart Bik     if (rank == 0) {
831d9b500d3SAart Bik       emitCall(rewriter, loc, printer, value);
832d9b500d3SAart Bik       return;
833d9b500d3SAart Bik     }
834d9b500d3SAart Bik 
835d9b500d3SAart Bik     emitCall(rewriter, loc, getPrintOpen(op));
836d9b500d3SAart Bik     Operation *printComma = getPrintComma(op);
837d9b500d3SAart Bik     int64_t dim = vectorType.getDimSize(0);
838d9b500d3SAart Bik     for (int64_t d = 0; d < dim; ++d) {
839d9b500d3SAart Bik       auto reducedType =
840d9b500d3SAart Bik           rank > 1 ? reducedVectorTypeFront(vectorType) : nullptr;
841d9b500d3SAart Bik       auto llvmType = lowering.convertType(
842d9b500d3SAart Bik           rank > 1 ? reducedType : vectorType.getElementType());
843e62a6956SRiver Riddle       Value nestedVal =
844d9b500d3SAart Bik           extractOne(rewriter, lowering, loc, value, llvmType, rank, d);
845d9b500d3SAart Bik       emitRanks(rewriter, op, nestedVal, reducedType, printer, rank - 1);
846d9b500d3SAart Bik       if (d != dim - 1)
847d9b500d3SAart Bik         emitCall(rewriter, loc, printComma);
848d9b500d3SAart Bik     }
849d9b500d3SAart Bik     emitCall(rewriter, loc, getPrintClose(op));
850d9b500d3SAart Bik   }
851d9b500d3SAart Bik 
852d9b500d3SAart Bik   // Helper to emit a call.
853d9b500d3SAart Bik   static void emitCall(ConversionPatternRewriter &rewriter, Location loc,
854d9b500d3SAart Bik                        Operation *ref, ValueRange params = ValueRange()) {
855d9b500d3SAart Bik     rewriter.create<LLVM::CallOp>(loc, ArrayRef<Type>{},
856d9b500d3SAart Bik                                   rewriter.getSymbolRefAttr(ref), params);
857d9b500d3SAart Bik   }
858d9b500d3SAart Bik 
859d9b500d3SAart Bik   // Helper for printer method declaration (first hit) and lookup.
860d9b500d3SAart Bik   static Operation *getPrint(Operation *op, LLVM::LLVMDialect *dialect,
861d9b500d3SAart Bik                              StringRef name, ArrayRef<LLVM::LLVMType> params) {
862d9b500d3SAart Bik     auto module = op->getParentOfType<ModuleOp>();
863d9b500d3SAart Bik     auto func = module.lookupSymbol<LLVM::LLVMFuncOp>(name);
864d9b500d3SAart Bik     if (func)
865d9b500d3SAart Bik       return func;
866d9b500d3SAart Bik     OpBuilder moduleBuilder(module.getBodyRegion());
867d9b500d3SAart Bik     return moduleBuilder.create<LLVM::LLVMFuncOp>(
868d9b500d3SAart Bik         op->getLoc(), name,
869d9b500d3SAart Bik         LLVM::LLVMType::getFunctionTy(LLVM::LLVMType::getVoidTy(dialect),
870d9b500d3SAart Bik                                       params, /*isVarArg=*/false));
871d9b500d3SAart Bik   }
872d9b500d3SAart Bik 
873d9b500d3SAart Bik   // Helpers for method names.
874d9b500d3SAart Bik   Operation *getPrintFloat(Operation *op) const {
875d9b500d3SAart Bik     LLVM::LLVMDialect *dialect = lowering.getDialect();
876d9b500d3SAart Bik     return getPrint(op, dialect, "print_f32",
877d9b500d3SAart Bik                     LLVM::LLVMType::getFloatTy(dialect));
878d9b500d3SAart Bik   }
879d9b500d3SAart Bik   Operation *getPrintDouble(Operation *op) const {
880d9b500d3SAart Bik     LLVM::LLVMDialect *dialect = lowering.getDialect();
881d9b500d3SAart Bik     return getPrint(op, dialect, "print_f64",
882d9b500d3SAart Bik                     LLVM::LLVMType::getDoubleTy(dialect));
883d9b500d3SAart Bik   }
884d9b500d3SAart Bik   Operation *getPrintOpen(Operation *op) const {
885d9b500d3SAart Bik     return getPrint(op, lowering.getDialect(), "print_open", {});
886d9b500d3SAart Bik   }
887d9b500d3SAart Bik   Operation *getPrintClose(Operation *op) const {
888d9b500d3SAart Bik     return getPrint(op, lowering.getDialect(), "print_close", {});
889d9b500d3SAart Bik   }
890d9b500d3SAart Bik   Operation *getPrintComma(Operation *op) const {
891d9b500d3SAart Bik     return getPrint(op, lowering.getDialect(), "print_comma", {});
892d9b500d3SAart Bik   }
893d9b500d3SAart Bik   Operation *getPrintNewline(Operation *op) const {
894d9b500d3SAart Bik     return getPrint(op, lowering.getDialect(), "print_newline", {});
895d9b500d3SAart Bik   }
896d9b500d3SAart Bik };
897d9b500d3SAart Bik 
89865678d93SNicolas Vasilache /// Progressive lowering of StridedSliceOp to either:
89965678d93SNicolas Vasilache ///   1. extractelement + insertelement for the 1-D case
90065678d93SNicolas Vasilache ///   2. extract + optional strided_slice + insert for the n-D case.
9012d515e49SNicolas Vasilache class VectorStridedSliceOpConversion : public OpRewritePattern<StridedSliceOp> {
90265678d93SNicolas Vasilache public:
90365678d93SNicolas Vasilache   using OpRewritePattern<StridedSliceOp>::OpRewritePattern;
90465678d93SNicolas Vasilache 
90565678d93SNicolas Vasilache   PatternMatchResult matchAndRewrite(StridedSliceOp op,
90665678d93SNicolas Vasilache                                      PatternRewriter &rewriter) const override {
90765678d93SNicolas Vasilache     auto dstType = op.getResult().getType().cast<VectorType>();
90865678d93SNicolas Vasilache 
90965678d93SNicolas Vasilache     assert(!op.offsets().getValue().empty() && "Unexpected empty offsets");
91065678d93SNicolas Vasilache 
91165678d93SNicolas Vasilache     int64_t offset =
91265678d93SNicolas Vasilache         op.offsets().getValue().front().cast<IntegerAttr>().getInt();
91365678d93SNicolas Vasilache     int64_t size = op.sizes().getValue().front().cast<IntegerAttr>().getInt();
91465678d93SNicolas Vasilache     int64_t stride =
91565678d93SNicolas Vasilache         op.strides().getValue().front().cast<IntegerAttr>().getInt();
91665678d93SNicolas Vasilache 
91765678d93SNicolas Vasilache     auto loc = op.getLoc();
91865678d93SNicolas Vasilache     auto elemType = dstType.getElementType();
91965678d93SNicolas Vasilache     assert(elemType.isIntOrIndexOrFloat());
92065678d93SNicolas Vasilache     Value zero = rewriter.create<ConstantOp>(loc, elemType,
92165678d93SNicolas Vasilache                                              rewriter.getZeroAttr(elemType));
92265678d93SNicolas Vasilache     Value res = rewriter.create<SplatOp>(loc, dstType, zero);
92365678d93SNicolas Vasilache     for (int64_t off = offset, e = offset + size * stride, idx = 0; off < e;
92465678d93SNicolas Vasilache          off += stride, ++idx) {
92565678d93SNicolas Vasilache       Value extracted = extractOne(rewriter, loc, op.vector(), off);
92665678d93SNicolas Vasilache       if (op.offsets().getValue().size() > 1) {
92765678d93SNicolas Vasilache         StridedSliceOp stridedSliceOp = rewriter.create<StridedSliceOp>(
92865678d93SNicolas Vasilache             loc, extracted, getI64SubArray(op.offsets(), /* dropFront=*/1),
92965678d93SNicolas Vasilache             getI64SubArray(op.sizes(), /* dropFront=*/1),
93065678d93SNicolas Vasilache             getI64SubArray(op.strides(), /* dropFront=*/1));
93165678d93SNicolas Vasilache         // Call matchAndRewrite recursively from within the pattern. This
93265678d93SNicolas Vasilache         // circumvents the current limitation that a given pattern cannot
93365678d93SNicolas Vasilache         // be called multiple times by the PatternRewrite infrastructure (to
93465678d93SNicolas Vasilache         // avoid infinite recursion, but in this case, infinite recursion
93565678d93SNicolas Vasilache         // cannot happen because the rank is strictly decreasing).
93665678d93SNicolas Vasilache         // TODO(rriddle, nicolasvasilache) Implement something like a hook for
93765678d93SNicolas Vasilache         // a potential function that must decrease and allow the same pattern
93865678d93SNicolas Vasilache         // multiple times.
93965678d93SNicolas Vasilache         auto success = matchAndRewrite(stridedSliceOp, rewriter);
94065678d93SNicolas Vasilache         (void)success;
94165678d93SNicolas Vasilache         assert(success && "Unexpected failure");
94265678d93SNicolas Vasilache         extracted = stridedSliceOp;
94365678d93SNicolas Vasilache       }
94465678d93SNicolas Vasilache       res = insertOne(rewriter, loc, extracted, res, idx);
94565678d93SNicolas Vasilache     }
94665678d93SNicolas Vasilache     rewriter.replaceOp(op, {res});
94765678d93SNicolas Vasilache     return matchSuccess();
94865678d93SNicolas Vasilache   }
94965678d93SNicolas Vasilache };
95065678d93SNicolas Vasilache 
9515c0c51a9SNicolas Vasilache /// Populate the given list with patterns that convert from Vector to LLVM.
9525c0c51a9SNicolas Vasilache void mlir::populateVectorToLLVMConversionPatterns(
9535c0c51a9SNicolas Vasilache     LLVMTypeConverter &converter, OwningRewritePatternList &patterns) {
95465678d93SNicolas Vasilache   MLIRContext *ctx = converter.getDialect()->getContext();
9552d515e49SNicolas Vasilache   patterns.insert<VectorInsertStridedSliceOpDifferentRankRewritePattern,
9562d515e49SNicolas Vasilache                   VectorInsertStridedSliceOpSameRankRewritePattern,
9572d515e49SNicolas Vasilache                   VectorStridedSliceOpConversion>(ctx);
9581c81adf3SAart Bik   patterns.insert<VectorBroadcastOpConversion, VectorShuffleOpConversion,
959cd5dab8aSAart Bik                   VectorExtractElementOpConversion, VectorExtractOpConversion,
960cd5dab8aSAart Bik                   VectorInsertElementOpConversion, VectorInsertOpConversion,
961d9b500d3SAart Bik                   VectorOuterProductOpConversion, VectorTypeCastOpConversion,
96265678d93SNicolas Vasilache                   VectorPrintOpConversion>(ctx, converter);
9635c0c51a9SNicolas Vasilache }
9645c0c51a9SNicolas Vasilache 
9655c0c51a9SNicolas Vasilache namespace {
9665c0c51a9SNicolas Vasilache struct LowerVectorToLLVMPass : public ModulePass<LowerVectorToLLVMPass> {
9675c0c51a9SNicolas Vasilache   void runOnModule() override;
9685c0c51a9SNicolas Vasilache };
9695c0c51a9SNicolas Vasilache } // namespace
9705c0c51a9SNicolas Vasilache 
9715c0c51a9SNicolas Vasilache void LowerVectorToLLVMPass::runOnModule() {
9725c0c51a9SNicolas Vasilache   // Convert to the LLVM IR dialect using the converter defined above.
9735c0c51a9SNicolas Vasilache   OwningRewritePatternList patterns;
9745c0c51a9SNicolas Vasilache   LLVMTypeConverter converter(&getContext());
9755c0c51a9SNicolas Vasilache   populateVectorToLLVMConversionPatterns(converter, patterns);
9765c0c51a9SNicolas Vasilache   populateStdToLLVMConversionPatterns(converter, patterns);
9775c0c51a9SNicolas Vasilache 
9785c0c51a9SNicolas Vasilache   ConversionTarget target(getContext());
9795c0c51a9SNicolas Vasilache   target.addLegalDialect<LLVM::LLVMDialect>();
9805c0c51a9SNicolas Vasilache   target.addDynamicallyLegalOp<FuncOp>(
9815c0c51a9SNicolas Vasilache       [&](FuncOp op) { return converter.isSignatureLegal(op.getType()); });
9825c0c51a9SNicolas Vasilache   if (failed(
9835c0c51a9SNicolas Vasilache           applyPartialConversion(getModule(), target, patterns, &converter))) {
9845c0c51a9SNicolas Vasilache     signalPassFailure();
9855c0c51a9SNicolas Vasilache   }
9865c0c51a9SNicolas Vasilache }
9875c0c51a9SNicolas Vasilache 
9885c0c51a9SNicolas Vasilache OpPassBase<ModuleOp> *mlir::createLowerVectorToLLVMPass() {
9895c0c51a9SNicolas Vasilache   return new LowerVectorToLLVMPass();
9905c0c51a9SNicolas Vasilache }
9915c0c51a9SNicolas Vasilache 
9925c0c51a9SNicolas Vasilache static PassRegistration<LowerVectorToLLVMPass>
9935c0c51a9SNicolas Vasilache     pass("convert-vector-to-llvm",
9945c0c51a9SNicolas Vasilache          "Lower the operations from the vector dialect into the LLVM dialect");
995