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"
1401178654SLei Zhang #include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h"
1501178654SLei Zhang #include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
167c3ae48fSLei Zhang #include "mlir/Transforms/DialectConversion.h"
1701178654SLei Zhang #include "llvm/ADT/Sequence.h"
1801178654SLei Zhang #include "llvm/ADT/StringExtras.h"
1901178654SLei Zhang #include "llvm/Support/Debug.h"
2001178654SLei Zhang 
2101178654SLei Zhang #include <functional>
2201178654SLei Zhang 
2301178654SLei Zhang #define DEBUG_TYPE "mlir-spirv-conversion"
2401178654SLei Zhang 
2501178654SLei Zhang using namespace mlir;
2601178654SLei Zhang 
2701178654SLei Zhang //===----------------------------------------------------------------------===//
2801178654SLei Zhang // Utility functions
2901178654SLei Zhang //===----------------------------------------------------------------------===//
3001178654SLei Zhang 
3101178654SLei Zhang /// Checks that `candidates` extension requirements are possible to be satisfied
3201178654SLei Zhang /// with the given `targetEnv`.
3301178654SLei Zhang ///
3401178654SLei Zhang ///  `candidates` is a vector of vector for extension requirements following
3501178654SLei Zhang /// ((Extension::A OR Extension::B) AND (Extension::C OR Extension::D))
3601178654SLei Zhang /// convention.
3701178654SLei Zhang template <typename LabelT>
3801178654SLei Zhang static LogicalResult checkExtensionRequirements(
3901178654SLei Zhang     LabelT label, const spirv::TargetEnv &targetEnv,
4001178654SLei Zhang     const spirv::SPIRVType::ExtensionArrayRefVector &candidates) {
4101178654SLei Zhang   for (const auto &ors : candidates) {
4201178654SLei Zhang     if (targetEnv.allows(ors))
4301178654SLei Zhang       continue;
4401178654SLei Zhang 
4501178654SLei Zhang     SmallVector<StringRef, 4> extStrings;
4601178654SLei Zhang     for (spirv::Extension ext : ors)
4701178654SLei Zhang       extStrings.push_back(spirv::stringifyExtension(ext));
4801178654SLei Zhang 
4901178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
5001178654SLei Zhang                << label << " illegal: requires at least one extension in ["
5101178654SLei Zhang                << llvm::join(extStrings, ", ")
5201178654SLei Zhang                << "] but none allowed in target environment\n");
5301178654SLei Zhang     return failure();
5401178654SLei Zhang   }
5501178654SLei Zhang   return success();
5601178654SLei Zhang }
5701178654SLei Zhang 
5801178654SLei Zhang /// Checks that `candidates`capability requirements are possible to be satisfied
5901178654SLei Zhang /// with the given `isAllowedFn`.
6001178654SLei Zhang ///
6101178654SLei Zhang ///  `candidates` is a vector of vector for capability requirements following
6201178654SLei Zhang /// ((Capability::A OR Capability::B) AND (Capability::C OR Capability::D))
6301178654SLei Zhang /// convention.
6401178654SLei Zhang template <typename LabelT>
6501178654SLei Zhang static LogicalResult checkCapabilityRequirements(
6601178654SLei Zhang     LabelT label, const spirv::TargetEnv &targetEnv,
6701178654SLei Zhang     const spirv::SPIRVType::CapabilityArrayRefVector &candidates) {
6801178654SLei Zhang   for (const auto &ors : candidates) {
6901178654SLei Zhang     if (targetEnv.allows(ors))
7001178654SLei Zhang       continue;
7101178654SLei Zhang 
7201178654SLei Zhang     SmallVector<StringRef, 4> capStrings;
7301178654SLei Zhang     for (spirv::Capability cap : ors)
7401178654SLei Zhang       capStrings.push_back(spirv::stringifyCapability(cap));
7501178654SLei Zhang 
7601178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
7701178654SLei Zhang                << label << " illegal: requires at least one capability in ["
7801178654SLei Zhang                << llvm::join(capStrings, ", ")
7901178654SLei Zhang                << "] but none allowed in target environment\n");
8001178654SLei Zhang     return failure();
8101178654SLei Zhang   }
8201178654SLei Zhang   return success();
8301178654SLei Zhang }
8401178654SLei Zhang 
8501178654SLei Zhang //===----------------------------------------------------------------------===//
8601178654SLei Zhang // Type Conversion
8701178654SLei Zhang //===----------------------------------------------------------------------===//
8801178654SLei Zhang 
8901178654SLei Zhang Type SPIRVTypeConverter::getIndexType(MLIRContext *context) {
9001178654SLei Zhang   // Convert to 32-bit integers for now. Might need a way to control this in
9101178654SLei Zhang   // future.
9201178654SLei Zhang   // TODO: It is probably better to make it 64-bit integers. To
9301178654SLei Zhang   // this some support is needed in SPIR-V dialect for Conversion
9401178654SLei Zhang   // instructions. The Vulkan spec requires the builtins like
9501178654SLei Zhang   // GlobalInvocationID, etc. to be 32-bit (unsigned) integers which should be
9601178654SLei Zhang   // SExtended to 64-bit for index computations.
971b97cdf8SRiver Riddle   return IntegerType::get(context, 32);
9801178654SLei Zhang }
9901178654SLei Zhang 
10001178654SLei Zhang /// Mapping between SPIR-V storage classes to memref memory spaces.
10101178654SLei Zhang ///
10201178654SLei Zhang /// Note: memref does not have a defined semantics for each memory space; it
10301178654SLei Zhang /// depends on the context where it is used. There are no particular reasons
10401178654SLei Zhang /// behind the number assignments; we try to follow NVVM conventions and largely
10501178654SLei Zhang /// give common storage classes a smaller number. The hope is use symbolic
10601178654SLei Zhang /// memory space representation eventually after memref supports it.
10701178654SLei Zhang // TODO: swap Generic and StorageBuffer assignment to be more akin
10801178654SLei Zhang // to NVVM.
10901178654SLei Zhang #define STORAGE_SPACE_MAP_LIST(MAP_FN)                                         \
11001178654SLei Zhang   MAP_FN(spirv::StorageClass::Generic, 1)                                      \
11101178654SLei Zhang   MAP_FN(spirv::StorageClass::StorageBuffer, 0)                                \
11201178654SLei Zhang   MAP_FN(spirv::StorageClass::Workgroup, 3)                                    \
11301178654SLei Zhang   MAP_FN(spirv::StorageClass::Uniform, 4)                                      \
11401178654SLei Zhang   MAP_FN(spirv::StorageClass::Private, 5)                                      \
11501178654SLei Zhang   MAP_FN(spirv::StorageClass::Function, 6)                                     \
11601178654SLei Zhang   MAP_FN(spirv::StorageClass::PushConstant, 7)                                 \
11701178654SLei Zhang   MAP_FN(spirv::StorageClass::UniformConstant, 8)                              \
11801178654SLei Zhang   MAP_FN(spirv::StorageClass::Input, 9)                                        \
11901178654SLei Zhang   MAP_FN(spirv::StorageClass::Output, 10)                                      \
12001178654SLei Zhang   MAP_FN(spirv::StorageClass::CrossWorkgroup, 11)                              \
12101178654SLei Zhang   MAP_FN(spirv::StorageClass::AtomicCounter, 12)                               \
12201178654SLei Zhang   MAP_FN(spirv::StorageClass::Image, 13)                                       \
12301178654SLei Zhang   MAP_FN(spirv::StorageClass::CallableDataNV, 14)                              \
12401178654SLei Zhang   MAP_FN(spirv::StorageClass::IncomingCallableDataNV, 15)                      \
12501178654SLei Zhang   MAP_FN(spirv::StorageClass::RayPayloadNV, 16)                                \
12601178654SLei Zhang   MAP_FN(spirv::StorageClass::HitAttributeNV, 17)                              \
12701178654SLei Zhang   MAP_FN(spirv::StorageClass::IncomingRayPayloadNV, 18)                        \
12801178654SLei Zhang   MAP_FN(spirv::StorageClass::ShaderRecordBufferNV, 19)                        \
12901178654SLei Zhang   MAP_FN(spirv::StorageClass::PhysicalStorageBuffer, 20)
13001178654SLei Zhang 
13101178654SLei Zhang unsigned
13201178654SLei Zhang SPIRVTypeConverter::getMemorySpaceForStorageClass(spirv::StorageClass storage) {
13301178654SLei Zhang #define STORAGE_SPACE_MAP_FN(storage, space)                                   \
13401178654SLei Zhang   case storage:                                                                \
13501178654SLei Zhang     return space;
13601178654SLei Zhang 
13701178654SLei Zhang   switch (storage) { STORAGE_SPACE_MAP_LIST(STORAGE_SPACE_MAP_FN) }
13801178654SLei Zhang #undef STORAGE_SPACE_MAP_FN
13901178654SLei Zhang   llvm_unreachable("unhandled storage class!");
14001178654SLei Zhang }
14101178654SLei Zhang 
14201178654SLei Zhang Optional<spirv::StorageClass>
14301178654SLei Zhang SPIRVTypeConverter::getStorageClassForMemorySpace(unsigned space) {
14401178654SLei Zhang #define STORAGE_SPACE_MAP_FN(storage, space)                                   \
14501178654SLei Zhang   case space:                                                                  \
14601178654SLei Zhang     return storage;
14701178654SLei Zhang 
14801178654SLei Zhang   switch (space) {
14901178654SLei Zhang     STORAGE_SPACE_MAP_LIST(STORAGE_SPACE_MAP_FN)
15001178654SLei Zhang   default:
15101178654SLei Zhang     return llvm::None;
15201178654SLei Zhang   }
15301178654SLei Zhang #undef STORAGE_SPACE_MAP_FN
15401178654SLei Zhang }
15501178654SLei Zhang 
15601178654SLei Zhang #undef STORAGE_SPACE_MAP_LIST
15701178654SLei Zhang 
158*5299843cSLei Zhang // TODO: This is a utility function that should probably be exposed by the
159*5299843cSLei Zhang // SPIR-V dialect. Keeping it local till the use case arises.
160*5299843cSLei Zhang static Optional<int64_t>
161*5299843cSLei Zhang getTypeNumBytes(const SPIRVTypeConverter::Options &options, Type type) {
162*5299843cSLei Zhang   if (type.isa<spirv::ScalarType>()) {
163*5299843cSLei Zhang     auto bitWidth = type.getIntOrFloatBitWidth();
16401178654SLei Zhang     // According to the SPIR-V spec:
16501178654SLei Zhang     // "There is no physical size or bit pattern defined for values with boolean
16601178654SLei Zhang     // type. If they are stored (in conjunction with OpVariable), they can only
16701178654SLei Zhang     // be used with logical addressing operations, not physical, and only with
16801178654SLei Zhang     // non-externally visible shader Storage Classes: Workgroup, CrossWorkgroup,
16901178654SLei Zhang     // Private, Function, Input, and Output."
170*5299843cSLei Zhang     if (bitWidth == 1)
17101178654SLei Zhang       return llvm::None;
17201178654SLei Zhang     return bitWidth / 8;
17301178654SLei Zhang   }
1746dd07fa5SLei Zhang 
175*5299843cSLei Zhang   if (auto vecType = type.dyn_cast<VectorType>()) {
176*5299843cSLei Zhang     auto elementSize = getTypeNumBytes(options, vecType.getElementType());
17701178654SLei Zhang     if (!elementSize)
17801178654SLei Zhang       return llvm::None;
179*5299843cSLei Zhang     return vecType.getNumElements() * elementSize.getValue();
18001178654SLei Zhang   }
1816dd07fa5SLei Zhang 
182*5299843cSLei Zhang   if (auto memRefType = type.dyn_cast<MemRefType>()) {
18301178654SLei Zhang     // TODO: Layout should also be controlled by the ABI attributes. For now
18401178654SLei Zhang     // using the layout from MemRef.
18501178654SLei Zhang     int64_t offset;
18601178654SLei Zhang     SmallVector<int64_t, 4> strides;
18701178654SLei Zhang     if (!memRefType.hasStaticShape() ||
188*5299843cSLei Zhang         failed(getStridesAndOffset(memRefType, strides, offset)))
18901178654SLei Zhang       return llvm::None;
190*5299843cSLei Zhang 
19101178654SLei Zhang     // To get the size of the memref object in memory, the total size is the
19201178654SLei Zhang     // max(stride * dimension-size) computed for all dimensions times the size
19301178654SLei Zhang     // of the element.
194*5299843cSLei Zhang     auto elementSize = getTypeNumBytes(options, memRefType.getElementType());
195*5299843cSLei Zhang     if (!elementSize)
19601178654SLei Zhang       return llvm::None;
197*5299843cSLei Zhang 
198*5299843cSLei Zhang     if (memRefType.getRank() == 0)
19901178654SLei Zhang       return elementSize;
200*5299843cSLei Zhang 
20101178654SLei Zhang     auto dims = memRefType.getShape();
20201178654SLei Zhang     if (llvm::is_contained(dims, ShapedType::kDynamicSize) ||
20301178654SLei Zhang         offset == MemRefType::getDynamicStrideOrOffset() ||
204*5299843cSLei Zhang         llvm::is_contained(strides, MemRefType::getDynamicStrideOrOffset()))
20501178654SLei Zhang       return llvm::None;
206*5299843cSLei Zhang 
20701178654SLei Zhang     int64_t memrefSize = -1;
208*5299843cSLei Zhang     for (auto shape : enumerate(dims))
20901178654SLei Zhang       memrefSize = std::max(memrefSize, shape.value() * strides[shape.index()]);
210*5299843cSLei Zhang 
21101178654SLei Zhang     return (offset + memrefSize) * elementSize.getValue();
2126dd07fa5SLei Zhang   }
2136dd07fa5SLei Zhang 
214*5299843cSLei Zhang   if (auto tensorType = type.dyn_cast<TensorType>()) {
215*5299843cSLei Zhang     if (!tensorType.hasStaticShape())
21601178654SLei Zhang       return llvm::None;
217*5299843cSLei Zhang 
218*5299843cSLei Zhang     auto elementSize = getTypeNumBytes(options, tensorType.getElementType());
219*5299843cSLei Zhang     if (!elementSize)
22001178654SLei Zhang       return llvm::None;
221*5299843cSLei Zhang 
22201178654SLei Zhang     int64_t size = elementSize.getValue();
223*5299843cSLei Zhang     for (auto shape : tensorType.getShape())
22401178654SLei Zhang       size *= shape;
225*5299843cSLei Zhang 
22601178654SLei Zhang     return size;
22701178654SLei Zhang   }
2286dd07fa5SLei Zhang 
22901178654SLei Zhang   // TODO: Add size computation for other types.
23001178654SLei Zhang   return llvm::None;
23101178654SLei Zhang }
23201178654SLei Zhang 
23301178654SLei Zhang /// Converts a scalar `type` to a suitable type under the given `targetEnv`.
234004f29c0SLei Zhang static Type convertScalarType(const spirv::TargetEnv &targetEnv,
235*5299843cSLei Zhang                               const SPIRVTypeConverter::Options &options,
236004f29c0SLei Zhang                               spirv::ScalarType type,
23701178654SLei Zhang                               Optional<spirv::StorageClass> storageClass = {}) {
23801178654SLei Zhang   // Get extension and capability requirements for the given type.
23901178654SLei Zhang   SmallVector<ArrayRef<spirv::Extension>, 1> extensions;
24001178654SLei Zhang   SmallVector<ArrayRef<spirv::Capability>, 2> capabilities;
24101178654SLei Zhang   type.getExtensions(extensions, storageClass);
24201178654SLei Zhang   type.getCapabilities(capabilities, storageClass);
24301178654SLei Zhang 
24401178654SLei Zhang   // If all requirements are met, then we can accept this type as-is.
24501178654SLei Zhang   if (succeeded(checkCapabilityRequirements(type, targetEnv, capabilities)) &&
24601178654SLei Zhang       succeeded(checkExtensionRequirements(type, targetEnv, extensions)))
24701178654SLei Zhang     return type;
24801178654SLei Zhang 
24901178654SLei Zhang   // Otherwise we need to adjust the type, which really means adjusting the
25001178654SLei Zhang   // bitwidth given this is a scalar type.
251*5299843cSLei Zhang 
252*5299843cSLei Zhang   if (!options.emulateNon32BitScalarTypes)
253*5299843cSLei Zhang     return nullptr;
25401178654SLei Zhang 
25501178654SLei Zhang   if (auto floatType = type.dyn_cast<FloatType>()) {
25601178654SLei Zhang     LLVM_DEBUG(llvm::dbgs() << type << " converted to 32-bit for SPIR-V\n");
25701178654SLei Zhang     return Builder(targetEnv.getContext()).getF32Type();
25801178654SLei Zhang   }
25901178654SLei Zhang 
26001178654SLei Zhang   auto intType = type.cast<IntegerType>();
26101178654SLei Zhang   LLVM_DEBUG(llvm::dbgs() << type << " converted to 32-bit for SPIR-V\n");
2621b97cdf8SRiver Riddle   return IntegerType::get(targetEnv.getContext(), /*width=*/32,
2631b97cdf8SRiver Riddle                           intType.getSignedness());
26401178654SLei Zhang }
26501178654SLei Zhang 
26601178654SLei Zhang /// Converts a vector `type` to a suitable type under the given `targetEnv`.
267004f29c0SLei Zhang static Type convertVectorType(const spirv::TargetEnv &targetEnv,
268*5299843cSLei Zhang                               const SPIRVTypeConverter::Options &options,
269004f29c0SLei Zhang                               VectorType type,
27001178654SLei Zhang                               Optional<spirv::StorageClass> storageClass = {}) {
2719f622b3dSLei Zhang   if (type.getRank() == 1 && type.getNumElements() == 1)
2729f622b3dSLei Zhang     return type.getElementType();
2739f622b3dSLei Zhang 
27401178654SLei Zhang   if (!spirv::CompositeType::isValid(type)) {
2759f622b3dSLei Zhang     // TODO: Vector types with more than four elements can be translated into
27601178654SLei Zhang     // array types.
2779f622b3dSLei Zhang     LLVM_DEBUG(llvm::dbgs() << type << " illegal: > 4-element unimplemented\n");
278004f29c0SLei Zhang     return nullptr;
27901178654SLei Zhang   }
28001178654SLei Zhang 
28101178654SLei Zhang   // Get extension and capability requirements for the given type.
28201178654SLei Zhang   SmallVector<ArrayRef<spirv::Extension>, 1> extensions;
28301178654SLei Zhang   SmallVector<ArrayRef<spirv::Capability>, 2> capabilities;
28401178654SLei Zhang   type.cast<spirv::CompositeType>().getExtensions(extensions, storageClass);
28501178654SLei Zhang   type.cast<spirv::CompositeType>().getCapabilities(capabilities, storageClass);
28601178654SLei Zhang 
28701178654SLei Zhang   // If all requirements are met, then we can accept this type as-is.
28801178654SLei Zhang   if (succeeded(checkCapabilityRequirements(type, targetEnv, capabilities)) &&
28901178654SLei Zhang       succeeded(checkExtensionRequirements(type, targetEnv, extensions)))
29001178654SLei Zhang     return type;
29101178654SLei Zhang 
29201178654SLei Zhang   auto elementType = convertScalarType(
293*5299843cSLei Zhang       targetEnv, options, type.getElementType().cast<spirv::ScalarType>(),
294*5299843cSLei Zhang       storageClass);
29501178654SLei Zhang   if (elementType)
296004f29c0SLei Zhang     return VectorType::get(type.getShape(), elementType);
297004f29c0SLei Zhang   return nullptr;
29801178654SLei Zhang }
29901178654SLei Zhang 
30001178654SLei Zhang /// Converts a tensor `type` to a suitable type under the given `targetEnv`.
30101178654SLei Zhang ///
30201178654SLei Zhang /// Note that this is mainly for lowering constant tensors. In SPIR-V one can
30301178654SLei Zhang /// create composite constants with OpConstantComposite to embed relative large
30401178654SLei Zhang /// constant values and use OpCompositeExtract and OpCompositeInsert to
30501178654SLei Zhang /// manipulate, like what we do for vectors.
306004f29c0SLei Zhang static Type convertTensorType(const spirv::TargetEnv &targetEnv,
307*5299843cSLei Zhang                               const SPIRVTypeConverter::Options &options,
30801178654SLei Zhang                               TensorType type) {
30901178654SLei Zhang   // TODO: Handle dynamic shapes.
31001178654SLei Zhang   if (!type.hasStaticShape()) {
31101178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
31201178654SLei Zhang                << type << " illegal: dynamic shape unimplemented\n");
313004f29c0SLei Zhang     return nullptr;
31401178654SLei Zhang   }
31501178654SLei Zhang 
31601178654SLei Zhang   auto scalarType = type.getElementType().dyn_cast<spirv::ScalarType>();
31701178654SLei Zhang   if (!scalarType) {
31801178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
31901178654SLei Zhang                << type << " illegal: cannot convert non-scalar element type\n");
320004f29c0SLei Zhang     return nullptr;
32101178654SLei Zhang   }
32201178654SLei Zhang 
323*5299843cSLei Zhang   Optional<int64_t> scalarSize = getTypeNumBytes(options, scalarType);
324*5299843cSLei Zhang   Optional<int64_t> tensorSize = getTypeNumBytes(options, type);
32501178654SLei Zhang   if (!scalarSize || !tensorSize) {
32601178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
32701178654SLei Zhang                << type << " illegal: cannot deduce element count\n");
328004f29c0SLei Zhang     return nullptr;
32901178654SLei Zhang   }
33001178654SLei Zhang 
33101178654SLei Zhang   auto arrayElemCount = *tensorSize / *scalarSize;
332*5299843cSLei Zhang   auto arrayElemType = convertScalarType(targetEnv, options, scalarType);
33301178654SLei Zhang   if (!arrayElemType)
334004f29c0SLei Zhang     return nullptr;
335*5299843cSLei Zhang   Optional<int64_t> arrayElemSize = getTypeNumBytes(options, arrayElemType);
33601178654SLei Zhang   if (!arrayElemSize) {
33701178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
33801178654SLei Zhang                << type << " illegal: cannot deduce converted element size\n");
339004f29c0SLei Zhang     return nullptr;
34001178654SLei Zhang   }
34101178654SLei Zhang 
342004f29c0SLei Zhang   return spirv::ArrayType::get(arrayElemType, arrayElemCount, *arrayElemSize);
34301178654SLei Zhang }
34401178654SLei Zhang 
345004f29c0SLei Zhang static Type convertMemrefType(const spirv::TargetEnv &targetEnv,
346*5299843cSLei Zhang                               const SPIRVTypeConverter::Options &options,
34701178654SLei Zhang                               MemRefType type) {
34801178654SLei Zhang   Optional<spirv::StorageClass> storageClass =
34937eca08eSVladislav Vinogradov       SPIRVTypeConverter::getStorageClassForMemorySpace(
35037eca08eSVladislav Vinogradov           type.getMemorySpaceAsInt());
35101178654SLei Zhang   if (!storageClass) {
35201178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
35301178654SLei Zhang                << type << " illegal: cannot convert memory space\n");
354004f29c0SLei Zhang     return nullptr;
35501178654SLei Zhang   }
35601178654SLei Zhang 
357004f29c0SLei Zhang   Type arrayElemType;
35801178654SLei Zhang   Type elementType = type.getElementType();
35901178654SLei Zhang   if (auto vecType = elementType.dyn_cast<VectorType>()) {
360*5299843cSLei Zhang     arrayElemType =
361*5299843cSLei Zhang         convertVectorType(targetEnv, options, vecType, storageClass);
36201178654SLei Zhang   } else if (auto scalarType = elementType.dyn_cast<spirv::ScalarType>()) {
363*5299843cSLei Zhang     arrayElemType =
364*5299843cSLei Zhang         convertScalarType(targetEnv, options, scalarType, storageClass);
36501178654SLei Zhang   } else {
36601178654SLei Zhang     LLVM_DEBUG(
36701178654SLei Zhang         llvm::dbgs()
36801178654SLei Zhang         << type
36901178654SLei Zhang         << " unhandled: can only convert scalar or vector element type\n");
370004f29c0SLei Zhang     return nullptr;
37101178654SLei Zhang   }
37201178654SLei Zhang   if (!arrayElemType)
373004f29c0SLei Zhang     return nullptr;
37401178654SLei Zhang 
375*5299843cSLei Zhang   Optional<int64_t> elementSize = getTypeNumBytes(options, elementType);
37601178654SLei Zhang   if (!elementSize) {
37701178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
37801178654SLei Zhang                << type << " illegal: cannot deduce element size\n");
379004f29c0SLei Zhang     return nullptr;
38001178654SLei Zhang   }
38101178654SLei Zhang 
38201178654SLei Zhang   if (!type.hasStaticShape()) {
383004f29c0SLei Zhang     auto arrayType = spirv::RuntimeArrayType::get(arrayElemType, *elementSize);
38401178654SLei Zhang     // Wrap in a struct to satisfy Vulkan interface requirements.
38501178654SLei Zhang     auto structType = spirv::StructType::get(arrayType, 0);
38601178654SLei Zhang     return spirv::PointerType::get(structType, *storageClass);
38701178654SLei Zhang   }
38801178654SLei Zhang 
389*5299843cSLei Zhang   Optional<int64_t> memrefSize = getTypeNumBytes(options, type);
39001178654SLei Zhang   if (!memrefSize) {
39101178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
39201178654SLei Zhang                << type << " illegal: cannot deduce element count\n");
393004f29c0SLei Zhang     return nullptr;
39401178654SLei Zhang   }
39501178654SLei Zhang 
39601178654SLei Zhang   auto arrayElemCount = *memrefSize / *elementSize;
39701178654SLei Zhang 
398*5299843cSLei Zhang   Optional<int64_t> arrayElemSize = getTypeNumBytes(options, arrayElemType);
39901178654SLei Zhang   if (!arrayElemSize) {
40001178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
40101178654SLei Zhang                << type << " illegal: cannot deduce converted element size\n");
402004f29c0SLei Zhang     return nullptr;
40301178654SLei Zhang   }
40401178654SLei Zhang 
40501178654SLei Zhang   auto arrayType =
406004f29c0SLei Zhang       spirv::ArrayType::get(arrayElemType, arrayElemCount, *arrayElemSize);
40701178654SLei Zhang 
40801178654SLei Zhang   // Wrap in a struct to satisfy Vulkan interface requirements. Memrefs with
40901178654SLei Zhang   // workgroup storage class do not need the struct to be laid out explicitly.
41001178654SLei Zhang   auto structType = *storageClass == spirv::StorageClass::Workgroup
41101178654SLei Zhang                         ? spirv::StructType::get(arrayType)
41201178654SLei Zhang                         : spirv::StructType::get(arrayType, 0);
41301178654SLei Zhang   return spirv::PointerType::get(structType, *storageClass);
41401178654SLei Zhang }
41501178654SLei Zhang 
416*5299843cSLei Zhang SPIRVTypeConverter::SPIRVTypeConverter(spirv::TargetEnvAttr targetAttr,
417*5299843cSLei Zhang                                        Options options)
418*5299843cSLei Zhang     : targetEnv(targetAttr), options(options) {
41901178654SLei Zhang   // Add conversions. The order matters here: later ones will be tried earlier.
42001178654SLei Zhang 
42101178654SLei Zhang   // Allow all SPIR-V dialect specific types. This assumes all builtin types
42201178654SLei Zhang   // adopted in the SPIR-V dialect (i.e., IntegerType, FloatType, VectorType)
42301178654SLei Zhang   // were tried before.
42401178654SLei Zhang   //
42501178654SLei Zhang   // TODO: this assumes that the SPIR-V types are valid to use in
42601178654SLei Zhang   // the given target environment, which should be the case if the whole
42701178654SLei Zhang   // pipeline is driven by the same target environment. Still, we probably still
42801178654SLei Zhang   // want to validate and convert to be safe.
42901178654SLei Zhang   addConversion([](spirv::SPIRVType type) { return type; });
43001178654SLei Zhang 
43101178654SLei Zhang   addConversion([](IndexType indexType) {
43201178654SLei Zhang     return SPIRVTypeConverter::getIndexType(indexType.getContext());
43301178654SLei Zhang   });
43401178654SLei Zhang 
43501178654SLei Zhang   addConversion([this](IntegerType intType) -> Optional<Type> {
43601178654SLei Zhang     if (auto scalarType = intType.dyn_cast<spirv::ScalarType>())
437*5299843cSLei Zhang       return convertScalarType(this->targetEnv, this->options, scalarType);
438004f29c0SLei Zhang     return Type();
43901178654SLei Zhang   });
44001178654SLei Zhang 
44101178654SLei Zhang   addConversion([this](FloatType floatType) -> Optional<Type> {
44201178654SLei Zhang     if (auto scalarType = floatType.dyn_cast<spirv::ScalarType>())
443*5299843cSLei Zhang       return convertScalarType(this->targetEnv, this->options, scalarType);
444004f29c0SLei Zhang     return Type();
44501178654SLei Zhang   });
44601178654SLei Zhang 
44701178654SLei Zhang   addConversion([this](VectorType vectorType) {
448*5299843cSLei Zhang     return convertVectorType(this->targetEnv, this->options, vectorType);
44901178654SLei Zhang   });
45001178654SLei Zhang 
45101178654SLei Zhang   addConversion([this](TensorType tensorType) {
452*5299843cSLei Zhang     return convertTensorType(this->targetEnv, this->options, tensorType);
45301178654SLei Zhang   });
45401178654SLei Zhang 
45501178654SLei Zhang   addConversion([this](MemRefType memRefType) {
456*5299843cSLei Zhang     return convertMemrefType(this->targetEnv, this->options, memRefType);
45701178654SLei Zhang   });
45801178654SLei Zhang }
45901178654SLei Zhang 
46001178654SLei Zhang //===----------------------------------------------------------------------===//
46101178654SLei Zhang // FuncOp Conversion Patterns
46201178654SLei Zhang //===----------------------------------------------------------------------===//
46301178654SLei Zhang 
46401178654SLei Zhang namespace {
46501178654SLei Zhang /// A pattern for rewriting function signature to convert arguments of functions
46601178654SLei Zhang /// to be of valid SPIR-V types.
4677c3ae48fSLei Zhang class FuncOpConversion final : public OpConversionPattern<FuncOp> {
46801178654SLei Zhang public:
4697c3ae48fSLei Zhang   using OpConversionPattern<FuncOp>::OpConversionPattern;
47001178654SLei Zhang 
47101178654SLei Zhang   LogicalResult
47201178654SLei Zhang   matchAndRewrite(FuncOp funcOp, ArrayRef<Value> operands,
47301178654SLei Zhang                   ConversionPatternRewriter &rewriter) const override;
47401178654SLei Zhang };
47501178654SLei Zhang } // namespace
47601178654SLei Zhang 
47701178654SLei Zhang LogicalResult
47801178654SLei Zhang FuncOpConversion::matchAndRewrite(FuncOp funcOp, ArrayRef<Value> operands,
47901178654SLei Zhang                                   ConversionPatternRewriter &rewriter) const {
48001178654SLei Zhang   auto fnType = funcOp.getType();
48142980a78SLei Zhang   if (fnType.getNumResults() > 1)
48201178654SLei Zhang     return failure();
48301178654SLei Zhang 
48401178654SLei Zhang   TypeConverter::SignatureConversion signatureConverter(fnType.getNumInputs());
48542980a78SLei Zhang   for (auto argType : enumerate(fnType.getInputs())) {
4867c3ae48fSLei Zhang     auto convertedType = getTypeConverter()->convertType(argType.value());
48701178654SLei Zhang     if (!convertedType)
48801178654SLei Zhang       return failure();
48901178654SLei Zhang     signatureConverter.addInputs(argType.index(), convertedType);
49001178654SLei Zhang   }
49101178654SLei Zhang 
49242980a78SLei Zhang   Type resultType;
493*5299843cSLei Zhang   if (fnType.getNumResults() == 1) {
4947c3ae48fSLei Zhang     resultType = getTypeConverter()->convertType(fnType.getResult(0));
495*5299843cSLei Zhang     if (!resultType)
496*5299843cSLei Zhang       return failure();
497*5299843cSLei Zhang   }
49842980a78SLei Zhang 
49901178654SLei Zhang   // Create the converted spv.func op.
50001178654SLei Zhang   auto newFuncOp = rewriter.create<spirv::FuncOp>(
50101178654SLei Zhang       funcOp.getLoc(), funcOp.getName(),
50201178654SLei Zhang       rewriter.getFunctionType(signatureConverter.getConvertedTypes(),
50342980a78SLei Zhang                                resultType ? TypeRange(resultType)
50442980a78SLei Zhang                                           : TypeRange()));
50501178654SLei Zhang 
50601178654SLei Zhang   // Copy over all attributes other than the function name and type.
50756774bddSMarius Brehler   for (const auto &namedAttr : funcOp->getAttrs()) {
50801178654SLei Zhang     if (namedAttr.first != impl::getTypeAttrName() &&
50901178654SLei Zhang         namedAttr.first != SymbolTable::getSymbolAttrName())
51001178654SLei Zhang       newFuncOp->setAttr(namedAttr.first, namedAttr.second);
51101178654SLei Zhang   }
51201178654SLei Zhang 
51301178654SLei Zhang   rewriter.inlineRegionBefore(funcOp.getBody(), newFuncOp.getBody(),
51401178654SLei Zhang                               newFuncOp.end());
5157c3ae48fSLei Zhang   if (failed(rewriter.convertRegionTypes(
5167c3ae48fSLei Zhang           &newFuncOp.getBody(), *getTypeConverter(), &signatureConverter)))
51701178654SLei Zhang     return failure();
51801178654SLei Zhang   rewriter.eraseOp(funcOp);
51901178654SLei Zhang   return success();
52001178654SLei Zhang }
52101178654SLei Zhang 
522dc4e913bSChris Lattner void mlir::populateBuiltinFuncToSPIRVPatterns(SPIRVTypeConverter &typeConverter,
523dc4e913bSChris Lattner                                               RewritePatternSet &patterns) {
524dc4e913bSChris Lattner   patterns.add<FuncOpConversion>(typeConverter, patterns.getContext());
52501178654SLei Zhang }
52601178654SLei Zhang 
52701178654SLei Zhang //===----------------------------------------------------------------------===//
52801178654SLei Zhang // Builtin Variables
52901178654SLei Zhang //===----------------------------------------------------------------------===//
53001178654SLei Zhang 
53101178654SLei Zhang static spirv::GlobalVariableOp getBuiltinVariable(Block &body,
53201178654SLei Zhang                                                   spirv::BuiltIn builtin) {
53301178654SLei Zhang   // Look through all global variables in the given `body` block and check if
534c74eb466SKareemErgawy-TomTom   // there is a spv.GlobalVariable that has the same `builtin` attribute.
53501178654SLei Zhang   for (auto varOp : body.getOps<spirv::GlobalVariableOp>()) {
53601178654SLei Zhang     if (auto builtinAttr = varOp->getAttrOfType<StringAttr>(
53701178654SLei Zhang             spirv::SPIRVDialect::getAttributeName(
53801178654SLei Zhang                 spirv::Decoration::BuiltIn))) {
53901178654SLei Zhang       auto varBuiltIn = spirv::symbolizeBuiltIn(builtinAttr.getValue());
54001178654SLei Zhang       if (varBuiltIn && varBuiltIn.getValue() == builtin) {
54101178654SLei Zhang         return varOp;
54201178654SLei Zhang       }
54301178654SLei Zhang     }
54401178654SLei Zhang   }
54501178654SLei Zhang   return nullptr;
54601178654SLei Zhang }
54701178654SLei Zhang 
54801178654SLei Zhang /// Gets name of global variable for a builtin.
54901178654SLei Zhang static std::string getBuiltinVarName(spirv::BuiltIn builtin) {
55001178654SLei Zhang   return std::string("__builtin_var_") + stringifyBuiltIn(builtin).str() + "__";
55101178654SLei Zhang }
55201178654SLei Zhang 
55301178654SLei Zhang /// Gets or inserts a global variable for a builtin within `body` block.
55401178654SLei Zhang static spirv::GlobalVariableOp
55501178654SLei Zhang getOrInsertBuiltinVariable(Block &body, Location loc, spirv::BuiltIn builtin,
55601178654SLei Zhang                            OpBuilder &builder) {
55701178654SLei Zhang   if (auto varOp = getBuiltinVariable(body, builtin))
55801178654SLei Zhang     return varOp;
55901178654SLei Zhang 
56001178654SLei Zhang   OpBuilder::InsertionGuard guard(builder);
56101178654SLei Zhang   builder.setInsertionPointToStart(&body);
56201178654SLei Zhang 
56301178654SLei Zhang   spirv::GlobalVariableOp newVarOp;
56401178654SLei Zhang   switch (builtin) {
56501178654SLei Zhang   case spirv::BuiltIn::NumWorkgroups:
56601178654SLei Zhang   case spirv::BuiltIn::WorkgroupSize:
56701178654SLei Zhang   case spirv::BuiltIn::WorkgroupId:
56801178654SLei Zhang   case spirv::BuiltIn::LocalInvocationId:
56901178654SLei Zhang   case spirv::BuiltIn::GlobalInvocationId: {
57001178654SLei Zhang     auto ptrType = spirv::PointerType::get(
57101178654SLei Zhang         VectorType::get({3}, builder.getIntegerType(32)),
57201178654SLei Zhang         spirv::StorageClass::Input);
57301178654SLei Zhang     std::string name = getBuiltinVarName(builtin);
57401178654SLei Zhang     newVarOp =
57501178654SLei Zhang         builder.create<spirv::GlobalVariableOp>(loc, ptrType, name, builtin);
57601178654SLei Zhang     break;
57701178654SLei Zhang   }
57801178654SLei Zhang   case spirv::BuiltIn::SubgroupId:
57901178654SLei Zhang   case spirv::BuiltIn::NumSubgroups:
58001178654SLei Zhang   case spirv::BuiltIn::SubgroupSize: {
58101178654SLei Zhang     auto ptrType = spirv::PointerType::get(builder.getIntegerType(32),
58201178654SLei Zhang                                            spirv::StorageClass::Input);
58301178654SLei Zhang     std::string name = getBuiltinVarName(builtin);
58401178654SLei Zhang     newVarOp =
58501178654SLei Zhang         builder.create<spirv::GlobalVariableOp>(loc, ptrType, name, builtin);
58601178654SLei Zhang     break;
58701178654SLei Zhang   }
58801178654SLei Zhang   default:
58901178654SLei Zhang     emitError(loc, "unimplemented builtin variable generation for ")
59001178654SLei Zhang         << stringifyBuiltIn(builtin);
59101178654SLei Zhang   }
59201178654SLei Zhang   return newVarOp;
59301178654SLei Zhang }
59401178654SLei Zhang 
59501178654SLei Zhang Value mlir::spirv::getBuiltinVariableValue(Operation *op,
59601178654SLei Zhang                                            spirv::BuiltIn builtin,
59701178654SLei Zhang                                            OpBuilder &builder) {
59801178654SLei Zhang   Operation *parent = SymbolTable::getNearestSymbolTable(op->getParentOp());
59901178654SLei Zhang   if (!parent) {
60001178654SLei Zhang     op->emitError("expected operation to be within a module-like op");
60101178654SLei Zhang     return nullptr;
60201178654SLei Zhang   }
60301178654SLei Zhang 
60401178654SLei Zhang   spirv::GlobalVariableOp varOp = getOrInsertBuiltinVariable(
60501178654SLei Zhang       *parent->getRegion(0).begin(), op->getLoc(), builtin, builder);
60601178654SLei Zhang   Value ptr = builder.create<spirv::AddressOfOp>(op->getLoc(), varOp);
60701178654SLei Zhang   return builder.create<spirv::LoadOp>(op->getLoc(), ptr);
60801178654SLei Zhang }
60901178654SLei Zhang 
61001178654SLei Zhang //===----------------------------------------------------------------------===//
6116dd07fa5SLei Zhang // Push constant storage
6126dd07fa5SLei Zhang //===----------------------------------------------------------------------===//
6136dd07fa5SLei Zhang 
6146dd07fa5SLei Zhang /// Returns the pointer type for the push constant storage containing
6156dd07fa5SLei Zhang /// `elementCount` 32-bit integer values.
6166dd07fa5SLei Zhang static spirv::PointerType getPushConstantStorageType(unsigned elementCount,
6176dd07fa5SLei Zhang                                                      Builder &builder) {
6186dd07fa5SLei Zhang   auto arrayType = spirv::ArrayType::get(
6196dd07fa5SLei Zhang       SPIRVTypeConverter::getIndexType(builder.getContext()), elementCount,
6206dd07fa5SLei Zhang       /*stride=*/4);
6216dd07fa5SLei Zhang   auto structType = spirv::StructType::get({arrayType}, /*offsetInfo=*/0);
6226dd07fa5SLei Zhang   return spirv::PointerType::get(structType, spirv::StorageClass::PushConstant);
6236dd07fa5SLei Zhang }
6246dd07fa5SLei Zhang 
6256dd07fa5SLei Zhang /// Returns the push constant varible containing `elementCount` 32-bit integer
6266dd07fa5SLei Zhang /// values in `body`. Returns null op if such an op does not exit.
6276dd07fa5SLei Zhang static spirv::GlobalVariableOp getPushConstantVariable(Block &body,
6286dd07fa5SLei Zhang                                                        unsigned elementCount) {
6296dd07fa5SLei Zhang   for (auto varOp : body.getOps<spirv::GlobalVariableOp>()) {
6306dd07fa5SLei Zhang     auto ptrType = varOp.type().cast<spirv::PointerType>();
6316dd07fa5SLei Zhang     // Note that Vulkan requires "There must be no more than one push constant
6326dd07fa5SLei Zhang     // block statically used per shader entry point." So we should always reuse
6336dd07fa5SLei Zhang     // the existing one.
6346dd07fa5SLei Zhang     if (ptrType.getStorageClass() == spirv::StorageClass::PushConstant) {
6356dd07fa5SLei Zhang       auto numElements = ptrType.getPointeeType()
6366dd07fa5SLei Zhang                              .cast<spirv::StructType>()
6376dd07fa5SLei Zhang                              .getElementType(0)
6386dd07fa5SLei Zhang                              .cast<spirv::ArrayType>()
6396dd07fa5SLei Zhang                              .getNumElements();
6406dd07fa5SLei Zhang       if (numElements == elementCount)
6416dd07fa5SLei Zhang         return varOp;
6426dd07fa5SLei Zhang     }
6436dd07fa5SLei Zhang   }
6446dd07fa5SLei Zhang   return nullptr;
6456dd07fa5SLei Zhang }
6466dd07fa5SLei Zhang 
6476dd07fa5SLei Zhang /// Gets or inserts a global variable for push constant storage containing
6486dd07fa5SLei Zhang /// `elementCount` 32-bit integer values in `block`.
6496dd07fa5SLei Zhang static spirv::GlobalVariableOp
6506dd07fa5SLei Zhang getOrInsertPushConstantVariable(Location loc, Block &block,
6516dd07fa5SLei Zhang                                 unsigned elementCount, OpBuilder &b) {
6526dd07fa5SLei Zhang   if (auto varOp = getPushConstantVariable(block, elementCount))
6536dd07fa5SLei Zhang     return varOp;
6546dd07fa5SLei Zhang 
6556dd07fa5SLei Zhang   auto builder = OpBuilder::atBlockBegin(&block, b.getListener());
6566dd07fa5SLei Zhang   auto type = getPushConstantStorageType(elementCount, builder);
6576dd07fa5SLei Zhang   const char *name = "__push_constant_var__";
6586dd07fa5SLei Zhang   return builder.create<spirv::GlobalVariableOp>(loc, type, name,
6596dd07fa5SLei Zhang                                                  /*initializer=*/nullptr);
6606dd07fa5SLei Zhang }
6616dd07fa5SLei Zhang 
6626dd07fa5SLei Zhang Value spirv::getPushConstantValue(Operation *op, unsigned elementCount,
6636dd07fa5SLei Zhang                                   unsigned offset, OpBuilder &builder) {
6646dd07fa5SLei Zhang   Location loc = op->getLoc();
6656dd07fa5SLei Zhang   Operation *parent = SymbolTable::getNearestSymbolTable(op->getParentOp());
6666dd07fa5SLei Zhang   if (!parent) {
6676dd07fa5SLei Zhang     op->emitError("expected operation to be within a module-like op");
6686dd07fa5SLei Zhang     return nullptr;
6696dd07fa5SLei Zhang   }
6706dd07fa5SLei Zhang 
6716dd07fa5SLei Zhang   spirv::GlobalVariableOp varOp = getOrInsertPushConstantVariable(
6726dd07fa5SLei Zhang       loc, parent->getRegion(0).front(), elementCount, builder);
6736dd07fa5SLei Zhang 
6746dd07fa5SLei Zhang   auto i32Type = SPIRVTypeConverter::getIndexType(builder.getContext());
6756dd07fa5SLei Zhang   Value zeroOp = spirv::ConstantOp::getZero(i32Type, loc, builder);
6766dd07fa5SLei Zhang   Value offsetOp = builder.create<spirv::ConstantOp>(
6776dd07fa5SLei Zhang       loc, i32Type, builder.getI32IntegerAttr(offset));
6786dd07fa5SLei Zhang   auto addrOp = builder.create<spirv::AddressOfOp>(loc, varOp);
6796dd07fa5SLei Zhang   auto acOp = builder.create<spirv::AccessChainOp>(
6806dd07fa5SLei Zhang       loc, addrOp, llvm::makeArrayRef({zeroOp, offsetOp}));
6816dd07fa5SLei Zhang   return builder.create<spirv::LoadOp>(loc, acOp);
6826dd07fa5SLei Zhang }
6836dd07fa5SLei Zhang 
6846dd07fa5SLei Zhang //===----------------------------------------------------------------------===//
68501178654SLei Zhang // Index calculation
68601178654SLei Zhang //===----------------------------------------------------------------------===//
68701178654SLei Zhang 
688bb6f5c83SLei Zhang Value mlir::spirv::linearizeIndex(ValueRange indices, ArrayRef<int64_t> strides,
689bb6f5c83SLei Zhang                                   int64_t offset, Location loc,
690bb6f5c83SLei Zhang                                   OpBuilder &builder) {
691bb6f5c83SLei Zhang   assert(indices.size() == strides.size() &&
692bb6f5c83SLei Zhang          "must provide indices for all dimensions");
693bb6f5c83SLei Zhang 
694bb6f5c83SLei Zhang   auto indexType = SPIRVTypeConverter::getIndexType(builder.getContext());
695bb6f5c83SLei Zhang 
696bb6f5c83SLei Zhang   // TODO: Consider moving to use affine.apply and patterns converting
697bb6f5c83SLei Zhang   // affine.apply to standard ops. This needs converting to SPIR-V passes to be
698bb6f5c83SLei Zhang   // broken down into progressive small steps so we can have intermediate steps
699bb6f5c83SLei Zhang   // using other dialects. At the moment SPIR-V is the final sink.
700bb6f5c83SLei Zhang 
701bb6f5c83SLei Zhang   Value linearizedIndex = builder.create<spirv::ConstantOp>(
702bb6f5c83SLei Zhang       loc, indexType, IntegerAttr::get(indexType, offset));
703bb6f5c83SLei Zhang   for (auto index : llvm::enumerate(indices)) {
704bb6f5c83SLei Zhang     Value strideVal = builder.create<spirv::ConstantOp>(
705bb6f5c83SLei Zhang         loc, indexType, IntegerAttr::get(indexType, strides[index.index()]));
706bb6f5c83SLei Zhang     Value update = builder.create<spirv::IMulOp>(loc, strideVal, index.value());
707bb6f5c83SLei Zhang     linearizedIndex =
708bb6f5c83SLei Zhang         builder.create<spirv::IAddOp>(loc, linearizedIndex, update);
709bb6f5c83SLei Zhang   }
710bb6f5c83SLei Zhang   return linearizedIndex;
711bb6f5c83SLei Zhang }
712bb6f5c83SLei Zhang 
71301178654SLei Zhang spirv::AccessChainOp mlir::spirv::getElementPtr(
71401178654SLei Zhang     SPIRVTypeConverter &typeConverter, MemRefType baseType, Value basePtr,
71501178654SLei Zhang     ValueRange indices, Location loc, OpBuilder &builder) {
71601178654SLei Zhang   // Get base and offset of the MemRefType and verify they are static.
71701178654SLei Zhang 
71801178654SLei Zhang   int64_t offset;
71901178654SLei Zhang   SmallVector<int64_t, 4> strides;
72001178654SLei Zhang   if (failed(getStridesAndOffset(baseType, strides, offset)) ||
72101178654SLei Zhang       llvm::is_contained(strides, MemRefType::getDynamicStrideOrOffset()) ||
72201178654SLei Zhang       offset == MemRefType::getDynamicStrideOrOffset()) {
72301178654SLei Zhang     return nullptr;
72401178654SLei Zhang   }
72501178654SLei Zhang 
72601178654SLei Zhang   auto indexType = typeConverter.getIndexType(builder.getContext());
72701178654SLei Zhang 
72801178654SLei Zhang   SmallVector<Value, 2> linearizedIndices;
72901178654SLei Zhang   auto zero = spirv::ConstantOp::getZero(indexType, loc, builder);
730bb6f5c83SLei Zhang 
731bb6f5c83SLei Zhang   // Add a '0' at the start to index into the struct.
73201178654SLei Zhang   linearizedIndices.push_back(zero);
73301178654SLei Zhang 
73401178654SLei Zhang   if (baseType.getRank() == 0) {
73501178654SLei Zhang     linearizedIndices.push_back(zero);
73601178654SLei Zhang   } else {
737bb6f5c83SLei Zhang     linearizedIndices.push_back(
738bb6f5c83SLei Zhang         linearizeIndex(indices, strides, offset, loc, builder));
73901178654SLei Zhang   }
74001178654SLei Zhang   return builder.create<spirv::AccessChainOp>(loc, basePtr, linearizedIndices);
74101178654SLei Zhang }
74201178654SLei Zhang 
74301178654SLei Zhang //===----------------------------------------------------------------------===//
74401178654SLei Zhang // SPIR-V ConversionTarget
74501178654SLei Zhang //===----------------------------------------------------------------------===//
74601178654SLei Zhang 
7476dd07fa5SLei Zhang std::unique_ptr<SPIRVConversionTarget>
7486dd07fa5SLei Zhang SPIRVConversionTarget::get(spirv::TargetEnvAttr targetAttr) {
74901178654SLei Zhang   std::unique_ptr<SPIRVConversionTarget> target(
75001178654SLei Zhang       // std::make_unique does not work here because the constructor is private.
75101178654SLei Zhang       new SPIRVConversionTarget(targetAttr));
75201178654SLei Zhang   SPIRVConversionTarget *targetPtr = target.get();
7536dd07fa5SLei Zhang   target->addDynamicallyLegalDialect<spirv::SPIRVDialect>(
75401178654SLei Zhang       // We need to capture the raw pointer here because it is stable:
75501178654SLei Zhang       // target will be destroyed once this function is returned.
75601178654SLei Zhang       [targetPtr](Operation *op) { return targetPtr->isLegalOp(op); });
75701178654SLei Zhang   return target;
75801178654SLei Zhang }
75901178654SLei Zhang 
7606dd07fa5SLei Zhang SPIRVConversionTarget::SPIRVConversionTarget(spirv::TargetEnvAttr targetAttr)
76101178654SLei Zhang     : ConversionTarget(*targetAttr.getContext()), targetEnv(targetAttr) {}
76201178654SLei Zhang 
7636dd07fa5SLei Zhang bool SPIRVConversionTarget::isLegalOp(Operation *op) {
76401178654SLei Zhang   // Make sure this op is available at the given version. Ops not implementing
76501178654SLei Zhang   // QueryMinVersionInterface/QueryMaxVersionInterface are available to all
76601178654SLei Zhang   // SPIR-V versions.
76701178654SLei Zhang   if (auto minVersion = dyn_cast<spirv::QueryMinVersionInterface>(op))
76801178654SLei Zhang     if (minVersion.getMinVersion() > this->targetEnv.getVersion()) {
76901178654SLei Zhang       LLVM_DEBUG(llvm::dbgs()
77001178654SLei Zhang                  << op->getName() << " illegal: requiring min version "
77101178654SLei Zhang                  << spirv::stringifyVersion(minVersion.getMinVersion())
77201178654SLei Zhang                  << "\n");
77301178654SLei Zhang       return false;
77401178654SLei Zhang     }
77501178654SLei Zhang   if (auto maxVersion = dyn_cast<spirv::QueryMaxVersionInterface>(op))
77601178654SLei Zhang     if (maxVersion.getMaxVersion() < this->targetEnv.getVersion()) {
77701178654SLei Zhang       LLVM_DEBUG(llvm::dbgs()
77801178654SLei Zhang                  << op->getName() << " illegal: requiring max version "
77901178654SLei Zhang                  << spirv::stringifyVersion(maxVersion.getMaxVersion())
78001178654SLei Zhang                  << "\n");
78101178654SLei Zhang       return false;
78201178654SLei Zhang     }
78301178654SLei Zhang 
78401178654SLei Zhang   // Make sure this op's required extensions are allowed to use. Ops not
78501178654SLei Zhang   // implementing QueryExtensionInterface do not require extensions to be
78601178654SLei Zhang   // available.
78701178654SLei Zhang   if (auto extensions = dyn_cast<spirv::QueryExtensionInterface>(op))
78801178654SLei Zhang     if (failed(checkExtensionRequirements(op->getName(), this->targetEnv,
78901178654SLei Zhang                                           extensions.getExtensions())))
79001178654SLei Zhang       return false;
79101178654SLei Zhang 
79201178654SLei Zhang   // Make sure this op's required extensions are allowed to use. Ops not
79301178654SLei Zhang   // implementing QueryCapabilityInterface do not require capabilities to be
79401178654SLei Zhang   // available.
79501178654SLei Zhang   if (auto capabilities = dyn_cast<spirv::QueryCapabilityInterface>(op))
79601178654SLei Zhang     if (failed(checkCapabilityRequirements(op->getName(), this->targetEnv,
79701178654SLei Zhang                                            capabilities.getCapabilities())))
79801178654SLei Zhang       return false;
79901178654SLei Zhang 
80001178654SLei Zhang   SmallVector<Type, 4> valueTypes;
80101178654SLei Zhang   valueTypes.append(op->operand_type_begin(), op->operand_type_end());
80201178654SLei Zhang   valueTypes.append(op->result_type_begin(), op->result_type_end());
80301178654SLei Zhang 
80401178654SLei Zhang   // Special treatment for global variables, whose type requirements are
80501178654SLei Zhang   // conveyed by type attributes.
80601178654SLei Zhang   if (auto globalVar = dyn_cast<spirv::GlobalVariableOp>(op))
80701178654SLei Zhang     valueTypes.push_back(globalVar.type());
80801178654SLei Zhang 
80901178654SLei Zhang   // Make sure the op's operands/results use types that are allowed by the
81001178654SLei Zhang   // target environment.
81101178654SLei Zhang   SmallVector<ArrayRef<spirv::Extension>, 4> typeExtensions;
81201178654SLei Zhang   SmallVector<ArrayRef<spirv::Capability>, 8> typeCapabilities;
81301178654SLei Zhang   for (Type valueType : valueTypes) {
81401178654SLei Zhang     typeExtensions.clear();
81501178654SLei Zhang     valueType.cast<spirv::SPIRVType>().getExtensions(typeExtensions);
81601178654SLei Zhang     if (failed(checkExtensionRequirements(op->getName(), this->targetEnv,
81701178654SLei Zhang                                           typeExtensions)))
81801178654SLei Zhang       return false;
81901178654SLei Zhang 
82001178654SLei Zhang     typeCapabilities.clear();
82101178654SLei Zhang     valueType.cast<spirv::SPIRVType>().getCapabilities(typeCapabilities);
82201178654SLei Zhang     if (failed(checkCapabilityRequirements(op->getName(), this->targetEnv,
82301178654SLei Zhang                                            typeCapabilities)))
82401178654SLei Zhang       return false;
82501178654SLei Zhang   }
82601178654SLei Zhang 
82701178654SLei Zhang   return true;
82801178654SLei Zhang }
829