31#include "llvm/ADT/APInt.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/StringExtras.h"
35#include "llvm/Support/CheckedArithmetic.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/MathExtras.h"
41#define DEBUG_TYPE "mlir-spirv-conversion"
51static std::optional<SmallVector<int64_t>>
getTargetShape(VectorType vecType) {
52 LLVM_DEBUG(llvm::dbgs() <<
"Get target shape\n");
53 if (vecType.isScalable()) {
54 LLVM_DEBUG(llvm::dbgs()
55 <<
"--scalable vectors are not supported -> BAIL\n");
58 if (vecType.getRank() == 0) {
59 LLVM_DEBUG(llvm::dbgs() <<
"--0-D vectors are not supported -> BAIL\n");
66 LLVM_DEBUG(llvm::dbgs() <<
"--no unrolling target shape defined\n");
70 if (!maybeShapeRatio) {
71 LLVM_DEBUG(llvm::dbgs()
72 <<
"--could not compute integral shape ratio -> BAIL\n");
75 if (llvm::all_of(*maybeShapeRatio, [](
int64_t v) {
return v == 1; })) {
76 LLVM_DEBUG(llvm::dbgs() <<
"--no unrolling needed -> SKIP\n");
79 LLVM_DEBUG(llvm::dbgs()
80 <<
"--found an integral shape ratio to unroll to -> SUCCESS\n");
90template <
typename LabelT>
91static LogicalResult checkExtensionRequirements(
94 for (
const auto &ors : candidates) {
100 for (spirv::Extension ext : ors)
101 extStrings.push_back(spirv::stringifyExtension(ext));
103 llvm::dbgs() << label <<
" illegal: requires at least one extension in ["
104 << llvm::join(extStrings,
", ")
105 <<
"] but none allowed in target environment\n";
118template <
typename LabelT>
119static LogicalResult checkCapabilityRequirements(
122 for (
const auto &ors : candidates) {
123 if (targetEnv.
allows(ors))
128 for (spirv::Capability cap : ors)
129 capStrings.push_back(spirv::stringifyCapability(cap));
131 llvm::dbgs() << label <<
" illegal: requires at least one capability in ["
132 << llvm::join(capStrings,
", ")
133 <<
"] but none allowed in target environment\n";
142static bool needsExplicitLayout(spirv::StorageClass storageClass) {
143 switch (storageClass) {
144 case spirv::StorageClass::PhysicalStorageBuffer:
145 case spirv::StorageClass::PushConstant:
146 case spirv::StorageClass::StorageBuffer:
147 case spirv::StorageClass::Uniform:
157wrapInStructAndGetPointer(
Type elementType, spirv::StorageClass storageClass) {
158 auto structType = needsExplicitLayout(storageClass)
170 return cast<spirv::ScalarType>(
171 IntegerType::get(ctx,
options.use64bitIndex ? 64 : 32));
176static std::optional<int64_t>
178 if (isa<spirv::ScalarType>(type)) {
192 if (
options.emulateUnsupportedFloatTypes && isa<FloatType>(type)) {
199 if (
auto complexType = dyn_cast<ComplexType>(type)) {
200 auto elementSize = getTypeNumBytes(
options, complexType.getElementType());
203 return 2 * *elementSize;
206 if (
auto vecType = dyn_cast<VectorType>(type)) {
207 auto elementSize = getTypeNumBytes(
options, vecType.getElementType());
210 return vecType.getNumElements() * *elementSize;
213 if (
auto memRefType = dyn_cast<MemRefType>(type)) {
218 if (!memRefType.hasStaticShape() ||
219 failed(memRefType.getStridesAndOffset(strides, offset)))
225 auto elementSize = getTypeNumBytes(
options, memRefType.getElementType());
229 if (memRefType.getRank() == 0)
232 auto dims = memRefType.getShape();
233 if (llvm::is_contained(dims, ShapedType::kDynamic) ||
234 ShapedType::isDynamic(offset) ||
235 llvm::is_contained(strides, ShapedType::kDynamic))
239 for (
const auto &
shape : enumerate(dims))
240 memrefSize = std::max(memrefSize,
shape.value() * strides[
shape.index()]);
242 return (offset + memrefSize) * *elementSize;
245 if (
auto tensorType = dyn_cast<TensorType>(type)) {
246 if (!tensorType.hasStaticShape())
249 auto elementSize = getTypeNumBytes(
options, tensorType.getElementType());
254 for (
auto shape : tensorType.getShape())
267 std::optional<spirv::StorageClass> storageClass = {}) {
271 type.getExtensions(extensions, storageClass);
272 type.getCapabilities(capabilities, storageClass);
275 checkCapabilityRequirements(type, targetEnv, capabilities)) &&
276 succeeded(checkExtensionRequirements(type, targetEnv, extensions));
283 std::optional<spirv::StorageClass> storageClass = {}) {
284 if (isScalarTypeSupported(targetEnv, type, storageClass))
289 if (isa<Float4E2M1FNType, Float6E2M3FNType, Float6E3M2FNType>(type))
294 if (!
options.emulateLT32BitScalarTypes)
299 LLVM_DEBUG(llvm::dbgs()
301 <<
" not converted to 32-bit for SPIR-V to avoid truncation\n");
305 if (
auto floatType = dyn_cast<FloatType>(type)) {
306 LLVM_DEBUG(llvm::dbgs() << type <<
" converted to 32-bit for SPIR-V\n");
310 auto intType = cast<IntegerType>(type);
311 LLVM_DEBUG(llvm::dbgs() << type <<
" converted to 32-bit for SPIR-V\n");
312 return IntegerType::get(targetEnv.
getContext(), 32,
313 intType.getSignedness());
326 if (type.getWidth() > 8) {
327 LLVM_DEBUG(llvm::dbgs() <<
"not a subbyte type\n");
331 LLVM_DEBUG(llvm::dbgs() <<
"unsupported sub-byte storage kind\n");
335 if (!llvm::isPowerOf2_32(type.getWidth())) {
336 LLVM_DEBUG(llvm::dbgs()
337 <<
"unsupported non-power-of-two bitwidth in sub-byte" << type
342 LLVM_DEBUG(llvm::dbgs() << type <<
" converted to 32-bit for SPIR-V\n");
343 return IntegerType::get(type.getContext(), 32,
344 type.getSignedness());
351 if (!
options.emulateUnsupportedFloatTypes)
354 if (isa<Float8E5M2Type, Float8E4M3Type, Float8E4M3FNType, Float8E5M2FNUZType,
355 Float8E4M3FNUZType, Float8E4M3B11FNUZType, Float8E3M4Type,
356 Float8E8M0FNUType>(type))
357 return IntegerType::get(type.getContext(), type.getWidth());
358 LLVM_DEBUG(llvm::dbgs() <<
"unsupported 8-bit float type: " << type <<
"\n");
366convertShaped8BitFloatType(ShapedType type,
368 if (!
options.emulateUnsupportedFloatTypes)
370 Type srcElementType = type.getElementType();
371 Type convertedElementType =
nullptr;
373 if (isa<Float8E5M2Type, Float8E4M3Type, Float8E4M3FNType, Float8E5M2FNUZType,
374 Float8E4M3FNUZType, Float8E4M3B11FNUZType, Float8E3M4Type,
375 Float8E8M0FNUType>(srcElementType))
376 convertedElementType = IntegerType::get(
379 if (!convertedElementType)
382 return type.clone(convertedElementType);
389convertIndexElementType(ShapedType type,
391 Type indexType = dyn_cast<IndexType>(type.getElementType());
402 std::optional<spirv::StorageClass> storageClass = {}) {
403 type = cast<VectorType>(convertIndexElementType(type,
options));
404 type = cast<VectorType>(convertShaped8BitFloatType(type,
options));
405 auto scalarType = dyn_cast_or_null<spirv::ScalarType>(type.getElementType());
409 auto intType = dyn_cast<IntegerType>(type.getElementType());
411 LLVM_DEBUG(llvm::dbgs()
413 <<
" illegal: cannot convert non-scalar element type\n");
417 Type elementType = convertSubByteIntegerType(
options, intType);
421 if (type.getRank() <= 1 && type.getNumElements() == 1)
424 if (type.getNumElements() > 4) {
425 LLVM_DEBUG(llvm::dbgs()
426 << type <<
" illegal: > 4-element unimplemented\n");
430 return VectorType::get(type.getShape(), elementType);
433 if (type.getRank() <= 1 && type.getNumElements() == 1)
434 return convertScalarType(targetEnv,
options, scalarType, storageClass);
437 LLVM_DEBUG(llvm::dbgs()
438 << type <<
" illegal: not a valid composite type\n");
445 cast<spirv::CompositeType>(type).getExtensions(extensions, storageClass);
446 cast<spirv::CompositeType>(type).getCapabilities(capabilities, storageClass);
449 if (succeeded(checkCapabilityRequirements(type, targetEnv, capabilities)) &&
450 succeeded(checkExtensionRequirements(type, targetEnv, extensions)))
454 convertScalarType(targetEnv,
options, scalarType, storageClass);
456 return VectorType::get(type.getShape(), elementType);
463 std::optional<spirv::StorageClass> storageClass = {}) {
464 auto scalarType = dyn_cast_or_null<spirv::ScalarType>(type.getElementType());
466 LLVM_DEBUG(llvm::dbgs()
467 << type <<
" illegal: cannot convert non-scalar element type\n");
472 convertScalarType(targetEnv,
options, scalarType, storageClass);
475 if (elementType != type.getElementType()) {
476 LLVM_DEBUG(llvm::dbgs()
477 << type <<
" illegal: complex type emulation unsupported\n");
481 return VectorType::get(2, elementType);
494 if (!type.hasStaticShape()) {
495 LLVM_DEBUG(llvm::dbgs()
496 << type <<
" illegal: dynamic shape unimplemented\n");
500 type = cast<TensorType>(convertIndexElementType(type,
options));
501 type = cast<TensorType>(convertShaped8BitFloatType(type,
options));
502 auto scalarType = dyn_cast_or_null<spirv::ScalarType>(type.
getElementType());
504 LLVM_DEBUG(llvm::dbgs()
505 << type <<
" illegal: cannot convert non-scalar element type\n");
509 std::optional<int64_t> scalarSize = getTypeNumBytes(
options, scalarType);
510 std::optional<int64_t> tensorSize = getTypeNumBytes(
options, type);
511 if (!scalarSize || !tensorSize) {
512 LLVM_DEBUG(llvm::dbgs()
513 << type <<
" illegal: cannot deduce element count\n");
517 int64_t arrayElemCount = *tensorSize / *scalarSize;
518 if (arrayElemCount == 0) {
519 LLVM_DEBUG(llvm::dbgs()
520 << type <<
" illegal: cannot handle zero-element tensors\n");
523 if (arrayElemCount > std::numeric_limits<unsigned>::max()) {
524 LLVM_DEBUG(llvm::dbgs()
525 << type <<
" illegal: cannot fit tensor into target type\n");
529 Type arrayElemType = convertScalarType(targetEnv,
options, scalarType);
532 std::optional<int64_t> arrayElemSize =
533 getTypeNumBytes(
options, arrayElemType);
534 if (!arrayElemSize) {
535 LLVM_DEBUG(llvm::dbgs()
536 << type <<
" illegal: cannot deduce converted element size\n");
546 spirv::StorageClass storageClass) {
547 unsigned numBoolBits =
options.boolNumBits;
548 if (numBoolBits != 8) {
549 LLVM_DEBUG(llvm::dbgs()
550 <<
"using non-8-bit storage for bool types unimplemented");
553 auto elementType = dyn_cast<spirv::ScalarType>(
554 IntegerType::get(type.
getContext(), numBoolBits));
558 convertScalarType(targetEnv,
options, elementType, storageClass);
561 std::optional<int64_t> arrayElemSize =
562 getTypeNumBytes(
options, arrayElemType);
563 if (!arrayElemSize) {
564 LLVM_DEBUG(llvm::dbgs()
565 << type <<
" illegal: cannot deduce converted element size\n");
569 if (!type.hasStaticShape()) {
572 if (targetEnv.
allows(spirv::Capability::Kernel))
574 int64_t stride = needsExplicitLayout(storageClass) ? *arrayElemSize : 0;
578 return wrapInStructAndGetPointer(arrayType, storageClass);
581 if (type.getNumElements() == 0) {
582 LLVM_DEBUG(llvm::dbgs()
583 << type <<
" illegal: zero-element memrefs are not supported\n");
587 int64_t memrefSize = llvm::divideCeil(type.getNumElements() * numBoolBits, 8);
588 int64_t arrayElemCount = llvm::divideCeil(memrefSize, *arrayElemSize);
589 int64_t stride = needsExplicitLayout(storageClass) ? *arrayElemSize : 0;
591 if (targetEnv.
allows(spirv::Capability::Kernel))
593 return wrapInStructAndGetPointer(arrayType, storageClass);
599 spirv::StorageClass storageClass) {
600 IntegerType elementType = cast<IntegerType>(type.getElementType());
601 Type arrayElemType = convertSubByteIntegerType(
options, elementType);
606 if (!type.hasStaticShape()) {
609 if (targetEnv.
allows(spirv::Capability::Kernel))
611 int64_t stride = needsExplicitLayout(storageClass) ? arrayElemSize : 0;
615 return wrapInStructAndGetPointer(arrayType, storageClass);
618 if (type.getNumElements() == 0) {
619 LLVM_DEBUG(llvm::dbgs()
620 << type <<
" illegal: zero-element memrefs are not supported\n");
625 llvm::divideCeil(type.getNumElements() * elementType.getWidth(), 8);
626 int64_t arrayElemCount = llvm::divideCeil(memrefSize, arrayElemSize);
627 int64_t stride = needsExplicitLayout(storageClass) ? arrayElemSize : 0;
629 if (targetEnv.
allows(spirv::Capability::Kernel))
631 return wrapInStructAndGetPointer(arrayType, storageClass);
634static spirv::Dim convertRank(
int64_t rank) {
637 return spirv::Dim::Dim1D;
639 return spirv::Dim::Dim2D;
641 return spirv::Dim::Dim3D;
643 llvm_unreachable(
"Invalid memref rank!");
647static spirv::ImageFormat getImageFormat(
Type elementType) {
649 .Case([](Float16Type) {
return spirv::ImageFormat::R16f; })
650 .Case([](Float32Type) {
return spirv::ImageFormat::R32f; })
651 .Case([](IntegerType intType) {
652 auto const isSigned = intType.isSigned() || intType.isSignless();
653#define BIT_WIDTH_CASE(BIT_WIDTH) \
655 return isSigned ? spirv::ImageFormat::R##BIT_WIDTH##i \
656 : spirv::ImageFormat::R##BIT_WIDTH##ui
658 switch (intType.getWidth()) {
662 llvm_unreachable(
"Unhandled integer type!");
665 .DefaultUnreachable(
"Unhandled element type!");
672 auto attr = dyn_cast_or_null<spirv::StorageClassAttr>(type.getMemorySpace());
677 <<
" illegal: expected memory space to be a SPIR-V storage class "
678 "attribute; please use MemorySpaceToStorageClassConverter to map "
679 "numeric memory spaces beforehand\n");
682 spirv::StorageClass storageClass = attr.getValue();
687 if (storageClass == spirv::StorageClass::Image) {
688 const int64_t rank = type.getRank();
689 if (rank < 1 || rank > 3) {
690 LLVM_DEBUG(llvm::dbgs()
691 << type <<
" illegal: cannot lower memref of rank " << rank
692 <<
" to a SPIR-V Image\n");
698 auto elementType = type.getElementType();
699 if (!isa<spirv::ScalarType>(elementType) ||
701 LLVM_DEBUG(llvm::dbgs() << type <<
" illegal: cannot lower memref of "
702 << elementType <<
" to a SPIR-V Image\n");
710 elementType, convertRank(rank), spirv::ImageDepthInfo::DepthUnknown,
711 spirv::ImageArrayedInfo::NonArrayed,
712 spirv::ImageSamplingInfo::SingleSampled,
713 spirv::ImageSamplerUseInfo::NeedSampler, getImageFormat(elementType));
716 spvSampledImageType, spirv::StorageClass::UniformConstant);
720 if (isa<IntegerType>(type.getElementType())) {
721 if (type.getElementTypeBitWidth() == 1)
722 return convertBoolMemrefType(targetEnv,
options, type, storageClass);
723 if (type.getElementTypeBitWidth() < 8)
724 return convertSubByteMemrefType(targetEnv,
options, type, storageClass);
728 Type elementType = type.getElementType();
729 if (
auto vecType = dyn_cast<VectorType>(elementType)) {
731 convertVectorType(targetEnv,
options, vecType, storageClass);
732 }
else if (
auto complexType = dyn_cast<ComplexType>(elementType)) {
734 convertComplexType(targetEnv,
options, complexType, storageClass);
735 }
else if (
auto scalarType = dyn_cast<spirv::ScalarType>(elementType)) {
737 convertScalarType(targetEnv,
options, scalarType, storageClass);
738 }
else if (
auto indexType = dyn_cast<IndexType>(elementType)) {
739 type = cast<MemRefType>(convertIndexElementType(type,
options));
740 arrayElemType = type.getElementType();
741 }
else if (
auto floatType = dyn_cast<FloatType>(elementType)) {
743 type = cast<MemRefType>(convertShaped8BitFloatType(type,
options));
744 arrayElemType = type.getElementType();
749 <<
" unhandled: can only convert scalar or vector element type\n");
755 std::optional<int64_t> arrayElemSize =
756 getTypeNumBytes(
options, arrayElemType);
757 if (!arrayElemSize) {
758 LLVM_DEBUG(llvm::dbgs()
759 << type <<
" illegal: cannot deduce converted element size\n");
763 if (!type.hasStaticShape()) {
766 if (targetEnv.
allows(spirv::Capability::Kernel))
768 int64_t stride = needsExplicitLayout(storageClass) ? *arrayElemSize : 0;
772 return wrapInStructAndGetPointer(arrayType, storageClass);
775 std::optional<int64_t> memrefSize = getTypeNumBytes(
options, type);
777 LLVM_DEBUG(llvm::dbgs()
778 << type <<
" illegal: cannot deduce element count\n");
782 if (*memrefSize == 0) {
783 LLVM_DEBUG(llvm::dbgs()
784 << type <<
" illegal: zero-element memrefs are not supported\n");
788 int64_t arrayElemCount = llvm::divideCeil(*memrefSize, *arrayElemSize);
789 int64_t stride = needsExplicitLayout(storageClass) ? *arrayElemSize : 0;
791 if (targetEnv.
allows(spirv::Capability::Kernel))
793 return wrapInStructAndGetPointer(arrayType, storageClass);
817 if (inputs.size() != 1) {
819 UnrealizedConversionCastOp::create(builder, loc, type, inputs);
820 return castOp.getResult(0);
822 Value input = inputs.front();
825 if (!isa<IntegerType>(type)) {
827 UnrealizedConversionCastOp::create(builder, loc, type, inputs);
828 return castOp.getResult(0);
830 auto inputType = cast<IntegerType>(input.
getType());
832 auto scalarType = dyn_cast<spirv::ScalarType>(type);
835 UnrealizedConversionCastOp::create(builder, loc, type, inputs);
836 return castOp.getResult(0);
842 if (inputType.getIntOrFloatBitWidth() < scalarType.getIntOrFloatBitWidth()) {
844 UnrealizedConversionCastOp::create(builder, loc, type, inputs);
845 return castOp.getResult(0);
850 Value one = spirv::ConstantOp::getOne(inputType, loc, builder);
851 return spirv::IEqualOp::create(builder, loc, input, one);
857 scalarType.getExtensions(exts);
858 scalarType.getCapabilities(caps);
859 if (failed(checkCapabilityRequirements(type, targetEnv, caps)) ||
860 failed(checkExtensionRequirements(type, targetEnv, exts))) {
862 UnrealizedConversionCastOp::create(builder, loc, type, inputs);
863 return castOp.getResult(0);
870 return spirv::SConvertOp::create(builder, loc, type, input);
872 return spirv::UConvertOp::create(builder, loc, type, input);
879static spirv::GlobalVariableOp getBuiltinVariable(
Block &body,
883 for (
auto varOp : body.
getOps<spirv::GlobalVariableOp>()) {
884 if (StringAttr builtinAttr = varOp.getBuiltInAttr()) {
885 auto varBuiltIn = spirv::symbolizeBuiltIn(builtinAttr.getValue());
895std::string getBuiltinVarName(spirv::BuiltIn
builtin, StringRef prefix,
897 return Twine(prefix).concat(stringifyBuiltIn(
builtin)).concat(suffix).str();
901static spirv::GlobalVariableOp
904 StringRef prefix, StringRef suffix) {
905 if (
auto varOp = getBuiltinVariable(body,
builtin))
911 spirv::GlobalVariableOp newVarOp;
913 case spirv::BuiltIn::NumWorkgroups:
914 case spirv::BuiltIn::WorkgroupSize:
915 case spirv::BuiltIn::WorkgroupId:
916 case spirv::BuiltIn::LocalInvocationId:
917 case spirv::BuiltIn::GlobalInvocationId: {
919 spirv::StorageClass::Input);
920 std::string name = getBuiltinVarName(
builtin, prefix, suffix);
922 spirv::GlobalVariableOp::create(builder, loc, ptrType, name,
builtin);
925 case spirv::BuiltIn::SubgroupId:
926 case spirv::BuiltIn::NumSubgroups:
927 case spirv::BuiltIn::SubgroupSize:
928 case spirv::BuiltIn::SubgroupLocalInvocationId: {
931 std::string name = getBuiltinVarName(
builtin, prefix, suffix);
933 spirv::GlobalVariableOp::create(builder, loc, ptrType, name,
builtin);
937 emitError(loc,
"unimplemented builtin variable generation for ")
960static spirv::GlobalVariableOp getPushConstantVariable(
Block &body,
961 unsigned elementCount) {
962 for (
auto varOp : body.
getOps<spirv::GlobalVariableOp>()) {
963 auto ptrType = dyn_cast<spirv::PointerType>(varOp.getType());
970 if (ptrType.getStorageClass() == spirv::StorageClass::PushConstant) {
971 auto numElements = cast<spirv::ArrayType>(
972 cast<spirv::StructType>(ptrType.getPointeeType())
975 if (numElements == elementCount)
984static spirv::GlobalVariableOp
988 if (
auto varOp = getPushConstantVariable(block, elementCount))
992 auto type = getPushConstantStorageType(elementCount, builder, indexType);
993 const char *name =
"__push_constant_var__";
994 return spirv::GlobalVariableOp::create(builder, loc, type, name,
1004struct FuncOpConversion final : OpConversionPattern<func::FuncOp> {
1008 matchAndRewrite(func::FuncOp funcOp, OpAdaptor adaptor,
1009 ConversionPatternRewriter &rewriter)
const override {
1010 FunctionType fnType = funcOp.getFunctionType();
1011 if (fnType.getNumResults() > 1)
1014 TypeConverter::SignatureConversion signatureConverter(
1015 fnType.getNumInputs());
1016 for (
const auto &argType : enumerate(fnType.getInputs())) {
1017 auto convertedType = getTypeConverter()->convertType(argType.value());
1020 signatureConverter.addInputs(argType.index(), convertedType);
1024 if (fnType.getNumResults() == 1) {
1025 resultType = getTypeConverter()->convertType(fnType.getResult(0));
1031 auto newFuncOp = spirv::FuncOp::create(
1032 rewriter, funcOp.getLoc(), funcOp.getName(),
1033 rewriter.getFunctionType(signatureConverter.getConvertedTypes(),
1037 newFuncOp.setArgAttrsAttr(funcOp.getArgAttrsAttr());
1038 newFuncOp.setResAttrsAttr(funcOp.getResAttrsAttr());
1039 cast<SymbolOpInterface>(newFuncOp.getOperation())
1041 cast<SymbolOpInterface>(funcOp.getOperation()).getVisibility());
1045 funcOp->getDiscardableAttrDictionary().
getValue())
1046 newFuncOp->setDiscardableAttr(namedAttr.getName(), namedAttr.getValue());
1048 rewriter.inlineRegionBefore(funcOp.getBody(), newFuncOp.getBody(),
1050 if (failed(rewriter.convertRegionTypes(
1051 &newFuncOp.getBody(), *getTypeConverter(), &signatureConverter)))
1053 rewriter.eraseOp(funcOp);
1063 LogicalResult matchAndRewrite(func::FuncOp funcOp,
1065 FunctionType fnType = funcOp.getFunctionType();
1068 if (funcOp.isDeclaration()) {
1069 LLVM_DEBUG(llvm::dbgs()
1070 << fnType <<
" illegal: declarations are unsupported\n");
1077 if (llvm::any_of(fnType.getInputs(), [](
Type argType) {
1078 auto shapedType = dyn_cast<ShapedType>(argType);
1079 return shapedType && !shapedType.hasStaticShape();
1084 auto newFuncOp = func::FuncOp::create(rewriter, funcOp.getLoc(),
1085 funcOp.getName(), fnType);
1089 Location loc = newFuncOp.getBody().getLoc();
1091 Block &entryBlock = newFuncOp.getBlocks().
front();
1095 TypeConverter::SignatureConversion oneToNTypeMapping(
1096 fnType.getInputs().size());
1102 size_t newInputNo = 0;
1108 llvm::SmallDenseMap<Operation *, size_t> tmpOps;
1111 size_t newOpCount = 0;
1114 for (
auto [origInputNo, origType] : enumerate(fnType.getInputs())) {
1116 auto origVecType = dyn_cast<VectorType>(origType);
1119 auto castOp = UnrealizedConversionCastOp::create(
1123 tmpOps.insert({
result.getDefiningOp(), newInputNo});
1124 oneToNTypeMapping.addInputs(origInputNo, origType);
1133 auto castOp = UnrealizedConversionCastOp::create(
1137 tmpOps.insert({
result.getDefiningOp(), newInputNo});
1138 oneToNTypeMapping.addInputs(origInputNo, origType);
1143 VectorType unrolledType =
1144 VectorType::get(*targetShape, origVecType.getElementType());
1145 auto originalShape =
1146 llvm::to_vector_of<int64_t, 4>(origVecType.getShape());
1150 rewriter, loc, origVecType, rewriter.
getZeroAttr(origVecType));
1153 Value dummy = arith::ConstantOp::create(
1154 rewriter, loc, unrolledType, rewriter.
getZeroAttr(unrolledType));
1162 result = vector::InsertStridedSliceOp::create(rewriter, loc, dummy,
1163 result, offsets, strides);
1164 newTypes.push_back(unrolledType);
1165 unrolledInputNums.push_back(newInputNo);
1170 oneToNTypeMapping.addInputs(origInputNo, newTypes);
1174 auto convertedTypes = oneToNTypeMapping.getConvertedTypes();
1175 auto newFnType = fnType.clone(convertedTypes, fnType.getResults());
1177 [&] { newFuncOp.setFunctionType(newFnType); });
1186 for (
auto &[placeholderOp, argIdx] : tmpOps) {
1197 size_t unrolledInputIdx = 0;
1198 for (
auto [count, op] : enumerate(entryBlock.
getOperations())) {
1203 if (count >= newOpCount)
1205 if (
auto vecOp = dyn_cast<vector::InsertStridedSliceOp>(op)) {
1206 size_t unrolledInputNo = unrolledInputNums[unrolledInputIdx];
1208 curOp.
setOperand(0, newFuncOp.getArgument(unrolledInputNo));
1230 LogicalResult matchAndRewrite(func::ReturnOp returnOp,
1233 auto funcOp = dyn_cast<func::FuncOp>(returnOp->getParentOp());
1237 FunctionType fnType = funcOp.getFunctionType();
1238 TypeConverter::SignatureConversion oneToNTypeMapping(
1239 fnType.getResults().size());
1246 for (
auto [origResultNo, origType] : enumerate(fnType.getResults())) {
1248 auto origVecType = dyn_cast<VectorType>(origType);
1250 oneToNTypeMapping.addInputs(origResultNo, origType);
1251 newOperands.push_back(returnOp.getOperand(origResultNo));
1258 oneToNTypeMapping.addInputs(origResultNo, origType);
1259 newOperands.push_back(returnOp.getOperand(origResultNo));
1262 VectorType unrolledType =
1263 VectorType::get(*targetShape, origVecType.getElementType());
1267 auto originalShape =
1268 llvm::to_vector_of<int64_t, 4>(origVecType.getShape());
1271 extractShape.back() = targetShape->back();
1273 Value returnValue = returnOp.getOperand(origResultNo);
1276 Value result = vector::ExtractStridedSliceOp::create(
1277 rewriter, loc, returnValue, offsets, extractShape, strides);
1278 if (originalShape.size() > 1) {
1281 vector::ExtractOp::create(rewriter, loc,
result, extractIndices);
1283 newOperands.push_back(
result);
1284 newTypes.push_back(unrolledType);
1286 oneToNTypeMapping.addInputs(origResultNo, newTypes);
1292 TypeRange(oneToNTypeMapping.getConvertedTypes()));
1294 [&] { funcOp.setFunctionType(newFnType); });
1299 func::ReturnOp::create(rewriter, loc, newOperands));
1305static void addNoWrapDecorations(
Operation *op,
1321 if (
shape.size() != strides.size() || offset < 0)
1322 return std::nullopt;
1324 uint64_t maxLinearIndex = offset;
1325 for (
auto [dimension, stride] : llvm::zip(
shape, strides)) {
1326 if (dimension <= 0 || stride < 0)
1327 return std::nullopt;
1328 std::optional<uint64_t> nextMaxLinearIndex = llvm::checkedMulAddUnsigned(
1329 static_cast<uint64_t
>(dimension - 1),
static_cast<uint64_t
>(stride),
1331 if (!nextMaxLinearIndex)
1332 return std::nullopt;
1333 maxLinearIndex = *nextMaxLinearIndex;
1335 return maxLinearIndex;
1339 auto pointerType = dyn_cast<spirv::PointerType>(basePtr.
getType());
1341 pointerType.getStorageClass() != spirv::StorageClass::StorageBuffer)
1344 Type pointeeType = pointerType.getPointeeType();
1345 if (
auto structType = dyn_cast<spirv::StructType>(pointeeType)) {
1346 if (structType.getNumElements() != 1)
1348 pointeeType = structType.getElementType(0);
1350 return dyn_cast<spirv::ArrayType>(pointeeType);
1353static bool shouldEmitInBoundsAccessChain(MemRefType baseType,
Value basePtr,
1356 uint64_t accessElementCount) {
1357 std::optional<uint64_t> maxSourceElementIndex =
1358 getMaxLinearizedIndex(baseType.getShape(), strides, offset);
1360 if (!maxSourceElementIndex || !storageArrayType)
1368 if (baseType.getElementType() != storageArrayType.
getElementType())
1371 uint64_t storageElementCount = storageArrayType.
getNumElements();
1372 if (accessElementCount == 0 || accessElementCount > storageElementCount)
1381 return *maxSourceElementIndex < storageElementCount;
1393 StringRef prefix, StringRef suffix) {
1396 op->
emitError(
"expected operation to be within a module-like op");
1400 spirv::GlobalVariableOp varOp =
1402 builtin, integerType, builder, prefix, suffix);
1403 Value ptr = spirv::AddressOfOp::create(builder, op->
getLoc(), varOp);
1404 return spirv::LoadOp::create(builder, op->
getLoc(),
ptr);
1412 unsigned offset,
Type integerType,
1417 op->
emitError(
"expected operation to be within a module-like op");
1421 spirv::GlobalVariableOp varOp = getOrInsertPushConstantVariable(
1422 loc, parent->
getRegion(0).
front(), elementCount, builder, integerType);
1424 Value zeroOp = spirv::ConstantOp::getZero(integerType, loc, builder);
1425 Value offsetOp = spirv::ConstantOp::create(builder, loc, integerType,
1427 auto addrOp = spirv::AddressOfOp::create(builder, loc, varOp);
1428 auto acOp = spirv::AccessChainOp::create(builder, loc, addrOp,
1430 return spirv::LoadOp::create(builder, loc, acOp);
1443 if (!targetEnv.
allows(Extension::SPV_KHR_no_integer_wrap_decoration))
1446 auto integer = dyn_cast<IntegerType>(integerType);
1450 std::optional<uint64_t> maxLinearIndex =
1451 getMaxLinearizedIndex(
shape, strides, offset);
1452 if (!maxLinearIndex)
1457 APInt::getSignedMaxValue(integer.getWidth()).getZExtValue();
1459 *maxLinearIndex <= APInt::getMaxValue(integer.getWidth()).getZExtValue();
1467 assert(
indices.size() == strides.size() &&
1468 "must provide indices for all dimensions");
1476 loc, integerType, IntegerAttr::get(integerType, offset));
1480 IntegerAttr::get(integerType, strides[
index.index()]));
1484 if (
auto mul = update.getDefiningOp<spirv::IMulOp>())
1485 addNoWrapDecorations(
mul, noWrapFlags, builder);
1488 builder.
createOrFold<spirv::IAddOp>(loc, update, linearizedIndex);
1491 addNoWrapDecorations(
add, noWrapFlags, builder);
1493 return linearizedIndex;
1497 MemRefType baseType,
Value basePtr,
1500 uint64_t accessElementCount) {
1505 if (failed(baseType.getStridesAndOffset(strides, offset)) ||
1506 llvm::is_contained(strides, ShapedType::kDynamic) ||
1507 ShapedType::isDynamic(offset)) {
1513 typeConverter.
getTargetEnv(), baseType.getShape(), strides, offset,
1517 auto zero = spirv::ConstantOp::getZero(indexType, loc, builder);
1519 if (baseType.getRank() == 0) {
1520 linearizedIndices.push_back(zero);
1523 indices, strides, offset, indexType, loc, builder, noWrapFlags));
1526 const Type pointeeType =
1527 cast<spirv::PointerType>(basePtr.
getType()).getPointeeType();
1529 if (isa<spirv::StructType>(pointeeType))
1530 linearizedIndices.insert(linearizedIndices.begin(), zero);
1531 if (shouldEmitInBoundsAccessChain(baseType, basePtr, strides, offset,
1532 accessElementCount))
1533 return spirv::InBoundsAccessChainOp::create(builder, loc, basePtr,
1535 return spirv::AccessChainOp::create(builder, loc, basePtr, linearizedIndices);
1539 MemRefType baseType,
Value basePtr,
1547 MemRefType baseType,
Value basePtr,
1554 if (failed(baseType.getStridesAndOffset(strides, offset)) ||
1555 llvm::is_contained(strides, ShapedType::kDynamic) ||
1556 ShapedType::isDynamic(offset)) {
1562 typeConverter.
getTargetEnv(), baseType.getShape(), strides, offset,
1567 if (baseType.getRank() == 0) {
1568 linearIndex = spirv::ConstantOp::getZero(indexType, loc, builder);
1571 builder, noWrapFlags);
1574 cast<spirv::PointerType>(basePtr.
getType()).getPointeeType();
1575 if (isa<spirv::ArrayType>(pointeeType)) {
1576 linearizedIndices.push_back(linearIndex);
1577 return spirv::AccessChainOp::create(builder, loc, basePtr,
1580 return spirv::PtrAccessChainOp::create(builder, loc, basePtr, linearIndex,
1585 MemRefType baseType,
Value basePtr,
1588 uint64_t accessElementCount) {
1590 if (typeConverter.
allows(spirv::Capability::Kernel)) {
1596 builder, accessElementCount);
1600 MemRefType baseType,
Value basePtr,
1612 for (
int i : {4, 3, 2}) {
1621 VectorType srcVectorType = op.getSourceVectorType();
1622 assert(srcVectorType.getRank() == 1);
1625 return {vectorSize};
1630 VectorType vectorType = op.getResultVectorType();
1637std::optional<SmallVector<int64_t>>
1640 if (
auto vecType = dyn_cast<VectorType>(op->
getResultTypes()[0])) {
1641 if (vecType.getRank() == 0)
1642 return std::nullopt;
1651 .Case<vector::ReductionOp, vector::TransposeOp>(
1653 .Default(std::nullopt);
1677 populateVectorUnrollPatterns(patterns,
options);
1687 patterns, vector::VectorTransposeLowering::EltWise);
1698 vector::populateCastAwayVectorLeadingOneDimPatterns(patterns);
1699 vector::ReductionOp::getCanonicalizationPatterns(patterns, context);
1700 vector::TransposeOp::getCanonicalizationPatterns(patterns, context);
1704 vector::populateVectorInsertExtractStridedSliceDecompositionPatterns(
1706 vector::InsertOp::getCanonicalizationPatterns(patterns, context);
1707 vector::ExtractOp::getCanonicalizationPatterns(patterns, context);
1711 vector::BroadcastOp::getCanonicalizationPatterns(patterns, context);
1712 vector::ShapeCastOp::getCanonicalizationPatterns(patterns, context);
1726 : targetEnv(targetAttr), options(options) {
1739 addConversion([
this](IndexType ) {
return getIndexType(); });
1741 addConversion([
this](IntegerType intType) -> std::optional<Type> {
1742 if (
auto scalarType = dyn_cast<spirv::ScalarType>(intType))
1743 return convertScalarType(this->targetEnv, this->options, scalarType);
1744 if (intType.getWidth() < 8)
1745 return convertSubByteIntegerType(this->options, intType);
1749 addConversion([
this](FloatType floatType) -> std::optional<Type> {
1750 if (floatType.getWidth() == 8) {
1751 if (
auto scalarType = dyn_cast<spirv::ScalarType>(floatType);
1752 scalarType && isScalarTypeSupported(this->targetEnv, scalarType))
1754 return convert8BitFloatType(this->options, floatType);
1756 if (
auto scalarType = dyn_cast<spirv::ScalarType>(floatType))
1757 return convertScalarType(this->targetEnv, this->options, scalarType);
1761 addConversion([
this](ComplexType complexType) {
1762 return convertComplexType(this->targetEnv, this->options, complexType);
1765 addConversion([
this](VectorType vectorType) {
1766 return convertVectorType(this->targetEnv, this->options, vectorType);
1769 addConversion([
this](
TensorType tensorType) {
1770 return convertTensorType(this->targetEnv, this->options, tensorType);
1773 addConversion([
this](MemRefType memRefType) {
1774 return convertMemrefType(this->targetEnv, this->options, memRefType);
1778 addSourceMaterialization(
1780 return castToSourceType(this->targetEnv, builder, type, inputs, loc);
1784 auto cast = UnrealizedConversionCastOp::create(builder, loc, type, inputs);
1785 return cast.getResult(0);
1790 return ::getIndexType(
getContext(), options);
1793MLIRContext *SPIRVTypeConverter::getContext()
const {
1794 return targetEnv.
getAttr().getContext();
1798 return targetEnv.allows(capability);
1805std::unique_ptr<SPIRVConversionTarget>
1807 std::unique_ptr<SPIRVConversionTarget>
target(
1809 new SPIRVConversionTarget(targetAttr));
1810 SPIRVConversionTarget *targetPtr =
target.get();
1811 target->addDynamicallyLegalDialect<spirv::SPIRVDialect>(
1814 [targetPtr](
Operation *op) {
return targetPtr->isLegalOp(op); });
1821bool SPIRVConversionTarget::isLegalOp(
Operation *op) {
1825 if (
auto minVersionIfx = dyn_cast<spirv::QueryMinVersionInterface>(op)) {
1826 std::optional<spirv::Version> minVersion = minVersionIfx.getMinVersion();
1827 if (minVersion && *minVersion > this->targetEnv.
getVersion()) {
1828 LLVM_DEBUG(llvm::dbgs()
1829 << op->
getName() <<
" illegal: requiring min version "
1830 << spirv::stringifyVersion(*minVersion) <<
"\n");
1834 if (
auto maxVersionIfx = dyn_cast<spirv::QueryMaxVersionInterface>(op)) {
1835 std::optional<spirv::Version> maxVersion = maxVersionIfx.getMaxVersion();
1836 if (maxVersion && *maxVersion < this->targetEnv.getVersion()) {
1837 LLVM_DEBUG(llvm::dbgs()
1838 << op->
getName() <<
" illegal: requiring max version "
1839 << spirv::stringifyVersion(*maxVersion) <<
"\n");
1847 if (
auto extensions = dyn_cast<spirv::QueryExtensionInterface>(op))
1849 extensions.getExtensions())))
1855 if (
auto capabilities = dyn_cast<spirv::QueryCapabilityInterface>(op))
1857 capabilities.getCapabilities())))
1860 SmallVector<Type, 4> valueTypes;
1865 if (llvm::any_of(valueTypes,
1866 [](Type t) {
return !isa<spirv::SPIRVType>(t); }))
1871 if (
auto globalVar = dyn_cast<spirv::GlobalVariableOp>(op)) {
1872 valueTypes.push_back(globalVar.getType());
1875 if (std::optional<Type> dataType = globalVar.getDataType()) {
1876 auto spirvDataType = cast<spirv::SPIRVType>(*dataType);
1877 SmallVector<ArrayRef<spirv::Extension>, 4> exts;
1878 spirvDataType.getExtensions(exts, globalVar.storageClass());
1880 checkExtensionRequirements(op->
getName(),
this->targetEnv, exts)))
1882 SmallVector<ArrayRef<spirv::Capability>, 8> caps;
1883 spirvDataType.getCapabilities(caps, globalVar.storageClass());
1892 SmallVector<ArrayRef<spirv::Extension>, 4> typeExtensions;
1893 SmallVector<ArrayRef<spirv::Capability>, 8> typeCapabilities;
1894 for (Type valueType : valueTypes) {
1895 typeExtensions.clear();
1896 cast<spirv::SPIRVType>(valueType).getExtensions(typeExtensions);
1901 typeCapabilities.clear();
1902 cast<spirv::SPIRVType>(valueType).getCapabilities(typeCapabilities);
1917 patterns.
add<FuncOpConversion>(typeConverter, patterns.
getContext());
return MutableOperandRange * this
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be the output argument nBegin is set to its * replacement(set to `begin` if no invalidation happens). Since outgoing *copies could have been inserted at `end`
static llvm::ManagedStatic< PassManagerOptions > options
#define BIT_WIDTH_CASE(BIT_WIDTH)
static std::optional< SmallVector< int64_t > > getTargetShape(const vector::UnrollVectorOptions &options, VectorUnrollOpInterface &iface, bool allowMasked=false)
Return the target shape for unrolling for the given op, provided through its VectorUnrollOpInterface ...
Block represents an ordered list of Operations.
iterator_range< args_iterator > addArguments(TypeRange types, ArrayRef< Location > locs)
Add one argument to the argument list for each type specified in the list.
OpListType & getOperations()
void eraseArguments(unsigned start, unsigned num)
Erases 'num' arguments from the index 'start'.
auto getOps()
Return an iterator range over the operations within this block that are of 'OpT'.
This class is a general helper class for creating context-global objects like types,...
IntegerAttr getI32IntegerAttr(int32_t value)
TypedAttr getZeroAttr(Type type)
MLIRContext * getContext() const
This class allows control over how the GreedyPatternRewriteDriver works.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
NamedAttribute represents a combination of a name and an Attribute value.
Attribute getValue() const
Return the value of the attribute.
RAII guard to reset the insertion point of the builder when destroyed.
This class helps build Operations.
static OpBuilder atBlockBegin(Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to before the first operation in the block but still ins...
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
Operation is the basic unit of execution within MLIR.
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
void setOperand(unsigned idx, Value value)
void setDiscardableAttr(StringAttr name, Attribute value)
Set a discardable attribute by name.
operand_type_iterator operand_type_end()
Location getLoc()
The source location the operation was defined or derived from.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
result_type_iterator result_type_end()
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
result_type_iterator result_type_begin()
OperationName getName()
The name of an operation is the key identifier for it.
result_type_range getResultTypes()
MLIRContext * getContext()
Return the context this operation is associated with.
unsigned getNumResults()
Return the number of results held by this operation.
operand_type_iterator operand_type_begin()
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...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
void inlineRegionBefore(Region ®ion, Region &parent, Region::iterator before)
Move the blocks that belong to "region" before the given position in another region "parent".
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
static std::unique_ptr< SPIRVConversionTarget > get(spirv::TargetEnvAttr targetAttr)
Creates a SPIR-V conversion target for the given target environment.
Type conversion from builtin types to SPIR-V types for shader interface.
Type getIndexType() const
Gets the SPIR-V correspondence for the standard index type.
const spirv::TargetEnv & getTargetEnv() const
SPIRVTypeConverter(spirv::TargetEnvAttr targetAttr, const SPIRVConversionOptions &options={})
bool allows(spirv::Capability capability) const
Checks if the SPIR-V capability inquired is supported.
A range-style iterator that allows for iterating over the offsets of all potential tiles of size tile...
static Operation * getNearestSymbolTable(Operation *from)
Returns the nearest symbol table from a given operation from.
Tensor types represent multi-dimensional arrays, and have two variants: RankedTensorType and Unranked...
Type getElementType() const
Returns the element type of this tensor type.
This class provides an abstraction over the various different ranges of value types.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
bool isSignedInteger() const
Return true if this is a signed integer type (with the specified width).
bool isInteger() const
Return true if this is an integer type (with the specified width).
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
This class provides an abstraction over the different types of ranges over Values.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Type getElementType() const
unsigned getNumElements() const
static ArrayType get(Type elementType, unsigned elementCount)
static bool isValid(VectorType)
Returns true if the given vector type is valid for the SPIR-V dialect.
static ImageType get(Type elementType, Dim dim, ImageDepthInfo depth=ImageDepthInfo::DepthUnknown, ImageArrayedInfo arrayed=ImageArrayedInfo::NonArrayed, ImageSamplingInfo samplingInfo=ImageSamplingInfo::SingleSampled, ImageSamplerUseInfo samplerUse=ImageSamplerUseInfo::SamplerUnknown, ImageFormat format=ImageFormat::Unknown)
static PointerType get(Type pointeeType, StorageClass storageClass)
static RuntimeArrayType get(Type elementType)
SmallVectorImpl< ArrayRef< Capability > > CapabilityArrayRefVector
The capability requirements for each type are following the ((Capability::A OR Extension::B) AND (Cap...
SmallVectorImpl< ArrayRef< Extension > > ExtensionArrayRefVector
The extension requirements for each type are following the ((Extension::A OR Extension::B) AND (Exten...
static SampledImageType get(Type imageType)
static StructType get(ArrayRef< Type > memberTypes, ArrayRef< OffsetInfo > offsetInfo={}, ArrayRef< MemberDecorationInfo > memberDecorations={}, ArrayRef< StructDecorationInfo > structDecorations={})
Construct a literal StructType with at least one member.
An attribute that specifies the target version, allowed extensions and capabilities,...
A wrapper class around a spirv::TargetEnvAttr to provide query methods for allowed version/capabiliti...
Version getVersion() const
bool allows(Capability) const
Returns true if the given capability is allowed.
TargetEnvAttr getAttr() const
MLIRContext * getContext() const
Returns the MLIRContext.
bool hasElementwiseMappableTraits(Operation *op)
Together, Elementwise, Scalarizable, Vectorizable, and Tensorizable provide an easy way for scalar op...
Value getBuiltinVariableValue(Operation *op, BuiltIn builtin, Type integerType, OpBuilder &builder, StringRef prefix="__builtin__", StringRef suffix="__")
Returns the value for the given builtin variable.
Value getElementPtr(const SPIRVTypeConverter &typeConverter, MemRefType baseType, Value basePtr, ValueRange indices, Location loc, OpBuilder &builder)
Performs the index computation to get to the element at indices of the memory pointed to by basePtr,...
Value getOpenCLElementPtr(const SPIRVTypeConverter &typeConverter, MemRefType baseType, Value basePtr, ValueRange indices, Location loc, OpBuilder &builder)
Value getPushConstantValue(Operation *op, unsigned elementCount, unsigned offset, Type integerType, OpBuilder &builder)
Gets the value at the given offset of the push constant storage with a total of elementCount integerT...
std::optional< SmallVector< int64_t > > getNativeVectorShape(Operation *op)
LinearizedIndexNoWrapFlags getLinearizedIndexNoWrapFlags(const TargetEnv &targetEnv, ArrayRef< int64_t > shape, ArrayRef< int64_t > strides, int64_t offset, Type integerType)
Returns no-wrap guarantees for an in-bounds index into the static layout described by shape,...
bool containsMicroscalingType(Type type, bool subByteOnly=false)
Returns whether a type contains a microscaling element, including through composite types and pointer...
LogicalResult unrollVectorsInFuncBodies(Operation *op)
Value getVulkanElementPtr(const SPIRVTypeConverter &typeConverter, MemRefType baseType, Value basePtr, ValueRange indices, Location loc, OpBuilder &builder)
SmallVector< int64_t > getNativeVectorShapeImpl(vector::ReductionOp op)
std::string getDecorationString(Decoration decoration)
Converts a SPIR-V Decoration enum value to its snake_case string representation for use in MLIR attri...
int getComputeVectorSize(int64_t size)
LogicalResult unrollVectorsInSignatures(Operation *op)
Value linearizeIndex(ValueRange indices, ArrayRef< int64_t > strides, int64_t offset, Type integerType, Location loc, OpBuilder &builder, LinearizedIndexNoWrapFlags noWrapFlags={})
Generates IR to perform index linearization with the given indices and their corresponding strides,...
void populateVectorShapeCastLoweringPatterns(RewritePatternSet &patterns, PatternBenefit benefit=1)
Populate the pattern set with the following patterns:
void populateVectorTransposeLoweringPatterns(RewritePatternSet &patterns, VectorTransposeLowering vectorTransposeLowering, PatternBenefit benefit=1)
Populate the pattern set with the following patterns:
Include the generated interface declarations.
void populateFuncOpVectorRewritePatterns(RewritePatternSet &patterns)
void populateReturnOpVectorRewritePatterns(RewritePatternSet &patterns)
@ Packed
Sub-byte values are tightly packed without any padding, e.g., 4xi2 -> i8.
LogicalResult applyPatternsGreedily(Region ®ion, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr)
Rewrite ops in the given region, which must be isolated from above, by repeatedly applying the highes...
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
void populateBuiltinFuncToSPIRVPatterns(const SPIRVTypeConverter &typeConverter, RewritePatternSet &patterns)
Appends to a pattern list additional patterns for translating the builtin func op to the SPIR-V diale...
llvm::TypeSwitch< T, ResultT > TypeSwitch
@ ExistingOps
Only pre-existing ops are processed.
std::optional< SmallVector< int64_t > > computeShapeRatio(ArrayRef< int64_t > shape, ArrayRef< int64_t > subShape)
Return the multi-dimensional integral ratio of subShape to the trailing dimensions of shape.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
No-wrap guarantees proven for a linearized index calculation.
Options that control the vector unrolling.
UnrollVectorOptions & setNativeShapeFn(NativeShapeFnType fn)