1*01178654SLei Zhang //===- SPIRVConversion.cpp - SPIR-V Conversion Utilities ------------------===//
2*01178654SLei Zhang //
3*01178654SLei Zhang // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*01178654SLei Zhang // See https://llvm.org/LICENSE.txt for license information.
5*01178654SLei Zhang // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*01178654SLei Zhang //
7*01178654SLei Zhang //===----------------------------------------------------------------------===//
8*01178654SLei Zhang //
9*01178654SLei Zhang // This file implements utilities used to lower to SPIR-V dialect.
10*01178654SLei Zhang //
11*01178654SLei Zhang //===----------------------------------------------------------------------===//
12*01178654SLei Zhang 
13*01178654SLei Zhang #include "mlir/Dialect/SPIRV/Transforms/SPIRVConversion.h"
14*01178654SLei Zhang #include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h"
15*01178654SLei Zhang #include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
16*01178654SLei Zhang #include "llvm/ADT/Sequence.h"
17*01178654SLei Zhang #include "llvm/ADT/StringExtras.h"
18*01178654SLei Zhang #include "llvm/Support/Debug.h"
19*01178654SLei Zhang 
20*01178654SLei Zhang #include <functional>
21*01178654SLei Zhang 
22*01178654SLei Zhang #define DEBUG_TYPE "mlir-spirv-conversion"
23*01178654SLei Zhang 
24*01178654SLei Zhang using namespace mlir;
25*01178654SLei Zhang 
26*01178654SLei Zhang //===----------------------------------------------------------------------===//
27*01178654SLei Zhang // Utility functions
28*01178654SLei Zhang //===----------------------------------------------------------------------===//
29*01178654SLei Zhang 
30*01178654SLei Zhang /// Checks that `candidates` extension requirements are possible to be satisfied
31*01178654SLei Zhang /// with the given `targetEnv`.
32*01178654SLei Zhang ///
33*01178654SLei Zhang ///  `candidates` is a vector of vector for extension requirements following
34*01178654SLei Zhang /// ((Extension::A OR Extension::B) AND (Extension::C OR Extension::D))
35*01178654SLei Zhang /// convention.
36*01178654SLei Zhang template <typename LabelT>
37*01178654SLei Zhang static LogicalResult checkExtensionRequirements(
38*01178654SLei Zhang     LabelT label, const spirv::TargetEnv &targetEnv,
39*01178654SLei Zhang     const spirv::SPIRVType::ExtensionArrayRefVector &candidates) {
40*01178654SLei Zhang   for (const auto &ors : candidates) {
41*01178654SLei Zhang     if (targetEnv.allows(ors))
42*01178654SLei Zhang       continue;
43*01178654SLei Zhang 
44*01178654SLei Zhang     SmallVector<StringRef, 4> extStrings;
45*01178654SLei Zhang     for (spirv::Extension ext : ors)
46*01178654SLei Zhang       extStrings.push_back(spirv::stringifyExtension(ext));
47*01178654SLei Zhang 
48*01178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
49*01178654SLei Zhang                << label << " illegal: requires at least one extension in ["
50*01178654SLei Zhang                << llvm::join(extStrings, ", ")
51*01178654SLei Zhang                << "] but none allowed in target environment\n");
52*01178654SLei Zhang     return failure();
53*01178654SLei Zhang   }
54*01178654SLei Zhang   return success();
55*01178654SLei Zhang }
56*01178654SLei Zhang 
57*01178654SLei Zhang /// Checks that `candidates`capability requirements are possible to be satisfied
58*01178654SLei Zhang /// with the given `isAllowedFn`.
59*01178654SLei Zhang ///
60*01178654SLei Zhang ///  `candidates` is a vector of vector for capability requirements following
61*01178654SLei Zhang /// ((Capability::A OR Capability::B) AND (Capability::C OR Capability::D))
62*01178654SLei Zhang /// convention.
63*01178654SLei Zhang template <typename LabelT>
64*01178654SLei Zhang static LogicalResult checkCapabilityRequirements(
65*01178654SLei Zhang     LabelT label, const spirv::TargetEnv &targetEnv,
66*01178654SLei Zhang     const spirv::SPIRVType::CapabilityArrayRefVector &candidates) {
67*01178654SLei Zhang   for (const auto &ors : candidates) {
68*01178654SLei Zhang     if (targetEnv.allows(ors))
69*01178654SLei Zhang       continue;
70*01178654SLei Zhang 
71*01178654SLei Zhang     SmallVector<StringRef, 4> capStrings;
72*01178654SLei Zhang     for (spirv::Capability cap : ors)
73*01178654SLei Zhang       capStrings.push_back(spirv::stringifyCapability(cap));
74*01178654SLei Zhang 
75*01178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
76*01178654SLei Zhang                << label << " illegal: requires at least one capability in ["
77*01178654SLei Zhang                << llvm::join(capStrings, ", ")
78*01178654SLei Zhang                << "] but none allowed in target environment\n");
79*01178654SLei Zhang     return failure();
80*01178654SLei Zhang   }
81*01178654SLei Zhang   return success();
82*01178654SLei Zhang }
83*01178654SLei Zhang 
84*01178654SLei Zhang //===----------------------------------------------------------------------===//
85*01178654SLei Zhang // Type Conversion
86*01178654SLei Zhang //===----------------------------------------------------------------------===//
87*01178654SLei Zhang 
88*01178654SLei Zhang Type SPIRVTypeConverter::getIndexType(MLIRContext *context) {
89*01178654SLei Zhang   // Convert to 32-bit integers for now. Might need a way to control this in
90*01178654SLei Zhang   // future.
91*01178654SLei Zhang   // TODO: It is probably better to make it 64-bit integers. To
92*01178654SLei Zhang   // this some support is needed in SPIR-V dialect for Conversion
93*01178654SLei Zhang   // instructions. The Vulkan spec requires the builtins like
94*01178654SLei Zhang   // GlobalInvocationID, etc. to be 32-bit (unsigned) integers which should be
95*01178654SLei Zhang   // SExtended to 64-bit for index computations.
96*01178654SLei Zhang   return IntegerType::get(32, context);
97*01178654SLei Zhang }
98*01178654SLei Zhang 
99*01178654SLei Zhang /// Mapping between SPIR-V storage classes to memref memory spaces.
100*01178654SLei Zhang ///
101*01178654SLei Zhang /// Note: memref does not have a defined semantics for each memory space; it
102*01178654SLei Zhang /// depends on the context where it is used. There are no particular reasons
103*01178654SLei Zhang /// behind the number assignments; we try to follow NVVM conventions and largely
104*01178654SLei Zhang /// give common storage classes a smaller number. The hope is use symbolic
105*01178654SLei Zhang /// memory space representation eventually after memref supports it.
106*01178654SLei Zhang // TODO: swap Generic and StorageBuffer assignment to be more akin
107*01178654SLei Zhang // to NVVM.
108*01178654SLei Zhang #define STORAGE_SPACE_MAP_LIST(MAP_FN)                                         \
109*01178654SLei Zhang   MAP_FN(spirv::StorageClass::Generic, 1)                                      \
110*01178654SLei Zhang   MAP_FN(spirv::StorageClass::StorageBuffer, 0)                                \
111*01178654SLei Zhang   MAP_FN(spirv::StorageClass::Workgroup, 3)                                    \
112*01178654SLei Zhang   MAP_FN(spirv::StorageClass::Uniform, 4)                                      \
113*01178654SLei Zhang   MAP_FN(spirv::StorageClass::Private, 5)                                      \
114*01178654SLei Zhang   MAP_FN(spirv::StorageClass::Function, 6)                                     \
115*01178654SLei Zhang   MAP_FN(spirv::StorageClass::PushConstant, 7)                                 \
116*01178654SLei Zhang   MAP_FN(spirv::StorageClass::UniformConstant, 8)                              \
117*01178654SLei Zhang   MAP_FN(spirv::StorageClass::Input, 9)                                        \
118*01178654SLei Zhang   MAP_FN(spirv::StorageClass::Output, 10)                                      \
119*01178654SLei Zhang   MAP_FN(spirv::StorageClass::CrossWorkgroup, 11)                              \
120*01178654SLei Zhang   MAP_FN(spirv::StorageClass::AtomicCounter, 12)                               \
121*01178654SLei Zhang   MAP_FN(spirv::StorageClass::Image, 13)                                       \
122*01178654SLei Zhang   MAP_FN(spirv::StorageClass::CallableDataNV, 14)                              \
123*01178654SLei Zhang   MAP_FN(spirv::StorageClass::IncomingCallableDataNV, 15)                      \
124*01178654SLei Zhang   MAP_FN(spirv::StorageClass::RayPayloadNV, 16)                                \
125*01178654SLei Zhang   MAP_FN(spirv::StorageClass::HitAttributeNV, 17)                              \
126*01178654SLei Zhang   MAP_FN(spirv::StorageClass::IncomingRayPayloadNV, 18)                        \
127*01178654SLei Zhang   MAP_FN(spirv::StorageClass::ShaderRecordBufferNV, 19)                        \
128*01178654SLei Zhang   MAP_FN(spirv::StorageClass::PhysicalStorageBuffer, 20)
129*01178654SLei Zhang 
130*01178654SLei Zhang unsigned
131*01178654SLei Zhang SPIRVTypeConverter::getMemorySpaceForStorageClass(spirv::StorageClass storage) {
132*01178654SLei Zhang #define STORAGE_SPACE_MAP_FN(storage, space)                                   \
133*01178654SLei Zhang   case storage:                                                                \
134*01178654SLei Zhang     return space;
135*01178654SLei Zhang 
136*01178654SLei Zhang   switch (storage) { STORAGE_SPACE_MAP_LIST(STORAGE_SPACE_MAP_FN) }
137*01178654SLei Zhang #undef STORAGE_SPACE_MAP_FN
138*01178654SLei Zhang   llvm_unreachable("unhandled storage class!");
139*01178654SLei Zhang }
140*01178654SLei Zhang 
141*01178654SLei Zhang Optional<spirv::StorageClass>
142*01178654SLei Zhang SPIRVTypeConverter::getStorageClassForMemorySpace(unsigned space) {
143*01178654SLei Zhang #define STORAGE_SPACE_MAP_FN(storage, space)                                   \
144*01178654SLei Zhang   case space:                                                                  \
145*01178654SLei Zhang     return storage;
146*01178654SLei Zhang 
147*01178654SLei Zhang   switch (space) {
148*01178654SLei Zhang     STORAGE_SPACE_MAP_LIST(STORAGE_SPACE_MAP_FN)
149*01178654SLei Zhang   default:
150*01178654SLei Zhang     return llvm::None;
151*01178654SLei Zhang   }
152*01178654SLei Zhang #undef STORAGE_SPACE_MAP_FN
153*01178654SLei Zhang }
154*01178654SLei Zhang 
155*01178654SLei Zhang #undef STORAGE_SPACE_MAP_LIST
156*01178654SLei Zhang 
157*01178654SLei Zhang // TODO: This is a utility function that should probably be
158*01178654SLei Zhang // exposed by the SPIR-V dialect. Keeping it local till the use case arises.
159*01178654SLei Zhang static Optional<int64_t> getTypeNumBytes(Type t) {
160*01178654SLei Zhang   if (t.isa<spirv::ScalarType>()) {
161*01178654SLei Zhang     auto bitWidth = t.getIntOrFloatBitWidth();
162*01178654SLei Zhang     // According to the SPIR-V spec:
163*01178654SLei Zhang     // "There is no physical size or bit pattern defined for values with boolean
164*01178654SLei Zhang     // type. If they are stored (in conjunction with OpVariable), they can only
165*01178654SLei Zhang     // be used with logical addressing operations, not physical, and only with
166*01178654SLei Zhang     // non-externally visible shader Storage Classes: Workgroup, CrossWorkgroup,
167*01178654SLei Zhang     // Private, Function, Input, and Output."
168*01178654SLei Zhang     if (bitWidth == 1) {
169*01178654SLei Zhang       return llvm::None;
170*01178654SLei Zhang     }
171*01178654SLei Zhang     return bitWidth / 8;
172*01178654SLei Zhang   }
173*01178654SLei Zhang   if (auto vecType = t.dyn_cast<VectorType>()) {
174*01178654SLei Zhang     auto elementSize = getTypeNumBytes(vecType.getElementType());
175*01178654SLei Zhang     if (!elementSize)
176*01178654SLei Zhang       return llvm::None;
177*01178654SLei Zhang     return vecType.getNumElements() * *elementSize;
178*01178654SLei Zhang   }
179*01178654SLei Zhang   if (auto memRefType = t.dyn_cast<MemRefType>()) {
180*01178654SLei Zhang     // TODO: Layout should also be controlled by the ABI attributes. For now
181*01178654SLei Zhang     // using the layout from MemRef.
182*01178654SLei Zhang     int64_t offset;
183*01178654SLei Zhang     SmallVector<int64_t, 4> strides;
184*01178654SLei Zhang     if (!memRefType.hasStaticShape() ||
185*01178654SLei Zhang         failed(getStridesAndOffset(memRefType, strides, offset))) {
186*01178654SLei Zhang       return llvm::None;
187*01178654SLei Zhang     }
188*01178654SLei Zhang     // To get the size of the memref object in memory, the total size is the
189*01178654SLei Zhang     // max(stride * dimension-size) computed for all dimensions times the size
190*01178654SLei Zhang     // of the element.
191*01178654SLei Zhang     auto elementSize = getTypeNumBytes(memRefType.getElementType());
192*01178654SLei Zhang     if (!elementSize) {
193*01178654SLei Zhang       return llvm::None;
194*01178654SLei Zhang     }
195*01178654SLei Zhang     if (memRefType.getRank() == 0) {
196*01178654SLei Zhang       return elementSize;
197*01178654SLei Zhang     }
198*01178654SLei Zhang     auto dims = memRefType.getShape();
199*01178654SLei Zhang     if (llvm::is_contained(dims, ShapedType::kDynamicSize) ||
200*01178654SLei Zhang         offset == MemRefType::getDynamicStrideOrOffset() ||
201*01178654SLei Zhang         llvm::is_contained(strides, MemRefType::getDynamicStrideOrOffset())) {
202*01178654SLei Zhang       return llvm::None;
203*01178654SLei Zhang     }
204*01178654SLei Zhang     int64_t memrefSize = -1;
205*01178654SLei Zhang     for (auto shape : enumerate(dims)) {
206*01178654SLei Zhang       memrefSize = std::max(memrefSize, shape.value() * strides[shape.index()]);
207*01178654SLei Zhang     }
208*01178654SLei Zhang     return (offset + memrefSize) * elementSize.getValue();
209*01178654SLei Zhang   } else if (auto tensorType = t.dyn_cast<TensorType>()) {
210*01178654SLei Zhang     if (!tensorType.hasStaticShape()) {
211*01178654SLei Zhang       return llvm::None;
212*01178654SLei Zhang     }
213*01178654SLei Zhang     auto elementSize = getTypeNumBytes(tensorType.getElementType());
214*01178654SLei Zhang     if (!elementSize) {
215*01178654SLei Zhang       return llvm::None;
216*01178654SLei Zhang     }
217*01178654SLei Zhang     int64_t size = elementSize.getValue();
218*01178654SLei Zhang     for (auto shape : tensorType.getShape()) {
219*01178654SLei Zhang       size *= shape;
220*01178654SLei Zhang     }
221*01178654SLei Zhang     return size;
222*01178654SLei Zhang   }
223*01178654SLei Zhang   // TODO: Add size computation for other types.
224*01178654SLei Zhang   return llvm::None;
225*01178654SLei Zhang }
226*01178654SLei Zhang 
227*01178654SLei Zhang Optional<int64_t> SPIRVTypeConverter::getConvertedTypeNumBytes(Type t) {
228*01178654SLei Zhang   return getTypeNumBytes(t);
229*01178654SLei Zhang }
230*01178654SLei Zhang 
231*01178654SLei Zhang /// Converts a scalar `type` to a suitable type under the given `targetEnv`.
232*01178654SLei Zhang static Optional<Type>
233*01178654SLei Zhang convertScalarType(const spirv::TargetEnv &targetEnv, spirv::ScalarType type,
234*01178654SLei Zhang                   Optional<spirv::StorageClass> storageClass = {}) {
235*01178654SLei Zhang   // Get extension and capability requirements for the given type.
236*01178654SLei Zhang   SmallVector<ArrayRef<spirv::Extension>, 1> extensions;
237*01178654SLei Zhang   SmallVector<ArrayRef<spirv::Capability>, 2> capabilities;
238*01178654SLei Zhang   type.getExtensions(extensions, storageClass);
239*01178654SLei Zhang   type.getCapabilities(capabilities, storageClass);
240*01178654SLei Zhang 
241*01178654SLei Zhang   // If all requirements are met, then we can accept this type as-is.
242*01178654SLei Zhang   if (succeeded(checkCapabilityRequirements(type, targetEnv, capabilities)) &&
243*01178654SLei Zhang       succeeded(checkExtensionRequirements(type, targetEnv, extensions)))
244*01178654SLei Zhang     return type;
245*01178654SLei Zhang 
246*01178654SLei Zhang   // Otherwise we need to adjust the type, which really means adjusting the
247*01178654SLei Zhang   // bitwidth given this is a scalar type.
248*01178654SLei Zhang   // TODO: We are unconditionally converting the bitwidth here,
249*01178654SLei Zhang   // this might be okay for non-interface types (i.e., types used in
250*01178654SLei Zhang   // Private/Function storage classes), but not for interface types (i.e.,
251*01178654SLei Zhang   // types used in StorageBuffer/Uniform/PushConstant/etc. storage classes).
252*01178654SLei Zhang   // This is because the later actually affects the ABI contract with the
253*01178654SLei Zhang   // runtime. So we may want to expose a control on SPIRVTypeConverter to fail
254*01178654SLei Zhang   // conversion if we cannot change there.
255*01178654SLei Zhang 
256*01178654SLei Zhang   if (auto floatType = type.dyn_cast<FloatType>()) {
257*01178654SLei Zhang     LLVM_DEBUG(llvm::dbgs() << type << " converted to 32-bit for SPIR-V\n");
258*01178654SLei Zhang     return Builder(targetEnv.getContext()).getF32Type();
259*01178654SLei Zhang   }
260*01178654SLei Zhang 
261*01178654SLei Zhang   auto intType = type.cast<IntegerType>();
262*01178654SLei Zhang   LLVM_DEBUG(llvm::dbgs() << type << " converted to 32-bit for SPIR-V\n");
263*01178654SLei Zhang   return IntegerType::get(/*width=*/32, intType.getSignedness(),
264*01178654SLei Zhang                           targetEnv.getContext());
265*01178654SLei Zhang }
266*01178654SLei Zhang 
267*01178654SLei Zhang /// Converts a vector `type` to a suitable type under the given `targetEnv`.
268*01178654SLei Zhang static Optional<Type>
269*01178654SLei Zhang convertVectorType(const spirv::TargetEnv &targetEnv, VectorType type,
270*01178654SLei Zhang                   Optional<spirv::StorageClass> storageClass = {}) {
271*01178654SLei Zhang   if (!spirv::CompositeType::isValid(type)) {
272*01178654SLei Zhang     // TODO: One-element vector types can be translated into scalar
273*01178654SLei Zhang     // types. Vector types with more than four elements can be translated into
274*01178654SLei Zhang     // array types.
275*01178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
276*01178654SLei Zhang                << type << " illegal: 1- and > 4-element unimplemented\n");
277*01178654SLei Zhang     return llvm::None;
278*01178654SLei Zhang   }
279*01178654SLei Zhang 
280*01178654SLei Zhang   // Get extension and capability requirements for the given type.
281*01178654SLei Zhang   SmallVector<ArrayRef<spirv::Extension>, 1> extensions;
282*01178654SLei Zhang   SmallVector<ArrayRef<spirv::Capability>, 2> capabilities;
283*01178654SLei Zhang   type.cast<spirv::CompositeType>().getExtensions(extensions, storageClass);
284*01178654SLei Zhang   type.cast<spirv::CompositeType>().getCapabilities(capabilities, storageClass);
285*01178654SLei Zhang 
286*01178654SLei Zhang   // If all requirements are met, then we can accept this type as-is.
287*01178654SLei Zhang   if (succeeded(checkCapabilityRequirements(type, targetEnv, capabilities)) &&
288*01178654SLei Zhang       succeeded(checkExtensionRequirements(type, targetEnv, extensions)))
289*01178654SLei Zhang     return type;
290*01178654SLei Zhang 
291*01178654SLei Zhang   auto elementType = convertScalarType(
292*01178654SLei Zhang       targetEnv, type.getElementType().cast<spirv::ScalarType>(), storageClass);
293*01178654SLei Zhang   if (elementType)
294*01178654SLei Zhang     return VectorType::get(type.getShape(), *elementType);
295*01178654SLei Zhang   return llvm::None;
296*01178654SLei Zhang }
297*01178654SLei Zhang 
298*01178654SLei Zhang /// Converts a tensor `type` to a suitable type under the given `targetEnv`.
299*01178654SLei Zhang ///
300*01178654SLei Zhang /// Note that this is mainly for lowering constant tensors.In SPIR-V one can
301*01178654SLei Zhang /// create composite constants with OpConstantComposite to embed relative large
302*01178654SLei Zhang /// constant values and use OpCompositeExtract and OpCompositeInsert to
303*01178654SLei Zhang /// manipulate, like what we do for vectors.
304*01178654SLei Zhang static Optional<Type> convertTensorType(const spirv::TargetEnv &targetEnv,
305*01178654SLei Zhang                                         TensorType type) {
306*01178654SLei Zhang   // TODO: Handle dynamic shapes.
307*01178654SLei Zhang   if (!type.hasStaticShape()) {
308*01178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
309*01178654SLei Zhang                << type << " illegal: dynamic shape unimplemented\n");
310*01178654SLei Zhang     return llvm::None;
311*01178654SLei Zhang   }
312*01178654SLei Zhang 
313*01178654SLei Zhang   auto scalarType = type.getElementType().dyn_cast<spirv::ScalarType>();
314*01178654SLei Zhang   if (!scalarType) {
315*01178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
316*01178654SLei Zhang                << type << " illegal: cannot convert non-scalar element type\n");
317*01178654SLei Zhang     return llvm::None;
318*01178654SLei Zhang   }
319*01178654SLei Zhang 
320*01178654SLei Zhang   Optional<int64_t> scalarSize = getTypeNumBytes(scalarType);
321*01178654SLei Zhang   Optional<int64_t> tensorSize = getTypeNumBytes(type);
322*01178654SLei Zhang   if (!scalarSize || !tensorSize) {
323*01178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
324*01178654SLei Zhang                << type << " illegal: cannot deduce element count\n");
325*01178654SLei Zhang     return llvm::None;
326*01178654SLei Zhang   }
327*01178654SLei Zhang 
328*01178654SLei Zhang   auto arrayElemCount = *tensorSize / *scalarSize;
329*01178654SLei Zhang   auto arrayElemType = convertScalarType(targetEnv, scalarType);
330*01178654SLei Zhang   if (!arrayElemType)
331*01178654SLei Zhang     return llvm::None;
332*01178654SLei Zhang   Optional<int64_t> arrayElemSize = getTypeNumBytes(*arrayElemType);
333*01178654SLei Zhang   if (!arrayElemSize) {
334*01178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
335*01178654SLei Zhang                << type << " illegal: cannot deduce converted element size\n");
336*01178654SLei Zhang     return llvm::None;
337*01178654SLei Zhang   }
338*01178654SLei Zhang 
339*01178654SLei Zhang   return spirv::ArrayType::get(*arrayElemType, arrayElemCount, *arrayElemSize);
340*01178654SLei Zhang }
341*01178654SLei Zhang 
342*01178654SLei Zhang static Optional<Type> convertMemrefType(const spirv::TargetEnv &targetEnv,
343*01178654SLei Zhang                                         MemRefType type) {
344*01178654SLei Zhang   Optional<spirv::StorageClass> storageClass =
345*01178654SLei Zhang       SPIRVTypeConverter::getStorageClassForMemorySpace(type.getMemorySpace());
346*01178654SLei Zhang   if (!storageClass) {
347*01178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
348*01178654SLei Zhang                << type << " illegal: cannot convert memory space\n");
349*01178654SLei Zhang     return llvm::None;
350*01178654SLei Zhang   }
351*01178654SLei Zhang 
352*01178654SLei Zhang   Optional<Type> arrayElemType;
353*01178654SLei Zhang   Type elementType = type.getElementType();
354*01178654SLei Zhang   if (auto vecType = elementType.dyn_cast<VectorType>()) {
355*01178654SLei Zhang     arrayElemType = convertVectorType(targetEnv, vecType, storageClass);
356*01178654SLei Zhang   } else if (auto scalarType = elementType.dyn_cast<spirv::ScalarType>()) {
357*01178654SLei Zhang     arrayElemType = convertScalarType(targetEnv, scalarType, storageClass);
358*01178654SLei Zhang   } else {
359*01178654SLei Zhang     LLVM_DEBUG(
360*01178654SLei Zhang         llvm::dbgs()
361*01178654SLei Zhang         << type
362*01178654SLei Zhang         << " unhandled: can only convert scalar or vector element type\n");
363*01178654SLei Zhang     return llvm::None;
364*01178654SLei Zhang   }
365*01178654SLei Zhang   if (!arrayElemType)
366*01178654SLei Zhang     return llvm::None;
367*01178654SLei Zhang 
368*01178654SLei Zhang   Optional<int64_t> elementSize = getTypeNumBytes(elementType);
369*01178654SLei Zhang   if (!elementSize) {
370*01178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
371*01178654SLei Zhang                << type << " illegal: cannot deduce element size\n");
372*01178654SLei Zhang     return llvm::None;
373*01178654SLei Zhang   }
374*01178654SLei Zhang 
375*01178654SLei Zhang   if (!type.hasStaticShape()) {
376*01178654SLei Zhang     auto arrayType = spirv::RuntimeArrayType::get(*arrayElemType, *elementSize);
377*01178654SLei Zhang     // Wrap in a struct to satisfy Vulkan interface requirements.
378*01178654SLei Zhang     auto structType = spirv::StructType::get(arrayType, 0);
379*01178654SLei Zhang     return spirv::PointerType::get(structType, *storageClass);
380*01178654SLei Zhang   }
381*01178654SLei Zhang 
382*01178654SLei Zhang   Optional<int64_t> memrefSize = getTypeNumBytes(type);
383*01178654SLei Zhang   if (!memrefSize) {
384*01178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
385*01178654SLei Zhang                << type << " illegal: cannot deduce element count\n");
386*01178654SLei Zhang     return llvm::None;
387*01178654SLei Zhang   }
388*01178654SLei Zhang 
389*01178654SLei Zhang   auto arrayElemCount = *memrefSize / *elementSize;
390*01178654SLei Zhang 
391*01178654SLei Zhang   Optional<int64_t> arrayElemSize = getTypeNumBytes(*arrayElemType);
392*01178654SLei Zhang   if (!arrayElemSize) {
393*01178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
394*01178654SLei Zhang                << type << " illegal: cannot deduce converted element size\n");
395*01178654SLei Zhang     return llvm::None;
396*01178654SLei Zhang   }
397*01178654SLei Zhang 
398*01178654SLei Zhang   auto arrayType =
399*01178654SLei Zhang       spirv::ArrayType::get(*arrayElemType, arrayElemCount, *arrayElemSize);
400*01178654SLei Zhang 
401*01178654SLei Zhang   // Wrap in a struct to satisfy Vulkan interface requirements. Memrefs with
402*01178654SLei Zhang   // workgroup storage class do not need the struct to be laid out explicitly.
403*01178654SLei Zhang   auto structType = *storageClass == spirv::StorageClass::Workgroup
404*01178654SLei Zhang                         ? spirv::StructType::get(arrayType)
405*01178654SLei Zhang                         : spirv::StructType::get(arrayType, 0);
406*01178654SLei Zhang   return spirv::PointerType::get(structType, *storageClass);
407*01178654SLei Zhang }
408*01178654SLei Zhang 
409*01178654SLei Zhang SPIRVTypeConverter::SPIRVTypeConverter(spirv::TargetEnvAttr targetAttr)
410*01178654SLei Zhang     : targetEnv(targetAttr) {
411*01178654SLei Zhang   // Add conversions. The order matters here: later ones will be tried earlier.
412*01178654SLei Zhang 
413*01178654SLei Zhang   // All other cases failed. Then we cannot convert this type.
414*01178654SLei Zhang   addConversion([](Type type) { return llvm::None; });
415*01178654SLei Zhang 
416*01178654SLei Zhang   // Allow all SPIR-V dialect specific types. This assumes all builtin types
417*01178654SLei Zhang   // adopted in the SPIR-V dialect (i.e., IntegerType, FloatType, VectorType)
418*01178654SLei Zhang   // were tried before.
419*01178654SLei Zhang   //
420*01178654SLei Zhang   // TODO: this assumes that the SPIR-V types are valid to use in
421*01178654SLei Zhang   // the given target environment, which should be the case if the whole
422*01178654SLei Zhang   // pipeline is driven by the same target environment. Still, we probably still
423*01178654SLei Zhang   // want to validate and convert to be safe.
424*01178654SLei Zhang   addConversion([](spirv::SPIRVType type) { return type; });
425*01178654SLei Zhang 
426*01178654SLei Zhang   addConversion([](IndexType indexType) {
427*01178654SLei Zhang     return SPIRVTypeConverter::getIndexType(indexType.getContext());
428*01178654SLei Zhang   });
429*01178654SLei Zhang 
430*01178654SLei Zhang   addConversion([this](IntegerType intType) -> Optional<Type> {
431*01178654SLei Zhang     if (auto scalarType = intType.dyn_cast<spirv::ScalarType>())
432*01178654SLei Zhang       return convertScalarType(targetEnv, scalarType);
433*01178654SLei Zhang     return llvm::None;
434*01178654SLei Zhang   });
435*01178654SLei Zhang 
436*01178654SLei Zhang   addConversion([this](FloatType floatType) -> Optional<Type> {
437*01178654SLei Zhang     if (auto scalarType = floatType.dyn_cast<spirv::ScalarType>())
438*01178654SLei Zhang       return convertScalarType(targetEnv, scalarType);
439*01178654SLei Zhang     return llvm::None;
440*01178654SLei Zhang   });
441*01178654SLei Zhang 
442*01178654SLei Zhang   addConversion([this](VectorType vectorType) {
443*01178654SLei Zhang     return convertVectorType(targetEnv, vectorType);
444*01178654SLei Zhang   });
445*01178654SLei Zhang 
446*01178654SLei Zhang   addConversion([this](TensorType tensorType) {
447*01178654SLei Zhang     return convertTensorType(targetEnv, tensorType);
448*01178654SLei Zhang   });
449*01178654SLei Zhang 
450*01178654SLei Zhang   addConversion([this](MemRefType memRefType) {
451*01178654SLei Zhang     return convertMemrefType(targetEnv, memRefType);
452*01178654SLei Zhang   });
453*01178654SLei Zhang }
454*01178654SLei Zhang 
455*01178654SLei Zhang //===----------------------------------------------------------------------===//
456*01178654SLei Zhang // FuncOp Conversion Patterns
457*01178654SLei Zhang //===----------------------------------------------------------------------===//
458*01178654SLei Zhang 
459*01178654SLei Zhang namespace {
460*01178654SLei Zhang /// A pattern for rewriting function signature to convert arguments of functions
461*01178654SLei Zhang /// to be of valid SPIR-V types.
462*01178654SLei Zhang class FuncOpConversion final : public SPIRVOpLowering<FuncOp> {
463*01178654SLei Zhang public:
464*01178654SLei Zhang   using SPIRVOpLowering<FuncOp>::SPIRVOpLowering;
465*01178654SLei Zhang 
466*01178654SLei Zhang   LogicalResult
467*01178654SLei Zhang   matchAndRewrite(FuncOp funcOp, ArrayRef<Value> operands,
468*01178654SLei Zhang                   ConversionPatternRewriter &rewriter) const override;
469*01178654SLei Zhang };
470*01178654SLei Zhang } // namespace
471*01178654SLei Zhang 
472*01178654SLei Zhang LogicalResult
473*01178654SLei Zhang FuncOpConversion::matchAndRewrite(FuncOp funcOp, ArrayRef<Value> operands,
474*01178654SLei Zhang                                   ConversionPatternRewriter &rewriter) const {
475*01178654SLei Zhang   auto fnType = funcOp.getType();
476*01178654SLei Zhang   // TODO: support converting functions with one result.
477*01178654SLei Zhang   if (fnType.getNumResults())
478*01178654SLei Zhang     return failure();
479*01178654SLei Zhang 
480*01178654SLei Zhang   TypeConverter::SignatureConversion signatureConverter(fnType.getNumInputs());
481*01178654SLei Zhang   for (auto argType : enumerate(funcOp.getType().getInputs())) {
482*01178654SLei Zhang     auto convertedType = typeConverter.convertType(argType.value());
483*01178654SLei Zhang     if (!convertedType)
484*01178654SLei Zhang       return failure();
485*01178654SLei Zhang     signatureConverter.addInputs(argType.index(), convertedType);
486*01178654SLei Zhang   }
487*01178654SLei Zhang 
488*01178654SLei Zhang   // Create the converted spv.func op.
489*01178654SLei Zhang   auto newFuncOp = rewriter.create<spirv::FuncOp>(
490*01178654SLei Zhang       funcOp.getLoc(), funcOp.getName(),
491*01178654SLei Zhang       rewriter.getFunctionType(signatureConverter.getConvertedTypes(),
492*01178654SLei Zhang                                llvm::None));
493*01178654SLei Zhang 
494*01178654SLei Zhang   // Copy over all attributes other than the function name and type.
495*01178654SLei Zhang   for (const auto &namedAttr : funcOp.getAttrs()) {
496*01178654SLei Zhang     if (namedAttr.first != impl::getTypeAttrName() &&
497*01178654SLei Zhang         namedAttr.first != SymbolTable::getSymbolAttrName())
498*01178654SLei Zhang       newFuncOp->setAttr(namedAttr.first, namedAttr.second);
499*01178654SLei Zhang   }
500*01178654SLei Zhang 
501*01178654SLei Zhang   rewriter.inlineRegionBefore(funcOp.getBody(), newFuncOp.getBody(),
502*01178654SLei Zhang                               newFuncOp.end());
503*01178654SLei Zhang   if (failed(rewriter.convertRegionTypes(&newFuncOp.getBody(), typeConverter,
504*01178654SLei Zhang                                          &signatureConverter)))
505*01178654SLei Zhang     return failure();
506*01178654SLei Zhang   rewriter.eraseOp(funcOp);
507*01178654SLei Zhang   return success();
508*01178654SLei Zhang }
509*01178654SLei Zhang 
510*01178654SLei Zhang void mlir::populateBuiltinFuncToSPIRVPatterns(
511*01178654SLei Zhang     MLIRContext *context, SPIRVTypeConverter &typeConverter,
512*01178654SLei Zhang     OwningRewritePatternList &patterns) {
513*01178654SLei Zhang   patterns.insert<FuncOpConversion>(context, typeConverter);
514*01178654SLei Zhang }
515*01178654SLei Zhang 
516*01178654SLei Zhang //===----------------------------------------------------------------------===//
517*01178654SLei Zhang // Builtin Variables
518*01178654SLei Zhang //===----------------------------------------------------------------------===//
519*01178654SLei Zhang 
520*01178654SLei Zhang static spirv::GlobalVariableOp getBuiltinVariable(Block &body,
521*01178654SLei Zhang                                                   spirv::BuiltIn builtin) {
522*01178654SLei Zhang   // Look through all global variables in the given `body` block and check if
523*01178654SLei Zhang   // there is a spv.globalVariable that has the same `builtin` attribute.
524*01178654SLei Zhang   for (auto varOp : body.getOps<spirv::GlobalVariableOp>()) {
525*01178654SLei Zhang     if (auto builtinAttr = varOp->getAttrOfType<StringAttr>(
526*01178654SLei Zhang             spirv::SPIRVDialect::getAttributeName(
527*01178654SLei Zhang                 spirv::Decoration::BuiltIn))) {
528*01178654SLei Zhang       auto varBuiltIn = spirv::symbolizeBuiltIn(builtinAttr.getValue());
529*01178654SLei Zhang       if (varBuiltIn && varBuiltIn.getValue() == builtin) {
530*01178654SLei Zhang         return varOp;
531*01178654SLei Zhang       }
532*01178654SLei Zhang     }
533*01178654SLei Zhang   }
534*01178654SLei Zhang   return nullptr;
535*01178654SLei Zhang }
536*01178654SLei Zhang 
537*01178654SLei Zhang /// Gets name of global variable for a builtin.
538*01178654SLei Zhang static std::string getBuiltinVarName(spirv::BuiltIn builtin) {
539*01178654SLei Zhang   return std::string("__builtin_var_") + stringifyBuiltIn(builtin).str() + "__";
540*01178654SLei Zhang }
541*01178654SLei Zhang 
542*01178654SLei Zhang /// Gets or inserts a global variable for a builtin within `body` block.
543*01178654SLei Zhang static spirv::GlobalVariableOp
544*01178654SLei Zhang getOrInsertBuiltinVariable(Block &body, Location loc, spirv::BuiltIn builtin,
545*01178654SLei Zhang                            OpBuilder &builder) {
546*01178654SLei Zhang   if (auto varOp = getBuiltinVariable(body, builtin))
547*01178654SLei Zhang     return varOp;
548*01178654SLei Zhang 
549*01178654SLei Zhang   OpBuilder::InsertionGuard guard(builder);
550*01178654SLei Zhang   builder.setInsertionPointToStart(&body);
551*01178654SLei Zhang 
552*01178654SLei Zhang   spirv::GlobalVariableOp newVarOp;
553*01178654SLei Zhang   switch (builtin) {
554*01178654SLei Zhang   case spirv::BuiltIn::NumWorkgroups:
555*01178654SLei Zhang   case spirv::BuiltIn::WorkgroupSize:
556*01178654SLei Zhang   case spirv::BuiltIn::WorkgroupId:
557*01178654SLei Zhang   case spirv::BuiltIn::LocalInvocationId:
558*01178654SLei Zhang   case spirv::BuiltIn::GlobalInvocationId: {
559*01178654SLei Zhang     auto ptrType = spirv::PointerType::get(
560*01178654SLei Zhang         VectorType::get({3}, builder.getIntegerType(32)),
561*01178654SLei Zhang         spirv::StorageClass::Input);
562*01178654SLei Zhang     std::string name = getBuiltinVarName(builtin);
563*01178654SLei Zhang     newVarOp =
564*01178654SLei Zhang         builder.create<spirv::GlobalVariableOp>(loc, ptrType, name, builtin);
565*01178654SLei Zhang     break;
566*01178654SLei Zhang   }
567*01178654SLei Zhang   case spirv::BuiltIn::SubgroupId:
568*01178654SLei Zhang   case spirv::BuiltIn::NumSubgroups:
569*01178654SLei Zhang   case spirv::BuiltIn::SubgroupSize: {
570*01178654SLei Zhang     auto ptrType = spirv::PointerType::get(builder.getIntegerType(32),
571*01178654SLei Zhang                                            spirv::StorageClass::Input);
572*01178654SLei Zhang     std::string name = getBuiltinVarName(builtin);
573*01178654SLei Zhang     newVarOp =
574*01178654SLei Zhang         builder.create<spirv::GlobalVariableOp>(loc, ptrType, name, builtin);
575*01178654SLei Zhang     break;
576*01178654SLei Zhang   }
577*01178654SLei Zhang   default:
578*01178654SLei Zhang     emitError(loc, "unimplemented builtin variable generation for ")
579*01178654SLei Zhang         << stringifyBuiltIn(builtin);
580*01178654SLei Zhang   }
581*01178654SLei Zhang   return newVarOp;
582*01178654SLei Zhang }
583*01178654SLei Zhang 
584*01178654SLei Zhang Value mlir::spirv::getBuiltinVariableValue(Operation *op,
585*01178654SLei Zhang                                            spirv::BuiltIn builtin,
586*01178654SLei Zhang                                            OpBuilder &builder) {
587*01178654SLei Zhang   Operation *parent = SymbolTable::getNearestSymbolTable(op->getParentOp());
588*01178654SLei Zhang   if (!parent) {
589*01178654SLei Zhang     op->emitError("expected operation to be within a module-like op");
590*01178654SLei Zhang     return nullptr;
591*01178654SLei Zhang   }
592*01178654SLei Zhang 
593*01178654SLei Zhang   spirv::GlobalVariableOp varOp = getOrInsertBuiltinVariable(
594*01178654SLei Zhang       *parent->getRegion(0).begin(), op->getLoc(), builtin, builder);
595*01178654SLei Zhang   Value ptr = builder.create<spirv::AddressOfOp>(op->getLoc(), varOp);
596*01178654SLei Zhang   return builder.create<spirv::LoadOp>(op->getLoc(), ptr);
597*01178654SLei Zhang }
598*01178654SLei Zhang 
599*01178654SLei Zhang //===----------------------------------------------------------------------===//
600*01178654SLei Zhang // Index calculation
601*01178654SLei Zhang //===----------------------------------------------------------------------===//
602*01178654SLei Zhang 
603*01178654SLei Zhang spirv::AccessChainOp mlir::spirv::getElementPtr(
604*01178654SLei Zhang     SPIRVTypeConverter &typeConverter, MemRefType baseType, Value basePtr,
605*01178654SLei Zhang     ValueRange indices, Location loc, OpBuilder &builder) {
606*01178654SLei Zhang   // Get base and offset of the MemRefType and verify they are static.
607*01178654SLei Zhang 
608*01178654SLei Zhang   int64_t offset;
609*01178654SLei Zhang   SmallVector<int64_t, 4> strides;
610*01178654SLei Zhang   if (failed(getStridesAndOffset(baseType, strides, offset)) ||
611*01178654SLei Zhang       llvm::is_contained(strides, MemRefType::getDynamicStrideOrOffset()) ||
612*01178654SLei Zhang       offset == MemRefType::getDynamicStrideOrOffset()) {
613*01178654SLei Zhang     return nullptr;
614*01178654SLei Zhang   }
615*01178654SLei Zhang 
616*01178654SLei Zhang   auto indexType = typeConverter.getIndexType(builder.getContext());
617*01178654SLei Zhang 
618*01178654SLei Zhang   SmallVector<Value, 2> linearizedIndices;
619*01178654SLei Zhang   // Add a '0' at the start to index into the struct.
620*01178654SLei Zhang   auto zero = spirv::ConstantOp::getZero(indexType, loc, builder);
621*01178654SLei Zhang   linearizedIndices.push_back(zero);
622*01178654SLei Zhang 
623*01178654SLei Zhang   if (baseType.getRank() == 0) {
624*01178654SLei Zhang     linearizedIndices.push_back(zero);
625*01178654SLei Zhang   } else {
626*01178654SLei Zhang     // TODO: Instead of this logic, use affine.apply and add patterns for
627*01178654SLei Zhang     // lowering affine.apply to standard ops. These will get lowered to SPIR-V
628*01178654SLei Zhang     // ops by the DialectConversion framework.
629*01178654SLei Zhang     Value ptrLoc = builder.create<spirv::ConstantOp>(
630*01178654SLei Zhang         loc, indexType, IntegerAttr::get(indexType, offset));
631*01178654SLei Zhang     assert(indices.size() == strides.size() &&
632*01178654SLei Zhang            "must provide indices for all dimensions");
633*01178654SLei Zhang     for (auto index : llvm::enumerate(indices)) {
634*01178654SLei Zhang       Value strideVal = builder.create<spirv::ConstantOp>(
635*01178654SLei Zhang           loc, indexType, IntegerAttr::get(indexType, strides[index.index()]));
636*01178654SLei Zhang       Value update =
637*01178654SLei Zhang           builder.create<spirv::IMulOp>(loc, strideVal, index.value());
638*01178654SLei Zhang       ptrLoc = builder.create<spirv::IAddOp>(loc, ptrLoc, update);
639*01178654SLei Zhang     }
640*01178654SLei Zhang     linearizedIndices.push_back(ptrLoc);
641*01178654SLei Zhang   }
642*01178654SLei Zhang   return builder.create<spirv::AccessChainOp>(loc, basePtr, linearizedIndices);
643*01178654SLei Zhang }
644*01178654SLei Zhang 
645*01178654SLei Zhang //===----------------------------------------------------------------------===//
646*01178654SLei Zhang // Set ABI attributes for lowering entry functions.
647*01178654SLei Zhang //===----------------------------------------------------------------------===//
648*01178654SLei Zhang 
649*01178654SLei Zhang LogicalResult
650*01178654SLei Zhang mlir::spirv::setABIAttrs(spirv::FuncOp funcOp,
651*01178654SLei Zhang                          spirv::EntryPointABIAttr entryPointInfo,
652*01178654SLei Zhang                          ArrayRef<spirv::InterfaceVarABIAttr> argABIInfo) {
653*01178654SLei Zhang   // Set the attributes for argument and the function.
654*01178654SLei Zhang   StringRef argABIAttrName = spirv::getInterfaceVarABIAttrName();
655*01178654SLei Zhang   for (auto argIndex : llvm::seq<unsigned>(0, argABIInfo.size())) {
656*01178654SLei Zhang     funcOp.setArgAttr(argIndex, argABIAttrName, argABIInfo[argIndex]);
657*01178654SLei Zhang   }
658*01178654SLei Zhang   funcOp->setAttr(spirv::getEntryPointABIAttrName(), entryPointInfo);
659*01178654SLei Zhang   return success();
660*01178654SLei Zhang }
661*01178654SLei Zhang 
662*01178654SLei Zhang //===----------------------------------------------------------------------===//
663*01178654SLei Zhang // SPIR-V ConversionTarget
664*01178654SLei Zhang //===----------------------------------------------------------------------===//
665*01178654SLei Zhang 
666*01178654SLei Zhang std::unique_ptr<spirv::SPIRVConversionTarget>
667*01178654SLei Zhang spirv::SPIRVConversionTarget::get(spirv::TargetEnvAttr targetAttr) {
668*01178654SLei Zhang   std::unique_ptr<SPIRVConversionTarget> target(
669*01178654SLei Zhang       // std::make_unique does not work here because the constructor is private.
670*01178654SLei Zhang       new SPIRVConversionTarget(targetAttr));
671*01178654SLei Zhang   SPIRVConversionTarget *targetPtr = target.get();
672*01178654SLei Zhang   target->addDynamicallyLegalDialect<SPIRVDialect>(
673*01178654SLei Zhang       // We need to capture the raw pointer here because it is stable:
674*01178654SLei Zhang       // target will be destroyed once this function is returned.
675*01178654SLei Zhang       [targetPtr](Operation *op) { return targetPtr->isLegalOp(op); });
676*01178654SLei Zhang   return target;
677*01178654SLei Zhang }
678*01178654SLei Zhang 
679*01178654SLei Zhang spirv::SPIRVConversionTarget::SPIRVConversionTarget(
680*01178654SLei Zhang     spirv::TargetEnvAttr targetAttr)
681*01178654SLei Zhang     : ConversionTarget(*targetAttr.getContext()), targetEnv(targetAttr) {}
682*01178654SLei Zhang 
683*01178654SLei Zhang bool spirv::SPIRVConversionTarget::isLegalOp(Operation *op) {
684*01178654SLei Zhang   // Make sure this op is available at the given version. Ops not implementing
685*01178654SLei Zhang   // QueryMinVersionInterface/QueryMaxVersionInterface are available to all
686*01178654SLei Zhang   // SPIR-V versions.
687*01178654SLei Zhang   if (auto minVersion = dyn_cast<spirv::QueryMinVersionInterface>(op))
688*01178654SLei Zhang     if (minVersion.getMinVersion() > this->targetEnv.getVersion()) {
689*01178654SLei Zhang       LLVM_DEBUG(llvm::dbgs()
690*01178654SLei Zhang                  << op->getName() << " illegal: requiring min version "
691*01178654SLei Zhang                  << spirv::stringifyVersion(minVersion.getMinVersion())
692*01178654SLei Zhang                  << "\n");
693*01178654SLei Zhang       return false;
694*01178654SLei Zhang     }
695*01178654SLei Zhang   if (auto maxVersion = dyn_cast<spirv::QueryMaxVersionInterface>(op))
696*01178654SLei Zhang     if (maxVersion.getMaxVersion() < this->targetEnv.getVersion()) {
697*01178654SLei Zhang       LLVM_DEBUG(llvm::dbgs()
698*01178654SLei Zhang                  << op->getName() << " illegal: requiring max version "
699*01178654SLei Zhang                  << spirv::stringifyVersion(maxVersion.getMaxVersion())
700*01178654SLei Zhang                  << "\n");
701*01178654SLei Zhang       return false;
702*01178654SLei Zhang     }
703*01178654SLei Zhang 
704*01178654SLei Zhang   // Make sure this op's required extensions are allowed to use. Ops not
705*01178654SLei Zhang   // implementing QueryExtensionInterface do not require extensions to be
706*01178654SLei Zhang   // available.
707*01178654SLei Zhang   if (auto extensions = dyn_cast<spirv::QueryExtensionInterface>(op))
708*01178654SLei Zhang     if (failed(checkExtensionRequirements(op->getName(), this->targetEnv,
709*01178654SLei Zhang                                           extensions.getExtensions())))
710*01178654SLei Zhang       return false;
711*01178654SLei Zhang 
712*01178654SLei Zhang   // Make sure this op's required extensions are allowed to use. Ops not
713*01178654SLei Zhang   // implementing QueryCapabilityInterface do not require capabilities to be
714*01178654SLei Zhang   // available.
715*01178654SLei Zhang   if (auto capabilities = dyn_cast<spirv::QueryCapabilityInterface>(op))
716*01178654SLei Zhang     if (failed(checkCapabilityRequirements(op->getName(), this->targetEnv,
717*01178654SLei Zhang                                            capabilities.getCapabilities())))
718*01178654SLei Zhang       return false;
719*01178654SLei Zhang 
720*01178654SLei Zhang   SmallVector<Type, 4> valueTypes;
721*01178654SLei Zhang   valueTypes.append(op->operand_type_begin(), op->operand_type_end());
722*01178654SLei Zhang   valueTypes.append(op->result_type_begin(), op->result_type_end());
723*01178654SLei Zhang 
724*01178654SLei Zhang   // Special treatment for global variables, whose type requirements are
725*01178654SLei Zhang   // conveyed by type attributes.
726*01178654SLei Zhang   if (auto globalVar = dyn_cast<spirv::GlobalVariableOp>(op))
727*01178654SLei Zhang     valueTypes.push_back(globalVar.type());
728*01178654SLei Zhang 
729*01178654SLei Zhang   // Make sure the op's operands/results use types that are allowed by the
730*01178654SLei Zhang   // target environment.
731*01178654SLei Zhang   SmallVector<ArrayRef<spirv::Extension>, 4> typeExtensions;
732*01178654SLei Zhang   SmallVector<ArrayRef<spirv::Capability>, 8> typeCapabilities;
733*01178654SLei Zhang   for (Type valueType : valueTypes) {
734*01178654SLei Zhang     typeExtensions.clear();
735*01178654SLei Zhang     valueType.cast<spirv::SPIRVType>().getExtensions(typeExtensions);
736*01178654SLei Zhang     if (failed(checkExtensionRequirements(op->getName(), this->targetEnv,
737*01178654SLei Zhang                                           typeExtensions)))
738*01178654SLei Zhang       return false;
739*01178654SLei Zhang 
740*01178654SLei Zhang     typeCapabilities.clear();
741*01178654SLei Zhang     valueType.cast<spirv::SPIRVType>().getCapabilities(typeCapabilities);
742*01178654SLei Zhang     if (failed(checkCapabilityRequirements(op->getName(), this->targetEnv,
743*01178654SLei Zhang                                            typeCapabilities)))
744*01178654SLei Zhang       return false;
745*01178654SLei Zhang   }
746*01178654SLei Zhang 
747*01178654SLei Zhang   return true;
748*01178654SLei Zhang }
749