xref: /llvm-project/mlir/lib/Conversion/VectorToLLVM/ConvertVectorToLLVM.cpp (revision e62a69561fb9d7b1013d2853da68d79a7907fead)
1 //===- VectorToLLVM.cpp - Conversion from Vector to the LLVM dialect ------===//
2 //
3 // Part of the MLIR 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/StandardToLLVM/ConvertStandardToLLVM.h"
10 #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h"
11 #include "mlir/Conversion/VectorToLLVM/ConvertVectorToLLVM.h"
12 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
13 #include "mlir/Dialect/VectorOps/VectorOps.h"
14 #include "mlir/IR/Attributes.h"
15 #include "mlir/IR/Builders.h"
16 #include "mlir/IR/MLIRContext.h"
17 #include "mlir/IR/Module.h"
18 #include "mlir/IR/Operation.h"
19 #include "mlir/IR/PatternMatch.h"
20 #include "mlir/IR/StandardTypes.h"
21 #include "mlir/IR/Types.h"
22 #include "mlir/Pass/Pass.h"
23 #include "mlir/Pass/PassManager.h"
24 #include "mlir/Transforms/DialectConversion.h"
25 #include "mlir/Transforms/Passes.h"
26 
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Type.h"
30 #include "llvm/Support/Allocator.h"
31 #include "llvm/Support/ErrorHandling.h"
32 
33 using namespace mlir;
34 
35 template <typename T>
36 static LLVM::LLVMType getPtrToElementType(T containerType,
37                                           LLVMTypeConverter &lowering) {
38   return lowering.convertType(containerType.getElementType())
39       .template cast<LLVM::LLVMType>()
40       .getPointerTo();
41 }
42 
43 // Helper to reduce vector type by one rank at front.
44 static VectorType reducedVectorTypeFront(VectorType tp) {
45   assert((tp.getRank() > 1) && "unlowerable vector type");
46   return VectorType::get(tp.getShape().drop_front(), tp.getElementType());
47 }
48 
49 // Helper to reduce vector type by *all* but one rank at back.
50 static VectorType reducedVectorTypeBack(VectorType tp) {
51   assert((tp.getRank() > 1) && "unlowerable vector type");
52   return VectorType::get(tp.getShape().take_back(), tp.getElementType());
53 }
54 
55 // Helper that picks the proper sequence for inserting.
56 static Value insertOne(ConversionPatternRewriter &rewriter,
57                        LLVMTypeConverter &lowering, Location loc, Value val1,
58                        Value val2, Type llvmType, int64_t rank, int64_t pos) {
59   if (rank == 1) {
60     auto idxType = rewriter.getIndexType();
61     auto constant = rewriter.create<LLVM::ConstantOp>(
62         loc, lowering.convertType(idxType),
63         rewriter.getIntegerAttr(idxType, pos));
64     return rewriter.create<LLVM::InsertElementOp>(loc, llvmType, val1, val2,
65                                                   constant);
66   }
67   return rewriter.create<LLVM::InsertValueOp>(loc, llvmType, val1, val2,
68                                               rewriter.getI64ArrayAttr(pos));
69 }
70 
71 // Helper that picks the proper sequence for extracting.
72 static Value extractOne(ConversionPatternRewriter &rewriter,
73                         LLVMTypeConverter &lowering, Location loc, Value val,
74                         Type llvmType, int64_t rank, int64_t pos) {
75   if (rank == 1) {
76     auto idxType = rewriter.getIndexType();
77     auto constant = rewriter.create<LLVM::ConstantOp>(
78         loc, lowering.convertType(idxType),
79         rewriter.getIntegerAttr(idxType, pos));
80     return rewriter.create<LLVM::ExtractElementOp>(loc, llvmType, val,
81                                                    constant);
82   }
83   return rewriter.create<LLVM::ExtractValueOp>(loc, llvmType, val,
84                                                rewriter.getI64ArrayAttr(pos));
85 }
86 
87 class VectorBroadcastOpConversion : public LLVMOpLowering {
88 public:
89   explicit VectorBroadcastOpConversion(MLIRContext *context,
90                                        LLVMTypeConverter &typeConverter)
91       : LLVMOpLowering(vector::BroadcastOp::getOperationName(), context,
92                        typeConverter) {}
93 
94   PatternMatchResult
95   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
96                   ConversionPatternRewriter &rewriter) const override {
97     auto broadcastOp = cast<vector::BroadcastOp>(op);
98     VectorType dstVectorType = broadcastOp.getVectorType();
99     if (lowering.convertType(dstVectorType) == nullptr)
100       return matchFailure();
101     // Rewrite when the full vector type can be lowered (which
102     // implies all 'reduced' types can be lowered too).
103     auto adaptor = vector::BroadcastOpOperandAdaptor(operands);
104     VectorType srcVectorType =
105         broadcastOp.getSourceType().dyn_cast<VectorType>();
106     rewriter.replaceOp(
107         op, expandRanks(adaptor.source(), // source value to be expanded
108                         op->getLoc(),     // location of original broadcast
109                         srcVectorType, dstVectorType, rewriter));
110     return matchSuccess();
111   }
112 
113 private:
114   // Expands the given source value over all the ranks, as defined
115   // by the source and destination type (a null source type denotes
116   // expansion from a scalar value into a vector).
117   //
118   // TODO(ajcbik): consider replacing this one-pattern lowering
119   //               with a two-pattern lowering using other vector
120   //               ops once all insert/extract/shuffle operations
121   //               are available with lowering implemention.
122   //
123   Value expandRanks(Value value, Location loc, VectorType srcVectorType,
124                     VectorType dstVectorType,
125                     ConversionPatternRewriter &rewriter) const {
126     assert((dstVectorType != nullptr) && "invalid result type in broadcast");
127     // Determine rank of source and destination.
128     int64_t srcRank = srcVectorType ? srcVectorType.getRank() : 0;
129     int64_t dstRank = dstVectorType.getRank();
130     int64_t curDim = dstVectorType.getDimSize(0);
131     if (srcRank < dstRank)
132       // Duplicate this rank.
133       return duplicateOneRank(value, loc, srcVectorType, dstVectorType, dstRank,
134                               curDim, rewriter);
135     // If all trailing dimensions are the same, the broadcast consists of
136     // simply passing through the source value and we are done. Otherwise,
137     // any non-matching dimension forces a stretch along this rank.
138     assert((srcVectorType != nullptr) && (srcRank > 0) &&
139            (srcRank == dstRank) && "invalid rank in broadcast");
140     for (int64_t r = 0; r < dstRank; r++) {
141       if (srcVectorType.getDimSize(r) != dstVectorType.getDimSize(r)) {
142         return stretchOneRank(value, loc, srcVectorType, dstVectorType, dstRank,
143                               curDim, rewriter);
144       }
145     }
146     return value;
147   }
148 
149   // Picks the best way to duplicate a single rank. For the 1-D case, a
150   // single insert-elt/shuffle is the most efficient expansion. For higher
151   // dimensions, however, we need dim x insert-values on a new broadcast
152   // with one less leading dimension, which will be lowered "recursively"
153   // to matching LLVM IR.
154   // For example:
155   //   v = broadcast s : f32 to vector<4x2xf32>
156   // becomes:
157   //   x = broadcast s : f32 to vector<2xf32>
158   //   v = [x,x,x,x]
159   // becomes:
160   //   x = [s,s]
161   //   v = [x,x,x,x]
162   Value duplicateOneRank(Value value, Location loc, VectorType srcVectorType,
163                          VectorType dstVectorType, int64_t rank, int64_t dim,
164                          ConversionPatternRewriter &rewriter) const {
165     Type llvmType = lowering.convertType(dstVectorType);
166     assert((llvmType != nullptr) && "unlowerable vector type");
167     if (rank == 1) {
168       Value undef = rewriter.create<LLVM::UndefOp>(loc, llvmType);
169       Value expand =
170           insertOne(rewriter, lowering, loc, undef, value, llvmType, rank, 0);
171       SmallVector<int32_t, 4> zeroValues(dim, 0);
172       return rewriter.create<LLVM::ShuffleVectorOp>(
173           loc, expand, undef, rewriter.getI32ArrayAttr(zeroValues));
174     }
175     Value expand = expandRanks(value, loc, srcVectorType,
176                                reducedVectorTypeFront(dstVectorType), rewriter);
177     Value result = rewriter.create<LLVM::UndefOp>(loc, llvmType);
178     for (int64_t d = 0; d < dim; ++d) {
179       result =
180           insertOne(rewriter, lowering, loc, result, expand, llvmType, rank, d);
181     }
182     return result;
183   }
184 
185   // Picks the best way to stretch a single rank. For the 1-D case, a
186   // single insert-elt/shuffle is the most efficient expansion when at
187   // a stretch. Otherwise, every dimension needs to be expanded
188   // individually and individually inserted in the resulting vector.
189   // For example:
190   //   v = broadcast w : vector<4x1x2xf32> to vector<4x2x2xf32>
191   // becomes:
192   //   a = broadcast w[0] : vector<1x2xf32> to vector<2x2xf32>
193   //   b = broadcast w[1] : vector<1x2xf32> to vector<2x2xf32>
194   //   c = broadcast w[2] : vector<1x2xf32> to vector<2x2xf32>
195   //   d = broadcast w[3] : vector<1x2xf32> to vector<2x2xf32>
196   //   v = [a,b,c,d]
197   // becomes:
198   //   x = broadcast w[0][0] : vector<2xf32> to vector <2x2xf32>
199   //   y = broadcast w[1][0] : vector<2xf32> to vector <2x2xf32>
200   //   a = [x, y]
201   //   etc.
202   Value stretchOneRank(Value value, Location loc, VectorType srcVectorType,
203                        VectorType dstVectorType, int64_t rank, int64_t dim,
204                        ConversionPatternRewriter &rewriter) const {
205     Type llvmType = lowering.convertType(dstVectorType);
206     assert((llvmType != nullptr) && "unlowerable vector type");
207     Value result = rewriter.create<LLVM::UndefOp>(loc, llvmType);
208     bool atStretch = dim != srcVectorType.getDimSize(0);
209     if (rank == 1) {
210       assert(atStretch);
211       Type redLlvmType = lowering.convertType(dstVectorType.getElementType());
212       Value one =
213           extractOne(rewriter, lowering, loc, value, redLlvmType, rank, 0);
214       Value expand =
215           insertOne(rewriter, lowering, loc, result, one, llvmType, rank, 0);
216       SmallVector<int32_t, 4> zeroValues(dim, 0);
217       return rewriter.create<LLVM::ShuffleVectorOp>(
218           loc, expand, result, rewriter.getI32ArrayAttr(zeroValues));
219     }
220     VectorType redSrcType = reducedVectorTypeFront(srcVectorType);
221     VectorType redDstType = reducedVectorTypeFront(dstVectorType);
222     Type redLlvmType = lowering.convertType(redSrcType);
223     for (int64_t d = 0; d < dim; ++d) {
224       int64_t pos = atStretch ? 0 : d;
225       Value one =
226           extractOne(rewriter, lowering, loc, value, redLlvmType, rank, pos);
227       Value expand = expandRanks(one, loc, redSrcType, redDstType, rewriter);
228       result =
229           insertOne(rewriter, lowering, loc, result, expand, llvmType, rank, d);
230     }
231     return result;
232   }
233 };
234 
235 class VectorShuffleOpConversion : public LLVMOpLowering {
236 public:
237   explicit VectorShuffleOpConversion(MLIRContext *context,
238                                      LLVMTypeConverter &typeConverter)
239       : LLVMOpLowering(vector::ShuffleOp::getOperationName(), context,
240                        typeConverter) {}
241 
242   PatternMatchResult
243   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
244                   ConversionPatternRewriter &rewriter) const override {
245     auto loc = op->getLoc();
246     auto adaptor = vector::ShuffleOpOperandAdaptor(operands);
247     auto shuffleOp = cast<vector::ShuffleOp>(op);
248     auto v1Type = shuffleOp.getV1VectorType();
249     auto v2Type = shuffleOp.getV2VectorType();
250     auto vectorType = shuffleOp.getVectorType();
251     Type llvmType = lowering.convertType(vectorType);
252     auto maskArrayAttr = shuffleOp.mask();
253 
254     // Bail if result type cannot be lowered.
255     if (!llvmType)
256       return matchFailure();
257 
258     // Get rank and dimension sizes.
259     int64_t rank = vectorType.getRank();
260     assert(v1Type.getRank() == rank);
261     assert(v2Type.getRank() == rank);
262     int64_t v1Dim = v1Type.getDimSize(0);
263 
264     // For rank 1, where both operands have *exactly* the same vector type,
265     // there is direct shuffle support in LLVM. Use it!
266     if (rank == 1 && v1Type == v2Type) {
267       Value shuffle = rewriter.create<LLVM::ShuffleVectorOp>(
268           loc, adaptor.v1(), adaptor.v2(), maskArrayAttr);
269       rewriter.replaceOp(op, shuffle);
270       return matchSuccess();
271     }
272 
273     // For all other cases, insert the individual values individually.
274     Value insert = rewriter.create<LLVM::UndefOp>(loc, llvmType);
275     int64_t insPos = 0;
276     for (auto en : llvm::enumerate(maskArrayAttr)) {
277       int64_t extPos = en.value().cast<IntegerAttr>().getInt();
278       Value value = adaptor.v1();
279       if (extPos >= v1Dim) {
280         extPos -= v1Dim;
281         value = adaptor.v2();
282       }
283       Value extract =
284           extractOne(rewriter, lowering, loc, value, llvmType, rank, extPos);
285       insert = insertOne(rewriter, lowering, loc, insert, extract, llvmType,
286                          rank, insPos++);
287     }
288     rewriter.replaceOp(op, insert);
289     return matchSuccess();
290   }
291 };
292 
293 class VectorExtractElementOpConversion : public LLVMOpLowering {
294 public:
295   explicit VectorExtractElementOpConversion(MLIRContext *context,
296                                             LLVMTypeConverter &typeConverter)
297       : LLVMOpLowering(vector::ExtractElementOp::getOperationName(), context,
298                        typeConverter) {}
299 
300   PatternMatchResult
301   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
302                   ConversionPatternRewriter &rewriter) const override {
303     auto adaptor = vector::ExtractElementOpOperandAdaptor(operands);
304     auto extractEltOp = cast<vector::ExtractElementOp>(op);
305     auto vectorType = extractEltOp.getVectorType();
306     auto llvmType = lowering.convertType(vectorType.getElementType());
307 
308     // Bail if result type cannot be lowered.
309     if (!llvmType)
310       return matchFailure();
311 
312     rewriter.replaceOpWithNewOp<LLVM::ExtractElementOp>(
313         op, llvmType, adaptor.vector(), adaptor.position());
314     return matchSuccess();
315   }
316 };
317 
318 class VectorExtractOpConversion : public LLVMOpLowering {
319 public:
320   explicit VectorExtractOpConversion(MLIRContext *context,
321                                      LLVMTypeConverter &typeConverter)
322       : LLVMOpLowering(vector::ExtractOp::getOperationName(), context,
323                        typeConverter) {}
324 
325   PatternMatchResult
326   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
327                   ConversionPatternRewriter &rewriter) const override {
328     auto loc = op->getLoc();
329     auto adaptor = vector::ExtractOpOperandAdaptor(operands);
330     auto extractOp = cast<vector::ExtractOp>(op);
331     auto vectorType = extractOp.getVectorType();
332     auto resultType = extractOp.getResult()->getType();
333     auto llvmResultType = lowering.convertType(resultType);
334     auto positionArrayAttr = extractOp.position();
335 
336     // Bail if result type cannot be lowered.
337     if (!llvmResultType)
338       return matchFailure();
339 
340     // One-shot extraction of vector from array (only requires extractvalue).
341     if (resultType.isa<VectorType>()) {
342       Value extracted = rewriter.create<LLVM::ExtractValueOp>(
343           loc, llvmResultType, adaptor.vector(), positionArrayAttr);
344       rewriter.replaceOp(op, extracted);
345       return matchSuccess();
346     }
347 
348     // Potential extraction of 1-D vector from array.
349     auto *context = op->getContext();
350     Value extracted = adaptor.vector();
351     auto positionAttrs = positionArrayAttr.getValue();
352     if (positionAttrs.size() > 1) {
353       auto oneDVectorType = reducedVectorTypeBack(vectorType);
354       auto nMinusOnePositionAttrs =
355           ArrayAttr::get(positionAttrs.drop_back(), context);
356       extracted = rewriter.create<LLVM::ExtractValueOp>(
357           loc, lowering.convertType(oneDVectorType), extracted,
358           nMinusOnePositionAttrs);
359     }
360 
361     // Remaining extraction of element from 1-D LLVM vector
362     auto position = positionAttrs.back().cast<IntegerAttr>();
363     auto i64Type = LLVM::LLVMType::getInt64Ty(lowering.getDialect());
364     auto constant = rewriter.create<LLVM::ConstantOp>(loc, i64Type, position);
365     extracted =
366         rewriter.create<LLVM::ExtractElementOp>(loc, extracted, constant);
367     rewriter.replaceOp(op, extracted);
368 
369     return matchSuccess();
370   }
371 };
372 
373 class VectorInsertElementOpConversion : public LLVMOpLowering {
374 public:
375   explicit VectorInsertElementOpConversion(MLIRContext *context,
376                                            LLVMTypeConverter &typeConverter)
377       : LLVMOpLowering(vector::InsertElementOp::getOperationName(), context,
378                        typeConverter) {}
379 
380   PatternMatchResult
381   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
382                   ConversionPatternRewriter &rewriter) const override {
383     auto adaptor = vector::InsertElementOpOperandAdaptor(operands);
384     auto insertEltOp = cast<vector::InsertElementOp>(op);
385     auto vectorType = insertEltOp.getDestVectorType();
386     auto llvmType = lowering.convertType(vectorType);
387 
388     // Bail if result type cannot be lowered.
389     if (!llvmType)
390       return matchFailure();
391 
392     rewriter.replaceOpWithNewOp<LLVM::InsertElementOp>(
393         op, llvmType, adaptor.dest(), adaptor.source(), adaptor.position());
394     return matchSuccess();
395   }
396 };
397 
398 class VectorInsertOpConversion : public LLVMOpLowering {
399 public:
400   explicit VectorInsertOpConversion(MLIRContext *context,
401                                     LLVMTypeConverter &typeConverter)
402       : LLVMOpLowering(vector::InsertOp::getOperationName(), context,
403                        typeConverter) {}
404 
405   PatternMatchResult
406   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
407                   ConversionPatternRewriter &rewriter) const override {
408     auto loc = op->getLoc();
409     auto adaptor = vector::InsertOpOperandAdaptor(operands);
410     auto insertOp = cast<vector::InsertOp>(op);
411     auto sourceType = insertOp.getSourceType();
412     auto destVectorType = insertOp.getDestVectorType();
413     auto llvmResultType = lowering.convertType(destVectorType);
414     auto positionArrayAttr = insertOp.position();
415 
416     // Bail if result type cannot be lowered.
417     if (!llvmResultType)
418       return matchFailure();
419 
420     // One-shot insertion of a vector into an array (only requires insertvalue).
421     if (sourceType.isa<VectorType>()) {
422       Value inserted = rewriter.create<LLVM::InsertValueOp>(
423           loc, llvmResultType, adaptor.dest(), adaptor.source(),
424           positionArrayAttr);
425       rewriter.replaceOp(op, inserted);
426       return matchSuccess();
427     }
428 
429     // Potential extraction of 1-D vector from array.
430     auto *context = op->getContext();
431     Value extracted = adaptor.dest();
432     auto positionAttrs = positionArrayAttr.getValue();
433     auto position = positionAttrs.back().cast<IntegerAttr>();
434     auto oneDVectorType = destVectorType;
435     if (positionAttrs.size() > 1) {
436       oneDVectorType = reducedVectorTypeBack(destVectorType);
437       auto nMinusOnePositionAttrs =
438           ArrayAttr::get(positionAttrs.drop_back(), context);
439       extracted = rewriter.create<LLVM::ExtractValueOp>(
440           loc, lowering.convertType(oneDVectorType), extracted,
441           nMinusOnePositionAttrs);
442     }
443 
444     // Insertion of an element into a 1-D LLVM vector.
445     auto i64Type = LLVM::LLVMType::getInt64Ty(lowering.getDialect());
446     auto constant = rewriter.create<LLVM::ConstantOp>(loc, i64Type, position);
447     Value inserted = rewriter.create<LLVM::InsertElementOp>(
448         loc, lowering.convertType(oneDVectorType), extracted, adaptor.source(),
449         constant);
450 
451     // Potential insertion of resulting 1-D vector into array.
452     if (positionAttrs.size() > 1) {
453       auto nMinusOnePositionAttrs =
454           ArrayAttr::get(positionAttrs.drop_back(), context);
455       inserted = rewriter.create<LLVM::InsertValueOp>(loc, llvmResultType,
456                                                       adaptor.dest(), inserted,
457                                                       nMinusOnePositionAttrs);
458     }
459 
460     rewriter.replaceOp(op, inserted);
461     return matchSuccess();
462   }
463 };
464 
465 class VectorOuterProductOpConversion : public LLVMOpLowering {
466 public:
467   explicit VectorOuterProductOpConversion(MLIRContext *context,
468                                           LLVMTypeConverter &typeConverter)
469       : LLVMOpLowering(vector::OuterProductOp::getOperationName(), context,
470                        typeConverter) {}
471 
472   PatternMatchResult
473   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
474                   ConversionPatternRewriter &rewriter) const override {
475     auto loc = op->getLoc();
476     auto adaptor = vector::OuterProductOpOperandAdaptor(operands);
477     auto *ctx = op->getContext();
478     auto vLHS = adaptor.lhs()->getType().cast<LLVM::LLVMType>();
479     auto vRHS = adaptor.rhs()->getType().cast<LLVM::LLVMType>();
480     auto rankLHS = vLHS.getUnderlyingType()->getVectorNumElements();
481     auto rankRHS = vRHS.getUnderlyingType()->getVectorNumElements();
482     auto llvmArrayOfVectType = lowering.convertType(
483         cast<vector::OuterProductOp>(op).getResult()->getType());
484     Value desc = rewriter.create<LLVM::UndefOp>(loc, llvmArrayOfVectType);
485     Value a = adaptor.lhs(), b = adaptor.rhs();
486     Value acc = adaptor.acc().empty() ? nullptr : adaptor.acc().front();
487     SmallVector<Value, 8> lhs, accs;
488     lhs.reserve(rankLHS);
489     accs.reserve(rankLHS);
490     for (unsigned d = 0, e = rankLHS; d < e; ++d) {
491       // shufflevector explicitly requires i32.
492       auto attr = rewriter.getI32IntegerAttr(d);
493       SmallVector<Attribute, 4> bcastAttr(rankRHS, attr);
494       auto bcastArrayAttr = ArrayAttr::get(bcastAttr, ctx);
495       Value aD = nullptr, accD = nullptr;
496       // 1. Broadcast the element a[d] into vector aD.
497       aD = rewriter.create<LLVM::ShuffleVectorOp>(loc, a, a, bcastArrayAttr);
498       // 2. If acc is present, extract 1-d vector acc[d] into accD.
499       if (acc)
500         accD = rewriter.create<LLVM::ExtractValueOp>(
501             loc, vRHS, acc, rewriter.getI64ArrayAttr(d));
502       // 3. Compute aD outer b (plus accD, if relevant).
503       Value aOuterbD =
504           accD ? rewriter.create<LLVM::FMulAddOp>(loc, vRHS, aD, b, accD)
505                      .getResult()
506                : rewriter.create<LLVM::FMulOp>(loc, aD, b).getResult();
507       // 4. Insert as value `d` in the descriptor.
508       desc = rewriter.create<LLVM::InsertValueOp>(loc, llvmArrayOfVectType,
509                                                   desc, aOuterbD,
510                                                   rewriter.getI64ArrayAttr(d));
511     }
512     rewriter.replaceOp(op, desc);
513     return matchSuccess();
514   }
515 };
516 
517 class VectorTypeCastOpConversion : public LLVMOpLowering {
518 public:
519   explicit VectorTypeCastOpConversion(MLIRContext *context,
520                                       LLVMTypeConverter &typeConverter)
521       : LLVMOpLowering(vector::TypeCastOp::getOperationName(), context,
522                        typeConverter) {}
523 
524   PatternMatchResult
525   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
526                   ConversionPatternRewriter &rewriter) const override {
527     auto loc = op->getLoc();
528     vector::TypeCastOp castOp = cast<vector::TypeCastOp>(op);
529     MemRefType sourceMemRefType =
530         castOp.getOperand()->getType().cast<MemRefType>();
531     MemRefType targetMemRefType =
532         castOp.getResult()->getType().cast<MemRefType>();
533 
534     // Only static shape casts supported atm.
535     if (!sourceMemRefType.hasStaticShape() ||
536         !targetMemRefType.hasStaticShape())
537       return matchFailure();
538 
539     auto llvmSourceDescriptorTy =
540         operands[0]->getType().dyn_cast<LLVM::LLVMType>();
541     if (!llvmSourceDescriptorTy || !llvmSourceDescriptorTy.isStructTy())
542       return matchFailure();
543     MemRefDescriptor sourceMemRef(operands[0]);
544 
545     auto llvmTargetDescriptorTy = lowering.convertType(targetMemRefType)
546                                       .dyn_cast_or_null<LLVM::LLVMType>();
547     if (!llvmTargetDescriptorTy || !llvmTargetDescriptorTy.isStructTy())
548       return matchFailure();
549 
550     int64_t offset;
551     SmallVector<int64_t, 4> strides;
552     auto successStrides =
553         getStridesAndOffset(sourceMemRefType, strides, offset);
554     bool isContiguous = (strides.back() == 1);
555     if (isContiguous) {
556       auto sizes = sourceMemRefType.getShape();
557       for (int index = 0, e = strides.size() - 2; index < e; ++index) {
558         if (strides[index] != strides[index + 1] * sizes[index + 1]) {
559           isContiguous = false;
560           break;
561         }
562       }
563     }
564     // Only contiguous source tensors supported atm.
565     if (failed(successStrides) || !isContiguous)
566       return matchFailure();
567 
568     auto int64Ty = LLVM::LLVMType::getInt64Ty(lowering.getDialect());
569 
570     // Create descriptor.
571     auto desc = MemRefDescriptor::undef(rewriter, loc, llvmTargetDescriptorTy);
572     Type llvmTargetElementTy = desc.getElementType();
573     // Set allocated ptr.
574     Value allocated = sourceMemRef.allocatedPtr(rewriter, loc);
575     allocated =
576         rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, allocated);
577     desc.setAllocatedPtr(rewriter, loc, allocated);
578     // Set aligned ptr.
579     Value ptr = sourceMemRef.alignedPtr(rewriter, loc);
580     ptr = rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, ptr);
581     desc.setAlignedPtr(rewriter, loc, ptr);
582     // Fill offset 0.
583     auto attr = rewriter.getIntegerAttr(rewriter.getIndexType(), 0);
584     auto zero = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, attr);
585     desc.setOffset(rewriter, loc, zero);
586 
587     // Fill size and stride descriptors in memref.
588     for (auto indexedSize : llvm::enumerate(targetMemRefType.getShape())) {
589       int64_t index = indexedSize.index();
590       auto sizeAttr =
591           rewriter.getIntegerAttr(rewriter.getIndexType(), indexedSize.value());
592       auto size = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, sizeAttr);
593       desc.setSize(rewriter, loc, index, size);
594       auto strideAttr =
595           rewriter.getIntegerAttr(rewriter.getIndexType(), strides[index]);
596       auto stride = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, strideAttr);
597       desc.setStride(rewriter, loc, index, stride);
598     }
599 
600     rewriter.replaceOp(op, {desc});
601     return matchSuccess();
602   }
603 };
604 
605 class VectorPrintOpConversion : public LLVMOpLowering {
606 public:
607   explicit VectorPrintOpConversion(MLIRContext *context,
608                                    LLVMTypeConverter &typeConverter)
609       : LLVMOpLowering(vector::PrintOp::getOperationName(), context,
610                        typeConverter) {}
611 
612   // Proof-of-concept lowering implementation that relies on a small
613   // runtime support library, which only needs to provide a few
614   // printing methods (single value for all data types, opening/closing
615   // bracket, comma, newline). The lowering fully unrolls a vector
616   // in terms of these elementary printing operations. The advantage
617   // of this approach is that the library can remain unaware of all
618   // low-level implementation details of vectors while still supporting
619   // output of any shaped and dimensioned vector. Due to full unrolling,
620   // this approach is less suited for very large vectors though.
621   //
622   // TODO(ajcbik): rely solely on libc in future? something else?
623   //
624   PatternMatchResult
625   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
626                   ConversionPatternRewriter &rewriter) const override {
627     auto printOp = cast<vector::PrintOp>(op);
628     auto adaptor = vector::PrintOpOperandAdaptor(operands);
629     Type printType = printOp.getPrintType();
630 
631     if (lowering.convertType(printType) == nullptr)
632       return matchFailure();
633 
634     // Make sure element type has runtime support (currently just Float/Double).
635     VectorType vectorType = printType.dyn_cast<VectorType>();
636     Type eltType = vectorType ? vectorType.getElementType() : printType;
637     int64_t rank = vectorType ? vectorType.getRank() : 0;
638     Operation *printer;
639     if (eltType.isF32())
640       printer = getPrintFloat(op);
641     else if (eltType.isF64())
642       printer = getPrintDouble(op);
643     else
644       return matchFailure();
645 
646     // Unroll vector into elementary print calls.
647     emitRanks(rewriter, op, adaptor.source(), vectorType, printer, rank);
648     emitCall(rewriter, op->getLoc(), getPrintNewline(op));
649     rewriter.eraseOp(op);
650     return matchSuccess();
651   }
652 
653 private:
654   void emitRanks(ConversionPatternRewriter &rewriter, Operation *op,
655                  Value value, VectorType vectorType, Operation *printer,
656                  int64_t rank) const {
657     Location loc = op->getLoc();
658     if (rank == 0) {
659       emitCall(rewriter, loc, printer, value);
660       return;
661     }
662 
663     emitCall(rewriter, loc, getPrintOpen(op));
664     Operation *printComma = getPrintComma(op);
665     int64_t dim = vectorType.getDimSize(0);
666     for (int64_t d = 0; d < dim; ++d) {
667       auto reducedType =
668           rank > 1 ? reducedVectorTypeFront(vectorType) : nullptr;
669       auto llvmType = lowering.convertType(
670           rank > 1 ? reducedType : vectorType.getElementType());
671       Value nestedVal =
672           extractOne(rewriter, lowering, loc, value, llvmType, rank, d);
673       emitRanks(rewriter, op, nestedVal, reducedType, printer, rank - 1);
674       if (d != dim - 1)
675         emitCall(rewriter, loc, printComma);
676     }
677     emitCall(rewriter, loc, getPrintClose(op));
678   }
679 
680   // Helper to emit a call.
681   static void emitCall(ConversionPatternRewriter &rewriter, Location loc,
682                        Operation *ref, ValueRange params = ValueRange()) {
683     rewriter.create<LLVM::CallOp>(loc, ArrayRef<Type>{},
684                                   rewriter.getSymbolRefAttr(ref), params);
685   }
686 
687   // Helper for printer method declaration (first hit) and lookup.
688   static Operation *getPrint(Operation *op, LLVM::LLVMDialect *dialect,
689                              StringRef name, ArrayRef<LLVM::LLVMType> params) {
690     auto module = op->getParentOfType<ModuleOp>();
691     auto func = module.lookupSymbol<LLVM::LLVMFuncOp>(name);
692     if (func)
693       return func;
694     OpBuilder moduleBuilder(module.getBodyRegion());
695     return moduleBuilder.create<LLVM::LLVMFuncOp>(
696         op->getLoc(), name,
697         LLVM::LLVMType::getFunctionTy(LLVM::LLVMType::getVoidTy(dialect),
698                                       params, /*isVarArg=*/false));
699   }
700 
701   // Helpers for method names.
702   Operation *getPrintFloat(Operation *op) const {
703     LLVM::LLVMDialect *dialect = lowering.getDialect();
704     return getPrint(op, dialect, "print_f32",
705                     LLVM::LLVMType::getFloatTy(dialect));
706   }
707   Operation *getPrintDouble(Operation *op) const {
708     LLVM::LLVMDialect *dialect = lowering.getDialect();
709     return getPrint(op, dialect, "print_f64",
710                     LLVM::LLVMType::getDoubleTy(dialect));
711   }
712   Operation *getPrintOpen(Operation *op) const {
713     return getPrint(op, lowering.getDialect(), "print_open", {});
714   }
715   Operation *getPrintClose(Operation *op) const {
716     return getPrint(op, lowering.getDialect(), "print_close", {});
717   }
718   Operation *getPrintComma(Operation *op) const {
719     return getPrint(op, lowering.getDialect(), "print_comma", {});
720   }
721   Operation *getPrintNewline(Operation *op) const {
722     return getPrint(op, lowering.getDialect(), "print_newline", {});
723   }
724 };
725 
726 /// Populate the given list with patterns that convert from Vector to LLVM.
727 void mlir::populateVectorToLLVMConversionPatterns(
728     LLVMTypeConverter &converter, OwningRewritePatternList &patterns) {
729   patterns.insert<VectorBroadcastOpConversion, VectorShuffleOpConversion,
730                   VectorExtractElementOpConversion, VectorExtractOpConversion,
731                   VectorInsertElementOpConversion, VectorInsertOpConversion,
732                   VectorOuterProductOpConversion, VectorTypeCastOpConversion,
733                   VectorPrintOpConversion>(converter.getDialect()->getContext(),
734                                            converter);
735 }
736 
737 namespace {
738 struct LowerVectorToLLVMPass : public ModulePass<LowerVectorToLLVMPass> {
739   void runOnModule() override;
740 };
741 } // namespace
742 
743 void LowerVectorToLLVMPass::runOnModule() {
744   // Convert to the LLVM IR dialect using the converter defined above.
745   OwningRewritePatternList patterns;
746   LLVMTypeConverter converter(&getContext());
747   populateVectorToLLVMConversionPatterns(converter, patterns);
748   populateStdToLLVMConversionPatterns(converter, patterns);
749 
750   ConversionTarget target(getContext());
751   target.addLegalDialect<LLVM::LLVMDialect>();
752   target.addDynamicallyLegalOp<FuncOp>(
753       [&](FuncOp op) { return converter.isSignatureLegal(op.getType()); });
754   if (failed(
755           applyPartialConversion(getModule(), target, patterns, &converter))) {
756     signalPassFailure();
757   }
758 }
759 
760 OpPassBase<ModuleOp> *mlir::createLowerVectorToLLVMPass() {
761   return new LowerVectorToLLVMPass();
762 }
763 
764 static PassRegistration<LowerVectorToLLVMPass>
765     pass("convert-vector-to-llvm",
766          "Lower the operations from the vector dialect into the LLVM dialect");
767