xref: /llvm-project/mlir/lib/Conversion/VectorToLLVM/ConvertVectorToLLVM.cpp (revision 8f5d519458aaf8ca7731ee974b912f6897078282)
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/LLVMCommon/TypeConverter.h"
12 #include "mlir/Conversion/LLVMCommon/VectorPattern.h"
13 #include "mlir/Dialect/Arith/IR/Arith.h"
14 #include "mlir/Dialect/Arith/Utils/Utils.h"
15 #include "mlir/Dialect/LLVMIR/FunctionCallUtils.h"
16 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
17 #include "mlir/Dialect/MemRef/IR/MemRef.h"
18 #include "mlir/Dialect/Vector/IR/VectorOps.h"
19 #include "mlir/Dialect/Vector/Interfaces/MaskableOpInterface.h"
20 #include "mlir/Dialect/Vector/Transforms/LoweringPatterns.h"
21 #include "mlir/Dialect/Vector/Transforms/VectorTransforms.h"
22 #include "mlir/IR/BuiltinAttributes.h"
23 #include "mlir/IR/BuiltinTypeInterfaces.h"
24 #include "mlir/IR/BuiltinTypes.h"
25 #include "mlir/IR/TypeUtilities.h"
26 #include "mlir/Target/LLVMIR/TypeToLLVM.h"
27 #include "mlir/Transforms/DialectConversion.h"
28 #include "llvm/ADT/APFloat.h"
29 #include "llvm/Support/Casting.h"
30 #include <optional>
31 
32 using namespace mlir;
33 using namespace mlir::vector;
34 
35 // Helper to reduce vector type by *all* but one rank at back.
36 static VectorType reducedVectorTypeBack(VectorType tp) {
37   assert((tp.getRank() > 1) && "unlowerable vector type");
38   return VectorType::get(tp.getShape().take_back(), tp.getElementType(),
39                          tp.getScalableDims().take_back());
40 }
41 
42 // Helper that picks the proper sequence for inserting.
43 static Value insertOne(ConversionPatternRewriter &rewriter,
44                        const LLVMTypeConverter &typeConverter, Location loc,
45                        Value val1, Value val2, Type llvmType, int64_t rank,
46                        int64_t pos) {
47   assert(rank > 0 && "0-D vector corner case should have been handled already");
48   if (rank == 1) {
49     auto idxType = rewriter.getIndexType();
50     auto constant = rewriter.create<LLVM::ConstantOp>(
51         loc, typeConverter.convertType(idxType),
52         rewriter.getIntegerAttr(idxType, pos));
53     return rewriter.create<LLVM::InsertElementOp>(loc, llvmType, val1, val2,
54                                                   constant);
55   }
56   return rewriter.create<LLVM::InsertValueOp>(loc, val1, val2, pos);
57 }
58 
59 // Helper that picks the proper sequence for extracting.
60 static Value extractOne(ConversionPatternRewriter &rewriter,
61                         const LLVMTypeConverter &typeConverter, Location loc,
62                         Value val, Type llvmType, int64_t rank, int64_t pos) {
63   if (rank <= 1) {
64     auto idxType = rewriter.getIndexType();
65     auto constant = rewriter.create<LLVM::ConstantOp>(
66         loc, typeConverter.convertType(idxType),
67         rewriter.getIntegerAttr(idxType, pos));
68     return rewriter.create<LLVM::ExtractElementOp>(loc, llvmType, val,
69                                                    constant);
70   }
71   return rewriter.create<LLVM::ExtractValueOp>(loc, val, pos);
72 }
73 
74 // Helper that returns data layout alignment of a memref.
75 LogicalResult getMemRefAlignment(const LLVMTypeConverter &typeConverter,
76                                  MemRefType memrefType, unsigned &align) {
77   Type elementTy = typeConverter.convertType(memrefType.getElementType());
78   if (!elementTy)
79     return failure();
80 
81   // TODO: this should use the MLIR data layout when it becomes available and
82   // stop depending on translation.
83   llvm::LLVMContext llvmContext;
84   align = LLVM::TypeToLLVMIRTranslator(llvmContext)
85               .getPreferredAlignment(elementTy, typeConverter.getDataLayout());
86   return success();
87 }
88 
89 // Check if the last stride is non-unit or the memory space is not zero.
90 static LogicalResult isMemRefTypeSupported(MemRefType memRefType,
91                                            const LLVMTypeConverter &converter) {
92   if (!isLastMemrefDimUnitStride(memRefType))
93     return failure();
94   FailureOr<unsigned> addressSpace =
95       converter.getMemRefAddressSpace(memRefType);
96   if (failed(addressSpace) || *addressSpace != 0)
97     return failure();
98   return success();
99 }
100 
101 // Add an index vector component to a base pointer.
102 static Value getIndexedPtrs(ConversionPatternRewriter &rewriter, Location loc,
103                             const LLVMTypeConverter &typeConverter,
104                             MemRefType memRefType, Value llvmMemref, Value base,
105                             Value index, uint64_t vLen) {
106   assert(succeeded(isMemRefTypeSupported(memRefType, typeConverter)) &&
107          "unsupported memref type");
108   auto pType = MemRefDescriptor(llvmMemref).getElementPtrType();
109   auto ptrsType = LLVM::getFixedVectorType(pType, vLen);
110   return rewriter.create<LLVM::GEPOp>(
111       loc, ptrsType, typeConverter.convertType(memRefType.getElementType()),
112       base, index);
113 }
114 
115 // Casts a strided element pointer to a vector pointer.  The vector pointer
116 // will be in the same address space as the incoming memref type.
117 static Value castDataPtr(ConversionPatternRewriter &rewriter, Location loc,
118                          Value ptr, MemRefType memRefType, Type vt,
119                          const LLVMTypeConverter &converter) {
120   if (converter.useOpaquePointers())
121     return ptr;
122 
123   unsigned addressSpace = *converter.getMemRefAddressSpace(memRefType);
124   auto pType = LLVM::LLVMPointerType::get(vt, addressSpace);
125   return rewriter.create<LLVM::BitcastOp>(loc, pType, ptr);
126 }
127 
128 namespace {
129 
130 /// Trivial Vector to LLVM conversions
131 using VectorScaleOpConversion =
132     OneToOneConvertToLLVMPattern<vector::VectorScaleOp, LLVM::vscale>;
133 
134 /// Conversion pattern for a vector.bitcast.
135 class VectorBitCastOpConversion
136     : public ConvertOpToLLVMPattern<vector::BitCastOp> {
137 public:
138   using ConvertOpToLLVMPattern<vector::BitCastOp>::ConvertOpToLLVMPattern;
139 
140   LogicalResult
141   matchAndRewrite(vector::BitCastOp bitCastOp, OpAdaptor adaptor,
142                   ConversionPatternRewriter &rewriter) const override {
143     // Only 0-D and 1-D vectors can be lowered to LLVM.
144     VectorType resultTy = bitCastOp.getResultVectorType();
145     if (resultTy.getRank() > 1)
146       return failure();
147     Type newResultTy = typeConverter->convertType(resultTy);
148     rewriter.replaceOpWithNewOp<LLVM::BitcastOp>(bitCastOp, newResultTy,
149                                                  adaptor.getOperands()[0]);
150     return success();
151   }
152 };
153 
154 /// Conversion pattern for a vector.matrix_multiply.
155 /// This is lowered directly to the proper llvm.intr.matrix.multiply.
156 class VectorMatmulOpConversion
157     : public ConvertOpToLLVMPattern<vector::MatmulOp> {
158 public:
159   using ConvertOpToLLVMPattern<vector::MatmulOp>::ConvertOpToLLVMPattern;
160 
161   LogicalResult
162   matchAndRewrite(vector::MatmulOp matmulOp, OpAdaptor adaptor,
163                   ConversionPatternRewriter &rewriter) const override {
164     rewriter.replaceOpWithNewOp<LLVM::MatrixMultiplyOp>(
165         matmulOp, typeConverter->convertType(matmulOp.getRes().getType()),
166         adaptor.getLhs(), adaptor.getRhs(), matmulOp.getLhsRows(),
167         matmulOp.getLhsColumns(), matmulOp.getRhsColumns());
168     return success();
169   }
170 };
171 
172 /// Conversion pattern for a vector.flat_transpose.
173 /// This is lowered directly to the proper llvm.intr.matrix.transpose.
174 class VectorFlatTransposeOpConversion
175     : public ConvertOpToLLVMPattern<vector::FlatTransposeOp> {
176 public:
177   using ConvertOpToLLVMPattern<vector::FlatTransposeOp>::ConvertOpToLLVMPattern;
178 
179   LogicalResult
180   matchAndRewrite(vector::FlatTransposeOp transOp, OpAdaptor adaptor,
181                   ConversionPatternRewriter &rewriter) const override {
182     rewriter.replaceOpWithNewOp<LLVM::MatrixTransposeOp>(
183         transOp, typeConverter->convertType(transOp.getRes().getType()),
184         adaptor.getMatrix(), transOp.getRows(), transOp.getColumns());
185     return success();
186   }
187 };
188 
189 /// Overloaded utility that replaces a vector.load, vector.store,
190 /// vector.maskedload and vector.maskedstore with their respective LLVM
191 /// couterparts.
192 static void replaceLoadOrStoreOp(vector::LoadOp loadOp,
193                                  vector::LoadOpAdaptor adaptor,
194                                  VectorType vectorTy, Value ptr, unsigned align,
195                                  ConversionPatternRewriter &rewriter) {
196   rewriter.replaceOpWithNewOp<LLVM::LoadOp>(loadOp, vectorTy, ptr, align);
197 }
198 
199 static void replaceLoadOrStoreOp(vector::MaskedLoadOp loadOp,
200                                  vector::MaskedLoadOpAdaptor adaptor,
201                                  VectorType vectorTy, Value ptr, unsigned align,
202                                  ConversionPatternRewriter &rewriter) {
203   rewriter.replaceOpWithNewOp<LLVM::MaskedLoadOp>(
204       loadOp, vectorTy, ptr, adaptor.getMask(), adaptor.getPassThru(), align);
205 }
206 
207 static void replaceLoadOrStoreOp(vector::StoreOp storeOp,
208                                  vector::StoreOpAdaptor adaptor,
209                                  VectorType vectorTy, Value ptr, unsigned align,
210                                  ConversionPatternRewriter &rewriter) {
211   rewriter.replaceOpWithNewOp<LLVM::StoreOp>(storeOp, adaptor.getValueToStore(),
212                                              ptr, align);
213 }
214 
215 static void replaceLoadOrStoreOp(vector::MaskedStoreOp storeOp,
216                                  vector::MaskedStoreOpAdaptor adaptor,
217                                  VectorType vectorTy, Value ptr, unsigned align,
218                                  ConversionPatternRewriter &rewriter) {
219   rewriter.replaceOpWithNewOp<LLVM::MaskedStoreOp>(
220       storeOp, adaptor.getValueToStore(), ptr, adaptor.getMask(), align);
221 }
222 
223 /// Conversion pattern for a vector.load, vector.store, vector.maskedload, and
224 /// vector.maskedstore.
225 template <class LoadOrStoreOp, class LoadOrStoreOpAdaptor>
226 class VectorLoadStoreConversion : public ConvertOpToLLVMPattern<LoadOrStoreOp> {
227 public:
228   using ConvertOpToLLVMPattern<LoadOrStoreOp>::ConvertOpToLLVMPattern;
229 
230   LogicalResult
231   matchAndRewrite(LoadOrStoreOp loadOrStoreOp,
232                   typename LoadOrStoreOp::Adaptor adaptor,
233                   ConversionPatternRewriter &rewriter) const override {
234     // Only 1-D vectors can be lowered to LLVM.
235     VectorType vectorTy = loadOrStoreOp.getVectorType();
236     if (vectorTy.getRank() > 1)
237       return failure();
238 
239     auto loc = loadOrStoreOp->getLoc();
240     MemRefType memRefTy = loadOrStoreOp.getMemRefType();
241 
242     // Resolve alignment.
243     unsigned align;
244     if (failed(getMemRefAlignment(*this->getTypeConverter(), memRefTy, align)))
245       return failure();
246 
247     // Resolve address.
248     auto vtype = cast<VectorType>(
249         this->typeConverter->convertType(loadOrStoreOp.getVectorType()));
250     Value dataPtr = this->getStridedElementPtr(loc, memRefTy, adaptor.getBase(),
251                                                adaptor.getIndices(), rewriter);
252     Value ptr = castDataPtr(rewriter, loc, dataPtr, memRefTy, vtype,
253                             *this->getTypeConverter());
254 
255     replaceLoadOrStoreOp(loadOrStoreOp, adaptor, vtype, ptr, align, rewriter);
256     return success();
257   }
258 };
259 
260 /// Conversion pattern for a vector.gather.
261 class VectorGatherOpConversion
262     : public ConvertOpToLLVMPattern<vector::GatherOp> {
263 public:
264   using ConvertOpToLLVMPattern<vector::GatherOp>::ConvertOpToLLVMPattern;
265 
266   LogicalResult
267   matchAndRewrite(vector::GatherOp gather, OpAdaptor adaptor,
268                   ConversionPatternRewriter &rewriter) const override {
269     MemRefType memRefType = dyn_cast<MemRefType>(gather.getBaseType());
270     assert(memRefType && "The base should be bufferized");
271 
272     if (failed(isMemRefTypeSupported(memRefType, *this->getTypeConverter())))
273       return failure();
274 
275     auto loc = gather->getLoc();
276 
277     // Resolve alignment.
278     unsigned align;
279     if (failed(getMemRefAlignment(*getTypeConverter(), memRefType, align)))
280       return failure();
281 
282     Value ptr = getStridedElementPtr(loc, memRefType, adaptor.getBase(),
283                                      adaptor.getIndices(), rewriter);
284     Value base = adaptor.getBase();
285 
286     auto llvmNDVectorTy = adaptor.getIndexVec().getType();
287     // Handle the simple case of 1-D vector.
288     if (!isa<LLVM::LLVMArrayType>(llvmNDVectorTy)) {
289       auto vType = gather.getVectorType();
290       // Resolve address.
291       Value ptrs = getIndexedPtrs(rewriter, loc, *this->getTypeConverter(),
292                                   memRefType, base, ptr, adaptor.getIndexVec(),
293                                   /*vLen=*/vType.getDimSize(0));
294       // Replace with the gather intrinsic.
295       rewriter.replaceOpWithNewOp<LLVM::masked_gather>(
296           gather, typeConverter->convertType(vType), ptrs, adaptor.getMask(),
297           adaptor.getPassThru(), rewriter.getI32IntegerAttr(align));
298       return success();
299     }
300 
301     const LLVMTypeConverter &typeConverter = *this->getTypeConverter();
302     auto callback = [align, memRefType, base, ptr, loc, &rewriter,
303                      &typeConverter](Type llvm1DVectorTy,
304                                      ValueRange vectorOperands) {
305       // Resolve address.
306       Value ptrs = getIndexedPtrs(
307           rewriter, loc, typeConverter, memRefType, base, ptr,
308           /*index=*/vectorOperands[0],
309           LLVM::getVectorNumElements(llvm1DVectorTy).getFixedValue());
310       // Create the gather intrinsic.
311       return rewriter.create<LLVM::masked_gather>(
312           loc, llvm1DVectorTy, ptrs, /*mask=*/vectorOperands[1],
313           /*passThru=*/vectorOperands[2], rewriter.getI32IntegerAttr(align));
314     };
315     SmallVector<Value> vectorOperands = {
316         adaptor.getIndexVec(), adaptor.getMask(), adaptor.getPassThru()};
317     return LLVM::detail::handleMultidimensionalVectors(
318         gather, vectorOperands, *getTypeConverter(), callback, rewriter);
319   }
320 };
321 
322 /// Conversion pattern for a vector.scatter.
323 class VectorScatterOpConversion
324     : public ConvertOpToLLVMPattern<vector::ScatterOp> {
325 public:
326   using ConvertOpToLLVMPattern<vector::ScatterOp>::ConvertOpToLLVMPattern;
327 
328   LogicalResult
329   matchAndRewrite(vector::ScatterOp scatter, OpAdaptor adaptor,
330                   ConversionPatternRewriter &rewriter) const override {
331     auto loc = scatter->getLoc();
332     MemRefType memRefType = scatter.getMemRefType();
333 
334     if (failed(isMemRefTypeSupported(memRefType, *this->getTypeConverter())))
335       return failure();
336 
337     // Resolve alignment.
338     unsigned align;
339     if (failed(getMemRefAlignment(*getTypeConverter(), memRefType, align)))
340       return failure();
341 
342     // Resolve address.
343     VectorType vType = scatter.getVectorType();
344     Value ptr = getStridedElementPtr(loc, memRefType, adaptor.getBase(),
345                                      adaptor.getIndices(), rewriter);
346     Value ptrs = getIndexedPtrs(
347         rewriter, loc, *this->getTypeConverter(), memRefType, adaptor.getBase(),
348         ptr, adaptor.getIndexVec(), /*vLen=*/vType.getDimSize(0));
349 
350     // Replace with the scatter intrinsic.
351     rewriter.replaceOpWithNewOp<LLVM::masked_scatter>(
352         scatter, adaptor.getValueToStore(), ptrs, adaptor.getMask(),
353         rewriter.getI32IntegerAttr(align));
354     return success();
355   }
356 };
357 
358 /// Conversion pattern for a vector.expandload.
359 class VectorExpandLoadOpConversion
360     : public ConvertOpToLLVMPattern<vector::ExpandLoadOp> {
361 public:
362   using ConvertOpToLLVMPattern<vector::ExpandLoadOp>::ConvertOpToLLVMPattern;
363 
364   LogicalResult
365   matchAndRewrite(vector::ExpandLoadOp expand, OpAdaptor adaptor,
366                   ConversionPatternRewriter &rewriter) const override {
367     auto loc = expand->getLoc();
368     MemRefType memRefType = expand.getMemRefType();
369 
370     // Resolve address.
371     auto vtype = typeConverter->convertType(expand.getVectorType());
372     Value ptr = getStridedElementPtr(loc, memRefType, adaptor.getBase(),
373                                      adaptor.getIndices(), rewriter);
374 
375     rewriter.replaceOpWithNewOp<LLVM::masked_expandload>(
376         expand, vtype, ptr, adaptor.getMask(), adaptor.getPassThru());
377     return success();
378   }
379 };
380 
381 /// Conversion pattern for a vector.compressstore.
382 class VectorCompressStoreOpConversion
383     : public ConvertOpToLLVMPattern<vector::CompressStoreOp> {
384 public:
385   using ConvertOpToLLVMPattern<vector::CompressStoreOp>::ConvertOpToLLVMPattern;
386 
387   LogicalResult
388   matchAndRewrite(vector::CompressStoreOp compress, OpAdaptor adaptor,
389                   ConversionPatternRewriter &rewriter) const override {
390     auto loc = compress->getLoc();
391     MemRefType memRefType = compress.getMemRefType();
392 
393     // Resolve address.
394     Value ptr = getStridedElementPtr(loc, memRefType, adaptor.getBase(),
395                                      adaptor.getIndices(), rewriter);
396 
397     rewriter.replaceOpWithNewOp<LLVM::masked_compressstore>(
398         compress, adaptor.getValueToStore(), ptr, adaptor.getMask());
399     return success();
400   }
401 };
402 
403 /// Reduction neutral classes for overloading.
404 class ReductionNeutralZero {};
405 class ReductionNeutralIntOne {};
406 class ReductionNeutralFPOne {};
407 class ReductionNeutralAllOnes {};
408 class ReductionNeutralSIntMin {};
409 class ReductionNeutralUIntMin {};
410 class ReductionNeutralSIntMax {};
411 class ReductionNeutralUIntMax {};
412 class ReductionNeutralFPMin {};
413 class ReductionNeutralFPMax {};
414 
415 /// Create the reduction neutral zero value.
416 static Value createReductionNeutralValue(ReductionNeutralZero neutral,
417                                          ConversionPatternRewriter &rewriter,
418                                          Location loc, Type llvmType) {
419   return rewriter.create<LLVM::ConstantOp>(loc, llvmType,
420                                            rewriter.getZeroAttr(llvmType));
421 }
422 
423 /// Create the reduction neutral integer one value.
424 static Value createReductionNeutralValue(ReductionNeutralIntOne neutral,
425                                          ConversionPatternRewriter &rewriter,
426                                          Location loc, Type llvmType) {
427   return rewriter.create<LLVM::ConstantOp>(
428       loc, llvmType, rewriter.getIntegerAttr(llvmType, 1));
429 }
430 
431 /// Create the reduction neutral fp one value.
432 static Value createReductionNeutralValue(ReductionNeutralFPOne neutral,
433                                          ConversionPatternRewriter &rewriter,
434                                          Location loc, Type llvmType) {
435   return rewriter.create<LLVM::ConstantOp>(
436       loc, llvmType, rewriter.getFloatAttr(llvmType, 1.0));
437 }
438 
439 /// Create the reduction neutral all-ones value.
440 static Value createReductionNeutralValue(ReductionNeutralAllOnes neutral,
441                                          ConversionPatternRewriter &rewriter,
442                                          Location loc, Type llvmType) {
443   return rewriter.create<LLVM::ConstantOp>(
444       loc, llvmType,
445       rewriter.getIntegerAttr(
446           llvmType, llvm::APInt::getAllOnes(llvmType.getIntOrFloatBitWidth())));
447 }
448 
449 /// Create the reduction neutral signed int minimum value.
450 static Value createReductionNeutralValue(ReductionNeutralSIntMin neutral,
451                                          ConversionPatternRewriter &rewriter,
452                                          Location loc, Type llvmType) {
453   return rewriter.create<LLVM::ConstantOp>(
454       loc, llvmType,
455       rewriter.getIntegerAttr(llvmType, llvm::APInt::getSignedMinValue(
456                                             llvmType.getIntOrFloatBitWidth())));
457 }
458 
459 /// Create the reduction neutral unsigned int minimum value.
460 static Value createReductionNeutralValue(ReductionNeutralUIntMin neutral,
461                                          ConversionPatternRewriter &rewriter,
462                                          Location loc, Type llvmType) {
463   return rewriter.create<LLVM::ConstantOp>(
464       loc, llvmType,
465       rewriter.getIntegerAttr(llvmType, llvm::APInt::getMinValue(
466                                             llvmType.getIntOrFloatBitWidth())));
467 }
468 
469 /// Create the reduction neutral signed int maximum value.
470 static Value createReductionNeutralValue(ReductionNeutralSIntMax neutral,
471                                          ConversionPatternRewriter &rewriter,
472                                          Location loc, Type llvmType) {
473   return rewriter.create<LLVM::ConstantOp>(
474       loc, llvmType,
475       rewriter.getIntegerAttr(llvmType, llvm::APInt::getSignedMaxValue(
476                                             llvmType.getIntOrFloatBitWidth())));
477 }
478 
479 /// Create the reduction neutral unsigned int maximum value.
480 static Value createReductionNeutralValue(ReductionNeutralUIntMax neutral,
481                                          ConversionPatternRewriter &rewriter,
482                                          Location loc, Type llvmType) {
483   return rewriter.create<LLVM::ConstantOp>(
484       loc, llvmType,
485       rewriter.getIntegerAttr(llvmType, llvm::APInt::getMaxValue(
486                                             llvmType.getIntOrFloatBitWidth())));
487 }
488 
489 /// Create the reduction neutral fp minimum value.
490 static Value createReductionNeutralValue(ReductionNeutralFPMin neutral,
491                                          ConversionPatternRewriter &rewriter,
492                                          Location loc, Type llvmType) {
493   auto floatType = cast<FloatType>(llvmType);
494   return rewriter.create<LLVM::ConstantOp>(
495       loc, llvmType,
496       rewriter.getFloatAttr(
497           llvmType, llvm::APFloat::getQNaN(floatType.getFloatSemantics(),
498                                            /*Negative=*/false)));
499 }
500 
501 /// Create the reduction neutral fp maximum value.
502 static Value createReductionNeutralValue(ReductionNeutralFPMax neutral,
503                                          ConversionPatternRewriter &rewriter,
504                                          Location loc, Type llvmType) {
505   auto floatType = cast<FloatType>(llvmType);
506   return rewriter.create<LLVM::ConstantOp>(
507       loc, llvmType,
508       rewriter.getFloatAttr(
509           llvmType, llvm::APFloat::getQNaN(floatType.getFloatSemantics(),
510                                            /*Negative=*/true)));
511 }
512 
513 /// Returns `accumulator` if it has a valid value. Otherwise, creates and
514 /// returns a new accumulator value using `ReductionNeutral`.
515 template <class ReductionNeutral>
516 static Value getOrCreateAccumulator(ConversionPatternRewriter &rewriter,
517                                     Location loc, Type llvmType,
518                                     Value accumulator) {
519   if (accumulator)
520     return accumulator;
521 
522   return createReductionNeutralValue(ReductionNeutral(), rewriter, loc,
523                                      llvmType);
524 }
525 
526 /// Creates a constant value with the 1-D vector shape provided in `llvmType`.
527 /// This is used as effective vector length by some intrinsics supporting
528 /// dynamic vector lengths at runtime.
529 static Value createVectorLengthValue(ConversionPatternRewriter &rewriter,
530                                      Location loc, Type llvmType) {
531   VectorType vType = cast<VectorType>(llvmType);
532   auto vShape = vType.getShape();
533   assert(vShape.size() == 1 && "Unexpected multi-dim vector type");
534 
535   return rewriter.create<LLVM::ConstantOp>(
536       loc, rewriter.getI32Type(),
537       rewriter.getIntegerAttr(rewriter.getI32Type(), vShape[0]));
538 }
539 
540 /// Helper method to lower a `vector.reduction` op that performs an arithmetic
541 /// operation like add,mul, etc.. `VectorOp` is the LLVM vector intrinsic to use
542 /// and `ScalarOp` is the scalar operation used to add the accumulation value if
543 /// non-null.
544 template <class LLVMRedIntrinOp, class ScalarOp>
545 static Value createIntegerReductionArithmeticOpLowering(
546     ConversionPatternRewriter &rewriter, Location loc, Type llvmType,
547     Value vectorOperand, Value accumulator) {
548 
549   Value result = rewriter.create<LLVMRedIntrinOp>(loc, llvmType, vectorOperand);
550 
551   if (accumulator)
552     result = rewriter.create<ScalarOp>(loc, accumulator, result);
553   return result;
554 }
555 
556 /// Helper method to lower a `vector.reduction` operation that performs
557 /// a comparison operation like `min`/`max`. `VectorOp` is the LLVM vector
558 /// intrinsic to use and `predicate` is the predicate to use to compare+combine
559 /// the accumulator value if non-null.
560 template <class LLVMRedIntrinOp>
561 static Value createIntegerReductionComparisonOpLowering(
562     ConversionPatternRewriter &rewriter, Location loc, Type llvmType,
563     Value vectorOperand, Value accumulator, LLVM::ICmpPredicate predicate) {
564   Value result = rewriter.create<LLVMRedIntrinOp>(loc, llvmType, vectorOperand);
565   if (accumulator) {
566     Value cmp =
567         rewriter.create<LLVM::ICmpOp>(loc, predicate, accumulator, result);
568     result = rewriter.create<LLVM::SelectOp>(loc, cmp, accumulator, result);
569   }
570   return result;
571 }
572 
573 namespace {
574 template <typename Source>
575 struct VectorToScalarMapper;
576 template <>
577 struct VectorToScalarMapper<LLVM::vector_reduce_fmaximum> {
578   using Type = LLVM::MaximumOp;
579 };
580 template <>
581 struct VectorToScalarMapper<LLVM::vector_reduce_fminimum> {
582   using Type = LLVM::MinimumOp;
583 };
584 template <>
585 struct VectorToScalarMapper<LLVM::vector_reduce_fmax> {
586   using Type = LLVM::MaxNumOp;
587 };
588 template <>
589 struct VectorToScalarMapper<LLVM::vector_reduce_fmin> {
590   using Type = LLVM::MinNumOp;
591 };
592 } // namespace
593 
594 template <class LLVMRedIntrinOp>
595 static Value
596 createFPReductionComparisonOpLowering(ConversionPatternRewriter &rewriter,
597                                       Location loc, Type llvmType,
598                                       Value vectorOperand, Value accumulator) {
599   Value result = rewriter.create<LLVMRedIntrinOp>(loc, llvmType, vectorOperand);
600 
601   if (accumulator) {
602     result =
603         rewriter.create<typename VectorToScalarMapper<LLVMRedIntrinOp>::Type>(
604             loc, result, accumulator);
605   }
606 
607   return result;
608 }
609 
610 /// Reduction neutral classes for overloading
611 class MaskNeutralFMaximum {};
612 class MaskNeutralFMinimum {};
613 
614 /// Get the mask neutral floating point maximum value
615 static llvm::APFloat
616 getMaskNeutralValue(MaskNeutralFMaximum,
617                     const llvm::fltSemantics &floatSemantics) {
618   return llvm::APFloat::getSmallest(floatSemantics, /*Negative=*/true);
619 }
620 /// Get the mask neutral floating point minimum value
621 static llvm::APFloat
622 getMaskNeutralValue(MaskNeutralFMinimum,
623                     const llvm::fltSemantics &floatSemantics) {
624   return llvm::APFloat::getLargest(floatSemantics, /*Negative=*/false);
625 }
626 
627 /// Create the mask neutral floating point MLIR vector constant
628 template <typename MaskNeutral>
629 static Value createMaskNeutralValue(ConversionPatternRewriter &rewriter,
630                                     Location loc, Type llvmType,
631                                     Type vectorType) {
632   const auto &floatSemantics = cast<FloatType>(llvmType).getFloatSemantics();
633   auto value = getMaskNeutralValue(MaskNeutral{}, floatSemantics);
634   auto denseValue =
635       DenseElementsAttr::get(vectorType.cast<ShapedType>(), value);
636   return rewriter.create<LLVM::ConstantOp>(loc, vectorType, denseValue);
637 }
638 
639 /// Lowers masked `fmaximum` and `fminimum` reductions using the non-masked
640 /// intrinsics. It is a workaround to overcome the lack of masked intrinsics for
641 /// `fmaximum`/`fminimum`.
642 /// More information: https://github.com/llvm/llvm-project/issues/64940
643 template <class LLVMRedIntrinOp, class MaskNeutral>
644 static Value lowerMaskedReductionWithRegular(
645     ConversionPatternRewriter &rewriter, Location loc, Type llvmType,
646     Value vectorOperand, Value accumulator, Value mask) {
647   const Value vectorMaskNeutral = createMaskNeutralValue<MaskNeutral>(
648       rewriter, loc, llvmType, vectorOperand.getType());
649   const Value selectedVectorByMask = rewriter.create<LLVM::SelectOp>(
650       loc, mask, vectorOperand, vectorMaskNeutral);
651   return createFPReductionComparisonOpLowering<LLVMRedIntrinOp>(
652       rewriter, loc, llvmType, selectedVectorByMask, accumulator);
653 }
654 
655 /// Overloaded methods to lower a reduction to an llvm instrinsic that requires
656 /// a start value. This start value format spans across fp reductions without
657 /// mask and all the masked reduction intrinsics.
658 template <class LLVMVPRedIntrinOp, class ReductionNeutral>
659 static Value lowerReductionWithStartValue(ConversionPatternRewriter &rewriter,
660                                           Location loc, Type llvmType,
661                                           Value vectorOperand,
662                                           Value accumulator) {
663   accumulator = getOrCreateAccumulator<ReductionNeutral>(rewriter, loc,
664                                                          llvmType, accumulator);
665   return rewriter.create<LLVMVPRedIntrinOp>(loc, llvmType,
666                                             /*startValue=*/accumulator,
667                                             vectorOperand);
668 }
669 
670 template <class LLVMVPRedIntrinOp, class ReductionNeutral>
671 static Value
672 lowerReductionWithStartValue(ConversionPatternRewriter &rewriter, Location loc,
673                              Type llvmType, Value vectorOperand,
674                              Value accumulator, bool reassociateFPReds) {
675   accumulator = getOrCreateAccumulator<ReductionNeutral>(rewriter, loc,
676                                                          llvmType, accumulator);
677   return rewriter.create<LLVMVPRedIntrinOp>(loc, llvmType,
678                                             /*startValue=*/accumulator,
679                                             vectorOperand, reassociateFPReds);
680 }
681 
682 template <class LLVMVPRedIntrinOp, class ReductionNeutral>
683 static Value lowerReductionWithStartValue(ConversionPatternRewriter &rewriter,
684                                           Location loc, Type llvmType,
685                                           Value vectorOperand,
686                                           Value accumulator, Value mask) {
687   accumulator = getOrCreateAccumulator<ReductionNeutral>(rewriter, loc,
688                                                          llvmType, accumulator);
689   Value vectorLength =
690       createVectorLengthValue(rewriter, loc, vectorOperand.getType());
691   return rewriter.create<LLVMVPRedIntrinOp>(loc, llvmType,
692                                             /*startValue=*/accumulator,
693                                             vectorOperand, mask, vectorLength);
694 }
695 
696 template <class LLVMVPRedIntrinOp, class ReductionNeutral>
697 static Value lowerReductionWithStartValue(ConversionPatternRewriter &rewriter,
698                                           Location loc, Type llvmType,
699                                           Value vectorOperand,
700                                           Value accumulator, Value mask,
701                                           bool reassociateFPReds) {
702   accumulator = getOrCreateAccumulator<ReductionNeutral>(rewriter, loc,
703                                                          llvmType, accumulator);
704   Value vectorLength =
705       createVectorLengthValue(rewriter, loc, vectorOperand.getType());
706   return rewriter.create<LLVMVPRedIntrinOp>(loc, llvmType,
707                                             /*startValue=*/accumulator,
708                                             vectorOperand, mask, vectorLength,
709                                             reassociateFPReds);
710 }
711 
712 template <class LLVMIntVPRedIntrinOp, class IntReductionNeutral,
713           class LLVMFPVPRedIntrinOp, class FPReductionNeutral>
714 static Value lowerReductionWithStartValue(ConversionPatternRewriter &rewriter,
715                                           Location loc, Type llvmType,
716                                           Value vectorOperand,
717                                           Value accumulator, Value mask) {
718   if (llvmType.isIntOrIndex())
719     return lowerReductionWithStartValue<LLVMIntVPRedIntrinOp,
720                                         IntReductionNeutral>(
721         rewriter, loc, llvmType, vectorOperand, accumulator, mask);
722 
723   // FP dispatch.
724   return lowerReductionWithStartValue<LLVMFPVPRedIntrinOp, FPReductionNeutral>(
725       rewriter, loc, llvmType, vectorOperand, accumulator, mask);
726 }
727 
728 /// Conversion pattern for all vector reductions.
729 class VectorReductionOpConversion
730     : public ConvertOpToLLVMPattern<vector::ReductionOp> {
731 public:
732   explicit VectorReductionOpConversion(const LLVMTypeConverter &typeConv,
733                                        bool reassociateFPRed)
734       : ConvertOpToLLVMPattern<vector::ReductionOp>(typeConv),
735         reassociateFPReductions(reassociateFPRed) {}
736 
737   LogicalResult
738   matchAndRewrite(vector::ReductionOp reductionOp, OpAdaptor adaptor,
739                   ConversionPatternRewriter &rewriter) const override {
740     auto kind = reductionOp.getKind();
741     Type eltType = reductionOp.getDest().getType();
742     Type llvmType = typeConverter->convertType(eltType);
743     Value operand = adaptor.getVector();
744     Value acc = adaptor.getAcc();
745     Location loc = reductionOp.getLoc();
746 
747     if (eltType.isIntOrIndex()) {
748       // Integer reductions: add/mul/min/max/and/or/xor.
749       Value result;
750       switch (kind) {
751       case vector::CombiningKind::ADD:
752         result =
753             createIntegerReductionArithmeticOpLowering<LLVM::vector_reduce_add,
754                                                        LLVM::AddOp>(
755                 rewriter, loc, llvmType, operand, acc);
756         break;
757       case vector::CombiningKind::MUL:
758         result =
759             createIntegerReductionArithmeticOpLowering<LLVM::vector_reduce_mul,
760                                                        LLVM::MulOp>(
761                 rewriter, loc, llvmType, operand, acc);
762         break;
763       case vector::CombiningKind::MINUI:
764         result = createIntegerReductionComparisonOpLowering<
765             LLVM::vector_reduce_umin>(rewriter, loc, llvmType, operand, acc,
766                                       LLVM::ICmpPredicate::ule);
767         break;
768       case vector::CombiningKind::MINSI:
769         result = createIntegerReductionComparisonOpLowering<
770             LLVM::vector_reduce_smin>(rewriter, loc, llvmType, operand, acc,
771                                       LLVM::ICmpPredicate::sle);
772         break;
773       case vector::CombiningKind::MAXUI:
774         result = createIntegerReductionComparisonOpLowering<
775             LLVM::vector_reduce_umax>(rewriter, loc, llvmType, operand, acc,
776                                       LLVM::ICmpPredicate::uge);
777         break;
778       case vector::CombiningKind::MAXSI:
779         result = createIntegerReductionComparisonOpLowering<
780             LLVM::vector_reduce_smax>(rewriter, loc, llvmType, operand, acc,
781                                       LLVM::ICmpPredicate::sge);
782         break;
783       case vector::CombiningKind::AND:
784         result =
785             createIntegerReductionArithmeticOpLowering<LLVM::vector_reduce_and,
786                                                        LLVM::AndOp>(
787                 rewriter, loc, llvmType, operand, acc);
788         break;
789       case vector::CombiningKind::OR:
790         result =
791             createIntegerReductionArithmeticOpLowering<LLVM::vector_reduce_or,
792                                                        LLVM::OrOp>(
793                 rewriter, loc, llvmType, operand, acc);
794         break;
795       case vector::CombiningKind::XOR:
796         result =
797             createIntegerReductionArithmeticOpLowering<LLVM::vector_reduce_xor,
798                                                        LLVM::XOrOp>(
799                 rewriter, loc, llvmType, operand, acc);
800         break;
801       default:
802         return failure();
803       }
804       rewriter.replaceOp(reductionOp, result);
805 
806       return success();
807     }
808 
809     if (!isa<FloatType>(eltType))
810       return failure();
811 
812     // Floating-point reductions: add/mul/min/max
813     Value result;
814     if (kind == vector::CombiningKind::ADD) {
815       result = lowerReductionWithStartValue<LLVM::vector_reduce_fadd,
816                                             ReductionNeutralZero>(
817           rewriter, loc, llvmType, operand, acc, reassociateFPReductions);
818     } else if (kind == vector::CombiningKind::MUL) {
819       result = lowerReductionWithStartValue<LLVM::vector_reduce_fmul,
820                                             ReductionNeutralFPOne>(
821           rewriter, loc, llvmType, operand, acc, reassociateFPReductions);
822     } else if (kind == vector::CombiningKind::MINIMUMF) {
823       result =
824           createFPReductionComparisonOpLowering<LLVM::vector_reduce_fminimum>(
825               rewriter, loc, llvmType, operand, acc);
826     } else if (kind == vector::CombiningKind::MAXIMUMF) {
827       result =
828           createFPReductionComparisonOpLowering<LLVM::vector_reduce_fmaximum>(
829               rewriter, loc, llvmType, operand, acc);
830     } else if (kind == vector::CombiningKind::MINF) {
831       result = createFPReductionComparisonOpLowering<LLVM::vector_reduce_fmin>(
832           rewriter, loc, llvmType, operand, acc);
833     } else if (kind == vector::CombiningKind::MAXF) {
834       result = createFPReductionComparisonOpLowering<LLVM::vector_reduce_fmax>(
835           rewriter, loc, llvmType, operand, acc);
836     } else
837       return failure();
838 
839     rewriter.replaceOp(reductionOp, result);
840     return success();
841   }
842 
843 private:
844   const bool reassociateFPReductions;
845 };
846 
847 /// Base class to convert a `vector.mask` operation while matching traits
848 /// of the maskable operation nested inside. A `VectorMaskOpConversionBase`
849 /// instance matches against a `vector.mask` operation. The `matchAndRewrite`
850 /// method performs a second match against the maskable operation `MaskedOp`.
851 /// Finally, it invokes the virtual method `matchAndRewriteMaskableOp` to be
852 /// implemented by the concrete conversion classes. This method can match
853 /// against specific traits of the `vector.mask` and the maskable operation. It
854 /// must replace the `vector.mask` operation.
855 template <class MaskedOp>
856 class VectorMaskOpConversionBase
857     : public ConvertOpToLLVMPattern<vector::MaskOp> {
858 public:
859   using ConvertOpToLLVMPattern<vector::MaskOp>::ConvertOpToLLVMPattern;
860 
861   LogicalResult
862   matchAndRewrite(vector::MaskOp maskOp, OpAdaptor adaptor,
863                   ConversionPatternRewriter &rewriter) const final {
864     // Match against the maskable operation kind.
865     auto maskedOp = llvm::dyn_cast_or_null<MaskedOp>(maskOp.getMaskableOp());
866     if (!maskedOp)
867       return failure();
868     return matchAndRewriteMaskableOp(maskOp, maskedOp, rewriter);
869   }
870 
871 protected:
872   virtual LogicalResult
873   matchAndRewriteMaskableOp(vector::MaskOp maskOp,
874                             vector::MaskableOpInterface maskableOp,
875                             ConversionPatternRewriter &rewriter) const = 0;
876 };
877 
878 class MaskedReductionOpConversion
879     : public VectorMaskOpConversionBase<vector::ReductionOp> {
880 
881 public:
882   using VectorMaskOpConversionBase<
883       vector::ReductionOp>::VectorMaskOpConversionBase;
884 
885   LogicalResult matchAndRewriteMaskableOp(
886       vector::MaskOp maskOp, MaskableOpInterface maskableOp,
887       ConversionPatternRewriter &rewriter) const override {
888     auto reductionOp = cast<ReductionOp>(maskableOp.getOperation());
889     auto kind = reductionOp.getKind();
890     Type eltType = reductionOp.getDest().getType();
891     Type llvmType = typeConverter->convertType(eltType);
892     Value operand = reductionOp.getVector();
893     Value acc = reductionOp.getAcc();
894     Location loc = reductionOp.getLoc();
895 
896     Value result;
897     switch (kind) {
898     case vector::CombiningKind::ADD:
899       result = lowerReductionWithStartValue<
900           LLVM::VPReduceAddOp, ReductionNeutralZero, LLVM::VPReduceFAddOp,
901           ReductionNeutralZero>(rewriter, loc, llvmType, operand, acc,
902                                 maskOp.getMask());
903       break;
904     case vector::CombiningKind::MUL:
905       result = lowerReductionWithStartValue<
906           LLVM::VPReduceMulOp, ReductionNeutralIntOne, LLVM::VPReduceFMulOp,
907           ReductionNeutralFPOne>(rewriter, loc, llvmType, operand, acc,
908                                  maskOp.getMask());
909       break;
910     case vector::CombiningKind::MINUI:
911       result = lowerReductionWithStartValue<LLVM::VPReduceUMinOp,
912                                             ReductionNeutralUIntMax>(
913           rewriter, loc, llvmType, operand, acc, maskOp.getMask());
914       break;
915     case vector::CombiningKind::MINSI:
916       result = lowerReductionWithStartValue<LLVM::VPReduceSMinOp,
917                                             ReductionNeutralSIntMax>(
918           rewriter, loc, llvmType, operand, acc, maskOp.getMask());
919       break;
920     case vector::CombiningKind::MAXUI:
921       result = lowerReductionWithStartValue<LLVM::VPReduceUMaxOp,
922                                             ReductionNeutralUIntMin>(
923           rewriter, loc, llvmType, operand, acc, maskOp.getMask());
924       break;
925     case vector::CombiningKind::MAXSI:
926       result = lowerReductionWithStartValue<LLVM::VPReduceSMaxOp,
927                                             ReductionNeutralSIntMin>(
928           rewriter, loc, llvmType, operand, acc, maskOp.getMask());
929       break;
930     case vector::CombiningKind::AND:
931       result = lowerReductionWithStartValue<LLVM::VPReduceAndOp,
932                                             ReductionNeutralAllOnes>(
933           rewriter, loc, llvmType, operand, acc, maskOp.getMask());
934       break;
935     case vector::CombiningKind::OR:
936       result = lowerReductionWithStartValue<LLVM::VPReduceOrOp,
937                                             ReductionNeutralZero>(
938           rewriter, loc, llvmType, operand, acc, maskOp.getMask());
939       break;
940     case vector::CombiningKind::XOR:
941       result = lowerReductionWithStartValue<LLVM::VPReduceXorOp,
942                                             ReductionNeutralZero>(
943           rewriter, loc, llvmType, operand, acc, maskOp.getMask());
944       break;
945     case vector::CombiningKind::MINF:
946       result = lowerReductionWithStartValue<LLVM::VPReduceFMinOp,
947                                             ReductionNeutralFPMax>(
948           rewriter, loc, llvmType, operand, acc, maskOp.getMask());
949       break;
950     case vector::CombiningKind::MAXF:
951       result = lowerReductionWithStartValue<LLVM::VPReduceFMaxOp,
952                                             ReductionNeutralFPMin>(
953           rewriter, loc, llvmType, operand, acc, maskOp.getMask());
954       break;
955     case CombiningKind::MAXIMUMF:
956       result = lowerMaskedReductionWithRegular<LLVM::vector_reduce_fmaximum,
957                                                MaskNeutralFMaximum>(
958           rewriter, loc, llvmType, operand, acc, maskOp.getMask());
959       break;
960     case CombiningKind::MINIMUMF:
961       result = lowerMaskedReductionWithRegular<LLVM::vector_reduce_fminimum,
962                                                MaskNeutralFMinimum>(
963           rewriter, loc, llvmType, operand, acc, maskOp.getMask());
964       break;
965     }
966 
967     // Replace `vector.mask` operation altogether.
968     rewriter.replaceOp(maskOp, result);
969     return success();
970   }
971 };
972 
973 class VectorShuffleOpConversion
974     : public ConvertOpToLLVMPattern<vector::ShuffleOp> {
975 public:
976   using ConvertOpToLLVMPattern<vector::ShuffleOp>::ConvertOpToLLVMPattern;
977 
978   LogicalResult
979   matchAndRewrite(vector::ShuffleOp shuffleOp, OpAdaptor adaptor,
980                   ConversionPatternRewriter &rewriter) const override {
981     auto loc = shuffleOp->getLoc();
982     auto v1Type = shuffleOp.getV1VectorType();
983     auto v2Type = shuffleOp.getV2VectorType();
984     auto vectorType = shuffleOp.getResultVectorType();
985     Type llvmType = typeConverter->convertType(vectorType);
986     auto maskArrayAttr = shuffleOp.getMask();
987 
988     // Bail if result type cannot be lowered.
989     if (!llvmType)
990       return failure();
991 
992     // Get rank and dimension sizes.
993     int64_t rank = vectorType.getRank();
994 #ifndef NDEBUG
995     bool wellFormed0DCase =
996         v1Type.getRank() == 0 && v2Type.getRank() == 0 && rank == 1;
997     bool wellFormedNDCase =
998         v1Type.getRank() == rank && v2Type.getRank() == rank;
999     assert((wellFormed0DCase || wellFormedNDCase) && "op is not well-formed");
1000 #endif
1001 
1002     // For rank 0 and 1, where both operands have *exactly* the same vector
1003     // type, there is direct shuffle support in LLVM. Use it!
1004     if (rank <= 1 && v1Type == v2Type) {
1005       Value llvmShuffleOp = rewriter.create<LLVM::ShuffleVectorOp>(
1006           loc, adaptor.getV1(), adaptor.getV2(),
1007           LLVM::convertArrayToIndices<int32_t>(maskArrayAttr));
1008       rewriter.replaceOp(shuffleOp, llvmShuffleOp);
1009       return success();
1010     }
1011 
1012     // For all other cases, insert the individual values individually.
1013     int64_t v1Dim = v1Type.getDimSize(0);
1014     Type eltType;
1015     if (auto arrayType = dyn_cast<LLVM::LLVMArrayType>(llvmType))
1016       eltType = arrayType.getElementType();
1017     else
1018       eltType = cast<VectorType>(llvmType).getElementType();
1019     Value insert = rewriter.create<LLVM::UndefOp>(loc, llvmType);
1020     int64_t insPos = 0;
1021     for (const auto &en : llvm::enumerate(maskArrayAttr)) {
1022       int64_t extPos = cast<IntegerAttr>(en.value()).getInt();
1023       Value value = adaptor.getV1();
1024       if (extPos >= v1Dim) {
1025         extPos -= v1Dim;
1026         value = adaptor.getV2();
1027       }
1028       Value extract = extractOne(rewriter, *getTypeConverter(), loc, value,
1029                                  eltType, rank, extPos);
1030       insert = insertOne(rewriter, *getTypeConverter(), loc, insert, extract,
1031                          llvmType, rank, insPos++);
1032     }
1033     rewriter.replaceOp(shuffleOp, insert);
1034     return success();
1035   }
1036 };
1037 
1038 class VectorExtractElementOpConversion
1039     : public ConvertOpToLLVMPattern<vector::ExtractElementOp> {
1040 public:
1041   using ConvertOpToLLVMPattern<
1042       vector::ExtractElementOp>::ConvertOpToLLVMPattern;
1043 
1044   LogicalResult
1045   matchAndRewrite(vector::ExtractElementOp extractEltOp, OpAdaptor adaptor,
1046                   ConversionPatternRewriter &rewriter) const override {
1047     auto vectorType = extractEltOp.getSourceVectorType();
1048     auto llvmType = typeConverter->convertType(vectorType.getElementType());
1049 
1050     // Bail if result type cannot be lowered.
1051     if (!llvmType)
1052       return failure();
1053 
1054     if (vectorType.getRank() == 0) {
1055       Location loc = extractEltOp.getLoc();
1056       auto idxType = rewriter.getIndexType();
1057       auto zero = rewriter.create<LLVM::ConstantOp>(
1058           loc, typeConverter->convertType(idxType),
1059           rewriter.getIntegerAttr(idxType, 0));
1060       rewriter.replaceOpWithNewOp<LLVM::ExtractElementOp>(
1061           extractEltOp, llvmType, adaptor.getVector(), zero);
1062       return success();
1063     }
1064 
1065     rewriter.replaceOpWithNewOp<LLVM::ExtractElementOp>(
1066         extractEltOp, llvmType, adaptor.getVector(), adaptor.getPosition());
1067     return success();
1068   }
1069 };
1070 
1071 class VectorExtractOpConversion
1072     : public ConvertOpToLLVMPattern<vector::ExtractOp> {
1073 public:
1074   using ConvertOpToLLVMPattern<vector::ExtractOp>::ConvertOpToLLVMPattern;
1075 
1076   LogicalResult
1077   matchAndRewrite(vector::ExtractOp extractOp, OpAdaptor adaptor,
1078                   ConversionPatternRewriter &rewriter) const override {
1079     auto loc = extractOp->getLoc();
1080     auto resultType = extractOp.getResult().getType();
1081     auto llvmResultType = typeConverter->convertType(resultType);
1082     ArrayRef<int64_t> positionArray = extractOp.getPosition();
1083 
1084     // Bail if result type cannot be lowered.
1085     if (!llvmResultType)
1086       return failure();
1087 
1088     // Extract entire vector. Should be handled by folder, but just to be safe.
1089     if (positionArray.empty()) {
1090       rewriter.replaceOp(extractOp, adaptor.getVector());
1091       return success();
1092     }
1093 
1094     // One-shot extraction of vector from array (only requires extractvalue).
1095     if (isa<VectorType>(resultType)) {
1096       Value extracted = rewriter.create<LLVM::ExtractValueOp>(
1097           loc, adaptor.getVector(), positionArray);
1098       rewriter.replaceOp(extractOp, extracted);
1099       return success();
1100     }
1101 
1102     // Potential extraction of 1-D vector from array.
1103     Value extracted = adaptor.getVector();
1104     if (positionArray.size() > 1) {
1105       extracted = rewriter.create<LLVM::ExtractValueOp>(
1106           loc, extracted, positionArray.drop_back());
1107     }
1108 
1109     // Remaining extraction of element from 1-D LLVM vector
1110     auto i64Type = IntegerType::get(rewriter.getContext(), 64);
1111     auto constant =
1112         rewriter.create<LLVM::ConstantOp>(loc, i64Type, positionArray.back());
1113     extracted =
1114         rewriter.create<LLVM::ExtractElementOp>(loc, extracted, constant);
1115     rewriter.replaceOp(extractOp, extracted);
1116 
1117     return success();
1118   }
1119 };
1120 
1121 /// Conversion pattern that turns a vector.fma on a 1-D vector
1122 /// into an llvm.intr.fmuladd. This is a trivial 1-1 conversion.
1123 /// This does not match vectors of n >= 2 rank.
1124 ///
1125 /// Example:
1126 /// ```
1127 ///  vector.fma %a, %a, %a : vector<8xf32>
1128 /// ```
1129 /// is converted to:
1130 /// ```
1131 ///  llvm.intr.fmuladd %va, %va, %va:
1132 ///    (!llvm."<8 x f32>">, !llvm<"<8 x f32>">, !llvm<"<8 x f32>">)
1133 ///    -> !llvm."<8 x f32>">
1134 /// ```
1135 class VectorFMAOp1DConversion : public ConvertOpToLLVMPattern<vector::FMAOp> {
1136 public:
1137   using ConvertOpToLLVMPattern<vector::FMAOp>::ConvertOpToLLVMPattern;
1138 
1139   LogicalResult
1140   matchAndRewrite(vector::FMAOp fmaOp, OpAdaptor adaptor,
1141                   ConversionPatternRewriter &rewriter) const override {
1142     VectorType vType = fmaOp.getVectorType();
1143     if (vType.getRank() > 1)
1144       return failure();
1145 
1146     rewriter.replaceOpWithNewOp<LLVM::FMulAddOp>(
1147         fmaOp, adaptor.getLhs(), adaptor.getRhs(), adaptor.getAcc());
1148     return success();
1149   }
1150 };
1151 
1152 class VectorInsertElementOpConversion
1153     : public ConvertOpToLLVMPattern<vector::InsertElementOp> {
1154 public:
1155   using ConvertOpToLLVMPattern<vector::InsertElementOp>::ConvertOpToLLVMPattern;
1156 
1157   LogicalResult
1158   matchAndRewrite(vector::InsertElementOp insertEltOp, OpAdaptor adaptor,
1159                   ConversionPatternRewriter &rewriter) const override {
1160     auto vectorType = insertEltOp.getDestVectorType();
1161     auto llvmType = typeConverter->convertType(vectorType);
1162 
1163     // Bail if result type cannot be lowered.
1164     if (!llvmType)
1165       return failure();
1166 
1167     if (vectorType.getRank() == 0) {
1168       Location loc = insertEltOp.getLoc();
1169       auto idxType = rewriter.getIndexType();
1170       auto zero = rewriter.create<LLVM::ConstantOp>(
1171           loc, typeConverter->convertType(idxType),
1172           rewriter.getIntegerAttr(idxType, 0));
1173       rewriter.replaceOpWithNewOp<LLVM::InsertElementOp>(
1174           insertEltOp, llvmType, adaptor.getDest(), adaptor.getSource(), zero);
1175       return success();
1176     }
1177 
1178     rewriter.replaceOpWithNewOp<LLVM::InsertElementOp>(
1179         insertEltOp, llvmType, adaptor.getDest(), adaptor.getSource(),
1180         adaptor.getPosition());
1181     return success();
1182   }
1183 };
1184 
1185 class VectorInsertOpConversion
1186     : public ConvertOpToLLVMPattern<vector::InsertOp> {
1187 public:
1188   using ConvertOpToLLVMPattern<vector::InsertOp>::ConvertOpToLLVMPattern;
1189 
1190   LogicalResult
1191   matchAndRewrite(vector::InsertOp insertOp, OpAdaptor adaptor,
1192                   ConversionPatternRewriter &rewriter) const override {
1193     auto loc = insertOp->getLoc();
1194     auto sourceType = insertOp.getSourceType();
1195     auto destVectorType = insertOp.getDestVectorType();
1196     auto llvmResultType = typeConverter->convertType(destVectorType);
1197     ArrayRef<int64_t> positionArray = insertOp.getPosition();
1198 
1199     // Bail if result type cannot be lowered.
1200     if (!llvmResultType)
1201       return failure();
1202 
1203     // Overwrite entire vector with value. Should be handled by folder, but
1204     // just to be safe.
1205     if (positionArray.empty()) {
1206       rewriter.replaceOp(insertOp, adaptor.getSource());
1207       return success();
1208     }
1209 
1210     // One-shot insertion of a vector into an array (only requires insertvalue).
1211     if (isa<VectorType>(sourceType)) {
1212       Value inserted = rewriter.create<LLVM::InsertValueOp>(
1213           loc, adaptor.getDest(), adaptor.getSource(), positionArray);
1214       rewriter.replaceOp(insertOp, inserted);
1215       return success();
1216     }
1217 
1218     // Potential extraction of 1-D vector from array.
1219     Value extracted = adaptor.getDest();
1220     auto oneDVectorType = destVectorType;
1221     if (positionArray.size() > 1) {
1222       oneDVectorType = reducedVectorTypeBack(destVectorType);
1223       extracted = rewriter.create<LLVM::ExtractValueOp>(
1224           loc, extracted, positionArray.drop_back());
1225     }
1226 
1227     // Insertion of an element into a 1-D LLVM vector.
1228     auto i64Type = IntegerType::get(rewriter.getContext(), 64);
1229     auto constant =
1230         rewriter.create<LLVM::ConstantOp>(loc, i64Type, positionArray.back());
1231     Value inserted = rewriter.create<LLVM::InsertElementOp>(
1232         loc, typeConverter->convertType(oneDVectorType), extracted,
1233         adaptor.getSource(), constant);
1234 
1235     // Potential insertion of resulting 1-D vector into array.
1236     if (positionArray.size() > 1) {
1237       inserted = rewriter.create<LLVM::InsertValueOp>(
1238           loc, adaptor.getDest(), inserted, positionArray.drop_back());
1239     }
1240 
1241     rewriter.replaceOp(insertOp, inserted);
1242     return success();
1243   }
1244 };
1245 
1246 /// Lower vector.scalable.insert ops to LLVM vector.insert
1247 struct VectorScalableInsertOpLowering
1248     : public ConvertOpToLLVMPattern<vector::ScalableInsertOp> {
1249   using ConvertOpToLLVMPattern<
1250       vector::ScalableInsertOp>::ConvertOpToLLVMPattern;
1251 
1252   LogicalResult
1253   matchAndRewrite(vector::ScalableInsertOp insOp, OpAdaptor adaptor,
1254                   ConversionPatternRewriter &rewriter) const override {
1255     rewriter.replaceOpWithNewOp<LLVM::vector_insert>(
1256         insOp, adaptor.getSource(), adaptor.getDest(), adaptor.getPos());
1257     return success();
1258   }
1259 };
1260 
1261 /// Lower vector.scalable.extract ops to LLVM vector.extract
1262 struct VectorScalableExtractOpLowering
1263     : public ConvertOpToLLVMPattern<vector::ScalableExtractOp> {
1264   using ConvertOpToLLVMPattern<
1265       vector::ScalableExtractOp>::ConvertOpToLLVMPattern;
1266 
1267   LogicalResult
1268   matchAndRewrite(vector::ScalableExtractOp extOp, OpAdaptor adaptor,
1269                   ConversionPatternRewriter &rewriter) const override {
1270     rewriter.replaceOpWithNewOp<LLVM::vector_extract>(
1271         extOp, typeConverter->convertType(extOp.getResultVectorType()),
1272         adaptor.getSource(), adaptor.getPos());
1273     return success();
1274   }
1275 };
1276 
1277 /// Rank reducing rewrite for n-D FMA into (n-1)-D FMA where n > 1.
1278 ///
1279 /// Example:
1280 /// ```
1281 ///   %d = vector.fma %a, %b, %c : vector<2x4xf32>
1282 /// ```
1283 /// is rewritten into:
1284 /// ```
1285 ///  %r = splat %f0: vector<2x4xf32>
1286 ///  %va = vector.extractvalue %a[0] : vector<2x4xf32>
1287 ///  %vb = vector.extractvalue %b[0] : vector<2x4xf32>
1288 ///  %vc = vector.extractvalue %c[0] : vector<2x4xf32>
1289 ///  %vd = vector.fma %va, %vb, %vc : vector<4xf32>
1290 ///  %r2 = vector.insertvalue %vd, %r[0] : vector<4xf32> into vector<2x4xf32>
1291 ///  %va2 = vector.extractvalue %a2[1] : vector<2x4xf32>
1292 ///  %vb2 = vector.extractvalue %b2[1] : vector<2x4xf32>
1293 ///  %vc2 = vector.extractvalue %c2[1] : vector<2x4xf32>
1294 ///  %vd2 = vector.fma %va2, %vb2, %vc2 : vector<4xf32>
1295 ///  %r3 = vector.insertvalue %vd2, %r2[1] : vector<4xf32> into vector<2x4xf32>
1296 ///  // %r3 holds the final value.
1297 /// ```
1298 class VectorFMAOpNDRewritePattern : public OpRewritePattern<FMAOp> {
1299 public:
1300   using OpRewritePattern<FMAOp>::OpRewritePattern;
1301 
1302   void initialize() {
1303     // This pattern recursively unpacks one dimension at a time. The recursion
1304     // bounded as the rank is strictly decreasing.
1305     setHasBoundedRewriteRecursion();
1306   }
1307 
1308   LogicalResult matchAndRewrite(FMAOp op,
1309                                 PatternRewriter &rewriter) const override {
1310     auto vType = op.getVectorType();
1311     if (vType.getRank() < 2)
1312       return failure();
1313 
1314     auto loc = op.getLoc();
1315     auto elemType = vType.getElementType();
1316     Value zero = rewriter.create<arith::ConstantOp>(
1317         loc, elemType, rewriter.getZeroAttr(elemType));
1318     Value desc = rewriter.create<vector::SplatOp>(loc, vType, zero);
1319     for (int64_t i = 0, e = vType.getShape().front(); i != e; ++i) {
1320       Value extrLHS = rewriter.create<ExtractOp>(loc, op.getLhs(), i);
1321       Value extrRHS = rewriter.create<ExtractOp>(loc, op.getRhs(), i);
1322       Value extrACC = rewriter.create<ExtractOp>(loc, op.getAcc(), i);
1323       Value fma = rewriter.create<FMAOp>(loc, extrLHS, extrRHS, extrACC);
1324       desc = rewriter.create<InsertOp>(loc, fma, desc, i);
1325     }
1326     rewriter.replaceOp(op, desc);
1327     return success();
1328   }
1329 };
1330 
1331 /// Returns the strides if the memory underlying `memRefType` has a contiguous
1332 /// static layout.
1333 static std::optional<SmallVector<int64_t, 4>>
1334 computeContiguousStrides(MemRefType memRefType) {
1335   int64_t offset;
1336   SmallVector<int64_t, 4> strides;
1337   if (failed(getStridesAndOffset(memRefType, strides, offset)))
1338     return std::nullopt;
1339   if (!strides.empty() && strides.back() != 1)
1340     return std::nullopt;
1341   // If no layout or identity layout, this is contiguous by definition.
1342   if (memRefType.getLayout().isIdentity())
1343     return strides;
1344 
1345   // Otherwise, we must determine contiguity form shapes. This can only ever
1346   // work in static cases because MemRefType is underspecified to represent
1347   // contiguous dynamic shapes in other ways than with just empty/identity
1348   // layout.
1349   auto sizes = memRefType.getShape();
1350   for (int index = 0, e = strides.size() - 1; index < e; ++index) {
1351     if (ShapedType::isDynamic(sizes[index + 1]) ||
1352         ShapedType::isDynamic(strides[index]) ||
1353         ShapedType::isDynamic(strides[index + 1]))
1354       return std::nullopt;
1355     if (strides[index] != strides[index + 1] * sizes[index + 1])
1356       return std::nullopt;
1357   }
1358   return strides;
1359 }
1360 
1361 class VectorTypeCastOpConversion
1362     : public ConvertOpToLLVMPattern<vector::TypeCastOp> {
1363 public:
1364   using ConvertOpToLLVMPattern<vector::TypeCastOp>::ConvertOpToLLVMPattern;
1365 
1366   LogicalResult
1367   matchAndRewrite(vector::TypeCastOp castOp, OpAdaptor adaptor,
1368                   ConversionPatternRewriter &rewriter) const override {
1369     auto loc = castOp->getLoc();
1370     MemRefType sourceMemRefType =
1371         cast<MemRefType>(castOp.getOperand().getType());
1372     MemRefType targetMemRefType = castOp.getType();
1373 
1374     // Only static shape casts supported atm.
1375     if (!sourceMemRefType.hasStaticShape() ||
1376         !targetMemRefType.hasStaticShape())
1377       return failure();
1378 
1379     auto llvmSourceDescriptorTy =
1380         dyn_cast<LLVM::LLVMStructType>(adaptor.getOperands()[0].getType());
1381     if (!llvmSourceDescriptorTy)
1382       return failure();
1383     MemRefDescriptor sourceMemRef(adaptor.getOperands()[0]);
1384 
1385     auto llvmTargetDescriptorTy = dyn_cast_or_null<LLVM::LLVMStructType>(
1386         typeConverter->convertType(targetMemRefType));
1387     if (!llvmTargetDescriptorTy)
1388       return failure();
1389 
1390     // Only contiguous source buffers supported atm.
1391     auto sourceStrides = computeContiguousStrides(sourceMemRefType);
1392     if (!sourceStrides)
1393       return failure();
1394     auto targetStrides = computeContiguousStrides(targetMemRefType);
1395     if (!targetStrides)
1396       return failure();
1397     // Only support static strides for now, regardless of contiguity.
1398     if (llvm::any_of(*targetStrides, ShapedType::isDynamic))
1399       return failure();
1400 
1401     auto int64Ty = IntegerType::get(rewriter.getContext(), 64);
1402 
1403     // Create descriptor.
1404     auto desc = MemRefDescriptor::undef(rewriter, loc, llvmTargetDescriptorTy);
1405     Type llvmTargetElementTy = desc.getElementPtrType();
1406     // Set allocated ptr.
1407     Value allocated = sourceMemRef.allocatedPtr(rewriter, loc);
1408     if (!getTypeConverter()->useOpaquePointers())
1409       allocated =
1410           rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, allocated);
1411     desc.setAllocatedPtr(rewriter, loc, allocated);
1412 
1413     // Set aligned ptr.
1414     Value ptr = sourceMemRef.alignedPtr(rewriter, loc);
1415     if (!getTypeConverter()->useOpaquePointers())
1416       ptr = rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, ptr);
1417 
1418     desc.setAlignedPtr(rewriter, loc, ptr);
1419     // Fill offset 0.
1420     auto attr = rewriter.getIntegerAttr(rewriter.getIndexType(), 0);
1421     auto zero = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, attr);
1422     desc.setOffset(rewriter, loc, zero);
1423 
1424     // Fill size and stride descriptors in memref.
1425     for (const auto &indexedSize :
1426          llvm::enumerate(targetMemRefType.getShape())) {
1427       int64_t index = indexedSize.index();
1428       auto sizeAttr =
1429           rewriter.getIntegerAttr(rewriter.getIndexType(), indexedSize.value());
1430       auto size = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, sizeAttr);
1431       desc.setSize(rewriter, loc, index, size);
1432       auto strideAttr = rewriter.getIntegerAttr(rewriter.getIndexType(),
1433                                                 (*targetStrides)[index]);
1434       auto stride = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, strideAttr);
1435       desc.setStride(rewriter, loc, index, stride);
1436     }
1437 
1438     rewriter.replaceOp(castOp, {desc});
1439     return success();
1440   }
1441 };
1442 
1443 /// Conversion pattern for a `vector.create_mask` (1-D scalable vectors only).
1444 /// Non-scalable versions of this operation are handled in Vector Transforms.
1445 class VectorCreateMaskOpRewritePattern
1446     : public OpRewritePattern<vector::CreateMaskOp> {
1447 public:
1448   explicit VectorCreateMaskOpRewritePattern(MLIRContext *context,
1449                                             bool enableIndexOpt)
1450       : OpRewritePattern<vector::CreateMaskOp>(context),
1451         force32BitVectorIndices(enableIndexOpt) {}
1452 
1453   LogicalResult matchAndRewrite(vector::CreateMaskOp op,
1454                                 PatternRewriter &rewriter) const override {
1455     auto dstType = op.getType();
1456     if (dstType.getRank() != 1 || !cast<VectorType>(dstType).isScalable())
1457       return failure();
1458     IntegerType idxType =
1459         force32BitVectorIndices ? rewriter.getI32Type() : rewriter.getI64Type();
1460     auto loc = op->getLoc();
1461     Value indices = rewriter.create<LLVM::StepVectorOp>(
1462         loc, LLVM::getVectorType(idxType, dstType.getShape()[0],
1463                                  /*isScalable=*/true));
1464     auto bound = getValueOrCreateCastToIndexLike(rewriter, loc, idxType,
1465                                                  op.getOperand(0));
1466     Value bounds = rewriter.create<SplatOp>(loc, indices.getType(), bound);
1467     Value comp = rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::slt,
1468                                                 indices, bounds);
1469     rewriter.replaceOp(op, comp);
1470     return success();
1471   }
1472 
1473 private:
1474   const bool force32BitVectorIndices;
1475 };
1476 
1477 class VectorPrintOpConversion : public ConvertOpToLLVMPattern<vector::PrintOp> {
1478 public:
1479   using ConvertOpToLLVMPattern<vector::PrintOp>::ConvertOpToLLVMPattern;
1480 
1481   // Lowering implementation that relies on a small runtime support library,
1482   // which only needs to provide a few printing methods (single value for all
1483   // data types, opening/closing bracket, comma, newline). The lowering splits
1484   // the vector into elementary printing operations. The advantage of this
1485   // approach is that the library can remain unaware of all low-level
1486   // implementation details of vectors while still supporting output of any
1487   // shaped and dimensioned vector.
1488   //
1489   // Note: This lowering only handles scalars, n-D vectors are broken into
1490   // printing scalars in loops in VectorToSCF.
1491   //
1492   // TODO: rely solely on libc in future? something else?
1493   //
1494   LogicalResult
1495   matchAndRewrite(vector::PrintOp printOp, OpAdaptor adaptor,
1496                   ConversionPatternRewriter &rewriter) const override {
1497     auto parent = printOp->getParentOfType<ModuleOp>();
1498     if (!parent)
1499       return failure();
1500 
1501     auto loc = printOp->getLoc();
1502 
1503     if (auto value = adaptor.getSource()) {
1504       Type printType = printOp.getPrintType();
1505       if (isa<VectorType>(printType)) {
1506         // Vectors should be broken into elementary print ops in VectorToSCF.
1507         return failure();
1508       }
1509       if (failed(emitScalarPrint(rewriter, parent, loc, printType, value)))
1510         return failure();
1511     }
1512 
1513     auto punct = printOp.getPunctuation();
1514     if (punct != PrintPunctuation::NoPunctuation) {
1515       emitCall(rewriter, printOp->getLoc(), [&] {
1516         switch (punct) {
1517         case PrintPunctuation::Close:
1518           return LLVM::lookupOrCreatePrintCloseFn(parent);
1519         case PrintPunctuation::Open:
1520           return LLVM::lookupOrCreatePrintOpenFn(parent);
1521         case PrintPunctuation::Comma:
1522           return LLVM::lookupOrCreatePrintCommaFn(parent);
1523         case PrintPunctuation::NewLine:
1524           return LLVM::lookupOrCreatePrintNewlineFn(parent);
1525         default:
1526           llvm_unreachable("unexpected punctuation");
1527         }
1528       }());
1529     }
1530 
1531     rewriter.eraseOp(printOp);
1532     return success();
1533   }
1534 
1535 private:
1536   enum class PrintConversion {
1537     // clang-format off
1538     None,
1539     ZeroExt64,
1540     SignExt64,
1541     Bitcast16
1542     // clang-format on
1543   };
1544 
1545   LogicalResult emitScalarPrint(ConversionPatternRewriter &rewriter,
1546                                 ModuleOp parent, Location loc, Type printType,
1547                                 Value value) const {
1548     if (typeConverter->convertType(printType) == nullptr)
1549       return failure();
1550 
1551     // Make sure element type has runtime support.
1552     PrintConversion conversion = PrintConversion::None;
1553     Operation *printer;
1554     if (printType.isF32()) {
1555       printer = LLVM::lookupOrCreatePrintF32Fn(parent);
1556     } else if (printType.isF64()) {
1557       printer = LLVM::lookupOrCreatePrintF64Fn(parent);
1558     } else if (printType.isF16()) {
1559       conversion = PrintConversion::Bitcast16; // bits!
1560       printer = LLVM::lookupOrCreatePrintF16Fn(parent);
1561     } else if (printType.isBF16()) {
1562       conversion = PrintConversion::Bitcast16; // bits!
1563       printer = LLVM::lookupOrCreatePrintBF16Fn(parent);
1564     } else if (printType.isIndex()) {
1565       printer = LLVM::lookupOrCreatePrintU64Fn(parent);
1566     } else if (auto intTy = dyn_cast<IntegerType>(printType)) {
1567       // Integers need a zero or sign extension on the operand
1568       // (depending on the source type) as well as a signed or
1569       // unsigned print method. Up to 64-bit is supported.
1570       unsigned width = intTy.getWidth();
1571       if (intTy.isUnsigned()) {
1572         if (width <= 64) {
1573           if (width < 64)
1574             conversion = PrintConversion::ZeroExt64;
1575           printer = LLVM::lookupOrCreatePrintU64Fn(parent);
1576         } else {
1577           return failure();
1578         }
1579       } else {
1580         assert(intTy.isSignless() || intTy.isSigned());
1581         if (width <= 64) {
1582           // Note that we *always* zero extend booleans (1-bit integers),
1583           // so that true/false is printed as 1/0 rather than -1/0.
1584           if (width == 1)
1585             conversion = PrintConversion::ZeroExt64;
1586           else if (width < 64)
1587             conversion = PrintConversion::SignExt64;
1588           printer = LLVM::lookupOrCreatePrintI64Fn(parent);
1589         } else {
1590           return failure();
1591         }
1592       }
1593     } else {
1594       return failure();
1595     }
1596 
1597     switch (conversion) {
1598     case PrintConversion::ZeroExt64:
1599       value = rewriter.create<arith::ExtUIOp>(
1600           loc, IntegerType::get(rewriter.getContext(), 64), value);
1601       break;
1602     case PrintConversion::SignExt64:
1603       value = rewriter.create<arith::ExtSIOp>(
1604           loc, IntegerType::get(rewriter.getContext(), 64), value);
1605       break;
1606     case PrintConversion::Bitcast16:
1607       value = rewriter.create<LLVM::BitcastOp>(
1608           loc, IntegerType::get(rewriter.getContext(), 16), value);
1609       break;
1610     case PrintConversion::None:
1611       break;
1612     }
1613     emitCall(rewriter, loc, printer, value);
1614     return success();
1615   }
1616 
1617   // Helper to emit a call.
1618   static void emitCall(ConversionPatternRewriter &rewriter, Location loc,
1619                        Operation *ref, ValueRange params = ValueRange()) {
1620     rewriter.create<LLVM::CallOp>(loc, TypeRange(), SymbolRefAttr::get(ref),
1621                                   params);
1622   }
1623 };
1624 
1625 /// The Splat operation is lowered to an insertelement + a shufflevector
1626 /// operation. Splat to only 0-d and 1-d vector result types are lowered.
1627 struct VectorSplatOpLowering : public ConvertOpToLLVMPattern<vector::SplatOp> {
1628   using ConvertOpToLLVMPattern<vector::SplatOp>::ConvertOpToLLVMPattern;
1629 
1630   LogicalResult
1631   matchAndRewrite(vector::SplatOp splatOp, OpAdaptor adaptor,
1632                   ConversionPatternRewriter &rewriter) const override {
1633     VectorType resultType = cast<VectorType>(splatOp.getType());
1634     if (resultType.getRank() > 1)
1635       return failure();
1636 
1637     // First insert it into an undef vector so we can shuffle it.
1638     auto vectorType = typeConverter->convertType(splatOp.getType());
1639     Value undef = rewriter.create<LLVM::UndefOp>(splatOp.getLoc(), vectorType);
1640     auto zero = rewriter.create<LLVM::ConstantOp>(
1641         splatOp.getLoc(),
1642         typeConverter->convertType(rewriter.getIntegerType(32)),
1643         rewriter.getZeroAttr(rewriter.getIntegerType(32)));
1644 
1645     // For 0-d vector, we simply do `insertelement`.
1646     if (resultType.getRank() == 0) {
1647       rewriter.replaceOpWithNewOp<LLVM::InsertElementOp>(
1648           splatOp, vectorType, undef, adaptor.getInput(), zero);
1649       return success();
1650     }
1651 
1652     // For 1-d vector, we additionally do a `vectorshuffle`.
1653     auto v = rewriter.create<LLVM::InsertElementOp>(
1654         splatOp.getLoc(), vectorType, undef, adaptor.getInput(), zero);
1655 
1656     int64_t width = cast<VectorType>(splatOp.getType()).getDimSize(0);
1657     SmallVector<int32_t> zeroValues(width, 0);
1658 
1659     // Shuffle the value across the desired number of elements.
1660     rewriter.replaceOpWithNewOp<LLVM::ShuffleVectorOp>(splatOp, v, undef,
1661                                                        zeroValues);
1662     return success();
1663   }
1664 };
1665 
1666 /// The Splat operation is lowered to an insertelement + a shufflevector
1667 /// operation. Splat to only 2+-d vector result types are lowered by the
1668 /// SplatNdOpLowering, the 1-d case is handled by SplatOpLowering.
1669 struct VectorSplatNdOpLowering : public ConvertOpToLLVMPattern<SplatOp> {
1670   using ConvertOpToLLVMPattern<SplatOp>::ConvertOpToLLVMPattern;
1671 
1672   LogicalResult
1673   matchAndRewrite(SplatOp splatOp, OpAdaptor adaptor,
1674                   ConversionPatternRewriter &rewriter) const override {
1675     VectorType resultType = splatOp.getType();
1676     if (resultType.getRank() <= 1)
1677       return failure();
1678 
1679     // First insert it into an undef vector so we can shuffle it.
1680     auto loc = splatOp.getLoc();
1681     auto vectorTypeInfo =
1682         LLVM::detail::extractNDVectorTypeInfo(resultType, *getTypeConverter());
1683     auto llvmNDVectorTy = vectorTypeInfo.llvmNDVectorTy;
1684     auto llvm1DVectorTy = vectorTypeInfo.llvm1DVectorTy;
1685     if (!llvmNDVectorTy || !llvm1DVectorTy)
1686       return failure();
1687 
1688     // Construct returned value.
1689     Value desc = rewriter.create<LLVM::UndefOp>(loc, llvmNDVectorTy);
1690 
1691     // Construct a 1-D vector with the splatted value that we insert in all the
1692     // places within the returned descriptor.
1693     Value vdesc = rewriter.create<LLVM::UndefOp>(loc, llvm1DVectorTy);
1694     auto zero = rewriter.create<LLVM::ConstantOp>(
1695         loc, typeConverter->convertType(rewriter.getIntegerType(32)),
1696         rewriter.getZeroAttr(rewriter.getIntegerType(32)));
1697     Value v = rewriter.create<LLVM::InsertElementOp>(loc, llvm1DVectorTy, vdesc,
1698                                                      adaptor.getInput(), zero);
1699 
1700     // Shuffle the value across the desired number of elements.
1701     int64_t width = resultType.getDimSize(resultType.getRank() - 1);
1702     SmallVector<int32_t> zeroValues(width, 0);
1703     v = rewriter.create<LLVM::ShuffleVectorOp>(loc, v, v, zeroValues);
1704 
1705     // Iterate of linear index, convert to coords space and insert splatted 1-D
1706     // vector in each position.
1707     nDVectorIterate(vectorTypeInfo, rewriter, [&](ArrayRef<int64_t> position) {
1708       desc = rewriter.create<LLVM::InsertValueOp>(loc, desc, v, position);
1709     });
1710     rewriter.replaceOp(splatOp, desc);
1711     return success();
1712   }
1713 };
1714 
1715 } // namespace
1716 
1717 /// Populate the given list with patterns that convert from Vector to LLVM.
1718 void mlir::populateVectorToLLVMConversionPatterns(
1719     LLVMTypeConverter &converter, RewritePatternSet &patterns,
1720     bool reassociateFPReductions, bool force32BitVectorIndices) {
1721   MLIRContext *ctx = converter.getDialect()->getContext();
1722   patterns.add<VectorFMAOpNDRewritePattern>(ctx);
1723   populateVectorInsertExtractStridedSliceTransforms(patterns);
1724   patterns.add<VectorReductionOpConversion>(converter, reassociateFPReductions);
1725   patterns.add<VectorCreateMaskOpRewritePattern>(ctx, force32BitVectorIndices);
1726   patterns
1727       .add<VectorBitCastOpConversion, VectorShuffleOpConversion,
1728            VectorExtractElementOpConversion, VectorExtractOpConversion,
1729            VectorFMAOp1DConversion, VectorInsertElementOpConversion,
1730            VectorInsertOpConversion, VectorPrintOpConversion,
1731            VectorTypeCastOpConversion, VectorScaleOpConversion,
1732            VectorLoadStoreConversion<vector::LoadOp, vector::LoadOpAdaptor>,
1733            VectorLoadStoreConversion<vector::MaskedLoadOp,
1734                                      vector::MaskedLoadOpAdaptor>,
1735            VectorLoadStoreConversion<vector::StoreOp, vector::StoreOpAdaptor>,
1736            VectorLoadStoreConversion<vector::MaskedStoreOp,
1737                                      vector::MaskedStoreOpAdaptor>,
1738            VectorGatherOpConversion, VectorScatterOpConversion,
1739            VectorExpandLoadOpConversion, VectorCompressStoreOpConversion,
1740            VectorSplatOpLowering, VectorSplatNdOpLowering,
1741            VectorScalableInsertOpLowering, VectorScalableExtractOpLowering,
1742            MaskedReductionOpConversion>(converter);
1743   // Transfer ops with rank > 1 are handled by VectorToSCF.
1744   populateVectorTransferLoweringPatterns(patterns, /*maxTransferRank=*/1);
1745 }
1746 
1747 void mlir::populateVectorToLLVMMatrixConversionPatterns(
1748     LLVMTypeConverter &converter, RewritePatternSet &patterns) {
1749   patterns.add<VectorMatmulOpConversion>(converter);
1750   patterns.add<VectorFlatTransposeOpConversion>(converter);
1751 }
1752