MLIR 24.0.0git
ConvertVectorToLLVM.cpp
Go to the documentation of this file.
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
10
32#include "llvm/ADT/APFloat.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/Support/Casting.h"
35
36#include <optional>
37
38using namespace mlir;
39using namespace mlir::vector;
40
41// Helper that picks the proper sequence for inserting.
42static Value insertOne(ConversionPatternRewriter &rewriter,
43 const LLVMTypeConverter &typeConverter, Location loc,
44 Value val1, Value val2, Type llvmType, int64_t rank,
45 int64_t pos) {
46 assert(rank > 0 && "0-D vector corner case should have been handled already");
47 if (rank == 1) {
48 Type idxType = typeConverter.convertType(rewriter.getIndexType());
49 auto constant = LLVM::ConstantOp::create(
50 rewriter, loc, idxType, rewriter.getIntegerAttr(idxType, pos));
51 return LLVM::InsertElementOp::create(rewriter, loc, llvmType, val1, val2,
52 constant);
53 }
54 return LLVM::InsertValueOp::create(rewriter, loc, val1, val2, pos);
55}
56
57// Helper that picks the proper sequence for extracting.
58static Value extractOne(ConversionPatternRewriter &rewriter,
59 const LLVMTypeConverter &typeConverter, Location loc,
60 Value val, Type llvmType, int64_t rank, int64_t pos) {
61 if (rank <= 1) {
62 Type idxType = typeConverter.convertType(rewriter.getIndexType());
63 auto constant = LLVM::ConstantOp::create(
64 rewriter, loc, idxType, rewriter.getIntegerAttr(idxType, pos));
65 return LLVM::ExtractElementOp::create(rewriter, loc, llvmType, val,
66 constant);
67 }
68 return LLVM::ExtractValueOp::create(rewriter, loc, val, pos);
69}
70
71// Helper that returns data layout alignment of a vector.
72LogicalResult getVectorAlignment(const LLVMTypeConverter &typeConverter,
73 VectorType vectorType, unsigned &align) {
74 Type convertedVectorTy = typeConverter.convertType(vectorType);
75 if (!convertedVectorTy)
76 return failure();
77
78 llvm::LLVMContext llvmContext;
79 align = LLVM::TypeToLLVMIRTranslator(llvmContext)
80 .getPreferredAlignment(convertedVectorTy,
81 typeConverter.getDataLayout());
82
83 return success();
84}
85
86// Helper that returns data layout alignment of a memref.
87LogicalResult getMemRefAlignment(const LLVMTypeConverter &typeConverter,
88 MemRefType memrefType, unsigned &align) {
89 Type elementTy = typeConverter.convertType(memrefType.getElementType());
90 if (!elementTy)
91 return failure();
92
93 // TODO: this should use the MLIR data layout when it becomes available and
94 // stop depending on translation.
95 llvm::LLVMContext llvmContext;
96 align = LLVM::TypeToLLVMIRTranslator(llvmContext)
97 .getPreferredAlignment(elementTy, typeConverter.getDataLayout());
98 return success();
99}
100
101// Helper to resolve the alignment for vector load/store, gather and scatter
102// ops. If useVectorAlignment is true, get the preferred alignment for the
103// vector type in the operation. This option is used for hardware backends with
104// vectorization. Otherwise, use the preferred alignment of the element type of
105// the memref. Note that if you choose to use vector alignment, the shape of the
106// vector type must be resolved before the ConvertVectorToLLVM pass is run.
107LogicalResult getVectorToLLVMAlignment(const LLVMTypeConverter &typeConverter,
108 VectorType vectorType,
109 MemRefType memrefType, unsigned &align,
110 bool useVectorAlignment) {
111 if (useVectorAlignment) {
112 if (failed(getVectorAlignment(typeConverter, vectorType, align))) {
113 return failure();
114 }
115 } else {
116 if (failed(getMemRefAlignment(typeConverter, memrefType, align))) {
117 return failure();
118 }
119 }
120 return success();
121}
122
123// Check if the last stride is non-unit and has a valid memory space.
124static LogicalResult isMemRefTypeSupported(MemRefType memRefType,
125 const LLVMTypeConverter &converter) {
126 if (!memRefType.isLastDimUnitStride())
127 return failure();
128 if (failed(converter.getMemRefAddressSpace(memRefType)))
129 return failure();
130 return success();
131}
132
133// Add an index vector component to a base pointer.
134static Value getIndexedPtrs(ConversionPatternRewriter &rewriter, Location loc,
135 const LLVMTypeConverter &typeConverter,
136 MemRefType memRefType, Value llvmMemref, Value base,
137 Value index, VectorType vectorType) {
138 assert(succeeded(isMemRefTypeSupported(memRefType, typeConverter)) &&
139 "unsupported memref type");
140 assert(vectorType.getRank() == 1 && "expected a 1-d vector type");
141 auto pType = MemRefDescriptor(llvmMemref).getElementPtrType();
142 auto ptrsType =
143 LLVM::getVectorType(pType, vectorType.getDimSize(0),
144 /*isScalable=*/vectorType.getScalableDims()[0]);
145 return LLVM::GEPOp::create(
146 rewriter, loc, ptrsType,
147 typeConverter.convertType(memRefType.getElementType()), base, index);
148}
149
150/// Convert `foldResult` into a Value. Integer attribute is converted to
151/// an LLVM constant op.
153 OpFoldResult foldResult) {
154 if (auto attr = dyn_cast<Attribute>(foldResult)) {
155 auto intAttr = cast<IntegerAttr>(attr);
156 return LLVM::ConstantOp::create(builder, loc, intAttr).getResult();
157 }
158
159 return cast<Value>(foldResult);
160}
161
162namespace {
163
164/// Trivial Vector to LLVM conversions
165using VectorScaleOpConversion =
167
168/// Conversion pattern for a vector.bitcast.
169class VectorBitCastOpConversion
170 : public ConvertOpToLLVMPattern<vector::BitCastOp> {
171public:
172 using ConvertOpToLLVMPattern<vector::BitCastOp>::ConvertOpToLLVMPattern;
173
174 LogicalResult
175 matchAndRewrite(vector::BitCastOp bitCastOp, OpAdaptor adaptor,
176 ConversionPatternRewriter &rewriter) const override {
177 // Only 0-D and 1-D vectors can be lowered to LLVM.
178 VectorType resultTy = bitCastOp.getResultVectorType();
179 if (resultTy.getRank() > 1)
180 return failure();
181 Type newResultTy = typeConverter->convertType(resultTy);
182 rewriter.replaceOpWithNewOp<LLVM::BitcastOp>(bitCastOp, newResultTy,
183 adaptor.getOperands()[0]);
184 return success();
185 }
186};
187
188/// Overloaded utility that replaces a vector.load, vector.store,
189/// vector.maskedload and vector.maskedstore with their respective LLVM
190/// couterparts.
191static void replaceLoadOrStoreOp(vector::LoadOp loadOp,
192 vector::LoadOpAdaptor adaptor,
193 VectorType vectorTy, Value ptr, unsigned align,
194 ConversionPatternRewriter &rewriter) {
195 rewriter.replaceOpWithNewOp<LLVM::LoadOp>(loadOp, vectorTy, ptr, align,
196 /*volatile_=*/false,
197 loadOp.getNontemporal());
198}
199
200static void replaceLoadOrStoreOp(vector::MaskedLoadOp loadOp,
201 vector::MaskedLoadOpAdaptor adaptor,
202 VectorType vectorTy, Value ptr, unsigned align,
203 ConversionPatternRewriter &rewriter) {
204 rewriter.replaceOpWithNewOp<LLVM::MaskedLoadOp>(
205 loadOp, vectorTy, ptr, adaptor.getMask(), adaptor.getPassThru(), align);
206}
207
208static void replaceLoadOrStoreOp(vector::StoreOp storeOp,
209 vector::StoreOpAdaptor adaptor,
210 VectorType vectorTy, Value ptr, unsigned align,
211 ConversionPatternRewriter &rewriter) {
212 rewriter.replaceOpWithNewOp<LLVM::StoreOp>(storeOp, adaptor.getValueToStore(),
213 ptr, align, /*volatile_=*/false,
214 storeOp.getNontemporal());
215}
216
217static void replaceLoadOrStoreOp(vector::MaskedStoreOp storeOp,
218 vector::MaskedStoreOpAdaptor adaptor,
219 VectorType vectorTy, Value ptr, unsigned align,
220 ConversionPatternRewriter &rewriter) {
221 rewriter.replaceOpWithNewOp<LLVM::MaskedStoreOp>(
222 storeOp, adaptor.getValueToStore(), ptr, adaptor.getMask(), align);
223}
224
225/// Conversion pattern for a vector.load, vector.store, vector.maskedload, and
226/// vector.maskedstore.
227template <class LoadOrStoreOp>
228class VectorLoadStoreConversion : public ConvertOpToLLVMPattern<LoadOrStoreOp> {
229public:
230 explicit VectorLoadStoreConversion(const LLVMTypeConverter &typeConv,
231 bool useVectorAlign,
232 bool enableGEPInboundsNuw)
233 : ConvertOpToLLVMPattern<LoadOrStoreOp>(typeConv),
234 useVectorAlignment(useVectorAlign),
235 enableGEPInboundsNuw(enableGEPInboundsNuw) {}
236
237 LogicalResult
238 matchAndRewrite(LoadOrStoreOp loadOrStoreOp,
239 typename LoadOrStoreOp::Adaptor adaptor,
240 ConversionPatternRewriter &rewriter) const override {
241 // Only 1-D vectors can be lowered to LLVM.
242 VectorType vectorTy = loadOrStoreOp.getVectorType();
243 if (vectorTy.getRank() > 1)
244 return failure();
245
246 auto loc = loadOrStoreOp->getLoc();
247 MemRefType memRefTy = loadOrStoreOp.getMemRefType();
248
249 // Resolve alignment.
250 // Explicit alignment takes priority over use-vector-alignment.
251 unsigned align = loadOrStoreOp.getAlignment().value_or(0);
252 if (!align &&
253 failed(getVectorToLLVMAlignment(*this->getTypeConverter(), vectorTy,
254 memRefTy, align, useVectorAlignment)))
255 return rewriter.notifyMatchFailure(loadOrStoreOp,
256 "could not resolve alignment");
257
258 // The verifier (verifyLoadStoreMemRefLayout) guarantees a valid memref
259 // layout. Assert to make the invariant explicit in the lowering code.
260 assert(vector::isValidLoadStoreMemRefLayout(vectorTy, memRefTy) &&
261 "invalid memref layout for vector load/store op");
262
263 // Resolve address.
264 // When --enable-gep-inbounds-nuw is set, emit inbounds|nuw on the GEP so
265 // LLVM can apply no-wrap optimizations on the index arithmetic. This
266 // assumes 0 <= idx < dim_size and non-negative strides; the caller is
267 // responsible for ensuring those conditions hold. Masked variants are
268 // designed for near-boundary access and never receive these flags.
269 LLVM::GEPNoWrapFlags noWrapFlags = LLVM::GEPNoWrapFlags::none;
270 if constexpr (std::is_same_v<LoadOrStoreOp, vector::LoadOp> ||
271 std::is_same_v<LoadOrStoreOp, vector::StoreOp>) {
272 if (enableGEPInboundsNuw) {
273 noWrapFlags = noWrapFlags | LLVM::GEPNoWrapFlags::inbounds;
274
275 // `nuw` additionally requires non-negative strides.
276 assert(
277 !(memref::hasNegativeStaticStride(memRefTy)) &&
278 "Invalid MemRef type - should have been rejected by Op verifier.");
279 noWrapFlags = noWrapFlags | LLVM::GEPNoWrapFlags::nuw;
280 }
281 }
282 auto vtype = cast<VectorType>(
283 this->typeConverter->convertType(loadOrStoreOp.getVectorType()));
284 Value dataPtr =
285 this->getStridedElementPtr(rewriter, loc, memRefTy, adaptor.getBase(),
286 adaptor.getIndices(), noWrapFlags);
287 replaceLoadOrStoreOp(loadOrStoreOp, adaptor, vtype, dataPtr, align,
288 rewriter);
289 return success();
290 }
291
292private:
293 // If true, use the preferred alignment of the vector type.
294 // If false, use the preferred alignment of the element type
295 // of the memref. This flag is intended for use with hardware
296 // backends that require alignment of vector operations.
297 const bool useVectorAlignment;
298 const bool enableGEPInboundsNuw;
299};
300
301/// Conversion pattern for a vector.gather.
302class VectorGatherOpConversion
303 : public ConvertOpToLLVMPattern<vector::GatherOp> {
304public:
305 explicit VectorGatherOpConversion(const LLVMTypeConverter &typeConv,
306 bool useVectorAlign)
307 : ConvertOpToLLVMPattern<vector::GatherOp>(typeConv),
308 useVectorAlignment(useVectorAlign) {}
309 using ConvertOpToLLVMPattern<vector::GatherOp>::ConvertOpToLLVMPattern;
310
311 LogicalResult
312 matchAndRewrite(vector::GatherOp gather, OpAdaptor adaptor,
313 ConversionPatternRewriter &rewriter) const override {
314 Location loc = gather->getLoc();
315 MemRefType memRefType = dyn_cast<MemRefType>(gather.getBaseType());
316 assert(memRefType && "The base should be bufferized");
317
318 // TODO: Add support for strided MemRef.
319 if (failed(isMemRefTypeSupported(memRefType, *this->getTypeConverter())))
320 return rewriter.notifyMatchFailure(gather, "memref type not supported");
321
322 VectorType vType = gather.getVectorType();
323 if (vType.getRank() > 1) {
324 return rewriter.notifyMatchFailure(
325 gather, "only 1-D vectors can be lowered to LLVM");
326 }
327
328 // Resolve alignment.
329 // Explicit alignment takes priority over use-vector-alignment.
330 unsigned align = gather.getAlignment().value_or(0);
331 if (!align &&
332 failed(getVectorToLLVMAlignment(*this->getTypeConverter(), vType,
333 memRefType, align, useVectorAlignment)))
334 return rewriter.notifyMatchFailure(gather, "could not resolve alignment");
335
336 // Resolve address.
337 Value ptr = getStridedElementPtr(rewriter, loc, memRefType,
338 adaptor.getBase(), adaptor.getOffsets());
339 Value base = adaptor.getBase();
340 Value ptrs =
341 getIndexedPtrs(rewriter, loc, *this->getTypeConverter(), memRefType,
342 base, ptr, adaptor.getIndices(), vType);
343
344 // Replace with the gather intrinsic.
345 rewriter.replaceOpWithNewOp<LLVM::masked_gather>(
346 gather, typeConverter->convertType(vType), ptrs, adaptor.getMask(),
347 adaptor.getPassThru(), align);
348 return success();
349 }
350
351private:
352 // If true, use the preferred alignment of the vector type.
353 // If false, use the preferred alignment of the element type
354 // of the memref. This flag is intended for use with hardware
355 // backends that require alignment of vector operations.
356 const bool useVectorAlignment;
357};
358
359/// Conversion pattern for a vector.scatter.
360class VectorScatterOpConversion
361 : public ConvertOpToLLVMPattern<vector::ScatterOp> {
362public:
363 explicit VectorScatterOpConversion(const LLVMTypeConverter &typeConv,
364 bool useVectorAlign)
365 : ConvertOpToLLVMPattern<vector::ScatterOp>(typeConv),
366 useVectorAlignment(useVectorAlign) {}
367
368 using ConvertOpToLLVMPattern<vector::ScatterOp>::ConvertOpToLLVMPattern;
369
370 LogicalResult
371 matchAndRewrite(vector::ScatterOp scatter, OpAdaptor adaptor,
372 ConversionPatternRewriter &rewriter) const override {
373 auto loc = scatter->getLoc();
374 auto memRefType = dyn_cast<MemRefType>(scatter.getBaseType());
375 assert(memRefType && "The base should be bufferized");
376
377 // TODO: Add support for strided MemRef.
378 if (failed(isMemRefTypeSupported(memRefType, *this->getTypeConverter())))
379 return rewriter.notifyMatchFailure(scatter, "memref type not supported");
380
381 VectorType vType = scatter.getVectorType();
382 if (vType.getRank() > 1) {
383 return rewriter.notifyMatchFailure(
384 scatter, "only 1-D vectors can be lowered to LLVM");
385 }
386
387 // Resolve alignment.
388 // Explicit alignment takes priority over use-vector-alignment.
389 unsigned align = scatter.getAlignment().value_or(0);
390 if (!align &&
391 failed(getVectorToLLVMAlignment(*this->getTypeConverter(), vType,
392 memRefType, align, useVectorAlignment)))
393 return rewriter.notifyMatchFailure(scatter,
394 "could not resolve alignment");
395
396 // Resolve address.
397 Value ptr = getStridedElementPtr(rewriter, loc, memRefType,
398 adaptor.getBase(), adaptor.getOffsets());
399 Value ptrs =
400 getIndexedPtrs(rewriter, loc, *this->getTypeConverter(), memRefType,
401 adaptor.getBase(), ptr, adaptor.getIndices(), vType);
402
403 // Replace with the scatter intrinsic.
404 rewriter.replaceOpWithNewOp<LLVM::masked_scatter>(
405 scatter, adaptor.getValueToStore(), ptrs, adaptor.getMask(), align);
406 return success();
407 }
408
409private:
410 // If true, use the preferred alignment of the vector type.
411 // If false, use the preferred alignment of the element type
412 // of the memref. This flag is intended for use with hardware
413 // backends that require alignment of vector operations.
414 const bool useVectorAlignment;
415};
416
417/// Conversion pattern for a vector.expandload.
418class VectorExpandLoadOpConversion
419 : public ConvertOpToLLVMPattern<vector::ExpandLoadOp> {
420public:
421 using ConvertOpToLLVMPattern<vector::ExpandLoadOp>::ConvertOpToLLVMPattern;
422
423 LogicalResult
424 matchAndRewrite(vector::ExpandLoadOp expand, OpAdaptor adaptor,
425 ConversionPatternRewriter &rewriter) const override {
426 auto loc = expand->getLoc();
427 MemRefType memRefType = expand.getMemRefType();
428
429 // Resolve address.
430 auto vtype = typeConverter->convertType(expand.getVectorType());
431 Value ptr = getStridedElementPtr(rewriter, loc, memRefType,
432 adaptor.getBase(), adaptor.getIndices());
433
434 // From:
435 // https://llvm.org/docs/LangRef.html#llvm-masked-expandload-intrinsics
436 // The pointer alignment defaults to 1.
437 uint64_t alignment = expand.getAlignment().value_or(1);
438
439 rewriter.replaceOpWithNewOp<LLVM::masked_expandload>(
440 expand, vtype, ptr, adaptor.getMask(), adaptor.getPassThru(),
441 alignment);
442 return success();
443 }
444};
445
446/// Conversion pattern for a vector.compressstore.
447class VectorCompressStoreOpConversion
448 : public ConvertOpToLLVMPattern<vector::CompressStoreOp> {
449public:
450 using ConvertOpToLLVMPattern<vector::CompressStoreOp>::ConvertOpToLLVMPattern;
451
452 LogicalResult
453 matchAndRewrite(vector::CompressStoreOp compress, OpAdaptor adaptor,
454 ConversionPatternRewriter &rewriter) const override {
455 auto loc = compress->getLoc();
456 MemRefType memRefType = compress.getMemRefType();
457
458 // Resolve address.
459 Value ptr = getStridedElementPtr(rewriter, loc, memRefType,
460 adaptor.getBase(), adaptor.getIndices());
461
462 // From:
463 // https://llvm.org/docs/LangRef.html#llvm-masked-compressstore-intrinsics
464 // The pointer alignment defaults to 1.
465 uint64_t alignment = compress.getAlignment().value_or(1);
466
467 rewriter.replaceOpWithNewOp<LLVM::masked_compressstore>(
468 compress, adaptor.getValueToStore(), ptr, adaptor.getMask(), alignment);
469 return success();
470 }
471};
472
473/// Reduction neutral classes for overloading.
474class ReductionNeutralZero {};
475class ReductionNeutralIntOne {};
476class ReductionNeutralFPOne {};
477class ReductionNeutralAllOnes {};
478class ReductionNeutralSIntMin {};
479class ReductionNeutralUIntMin {};
480class ReductionNeutralSIntMax {};
481class ReductionNeutralUIntMax {};
482class ReductionNeutralFPQNaN {};
483class ReductionNeutralFPNegQNaN {};
484class ReductionNeutralFPNegInf {};
485class ReductionNeutralFPPosInf {};
486class ReductionNeutralFPLowestFinite {};
487class ReductionNeutralFPLargestFinite {};
488
489/// Create the reduction neutral zero value.
490static Value createReductionNeutralValue(ReductionNeutralZero neutral,
491 ConversionPatternRewriter &rewriter,
492 Location loc, Type llvmType) {
493 return LLVM::ConstantOp::create(rewriter, loc, llvmType,
494 rewriter.getZeroAttr(llvmType));
495}
496
497/// Create the reduction neutral integer one value.
498static Value createReductionNeutralValue(ReductionNeutralIntOne neutral,
499 ConversionPatternRewriter &rewriter,
500 Location loc, Type llvmType) {
501 return LLVM::ConstantOp::create(rewriter, loc, llvmType,
502 rewriter.getIntegerAttr(llvmType, 1));
503}
504
505/// Create the reduction neutral fp one value.
506static Value createReductionNeutralValue(ReductionNeutralFPOne neutral,
507 ConversionPatternRewriter &rewriter,
508 Location loc, Type llvmType) {
509 return LLVM::ConstantOp::create(rewriter, loc, llvmType,
510 rewriter.getFloatAttr(llvmType, 1.0));
511}
512
513/// Create the reduction neutral all-ones value.
514static Value createReductionNeutralValue(ReductionNeutralAllOnes neutral,
515 ConversionPatternRewriter &rewriter,
516 Location loc, Type llvmType) {
517 return LLVM::ConstantOp::create(
518 rewriter, loc, llvmType,
519 rewriter.getIntegerAttr(
520 llvmType, llvm::APInt::getAllOnes(llvmType.getIntOrFloatBitWidth())));
521}
522
523/// Create the reduction neutral signed int minimum value.
524static Value createReductionNeutralValue(ReductionNeutralSIntMin neutral,
525 ConversionPatternRewriter &rewriter,
526 Location loc, Type llvmType) {
527 return LLVM::ConstantOp::create(
528 rewriter, loc, llvmType,
529 rewriter.getIntegerAttr(llvmType, llvm::APInt::getSignedMinValue(
530 llvmType.getIntOrFloatBitWidth())));
531}
532
533/// Create the reduction neutral unsigned int minimum value.
534static Value createReductionNeutralValue(ReductionNeutralUIntMin neutral,
535 ConversionPatternRewriter &rewriter,
536 Location loc, Type llvmType) {
537 return LLVM::ConstantOp::create(
538 rewriter, loc, llvmType,
539 rewriter.getIntegerAttr(llvmType, llvm::APInt::getMinValue(
540 llvmType.getIntOrFloatBitWidth())));
541}
542
543/// Create the reduction neutral signed int maximum value.
544static Value createReductionNeutralValue(ReductionNeutralSIntMax neutral,
545 ConversionPatternRewriter &rewriter,
546 Location loc, Type llvmType) {
547 return LLVM::ConstantOp::create(
548 rewriter, loc, llvmType,
549 rewriter.getIntegerAttr(llvmType, llvm::APInt::getSignedMaxValue(
550 llvmType.getIntOrFloatBitWidth())));
551}
552
553/// Create the reduction neutral unsigned int maximum value.
554static Value createReductionNeutralValue(ReductionNeutralUIntMax neutral,
555 ConversionPatternRewriter &rewriter,
556 Location loc, Type llvmType) {
557 return LLVM::ConstantOp::create(
558 rewriter, loc, llvmType,
559 rewriter.getIntegerAttr(llvmType, llvm::APInt::getMaxValue(
560 llvmType.getIntOrFloatBitWidth())));
561}
562
563/// Create the reduction neutral quiet NaN value.
564static Value createReductionNeutralValue(ReductionNeutralFPQNaN neutral,
565 ConversionPatternRewriter &rewriter,
566 Location loc, Type llvmType) {
567 auto floatType = cast<FloatType>(llvmType);
568 return LLVM::ConstantOp::create(
569 rewriter, loc, llvmType,
570 rewriter.getFloatAttr(
571 llvmType, llvm::APFloat::getQNaN(floatType.getFloatSemantics(),
572 /*Negative=*/false)));
573}
574
575/// Create the reduction neutral negative quiet NaN value.
576static Value createReductionNeutralValue(ReductionNeutralFPNegQNaN neutral,
577 ConversionPatternRewriter &rewriter,
578 Location loc, Type llvmType) {
579 auto floatType = cast<FloatType>(llvmType);
580 return LLVM::ConstantOp::create(
581 rewriter, loc, llvmType,
582 rewriter.getFloatAttr(
583 llvmType, llvm::APFloat::getQNaN(floatType.getFloatSemantics(),
584 /*Negative=*/true)));
585}
586
587/// Create the reduction neutral negative infinity value.
588static Value createReductionNeutralValue(ReductionNeutralFPNegInf neutral,
589 ConversionPatternRewriter &rewriter,
590 Location loc, Type llvmType) {
591 auto floatType = cast<FloatType>(llvmType);
592 return LLVM::ConstantOp::create(
593 rewriter, loc, llvmType,
594 rewriter.getFloatAttr(llvmType,
595 llvm::APFloat::getInf(floatType.getFloatSemantics(),
596 /*Negative=*/true)));
597}
598
599/// Create the reduction neutral positive infinity value.
600static Value createReductionNeutralValue(ReductionNeutralFPPosInf neutral,
601 ConversionPatternRewriter &rewriter,
602 Location loc, Type llvmType) {
603 auto floatType = cast<FloatType>(llvmType);
604 return LLVM::ConstantOp::create(
605 rewriter, loc, llvmType,
606 rewriter.getFloatAttr(llvmType,
607 llvm::APFloat::getInf(floatType.getFloatSemantics(),
608 /*Negative=*/false)));
609}
610
611/// Create the reduction neutral lowest finite value.
612static Value createReductionNeutralValue(ReductionNeutralFPLowestFinite neutral,
613 ConversionPatternRewriter &rewriter,
614 Location loc, Type llvmType) {
615 auto floatType = cast<FloatType>(llvmType);
616 return LLVM::ConstantOp::create(
617 rewriter, loc, llvmType,
618 rewriter.getFloatAttr(
619 llvmType, llvm::APFloat::getLargest(floatType.getFloatSemantics(),
620 /*Negative=*/true)));
621}
622
623/// Create the reduction neutral largest finite value.
624static Value
625createReductionNeutralValue(ReductionNeutralFPLargestFinite neutral,
626 ConversionPatternRewriter &rewriter, Location loc,
627 Type llvmType) {
628 auto floatType = cast<FloatType>(llvmType);
629 return LLVM::ConstantOp::create(
630 rewriter, loc, llvmType,
631 rewriter.getFloatAttr(
632 llvmType, llvm::APFloat::getLargest(floatType.getFloatSemantics(),
633 /*Negative=*/false)));
634}
635
636/// Returns `accumulator` if it has a valid value. Otherwise, creates and
637/// returns a new accumulator value using `ReductionNeutral`.
638template <class ReductionNeutral>
639static Value getOrCreateAccumulator(ConversionPatternRewriter &rewriter,
640 Location loc, Type llvmType,
641 Value accumulator) {
642 if (accumulator)
643 return accumulator;
644
645 return createReductionNeutralValue(ReductionNeutral(), rewriter, loc,
646 llvmType);
647}
648
649/// Creates a value with the 1-D vector shape provided in `llvmType`.
650/// This is used as effective vector length by some intrinsics supporting
651/// dynamic vector lengths at runtime.
652static Value createVectorLengthValue(ConversionPatternRewriter &rewriter,
653 Location loc, Type llvmType) {
654 VectorType vType = cast<VectorType>(llvmType);
655 auto vShape = vType.getShape();
656 assert(vShape.size() == 1 && "Unexpected multi-dim vector type");
657
658 Value baseVecLength = LLVM::ConstantOp::create(
659 rewriter, loc, rewriter.getI32Type(),
660 rewriter.getIntegerAttr(rewriter.getI32Type(), vShape[0]));
661
662 if (!vType.getScalableDims()[0])
663 return baseVecLength;
664
665 // For a scalable vector type, create and return `vScale * baseVecLength`.
666 Value vScale = vector::VectorScaleOp::create(rewriter, loc);
667 vScale =
668 arith::IndexCastOp::create(rewriter, loc, rewriter.getI32Type(), vScale);
669 Value scalableVecLength =
670 arith::MulIOp::create(rewriter, loc, baseVecLength, vScale);
671 return scalableVecLength;
672}
673
674/// Helper method to lower a `vector.reduction` op that performs an arithmetic
675/// operation like add,mul, etc.. `VectorOp` is the LLVM vector intrinsic to use
676/// and `ScalarOp` is the scalar operation used to add the accumulation value if
677/// non-null.
678template <class LLVMRedIntrinOp, class ScalarOp>
679static Value createIntegerReductionArithmeticOpLowering(
680 ConversionPatternRewriter &rewriter, Location loc, Type llvmType,
681 Value vectorOperand, Value accumulator) {
682
683 Value result =
684 LLVMRedIntrinOp::create(rewriter, loc, llvmType, vectorOperand);
685
686 if (accumulator)
687 result = ScalarOp::create(rewriter, loc, accumulator, result);
688 return result;
689}
690
691/// Helper method to lower a `vector.reduction` operation that performs
692/// a comparison operation like `min`/`max`. `VectorOp` is the LLVM vector
693/// intrinsic to use and `predicate` is the predicate to use to compare+combine
694/// the accumulator value if non-null.
695template <class LLVMRedIntrinOp>
696static Value createIntegerReductionComparisonOpLowering(
697 ConversionPatternRewriter &rewriter, Location loc, Type llvmType,
698 Value vectorOperand, Value accumulator, LLVM::ICmpPredicate predicate) {
699 Value result =
700 LLVMRedIntrinOp::create(rewriter, loc, llvmType, vectorOperand);
701 if (accumulator) {
702 Value cmp =
703 LLVM::ICmpOp::create(rewriter, loc, predicate, accumulator, result);
704 result = LLVM::SelectOp::create(rewriter, loc, cmp, accumulator, result);
705 }
706 return result;
707}
708
709namespace {
710template <typename Source>
711struct VectorToScalarMapper;
712template <>
713struct VectorToScalarMapper<LLVM::vector_reduce_fmaximum> {
714 using Type = LLVM::MaximumOp;
715};
716template <>
717struct VectorToScalarMapper<LLVM::vector_reduce_fminimum> {
718 using Type = LLVM::MinimumOp;
719};
720template <>
721struct VectorToScalarMapper<LLVM::vector_reduce_fmax> {
722 using Type = LLVM::MaxNumOp;
723};
724template <>
725struct VectorToScalarMapper<LLVM::vector_reduce_fmin> {
726 using Type = LLVM::MinNumOp;
727};
728template <>
729struct VectorToScalarMapper<LLVM::vector_reduce_fmaximumnum> {
730 using Type = LLVM::MaximumNumOp;
731};
732template <>
733struct VectorToScalarMapper<LLVM::vector_reduce_fminimumnum> {
734 using Type = LLVM::MinimumNumOp;
735};
736} // namespace
737
738template <class LLVMRedIntrinOp>
739static Value createFPReductionComparisonOpLowering(
740 ConversionPatternRewriter &rewriter, Location loc, Type llvmType,
741 Value vectorOperand, Value accumulator, LLVM::FastmathFlagsAttr fmf) {
742 Value result =
743 LLVMRedIntrinOp::create(rewriter, loc, llvmType, vectorOperand, fmf);
744
745 if (accumulator) {
746 result = VectorToScalarMapper<LLVMRedIntrinOp>::Type::create(
747 rewriter, loc, result, accumulator);
748 }
749
750 return result;
751}
752
753/// Mask neutral classes for overloading.
754class MaskNeutralFMaximumNum {};
755class MaskNeutralFMinimumNum {};
756
757/// Get the mask neutral value for a `fmaximumnum` reduction. `maximumnum`
758/// ignores NaN operands, making a quiet NaN the identity element. When `nnan`
759/// promises no NaN reaches the reduction, fall back to the smallest
760/// representable value, which `ninf` further constrains to be finite.
761static llvm::APFloat getMaskNeutralValue(MaskNeutralFMaximumNum,
762 const llvm::fltSemantics &semantics,
763 bool noNaNs, bool noInfs) {
764 if (!noNaNs)
765 return llvm::APFloat::getQNaN(semantics);
766 if (noInfs)
767 return llvm::APFloat::getLargest(semantics, /*Negative=*/true);
768 return llvm::APFloat::getInf(semantics, /*Negative=*/true);
769}
770
771/// Get the mask neutral value for a `fminimumnum` reduction. See the
772/// `fmaximumnum` overload above for the rationale.
773static llvm::APFloat getMaskNeutralValue(MaskNeutralFMinimumNum,
774 const llvm::fltSemantics &semantics,
775 bool noNaNs, bool noInfs) {
776 if (!noNaNs)
777 return llvm::APFloat::getQNaN(semantics);
778 if (noInfs)
779 return llvm::APFloat::getLargest(semantics);
780 return llvm::APFloat::getInf(semantics);
781}
782
783/// Lowers masked `fmaximumnum` and `fminimumnum` reductions using the
784/// non-masked intrinsics, since LLVM has no predicated counterpart for them.
785/// Inactive lanes are replaced by a mask neutral value before reducing.
786/// TODO: Switch to `lowerPredicatedReductionWithStartValue` once
787/// `llvm.vp.reduce.fmaximumnum`/`fminimumnum` are added to LLVM IR.
788template <class LLVMRedIntrinOp, class MaskNeutral>
789static Value
790lowerMaskedReductionWithRegular(ConversionPatternRewriter &rewriter,
791 Location loc, Type llvmType,
792 Value vectorOperand, Value accumulator,
793 Value mask, LLVM::FastmathFlagsAttr fmf) {
794 const auto &floatSemantics = cast<FloatType>(llvmType).getFloatSemantics();
795 auto value = getMaskNeutralValue(
796 MaskNeutral{}, floatSemantics,
797 LLVM::bitEnumContainsAny(fmf.getValue(), LLVM::FastmathFlags::nnan),
798 LLVM::bitEnumContainsAny(fmf.getValue(), LLVM::FastmathFlags::ninf));
799 Type vectorType = vectorOperand.getType();
800 auto denseValue = DenseElementsAttr::get(cast<ShapedType>(vectorType), value);
801 const Value vectorMaskNeutral =
802 LLVM::ConstantOp::create(rewriter, loc, vectorType, denseValue);
803 const Value selectedVectorByMask = LLVM::SelectOp::create(
804 rewriter, loc, mask, vectorOperand, vectorMaskNeutral);
805 return createFPReductionComparisonOpLowering<LLVMRedIntrinOp>(
806 rewriter, loc, llvmType, selectedVectorByMask, accumulator, fmf);
807}
808
809template <class LLVMRedIntrinOp, class ReductionNeutral>
810static Value
811lowerReductionWithStartValue(ConversionPatternRewriter &rewriter, Location loc,
812 Type llvmType, Value vectorOperand,
813 Value accumulator, LLVM::FastmathFlagsAttr fmf) {
814 accumulator = getOrCreateAccumulator<ReductionNeutral>(rewriter, loc,
815 llvmType, accumulator);
816 return LLVMRedIntrinOp::create(rewriter, loc, llvmType,
817 /*start_value=*/accumulator, vectorOperand,
818 fmf);
819}
820
821template <class LLVMVPRedIntrinOp, class ReductionNeutral>
822static Value lowerPredicatedReductionWithStartValue(
823 ConversionPatternRewriter &rewriter, Location loc, Type llvmType,
824 Value vectorOperand, Value accumulator, Value mask) {
825 accumulator = getOrCreateAccumulator<ReductionNeutral>(rewriter, loc,
826 llvmType, accumulator);
827 Value vectorLength =
828 createVectorLengthValue(rewriter, loc, vectorOperand.getType());
829 return LLVMVPRedIntrinOp::create(rewriter, loc, llvmType,
830 /*satrt_value=*/accumulator, vectorOperand,
831 mask, vectorLength);
832}
833
834template <class LLVMIntVPRedIntrinOp, class IntReductionNeutral,
835 class LLVMFPVPRedIntrinOp, class FPReductionNeutral>
836static Value lowerPredicatedReductionWithStartValue(
837 ConversionPatternRewriter &rewriter, Location loc, Type llvmType,
838 Value vectorOperand, Value accumulator, Value mask) {
839 if (llvmType.isIntOrIndex())
840 return lowerPredicatedReductionWithStartValue<LLVMIntVPRedIntrinOp,
841 IntReductionNeutral>(
842 rewriter, loc, llvmType, vectorOperand, accumulator, mask);
843
844 // FP dispatch.
845 return lowerPredicatedReductionWithStartValue<LLVMFPVPRedIntrinOp,
846 FPReductionNeutral>(
847 rewriter, loc, llvmType, vectorOperand, accumulator, mask);
848}
849
850/// Conversion pattern for all vector reductions.
851class VectorReductionOpConversion
852 : public ConvertOpToLLVMPattern<vector::ReductionOp> {
853public:
854 explicit VectorReductionOpConversion(const LLVMTypeConverter &typeConv,
855 bool reassociateFPRed)
856 : ConvertOpToLLVMPattern<vector::ReductionOp>(typeConv),
857 reassociateFPReductions(reassociateFPRed) {}
858
859 LogicalResult
860 matchAndRewrite(vector::ReductionOp reductionOp, OpAdaptor adaptor,
861 ConversionPatternRewriter &rewriter) const override {
862 auto kind = reductionOp.getKind();
863 Type eltType = reductionOp.getResult().getType();
864 Type llvmType = typeConverter->convertType(eltType);
865 Value operand = adaptor.getVector();
866 Value acc = adaptor.getAcc();
867 Location loc = reductionOp.getLoc();
868
869 if (eltType.isIntOrIndex()) {
870 // Integer reductions: add/mul/min/max/and/or/xor.
871 Value result;
872 switch (kind) {
873 case vector::CombiningKind::ADD:
874 result =
875 createIntegerReductionArithmeticOpLowering<LLVM::vector_reduce_add,
876 LLVM::AddOp>(
877 rewriter, loc, llvmType, operand, acc);
878 break;
879 case vector::CombiningKind::MUL:
880 result =
881 createIntegerReductionArithmeticOpLowering<LLVM::vector_reduce_mul,
882 LLVM::MulOp>(
883 rewriter, loc, llvmType, operand, acc);
884 break;
885 case vector::CombiningKind::MINUI:
886 result = createIntegerReductionComparisonOpLowering<
887 LLVM::vector_reduce_umin>(rewriter, loc, llvmType, operand, acc,
888 LLVM::ICmpPredicate::ule);
889 break;
890 case vector::CombiningKind::MINSI:
891 result = createIntegerReductionComparisonOpLowering<
892 LLVM::vector_reduce_smin>(rewriter, loc, llvmType, operand, acc,
893 LLVM::ICmpPredicate::sle);
894 break;
895 case vector::CombiningKind::MAXUI:
896 result = createIntegerReductionComparisonOpLowering<
897 LLVM::vector_reduce_umax>(rewriter, loc, llvmType, operand, acc,
898 LLVM::ICmpPredicate::uge);
899 break;
900 case vector::CombiningKind::MAXSI:
901 result = createIntegerReductionComparisonOpLowering<
902 LLVM::vector_reduce_smax>(rewriter, loc, llvmType, operand, acc,
903 LLVM::ICmpPredicate::sge);
904 break;
905 case vector::CombiningKind::AND:
906 result =
907 createIntegerReductionArithmeticOpLowering<LLVM::vector_reduce_and,
908 LLVM::AndOp>(
909 rewriter, loc, llvmType, operand, acc);
910 break;
911 case vector::CombiningKind::OR:
912 result =
913 createIntegerReductionArithmeticOpLowering<LLVM::vector_reduce_or,
914 LLVM::OrOp>(
915 rewriter, loc, llvmType, operand, acc);
916 break;
917 case vector::CombiningKind::XOR:
918 result =
919 createIntegerReductionArithmeticOpLowering<LLVM::vector_reduce_xor,
920 LLVM::XOrOp>(
921 rewriter, loc, llvmType, operand, acc);
922 break;
923 default:
924 return failure();
925 }
926 rewriter.replaceOp(reductionOp, result);
927
928 return success();
929 }
930
931 if (!isa<FloatType>(eltType))
932 return failure();
933
934 arith::FastMathFlagsAttr fMFAttr = reductionOp.getFastMathFlagsAttr();
935 LLVM::FastmathFlagsAttr fmf = LLVM::FastmathFlagsAttr::get(
936 reductionOp.getContext(),
937 convertArithFastMathFlagsToLLVM(fMFAttr.getValue()));
938 fmf = LLVM::FastmathFlagsAttr::get(
939 reductionOp.getContext(),
940 fmf.getValue() | (reassociateFPReductions ? LLVM::FastmathFlags::reassoc
941 : LLVM::FastmathFlags::none));
942
943 // Floating-point reductions: add/mul/min/max
944 Value result;
945 switch (kind) {
946 case vector::CombiningKind::ADD:
947 result = lowerReductionWithStartValue<LLVM::vector_reduce_fadd,
948 ReductionNeutralZero>(
949 rewriter, loc, llvmType, operand, acc, fmf);
950 break;
951 case vector::CombiningKind::MUL:
952 result = lowerReductionWithStartValue<LLVM::vector_reduce_fmul,
953 ReductionNeutralFPOne>(
954 rewriter, loc, llvmType, operand, acc, fmf);
955 break;
956 case vector::CombiningKind::MINIMUMF:
957 result =
958 createFPReductionComparisonOpLowering<LLVM::vector_reduce_fminimum>(
959 rewriter, loc, llvmType, operand, acc, fmf);
960 break;
961 case vector::CombiningKind::MAXIMUMF:
962 result =
963 createFPReductionComparisonOpLowering<LLVM::vector_reduce_fmaximum>(
964 rewriter, loc, llvmType, operand, acc, fmf);
965 break;
966 case vector::CombiningKind::MINNUMF:
967 result = createFPReductionComparisonOpLowering<LLVM::vector_reduce_fmin>(
968 rewriter, loc, llvmType, operand, acc, fmf);
969 break;
970 case vector::CombiningKind::MAXNUMF:
971 result = createFPReductionComparisonOpLowering<LLVM::vector_reduce_fmax>(
972 rewriter, loc, llvmType, operand, acc, fmf);
973 break;
974 case vector::CombiningKind::MAXIMUMNUMF:
975 result = createFPReductionComparisonOpLowering<
976 LLVM::vector_reduce_fmaximumnum>(rewriter, loc, llvmType, operand,
977 acc, fmf);
978 break;
979 case vector::CombiningKind::MINIMUMNUMF:
980 result = createFPReductionComparisonOpLowering<
981 LLVM::vector_reduce_fminimumnum>(rewriter, loc, llvmType, operand,
982 acc, fmf);
983 break;
984 default:
985 return failure();
986 }
987
988 rewriter.replaceOp(reductionOp, result);
989 return success();
990 }
991
992private:
993 const bool reassociateFPReductions;
994};
995
996/// Base class to convert a `vector.mask` operation while matching traits
997/// of the maskable operation nested inside. A `VectorMaskOpConversionBase`
998/// instance matches against a `vector.mask` operation. The `matchAndRewrite`
999/// method performs a second match against the maskable operation `MaskedOp`.
1000/// Finally, it invokes the virtual method `matchAndRewriteMaskableOp` to be
1001/// implemented by the concrete conversion classes. This method can match
1002/// against specific traits of the `vector.mask` and the maskable operation. It
1003/// must replace the `vector.mask` operation.
1004template <class MaskedOp>
1005class VectorMaskOpConversionBase
1006 : public ConvertOpToLLVMPattern<vector::MaskOp> {
1007public:
1008 using ConvertOpToLLVMPattern<vector::MaskOp>::ConvertOpToLLVMPattern;
1009
1010 LogicalResult
1011 matchAndRewrite(vector::MaskOp maskOp, OpAdaptor adaptor,
1012 ConversionPatternRewriter &rewriter) const final {
1013 // Match against the maskable operation kind.
1014 auto maskedOp = llvm::dyn_cast_or_null<MaskedOp>(maskOp.getMaskableOp());
1015 if (!maskedOp)
1016 return failure();
1017 return matchAndRewriteMaskableOp(maskOp, maskedOp, rewriter);
1018 }
1019
1020protected:
1021 virtual LogicalResult
1022 matchAndRewriteMaskableOp(vector::MaskOp maskOp,
1023 vector::MaskableOpInterface maskableOp,
1024 ConversionPatternRewriter &rewriter) const = 0;
1025};
1026
1027class MaskedReductionOpConversion
1028 : public VectorMaskOpConversionBase<vector::ReductionOp> {
1029
1030public:
1031 using VectorMaskOpConversionBase<
1032 vector::ReductionOp>::VectorMaskOpConversionBase;
1033
1034 LogicalResult matchAndRewriteMaskableOp(
1035 vector::MaskOp maskOp, MaskableOpInterface maskableOp,
1036 ConversionPatternRewriter &rewriter) const override {
1037 auto reductionOp = cast<ReductionOp>(maskableOp.getOperation());
1038 auto kind = reductionOp.getKind();
1039 Type eltType = reductionOp.getResult().getType();
1040 Type llvmType = typeConverter->convertType(eltType);
1041 Value operand = reductionOp.getVector();
1042 Value acc = reductionOp.getAcc();
1043 Location loc = reductionOp.getLoc();
1044
1045 arith::FastMathFlagsAttr fMFAttr = reductionOp.getFastMathFlagsAttr();
1046 LLVM::FastmathFlagsAttr fmf = LLVM::FastmathFlagsAttr::get(
1047 reductionOp.getContext(),
1048 convertArithFastMathFlagsToLLVM(fMFAttr.getValue()));
1049 const bool noInfs =
1050 LLVM::bitEnumContainsAny(fmf.getValue(), LLVM::FastmathFlags::ninf);
1051
1052 Value result;
1053 switch (kind) {
1054 case vector::CombiningKind::ADD:
1055 result = lowerPredicatedReductionWithStartValue<
1056 LLVM::VPReduceAddOp, ReductionNeutralZero, LLVM::VPReduceFAddOp,
1057 ReductionNeutralZero>(rewriter, loc, llvmType, operand, acc,
1058 maskOp.getMask());
1059 break;
1060 case vector::CombiningKind::MUL:
1061 result = lowerPredicatedReductionWithStartValue<
1062 LLVM::VPReduceMulOp, ReductionNeutralIntOne, LLVM::VPReduceFMulOp,
1063 ReductionNeutralFPOne>(rewriter, loc, llvmType, operand, acc,
1064 maskOp.getMask());
1065 break;
1066 case vector::CombiningKind::MINUI:
1067 result = lowerPredicatedReductionWithStartValue<LLVM::VPReduceUMinOp,
1068 ReductionNeutralUIntMax>(
1069 rewriter, loc, llvmType, operand, acc, maskOp.getMask());
1070 break;
1071 case vector::CombiningKind::MINSI:
1072 result = lowerPredicatedReductionWithStartValue<LLVM::VPReduceSMinOp,
1073 ReductionNeutralSIntMax>(
1074 rewriter, loc, llvmType, operand, acc, maskOp.getMask());
1075 break;
1076 case vector::CombiningKind::MAXUI:
1077 result = lowerPredicatedReductionWithStartValue<LLVM::VPReduceUMaxOp,
1078 ReductionNeutralUIntMin>(
1079 rewriter, loc, llvmType, operand, acc, maskOp.getMask());
1080 break;
1081 case vector::CombiningKind::MAXSI:
1082 result = lowerPredicatedReductionWithStartValue<LLVM::VPReduceSMaxOp,
1083 ReductionNeutralSIntMin>(
1084 rewriter, loc, llvmType, operand, acc, maskOp.getMask());
1085 break;
1086 case vector::CombiningKind::AND:
1087 result = lowerPredicatedReductionWithStartValue<LLVM::VPReduceAndOp,
1088 ReductionNeutralAllOnes>(
1089 rewriter, loc, llvmType, operand, acc, maskOp.getMask());
1090 break;
1091 case vector::CombiningKind::OR:
1092 result = lowerPredicatedReductionWithStartValue<LLVM::VPReduceOrOp,
1093 ReductionNeutralZero>(
1094 rewriter, loc, llvmType, operand, acc, maskOp.getMask());
1095 break;
1096 case vector::CombiningKind::XOR:
1097 result = lowerPredicatedReductionWithStartValue<LLVM::VPReduceXorOp,
1098 ReductionNeutralZero>(
1099 rewriter, loc, llvmType, operand, acc, maskOp.getMask());
1100 break;
1101 case vector::CombiningKind::MINNUMF:
1102 result =
1103 lowerPredicatedReductionWithStartValue<LLVM::VPReduceFMinOp,
1104 ReductionNeutralFPNegQNaN>(
1105 rewriter, loc, llvmType, operand, acc, maskOp.getMask());
1106 break;
1107 case vector::CombiningKind::MAXNUMF:
1108 result = lowerPredicatedReductionWithStartValue<LLVM::VPReduceFMaxOp,
1109 ReductionNeutralFPQNaN>(
1110 rewriter, loc, llvmType, operand, acc, maskOp.getMask());
1111 break;
1112 case CombiningKind::MAXIMUMF:
1113 // `ninf` promises no infinity reaches the reduction, so the neutral start
1114 // value must stay finite.
1115 result =
1116 noInfs
1117 ? lowerPredicatedReductionWithStartValue<
1118 LLVM::VPReduceFMaximumOp, ReductionNeutralFPLowestFinite>(
1119 rewriter, loc, llvmType, operand, acc, maskOp.getMask())
1120 : lowerPredicatedReductionWithStartValue<
1121 LLVM::VPReduceFMaximumOp, ReductionNeutralFPNegInf>(
1122 rewriter, loc, llvmType, operand, acc, maskOp.getMask());
1123 break;
1124 case CombiningKind::MINIMUMF:
1125 result =
1126 noInfs
1127 ? lowerPredicatedReductionWithStartValue<
1128 LLVM::VPReduceFMinimumOp, ReductionNeutralFPLargestFinite>(
1129 rewriter, loc, llvmType, operand, acc, maskOp.getMask())
1130 : lowerPredicatedReductionWithStartValue<
1131 LLVM::VPReduceFMinimumOp, ReductionNeutralFPPosInf>(
1132 rewriter, loc, llvmType, operand, acc, maskOp.getMask());
1133 break;
1134 case CombiningKind::MAXIMUMNUMF:
1135 result = lowerMaskedReductionWithRegular<LLVM::vector_reduce_fmaximumnum,
1136 MaskNeutralFMaximumNum>(
1137 rewriter, loc, llvmType, operand, acc, maskOp.getMask(), fmf);
1138 break;
1139 case CombiningKind::MINIMUMNUMF:
1140 result = lowerMaskedReductionWithRegular<LLVM::vector_reduce_fminimumnum,
1141 MaskNeutralFMinimumNum>(
1142 rewriter, loc, llvmType, operand, acc, maskOp.getMask(), fmf);
1143 break;
1144 }
1145
1146 // Replace `vector.mask` operation altogether.
1147 rewriter.replaceOp(maskOp, result);
1148 return success();
1149 }
1150};
1151
1152class VectorShuffleOpConversion
1153 : public ConvertOpToLLVMPattern<vector::ShuffleOp> {
1154public:
1155 using ConvertOpToLLVMPattern<vector::ShuffleOp>::ConvertOpToLLVMPattern;
1156
1157 LogicalResult
1158 matchAndRewrite(vector::ShuffleOp shuffleOp, OpAdaptor adaptor,
1159 ConversionPatternRewriter &rewriter) const override {
1160 auto loc = shuffleOp->getLoc();
1161 auto v1Type = shuffleOp.getV1VectorType();
1162 auto v2Type = shuffleOp.getV2VectorType();
1163 auto vectorType = shuffleOp.getResultVectorType();
1164 Type llvmType = typeConverter->convertType(vectorType);
1165 ArrayRef<int64_t> mask = shuffleOp.getMask();
1166
1167 // Bail if result type cannot be lowered.
1168 if (!llvmType)
1169 return failure();
1170
1171 // Get rank and dimension sizes.
1172 int64_t rank = vectorType.getRank();
1173#ifndef NDEBUG
1174 bool wellFormed0DCase =
1175 v1Type.getRank() == 0 && v2Type.getRank() == 0 && rank == 1;
1176 bool wellFormedNDCase =
1177 v1Type.getRank() == rank && v2Type.getRank() == rank;
1178 assert((wellFormed0DCase || wellFormedNDCase) && "op is not well-formed");
1179#endif
1180
1181 // For rank 0 and 1, where both operands have *exactly* the same vector
1182 // type, there is direct shuffle support in LLVM. Use it!
1183 if (rank <= 1 && v1Type == v2Type) {
1184 Value llvmShuffleOp = LLVM::ShuffleVectorOp::create(
1185 rewriter, loc, adaptor.getV1(), adaptor.getV2(),
1186 llvm::to_vector_of<int32_t>(mask));
1187 rewriter.replaceOp(shuffleOp, llvmShuffleOp);
1188 return success();
1189 }
1190
1191 // For all other cases, insert the individual values individually.
1192 int64_t v1Dim = v1Type.getDimSize(0);
1193 Type eltType;
1194 if (auto arrayType = dyn_cast<LLVM::LLVMArrayType>(llvmType))
1195 eltType = arrayType.getElementType();
1196 else
1197 eltType = cast<VectorType>(llvmType).getElementType();
1198 Value insert = LLVM::PoisonOp::create(rewriter, loc, llvmType);
1199 int64_t insPos = 0;
1200 for (int64_t extPos : mask) {
1201 // The result starts as poison, so a poison index needs no insertion.
1202 if (extPos == vector::ShuffleOp::kPoisonIndex) {
1203 ++insPos;
1204 continue;
1205 }
1206 Value value = adaptor.getV1();
1207 if (extPos >= v1Dim) {
1208 extPos -= v1Dim;
1209 value = adaptor.getV2();
1210 }
1211 Value extract = extractOne(rewriter, *getTypeConverter(), loc, value,
1212 eltType, rank, extPos);
1213 insert = insertOne(rewriter, *getTypeConverter(), loc, insert, extract,
1214 llvmType, rank, insPos++);
1215 }
1216 rewriter.replaceOp(shuffleOp, insert);
1217 return success();
1218 }
1219};
1220
1221class VectorExtractOpConversion
1222 : public ConvertOpToLLVMPattern<vector::ExtractOp> {
1223public:
1224 using ConvertOpToLLVMPattern<vector::ExtractOp>::ConvertOpToLLVMPattern;
1225
1226 LogicalResult
1227 matchAndRewrite(vector::ExtractOp extractOp, OpAdaptor adaptor,
1228 ConversionPatternRewriter &rewriter) const override {
1229 auto loc = extractOp->getLoc();
1230 auto resultType = extractOp.getResult().getType();
1231 auto llvmResultType = typeConverter->convertType(resultType);
1232 // Bail if result type cannot be lowered.
1233 if (!llvmResultType)
1234 return failure();
1235
1236 SmallVector<OpFoldResult> positionVec = getMixedValues(
1237 adaptor.getStaticPosition(), adaptor.getDynamicPosition(), rewriter);
1238
1239 // The Vector -> LLVM lowering models N-D vectors as nested aggregates of
1240 // 1-d vectors. This nesting is modeled using arrays. We do this conversion
1241 // from a N-d vector extract to a nested aggregate vector extract in two
1242 // steps:
1243 // - Extract a member from the nested aggregate. The result can be
1244 // a lower rank nested aggregate or a vector (1-D). This is done using
1245 // `llvm.extractvalue`.
1246 // - Extract a scalar out of the vector if needed. This is done using
1247 // `llvm.extractelement`.
1248
1249 // Determine if we need to extract a member out of the aggregate. We
1250 // always need to extract a member if the input rank >= 2.
1251 bool extractsAggregate = extractOp.getSourceVectorType().getRank() >= 2;
1252 // Determine if we need to extract a scalar as the result. We extract
1253 // a scalar if the extract is full rank, i.e., the number of indices is
1254 // equal to source vector rank.
1255 bool extractsScalar = static_cast<int64_t>(positionVec.size()) ==
1256 extractOp.getSourceVectorType().getRank();
1257
1258 // Since the LLVM type converter converts 0-d vectors to 1-d vectors, we
1259 // need to add a position for this change.
1260 if (extractOp.getSourceVectorType().getRank() == 0) {
1261 Type idxType = typeConverter->convertType(rewriter.getIndexType());
1262 positionVec.push_back(rewriter.getZeroAttr(idxType));
1263 }
1264
1265 Value extracted = adaptor.getSource();
1266 if (extractsAggregate) {
1267 ArrayRef<OpFoldResult> position(positionVec);
1268 if (extractsScalar) {
1269 // If we are extracting a scalar from the extracted member, we drop
1270 // the last index, which will be used to extract the scalar out of the
1271 // vector.
1272 position = position.drop_back();
1273 }
1274 // llvm.extractvalue does not support dynamic dimensions.
1275 if (!llvm::all_of(position, llvm::IsaPred<Attribute>)) {
1276 return failure();
1277 }
1278 extracted = LLVM::ExtractValueOp::create(rewriter, loc, extracted,
1279 getAsIntegers(position));
1280 }
1281
1282 if (extractsScalar) {
1283 extracted = LLVM::ExtractElementOp::create(
1284 rewriter, loc, extracted,
1285 getAsLLVMValue(rewriter, loc, positionVec.back()));
1286 }
1287
1288 rewriter.replaceOp(extractOp, extracted);
1289 return success();
1290 }
1291};
1292
1293/// Conversion pattern that turns a vector.fma on a 1-D vector
1294/// into an llvm.intr.fmuladd. This is a trivial 1-1 conversion.
1295/// This does not match vectors of n >= 2 rank.
1296///
1297/// Example:
1298/// ```
1299/// vector.fma %a, %a, %a : vector<8xf32>
1300/// ```
1301/// is converted to:
1302/// ```
1303/// llvm.intr.fmuladd %va, %va, %va:
1304/// (!llvm."<8 x f32>">, !llvm<"<8 x f32>">, !llvm<"<8 x f32>">)
1305/// -> !llvm."<8 x f32>">
1306/// ```
1307class VectorFMAOp1DConversion : public ConvertOpToLLVMPattern<vector::FMAOp> {
1308public:
1309 using ConvertOpToLLVMPattern<vector::FMAOp>::ConvertOpToLLVMPattern;
1310
1311 LogicalResult
1312 matchAndRewrite(vector::FMAOp fmaOp, OpAdaptor adaptor,
1313 ConversionPatternRewriter &rewriter) const override {
1314 VectorType vType = fmaOp.getVectorType();
1315 if (vType.getRank() > 1)
1316 return failure();
1317
1318 rewriter.replaceOpWithNewOp<LLVM::FMulAddOp>(
1319 fmaOp, adaptor.getLhs(), adaptor.getRhs(), adaptor.getAcc());
1320 return success();
1321 }
1322};
1323
1324class VectorInsertOpConversion
1325 : public ConvertOpToLLVMPattern<vector::InsertOp> {
1326public:
1327 using ConvertOpToLLVMPattern<vector::InsertOp>::ConvertOpToLLVMPattern;
1328
1329 LogicalResult
1330 matchAndRewrite(vector::InsertOp insertOp, OpAdaptor adaptor,
1331 ConversionPatternRewriter &rewriter) const override {
1332 auto loc = insertOp->getLoc();
1333 auto destVectorType = insertOp.getDestVectorType();
1334 auto llvmResultType = typeConverter->convertType(destVectorType);
1335 // Bail if result type cannot be lowered.
1336 if (!llvmResultType)
1337 return failure();
1338
1339 SmallVector<OpFoldResult> positionVec = getMixedValues(
1340 adaptor.getStaticPosition(), adaptor.getDynamicPosition(), rewriter);
1341
1342 // The logic in this pattern mirrors VectorExtractOpConversion. Refer to
1343 // its explanatory comment about how N-D vectors are converted as nested
1344 // aggregates (llvm.array's) of 1D vectors.
1345 //
1346 // The innermost dimension of the destination vector, when converted to a
1347 // nested aggregate form, will always be a 1D vector.
1348 //
1349 // * If the insertion is happening into the innermost dimension of the
1350 // destination vector:
1351 // - If the destination is a nested aggregate, extract a 1D vector out of
1352 // the aggregate. This can be done using llvm.extractvalue. The
1353 // destination is now guaranteed to be a 1D vector, to which we are
1354 // inserting.
1355 // - Do the insertion into the 1D destination vector, and make the result
1356 // the new source nested aggregate. This can be done using
1357 // llvm.insertelement.
1358 // * Insert the source nested aggregate into the destination nested
1359 // aggregate.
1360
1361 // Determine if we need to extract/insert a 1D vector out of the aggregate.
1362 bool isNestedAggregate = isa<LLVM::LLVMArrayType>(llvmResultType);
1363 // Determine if we need to insert a scalar into the 1D vector.
1364 bool insertIntoInnermostDim =
1365 static_cast<int64_t>(positionVec.size()) == destVectorType.getRank();
1366
1367 ArrayRef<OpFoldResult> positionOf1DVectorWithinAggregate(
1368 positionVec.begin(),
1369 insertIntoInnermostDim ? positionVec.size() - 1 : positionVec.size());
1370 OpFoldResult positionOfScalarWithin1DVector;
1371 if (destVectorType.getRank() == 0) {
1372 // Since the LLVM type converter converts 0D vectors to 1D vectors, we
1373 // need to create a 0 here as the position into the 1D vector.
1374 Type idxType = typeConverter->convertType(rewriter.getIndexType());
1375 positionOfScalarWithin1DVector = rewriter.getZeroAttr(idxType);
1376 } else if (insertIntoInnermostDim) {
1377 positionOfScalarWithin1DVector = positionVec.back();
1378 }
1379
1380 // We are going to mutate this 1D vector until it is either the final
1381 // result (in the non-aggregate case) or the value that needs to be
1382 // inserted into the aggregate result.
1383 Value sourceAggregate = adaptor.getValueToStore();
1384 if (insertIntoInnermostDim) {
1385 // Scalar-into-1D-vector case, so we know we will have to create a
1386 // InsertElementOp. The question is into what destination.
1387 if (isNestedAggregate) {
1388 // Aggregate case: the destination for the InsertElementOp needs to be
1389 // extracted from the aggregate.
1390 if (!llvm::all_of(positionOf1DVectorWithinAggregate,
1391 llvm::IsaPred<Attribute>)) {
1392 // llvm.extractvalue does not support dynamic dimensions.
1393 return failure();
1394 }
1395 sourceAggregate = LLVM::ExtractValueOp::create(
1396 rewriter, loc, adaptor.getDest(),
1397 getAsIntegers(positionOf1DVectorWithinAggregate));
1398 } else {
1399 // No-aggregate case. The destination for the InsertElementOp is just
1400 // the insertOp's destination.
1401 sourceAggregate = adaptor.getDest();
1402 }
1403 // Insert the scalar into the 1D vector.
1404 sourceAggregate = LLVM::InsertElementOp::create(
1405 rewriter, loc, sourceAggregate.getType(), sourceAggregate,
1406 adaptor.getValueToStore(),
1407 getAsLLVMValue(rewriter, loc, positionOfScalarWithin1DVector));
1408 }
1409
1410 Value result = sourceAggregate;
1411 if (isNestedAggregate) {
1412 if (!llvm::all_of(positionOf1DVectorWithinAggregate,
1413 llvm::IsaPred<Attribute>)) {
1414 // llvm.insertvalue does not support dynamic dimensions.
1415 return failure();
1416 }
1417 result = LLVM::InsertValueOp::create(
1418 rewriter, loc, adaptor.getDest(), sourceAggregate,
1419 getAsIntegers(positionOf1DVectorWithinAggregate));
1420 }
1421
1422 rewriter.replaceOp(insertOp, result);
1423 return success();
1424 }
1425};
1426
1427/// Lower vector.scalable.insert ops to LLVM vector.insert
1428struct VectorScalableInsertOpLowering
1429 : public ConvertOpToLLVMPattern<vector::ScalableInsertOp> {
1430 using ConvertOpToLLVMPattern<
1431 vector::ScalableInsertOp>::ConvertOpToLLVMPattern;
1432
1433 LogicalResult
1434 matchAndRewrite(vector::ScalableInsertOp insOp, OpAdaptor adaptor,
1435 ConversionPatternRewriter &rewriter) const override {
1436 rewriter.replaceOpWithNewOp<LLVM::vector_insert>(
1437 insOp, adaptor.getDest(), adaptor.getValueToStore(), adaptor.getPos());
1438 return success();
1439 }
1440};
1441
1442/// Lower vector.scalable.extract ops to LLVM vector.extract
1443struct VectorScalableExtractOpLowering
1444 : public ConvertOpToLLVMPattern<vector::ScalableExtractOp> {
1445 using ConvertOpToLLVMPattern<
1446 vector::ScalableExtractOp>::ConvertOpToLLVMPattern;
1447
1448 LogicalResult
1449 matchAndRewrite(vector::ScalableExtractOp extOp, OpAdaptor adaptor,
1450 ConversionPatternRewriter &rewriter) const override {
1451 rewriter.replaceOpWithNewOp<LLVM::vector_extract>(
1452 extOp, typeConverter->convertType(extOp.getResultVectorType()),
1453 adaptor.getSource(), adaptor.getPos());
1454 return success();
1455 }
1456};
1457
1458/// Rank reducing rewrite for n-D FMA into (n-1)-D FMA where n > 1.
1459///
1460/// Example:
1461/// ```
1462/// %d = vector.fma %a, %b, %c : vector<2x4xf32>
1463/// ```
1464/// is rewritten into:
1465/// ```
1466/// %r = vector.broadcast %f0 : f32 to vector<2x4xf32>
1467/// %va = vector.extractvalue %a[0] : vector<2x4xf32>
1468/// %vb = vector.extractvalue %b[0] : vector<2x4xf32>
1469/// %vc = vector.extractvalue %c[0] : vector<2x4xf32>
1470/// %vd = vector.fma %va, %vb, %vc : vector<4xf32>
1471/// %r2 = vector.insertvalue %vd, %r[0] : vector<4xf32> into vector<2x4xf32>
1472/// %va2 = vector.extractvalue %a2[1] : vector<2x4xf32>
1473/// %vb2 = vector.extractvalue %b2[1] : vector<2x4xf32>
1474/// %vc2 = vector.extractvalue %c2[1] : vector<2x4xf32>
1475/// %vd2 = vector.fma %va2, %vb2, %vc2 : vector<4xf32>
1476/// %r3 = vector.insertvalue %vd2, %r2[1] : vector<4xf32> into vector<2x4xf32>
1477/// // %r3 holds the final value.
1478/// ```
1479class VectorFMAOpNDRewritePattern : public OpRewritePattern<FMAOp> {
1480public:
1481 using Base::Base;
1482
1483 void initialize() {
1484 // This pattern recursively unpacks one dimension at a time. The recursion
1485 // bounded as the rank is strictly decreasing.
1486 setHasBoundedRewriteRecursion();
1487 }
1488
1489 LogicalResult matchAndRewrite(FMAOp op,
1490 PatternRewriter &rewriter) const override {
1491 auto vType = op.getVectorType();
1492 if (vType.getRank() < 2)
1493 return failure();
1494
1495 auto loc = op.getLoc();
1496 auto elemType = vType.getElementType();
1497 Value zero = arith::ConstantOp::create(rewriter, loc, elemType,
1498 rewriter.getZeroAttr(elemType));
1499 Value desc = vector::BroadcastOp::create(rewriter, loc, vType, zero);
1500 for (int64_t i = 0, e = vType.getShape().front(); i != e; ++i) {
1501 Value extrLHS = ExtractOp::create(rewriter, loc, op.getLhs(), i);
1502 Value extrRHS = ExtractOp::create(rewriter, loc, op.getRhs(), i);
1503 Value extrACC = ExtractOp::create(rewriter, loc, op.getAcc(), i);
1504 Value fma = FMAOp::create(rewriter, loc, extrLHS, extrRHS, extrACC);
1505 desc = InsertOp::create(rewriter, loc, fma, desc, i);
1506 }
1507 rewriter.replaceOp(op, desc);
1508 return success();
1509 }
1510};
1511
1512/// Returns the strides if the memory underlying `memRefType` has a contiguous
1513/// static layout.
1514static std::optional<SmallVector<int64_t, 4>>
1515computeContiguousStrides(MemRefType memRefType) {
1516 int64_t offset;
1518 if (failed(memRefType.getStridesAndOffset(strides, offset)))
1519 return std::nullopt;
1520 if (!strides.empty() && strides.back() != 1)
1521 return std::nullopt;
1522 // If no layout or identity layout, this is contiguous by definition.
1523 if (memRefType.getLayout().isIdentity())
1524 return strides;
1525
1526 // Otherwise, we must determine contiguity form shapes. This can only ever
1527 // work in static cases because MemRefType is underspecified to represent
1528 // contiguous dynamic shapes in other ways than with just empty/identity
1529 // layout.
1530 auto sizes = memRefType.getShape();
1531 for (int index = 0, e = strides.size() - 1; index < e; ++index) {
1532 if (ShapedType::isDynamic(sizes[index + 1]) ||
1533 ShapedType::isDynamic(strides[index]) ||
1534 ShapedType::isDynamic(strides[index + 1]))
1535 return std::nullopt;
1536 if (strides[index] != strides[index + 1] * sizes[index + 1])
1537 return std::nullopt;
1538 }
1539 return strides;
1540}
1541
1542class VectorTypeCastOpConversion
1543 : public ConvertOpToLLVMPattern<vector::TypeCastOp> {
1544public:
1545 using ConvertOpToLLVMPattern<vector::TypeCastOp>::ConvertOpToLLVMPattern;
1546
1547 LogicalResult
1548 matchAndRewrite(vector::TypeCastOp castOp, OpAdaptor adaptor,
1549 ConversionPatternRewriter &rewriter) const override {
1550 auto loc = castOp->getLoc();
1551 MemRefType sourceMemRefType =
1552 cast<MemRefType>(castOp.getOperand().getType());
1553 MemRefType targetMemRefType = castOp.getType();
1554
1555 // Only static shape casts supported atm.
1556 if (!sourceMemRefType.hasStaticShape() ||
1557 !targetMemRefType.hasStaticShape())
1558 return failure();
1559
1560 auto llvmSourceDescriptorTy =
1561 dyn_cast<LLVM::LLVMStructType>(adaptor.getOperands()[0].getType());
1562 if (!llvmSourceDescriptorTy)
1563 return failure();
1564 MemRefDescriptor sourceMemRef(adaptor.getOperands()[0]);
1565
1566 auto llvmTargetDescriptorTy = dyn_cast_or_null<LLVM::LLVMStructType>(
1567 typeConverter->convertType(targetMemRefType));
1568 if (!llvmTargetDescriptorTy)
1569 return failure();
1570
1571 // Only contiguous source buffers supported atm.
1572 auto sourceStrides = computeContiguousStrides(sourceMemRefType);
1573 if (!sourceStrides)
1574 return failure();
1575 auto targetStrides = computeContiguousStrides(targetMemRefType);
1576 if (!targetStrides)
1577 return failure();
1578 // Only support static strides for now, regardless of contiguity.
1579 if (llvm::any_of(*targetStrides, ShapedType::isDynamic))
1580 return failure();
1581
1582 // The offset, size and stride fields of a memref descriptor use the
1583 // converted index type.
1584 Type indexTy = getTypeConverter()->getIndexType();
1585
1586 // Create descriptor.
1587 auto desc = MemRefDescriptor::poison(rewriter, loc, llvmTargetDescriptorTy);
1588 // Set allocated ptr.
1589 Value allocated = sourceMemRef.allocatedPtr(rewriter, loc);
1590 desc.setAllocatedPtr(rewriter, loc, allocated);
1591
1592 // Set aligned ptr.
1593 Value ptr = sourceMemRef.alignedPtr(rewriter, loc);
1594 desc.setAlignedPtr(rewriter, loc, ptr);
1595 // Fill offset 0.
1596 desc.setOffset(rewriter, loc,
1597 LLVM::createIndexAttrConstant(rewriter, loc, indexTy, 0));
1598
1599 // Fill size and stride descriptors in memref.
1600 for (const auto &indexedSize :
1601 llvm::enumerate(targetMemRefType.getShape())) {
1602 int64_t index = indexedSize.index();
1603 desc.setSize(rewriter, loc, index,
1604 LLVM::createIndexAttrConstant(rewriter, loc, indexTy,
1605 indexedSize.value()));
1606 desc.setStride(rewriter, loc, index,
1607 LLVM::createIndexAttrConstant(rewriter, loc, indexTy,
1608 (*targetStrides)[index]));
1609 }
1610
1611 rewriter.replaceOp(castOp, {desc});
1612 return success();
1613 }
1614};
1615
1616/// Conversion pattern for a `vector.create_mask` (1-D scalable vectors only).
1617/// Non-scalable versions of this operation are handled in Vector Transforms.
1618class VectorCreateMaskOpConversion
1619 : public OpConversionPattern<vector::CreateMaskOp> {
1620public:
1621 explicit VectorCreateMaskOpConversion(MLIRContext *context,
1622 bool enableIndexOpt)
1623 : OpConversionPattern<vector::CreateMaskOp>(context),
1624 force32BitVectorIndices(enableIndexOpt) {}
1625
1626 LogicalResult
1627 matchAndRewrite(vector::CreateMaskOp op, OpAdaptor adaptor,
1628 ConversionPatternRewriter &rewriter) const override {
1629 auto dstType = op.getType();
1630 if (dstType.getRank() != 1 || !cast<VectorType>(dstType).isScalable())
1631 return failure();
1632 IntegerType idxType =
1633 force32BitVectorIndices ? rewriter.getI32Type() : rewriter.getI64Type();
1634 auto loc = op->getLoc();
1635 Value indices = LLVM::StepVectorOp::create(
1636 rewriter, loc,
1637 LLVM::getVectorType(idxType, dstType.getShape()[0],
1638 /*isScalable=*/true));
1639 Value maskBound = adaptor.getOperands()[0];
1640 // When using 32-bit indices, cap the bound at INT32_MAX in index type
1641 // before casting. For scalable vectors the runtime size (vscale * dim) is
1642 // unknown at compile time, so we can't clamp to `dim` as in the fixed-size
1643 // path. Clamping to INT32_MAX is safe because any realistic scalable vector
1644 // size fits well below this limit, so a bound >= vscale*dim still produces
1645 // an all-true mask after the comparison.
1646 if (force32BitVectorIndices) {
1647 Value maxBound =
1648 arith::ConstantIndexOp::create(rewriter, loc, (1LL << 31) - 1);
1649 maskBound = arith::MinSIOp::create(rewriter, loc, maskBound, maxBound);
1650 }
1651 auto bound =
1652 getValueOrCreateCastToIndexLike(rewriter, loc, idxType, maskBound);
1653 Value bounds = BroadcastOp::create(rewriter, loc, indices.getType(), bound);
1654 Value comp = arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::slt,
1655 indices, bounds);
1656 rewriter.replaceOp(op, comp);
1657 return success();
1658 }
1659
1660private:
1661 const bool force32BitVectorIndices;
1662};
1663
1664class VectorPrintOpConversion : public ConvertOpToLLVMPattern<vector::PrintOp> {
1665 SymbolTableCollection *symbolTables = nullptr;
1666
1667public:
1668 explicit VectorPrintOpConversion(
1669 const LLVMTypeConverter &typeConverter,
1670 SymbolTableCollection *symbolTables = nullptr)
1671 : ConvertOpToLLVMPattern<vector::PrintOp>(typeConverter),
1672 symbolTables(symbolTables) {}
1673
1674 // Lowering implementation that relies on a small runtime support library,
1675 // which only needs to provide a few printing methods (single value for all
1676 // data types, opening/closing bracket, comma, newline). The lowering splits
1677 // the vector into elementary printing operations. The advantage of this
1678 // approach is that the library can remain unaware of all low-level
1679 // implementation details of vectors while still supporting output of any
1680 // shaped and dimensioned vector.
1681 //
1682 // Note: This lowering only handles scalars, n-D vectors are broken into
1683 // printing scalars in loops in VectorToSCF.
1684 //
1685 // TODO: rely solely on libc in future? something else?
1686 //
1687 LogicalResult
1688 matchAndRewrite(vector::PrintOp printOp, OpAdaptor adaptor,
1689 ConversionPatternRewriter &rewriter) const override {
1690 auto parent = printOp->getParentOfType<ModuleOp>();
1691 if (!parent)
1692 return failure();
1693
1694 auto loc = printOp->getLoc();
1695
1696 if (auto value = adaptor.getSource()) {
1697 Type printType = printOp.getPrintType();
1698 if (isa<VectorType>(printType)) {
1699 // Vectors should be broken into elementary print ops in VectorToSCF.
1700 return failure();
1701 }
1702 if (failed(emitScalarPrint(rewriter, parent, loc, printType, value)))
1703 return failure();
1704 }
1705
1706 auto punct = printOp.getPunctuation();
1707 if (auto stringLiteral = printOp.getStringLiteral()) {
1708 auto createResult =
1709 LLVM::createPrintStrCall(rewriter, loc, parent, "vector_print_str",
1710 *stringLiteral, *getTypeConverter(),
1711 /*addNewline=*/false);
1712 if (createResult.failed())
1713 return failure();
1714
1715 } else if (punct != PrintPunctuation::NoPunctuation) {
1716 FailureOr<LLVM::LLVMFuncOp> op = [&]() {
1717 switch (punct) {
1718 case PrintPunctuation::Close:
1719 return LLVM::lookupOrCreatePrintCloseFn(rewriter, parent,
1720 symbolTables);
1721 case PrintPunctuation::Open:
1722 return LLVM::lookupOrCreatePrintOpenFn(rewriter, parent,
1723 symbolTables);
1724 case PrintPunctuation::Comma:
1725 return LLVM::lookupOrCreatePrintCommaFn(rewriter, parent,
1726 symbolTables);
1727 case PrintPunctuation::NewLine:
1728 return LLVM::lookupOrCreatePrintNewlineFn(rewriter, parent,
1729 symbolTables);
1730 default:
1731 llvm_unreachable("unexpected punctuation");
1732 }
1733 }();
1734 if (failed(op))
1735 return failure();
1736 emitCall(rewriter, printOp->getLoc(), op.value());
1737 }
1738
1739 rewriter.eraseOp(printOp);
1740 return success();
1741 }
1742
1743private:
1744 enum class PrintConversion {
1745 // clang-format off
1746 None,
1747 ZeroExt64,
1748 SignExt64,
1749 Bitcast16
1750 // clang-format on
1751 };
1752
1753 LogicalResult emitScalarPrint(ConversionPatternRewriter &rewriter,
1754 ModuleOp parent, Location loc, Type printType,
1755 Value value) const {
1756 if (typeConverter->convertType(printType) == nullptr)
1757 return failure();
1758
1759 // Make sure element type has runtime support.
1760 PrintConversion conversion = PrintConversion::None;
1761 FailureOr<Operation *> printer;
1762 if (printType.isF32()) {
1763 printer = LLVM::lookupOrCreatePrintF32Fn(rewriter, parent, symbolTables);
1764 } else if (printType.isF64()) {
1765 printer = LLVM::lookupOrCreatePrintF64Fn(rewriter, parent, symbolTables);
1766 } else if (printType.isF16()) {
1767 conversion = PrintConversion::Bitcast16; // bits!
1768 printer = LLVM::lookupOrCreatePrintF16Fn(rewriter, parent, symbolTables);
1769 } else if (printType.isBF16()) {
1770 conversion = PrintConversion::Bitcast16; // bits!
1771 printer = LLVM::lookupOrCreatePrintBF16Fn(rewriter, parent, symbolTables);
1772 } else if (printType.isIndex()) {
1773 printer = LLVM::lookupOrCreatePrintU64Fn(rewriter, parent, symbolTables);
1774 } else if (auto intTy = dyn_cast<IntegerType>(printType)) {
1775 // Integers need a zero or sign extension on the operand
1776 // (depending on the source type) as well as a signed or
1777 // unsigned print method. Up to 64-bit is supported.
1778 unsigned width = intTy.getWidth();
1779 if (intTy.isUnsigned()) {
1780 if (width <= 64) {
1781 if (width < 64)
1782 conversion = PrintConversion::ZeroExt64;
1783 printer =
1784 LLVM::lookupOrCreatePrintU64Fn(rewriter, parent, symbolTables);
1785 } else {
1786 return failure();
1787 }
1788 } else {
1789 assert(intTy.isSignless() || intTy.isSigned());
1790 if (width <= 64) {
1791 // Note that we *always* zero extend booleans (1-bit integers),
1792 // so that true/false is printed as 1/0 rather than -1/0.
1793 if (width == 1)
1794 conversion = PrintConversion::ZeroExt64;
1795 else if (width < 64)
1796 conversion = PrintConversion::SignExt64;
1797 printer =
1798 LLVM::lookupOrCreatePrintI64Fn(rewriter, parent, symbolTables);
1799 } else {
1800 return failure();
1801 }
1802 }
1803 } else if (auto floatTy = dyn_cast<FloatType>(printType)) {
1804 // Print other floating-point types using the APFloat runtime library.
1805 int32_t sem =
1806 llvm::APFloatBase::SemanticsToEnum(floatTy.getFloatSemantics());
1807 Value semValue = LLVM::ConstantOp::create(
1808 rewriter, loc, rewriter.getI32Type(),
1809 rewriter.getIntegerAttr(rewriter.getI32Type(), sem));
1810 Value floatBits =
1811 LLVM::ZExtOp::create(rewriter, loc, rewriter.getI64Type(), value);
1812 printer =
1813 LLVM::lookupOrCreateApFloatPrintFn(rewriter, parent, symbolTables);
1814 emitCall(rewriter, loc, printer.value(),
1815 ValueRange({semValue, floatBits}));
1816 return success();
1817 } else {
1818 return failure();
1819 }
1820 if (failed(printer))
1821 return failure();
1822
1823 switch (conversion) {
1824 case PrintConversion::ZeroExt64:
1825 value = arith::ExtUIOp::create(
1826 rewriter, loc, IntegerType::get(rewriter.getContext(), 64), value);
1827 break;
1828 case PrintConversion::SignExt64:
1829 value = arith::ExtSIOp::create(
1830 rewriter, loc, IntegerType::get(rewriter.getContext(), 64), value);
1831 break;
1832 case PrintConversion::Bitcast16:
1833 value = LLVM::BitcastOp::create(
1834 rewriter, loc, IntegerType::get(rewriter.getContext(), 16), value);
1835 break;
1836 case PrintConversion::None:
1837 break;
1838 }
1839 emitCall(rewriter, loc, printer.value(), value);
1840 return success();
1841 }
1842
1843 // Helper to emit a call.
1844 static void emitCall(ConversionPatternRewriter &rewriter, Location loc,
1845 Operation *ref, ValueRange params = ValueRange()) {
1846 LLVM::CallOp::create(rewriter, loc, TypeRange(), SymbolRefAttr::get(ref),
1847 params);
1848 }
1849};
1850
1851/// A broadcast of a scalar is lowered to an insertelement + a shufflevector
1852/// operation. Only broadcasts to 0-d and 1-d vectors are lowered by this
1853/// pattern, the higher rank cases are handled by another pattern.
1854struct VectorBroadcastScalarToLowRankLowering
1855 : public ConvertOpToLLVMPattern<vector::BroadcastOp> {
1856 using ConvertOpToLLVMPattern<vector::BroadcastOp>::ConvertOpToLLVMPattern;
1857
1858 LogicalResult
1859 matchAndRewrite(vector::BroadcastOp broadcast, OpAdaptor adaptor,
1860 ConversionPatternRewriter &rewriter) const override {
1861 if (isa<VectorType>(broadcast.getSourceType()))
1862 return rewriter.notifyMatchFailure(
1863 broadcast, "broadcast from vector type not handled");
1864
1865 VectorType resultType = broadcast.getType();
1866 if (resultType.getRank() > 1)
1867 return rewriter.notifyMatchFailure(broadcast,
1868 "broadcast to 2+-d handled elsewhere");
1869
1870 // First insert it into a poison vector so we can shuffle it.
1871 auto vectorType = typeConverter->convertType(broadcast.getType());
1872 Value poison =
1873 LLVM::PoisonOp::create(rewriter, broadcast.getLoc(), vectorType);
1874 auto zero = LLVM::ConstantOp::create(
1875 rewriter, broadcast.getLoc(),
1876 typeConverter->convertType(rewriter.getIntegerType(32)),
1877 rewriter.getZeroAttr(rewriter.getIntegerType(32)));
1878
1879 // For 0-d vector, we simply do `insertelement`.
1880 if (resultType.getRank() == 0) {
1881 rewriter.replaceOpWithNewOp<LLVM::InsertElementOp>(
1882 broadcast, vectorType, poison, adaptor.getSource(), zero);
1883 return success();
1884 }
1885
1886 auto v =
1887 LLVM::InsertElementOp::create(rewriter, broadcast.getLoc(), vectorType,
1888 poison, adaptor.getSource(), zero);
1889
1890 // For 1-d vector, we additionally do a `shufflevector`.
1891 int64_t width = cast<VectorType>(broadcast.getType()).getDimSize(0);
1892 SmallVector<int32_t> zeroValues(width, 0);
1893
1894 // Shuffle the value across the desired number of elements.
1895 auto shuffle = rewriter.createOrFold<LLVM::ShuffleVectorOp>(
1896 broadcast.getLoc(), v, poison, zeroValues);
1897 rewriter.replaceOp(broadcast, shuffle);
1898 return success();
1899 }
1900};
1901
1902/// The broadcast of a scalar is lowered to an insertelement + a shufflevector
1903/// operation. Only broadcasts to 2+-d vector result types are lowered by this
1904/// pattern, the 1-d case is handled by another pattern. Broadcasts from vectors
1905/// are not converted to LLVM, only broadcasts from scalars are.
1906struct VectorBroadcastScalarToNdLowering
1907 : public ConvertOpToLLVMPattern<BroadcastOp> {
1908 using ConvertOpToLLVMPattern<BroadcastOp>::ConvertOpToLLVMPattern;
1909
1910 LogicalResult
1911 matchAndRewrite(BroadcastOp broadcast, OpAdaptor adaptor,
1912 ConversionPatternRewriter &rewriter) const override {
1913 if (isa<VectorType>(broadcast.getSourceType()))
1914 return rewriter.notifyMatchFailure(
1915 broadcast, "broadcast from vector type not handled");
1916
1917 VectorType resultType = broadcast.getType();
1918 if (resultType.getRank() <= 1)
1919 return rewriter.notifyMatchFailure(
1920 broadcast, "broadcast to 1-d or 0-d handled elsewhere");
1921
1922 // First insert it into a poison vector so we can shuffle it.
1923 auto loc = broadcast.getLoc();
1924 auto vectorTypeInfo =
1925 LLVM::detail::extractNDVectorTypeInfo(resultType, *getTypeConverter());
1926 auto llvmNDVectorTy = vectorTypeInfo.llvmNDVectorTy;
1927 auto llvm1DVectorTy = vectorTypeInfo.llvm1DVectorTy;
1928 if (!llvmNDVectorTy || !llvm1DVectorTy)
1929 return failure();
1930
1931 // Construct returned value.
1932 Value desc = LLVM::PoisonOp::create(rewriter, loc, llvmNDVectorTy);
1933
1934 // Construct a 1-D vector with the broadcasted value that we insert in all
1935 // the places within the returned descriptor.
1936 Value vdesc = LLVM::PoisonOp::create(rewriter, loc, llvm1DVectorTy);
1937 auto zero = LLVM::ConstantOp::create(
1938 rewriter, loc, typeConverter->convertType(rewriter.getIntegerType(32)),
1939 rewriter.getZeroAttr(rewriter.getIntegerType(32)));
1940 Value v = LLVM::InsertElementOp::create(rewriter, loc, llvm1DVectorTy,
1941 vdesc, adaptor.getSource(), zero);
1942
1943 // Shuffle the value across the desired number of elements.
1944 int64_t width = resultType.getDimSize(resultType.getRank() - 1);
1945 SmallVector<int32_t> zeroValues(width, 0);
1946 v = LLVM::ShuffleVectorOp::create(rewriter, loc, v, v, zeroValues);
1947
1948 // Iterate of linear index, convert to coords space and insert broadcasted
1949 // 1-D vector in each position.
1950 nDVectorIterate(vectorTypeInfo, rewriter, [&](ArrayRef<int64_t> position) {
1951 desc = LLVM::InsertValueOp::create(rewriter, loc, desc, v, position);
1952 });
1953 rewriter.replaceOp(broadcast, desc);
1954 return success();
1955 }
1956};
1957
1958/// Conversion pattern for a `vector.interleave`.
1959/// This supports fixed-sized vectors and scalable vectors.
1960struct VectorInterleaveOpLowering
1961 : public ConvertOpToLLVMPattern<vector::InterleaveOp> {
1963
1964 LogicalResult
1965 matchAndRewrite(vector::InterleaveOp interleaveOp, OpAdaptor adaptor,
1966 ConversionPatternRewriter &rewriter) const override {
1967 VectorType resultType = interleaveOp.getResultVectorType();
1968 // n-D interleaves should have been lowered already.
1969 if (resultType.getRank() != 1)
1970 return rewriter.notifyMatchFailure(interleaveOp,
1971 "InterleaveOp not rank 1");
1972 // If the result is rank 1, then this directly maps to LLVM.
1973 if (resultType.isScalable()) {
1974 rewriter.replaceOpWithNewOp<LLVM::vector_interleave2>(
1975 interleaveOp, typeConverter->convertType(resultType),
1976 adaptor.getLhs(), adaptor.getRhs());
1977 return success();
1978 }
1979 // Lower fixed-size interleaves to a shufflevector. While the
1980 // vector.interleave2 intrinsic supports fixed and scalable vectors, the
1981 // langref still recommends fixed-vectors use shufflevector, see:
1982 // https://llvm.org/docs/LangRef.html#id876.
1983 int64_t resultVectorSize = resultType.getNumElements();
1984 SmallVector<int32_t> interleaveShuffleMask;
1985 interleaveShuffleMask.reserve(resultVectorSize);
1986 for (int i = 0, end = resultVectorSize / 2; i < end; ++i) {
1987 interleaveShuffleMask.push_back(i);
1988 interleaveShuffleMask.push_back((resultVectorSize / 2) + i);
1989 }
1990 rewriter.replaceOpWithNewOp<LLVM::ShuffleVectorOp>(
1991 interleaveOp, adaptor.getLhs(), adaptor.getRhs(),
1992 interleaveShuffleMask);
1993 return success();
1994 }
1995};
1996
1997/// Conversion pattern for a `vector.deinterleave`.
1998/// This supports fixed-sized vectors and scalable vectors.
1999struct VectorDeinterleaveOpLowering
2000 : public ConvertOpToLLVMPattern<vector::DeinterleaveOp> {
2002
2003 LogicalResult
2004 matchAndRewrite(vector::DeinterleaveOp deinterleaveOp, OpAdaptor adaptor,
2005 ConversionPatternRewriter &rewriter) const override {
2006 VectorType resultType = deinterleaveOp.getResultVectorType();
2007 VectorType sourceType = deinterleaveOp.getSourceVectorType();
2008 auto loc = deinterleaveOp.getLoc();
2009
2010 // Note: n-D deinterleave operations should be lowered to the 1-D before
2011 // converting to LLVM.
2012 if (resultType.getRank() != 1)
2013 return rewriter.notifyMatchFailure(deinterleaveOp,
2014 "DeinterleaveOp not rank 1");
2015
2016 if (resultType.isScalable()) {
2017 const auto *llvmTypeConverter = this->getTypeConverter();
2018 auto deinterleaveResults = deinterleaveOp.getResultTypes();
2019 auto packedOpResults =
2020 llvmTypeConverter->packOperationResults(deinterleaveResults);
2021 auto intrinsic = LLVM::vector_deinterleave2::create(
2022 rewriter, loc, packedOpResults, adaptor.getSource());
2023
2024 auto evenResult = LLVM::ExtractValueOp::create(
2025 rewriter, loc, intrinsic->getResult(0), 0);
2026 auto oddResult = LLVM::ExtractValueOp::create(rewriter, loc,
2027 intrinsic->getResult(0), 1);
2028
2029 rewriter.replaceOp(deinterleaveOp, ValueRange{evenResult, oddResult});
2030 return success();
2031 }
2032 // Lower fixed-size deinterleave to two shufflevectors. While the
2033 // vector.deinterleave2 intrinsic supports fixed and scalable vectors, the
2034 // langref still recommends fixed-vectors use shufflevector, see:
2035 // https://llvm.org/docs/LangRef.html#id889.
2036 int64_t resultVectorSize = resultType.getNumElements();
2037 SmallVector<int32_t> evenShuffleMask;
2038 SmallVector<int32_t> oddShuffleMask;
2039
2040 evenShuffleMask.reserve(resultVectorSize);
2041 oddShuffleMask.reserve(resultVectorSize);
2042
2043 for (int i = 0; i < sourceType.getNumElements(); ++i) {
2044 if (i % 2 == 0)
2045 evenShuffleMask.push_back(i);
2046 else
2047 oddShuffleMask.push_back(i);
2048 }
2049
2050 auto poison = LLVM::PoisonOp::create(rewriter, loc, sourceType);
2051 auto evenShuffle = LLVM::ShuffleVectorOp::create(
2052 rewriter, loc, adaptor.getSource(), poison, evenShuffleMask);
2053 auto oddShuffle = LLVM::ShuffleVectorOp::create(
2054 rewriter, loc, adaptor.getSource(), poison, oddShuffleMask);
2055
2056 rewriter.replaceOp(deinterleaveOp, ValueRange{evenShuffle, oddShuffle});
2057 return success();
2058 }
2059};
2060
2061/// Conversion pattern for a `vector.from_elements`.
2062struct VectorFromElementsLowering
2063 : public ConvertOpToLLVMPattern<vector::FromElementsOp> {
2065
2066 LogicalResult
2067 matchAndRewrite(vector::FromElementsOp fromElementsOp, OpAdaptor adaptor,
2068 ConversionPatternRewriter &rewriter) const override {
2069 Location loc = fromElementsOp.getLoc();
2070 VectorType vectorType = fromElementsOp.getType();
2071 // Only support 1-D vectors. Multi-dimensional vectors should have been
2072 // transformed to 1-D vectors by the vector-to-vector transformations before
2073 // this.
2074 if (vectorType.getRank() > 1)
2075 return rewriter.notifyMatchFailure(fromElementsOp,
2076 "rank > 1 vectors are not supported");
2077 Type llvmType = typeConverter->convertType(vectorType);
2078 Type llvmIndexType = typeConverter->convertType(rewriter.getIndexType());
2079 Value result = LLVM::PoisonOp::create(rewriter, loc, llvmType);
2080 for (auto [idx, val] : llvm::enumerate(adaptor.getElements())) {
2081 auto constIdx =
2082 LLVM::ConstantOp::create(rewriter, loc, llvmIndexType, idx);
2083 result = LLVM::InsertElementOp::create(rewriter, loc, llvmType, result,
2084 val, constIdx);
2085 }
2086 rewriter.replaceOp(fromElementsOp, result);
2087 return success();
2088 }
2089};
2090
2091/// Conversion pattern for a `vector.to_elements`.
2092struct VectorToElementsLowering
2093 : public ConvertOpToLLVMPattern<vector::ToElementsOp> {
2095
2096 LogicalResult
2097 matchAndRewrite(vector::ToElementsOp toElementsOp, OpAdaptor adaptor,
2098 ConversionPatternRewriter &rewriter) const override {
2099 Location loc = toElementsOp.getLoc();
2100 auto idxType = typeConverter->convertType(rewriter.getIndexType());
2101 Value source = adaptor.getSource();
2102
2103 SmallVector<Value> results(toElementsOp->getNumResults());
2104 for (auto [idx, element] : llvm::enumerate(toElementsOp.getElements())) {
2105 // Create an extractelement operation only for results that are not dead.
2106 if (element.use_empty())
2107 continue;
2108
2109 auto constIdx = LLVM::ConstantOp::create(
2110 rewriter, loc, idxType, rewriter.getIntegerAttr(idxType, idx));
2111 auto llvmType = typeConverter->convertType(element.getType());
2112
2113 Value result = LLVM::ExtractElementOp::create(rewriter, loc, llvmType,
2114 source, constIdx);
2115 results[idx] = result;
2116 }
2117
2118 rewriter.replaceOp(toElementsOp, results);
2119 return success();
2120 }
2121};
2122
2123/// Conversion pattern for vector.step.
2124struct VectorStepOpLowering : public ConvertOpToLLVMPattern<vector::StepOp> {
2126
2127 LogicalResult
2128 matchAndRewrite(vector::StepOp stepOp, OpAdaptor adaptor,
2129 ConversionPatternRewriter &rewriter) const override {
2130 Type llvmType = typeConverter->convertType(stepOp.getType());
2131 rewriter.replaceOpWithNewOp<LLVM::StepVectorOp>(stepOp, llvmType);
2132 return success();
2133 }
2134};
2135
2136/// Progressive lowering of a `vector.contract %a, %b, %c` with row-major matmul
2137/// semantics to:
2138/// ```
2139/// %flattened_a = vector.shape_cast %a
2140/// %flattened_b = vector.shape_cast %b
2141/// %flattened_d = vector.matrix_multiply %flattened_a, %flattened_b
2142/// %d = vector.shape_cast %%flattened_d
2143/// %e = add %c, %d
2144/// ```
2145/// `vector.matrix_multiply` later lowers to `llvm.matrix.multiply`.
2146class ContractionOpToMatmulOpLowering
2147 : public vector::MaskableOpRewritePattern<vector::ContractionOp> {
2148public:
2149 using MaskableOpRewritePattern::MaskableOpRewritePattern;
2150
2151 ContractionOpToMatmulOpLowering(MLIRContext *context,
2152 PatternBenefit benefit = 100)
2153 : MaskableOpRewritePattern<vector::ContractionOp>(context, benefit) {}
2154
2155 FailureOr<Value>
2156 matchAndRewriteMaskableOp(vector::ContractionOp op, MaskingOpInterface maskOp,
2157 PatternRewriter &rewriter) const override;
2158};
2159
2160/// Lower a qualifying `vector.contract %a, %b, %c` (with row-major matmul
2161/// semantics directly into `llvm.intr.matrix.multiply`:
2162/// BEFORE:
2163/// ```mlir
2164/// %res = vector.contract #matmat_trait %lhs, %rhs, %acc
2165/// : vector<2x4xf32>, vector<4x3xf32> into vector<2x3xf32>
2166/// ```
2167///
2168/// AFTER:
2169/// ```mlir
2170/// %lhs = vector.shape_cast %arg0 : vector<2x4xf32> to vector<8xf32>
2171/// %rhs = vector.shape_cast %arg1 : vector<4x3xf32> to vector<12xf32>
2172/// %matmul = llvm.intr.matrix.multiply %lhs, %rhs
2173/// %res = arith.addf %acc, %matmul : vector<2x3xf32>
2174/// ```
2175//
2176/// Scalable vectors are not supported.
2177FailureOr<Value> ContractionOpToMatmulOpLowering::matchAndRewriteMaskableOp(
2178 vector::ContractionOp op, MaskingOpInterface maskOp,
2179 PatternRewriter &rew) const {
2180 // TODO: Support vector.mask.
2181 if (maskOp)
2182 return failure();
2183
2184 auto iteratorTypes = op.getIteratorTypes().getValue();
2185 if (!isParallelIterator(iteratorTypes[0]) ||
2186 !isParallelIterator(iteratorTypes[1]) ||
2187 !isReductionIterator(iteratorTypes[2]))
2188 return failure();
2189
2190 Type opResType = op.getType();
2191 VectorType vecType = dyn_cast<VectorType>(opResType);
2192 if (vecType && vecType.isScalable())
2193 return failure();
2194 // The result type only reflects the M and N dims, so a scalable K
2195 // (reduction) dim would slip through the check above.
2196 if (op.getLhsType().isScalable() || op.getRhsType().isScalable())
2197 return failure();
2198
2199 Type elementType = op.getLhsType().getElementType();
2200 if (!elementType.isIntOrFloat())
2201 return failure();
2202
2203 Type dstElementType = vecType ? vecType.getElementType() : opResType;
2204 if (elementType != dstElementType)
2205 return failure();
2206
2207 // Perform lhs + rhs transpositions to conform to matmul row-major semantics.
2208 // Bail out if the contraction cannot be put in this form.
2209 MLIRContext *ctx = op.getContext();
2210 Location loc = op.getLoc();
2211 AffineExpr m, n, k;
2212 bindDims(rew.getContext(), m, n, k);
2213 // LHS must be A(m, k) or A(k, m).
2214 Value lhs = op.getLhs();
2215 auto lhsMap = op.getIndexingMapsArray()[0];
2216 if (lhsMap == AffineMap::get(3, 0, {k, m}, ctx))
2217 lhs = vector::TransposeOp::create(rew, loc, lhs, ArrayRef<int64_t>{1, 0});
2218 else if (lhsMap != AffineMap::get(3, 0, {m, k}, ctx))
2219 return failure();
2220
2221 // RHS must be B(k, n) or B(n, k).
2222 Value rhs = op.getRhs();
2223 auto rhsMap = op.getIndexingMapsArray()[1];
2224 if (rhsMap == AffineMap::get(3, 0, {n, k}, ctx))
2225 rhs = vector::TransposeOp::create(rew, loc, rhs, ArrayRef<int64_t>{1, 0});
2226 else if (rhsMap != AffineMap::get(3, 0, {k, n}, ctx))
2227 return failure();
2228
2229 // At this point lhs and rhs are in row-major.
2230 VectorType lhsType = cast<VectorType>(lhs.getType());
2231 VectorType rhsType = cast<VectorType>(rhs.getType());
2232 int64_t lhsRows = lhsType.getDimSize(0);
2233 int64_t lhsColumns = lhsType.getDimSize(1);
2234 int64_t rhsColumns = rhsType.getDimSize(1);
2235
2236 Type flattenedLHSType =
2237 VectorType::get(lhsType.getNumElements(), lhsType.getElementType());
2238 lhs = vector::ShapeCastOp::create(rew, loc, flattenedLHSType, lhs);
2239
2240 Type flattenedRHSType =
2241 VectorType::get(rhsType.getNumElements(), rhsType.getElementType());
2242 rhs = vector::ShapeCastOp::create(rew, loc, flattenedRHSType, rhs);
2243
2244 Value mul = LLVM::MatrixMultiplyOp::create(
2245 rew, loc,
2246 VectorType::get(lhsRows * rhsColumns,
2247 cast<VectorType>(lhs.getType()).getElementType()),
2248 lhs, rhs, lhsRows, lhsColumns, rhsColumns);
2249
2250 mul = vector::ShapeCastOp::create(
2251 rew, loc,
2252 VectorType::get({lhsRows, rhsColumns},
2253 getElementTypeOrSelf(op.getAcc().getType())),
2254 mul);
2255
2256 // ACC must be C(m, n) or C(n, m).
2257 auto accMap = op.getIndexingMapsArray()[2];
2258 if (accMap == AffineMap::get(3, 0, {n, m}, ctx))
2259 mul = vector::TransposeOp::create(rew, loc, mul, ArrayRef<int64_t>{1, 0});
2260 else if (accMap != AffineMap::get(3, 0, {m, n}, ctx))
2261 llvm_unreachable("invalid contraction semantics");
2262
2263 Value res = isa<IntegerType>(elementType)
2264 ? static_cast<Value>(
2265 arith::AddIOp::create(rew, loc, op.getAcc(), mul))
2266 : static_cast<Value>(
2267 arith::AddFOp::create(rew, loc, op.getAcc(), mul));
2268
2269 return res;
2270}
2271
2272/// Lowers vector.transpose directly to llvm.intr.matrix.transpose
2273///
2274/// BEFORE:
2275/// ```mlir
2276/// %tr = vector.transpose %vec, [1, 0] : vector<2x4xf32> to vector<4x2xf32>
2277/// ```
2278/// AFTER:
2279/// ```mlir
2280/// %vec_cs = vector.shape_cast %vec : vector<2x4xf32> to vector<8xf32>
2281/// %tr = llvm.intr.matrix.transpose %vec_sc
2282/// {columns = 2 : i32, rows = 4 : i32} : vector<8xf32> into vector<8xf32>
2283/// %res = vector.shape_cast %tr : vector<8xf32> to vector<4x2xf32>
2284/// ```
2285class TransposeOpToMatrixTransposeOpLowering
2286 : public OpRewritePattern<vector::TransposeOp> {
2287public:
2288 using Base::Base;
2289
2290 LogicalResult matchAndRewrite(vector::TransposeOp op,
2291 PatternRewriter &rewriter) const override {
2292 auto loc = op.getLoc();
2293
2294 Value input = op.getVector();
2295 VectorType inputType = op.getSourceVectorType();
2296 VectorType resType = op.getResultVectorType();
2297
2298 if (inputType.isScalable())
2299 return rewriter.notifyMatchFailure(
2300 op, "This lowering does not support scalable vectors");
2301
2302 // Set up convenience transposition table.
2303 ArrayRef<int64_t> transp = op.getPermutation();
2304
2305 if (resType.getRank() != 2 || transp[0] != 1 || transp[1] != 0) {
2306 return failure();
2307 }
2308
2309 Type flattenedType =
2310 VectorType::get(resType.getNumElements(), resType.getElementType());
2311 auto matrix =
2312 vector::ShapeCastOp::create(rewriter, loc, flattenedType, input);
2313 auto rows = rewriter.getI32IntegerAttr(resType.getShape()[0]);
2314 auto columns = rewriter.getI32IntegerAttr(resType.getShape()[1]);
2315 Value trans = LLVM::MatrixTransposeOp::create(rewriter, loc, flattenedType,
2316 matrix, rows, columns);
2317 rewriter.replaceOpWithNewOp<vector::ShapeCastOp>(op, resType, trans);
2318 return success();
2319 }
2320};
2321
2322} // namespace
2323
2325 RewritePatternSet &patterns) {
2326 patterns.add<VectorFMAOpNDRewritePattern>(patterns.getContext());
2327}
2328
2330 RewritePatternSet &patterns, PatternBenefit benefit) {
2331 patterns.add<ContractionOpToMatmulOpLowering>(patterns.getContext(), benefit);
2332}
2333
2335 RewritePatternSet &patterns, PatternBenefit benefit) {
2336 patterns.add<TransposeOpToMatrixTransposeOpLowering>(patterns.getContext(),
2337 benefit);
2338}
2339
2340/// Populate the given list with patterns that convert from Vector to LLVM.
2342 const LLVMTypeConverter &converter, RewritePatternSet &patterns,
2343 bool reassociateFPReductions, bool force32BitVectorIndices,
2344 bool useVectorAlignment, bool enableGEPInboundsNuw) {
2345 // This function populates only ConversionPatterns, not RewritePatterns.
2346 MLIRContext *ctx = converter.getDialect()->getContext();
2347 patterns.add<VectorReductionOpConversion>(converter, reassociateFPReductions);
2348 patterns.add<VectorCreateMaskOpConversion>(ctx, force32BitVectorIndices);
2349 patterns.add<VectorLoadStoreConversion<vector::LoadOp>,
2350 VectorLoadStoreConversion<vector::MaskedLoadOp>,
2351 VectorLoadStoreConversion<vector::StoreOp>,
2352 VectorLoadStoreConversion<vector::MaskedStoreOp>>(
2353 converter, useVectorAlignment, enableGEPInboundsNuw);
2354 patterns.add<VectorGatherOpConversion, VectorScatterOpConversion>(
2355 converter, useVectorAlignment);
2356 patterns.add<VectorBitCastOpConversion, VectorShuffleOpConversion,
2357 VectorExtractOpConversion, VectorFMAOp1DConversion,
2358 VectorInsertOpConversion, VectorPrintOpConversion,
2359 VectorTypeCastOpConversion, VectorScaleOpConversion,
2360 VectorExpandLoadOpConversion, VectorCompressStoreOpConversion,
2361 VectorBroadcastScalarToLowRankLowering,
2362 VectorBroadcastScalarToNdLowering,
2363 VectorScalableInsertOpLowering, VectorScalableExtractOpLowering,
2364 MaskedReductionOpConversion, VectorInterleaveOpLowering,
2365 VectorDeinterleaveOpLowering, VectorFromElementsLowering,
2366 VectorToElementsLowering, VectorStepOpLowering>(converter);
2367}
2368
2369namespace {
2370struct VectorToLLVMDialectInterface : public ConvertToLLVMPatternInterface {
2371 VectorToLLVMDialectInterface(Dialect *dialect)
2372 : ConvertToLLVMPatternInterface(dialect) {}
2373
2374 using ConvertToLLVMPatternInterface::ConvertToLLVMPatternInterface;
2375 void loadDependentDialects(MLIRContext *context) const final {
2376 context->loadDialect<LLVM::LLVMDialect>();
2377 }
2378
2379 /// Hook for derived dialect interface to provide conversion patterns
2380 /// and mark dialect legal for the conversion target.
2381 void populateConvertToLLVMConversionPatterns(
2382 ConversionTarget &target, LLVMTypeConverter &typeConverter,
2383 RewritePatternSet &patterns) const final {
2384 populateVectorToLLVMConversionPatterns(typeConverter, patterns);
2385 }
2386};
2387} // namespace
2388
2390 DialectRegistry &registry) {
2391 registry.addExtension(+[](MLIRContext *ctx, vector::VectorDialect *dialect) {
2392 dialect->addInterfaces<VectorToLLVMDialectInterface>();
2393 });
2394}
return success()
static Value getIndexedPtrs(ConversionPatternRewriter &rewriter, Location loc, const LLVMTypeConverter &typeConverter, MemRefType memRefType, Value llvmMemref, Value base, Value index, VectorType vectorType)
LogicalResult getVectorToLLVMAlignment(const LLVMTypeConverter &typeConverter, VectorType vectorType, MemRefType memrefType, unsigned &align, bool useVectorAlignment)
LogicalResult getVectorAlignment(const LLVMTypeConverter &typeConverter, VectorType vectorType, unsigned &align)
LogicalResult getMemRefAlignment(const LLVMTypeConverter &typeConverter, MemRefType memrefType, unsigned &align)
static Value extractOne(ConversionPatternRewriter &rewriter, const LLVMTypeConverter &typeConverter, Location loc, Value val, Type llvmType, int64_t rank, int64_t pos)
static Value insertOne(ConversionPatternRewriter &rewriter, const LLVMTypeConverter &typeConverter, Location loc, Value val1, Value val2, Type llvmType, int64_t rank, int64_t pos)
static Value getAsLLVMValue(OpBuilder &builder, Location loc, OpFoldResult foldResult)
Convert foldResult into a Value.
static LogicalResult isMemRefTypeSupported(MemRefType memRefType, const LLVMTypeConverter &converter)
LogicalResult initialize(unsigned origNumLoops, ArrayRef< ReassociationIndices > foldedIterationDims)
lhs
static Value broadcast(Location loc, Value toBroadcast, unsigned numElements, const TypeConverter &typeConverter, ConversionPatternRewriter &rewriter)
Broadcasts the value to vector with numElements number of elements.
static void printOp(llvm::raw_ostream &os, Operation *op, OpPrintingFlags &flags)
Definition Unit.cpp:18
#define mul(a, b)
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
IntegerAttr getI32IntegerAttr(int32_t value)
Definition Builders.cpp:208
TypedAttr getZeroAttr(Type type)
Definition Builders.cpp:333
MLIRContext * getContext() const
Definition Builders.h:56
Utility class for operation conversions targeting the LLVM dialect that match exactly one source oper...
Definition Pattern.h:233
ConvertOpToLLVMPattern(const LLVMTypeConverter &typeConverter, PatternBenefit benefit=1)
Definition Pattern.h:239
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
bool addExtension(TypeID extensionID, std::unique_ptr< DialectExtensionBase > extension)
Add the given extension to the registry.
Dialects are groups of MLIR operations, types and attributes, as well as behavior associated with the...
Definition Dialect.h:38
Conversion from types to the LLVM IR dialect.
const llvm::DataLayout & getDataLayout() const
Returns the data layout to use during and after conversion.
FailureOr< unsigned > getMemRefAddressSpace(BaseMemRefType type) const
Return the LLVM address space corresponding to the memory space of the memref type type or failure if...
LLVM::LLVMDialect * getDialect() const
Returns the LLVM dialect.
Utility class to translate MLIR LLVM dialect types to LLVM IR.
Definition TypeToLLVM.h:39
unsigned getPreferredAlignment(Type type, const llvm::DataLayout &layout)
Returns the preferred alignment for the type given the data layout.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
Helper class to produce LLVM dialect operations extracting or inserting elements of a MemRef descript...
LLVM::LLVMPointerType getElementPtrType()
Returns the (LLVM) pointer type this descriptor contains.
Generic implementation of one-to-one conversion from "SourceOp" to "TargetOp" where the latter belong...
Definition Pattern.h:336
This class helps build Operations.
Definition Builders.h:210
This class represents a single result from folding an operation.
This class represents the benefit of a pattern match in a unitless scheme that ranges from 0 (very li...
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isIntOrIndex() const
Return true if this is an integer (of any signedness) or an index type.
Definition Types.cpp:114
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Definition Types.cpp:118
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition Types.cpp:124
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
Location getLoc() const
Return the location of this value.
Definition Value.cpp:24
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:453
void printType(Type type, AsmPrinter &printer)
Prints an LLVM Dialect type.
void nDVectorIterate(const NDVectorTypeInfo &info, OpBuilder &builder, function_ref< void(ArrayRef< int64_t >)> fun)
NDVectorTypeInfo extractNDVectorTypeInfo(VectorType vectorType, const LLVMTypeConverter &converter)
Value getStridedElementPtr(OpBuilder &builder, Location loc, const LLVMTypeConverter &converter, MemRefType type, Value memRefDesc, ValueRange indices, LLVM::GEPNoWrapFlags noWrapFlags=LLVM::GEPNoWrapFlags::none)
Performs the index computation to get to the element at indices of the memory pointed to by memRefDes...
Definition Pattern.cpp:628
Type getVectorType(Type elementType, unsigned numElements, bool isScalable=false)
Creates an LLVM dialect-compatible vector type with the given element type and length.
LLVM::FastmathFlags convertArithFastMathFlagsToLLVM(arith::FastMathFlags arithFMF)
Maps arithmetic fastmath enum values to LLVM enum values.
bool hasNegativeStaticStride(MemRefType memRefTy)
Returns true if any stride of memRefTy is statically known to be negative.
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
bool isReductionIterator(Attribute attr)
Returns true if attr has "reduction" iterator type semantics.
Definition VectorOps.h:151
void populateVectorContractToMatrixMultiply(RewritePatternSet &patterns, PatternBenefit benefit=100)
Populate the pattern set with the following patterns:
void populateVectorRankReducingFMAPattern(RewritePatternSet &patterns)
Populates a pattern that rank-reduces n-D FMAs into (n-1)-D FMAs where n > 1.
bool isParallelIterator(Attribute attr)
Returns true if attr has "parallel" iterator type semantics.
Definition VectorOps.h:146
void registerConvertVectorToLLVMInterface(DialectRegistry &registry)
SmallVector< int64_t > getAsIntegers(ArrayRef< Value > values)
Returns the integer numbers in values.
bool isValidLoadStoreMemRefLayout(VectorType vecTy, MemRefType memRefTy)
Returns true if memRefTy has a valid layout for a vector.load/store of vecTy: the most minor memref d...
void populateVectorTransposeToFlatTranspose(RewritePatternSet &patterns, PatternBenefit benefit=100)
Populate the pattern set with the following patterns:
Value createReductionNeutralValue(OpBuilder &builder, Location loc, Type type, vector::CombiningKind kind, arith::FastMathFlagsAttr fastmath=nullptr)
Creates a constant filled with the neutral (identity) value for the given reduction kind.
Include the generated interface declarations.
SmallVector< OpFoldResult > getMixedValues(ArrayRef< int64_t > staticValues, ValueRange dynamicValues, MLIRContext *context)
Return a vector of OpFoldResults with the same size a staticValues, but all elements for which Shaped...
void populateVectorToLLVMConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, bool reassociateFPReductions=false, bool force32BitVectorIndices=false, bool useVectorAlignment=false, bool enableGEPInboundsNuw=false)
Collect a set of patterns to convert from the Vector dialect to LLVM.
void bindDims(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to DimExpr at positions: [0 .
Definition AffineExpr.h:313
Value getValueOrCreateCastToIndexLike(OpBuilder &b, Location loc, Type targetType, Value value)
Create a cast from an index-like value (index or integer) to another index-like value.
Definition Utils.cpp:122
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
@ None
An explicit data construct.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
A pattern for ops that implement MaskableOpInterface and that might be masked (i.e.