xref: /llvm-project/mlir/lib/Conversion/VectorToLLVM/ConvertVectorToLLVM.cpp (revision 0d924700a610c59555ede59325d3c51515679903)
1 //===- VectorToLLVM.cpp - Conversion from Vector to the LLVM dialect ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "mlir/Conversion/VectorToLLVM/ConvertVectorToLLVM.h"
10 
11 #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVM.h"
12 #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h"
13 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
14 #include "mlir/Dialect/StandardOps/IR/Ops.h"
15 #include "mlir/Dialect/VectorOps/VectorOps.h"
16 #include "mlir/IR/Attributes.h"
17 #include "mlir/IR/Builders.h"
18 #include "mlir/IR/MLIRContext.h"
19 #include "mlir/IR/Module.h"
20 #include "mlir/IR/Operation.h"
21 #include "mlir/IR/PatternMatch.h"
22 #include "mlir/IR/StandardTypes.h"
23 #include "mlir/IR/Types.h"
24 #include "mlir/Pass/Pass.h"
25 #include "mlir/Pass/PassManager.h"
26 #include "mlir/Transforms/DialectConversion.h"
27 #include "mlir/Transforms/Passes.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/Allocator.h"
32 #include "llvm/Support/ErrorHandling.h"
33 
34 using namespace mlir;
35 using namespace mlir::vector;
36 
37 template <typename T>
38 static LLVM::LLVMType getPtrToElementType(T containerType,
39                                           LLVMTypeConverter &typeConverter) {
40   return typeConverter.convertType(containerType.getElementType())
41       .template cast<LLVM::LLVMType>()
42       .getPointerTo();
43 }
44 
45 // Helper to reduce vector type by one rank at front.
46 static VectorType reducedVectorTypeFront(VectorType tp) {
47   assert((tp.getRank() > 1) && "unlowerable vector type");
48   return VectorType::get(tp.getShape().drop_front(), tp.getElementType());
49 }
50 
51 // Helper to reduce vector type by *all* but one rank at back.
52 static VectorType reducedVectorTypeBack(VectorType tp) {
53   assert((tp.getRank() > 1) && "unlowerable vector type");
54   return VectorType::get(tp.getShape().take_back(), tp.getElementType());
55 }
56 
57 // Helper that picks the proper sequence for inserting.
58 static Value insertOne(ConversionPatternRewriter &rewriter,
59                        LLVMTypeConverter &typeConverter, Location loc,
60                        Value val1, Value val2, Type llvmType, int64_t rank,
61                        int64_t pos) {
62   if (rank == 1) {
63     auto idxType = rewriter.getIndexType();
64     auto constant = rewriter.create<LLVM::ConstantOp>(
65         loc, typeConverter.convertType(idxType),
66         rewriter.getIntegerAttr(idxType, pos));
67     return rewriter.create<LLVM::InsertElementOp>(loc, llvmType, val1, val2,
68                                                   constant);
69   }
70   return rewriter.create<LLVM::InsertValueOp>(loc, llvmType, val1, val2,
71                                               rewriter.getI64ArrayAttr(pos));
72 }
73 
74 // Helper that picks the proper sequence for inserting.
75 static Value insertOne(PatternRewriter &rewriter, Location loc, Value from,
76                        Value into, int64_t offset) {
77   auto vectorType = into.getType().cast<VectorType>();
78   if (vectorType.getRank() > 1)
79     return rewriter.create<InsertOp>(loc, from, into, offset);
80   return rewriter.create<vector::InsertElementOp>(
81       loc, vectorType, from, into,
82       rewriter.create<ConstantIndexOp>(loc, offset));
83 }
84 
85 // Helper that picks the proper sequence for extracting.
86 static Value extractOne(ConversionPatternRewriter &rewriter,
87                         LLVMTypeConverter &typeConverter, Location loc,
88                         Value val, Type llvmType, int64_t rank, int64_t pos) {
89   if (rank == 1) {
90     auto idxType = rewriter.getIndexType();
91     auto constant = rewriter.create<LLVM::ConstantOp>(
92         loc, typeConverter.convertType(idxType),
93         rewriter.getIntegerAttr(idxType, pos));
94     return rewriter.create<LLVM::ExtractElementOp>(loc, llvmType, val,
95                                                    constant);
96   }
97   return rewriter.create<LLVM::ExtractValueOp>(loc, llvmType, val,
98                                                rewriter.getI64ArrayAttr(pos));
99 }
100 
101 // Helper that picks the proper sequence for extracting.
102 static Value extractOne(PatternRewriter &rewriter, Location loc, Value vector,
103                         int64_t offset) {
104   auto vectorType = vector.getType().cast<VectorType>();
105   if (vectorType.getRank() > 1)
106     return rewriter.create<ExtractOp>(loc, vector, offset);
107   return rewriter.create<vector::ExtractElementOp>(
108       loc, vectorType.getElementType(), vector,
109       rewriter.create<ConstantIndexOp>(loc, offset));
110 }
111 
112 // Helper that returns a subset of `arrayAttr` as a vector of int64_t.
113 // TODO(rriddle): Better support for attribute subtype forwarding + slicing.
114 static SmallVector<int64_t, 4> getI64SubArray(ArrayAttr arrayAttr,
115                                               unsigned dropFront = 0,
116                                               unsigned dropBack = 0) {
117   assert(arrayAttr.size() > dropFront + dropBack && "Out of bounds");
118   auto range = arrayAttr.getAsRange<IntegerAttr>();
119   SmallVector<int64_t, 4> res;
120   res.reserve(arrayAttr.size() - dropFront - dropBack);
121   for (auto it = range.begin() + dropFront, eit = range.end() - dropBack;
122        it != eit; ++it)
123     res.push_back((*it).getValue().getSExtValue());
124   return res;
125 }
126 
127 namespace {
128 
129 class VectorBroadcastOpConversion : public ConvertToLLVMPattern {
130 public:
131   explicit VectorBroadcastOpConversion(MLIRContext *context,
132                                        LLVMTypeConverter &typeConverter)
133       : ConvertToLLVMPattern(vector::BroadcastOp::getOperationName(), context,
134                              typeConverter) {}
135 
136   PatternMatchResult
137   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
138                   ConversionPatternRewriter &rewriter) const override {
139     auto broadcastOp = cast<vector::BroadcastOp>(op);
140     VectorType dstVectorType = broadcastOp.getVectorType();
141     if (typeConverter.convertType(dstVectorType) == nullptr)
142       return matchFailure();
143     // Rewrite when the full vector type can be lowered (which
144     // implies all 'reduced' types can be lowered too).
145     auto adaptor = vector::BroadcastOpOperandAdaptor(operands);
146     VectorType srcVectorType =
147         broadcastOp.getSourceType().dyn_cast<VectorType>();
148     rewriter.replaceOp(
149         op, expandRanks(adaptor.source(), // source value to be expanded
150                         op->getLoc(),     // location of original broadcast
151                         srcVectorType, dstVectorType, rewriter));
152     return matchSuccess();
153   }
154 
155 private:
156   // Expands the given source value over all the ranks, as defined
157   // by the source and destination type (a null source type denotes
158   // expansion from a scalar value into a vector).
159   //
160   // TODO(ajcbik): consider replacing this one-pattern lowering
161   //               with a two-pattern lowering using other vector
162   //               ops once all insert/extract/shuffle operations
163   //               are available with lowering implementation.
164   //
165   Value expandRanks(Value value, Location loc, VectorType srcVectorType,
166                     VectorType dstVectorType,
167                     ConversionPatternRewriter &rewriter) const {
168     assert((dstVectorType != nullptr) && "invalid result type in broadcast");
169     // Determine rank of source and destination.
170     int64_t srcRank = srcVectorType ? srcVectorType.getRank() : 0;
171     int64_t dstRank = dstVectorType.getRank();
172     int64_t curDim = dstVectorType.getDimSize(0);
173     if (srcRank < dstRank)
174       // Duplicate this rank.
175       return duplicateOneRank(value, loc, srcVectorType, dstVectorType, dstRank,
176                               curDim, rewriter);
177     // If all trailing dimensions are the same, the broadcast consists of
178     // simply passing through the source value and we are done. Otherwise,
179     // any non-matching dimension forces a stretch along this rank.
180     assert((srcVectorType != nullptr) && (srcRank > 0) &&
181            (srcRank == dstRank) && "invalid rank in broadcast");
182     for (int64_t r = 0; r < dstRank; r++) {
183       if (srcVectorType.getDimSize(r) != dstVectorType.getDimSize(r)) {
184         return stretchOneRank(value, loc, srcVectorType, dstVectorType, dstRank,
185                               curDim, rewriter);
186       }
187     }
188     return value;
189   }
190 
191   // Picks the best way to duplicate a single rank. For the 1-D case, a
192   // single insert-elt/shuffle is the most efficient expansion. For higher
193   // dimensions, however, we need dim x insert-values on a new broadcast
194   // with one less leading dimension, which will be lowered "recursively"
195   // to matching LLVM IR.
196   // For example:
197   //   v = broadcast s : f32 to vector<4x2xf32>
198   // becomes:
199   //   x = broadcast s : f32 to vector<2xf32>
200   //   v = [x,x,x,x]
201   // becomes:
202   //   x = [s,s]
203   //   v = [x,x,x,x]
204   Value duplicateOneRank(Value value, Location loc, VectorType srcVectorType,
205                          VectorType dstVectorType, int64_t rank, int64_t dim,
206                          ConversionPatternRewriter &rewriter) const {
207     Type llvmType = typeConverter.convertType(dstVectorType);
208     assert((llvmType != nullptr) && "unlowerable vector type");
209     if (rank == 1) {
210       Value undef = rewriter.create<LLVM::UndefOp>(loc, llvmType);
211       Value expand = insertOne(rewriter, typeConverter, loc, undef, value,
212                                llvmType, rank, 0);
213       SmallVector<int32_t, 4> zeroValues(dim, 0);
214       return rewriter.create<LLVM::ShuffleVectorOp>(
215           loc, expand, undef, rewriter.getI32ArrayAttr(zeroValues));
216     }
217     Value expand = expandRanks(value, loc, srcVectorType,
218                                reducedVectorTypeFront(dstVectorType), rewriter);
219     Value result = rewriter.create<LLVM::UndefOp>(loc, llvmType);
220     for (int64_t d = 0; d < dim; ++d) {
221       result = insertOne(rewriter, typeConverter, loc, result, expand, llvmType,
222                          rank, d);
223     }
224     return result;
225   }
226 
227   // Picks the best way to stretch a single rank. For the 1-D case, a
228   // single insert-elt/shuffle is the most efficient expansion when at
229   // a stretch. Otherwise, every dimension needs to be expanded
230   // individually and individually inserted in the resulting vector.
231   // For example:
232   //   v = broadcast w : vector<4x1x2xf32> to vector<4x2x2xf32>
233   // becomes:
234   //   a = broadcast w[0] : vector<1x2xf32> to vector<2x2xf32>
235   //   b = broadcast w[1] : vector<1x2xf32> to vector<2x2xf32>
236   //   c = broadcast w[2] : vector<1x2xf32> to vector<2x2xf32>
237   //   d = broadcast w[3] : vector<1x2xf32> to vector<2x2xf32>
238   //   v = [a,b,c,d]
239   // becomes:
240   //   x = broadcast w[0][0] : vector<2xf32> to vector <2x2xf32>
241   //   y = broadcast w[1][0] : vector<2xf32> to vector <2x2xf32>
242   //   a = [x, y]
243   //   etc.
244   Value stretchOneRank(Value value, Location loc, VectorType srcVectorType,
245                        VectorType dstVectorType, int64_t rank, int64_t dim,
246                        ConversionPatternRewriter &rewriter) const {
247     Type llvmType = typeConverter.convertType(dstVectorType);
248     assert((llvmType != nullptr) && "unlowerable vector type");
249     Value result = rewriter.create<LLVM::UndefOp>(loc, llvmType);
250     bool atStretch = dim != srcVectorType.getDimSize(0);
251     if (rank == 1) {
252       assert(atStretch);
253       Type redLlvmType =
254           typeConverter.convertType(dstVectorType.getElementType());
255       Value one =
256           extractOne(rewriter, typeConverter, loc, value, redLlvmType, rank, 0);
257       Value expand = insertOne(rewriter, typeConverter, loc, result, one,
258                                llvmType, rank, 0);
259       SmallVector<int32_t, 4> zeroValues(dim, 0);
260       return rewriter.create<LLVM::ShuffleVectorOp>(
261           loc, expand, result, rewriter.getI32ArrayAttr(zeroValues));
262     }
263     VectorType redSrcType = reducedVectorTypeFront(srcVectorType);
264     VectorType redDstType = reducedVectorTypeFront(dstVectorType);
265     Type redLlvmType = typeConverter.convertType(redSrcType);
266     for (int64_t d = 0; d < dim; ++d) {
267       int64_t pos = atStretch ? 0 : d;
268       Value one = extractOne(rewriter, typeConverter, loc, value, redLlvmType,
269                              rank, pos);
270       Value expand = expandRanks(one, loc, redSrcType, redDstType, rewriter);
271       result = insertOne(rewriter, typeConverter, loc, result, expand, llvmType,
272                          rank, d);
273     }
274     return result;
275   }
276 };
277 
278 class VectorReductionOpConversion : public ConvertToLLVMPattern {
279 public:
280   explicit VectorReductionOpConversion(MLIRContext *context,
281                                        LLVMTypeConverter &typeConverter)
282       : ConvertToLLVMPattern(vector::ReductionOp::getOperationName(), context,
283                              typeConverter) {}
284 
285   PatternMatchResult
286   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
287                   ConversionPatternRewriter &rewriter) const override {
288     auto reductionOp = cast<vector::ReductionOp>(op);
289     auto kind = reductionOp.kind();
290     Type eltType = reductionOp.dest().getType();
291     Type llvmType = typeConverter.convertType(eltType);
292     if (eltType.isSignlessInteger(32) || eltType.isSignlessInteger(64)) {
293       // Integer reductions: add/mul/min/max/and/or/xor.
294       if (kind == "add")
295         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_add>(
296             op, llvmType, operands[0]);
297       else if (kind == "mul")
298         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_mul>(
299             op, llvmType, operands[0]);
300       else if (kind == "min")
301         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_smin>(
302             op, llvmType, operands[0]);
303       else if (kind == "max")
304         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_smax>(
305             op, llvmType, operands[0]);
306       else if (kind == "and")
307         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_and>(
308             op, llvmType, operands[0]);
309       else if (kind == "or")
310         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_or>(
311             op, llvmType, operands[0]);
312       else if (kind == "xor")
313         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_xor>(
314             op, llvmType, operands[0]);
315       else
316         return matchFailure();
317       return matchSuccess();
318 
319     } else if (eltType.isF32() || eltType.isF64()) {
320       // Floating-point reductions: add/mul/min/max
321       if (kind == "add") {
322         // Optional accumulator (or zero).
323         Value acc = operands.size() > 1 ? operands[1]
324                                         : rewriter.create<LLVM::ConstantOp>(
325                                               op->getLoc(), llvmType,
326                                               rewriter.getZeroAttr(eltType));
327         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_v2_fadd>(
328             op, llvmType, acc, operands[0]);
329       } else if (kind == "mul") {
330         // Optional accumulator (or one).
331         Value acc = operands.size() > 1
332                         ? operands[1]
333                         : rewriter.create<LLVM::ConstantOp>(
334                               op->getLoc(), llvmType,
335                               rewriter.getFloatAttr(eltType, 1.0));
336         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_v2_fmul>(
337             op, llvmType, acc, operands[0]);
338       } else if (kind == "min")
339         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_fmin>(
340             op, llvmType, operands[0]);
341       else if (kind == "max")
342         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_fmax>(
343             op, llvmType, operands[0]);
344       else
345         return matchFailure();
346       return matchSuccess();
347     }
348     return matchFailure();
349   }
350 };
351 
352 class VectorShuffleOpConversion : public ConvertToLLVMPattern {
353 public:
354   explicit VectorShuffleOpConversion(MLIRContext *context,
355                                      LLVMTypeConverter &typeConverter)
356       : ConvertToLLVMPattern(vector::ShuffleOp::getOperationName(), context,
357                              typeConverter) {}
358 
359   PatternMatchResult
360   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
361                   ConversionPatternRewriter &rewriter) const override {
362     auto loc = op->getLoc();
363     auto adaptor = vector::ShuffleOpOperandAdaptor(operands);
364     auto shuffleOp = cast<vector::ShuffleOp>(op);
365     auto v1Type = shuffleOp.getV1VectorType();
366     auto v2Type = shuffleOp.getV2VectorType();
367     auto vectorType = shuffleOp.getVectorType();
368     Type llvmType = typeConverter.convertType(vectorType);
369     auto maskArrayAttr = shuffleOp.mask();
370 
371     // Bail if result type cannot be lowered.
372     if (!llvmType)
373       return matchFailure();
374 
375     // Get rank and dimension sizes.
376     int64_t rank = vectorType.getRank();
377     assert(v1Type.getRank() == rank);
378     assert(v2Type.getRank() == rank);
379     int64_t v1Dim = v1Type.getDimSize(0);
380 
381     // For rank 1, where both operands have *exactly* the same vector type,
382     // there is direct shuffle support in LLVM. Use it!
383     if (rank == 1 && v1Type == v2Type) {
384       Value shuffle = rewriter.create<LLVM::ShuffleVectorOp>(
385           loc, adaptor.v1(), adaptor.v2(), maskArrayAttr);
386       rewriter.replaceOp(op, shuffle);
387       return matchSuccess();
388     }
389 
390     // For all other cases, insert the individual values individually.
391     Value insert = rewriter.create<LLVM::UndefOp>(loc, llvmType);
392     int64_t insPos = 0;
393     for (auto en : llvm::enumerate(maskArrayAttr)) {
394       int64_t extPos = en.value().cast<IntegerAttr>().getInt();
395       Value value = adaptor.v1();
396       if (extPos >= v1Dim) {
397         extPos -= v1Dim;
398         value = adaptor.v2();
399       }
400       Value extract = extractOne(rewriter, typeConverter, loc, value, llvmType,
401                                  rank, extPos);
402       insert = insertOne(rewriter, typeConverter, loc, insert, extract,
403                          llvmType, rank, insPos++);
404     }
405     rewriter.replaceOp(op, insert);
406     return matchSuccess();
407   }
408 };
409 
410 class VectorExtractElementOpConversion : public ConvertToLLVMPattern {
411 public:
412   explicit VectorExtractElementOpConversion(MLIRContext *context,
413                                             LLVMTypeConverter &typeConverter)
414       : ConvertToLLVMPattern(vector::ExtractElementOp::getOperationName(),
415                              context, typeConverter) {}
416 
417   PatternMatchResult
418   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
419                   ConversionPatternRewriter &rewriter) const override {
420     auto adaptor = vector::ExtractElementOpOperandAdaptor(operands);
421     auto extractEltOp = cast<vector::ExtractElementOp>(op);
422     auto vectorType = extractEltOp.getVectorType();
423     auto llvmType = typeConverter.convertType(vectorType.getElementType());
424 
425     // Bail if result type cannot be lowered.
426     if (!llvmType)
427       return matchFailure();
428 
429     rewriter.replaceOpWithNewOp<LLVM::ExtractElementOp>(
430         op, llvmType, adaptor.vector(), adaptor.position());
431     return matchSuccess();
432   }
433 };
434 
435 class VectorExtractOpConversion : public ConvertToLLVMPattern {
436 public:
437   explicit VectorExtractOpConversion(MLIRContext *context,
438                                      LLVMTypeConverter &typeConverter)
439       : ConvertToLLVMPattern(vector::ExtractOp::getOperationName(), context,
440                              typeConverter) {}
441 
442   PatternMatchResult
443   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
444                   ConversionPatternRewriter &rewriter) const override {
445     auto loc = op->getLoc();
446     auto adaptor = vector::ExtractOpOperandAdaptor(operands);
447     auto extractOp = cast<vector::ExtractOp>(op);
448     auto vectorType = extractOp.getVectorType();
449     auto resultType = extractOp.getResult().getType();
450     auto llvmResultType = typeConverter.convertType(resultType);
451     auto positionArrayAttr = extractOp.position();
452 
453     // Bail if result type cannot be lowered.
454     if (!llvmResultType)
455       return matchFailure();
456 
457     // One-shot extraction of vector from array (only requires extractvalue).
458     if (resultType.isa<VectorType>()) {
459       Value extracted = rewriter.create<LLVM::ExtractValueOp>(
460           loc, llvmResultType, adaptor.vector(), positionArrayAttr);
461       rewriter.replaceOp(op, extracted);
462       return matchSuccess();
463     }
464 
465     // Potential extraction of 1-D vector from array.
466     auto *context = op->getContext();
467     Value extracted = adaptor.vector();
468     auto positionAttrs = positionArrayAttr.getValue();
469     if (positionAttrs.size() > 1) {
470       auto oneDVectorType = reducedVectorTypeBack(vectorType);
471       auto nMinusOnePositionAttrs =
472           ArrayAttr::get(positionAttrs.drop_back(), context);
473       extracted = rewriter.create<LLVM::ExtractValueOp>(
474           loc, typeConverter.convertType(oneDVectorType), extracted,
475           nMinusOnePositionAttrs);
476     }
477 
478     // Remaining extraction of element from 1-D LLVM vector
479     auto position = positionAttrs.back().cast<IntegerAttr>();
480     auto i64Type = LLVM::LLVMType::getInt64Ty(typeConverter.getDialect());
481     auto constant = rewriter.create<LLVM::ConstantOp>(loc, i64Type, position);
482     extracted =
483         rewriter.create<LLVM::ExtractElementOp>(loc, extracted, constant);
484     rewriter.replaceOp(op, extracted);
485 
486     return matchSuccess();
487   }
488 };
489 
490 /// Conversion pattern that turns a vector.fma on a 1-D vector
491 /// into an llvm.intr.fmuladd. This is a trivial 1-1 conversion.
492 /// This does not match vectors of n >= 2 rank.
493 ///
494 /// Example:
495 /// ```
496 ///  vector.fma %a, %a, %a : vector<8xf32>
497 /// ```
498 /// is converted to:
499 /// ```
500 ///  llvm.intr.fma %va, %va, %va:
501 ///    (!llvm<"<8 x float>">, !llvm<"<8 x float>">, !llvm<"<8 x float>">)
502 ///    -> !llvm<"<8 x float>">
503 /// ```
504 class VectorFMAOp1DConversion : public ConvertToLLVMPattern {
505 public:
506   explicit VectorFMAOp1DConversion(MLIRContext *context,
507                                    LLVMTypeConverter &typeConverter)
508       : ConvertToLLVMPattern(vector::FMAOp::getOperationName(), context,
509                              typeConverter) {}
510 
511   PatternMatchResult
512   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
513                   ConversionPatternRewriter &rewriter) const override {
514     auto adaptor = vector::FMAOpOperandAdaptor(operands);
515     vector::FMAOp fmaOp = cast<vector::FMAOp>(op);
516     VectorType vType = fmaOp.getVectorType();
517     if (vType.getRank() != 1)
518       return matchFailure();
519     rewriter.replaceOpWithNewOp<LLVM::FMAOp>(op, adaptor.lhs(), adaptor.rhs(),
520                                              adaptor.acc());
521     return matchSuccess();
522   }
523 };
524 
525 class VectorInsertElementOpConversion : public ConvertToLLVMPattern {
526 public:
527   explicit VectorInsertElementOpConversion(MLIRContext *context,
528                                            LLVMTypeConverter &typeConverter)
529       : ConvertToLLVMPattern(vector::InsertElementOp::getOperationName(),
530                              context, typeConverter) {}
531 
532   PatternMatchResult
533   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
534                   ConversionPatternRewriter &rewriter) const override {
535     auto adaptor = vector::InsertElementOpOperandAdaptor(operands);
536     auto insertEltOp = cast<vector::InsertElementOp>(op);
537     auto vectorType = insertEltOp.getDestVectorType();
538     auto llvmType = typeConverter.convertType(vectorType);
539 
540     // Bail if result type cannot be lowered.
541     if (!llvmType)
542       return matchFailure();
543 
544     rewriter.replaceOpWithNewOp<LLVM::InsertElementOp>(
545         op, llvmType, adaptor.dest(), adaptor.source(), adaptor.position());
546     return matchSuccess();
547   }
548 };
549 
550 class VectorInsertOpConversion : public ConvertToLLVMPattern {
551 public:
552   explicit VectorInsertOpConversion(MLIRContext *context,
553                                     LLVMTypeConverter &typeConverter)
554       : ConvertToLLVMPattern(vector::InsertOp::getOperationName(), context,
555                              typeConverter) {}
556 
557   PatternMatchResult
558   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
559                   ConversionPatternRewriter &rewriter) const override {
560     auto loc = op->getLoc();
561     auto adaptor = vector::InsertOpOperandAdaptor(operands);
562     auto insertOp = cast<vector::InsertOp>(op);
563     auto sourceType = insertOp.getSourceType();
564     auto destVectorType = insertOp.getDestVectorType();
565     auto llvmResultType = typeConverter.convertType(destVectorType);
566     auto positionArrayAttr = insertOp.position();
567 
568     // Bail if result type cannot be lowered.
569     if (!llvmResultType)
570       return matchFailure();
571 
572     // One-shot insertion of a vector into an array (only requires insertvalue).
573     if (sourceType.isa<VectorType>()) {
574       Value inserted = rewriter.create<LLVM::InsertValueOp>(
575           loc, llvmResultType, adaptor.dest(), adaptor.source(),
576           positionArrayAttr);
577       rewriter.replaceOp(op, inserted);
578       return matchSuccess();
579     }
580 
581     // Potential extraction of 1-D vector from array.
582     auto *context = op->getContext();
583     Value extracted = adaptor.dest();
584     auto positionAttrs = positionArrayAttr.getValue();
585     auto position = positionAttrs.back().cast<IntegerAttr>();
586     auto oneDVectorType = destVectorType;
587     if (positionAttrs.size() > 1) {
588       oneDVectorType = reducedVectorTypeBack(destVectorType);
589       auto nMinusOnePositionAttrs =
590           ArrayAttr::get(positionAttrs.drop_back(), context);
591       extracted = rewriter.create<LLVM::ExtractValueOp>(
592           loc, typeConverter.convertType(oneDVectorType), extracted,
593           nMinusOnePositionAttrs);
594     }
595 
596     // Insertion of an element into a 1-D LLVM vector.
597     auto i64Type = LLVM::LLVMType::getInt64Ty(typeConverter.getDialect());
598     auto constant = rewriter.create<LLVM::ConstantOp>(loc, i64Type, position);
599     Value inserted = rewriter.create<LLVM::InsertElementOp>(
600         loc, typeConverter.convertType(oneDVectorType), extracted,
601         adaptor.source(), constant);
602 
603     // Potential insertion of resulting 1-D vector into array.
604     if (positionAttrs.size() > 1) {
605       auto nMinusOnePositionAttrs =
606           ArrayAttr::get(positionAttrs.drop_back(), context);
607       inserted = rewriter.create<LLVM::InsertValueOp>(loc, llvmResultType,
608                                                       adaptor.dest(), inserted,
609                                                       nMinusOnePositionAttrs);
610     }
611 
612     rewriter.replaceOp(op, inserted);
613     return matchSuccess();
614   }
615 };
616 
617 /// Rank reducing rewrite for n-D FMA into (n-1)-D FMA where n > 1.
618 ///
619 /// Example:
620 /// ```
621 ///   %d = vector.fma %a, %b, %c : vector<2x4xf32>
622 /// ```
623 /// is rewritten into:
624 /// ```
625 ///  %r = splat %f0: vector<2x4xf32>
626 ///  %va = vector.extractvalue %a[0] : vector<2x4xf32>
627 ///  %vb = vector.extractvalue %b[0] : vector<2x4xf32>
628 ///  %vc = vector.extractvalue %c[0] : vector<2x4xf32>
629 ///  %vd = vector.fma %va, %vb, %vc : vector<4xf32>
630 ///  %r2 = vector.insertvalue %vd, %r[0] : vector<4xf32> into vector<2x4xf32>
631 ///  %va2 = vector.extractvalue %a2[1] : vector<2x4xf32>
632 ///  %vb2 = vector.extractvalue %b2[1] : vector<2x4xf32>
633 ///  %vc2 = vector.extractvalue %c2[1] : vector<2x4xf32>
634 ///  %vd2 = vector.fma %va2, %vb2, %vc2 : vector<4xf32>
635 ///  %r3 = vector.insertvalue %vd2, %r2[1] : vector<4xf32> into vector<2x4xf32>
636 ///  // %r3 holds the final value.
637 /// ```
638 class VectorFMAOpNDRewritePattern : public OpRewritePattern<FMAOp> {
639 public:
640   using OpRewritePattern<FMAOp>::OpRewritePattern;
641 
642   PatternMatchResult matchAndRewrite(FMAOp op,
643                                      PatternRewriter &rewriter) const override {
644     auto vType = op.getVectorType();
645     if (vType.getRank() < 2)
646       return matchFailure();
647 
648     auto loc = op.getLoc();
649     auto elemType = vType.getElementType();
650     Value zero = rewriter.create<ConstantOp>(loc, elemType,
651                                              rewriter.getZeroAttr(elemType));
652     Value desc = rewriter.create<SplatOp>(loc, vType, zero);
653     for (int64_t i = 0, e = vType.getShape().front(); i != e; ++i) {
654       Value extrLHS = rewriter.create<ExtractOp>(loc, op.lhs(), i);
655       Value extrRHS = rewriter.create<ExtractOp>(loc, op.rhs(), i);
656       Value extrACC = rewriter.create<ExtractOp>(loc, op.acc(), i);
657       Value fma = rewriter.create<FMAOp>(loc, extrLHS, extrRHS, extrACC);
658       desc = rewriter.create<InsertOp>(loc, fma, desc, i);
659     }
660     rewriter.replaceOp(op, desc);
661     return matchSuccess();
662   }
663 };
664 
665 // When ranks are different, InsertStridedSlice needs to extract a properly
666 // ranked vector from the destination vector into which to insert. This pattern
667 // only takes care of this part and forwards the rest of the conversion to
668 // another pattern that converts InsertStridedSlice for operands of the same
669 // rank.
670 //
671 // RewritePattern for InsertStridedSliceOp where source and destination vectors
672 // have different ranks. In this case:
673 //   1. the proper subvector is extracted from the destination vector
674 //   2. a new InsertStridedSlice op is created to insert the source in the
675 //   destination subvector
676 //   3. the destination subvector is inserted back in the proper place
677 //   4. the op is replaced by the result of step 3.
678 // The new InsertStridedSlice from step 2. will be picked up by a
679 // `VectorInsertStridedSliceOpSameRankRewritePattern`.
680 class VectorInsertStridedSliceOpDifferentRankRewritePattern
681     : public OpRewritePattern<InsertStridedSliceOp> {
682 public:
683   using OpRewritePattern<InsertStridedSliceOp>::OpRewritePattern;
684 
685   PatternMatchResult matchAndRewrite(InsertStridedSliceOp op,
686                                      PatternRewriter &rewriter) const override {
687     auto srcType = op.getSourceVectorType();
688     auto dstType = op.getDestVectorType();
689 
690     if (op.offsets().getValue().empty())
691       return matchFailure();
692 
693     auto loc = op.getLoc();
694     int64_t rankDiff = dstType.getRank() - srcType.getRank();
695     assert(rankDiff >= 0);
696     if (rankDiff == 0)
697       return matchFailure();
698 
699     int64_t rankRest = dstType.getRank() - rankDiff;
700     // Extract / insert the subvector of matching rank and InsertStridedSlice
701     // on it.
702     Value extracted =
703         rewriter.create<ExtractOp>(loc, op.dest(),
704                                    getI64SubArray(op.offsets(), /*dropFront=*/0,
705                                                   /*dropFront=*/rankRest));
706     // A different pattern will kick in for InsertStridedSlice with matching
707     // ranks.
708     auto stridedSliceInnerOp = rewriter.create<InsertStridedSliceOp>(
709         loc, op.source(), extracted,
710         getI64SubArray(op.offsets(), /*dropFront=*/rankDiff),
711         getI64SubArray(op.strides(), /*dropFront=*/0));
712     rewriter.replaceOpWithNewOp<InsertOp>(
713         op, stridedSliceInnerOp.getResult(), op.dest(),
714         getI64SubArray(op.offsets(), /*dropFront=*/0,
715                        /*dropFront=*/rankRest));
716     return matchSuccess();
717   }
718 };
719 
720 // RewritePattern for InsertStridedSliceOp where source and destination vectors
721 // have the same rank. In this case, we reduce
722 //   1. the proper subvector is extracted from the destination vector
723 //   2. a new InsertStridedSlice op is created to insert the source in the
724 //   destination subvector
725 //   3. the destination subvector is inserted back in the proper place
726 //   4. the op is replaced by the result of step 3.
727 // The new InsertStridedSlice from step 2. will be picked up by a
728 // `VectorInsertStridedSliceOpSameRankRewritePattern`.
729 class VectorInsertStridedSliceOpSameRankRewritePattern
730     : public OpRewritePattern<InsertStridedSliceOp> {
731 public:
732   using OpRewritePattern<InsertStridedSliceOp>::OpRewritePattern;
733 
734   PatternMatchResult matchAndRewrite(InsertStridedSliceOp op,
735                                      PatternRewriter &rewriter) const override {
736     auto srcType = op.getSourceVectorType();
737     auto dstType = op.getDestVectorType();
738 
739     if (op.offsets().getValue().empty())
740       return matchFailure();
741 
742     int64_t rankDiff = dstType.getRank() - srcType.getRank();
743     assert(rankDiff >= 0);
744     if (rankDiff != 0)
745       return matchFailure();
746 
747     if (srcType == dstType) {
748       rewriter.replaceOp(op, op.source());
749       return matchSuccess();
750     }
751 
752     int64_t offset =
753         op.offsets().getValue().front().cast<IntegerAttr>().getInt();
754     int64_t size = srcType.getShape().front();
755     int64_t stride =
756         op.strides().getValue().front().cast<IntegerAttr>().getInt();
757 
758     auto loc = op.getLoc();
759     Value res = op.dest();
760     // For each slice of the source vector along the most major dimension.
761     for (int64_t off = offset, e = offset + size * stride, idx = 0; off < e;
762          off += stride, ++idx) {
763       // 1. extract the proper subvector (or element) from source
764       Value extractedSource = extractOne(rewriter, loc, op.source(), idx);
765       if (extractedSource.getType().isa<VectorType>()) {
766         // 2. If we have a vector, extract the proper subvector from destination
767         // Otherwise we are at the element level and no need to recurse.
768         Value extractedDest = extractOne(rewriter, loc, op.dest(), off);
769         // 3. Reduce the problem to lowering a new InsertStridedSlice op with
770         // smaller rank.
771         InsertStridedSliceOp insertStridedSliceOp =
772             rewriter.create<InsertStridedSliceOp>(
773                 loc, extractedSource, extractedDest,
774                 getI64SubArray(op.offsets(), /* dropFront=*/1),
775                 getI64SubArray(op.strides(), /* dropFront=*/1));
776         // Call matchAndRewrite recursively from within the pattern. This
777         // circumvents the current limitation that a given pattern cannot
778         // be called multiple times by the PatternRewrite infrastructure (to
779         // avoid infinite recursion, but in this case, infinite recursion
780         // cannot happen because the rank is strictly decreasing).
781         // TODO(rriddle, nicolasvasilache) Implement something like a hook for
782         // a potential function that must decrease and allow the same pattern
783         // multiple times.
784         auto success = matchAndRewrite(insertStridedSliceOp, rewriter);
785         (void)success;
786         assert(success && "Unexpected failure");
787         extractedSource = insertStridedSliceOp;
788       }
789       // 4. Insert the extractedSource into the res vector.
790       res = insertOne(rewriter, loc, extractedSource, res, off);
791     }
792 
793     rewriter.replaceOp(op, res);
794     return matchSuccess();
795   }
796 };
797 
798 class VectorOuterProductOpConversion : public ConvertToLLVMPattern {
799 public:
800   explicit VectorOuterProductOpConversion(MLIRContext *context,
801                                           LLVMTypeConverter &typeConverter)
802       : ConvertToLLVMPattern(vector::OuterProductOp::getOperationName(),
803                              context, typeConverter) {}
804 
805   PatternMatchResult
806   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
807                   ConversionPatternRewriter &rewriter) const override {
808     auto loc = op->getLoc();
809     auto adaptor = vector::OuterProductOpOperandAdaptor(operands);
810     auto *ctx = op->getContext();
811     auto vLHS = adaptor.lhs().getType().cast<LLVM::LLVMType>();
812     auto vRHS = adaptor.rhs().getType().cast<LLVM::LLVMType>();
813     auto rankLHS = vLHS.getUnderlyingType()->getVectorNumElements();
814     auto rankRHS = vRHS.getUnderlyingType()->getVectorNumElements();
815     auto llvmArrayOfVectType = typeConverter.convertType(
816         cast<vector::OuterProductOp>(op).getResult().getType());
817     Value desc = rewriter.create<LLVM::UndefOp>(loc, llvmArrayOfVectType);
818     Value a = adaptor.lhs(), b = adaptor.rhs();
819     Value acc = adaptor.acc().empty() ? nullptr : adaptor.acc().front();
820     SmallVector<Value, 8> lhs, accs;
821     lhs.reserve(rankLHS);
822     accs.reserve(rankLHS);
823     for (unsigned d = 0, e = rankLHS; d < e; ++d) {
824       // shufflevector explicitly requires i32.
825       auto attr = rewriter.getI32IntegerAttr(d);
826       SmallVector<Attribute, 4> bcastAttr(rankRHS, attr);
827       auto bcastArrayAttr = ArrayAttr::get(bcastAttr, ctx);
828       Value aD = nullptr, accD = nullptr;
829       // 1. Broadcast the element a[d] into vector aD.
830       aD = rewriter.create<LLVM::ShuffleVectorOp>(loc, a, a, bcastArrayAttr);
831       // 2. If acc is present, extract 1-d vector acc[d] into accD.
832       if (acc)
833         accD = rewriter.create<LLVM::ExtractValueOp>(
834             loc, vRHS, acc, rewriter.getI64ArrayAttr(d));
835       // 3. Compute aD outer b (plus accD, if relevant).
836       Value aOuterbD =
837           accD
838               ? rewriter.create<LLVM::FMAOp>(loc, vRHS, aD, b, accD).getResult()
839               : rewriter.create<LLVM::FMulOp>(loc, aD, b).getResult();
840       // 4. Insert as value `d` in the descriptor.
841       desc = rewriter.create<LLVM::InsertValueOp>(loc, llvmArrayOfVectType,
842                                                   desc, aOuterbD,
843                                                   rewriter.getI64ArrayAttr(d));
844     }
845     rewriter.replaceOp(op, desc);
846     return matchSuccess();
847   }
848 };
849 
850 class VectorTypeCastOpConversion : public ConvertToLLVMPattern {
851 public:
852   explicit VectorTypeCastOpConversion(MLIRContext *context,
853                                       LLVMTypeConverter &typeConverter)
854       : ConvertToLLVMPattern(vector::TypeCastOp::getOperationName(), context,
855                              typeConverter) {}
856 
857   PatternMatchResult
858   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
859                   ConversionPatternRewriter &rewriter) const override {
860     auto loc = op->getLoc();
861     vector::TypeCastOp castOp = cast<vector::TypeCastOp>(op);
862     MemRefType sourceMemRefType =
863         castOp.getOperand().getType().cast<MemRefType>();
864     MemRefType targetMemRefType =
865         castOp.getResult().getType().cast<MemRefType>();
866 
867     // Only static shape casts supported atm.
868     if (!sourceMemRefType.hasStaticShape() ||
869         !targetMemRefType.hasStaticShape())
870       return matchFailure();
871 
872     auto llvmSourceDescriptorTy =
873         operands[0].getType().dyn_cast<LLVM::LLVMType>();
874     if (!llvmSourceDescriptorTy || !llvmSourceDescriptorTy.isStructTy())
875       return matchFailure();
876     MemRefDescriptor sourceMemRef(operands[0]);
877 
878     auto llvmTargetDescriptorTy = typeConverter.convertType(targetMemRefType)
879                                       .dyn_cast_or_null<LLVM::LLVMType>();
880     if (!llvmTargetDescriptorTy || !llvmTargetDescriptorTy.isStructTy())
881       return matchFailure();
882 
883     int64_t offset;
884     SmallVector<int64_t, 4> strides;
885     auto successStrides =
886         getStridesAndOffset(sourceMemRefType, strides, offset);
887     bool isContiguous = (strides.back() == 1);
888     if (isContiguous) {
889       auto sizes = sourceMemRefType.getShape();
890       for (int index = 0, e = strides.size() - 2; index < e; ++index) {
891         if (strides[index] != strides[index + 1] * sizes[index + 1]) {
892           isContiguous = false;
893           break;
894         }
895       }
896     }
897     // Only contiguous source tensors supported atm.
898     if (failed(successStrides) || !isContiguous)
899       return matchFailure();
900 
901     auto int64Ty = LLVM::LLVMType::getInt64Ty(typeConverter.getDialect());
902 
903     // Create descriptor.
904     auto desc = MemRefDescriptor::undef(rewriter, loc, llvmTargetDescriptorTy);
905     Type llvmTargetElementTy = desc.getElementType();
906     // Set allocated ptr.
907     Value allocated = sourceMemRef.allocatedPtr(rewriter, loc);
908     allocated =
909         rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, allocated);
910     desc.setAllocatedPtr(rewriter, loc, allocated);
911     // Set aligned ptr.
912     Value ptr = sourceMemRef.alignedPtr(rewriter, loc);
913     ptr = rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, ptr);
914     desc.setAlignedPtr(rewriter, loc, ptr);
915     // Fill offset 0.
916     auto attr = rewriter.getIntegerAttr(rewriter.getIndexType(), 0);
917     auto zero = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, attr);
918     desc.setOffset(rewriter, loc, zero);
919 
920     // Fill size and stride descriptors in memref.
921     for (auto indexedSize : llvm::enumerate(targetMemRefType.getShape())) {
922       int64_t index = indexedSize.index();
923       auto sizeAttr =
924           rewriter.getIntegerAttr(rewriter.getIndexType(), indexedSize.value());
925       auto size = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, sizeAttr);
926       desc.setSize(rewriter, loc, index, size);
927       auto strideAttr =
928           rewriter.getIntegerAttr(rewriter.getIndexType(), strides[index]);
929       auto stride = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, strideAttr);
930       desc.setStride(rewriter, loc, index, stride);
931     }
932 
933     rewriter.replaceOp(op, {desc});
934     return matchSuccess();
935   }
936 };
937 
938 class VectorPrintOpConversion : public ConvertToLLVMPattern {
939 public:
940   explicit VectorPrintOpConversion(MLIRContext *context,
941                                    LLVMTypeConverter &typeConverter)
942       : ConvertToLLVMPattern(vector::PrintOp::getOperationName(), context,
943                              typeConverter) {}
944 
945   // Proof-of-concept lowering implementation that relies on a small
946   // runtime support library, which only needs to provide a few
947   // printing methods (single value for all data types, opening/closing
948   // bracket, comma, newline). The lowering fully unrolls a vector
949   // in terms of these elementary printing operations. The advantage
950   // of this approach is that the library can remain unaware of all
951   // low-level implementation details of vectors while still supporting
952   // output of any shaped and dimensioned vector. Due to full unrolling,
953   // this approach is less suited for very large vectors though.
954   //
955   // TODO(ajcbik): rely solely on libc in future? something else?
956   //
957   PatternMatchResult
958   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
959                   ConversionPatternRewriter &rewriter) const override {
960     auto printOp = cast<vector::PrintOp>(op);
961     auto adaptor = vector::PrintOpOperandAdaptor(operands);
962     Type printType = printOp.getPrintType();
963 
964     if (typeConverter.convertType(printType) == nullptr)
965       return matchFailure();
966 
967     // Make sure element type has runtime support (currently just Float/Double).
968     VectorType vectorType = printType.dyn_cast<VectorType>();
969     Type eltType = vectorType ? vectorType.getElementType() : printType;
970     int64_t rank = vectorType ? vectorType.getRank() : 0;
971     Operation *printer;
972     if (eltType.isSignlessInteger(32))
973       printer = getPrintI32(op);
974     else if (eltType.isSignlessInteger(64))
975       printer = getPrintI64(op);
976     else if (eltType.isF32())
977       printer = getPrintFloat(op);
978     else if (eltType.isF64())
979       printer = getPrintDouble(op);
980     else
981       return matchFailure();
982 
983     // Unroll vector into elementary print calls.
984     emitRanks(rewriter, op, adaptor.source(), vectorType, printer, rank);
985     emitCall(rewriter, op->getLoc(), getPrintNewline(op));
986     rewriter.eraseOp(op);
987     return matchSuccess();
988   }
989 
990 private:
991   void emitRanks(ConversionPatternRewriter &rewriter, Operation *op,
992                  Value value, VectorType vectorType, Operation *printer,
993                  int64_t rank) const {
994     Location loc = op->getLoc();
995     if (rank == 0) {
996       emitCall(rewriter, loc, printer, value);
997       return;
998     }
999 
1000     emitCall(rewriter, loc, getPrintOpen(op));
1001     Operation *printComma = getPrintComma(op);
1002     int64_t dim = vectorType.getDimSize(0);
1003     for (int64_t d = 0; d < dim; ++d) {
1004       auto reducedType =
1005           rank > 1 ? reducedVectorTypeFront(vectorType) : nullptr;
1006       auto llvmType = typeConverter.convertType(
1007           rank > 1 ? reducedType : vectorType.getElementType());
1008       Value nestedVal =
1009           extractOne(rewriter, typeConverter, loc, value, llvmType, rank, d);
1010       emitRanks(rewriter, op, nestedVal, reducedType, printer, rank - 1);
1011       if (d != dim - 1)
1012         emitCall(rewriter, loc, printComma);
1013     }
1014     emitCall(rewriter, loc, getPrintClose(op));
1015   }
1016 
1017   // Helper to emit a call.
1018   static void emitCall(ConversionPatternRewriter &rewriter, Location loc,
1019                        Operation *ref, ValueRange params = ValueRange()) {
1020     rewriter.create<LLVM::CallOp>(loc, ArrayRef<Type>{},
1021                                   rewriter.getSymbolRefAttr(ref), params);
1022   }
1023 
1024   // Helper for printer method declaration (first hit) and lookup.
1025   static Operation *getPrint(Operation *op, LLVM::LLVMDialect *dialect,
1026                              StringRef name, ArrayRef<LLVM::LLVMType> params) {
1027     auto module = op->getParentOfType<ModuleOp>();
1028     auto func = module.lookupSymbol<LLVM::LLVMFuncOp>(name);
1029     if (func)
1030       return func;
1031     OpBuilder moduleBuilder(module.getBodyRegion());
1032     return moduleBuilder.create<LLVM::LLVMFuncOp>(
1033         op->getLoc(), name,
1034         LLVM::LLVMType::getFunctionTy(LLVM::LLVMType::getVoidTy(dialect),
1035                                       params, /*isVarArg=*/false));
1036   }
1037 
1038   // Helpers for method names.
1039   Operation *getPrintI32(Operation *op) const {
1040     LLVM::LLVMDialect *dialect = typeConverter.getDialect();
1041     return getPrint(op, dialect, "print_i32",
1042                     LLVM::LLVMType::getInt32Ty(dialect));
1043   }
1044   Operation *getPrintI64(Operation *op) const {
1045     LLVM::LLVMDialect *dialect = typeConverter.getDialect();
1046     return getPrint(op, dialect, "print_i64",
1047                     LLVM::LLVMType::getInt64Ty(dialect));
1048   }
1049   Operation *getPrintFloat(Operation *op) const {
1050     LLVM::LLVMDialect *dialect = typeConverter.getDialect();
1051     return getPrint(op, dialect, "print_f32",
1052                     LLVM::LLVMType::getFloatTy(dialect));
1053   }
1054   Operation *getPrintDouble(Operation *op) const {
1055     LLVM::LLVMDialect *dialect = typeConverter.getDialect();
1056     return getPrint(op, dialect, "print_f64",
1057                     LLVM::LLVMType::getDoubleTy(dialect));
1058   }
1059   Operation *getPrintOpen(Operation *op) const {
1060     return getPrint(op, typeConverter.getDialect(), "print_open", {});
1061   }
1062   Operation *getPrintClose(Operation *op) const {
1063     return getPrint(op, typeConverter.getDialect(), "print_close", {});
1064   }
1065   Operation *getPrintComma(Operation *op) const {
1066     return getPrint(op, typeConverter.getDialect(), "print_comma", {});
1067   }
1068   Operation *getPrintNewline(Operation *op) const {
1069     return getPrint(op, typeConverter.getDialect(), "print_newline", {});
1070   }
1071 };
1072 
1073 /// Progressive lowering of StridedSliceOp to either:
1074 ///   1. extractelement + insertelement for the 1-D case
1075 ///   2. extract + optional strided_slice + insert for the n-D case.
1076 class VectorStridedSliceOpConversion : public OpRewritePattern<StridedSliceOp> {
1077 public:
1078   using OpRewritePattern<StridedSliceOp>::OpRewritePattern;
1079 
1080   PatternMatchResult matchAndRewrite(StridedSliceOp op,
1081                                      PatternRewriter &rewriter) const override {
1082     auto dstType = op.getResult().getType().cast<VectorType>();
1083 
1084     assert(!op.offsets().getValue().empty() && "Unexpected empty offsets");
1085 
1086     int64_t offset =
1087         op.offsets().getValue().front().cast<IntegerAttr>().getInt();
1088     int64_t size = op.sizes().getValue().front().cast<IntegerAttr>().getInt();
1089     int64_t stride =
1090         op.strides().getValue().front().cast<IntegerAttr>().getInt();
1091 
1092     auto loc = op.getLoc();
1093     auto elemType = dstType.getElementType();
1094     assert(elemType.isSignlessIntOrIndexOrFloat());
1095     Value zero = rewriter.create<ConstantOp>(loc, elemType,
1096                                              rewriter.getZeroAttr(elemType));
1097     Value res = rewriter.create<SplatOp>(loc, dstType, zero);
1098     for (int64_t off = offset, e = offset + size * stride, idx = 0; off < e;
1099          off += stride, ++idx) {
1100       Value extracted = extractOne(rewriter, loc, op.vector(), off);
1101       if (op.offsets().getValue().size() > 1) {
1102         StridedSliceOp stridedSliceOp = rewriter.create<StridedSliceOp>(
1103             loc, extracted, getI64SubArray(op.offsets(), /* dropFront=*/1),
1104             getI64SubArray(op.sizes(), /* dropFront=*/1),
1105             getI64SubArray(op.strides(), /* dropFront=*/1));
1106         // Call matchAndRewrite recursively from within the pattern. This
1107         // circumvents the current limitation that a given pattern cannot
1108         // be called multiple times by the PatternRewrite infrastructure (to
1109         // avoid infinite recursion, but in this case, infinite recursion
1110         // cannot happen because the rank is strictly decreasing).
1111         // TODO(rriddle, nicolasvasilache) Implement something like a hook for
1112         // a potential function that must decrease and allow the same pattern
1113         // multiple times.
1114         auto success = matchAndRewrite(stridedSliceOp, rewriter);
1115         (void)success;
1116         assert(success && "Unexpected failure");
1117         extracted = stridedSliceOp;
1118       }
1119       res = insertOne(rewriter, loc, extracted, res, idx);
1120     }
1121     rewriter.replaceOp(op, {res});
1122     return matchSuccess();
1123   }
1124 };
1125 
1126 } // namespace
1127 
1128 /// Populate the given list with patterns that convert from Vector to LLVM.
1129 void mlir::populateVectorToLLVMConversionPatterns(
1130     LLVMTypeConverter &converter, OwningRewritePatternList &patterns) {
1131   MLIRContext *ctx = converter.getDialect()->getContext();
1132   patterns.insert<VectorFMAOpNDRewritePattern,
1133                   VectorInsertStridedSliceOpDifferentRankRewritePattern,
1134                   VectorInsertStridedSliceOpSameRankRewritePattern,
1135                   VectorStridedSliceOpConversion>(ctx);
1136   patterns.insert<VectorBroadcastOpConversion, VectorReductionOpConversion,
1137                   VectorShuffleOpConversion, VectorExtractElementOpConversion,
1138                   VectorExtractOpConversion, VectorFMAOp1DConversion,
1139                   VectorInsertElementOpConversion, VectorInsertOpConversion,
1140                   VectorOuterProductOpConversion, VectorTypeCastOpConversion,
1141                   VectorPrintOpConversion>(ctx, converter);
1142 }
1143 
1144 namespace {
1145 struct LowerVectorToLLVMPass : public ModulePass<LowerVectorToLLVMPass> {
1146   void runOnModule() override;
1147 };
1148 } // namespace
1149 
1150 void LowerVectorToLLVMPass::runOnModule() {
1151   // Perform progressive lowering of operations on "slices" and
1152   // all contraction operations. Also applies folding and DCE.
1153   {
1154     OwningRewritePatternList patterns;
1155     populateVectorSlicesLoweringPatterns(patterns, &getContext());
1156     populateVectorContractLoweringPatterns(patterns, &getContext());
1157     applyPatternsGreedily(getModule(), patterns);
1158   }
1159 
1160   // Convert to the LLVM IR dialect.
1161   LLVMTypeConverter converter(&getContext());
1162   OwningRewritePatternList patterns;
1163   populateVectorToLLVMConversionPatterns(converter, patterns);
1164   populateStdToLLVMConversionPatterns(converter, patterns);
1165 
1166   LLVMConversionTarget target(getContext());
1167   target.addDynamicallyLegalOp<FuncOp>(
1168       [&](FuncOp op) { return converter.isSignatureLegal(op.getType()); });
1169   if (failed(
1170           applyPartialConversion(getModule(), target, patterns, &converter))) {
1171     signalPassFailure();
1172   }
1173 }
1174 
1175 OpPassBase<ModuleOp> *mlir::createLowerVectorToLLVMPass() {
1176   return new LowerVectorToLLVMPass();
1177 }
1178 
1179 static PassRegistration<LowerVectorToLLVMPass>
1180     pass("convert-vector-to-llvm",
1181          "Lower the operations from the vector dialect into the LLVM dialect");
1182