101178654SLei Zhang //===- SPIRVConversion.cpp - SPIR-V Conversion Utilities ------------------===//
201178654SLei Zhang //
301178654SLei Zhang // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
401178654SLei Zhang // See https://llvm.org/LICENSE.txt for license information.
501178654SLei Zhang // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
601178654SLei Zhang //
701178654SLei Zhang //===----------------------------------------------------------------------===//
801178654SLei Zhang //
901178654SLei Zhang // This file implements utilities used to lower to SPIR-V dialect.
1001178654SLei Zhang //
1101178654SLei Zhang //===----------------------------------------------------------------------===//
1201178654SLei Zhang 
1301178654SLei Zhang #include "mlir/Dialect/SPIRV/Transforms/SPIRVConversion.h"
1436550692SRiver Riddle #include "mlir/Dialect/Func/IR/FuncOps.h"
1501178654SLei Zhang #include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h"
1601178654SLei Zhang #include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
177c3ae48fSLei Zhang #include "mlir/Transforms/DialectConversion.h"
1801178654SLei Zhang #include "llvm/ADT/Sequence.h"
1901178654SLei Zhang #include "llvm/ADT/StringExtras.h"
2001178654SLei Zhang #include "llvm/Support/Debug.h"
2101178654SLei Zhang 
2201178654SLei Zhang #include <functional>
2301178654SLei Zhang 
2401178654SLei Zhang #define DEBUG_TYPE "mlir-spirv-conversion"
2501178654SLei Zhang 
2601178654SLei Zhang using namespace mlir;
2701178654SLei Zhang 
2801178654SLei Zhang //===----------------------------------------------------------------------===//
2901178654SLei Zhang // Utility functions
3001178654SLei Zhang //===----------------------------------------------------------------------===//
3101178654SLei Zhang 
3201178654SLei Zhang /// Checks that `candidates` extension requirements are possible to be satisfied
3301178654SLei Zhang /// with the given `targetEnv`.
3401178654SLei Zhang ///
3501178654SLei Zhang ///  `candidates` is a vector of vector for extension requirements following
3601178654SLei Zhang /// ((Extension::A OR Extension::B) AND (Extension::C OR Extension::D))
3701178654SLei Zhang /// convention.
3801178654SLei Zhang template <typename LabelT>
3901178654SLei Zhang static LogicalResult checkExtensionRequirements(
4001178654SLei Zhang     LabelT label, const spirv::TargetEnv &targetEnv,
4101178654SLei Zhang     const spirv::SPIRVType::ExtensionArrayRefVector &candidates) {
4201178654SLei Zhang   for (const auto &ors : candidates) {
4301178654SLei Zhang     if (targetEnv.allows(ors))
4401178654SLei Zhang       continue;
4501178654SLei Zhang 
46fd91f81cSLei Zhang     LLVM_DEBUG({
47fd91f81cSLei Zhang       SmallVector<StringRef> extStrings;
4801178654SLei Zhang       for (spirv::Extension ext : ors)
4901178654SLei Zhang         extStrings.push_back(spirv::stringifyExtension(ext));
5001178654SLei Zhang 
51fd91f81cSLei Zhang       llvm::dbgs() << label << " illegal: requires at least one extension in ["
5201178654SLei Zhang                    << llvm::join(extStrings, ", ")
53fd91f81cSLei Zhang                    << "] but none allowed in target environment\n";
54fd91f81cSLei Zhang     });
5501178654SLei Zhang     return failure();
5601178654SLei Zhang   }
5701178654SLei Zhang   return success();
5801178654SLei Zhang }
5901178654SLei Zhang 
6001178654SLei Zhang /// Checks that `candidates`capability requirements are possible to be satisfied
6101178654SLei Zhang /// with the given `isAllowedFn`.
6201178654SLei Zhang ///
6301178654SLei Zhang ///  `candidates` is a vector of vector for capability requirements following
6401178654SLei Zhang /// ((Capability::A OR Capability::B) AND (Capability::C OR Capability::D))
6501178654SLei Zhang /// convention.
6601178654SLei Zhang template <typename LabelT>
6701178654SLei Zhang static LogicalResult checkCapabilityRequirements(
6801178654SLei Zhang     LabelT label, const spirv::TargetEnv &targetEnv,
6901178654SLei Zhang     const spirv::SPIRVType::CapabilityArrayRefVector &candidates) {
7001178654SLei Zhang   for (const auto &ors : candidates) {
7101178654SLei Zhang     if (targetEnv.allows(ors))
7201178654SLei Zhang       continue;
7301178654SLei Zhang 
74fd91f81cSLei Zhang     LLVM_DEBUG({
75fd91f81cSLei Zhang       SmallVector<StringRef> capStrings;
7601178654SLei Zhang       for (spirv::Capability cap : ors)
7701178654SLei Zhang         capStrings.push_back(spirv::stringifyCapability(cap));
7801178654SLei Zhang 
79fd91f81cSLei Zhang       llvm::dbgs() << label << " illegal: requires at least one capability in ["
8001178654SLei Zhang                    << llvm::join(capStrings, ", ")
81fd91f81cSLei Zhang                    << "] but none allowed in target environment\n";
82fd91f81cSLei Zhang     });
8301178654SLei Zhang     return failure();
8401178654SLei Zhang   }
8501178654SLei Zhang   return success();
8601178654SLei Zhang }
8701178654SLei Zhang 
885b15fe93SLei Zhang /// Returns true if the given `storageClass` needs explicit layout when used in
895b15fe93SLei Zhang /// Shader environments.
905b15fe93SLei Zhang static bool needsExplicitLayout(spirv::StorageClass storageClass) {
915b15fe93SLei Zhang   switch (storageClass) {
925b15fe93SLei Zhang   case spirv::StorageClass::PhysicalStorageBuffer:
935b15fe93SLei Zhang   case spirv::StorageClass::PushConstant:
945b15fe93SLei Zhang   case spirv::StorageClass::StorageBuffer:
955b15fe93SLei Zhang   case spirv::StorageClass::Uniform:
965b15fe93SLei Zhang     return true;
975b15fe93SLei Zhang   default:
985b15fe93SLei Zhang     return false;
995b15fe93SLei Zhang   }
1005b15fe93SLei Zhang }
1015b15fe93SLei Zhang 
1025b15fe93SLei Zhang /// Wraps the given `elementType` in a struct and gets the pointer to the
1035b15fe93SLei Zhang /// struct. This is used to satisfy Vulkan interface requirements.
1045b15fe93SLei Zhang static spirv::PointerType
1055b15fe93SLei Zhang wrapInStructAndGetPointer(Type elementType, spirv::StorageClass storageClass) {
1065b15fe93SLei Zhang   auto structType = needsExplicitLayout(storageClass)
1075b15fe93SLei Zhang                         ? spirv::StructType::get(elementType, /*offsetInfo=*/0)
1085b15fe93SLei Zhang                         : spirv::StructType::get(elementType);
1095b15fe93SLei Zhang   return spirv::PointerType::get(structType, storageClass);
1105b15fe93SLei Zhang }
1115b15fe93SLei Zhang 
11201178654SLei Zhang //===----------------------------------------------------------------------===//
11301178654SLei Zhang // Type Conversion
11401178654SLei Zhang //===----------------------------------------------------------------------===//
11501178654SLei Zhang 
1161e35a769SButygin Type SPIRVTypeConverter::getIndexType() const {
1171e35a769SButygin   return IntegerType::get(getContext(), options.use64bitIndex ? 64 : 32);
11801178654SLei Zhang }
11901178654SLei Zhang 
12001178654SLei Zhang /// Mapping between SPIR-V storage classes to memref memory spaces.
12101178654SLei Zhang ///
12201178654SLei Zhang /// Note: memref does not have a defined semantics for each memory space; it
12301178654SLei Zhang /// depends on the context where it is used. There are no particular reasons
12401178654SLei Zhang /// behind the number assignments; we try to follow NVVM conventions and largely
12501178654SLei Zhang /// give common storage classes a smaller number. The hope is use symbolic
12601178654SLei Zhang /// memory space representation eventually after memref supports it.
12701178654SLei Zhang // TODO: swap Generic and StorageBuffer assignment to be more akin
12801178654SLei Zhang // to NVVM.
12901178654SLei Zhang #define STORAGE_SPACE_MAP_LIST(MAP_FN)                                         \
13001178654SLei Zhang   MAP_FN(spirv::StorageClass::Generic, 1)                                      \
13101178654SLei Zhang   MAP_FN(spirv::StorageClass::StorageBuffer, 0)                                \
13201178654SLei Zhang   MAP_FN(spirv::StorageClass::Workgroup, 3)                                    \
13301178654SLei Zhang   MAP_FN(spirv::StorageClass::Uniform, 4)                                      \
13401178654SLei Zhang   MAP_FN(spirv::StorageClass::Private, 5)                                      \
13501178654SLei Zhang   MAP_FN(spirv::StorageClass::Function, 6)                                     \
13601178654SLei Zhang   MAP_FN(spirv::StorageClass::PushConstant, 7)                                 \
13701178654SLei Zhang   MAP_FN(spirv::StorageClass::UniformConstant, 8)                              \
13801178654SLei Zhang   MAP_FN(spirv::StorageClass::Input, 9)                                        \
13901178654SLei Zhang   MAP_FN(spirv::StorageClass::Output, 10)                                      \
14001178654SLei Zhang   MAP_FN(spirv::StorageClass::CrossWorkgroup, 11)                              \
14101178654SLei Zhang   MAP_FN(spirv::StorageClass::AtomicCounter, 12)                               \
14201178654SLei Zhang   MAP_FN(spirv::StorageClass::Image, 13)                                       \
14392fc60bcSButygin   MAP_FN(spirv::StorageClass::CallableDataKHR, 14)                             \
14492fc60bcSButygin   MAP_FN(spirv::StorageClass::IncomingCallableDataKHR, 15)                     \
14592fc60bcSButygin   MAP_FN(spirv::StorageClass::RayPayloadKHR, 16)                               \
14692fc60bcSButygin   MAP_FN(spirv::StorageClass::HitAttributeKHR, 17)                             \
14792fc60bcSButygin   MAP_FN(spirv::StorageClass::IncomingRayPayloadKHR, 18)                       \
14892fc60bcSButygin   MAP_FN(spirv::StorageClass::ShaderRecordBufferKHR, 19)                       \
14992fc60bcSButygin   MAP_FN(spirv::StorageClass::PhysicalStorageBuffer, 20)                       \
15092fc60bcSButygin   MAP_FN(spirv::StorageClass::CodeSectionINTEL, 21)                            \
15192fc60bcSButygin   MAP_FN(spirv::StorageClass::DeviceOnlyINTEL, 22)                             \
15292fc60bcSButygin   MAP_FN(spirv::StorageClass::HostOnlyINTEL, 23)
15301178654SLei Zhang 
15401178654SLei Zhang unsigned
15501178654SLei Zhang SPIRVTypeConverter::getMemorySpaceForStorageClass(spirv::StorageClass storage) {
15601178654SLei Zhang #define STORAGE_SPACE_MAP_FN(storage, space)                                   \
15701178654SLei Zhang   case storage:                                                                \
15801178654SLei Zhang     return space;
15901178654SLei Zhang 
16001178654SLei Zhang   switch (storage) { STORAGE_SPACE_MAP_LIST(STORAGE_SPACE_MAP_FN) }
16101178654SLei Zhang #undef STORAGE_SPACE_MAP_FN
16201178654SLei Zhang   llvm_unreachable("unhandled storage class!");
16301178654SLei Zhang }
16401178654SLei Zhang 
16501178654SLei Zhang Optional<spirv::StorageClass>
16601178654SLei Zhang SPIRVTypeConverter::getStorageClassForMemorySpace(unsigned space) {
16701178654SLei Zhang #define STORAGE_SPACE_MAP_FN(storage, space)                                   \
16801178654SLei Zhang   case space:                                                                  \
16901178654SLei Zhang     return storage;
17001178654SLei Zhang 
17101178654SLei Zhang   switch (space) {
17201178654SLei Zhang     STORAGE_SPACE_MAP_LIST(STORAGE_SPACE_MAP_FN)
17301178654SLei Zhang   default:
17401178654SLei Zhang     return llvm::None;
17501178654SLei Zhang   }
17601178654SLei Zhang #undef STORAGE_SPACE_MAP_FN
17701178654SLei Zhang }
17801178654SLei Zhang 
179c3614358SHanhan Wang const SPIRVTypeConverter::Options &SPIRVTypeConverter::getOptions() const {
180c3614358SHanhan Wang   return options;
181c3614358SHanhan Wang }
182c3614358SHanhan Wang 
1831e35a769SButygin MLIRContext *SPIRVTypeConverter::getContext() const {
1841e35a769SButygin   return targetEnv.getAttr().getContext();
1851e35a769SButygin }
1861e35a769SButygin 
18701178654SLei Zhang #undef STORAGE_SPACE_MAP_LIST
18801178654SLei Zhang 
1895299843cSLei Zhang // TODO: This is a utility function that should probably be exposed by the
1905299843cSLei Zhang // SPIR-V dialect. Keeping it local till the use case arises.
1915299843cSLei Zhang static Optional<int64_t>
1925299843cSLei Zhang getTypeNumBytes(const SPIRVTypeConverter::Options &options, Type type) {
1935299843cSLei Zhang   if (type.isa<spirv::ScalarType>()) {
1945299843cSLei Zhang     auto bitWidth = type.getIntOrFloatBitWidth();
19501178654SLei Zhang     // According to the SPIR-V spec:
19601178654SLei Zhang     // "There is no physical size or bit pattern defined for values with boolean
19701178654SLei Zhang     // type. If they are stored (in conjunction with OpVariable), they can only
19801178654SLei Zhang     // be used with logical addressing operations, not physical, and only with
19901178654SLei Zhang     // non-externally visible shader Storage Classes: Workgroup, CrossWorkgroup,
20001178654SLei Zhang     // Private, Function, Input, and Output."
2015299843cSLei Zhang     if (bitWidth == 1)
20201178654SLei Zhang       return llvm::None;
20301178654SLei Zhang     return bitWidth / 8;
20401178654SLei Zhang   }
2056dd07fa5SLei Zhang 
2065299843cSLei Zhang   if (auto vecType = type.dyn_cast<VectorType>()) {
2075299843cSLei Zhang     auto elementSize = getTypeNumBytes(options, vecType.getElementType());
20801178654SLei Zhang     if (!elementSize)
20901178654SLei Zhang       return llvm::None;
2105299843cSLei Zhang     return vecType.getNumElements() * elementSize.getValue();
21101178654SLei Zhang   }
2126dd07fa5SLei Zhang 
2135299843cSLei Zhang   if (auto memRefType = type.dyn_cast<MemRefType>()) {
21401178654SLei Zhang     // TODO: Layout should also be controlled by the ABI attributes. For now
21501178654SLei Zhang     // using the layout from MemRef.
21601178654SLei Zhang     int64_t offset;
21701178654SLei Zhang     SmallVector<int64_t, 4> strides;
21801178654SLei Zhang     if (!memRefType.hasStaticShape() ||
2195299843cSLei Zhang         failed(getStridesAndOffset(memRefType, strides, offset)))
22001178654SLei Zhang       return llvm::None;
2215299843cSLei Zhang 
22201178654SLei Zhang     // To get the size of the memref object in memory, the total size is the
22301178654SLei Zhang     // max(stride * dimension-size) computed for all dimensions times the size
22401178654SLei Zhang     // of the element.
2255299843cSLei Zhang     auto elementSize = getTypeNumBytes(options, memRefType.getElementType());
2265299843cSLei Zhang     if (!elementSize)
22701178654SLei Zhang       return llvm::None;
2285299843cSLei Zhang 
2295299843cSLei Zhang     if (memRefType.getRank() == 0)
23001178654SLei Zhang       return elementSize;
2315299843cSLei Zhang 
23201178654SLei Zhang     auto dims = memRefType.getShape();
23301178654SLei Zhang     if (llvm::is_contained(dims, ShapedType::kDynamicSize) ||
23401178654SLei Zhang         offset == MemRefType::getDynamicStrideOrOffset() ||
2355299843cSLei Zhang         llvm::is_contained(strides, MemRefType::getDynamicStrideOrOffset()))
23601178654SLei Zhang       return llvm::None;
2375299843cSLei Zhang 
23801178654SLei Zhang     int64_t memrefSize = -1;
239e4853be2SMehdi Amini     for (const auto &shape : enumerate(dims))
24001178654SLei Zhang       memrefSize = std::max(memrefSize, shape.value() * strides[shape.index()]);
2415299843cSLei Zhang 
24201178654SLei Zhang     return (offset + memrefSize) * elementSize.getValue();
2436dd07fa5SLei Zhang   }
2446dd07fa5SLei Zhang 
2455299843cSLei Zhang   if (auto tensorType = type.dyn_cast<TensorType>()) {
2465299843cSLei Zhang     if (!tensorType.hasStaticShape())
24701178654SLei Zhang       return llvm::None;
2485299843cSLei Zhang 
2495299843cSLei Zhang     auto elementSize = getTypeNumBytes(options, tensorType.getElementType());
2505299843cSLei Zhang     if (!elementSize)
25101178654SLei Zhang       return llvm::None;
2525299843cSLei Zhang 
25301178654SLei Zhang     int64_t size = elementSize.getValue();
2545299843cSLei Zhang     for (auto shape : tensorType.getShape())
25501178654SLei Zhang       size *= shape;
2565299843cSLei Zhang 
25701178654SLei Zhang     return size;
25801178654SLei Zhang   }
2596dd07fa5SLei Zhang 
26001178654SLei Zhang   // TODO: Add size computation for other types.
26101178654SLei Zhang   return llvm::None;
26201178654SLei Zhang }
26301178654SLei Zhang 
26401178654SLei Zhang /// Converts a scalar `type` to a suitable type under the given `targetEnv`.
265004f29c0SLei Zhang static Type convertScalarType(const spirv::TargetEnv &targetEnv,
2665299843cSLei Zhang                               const SPIRVTypeConverter::Options &options,
267004f29c0SLei Zhang                               spirv::ScalarType type,
26801178654SLei Zhang                               Optional<spirv::StorageClass> storageClass = {}) {
26901178654SLei Zhang   // Get extension and capability requirements for the given type.
27001178654SLei Zhang   SmallVector<ArrayRef<spirv::Extension>, 1> extensions;
27101178654SLei Zhang   SmallVector<ArrayRef<spirv::Capability>, 2> capabilities;
27201178654SLei Zhang   type.getExtensions(extensions, storageClass);
27301178654SLei Zhang   type.getCapabilities(capabilities, storageClass);
27401178654SLei Zhang 
27501178654SLei Zhang   // If all requirements are met, then we can accept this type as-is.
27601178654SLei Zhang   if (succeeded(checkCapabilityRequirements(type, targetEnv, capabilities)) &&
27701178654SLei Zhang       succeeded(checkExtensionRequirements(type, targetEnv, extensions)))
27801178654SLei Zhang     return type;
27901178654SLei Zhang 
28001178654SLei Zhang   // Otherwise we need to adjust the type, which really means adjusting the
28101178654SLei Zhang   // bitwidth given this is a scalar type.
2825299843cSLei Zhang 
2835299843cSLei Zhang   if (!options.emulateNon32BitScalarTypes)
2845299843cSLei Zhang     return nullptr;
28501178654SLei Zhang 
28601178654SLei Zhang   if (auto floatType = type.dyn_cast<FloatType>()) {
28701178654SLei Zhang     LLVM_DEBUG(llvm::dbgs() << type << " converted to 32-bit for SPIR-V\n");
28801178654SLei Zhang     return Builder(targetEnv.getContext()).getF32Type();
28901178654SLei Zhang   }
29001178654SLei Zhang 
29101178654SLei Zhang   auto intType = type.cast<IntegerType>();
29201178654SLei Zhang   LLVM_DEBUG(llvm::dbgs() << type << " converted to 32-bit for SPIR-V\n");
2931b97cdf8SRiver Riddle   return IntegerType::get(targetEnv.getContext(), /*width=*/32,
2941b97cdf8SRiver Riddle                           intType.getSignedness());
29501178654SLei Zhang }
29601178654SLei Zhang 
29701178654SLei Zhang /// Converts a vector `type` to a suitable type under the given `targetEnv`.
298004f29c0SLei Zhang static Type convertVectorType(const spirv::TargetEnv &targetEnv,
2995299843cSLei Zhang                               const SPIRVTypeConverter::Options &options,
300004f29c0SLei Zhang                               VectorType type,
30101178654SLei Zhang                               Optional<spirv::StorageClass> storageClass = {}) {
3029f622b3dSLei Zhang   if (type.getRank() == 1 && type.getNumElements() == 1)
3039f622b3dSLei Zhang     return type.getElementType();
3049f622b3dSLei Zhang 
30501178654SLei Zhang   if (!spirv::CompositeType::isValid(type)) {
3069f622b3dSLei Zhang     // TODO: Vector types with more than four elements can be translated into
30701178654SLei Zhang     // array types.
3089f622b3dSLei Zhang     LLVM_DEBUG(llvm::dbgs() << type << " illegal: > 4-element unimplemented\n");
309004f29c0SLei Zhang     return nullptr;
31001178654SLei Zhang   }
31101178654SLei Zhang 
31201178654SLei Zhang   // Get extension and capability requirements for the given type.
31301178654SLei Zhang   SmallVector<ArrayRef<spirv::Extension>, 1> extensions;
31401178654SLei Zhang   SmallVector<ArrayRef<spirv::Capability>, 2> capabilities;
31501178654SLei Zhang   type.cast<spirv::CompositeType>().getExtensions(extensions, storageClass);
31601178654SLei Zhang   type.cast<spirv::CompositeType>().getCapabilities(capabilities, storageClass);
31701178654SLei Zhang 
31801178654SLei Zhang   // If all requirements are met, then we can accept this type as-is.
31901178654SLei Zhang   if (succeeded(checkCapabilityRequirements(type, targetEnv, capabilities)) &&
32001178654SLei Zhang       succeeded(checkExtensionRequirements(type, targetEnv, extensions)))
32101178654SLei Zhang     return type;
32201178654SLei Zhang 
32301178654SLei Zhang   auto elementType = convertScalarType(
3245299843cSLei Zhang       targetEnv, options, type.getElementType().cast<spirv::ScalarType>(),
3255299843cSLei Zhang       storageClass);
32601178654SLei Zhang   if (elementType)
327004f29c0SLei Zhang     return VectorType::get(type.getShape(), elementType);
328004f29c0SLei Zhang   return nullptr;
32901178654SLei Zhang }
33001178654SLei Zhang 
33101178654SLei Zhang /// Converts a tensor `type` to a suitable type under the given `targetEnv`.
33201178654SLei Zhang ///
33301178654SLei Zhang /// Note that this is mainly for lowering constant tensors. In SPIR-V one can
33401178654SLei Zhang /// create composite constants with OpConstantComposite to embed relative large
33501178654SLei Zhang /// constant values and use OpCompositeExtract and OpCompositeInsert to
33601178654SLei Zhang /// manipulate, like what we do for vectors.
337004f29c0SLei Zhang static Type convertTensorType(const spirv::TargetEnv &targetEnv,
3385299843cSLei Zhang                               const SPIRVTypeConverter::Options &options,
33901178654SLei Zhang                               TensorType type) {
34001178654SLei Zhang   // TODO: Handle dynamic shapes.
34101178654SLei Zhang   if (!type.hasStaticShape()) {
34201178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
34301178654SLei Zhang                << type << " illegal: dynamic shape unimplemented\n");
344004f29c0SLei Zhang     return nullptr;
34501178654SLei Zhang   }
34601178654SLei Zhang 
34701178654SLei Zhang   auto scalarType = type.getElementType().dyn_cast<spirv::ScalarType>();
34801178654SLei Zhang   if (!scalarType) {
34901178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
35001178654SLei Zhang                << type << " illegal: cannot convert non-scalar element type\n");
351004f29c0SLei Zhang     return nullptr;
35201178654SLei Zhang   }
35301178654SLei Zhang 
3545299843cSLei Zhang   Optional<int64_t> scalarSize = getTypeNumBytes(options, scalarType);
3555299843cSLei Zhang   Optional<int64_t> tensorSize = getTypeNumBytes(options, type);
35601178654SLei Zhang   if (!scalarSize || !tensorSize) {
35701178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
35801178654SLei Zhang                << type << " illegal: cannot deduce element count\n");
359004f29c0SLei Zhang     return nullptr;
36001178654SLei Zhang   }
36101178654SLei Zhang 
36201178654SLei Zhang   auto arrayElemCount = *tensorSize / *scalarSize;
3635299843cSLei Zhang   auto arrayElemType = convertScalarType(targetEnv, options, scalarType);
36401178654SLei Zhang   if (!arrayElemType)
365004f29c0SLei Zhang     return nullptr;
3665299843cSLei Zhang   Optional<int64_t> arrayElemSize = getTypeNumBytes(options, arrayElemType);
36701178654SLei Zhang   if (!arrayElemSize) {
36801178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
36901178654SLei Zhang                << type << " illegal: cannot deduce converted element size\n");
370004f29c0SLei Zhang     return nullptr;
37101178654SLei Zhang   }
37201178654SLei Zhang 
373bbffece3SLei Zhang   return spirv::ArrayType::get(arrayElemType, arrayElemCount);
37401178654SLei Zhang }
37501178654SLei Zhang 
376c3614358SHanhan Wang static Type convertBoolMemrefType(const spirv::TargetEnv &targetEnv,
377c3614358SHanhan Wang                                   const SPIRVTypeConverter::Options &options,
378c3614358SHanhan Wang                                   MemRefType type) {
379c3614358SHanhan Wang   Optional<spirv::StorageClass> storageClass =
380c3614358SHanhan Wang       SPIRVTypeConverter::getStorageClassForMemorySpace(
381c3614358SHanhan Wang           type.getMemorySpaceAsInt());
382c3614358SHanhan Wang   if (!storageClass) {
383c3614358SHanhan Wang     LLVM_DEBUG(llvm::dbgs()
384c3614358SHanhan Wang                << type << " illegal: cannot convert memory space\n");
385c3614358SHanhan Wang     return nullptr;
386c3614358SHanhan Wang   }
387c3614358SHanhan Wang 
388c3614358SHanhan Wang   unsigned numBoolBits = options.boolNumBits;
389c3614358SHanhan Wang   if (numBoolBits != 8) {
390c3614358SHanhan Wang     LLVM_DEBUG(llvm::dbgs()
391c3614358SHanhan Wang                << "using non-8-bit storage for bool types unimplemented");
392c3614358SHanhan Wang     return nullptr;
393c3614358SHanhan Wang   }
394c3614358SHanhan Wang   auto elementType = IntegerType::get(type.getContext(), numBoolBits)
395c3614358SHanhan Wang                          .dyn_cast<spirv::ScalarType>();
396c3614358SHanhan Wang   if (!elementType)
397c3614358SHanhan Wang     return nullptr;
398c3614358SHanhan Wang   Type arrayElemType =
399c3614358SHanhan Wang       convertScalarType(targetEnv, options, elementType, storageClass);
400c3614358SHanhan Wang   if (!arrayElemType)
401c3614358SHanhan Wang     return nullptr;
402c3614358SHanhan Wang   Optional<int64_t> arrayElemSize = getTypeNumBytes(options, arrayElemType);
403c3614358SHanhan Wang   if (!arrayElemSize) {
404c3614358SHanhan Wang     LLVM_DEBUG(llvm::dbgs()
405c3614358SHanhan Wang                << type << " illegal: cannot deduce converted element size\n");
406c3614358SHanhan Wang     return nullptr;
407c3614358SHanhan Wang   }
408c3614358SHanhan Wang 
4097c4de2e9SHanhan Wang   if (!type.hasStaticShape()) {
410bbffece3SLei Zhang     int64_t stride = needsExplicitLayout(*storageClass) ? *arrayElemSize : 0;
411bbffece3SLei Zhang     auto arrayType = spirv::RuntimeArrayType::get(arrayElemType, stride);
4127c4de2e9SHanhan Wang     return wrapInStructAndGetPointer(arrayType, *storageClass);
4137c4de2e9SHanhan Wang   }
4147c4de2e9SHanhan Wang 
415c3614358SHanhan Wang   int64_t memrefSize = (type.getNumElements() * numBoolBits + 7) / 8;
416*e0ea1fc6SLei Zhang   auto arrayElemCount = llvm::divideCeil(memrefSize, *arrayElemSize);
417bbffece3SLei Zhang   int64_t stride = needsExplicitLayout(*storageClass) ? *arrayElemSize : 0;
418bbffece3SLei Zhang   auto arrayType = spirv::ArrayType::get(arrayElemType, arrayElemCount, stride);
419c3614358SHanhan Wang 
4205b15fe93SLei Zhang   return wrapInStructAndGetPointer(arrayType, *storageClass);
421c3614358SHanhan Wang }
422c3614358SHanhan Wang 
423004f29c0SLei Zhang static Type convertMemrefType(const spirv::TargetEnv &targetEnv,
4245299843cSLei Zhang                               const SPIRVTypeConverter::Options &options,
42501178654SLei Zhang                               MemRefType type) {
426c3614358SHanhan Wang   if (type.getElementType().isa<IntegerType>() &&
427c3614358SHanhan Wang       type.getElementTypeBitWidth() == 1) {
428c3614358SHanhan Wang     return convertBoolMemrefType(targetEnv, options, type);
429c3614358SHanhan Wang   }
430c3614358SHanhan Wang 
43101178654SLei Zhang   Optional<spirv::StorageClass> storageClass =
43237eca08eSVladislav Vinogradov       SPIRVTypeConverter::getStorageClassForMemorySpace(
43337eca08eSVladislav Vinogradov           type.getMemorySpaceAsInt());
43401178654SLei Zhang   if (!storageClass) {
43501178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
43601178654SLei Zhang                << type << " illegal: cannot convert memory space\n");
437004f29c0SLei Zhang     return nullptr;
43801178654SLei Zhang   }
43901178654SLei Zhang 
440004f29c0SLei Zhang   Type arrayElemType;
44101178654SLei Zhang   Type elementType = type.getElementType();
44201178654SLei Zhang   if (auto vecType = elementType.dyn_cast<VectorType>()) {
4435299843cSLei Zhang     arrayElemType =
4445299843cSLei Zhang         convertVectorType(targetEnv, options, vecType, storageClass);
44501178654SLei Zhang   } else if (auto scalarType = elementType.dyn_cast<spirv::ScalarType>()) {
4465299843cSLei Zhang     arrayElemType =
4475299843cSLei Zhang         convertScalarType(targetEnv, options, scalarType, storageClass);
44801178654SLei Zhang   } else {
44901178654SLei Zhang     LLVM_DEBUG(
45001178654SLei Zhang         llvm::dbgs()
45101178654SLei Zhang         << type
45201178654SLei Zhang         << " unhandled: can only convert scalar or vector element type\n");
453004f29c0SLei Zhang     return nullptr;
45401178654SLei Zhang   }
45501178654SLei Zhang   if (!arrayElemType)
456004f29c0SLei Zhang     return nullptr;
45701178654SLei Zhang 
45823b8264bSLei Zhang   Optional<int64_t> arrayElemSize = getTypeNumBytes(options, arrayElemType);
45923b8264bSLei Zhang   if (!arrayElemSize) {
46023b8264bSLei Zhang     LLVM_DEBUG(llvm::dbgs()
46123b8264bSLei Zhang                << type << " illegal: cannot deduce converted element size\n");
46223b8264bSLei Zhang     return nullptr;
46323b8264bSLei Zhang   }
46423b8264bSLei Zhang 
46501178654SLei Zhang   if (!type.hasStaticShape()) {
466bbffece3SLei Zhang     int64_t stride = needsExplicitLayout(*storageClass) ? *arrayElemSize : 0;
467bbffece3SLei Zhang     auto arrayType = spirv::RuntimeArrayType::get(arrayElemType, stride);
4685b15fe93SLei Zhang     return wrapInStructAndGetPointer(arrayType, *storageClass);
46901178654SLei Zhang   }
47001178654SLei Zhang 
4715299843cSLei Zhang   Optional<int64_t> memrefSize = getTypeNumBytes(options, type);
47201178654SLei Zhang   if (!memrefSize) {
47301178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
47401178654SLei Zhang                << type << " illegal: cannot deduce element count\n");
475004f29c0SLei Zhang     return nullptr;
47601178654SLei Zhang   }
47701178654SLei Zhang 
478*e0ea1fc6SLei Zhang   auto arrayElemCount = llvm::divideCeil(*memrefSize, *arrayElemSize);
479bbffece3SLei Zhang   int64_t stride = needsExplicitLayout(*storageClass) ? *arrayElemSize : 0;
480bbffece3SLei Zhang   auto arrayType = spirv::ArrayType::get(arrayElemType, arrayElemCount, stride);
48101178654SLei Zhang 
4825b15fe93SLei Zhang   return wrapInStructAndGetPointer(arrayType, *storageClass);
48301178654SLei Zhang }
48401178654SLei Zhang 
4855299843cSLei Zhang SPIRVTypeConverter::SPIRVTypeConverter(spirv::TargetEnvAttr targetAttr,
4865299843cSLei Zhang                                        Options options)
4875299843cSLei Zhang     : targetEnv(targetAttr), options(options) {
48801178654SLei Zhang   // Add conversions. The order matters here: later ones will be tried earlier.
48901178654SLei Zhang 
49001178654SLei Zhang   // Allow all SPIR-V dialect specific types. This assumes all builtin types
49101178654SLei Zhang   // adopted in the SPIR-V dialect (i.e., IntegerType, FloatType, VectorType)
49201178654SLei Zhang   // were tried before.
49301178654SLei Zhang   //
49401178654SLei Zhang   // TODO: this assumes that the SPIR-V types are valid to use in
49501178654SLei Zhang   // the given target environment, which should be the case if the whole
49601178654SLei Zhang   // pipeline is driven by the same target environment. Still, we probably still
49701178654SLei Zhang   // want to validate and convert to be safe.
49801178654SLei Zhang   addConversion([](spirv::SPIRVType type) { return type; });
49901178654SLei Zhang 
5001e35a769SButygin   addConversion([this](IndexType /*indexType*/) { return getIndexType(); });
50101178654SLei Zhang 
50201178654SLei Zhang   addConversion([this](IntegerType intType) -> Optional<Type> {
50301178654SLei Zhang     if (auto scalarType = intType.dyn_cast<spirv::ScalarType>())
5045299843cSLei Zhang       return convertScalarType(this->targetEnv, this->options, scalarType);
505004f29c0SLei Zhang     return Type();
50601178654SLei Zhang   });
50701178654SLei Zhang 
50801178654SLei Zhang   addConversion([this](FloatType floatType) -> Optional<Type> {
50901178654SLei Zhang     if (auto scalarType = floatType.dyn_cast<spirv::ScalarType>())
5105299843cSLei Zhang       return convertScalarType(this->targetEnv, this->options, scalarType);
511004f29c0SLei Zhang     return Type();
51201178654SLei Zhang   });
51301178654SLei Zhang 
51401178654SLei Zhang   addConversion([this](VectorType vectorType) {
5155299843cSLei Zhang     return convertVectorType(this->targetEnv, this->options, vectorType);
51601178654SLei Zhang   });
51701178654SLei Zhang 
51801178654SLei Zhang   addConversion([this](TensorType tensorType) {
5195299843cSLei Zhang     return convertTensorType(this->targetEnv, this->options, tensorType);
52001178654SLei Zhang   });
52101178654SLei Zhang 
52201178654SLei Zhang   addConversion([this](MemRefType memRefType) {
5235299843cSLei Zhang     return convertMemrefType(this->targetEnv, this->options, memRefType);
52401178654SLei Zhang   });
52501178654SLei Zhang }
52601178654SLei Zhang 
52701178654SLei Zhang //===----------------------------------------------------------------------===//
52858ceae95SRiver Riddle // func::FuncOp Conversion Patterns
52901178654SLei Zhang //===----------------------------------------------------------------------===//
53001178654SLei Zhang 
53101178654SLei Zhang namespace {
53201178654SLei Zhang /// A pattern for rewriting function signature to convert arguments of functions
53301178654SLei Zhang /// to be of valid SPIR-V types.
53458ceae95SRiver Riddle class FuncOpConversion final : public OpConversionPattern<func::FuncOp> {
53501178654SLei Zhang public:
53658ceae95SRiver Riddle   using OpConversionPattern<func::FuncOp>::OpConversionPattern;
53701178654SLei Zhang 
53801178654SLei Zhang   LogicalResult
53958ceae95SRiver Riddle   matchAndRewrite(func::FuncOp funcOp, OpAdaptor adaptor,
54001178654SLei Zhang                   ConversionPatternRewriter &rewriter) const override;
54101178654SLei Zhang };
54201178654SLei Zhang } // namespace
54301178654SLei Zhang 
54401178654SLei Zhang LogicalResult
54558ceae95SRiver Riddle FuncOpConversion::matchAndRewrite(func::FuncOp funcOp, OpAdaptor adaptor,
54601178654SLei Zhang                                   ConversionPatternRewriter &rewriter) const {
5474a3460a7SRiver Riddle   auto fnType = funcOp.getFunctionType();
54842980a78SLei Zhang   if (fnType.getNumResults() > 1)
54901178654SLei Zhang     return failure();
55001178654SLei Zhang 
55101178654SLei Zhang   TypeConverter::SignatureConversion signatureConverter(fnType.getNumInputs());
552e4853be2SMehdi Amini   for (const auto &argType : enumerate(fnType.getInputs())) {
5537c3ae48fSLei Zhang     auto convertedType = getTypeConverter()->convertType(argType.value());
55401178654SLei Zhang     if (!convertedType)
55501178654SLei Zhang       return failure();
55601178654SLei Zhang     signatureConverter.addInputs(argType.index(), convertedType);
55701178654SLei Zhang   }
55801178654SLei Zhang 
55942980a78SLei Zhang   Type resultType;
5605299843cSLei Zhang   if (fnType.getNumResults() == 1) {
5617c3ae48fSLei Zhang     resultType = getTypeConverter()->convertType(fnType.getResult(0));
5625299843cSLei Zhang     if (!resultType)
5635299843cSLei Zhang       return failure();
5645299843cSLei Zhang   }
56542980a78SLei Zhang 
56601178654SLei Zhang   // Create the converted spv.func op.
56701178654SLei Zhang   auto newFuncOp = rewriter.create<spirv::FuncOp>(
56801178654SLei Zhang       funcOp.getLoc(), funcOp.getName(),
56901178654SLei Zhang       rewriter.getFunctionType(signatureConverter.getConvertedTypes(),
57042980a78SLei Zhang                                resultType ? TypeRange(resultType)
57142980a78SLei Zhang                                           : TypeRange()));
57201178654SLei Zhang 
57301178654SLei Zhang   // Copy over all attributes other than the function name and type.
57456774bddSMarius Brehler   for (const auto &namedAttr : funcOp->getAttrs()) {
5757ceffae1SRiver Riddle     if (namedAttr.getName() != FunctionOpInterface::getTypeAttrName() &&
5760c7890c8SRiver Riddle         namedAttr.getName() != SymbolTable::getSymbolAttrName())
5770c7890c8SRiver Riddle       newFuncOp->setAttr(namedAttr.getName(), namedAttr.getValue());
57801178654SLei Zhang   }
57901178654SLei Zhang 
58001178654SLei Zhang   rewriter.inlineRegionBefore(funcOp.getBody(), newFuncOp.getBody(),
58101178654SLei Zhang                               newFuncOp.end());
5827c3ae48fSLei Zhang   if (failed(rewriter.convertRegionTypes(
5837c3ae48fSLei Zhang           &newFuncOp.getBody(), *getTypeConverter(), &signatureConverter)))
58401178654SLei Zhang     return failure();
58501178654SLei Zhang   rewriter.eraseOp(funcOp);
58601178654SLei Zhang   return success();
58701178654SLei Zhang }
58801178654SLei Zhang 
589dc4e913bSChris Lattner void mlir::populateBuiltinFuncToSPIRVPatterns(SPIRVTypeConverter &typeConverter,
590dc4e913bSChris Lattner                                               RewritePatternSet &patterns) {
591dc4e913bSChris Lattner   patterns.add<FuncOpConversion>(typeConverter, patterns.getContext());
59201178654SLei Zhang }
59301178654SLei Zhang 
59401178654SLei Zhang //===----------------------------------------------------------------------===//
59501178654SLei Zhang // Builtin Variables
59601178654SLei Zhang //===----------------------------------------------------------------------===//
59701178654SLei Zhang 
59801178654SLei Zhang static spirv::GlobalVariableOp getBuiltinVariable(Block &body,
59901178654SLei Zhang                                                   spirv::BuiltIn builtin) {
60001178654SLei Zhang   // Look through all global variables in the given `body` block and check if
601c74eb466SKareemErgawy-TomTom   // there is a spv.GlobalVariable that has the same `builtin` attribute.
60201178654SLei Zhang   for (auto varOp : body.getOps<spirv::GlobalVariableOp>()) {
60301178654SLei Zhang     if (auto builtinAttr = varOp->getAttrOfType<StringAttr>(
60401178654SLei Zhang             spirv::SPIRVDialect::getAttributeName(
60501178654SLei Zhang                 spirv::Decoration::BuiltIn))) {
60601178654SLei Zhang       auto varBuiltIn = spirv::symbolizeBuiltIn(builtinAttr.getValue());
60701178654SLei Zhang       if (varBuiltIn && varBuiltIn.getValue() == builtin) {
60801178654SLei Zhang         return varOp;
60901178654SLei Zhang       }
61001178654SLei Zhang     }
61101178654SLei Zhang   }
61201178654SLei Zhang   return nullptr;
61301178654SLei Zhang }
61401178654SLei Zhang 
61501178654SLei Zhang /// Gets name of global variable for a builtin.
61601178654SLei Zhang static std::string getBuiltinVarName(spirv::BuiltIn builtin) {
61701178654SLei Zhang   return std::string("__builtin_var_") + stringifyBuiltIn(builtin).str() + "__";
61801178654SLei Zhang }
61901178654SLei Zhang 
62001178654SLei Zhang /// Gets or inserts a global variable for a builtin within `body` block.
62101178654SLei Zhang static spirv::GlobalVariableOp
62201178654SLei Zhang getOrInsertBuiltinVariable(Block &body, Location loc, spirv::BuiltIn builtin,
6231e35a769SButygin                            Type integerType, OpBuilder &builder) {
62401178654SLei Zhang   if (auto varOp = getBuiltinVariable(body, builtin))
62501178654SLei Zhang     return varOp;
62601178654SLei Zhang 
62701178654SLei Zhang   OpBuilder::InsertionGuard guard(builder);
62801178654SLei Zhang   builder.setInsertionPointToStart(&body);
62901178654SLei Zhang 
63001178654SLei Zhang   spirv::GlobalVariableOp newVarOp;
63101178654SLei Zhang   switch (builtin) {
63201178654SLei Zhang   case spirv::BuiltIn::NumWorkgroups:
63301178654SLei Zhang   case spirv::BuiltIn::WorkgroupSize:
63401178654SLei Zhang   case spirv::BuiltIn::WorkgroupId:
63501178654SLei Zhang   case spirv::BuiltIn::LocalInvocationId:
63601178654SLei Zhang   case spirv::BuiltIn::GlobalInvocationId: {
6371e35a769SButygin     auto ptrType = spirv::PointerType::get(VectorType::get({3}, integerType),
63801178654SLei Zhang                                            spirv::StorageClass::Input);
63901178654SLei Zhang     std::string name = getBuiltinVarName(builtin);
64001178654SLei Zhang     newVarOp =
64101178654SLei Zhang         builder.create<spirv::GlobalVariableOp>(loc, ptrType, name, builtin);
64201178654SLei Zhang     break;
64301178654SLei Zhang   }
64401178654SLei Zhang   case spirv::BuiltIn::SubgroupId:
64501178654SLei Zhang   case spirv::BuiltIn::NumSubgroups:
64601178654SLei Zhang   case spirv::BuiltIn::SubgroupSize: {
6471e35a769SButygin     auto ptrType =
6481e35a769SButygin         spirv::PointerType::get(integerType, spirv::StorageClass::Input);
64901178654SLei Zhang     std::string name = getBuiltinVarName(builtin);
65001178654SLei Zhang     newVarOp =
65101178654SLei Zhang         builder.create<spirv::GlobalVariableOp>(loc, ptrType, name, builtin);
65201178654SLei Zhang     break;
65301178654SLei Zhang   }
65401178654SLei Zhang   default:
65501178654SLei Zhang     emitError(loc, "unimplemented builtin variable generation for ")
65601178654SLei Zhang         << stringifyBuiltIn(builtin);
65701178654SLei Zhang   }
65801178654SLei Zhang   return newVarOp;
65901178654SLei Zhang }
66001178654SLei Zhang 
66101178654SLei Zhang Value mlir::spirv::getBuiltinVariableValue(Operation *op,
66201178654SLei Zhang                                            spirv::BuiltIn builtin,
6631e35a769SButygin                                            Type integerType,
66401178654SLei Zhang                                            OpBuilder &builder) {
66501178654SLei Zhang   Operation *parent = SymbolTable::getNearestSymbolTable(op->getParentOp());
66601178654SLei Zhang   if (!parent) {
66701178654SLei Zhang     op->emitError("expected operation to be within a module-like op");
66801178654SLei Zhang     return nullptr;
66901178654SLei Zhang   }
67001178654SLei Zhang 
6711e35a769SButygin   spirv::GlobalVariableOp varOp =
6721e35a769SButygin       getOrInsertBuiltinVariable(*parent->getRegion(0).begin(), op->getLoc(),
6731e35a769SButygin                                  builtin, integerType, builder);
67401178654SLei Zhang   Value ptr = builder.create<spirv::AddressOfOp>(op->getLoc(), varOp);
67501178654SLei Zhang   return builder.create<spirv::LoadOp>(op->getLoc(), ptr);
67601178654SLei Zhang }
67701178654SLei Zhang 
67801178654SLei Zhang //===----------------------------------------------------------------------===//
6796dd07fa5SLei Zhang // Push constant storage
6806dd07fa5SLei Zhang //===----------------------------------------------------------------------===//
6816dd07fa5SLei Zhang 
6826dd07fa5SLei Zhang /// Returns the pointer type for the push constant storage containing
6836dd07fa5SLei Zhang /// `elementCount` 32-bit integer values.
6846dd07fa5SLei Zhang static spirv::PointerType getPushConstantStorageType(unsigned elementCount,
6851e35a769SButygin                                                      Builder &builder,
6861e35a769SButygin                                                      Type indexType) {
6871e35a769SButygin   auto arrayType = spirv::ArrayType::get(indexType, elementCount,
6886dd07fa5SLei Zhang                                          /*stride=*/4);
6896dd07fa5SLei Zhang   auto structType = spirv::StructType::get({arrayType}, /*offsetInfo=*/0);
6906dd07fa5SLei Zhang   return spirv::PointerType::get(structType, spirv::StorageClass::PushConstant);
6916dd07fa5SLei Zhang }
6926dd07fa5SLei Zhang 
6936dd07fa5SLei Zhang /// Returns the push constant varible containing `elementCount` 32-bit integer
6946dd07fa5SLei Zhang /// values in `body`. Returns null op if such an op does not exit.
6956dd07fa5SLei Zhang static spirv::GlobalVariableOp getPushConstantVariable(Block &body,
6966dd07fa5SLei Zhang                                                        unsigned elementCount) {
6976dd07fa5SLei Zhang   for (auto varOp : body.getOps<spirv::GlobalVariableOp>()) {
698a5621e26SLei Zhang     auto ptrType = varOp.type().dyn_cast<spirv::PointerType>();
699a5621e26SLei Zhang     if (!ptrType)
700a5621e26SLei Zhang       continue;
701a5621e26SLei Zhang 
7026dd07fa5SLei Zhang     // Note that Vulkan requires "There must be no more than one push constant
7036dd07fa5SLei Zhang     // block statically used per shader entry point." So we should always reuse
7046dd07fa5SLei Zhang     // the existing one.
7056dd07fa5SLei Zhang     if (ptrType.getStorageClass() == spirv::StorageClass::PushConstant) {
7066dd07fa5SLei Zhang       auto numElements = ptrType.getPointeeType()
7076dd07fa5SLei Zhang                              .cast<spirv::StructType>()
7086dd07fa5SLei Zhang                              .getElementType(0)
7096dd07fa5SLei Zhang                              .cast<spirv::ArrayType>()
7106dd07fa5SLei Zhang                              .getNumElements();
7116dd07fa5SLei Zhang       if (numElements == elementCount)
7126dd07fa5SLei Zhang         return varOp;
7136dd07fa5SLei Zhang     }
7146dd07fa5SLei Zhang   }
7156dd07fa5SLei Zhang   return nullptr;
7166dd07fa5SLei Zhang }
7176dd07fa5SLei Zhang 
7186dd07fa5SLei Zhang /// Gets or inserts a global variable for push constant storage containing
7196dd07fa5SLei Zhang /// `elementCount` 32-bit integer values in `block`.
7206dd07fa5SLei Zhang static spirv::GlobalVariableOp
7216dd07fa5SLei Zhang getOrInsertPushConstantVariable(Location loc, Block &block,
7221e35a769SButygin                                 unsigned elementCount, OpBuilder &b,
7231e35a769SButygin                                 Type indexType) {
7246dd07fa5SLei Zhang   if (auto varOp = getPushConstantVariable(block, elementCount))
7256dd07fa5SLei Zhang     return varOp;
7266dd07fa5SLei Zhang 
7276dd07fa5SLei Zhang   auto builder = OpBuilder::atBlockBegin(&block, b.getListener());
7281e35a769SButygin   auto type = getPushConstantStorageType(elementCount, builder, indexType);
7296dd07fa5SLei Zhang   const char *name = "__push_constant_var__";
7306dd07fa5SLei Zhang   return builder.create<spirv::GlobalVariableOp>(loc, type, name,
7316dd07fa5SLei Zhang                                                  /*initializer=*/nullptr);
7326dd07fa5SLei Zhang }
7336dd07fa5SLei Zhang 
7346dd07fa5SLei Zhang Value spirv::getPushConstantValue(Operation *op, unsigned elementCount,
7351e35a769SButygin                                   unsigned offset, Type integerType,
7361e35a769SButygin                                   OpBuilder &builder) {
7376dd07fa5SLei Zhang   Location loc = op->getLoc();
7386dd07fa5SLei Zhang   Operation *parent = SymbolTable::getNearestSymbolTable(op->getParentOp());
7396dd07fa5SLei Zhang   if (!parent) {
7406dd07fa5SLei Zhang     op->emitError("expected operation to be within a module-like op");
7416dd07fa5SLei Zhang     return nullptr;
7426dd07fa5SLei Zhang   }
7436dd07fa5SLei Zhang 
7446dd07fa5SLei Zhang   spirv::GlobalVariableOp varOp = getOrInsertPushConstantVariable(
7451e35a769SButygin       loc, parent->getRegion(0).front(), elementCount, builder, integerType);
7466dd07fa5SLei Zhang 
7471e35a769SButygin   Value zeroOp = spirv::ConstantOp::getZero(integerType, loc, builder);
7486dd07fa5SLei Zhang   Value offsetOp = builder.create<spirv::ConstantOp>(
7491e35a769SButygin       loc, integerType, builder.getI32IntegerAttr(offset));
7506dd07fa5SLei Zhang   auto addrOp = builder.create<spirv::AddressOfOp>(loc, varOp);
7516dd07fa5SLei Zhang   auto acOp = builder.create<spirv::AccessChainOp>(
7526dd07fa5SLei Zhang       loc, addrOp, llvm::makeArrayRef({zeroOp, offsetOp}));
7536dd07fa5SLei Zhang   return builder.create<spirv::LoadOp>(loc, acOp);
7546dd07fa5SLei Zhang }
7556dd07fa5SLei Zhang 
7566dd07fa5SLei Zhang //===----------------------------------------------------------------------===//
75701178654SLei Zhang // Index calculation
75801178654SLei Zhang //===----------------------------------------------------------------------===//
75901178654SLei Zhang 
760bb6f5c83SLei Zhang Value mlir::spirv::linearizeIndex(ValueRange indices, ArrayRef<int64_t> strides,
7611e35a769SButygin                                   int64_t offset, Type integerType,
7621e35a769SButygin                                   Location loc, OpBuilder &builder) {
763bb6f5c83SLei Zhang   assert(indices.size() == strides.size() &&
764bb6f5c83SLei Zhang          "must provide indices for all dimensions");
765bb6f5c83SLei Zhang 
766bb6f5c83SLei Zhang   // TODO: Consider moving to use affine.apply and patterns converting
767bb6f5c83SLei Zhang   // affine.apply to standard ops. This needs converting to SPIR-V passes to be
768bb6f5c83SLei Zhang   // broken down into progressive small steps so we can have intermediate steps
769bb6f5c83SLei Zhang   // using other dialects. At the moment SPIR-V is the final sink.
770bb6f5c83SLei Zhang 
771bb6f5c83SLei Zhang   Value linearizedIndex = builder.create<spirv::ConstantOp>(
7721e35a769SButygin       loc, integerType, IntegerAttr::get(integerType, offset));
773e4853be2SMehdi Amini   for (const auto &index : llvm::enumerate(indices)) {
774bb6f5c83SLei Zhang     Value strideVal = builder.create<spirv::ConstantOp>(
7751e35a769SButygin         loc, integerType,
7761e35a769SButygin         IntegerAttr::get(integerType, strides[index.index()]));
777bb6f5c83SLei Zhang     Value update = builder.create<spirv::IMulOp>(loc, strideVal, index.value());
778bb6f5c83SLei Zhang     linearizedIndex =
779bb6f5c83SLei Zhang         builder.create<spirv::IAddOp>(loc, linearizedIndex, update);
780bb6f5c83SLei Zhang   }
781bb6f5c83SLei Zhang   return linearizedIndex;
782bb6f5c83SLei Zhang }
783bb6f5c83SLei Zhang 
78401178654SLei Zhang spirv::AccessChainOp mlir::spirv::getElementPtr(
78501178654SLei Zhang     SPIRVTypeConverter &typeConverter, MemRefType baseType, Value basePtr,
78601178654SLei Zhang     ValueRange indices, Location loc, OpBuilder &builder) {
78701178654SLei Zhang   // Get base and offset of the MemRefType and verify they are static.
78801178654SLei Zhang 
78901178654SLei Zhang   int64_t offset;
79001178654SLei Zhang   SmallVector<int64_t, 4> strides;
79101178654SLei Zhang   if (failed(getStridesAndOffset(baseType, strides, offset)) ||
79201178654SLei Zhang       llvm::is_contained(strides, MemRefType::getDynamicStrideOrOffset()) ||
79301178654SLei Zhang       offset == MemRefType::getDynamicStrideOrOffset()) {
79401178654SLei Zhang     return nullptr;
79501178654SLei Zhang   }
79601178654SLei Zhang 
7971e35a769SButygin   auto indexType = typeConverter.getIndexType();
79801178654SLei Zhang 
79901178654SLei Zhang   SmallVector<Value, 2> linearizedIndices;
80001178654SLei Zhang   auto zero = spirv::ConstantOp::getZero(indexType, loc, builder);
801bb6f5c83SLei Zhang 
802bb6f5c83SLei Zhang   // Add a '0' at the start to index into the struct.
80301178654SLei Zhang   linearizedIndices.push_back(zero);
80401178654SLei Zhang 
80501178654SLei Zhang   if (baseType.getRank() == 0) {
80601178654SLei Zhang     linearizedIndices.push_back(zero);
80701178654SLei Zhang   } else {
808bb6f5c83SLei Zhang     linearizedIndices.push_back(
8091e35a769SButygin         linearizeIndex(indices, strides, offset, indexType, loc, builder));
81001178654SLei Zhang   }
81101178654SLei Zhang   return builder.create<spirv::AccessChainOp>(loc, basePtr, linearizedIndices);
81201178654SLei Zhang }
81301178654SLei Zhang 
81401178654SLei Zhang //===----------------------------------------------------------------------===//
81501178654SLei Zhang // SPIR-V ConversionTarget
81601178654SLei Zhang //===----------------------------------------------------------------------===//
81701178654SLei Zhang 
8186dd07fa5SLei Zhang std::unique_ptr<SPIRVConversionTarget>
8196dd07fa5SLei Zhang SPIRVConversionTarget::get(spirv::TargetEnvAttr targetAttr) {
82001178654SLei Zhang   std::unique_ptr<SPIRVConversionTarget> target(
82101178654SLei Zhang       // std::make_unique does not work here because the constructor is private.
82201178654SLei Zhang       new SPIRVConversionTarget(targetAttr));
82301178654SLei Zhang   SPIRVConversionTarget *targetPtr = target.get();
8246dd07fa5SLei Zhang   target->addDynamicallyLegalDialect<spirv::SPIRVDialect>(
82501178654SLei Zhang       // We need to capture the raw pointer here because it is stable:
82601178654SLei Zhang       // target will be destroyed once this function is returned.
82701178654SLei Zhang       [targetPtr](Operation *op) { return targetPtr->isLegalOp(op); });
82801178654SLei Zhang   return target;
82901178654SLei Zhang }
83001178654SLei Zhang 
8316dd07fa5SLei Zhang SPIRVConversionTarget::SPIRVConversionTarget(spirv::TargetEnvAttr targetAttr)
83201178654SLei Zhang     : ConversionTarget(*targetAttr.getContext()), targetEnv(targetAttr) {}
83301178654SLei Zhang 
8346dd07fa5SLei Zhang bool SPIRVConversionTarget::isLegalOp(Operation *op) {
83501178654SLei Zhang   // Make sure this op is available at the given version. Ops not implementing
83601178654SLei Zhang   // QueryMinVersionInterface/QueryMaxVersionInterface are available to all
83701178654SLei Zhang   // SPIR-V versions.
838cb395f66SLei Zhang   if (auto minVersionIfx = dyn_cast<spirv::QueryMinVersionInterface>(op)) {
839cb395f66SLei Zhang     Optional<spirv::Version> minVersion = minVersionIfx.getMinVersion();
840cb395f66SLei Zhang     if (minVersion && *minVersion > this->targetEnv.getVersion()) {
84101178654SLei Zhang       LLVM_DEBUG(llvm::dbgs()
84201178654SLei Zhang                  << op->getName() << " illegal: requiring min version "
843cb395f66SLei Zhang                  << spirv::stringifyVersion(*minVersion) << "\n");
84401178654SLei Zhang       return false;
84501178654SLei Zhang     }
846cb395f66SLei Zhang   }
847cb395f66SLei Zhang   if (auto maxVersionIfx = dyn_cast<spirv::QueryMaxVersionInterface>(op)) {
848cb395f66SLei Zhang     Optional<spirv::Version> maxVersion = maxVersionIfx.getMaxVersion();
849cb395f66SLei Zhang     if (maxVersion && *maxVersion < this->targetEnv.getVersion()) {
85001178654SLei Zhang       LLVM_DEBUG(llvm::dbgs()
85101178654SLei Zhang                  << op->getName() << " illegal: requiring max version "
852cb395f66SLei Zhang                  << spirv::stringifyVersion(*maxVersion) << "\n");
85301178654SLei Zhang       return false;
85401178654SLei Zhang     }
855cb395f66SLei Zhang   }
85601178654SLei Zhang 
85701178654SLei Zhang   // Make sure this op's required extensions are allowed to use. Ops not
85801178654SLei Zhang   // implementing QueryExtensionInterface do not require extensions to be
85901178654SLei Zhang   // available.
86001178654SLei Zhang   if (auto extensions = dyn_cast<spirv::QueryExtensionInterface>(op))
86101178654SLei Zhang     if (failed(checkExtensionRequirements(op->getName(), this->targetEnv,
86201178654SLei Zhang                                           extensions.getExtensions())))
86301178654SLei Zhang       return false;
86401178654SLei Zhang 
86501178654SLei Zhang   // Make sure this op's required extensions are allowed to use. Ops not
86601178654SLei Zhang   // implementing QueryCapabilityInterface do not require capabilities to be
86701178654SLei Zhang   // available.
86801178654SLei Zhang   if (auto capabilities = dyn_cast<spirv::QueryCapabilityInterface>(op))
86901178654SLei Zhang     if (failed(checkCapabilityRequirements(op->getName(), this->targetEnv,
87001178654SLei Zhang                                            capabilities.getCapabilities())))
87101178654SLei Zhang       return false;
87201178654SLei Zhang 
87301178654SLei Zhang   SmallVector<Type, 4> valueTypes;
87401178654SLei Zhang   valueTypes.append(op->operand_type_begin(), op->operand_type_end());
87501178654SLei Zhang   valueTypes.append(op->result_type_begin(), op->result_type_end());
87601178654SLei Zhang 
8777c5ecc8bSMogball   // Ensure that all types have been converted to SPIRV types.
8787c5ecc8bSMogball   if (llvm::any_of(valueTypes,
8797c5ecc8bSMogball                    [](Type t) { return !t.isa<spirv::SPIRVType>(); }))
8807c5ecc8bSMogball     return false;
8817c5ecc8bSMogball 
88201178654SLei Zhang   // Special treatment for global variables, whose type requirements are
88301178654SLei Zhang   // conveyed by type attributes.
88401178654SLei Zhang   if (auto globalVar = dyn_cast<spirv::GlobalVariableOp>(op))
88501178654SLei Zhang     valueTypes.push_back(globalVar.type());
88601178654SLei Zhang 
88701178654SLei Zhang   // Make sure the op's operands/results use types that are allowed by the
88801178654SLei Zhang   // target environment.
88901178654SLei Zhang   SmallVector<ArrayRef<spirv::Extension>, 4> typeExtensions;
89001178654SLei Zhang   SmallVector<ArrayRef<spirv::Capability>, 8> typeCapabilities;
89101178654SLei Zhang   for (Type valueType : valueTypes) {
89201178654SLei Zhang     typeExtensions.clear();
89301178654SLei Zhang     valueType.cast<spirv::SPIRVType>().getExtensions(typeExtensions);
89401178654SLei Zhang     if (failed(checkExtensionRequirements(op->getName(), this->targetEnv,
89501178654SLei Zhang                                           typeExtensions)))
89601178654SLei Zhang       return false;
89701178654SLei Zhang 
89801178654SLei Zhang     typeCapabilities.clear();
89901178654SLei Zhang     valueType.cast<spirv::SPIRVType>().getCapabilities(typeCapabilities);
90001178654SLei Zhang     if (failed(checkCapabilityRequirements(op->getName(), this->targetEnv,
90101178654SLei Zhang                                            typeCapabilities)))
90201178654SLei Zhang       return false;
90301178654SLei Zhang   }
90401178654SLei Zhang 
90501178654SLei Zhang   return true;
90601178654SLei Zhang }
907