1 //===- SPIRVOps.cpp - MLIR SPIR-V operations ------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the operations in the SPIR-V dialect.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
14 
15 #include "mlir/Dialect/SPIRV/IR/ParserUtils.h"
16 #include "mlir/Dialect/SPIRV/IR/SPIRVAttributes.h"
17 #include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h"
18 #include "mlir/Dialect/SPIRV/IR/SPIRVOpTraits.h"
19 #include "mlir/Dialect/SPIRV/IR/SPIRVTypes.h"
20 #include "mlir/Dialect/SPIRV/IR/TargetAndABI.h"
21 #include "mlir/IR/Builders.h"
22 #include "mlir/IR/BuiltinOps.h"
23 #include "mlir/IR/BuiltinTypes.h"
24 #include "mlir/IR/FunctionImplementation.h"
25 #include "mlir/IR/OpDefinition.h"
26 #include "mlir/IR/OpImplementation.h"
27 #include "mlir/IR/TypeUtilities.h"
28 #include "mlir/Interfaces/CallInterfaces.h"
29 #include "llvm/ADT/APFloat.h"
30 #include "llvm/ADT/APInt.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/ADT/bit.h"
33 
34 using namespace mlir;
35 
36 // TODO: generate these strings using ODS.
37 static constexpr const char kMemoryAccessAttrName[] = "memory_access";
38 static constexpr const char kSourceMemoryAccessAttrName[] =
39     "source_memory_access";
40 static constexpr const char kAlignmentAttrName[] = "alignment";
41 static constexpr const char kSourceAlignmentAttrName[] = "source_alignment";
42 static constexpr const char kBranchWeightAttrName[] = "branch_weights";
43 static constexpr const char kCallee[] = "callee";
44 static constexpr const char kClusterSize[] = "cluster_size";
45 static constexpr const char kControl[] = "control";
46 static constexpr const char kDefaultValueAttrName[] = "default_value";
47 static constexpr const char kExecutionScopeAttrName[] = "execution_scope";
48 static constexpr const char kEqualSemanticsAttrName[] = "equal_semantics";
49 static constexpr const char kFnNameAttrName[] = "fn";
50 static constexpr const char kGroupOperationAttrName[] = "group_operation";
51 static constexpr const char kIndicesAttrName[] = "indices";
52 static constexpr const char kInitializerAttrName[] = "initializer";
53 static constexpr const char kInterfaceAttrName[] = "interface";
54 static constexpr const char kMemoryScopeAttrName[] = "memory_scope";
55 static constexpr const char kSemanticsAttrName[] = "semantics";
56 static constexpr const char kSpecIdAttrName[] = "spec_id";
57 static constexpr const char kTypeAttrName[] = "type";
58 static constexpr const char kUnequalSemanticsAttrName[] = "unequal_semantics";
59 static constexpr const char kValueAttrName[] = "value";
60 static constexpr const char kValuesAttrName[] = "values";
61 static constexpr const char kCompositeSpecConstituentsName[] = "constituents";
62 
63 //===----------------------------------------------------------------------===//
64 // Common utility functions
65 //===----------------------------------------------------------------------===//
66 
67 /// Returns true if the given op is a function-like op or nested in a
68 /// function-like op without a module-like op in the middle.
69 static bool isNestedInFunctionLikeOp(Operation *op) {
70   if (!op)
71     return false;
72   if (op->hasTrait<OpTrait::SymbolTable>())
73     return false;
74   if (op->hasTrait<OpTrait::FunctionLike>())
75     return true;
76   return isNestedInFunctionLikeOp(op->getParentOp());
77 }
78 
79 /// Returns true if the given op is an module-like op that maintains a symbol
80 /// table.
81 static bool isDirectInModuleLikeOp(Operation *op) {
82   return op && op->hasTrait<OpTrait::SymbolTable>();
83 }
84 
85 static LogicalResult extractValueFromConstOp(Operation *op, int32_t &value) {
86   auto constOp = dyn_cast_or_null<spirv::ConstantOp>(op);
87   if (!constOp) {
88     return failure();
89   }
90   auto valueAttr = constOp.value();
91   auto integerValueAttr = valueAttr.dyn_cast<IntegerAttr>();
92   if (!integerValueAttr) {
93     return failure();
94   }
95   value = integerValueAttr.getInt();
96   return success();
97 }
98 
99 template <typename Ty>
100 static ArrayAttr
101 getStrArrayAttrForEnumList(Builder &builder, ArrayRef<Ty> enumValues,
102                            function_ref<StringRef(Ty)> stringifyFn) {
103   if (enumValues.empty()) {
104     return nullptr;
105   }
106   SmallVector<StringRef, 1> enumValStrs;
107   enumValStrs.reserve(enumValues.size());
108   for (auto val : enumValues) {
109     enumValStrs.emplace_back(stringifyFn(val));
110   }
111   return builder.getStrArrayAttr(enumValStrs);
112 }
113 
114 /// Parses the next string attribute in `parser` as an enumerant of the given
115 /// `EnumClass`.
116 template <typename EnumClass>
117 static ParseResult
118 parseEnumStrAttr(EnumClass &value, OpAsmParser &parser,
119                  StringRef attrName = spirv::attributeName<EnumClass>()) {
120   Attribute attrVal;
121   NamedAttrList attr;
122   auto loc = parser.getCurrentLocation();
123   if (parser.parseAttribute(attrVal, parser.getBuilder().getNoneType(),
124                             attrName, attr)) {
125     return failure();
126   }
127   if (!attrVal.isa<StringAttr>()) {
128     return parser.emitError(loc, "expected ")
129            << attrName << " attribute specified as string";
130   }
131   auto attrOptional =
132       spirv::symbolizeEnum<EnumClass>(attrVal.cast<StringAttr>().getValue());
133   if (!attrOptional) {
134     return parser.emitError(loc, "invalid ")
135            << attrName << " attribute specification: " << attrVal;
136   }
137   value = attrOptional.getValue();
138   return success();
139 }
140 
141 /// Parses the next string attribute in `parser` as an enumerant of the given
142 /// `EnumClass` and inserts the enumerant into `state` as an 32-bit integer
143 /// attribute with the enum class's name as attribute name.
144 template <typename EnumClass>
145 static ParseResult
146 parseEnumStrAttr(EnumClass &value, OpAsmParser &parser, OperationState &state,
147                  StringRef attrName = spirv::attributeName<EnumClass>()) {
148   if (parseEnumStrAttr(value, parser)) {
149     return failure();
150   }
151   state.addAttribute(attrName, parser.getBuilder().getI32IntegerAttr(
152                                    llvm::bit_cast<int32_t>(value)));
153   return success();
154 }
155 
156 /// Parses the next keyword in `parser` as an enumerant of the given `EnumClass`
157 /// and inserts the enumerant into `state` as an 32-bit integer attribute with
158 /// the enum class's name as attribute name.
159 template <typename EnumClass>
160 static ParseResult
161 parseEnumKeywordAttr(EnumClass &value, OpAsmParser &parser,
162                      OperationState &state,
163                      StringRef attrName = spirv::attributeName<EnumClass>()) {
164   if (parseEnumKeywordAttr(value, parser)) {
165     return failure();
166   }
167   state.addAttribute(attrName, parser.getBuilder().getI32IntegerAttr(
168                                    llvm::bit_cast<int32_t>(value)));
169   return success();
170 }
171 
172 /// Parses Function, Selection and Loop control attributes. If no control is
173 /// specified, "None" is used as a default.
174 template <typename EnumClass>
175 static ParseResult
176 parseControlAttribute(OpAsmParser &parser, OperationState &state,
177                       StringRef attrName = spirv::attributeName<EnumClass>()) {
178   if (succeeded(parser.parseOptionalKeyword(kControl))) {
179     EnumClass control;
180     if (parser.parseLParen() || parseEnumKeywordAttr(control, parser, state) ||
181         parser.parseRParen())
182       return failure();
183     return success();
184   }
185   // Set control to "None" otherwise.
186   Builder builder = parser.getBuilder();
187   state.addAttribute(attrName, builder.getI32IntegerAttr(0));
188   return success();
189 }
190 
191 /// Parses optional memory access attributes attached to a memory access
192 /// operand/pointer. Specifically, parses the following syntax:
193 ///     (`[` memory-access `]`)?
194 /// where:
195 ///     memory-access ::= `"None"` | `"Volatile"` | `"Aligned", `
196 ///         integer-literal | `"NonTemporal"`
197 static ParseResult parseMemoryAccessAttributes(OpAsmParser &parser,
198                                                OperationState &state) {
199   // Parse an optional list of attributes staring with '['
200   if (parser.parseOptionalLSquare()) {
201     // Nothing to do
202     return success();
203   }
204 
205   spirv::MemoryAccess memoryAccessAttr;
206   if (parseEnumStrAttr(memoryAccessAttr, parser, state,
207                        kMemoryAccessAttrName)) {
208     return failure();
209   }
210 
211   if (spirv::bitEnumContains(memoryAccessAttr, spirv::MemoryAccess::Aligned)) {
212     // Parse integer attribute for alignment.
213     Attribute alignmentAttr;
214     Type i32Type = parser.getBuilder().getIntegerType(32);
215     if (parser.parseComma() ||
216         parser.parseAttribute(alignmentAttr, i32Type, kAlignmentAttrName,
217                               state.attributes)) {
218       return failure();
219     }
220   }
221   return parser.parseRSquare();
222 }
223 
224 // TODO Make sure to merge this and the previous function into one template
225 // parameterized by memory access attribute name and alignment. Doing so now
226 // results in VS2017 in producing an internal error (at the call site) that's
227 // not detailed enough to understand what is happening.
228 static ParseResult parseSourceMemoryAccessAttributes(OpAsmParser &parser,
229                                                      OperationState &state) {
230   // Parse an optional list of attributes staring with '['
231   if (parser.parseOptionalLSquare()) {
232     // Nothing to do
233     return success();
234   }
235 
236   spirv::MemoryAccess memoryAccessAttr;
237   if (parseEnumStrAttr(memoryAccessAttr, parser, state,
238                        kSourceMemoryAccessAttrName)) {
239     return failure();
240   }
241 
242   if (spirv::bitEnumContains(memoryAccessAttr, spirv::MemoryAccess::Aligned)) {
243     // Parse integer attribute for alignment.
244     Attribute alignmentAttr;
245     Type i32Type = parser.getBuilder().getIntegerType(32);
246     if (parser.parseComma() ||
247         parser.parseAttribute(alignmentAttr, i32Type, kSourceAlignmentAttrName,
248                               state.attributes)) {
249       return failure();
250     }
251   }
252   return parser.parseRSquare();
253 }
254 
255 template <typename MemoryOpTy>
256 static void printMemoryAccessAttribute(
257     MemoryOpTy memoryOp, OpAsmPrinter &printer,
258     SmallVectorImpl<StringRef> &elidedAttrs,
259     Optional<spirv::MemoryAccess> memoryAccessAtrrValue = None,
260     Optional<uint32_t> alignmentAttrValue = None) {
261   // Print optional memory access attribute.
262   if (auto memAccess = (memoryAccessAtrrValue ? memoryAccessAtrrValue
263                                               : memoryOp.memory_access())) {
264     elidedAttrs.push_back(kMemoryAccessAttrName);
265 
266     printer << " [\"" << stringifyMemoryAccess(*memAccess) << "\"";
267 
268     if (spirv::bitEnumContains(*memAccess, spirv::MemoryAccess::Aligned)) {
269       // Print integer alignment attribute.
270       if (auto alignment = (alignmentAttrValue ? alignmentAttrValue
271                                                : memoryOp.alignment())) {
272         elidedAttrs.push_back(kAlignmentAttrName);
273         printer << ", " << alignment;
274       }
275     }
276     printer << "]";
277   }
278   elidedAttrs.push_back(spirv::attributeName<spirv::StorageClass>());
279 }
280 
281 // TODO Make sure to merge this and the previous function into one template
282 // parameterized by memory access attribute name and alignment. Doing so now
283 // results in VS2017 in producing an internal error (at the call site) that's
284 // not detailed enough to understand what is happening.
285 template <typename MemoryOpTy>
286 static void printSourceMemoryAccessAttribute(
287     MemoryOpTy memoryOp, OpAsmPrinter &printer,
288     SmallVectorImpl<StringRef> &elidedAttrs,
289     Optional<spirv::MemoryAccess> memoryAccessAtrrValue = None,
290     Optional<uint32_t> alignmentAttrValue = None) {
291 
292   printer << ", ";
293 
294   // Print optional memory access attribute.
295   if (auto memAccess = (memoryAccessAtrrValue ? memoryAccessAtrrValue
296                                               : memoryOp.memory_access())) {
297     elidedAttrs.push_back(kSourceMemoryAccessAttrName);
298 
299     printer << " [\"" << stringifyMemoryAccess(*memAccess) << "\"";
300 
301     if (spirv::bitEnumContains(*memAccess, spirv::MemoryAccess::Aligned)) {
302       // Print integer alignment attribute.
303       if (auto alignment = (alignmentAttrValue ? alignmentAttrValue
304                                                : memoryOp.alignment())) {
305         elidedAttrs.push_back(kSourceAlignmentAttrName);
306         printer << ", " << alignment;
307       }
308     }
309     printer << "]";
310   }
311   elidedAttrs.push_back(spirv::attributeName<spirv::StorageClass>());
312 }
313 
314 static LogicalResult verifyCastOp(Operation *op,
315                                   bool requireSameBitWidth = true,
316                                   bool skipBitWidthCheck = false) {
317   // Some CastOps have no limit on bit widths for result and operand type.
318   if (skipBitWidthCheck)
319     return success();
320 
321   Type operandType = op->getOperand(0).getType();
322   Type resultType = op->getResult(0).getType();
323 
324   // ODS checks that result type and operand type have the same shape.
325   if (auto vectorType = operandType.dyn_cast<VectorType>()) {
326     operandType = vectorType.getElementType();
327     resultType = resultType.cast<VectorType>().getElementType();
328   }
329 
330   if (auto coopMatrixType =
331           operandType.dyn_cast<spirv::CooperativeMatrixNVType>()) {
332     operandType = coopMatrixType.getElementType();
333     resultType =
334         resultType.cast<spirv::CooperativeMatrixNVType>().getElementType();
335   }
336 
337   auto operandTypeBitWidth = operandType.getIntOrFloatBitWidth();
338   auto resultTypeBitWidth = resultType.getIntOrFloatBitWidth();
339   auto isSameBitWidth = operandTypeBitWidth == resultTypeBitWidth;
340 
341   if (requireSameBitWidth) {
342     if (!isSameBitWidth) {
343       return op->emitOpError(
344                  "expected the same bit widths for operand type and result "
345                  "type, but provided ")
346              << operandType << " and " << resultType;
347     }
348     return success();
349   }
350 
351   if (isSameBitWidth) {
352     return op->emitOpError(
353                "expected the different bit widths for operand type and result "
354                "type, but provided ")
355            << operandType << " and " << resultType;
356   }
357   return success();
358 }
359 
360 template <typename MemoryOpTy>
361 static LogicalResult verifyMemoryAccessAttribute(MemoryOpTy memoryOp) {
362   // ODS checks for attributes values. Just need to verify that if the
363   // memory-access attribute is Aligned, then the alignment attribute must be
364   // present.
365   auto *op = memoryOp.getOperation();
366   auto memAccessAttr = op->getAttr(kMemoryAccessAttrName);
367   if (!memAccessAttr) {
368     // Alignment attribute shouldn't be present if memory access attribute is
369     // not present.
370     if (op->getAttr(kAlignmentAttrName)) {
371       return memoryOp.emitOpError(
372           "invalid alignment specification without aligned memory access "
373           "specification");
374     }
375     return success();
376   }
377 
378   auto memAccessVal = memAccessAttr.template cast<IntegerAttr>();
379   auto memAccess = spirv::symbolizeMemoryAccess(memAccessVal.getInt());
380 
381   if (!memAccess) {
382     return memoryOp.emitOpError("invalid memory access specifier: ")
383            << memAccessVal;
384   }
385 
386   if (spirv::bitEnumContains(*memAccess, spirv::MemoryAccess::Aligned)) {
387     if (!op->getAttr(kAlignmentAttrName)) {
388       return memoryOp.emitOpError("missing alignment value");
389     }
390   } else {
391     if (op->getAttr(kAlignmentAttrName)) {
392       return memoryOp.emitOpError(
393           "invalid alignment specification with non-aligned memory access "
394           "specification");
395     }
396   }
397   return success();
398 }
399 
400 // TODO Make sure to merge this and the previous function into one template
401 // parameterized by memory access attribute name and alignment. Doing so now
402 // results in VS2017 in producing an internal error (at the call site) that's
403 // not detailed enough to understand what is happening.
404 template <typename MemoryOpTy>
405 static LogicalResult verifySourceMemoryAccessAttribute(MemoryOpTy memoryOp) {
406   // ODS checks for attributes values. Just need to verify that if the
407   // memory-access attribute is Aligned, then the alignment attribute must be
408   // present.
409   auto *op = memoryOp.getOperation();
410   auto memAccessAttr = op->getAttr(kSourceMemoryAccessAttrName);
411   if (!memAccessAttr) {
412     // Alignment attribute shouldn't be present if memory access attribute is
413     // not present.
414     if (op->getAttr(kSourceAlignmentAttrName)) {
415       return memoryOp.emitOpError(
416           "invalid alignment specification without aligned memory access "
417           "specification");
418     }
419     return success();
420   }
421 
422   auto memAccessVal = memAccessAttr.template cast<IntegerAttr>();
423   auto memAccess = spirv::symbolizeMemoryAccess(memAccessVal.getInt());
424 
425   if (!memAccess) {
426     return memoryOp.emitOpError("invalid memory access specifier: ")
427            << memAccessVal;
428   }
429 
430   if (spirv::bitEnumContains(*memAccess, spirv::MemoryAccess::Aligned)) {
431     if (!op->getAttr(kSourceAlignmentAttrName)) {
432       return memoryOp.emitOpError("missing alignment value");
433     }
434   } else {
435     if (op->getAttr(kSourceAlignmentAttrName)) {
436       return memoryOp.emitOpError(
437           "invalid alignment specification with non-aligned memory access "
438           "specification");
439     }
440   }
441   return success();
442 }
443 
444 template <typename BarrierOp>
445 static LogicalResult verifyMemorySemantics(BarrierOp op) {
446   // According to the SPIR-V specification:
447   // "Despite being a mask and allowing multiple bits to be combined, it is
448   // invalid for more than one of these four bits to be set: Acquire, Release,
449   // AcquireRelease, or SequentiallyConsistent. Requesting both Acquire and
450   // Release semantics is done by setting the AcquireRelease bit, not by setting
451   // two bits."
452   auto memorySemantics = op.memory_semantics();
453   auto atMostOneInSet = spirv::MemorySemantics::Acquire |
454                         spirv::MemorySemantics::Release |
455                         spirv::MemorySemantics::AcquireRelease |
456                         spirv::MemorySemantics::SequentiallyConsistent;
457 
458   auto bitCount = llvm::countPopulation(
459       static_cast<uint32_t>(memorySemantics & atMostOneInSet));
460   if (bitCount > 1) {
461     return op.emitError("expected at most one of these four memory constraints "
462                         "to be set: `Acquire`, `Release`,"
463                         "`AcquireRelease` or `SequentiallyConsistent`");
464   }
465   return success();
466 }
467 
468 template <typename LoadStoreOpTy>
469 static LogicalResult verifyLoadStorePtrAndValTypes(LoadStoreOpTy op, Value ptr,
470                                                    Value val) {
471   // ODS already checks ptr is spirv::PointerType. Just check that the pointee
472   // type of the pointer and the type of the value are the same
473   //
474   // TODO: Check that the value type satisfies restrictions of
475   // SPIR-V OpLoad/OpStore operations
476   if (val.getType() !=
477       ptr.getType().cast<spirv::PointerType>().getPointeeType()) {
478     return op.emitOpError("mismatch in result type and pointer type");
479   }
480   return success();
481 }
482 
483 template <typename BlockReadWriteOpTy>
484 static LogicalResult verifyBlockReadWritePtrAndValTypes(BlockReadWriteOpTy op,
485                                                         Value ptr, Value val) {
486   auto valType = val.getType();
487   if (auto valVecTy = valType.dyn_cast<VectorType>())
488     valType = valVecTy.getElementType();
489 
490   if (valType != ptr.getType().cast<spirv::PointerType>().getPointeeType()) {
491     return op.emitOpError("mismatch in result type and pointer type");
492   }
493   return success();
494 }
495 
496 static ParseResult parseVariableDecorations(OpAsmParser &parser,
497                                             OperationState &state) {
498   auto builtInName = llvm::convertToSnakeFromCamelCase(
499       stringifyDecoration(spirv::Decoration::BuiltIn));
500   if (succeeded(parser.parseOptionalKeyword("bind"))) {
501     Attribute set, binding;
502     // Parse optional descriptor binding
503     auto descriptorSetName = llvm::convertToSnakeFromCamelCase(
504         stringifyDecoration(spirv::Decoration::DescriptorSet));
505     auto bindingName = llvm::convertToSnakeFromCamelCase(
506         stringifyDecoration(spirv::Decoration::Binding));
507     Type i32Type = parser.getBuilder().getIntegerType(32);
508     if (parser.parseLParen() ||
509         parser.parseAttribute(set, i32Type, descriptorSetName,
510                               state.attributes) ||
511         parser.parseComma() ||
512         parser.parseAttribute(binding, i32Type, bindingName,
513                               state.attributes) ||
514         parser.parseRParen()) {
515       return failure();
516     }
517   } else if (succeeded(parser.parseOptionalKeyword(builtInName))) {
518     StringAttr builtIn;
519     if (parser.parseLParen() ||
520         parser.parseAttribute(builtIn, builtInName, state.attributes) ||
521         parser.parseRParen()) {
522       return failure();
523     }
524   }
525 
526   // Parse other attributes
527   if (parser.parseOptionalAttrDict(state.attributes))
528     return failure();
529 
530   return success();
531 }
532 
533 static void printVariableDecorations(Operation *op, OpAsmPrinter &printer,
534                                      SmallVectorImpl<StringRef> &elidedAttrs) {
535   // Print optional descriptor binding
536   auto descriptorSetName = llvm::convertToSnakeFromCamelCase(
537       stringifyDecoration(spirv::Decoration::DescriptorSet));
538   auto bindingName = llvm::convertToSnakeFromCamelCase(
539       stringifyDecoration(spirv::Decoration::Binding));
540   auto descriptorSet = op->getAttrOfType<IntegerAttr>(descriptorSetName);
541   auto binding = op->getAttrOfType<IntegerAttr>(bindingName);
542   if (descriptorSet && binding) {
543     elidedAttrs.push_back(descriptorSetName);
544     elidedAttrs.push_back(bindingName);
545     printer << " bind(" << descriptorSet.getInt() << ", " << binding.getInt()
546             << ")";
547   }
548 
549   // Print BuiltIn attribute if present
550   auto builtInName = llvm::convertToSnakeFromCamelCase(
551       stringifyDecoration(spirv::Decoration::BuiltIn));
552   if (auto builtin = op->getAttrOfType<StringAttr>(builtInName)) {
553     printer << " " << builtInName << "(\"" << builtin.getValue() << "\")";
554     elidedAttrs.push_back(builtInName);
555   }
556 
557   printer.printOptionalAttrDict(op->getAttrs(), elidedAttrs);
558 }
559 
560 // Get bit width of types.
561 static unsigned getBitWidth(Type type) {
562   if (type.isa<spirv::PointerType>()) {
563     // Just return 64 bits for pointer types for now.
564     // TODO: Make sure not caller relies on the actual pointer width value.
565     return 64;
566   }
567 
568   if (type.isIntOrFloat())
569     return type.getIntOrFloatBitWidth();
570 
571   if (auto vectorType = type.dyn_cast<VectorType>()) {
572     assert(vectorType.getElementType().isIntOrFloat());
573     return vectorType.getNumElements() *
574            vectorType.getElementType().getIntOrFloatBitWidth();
575   }
576   llvm_unreachable("unhandled bit width computation for type");
577 }
578 
579 /// Walks the given type hierarchy with the given indices, potentially down
580 /// to component granularity, to select an element type. Returns null type and
581 /// emits errors with the given loc on failure.
582 static Type
583 getElementType(Type type, ArrayRef<int32_t> indices,
584                function_ref<InFlightDiagnostic(StringRef)> emitErrorFn) {
585   if (indices.empty()) {
586     emitErrorFn("expected at least one index for spv.CompositeExtract");
587     return nullptr;
588   }
589 
590   for (auto index : indices) {
591     if (auto cType = type.dyn_cast<spirv::CompositeType>()) {
592       if (cType.hasCompileTimeKnownNumElements() &&
593           (index < 0 ||
594            static_cast<uint64_t>(index) >= cType.getNumElements())) {
595         emitErrorFn("index ") << index << " out of bounds for " << type;
596         return nullptr;
597       }
598       type = cType.getElementType(index);
599     } else {
600       emitErrorFn("cannot extract from non-composite type ")
601           << type << " with index " << index;
602       return nullptr;
603     }
604   }
605   return type;
606 }
607 
608 static Type
609 getElementType(Type type, Attribute indices,
610                function_ref<InFlightDiagnostic(StringRef)> emitErrorFn) {
611   auto indicesArrayAttr = indices.dyn_cast<ArrayAttr>();
612   if (!indicesArrayAttr) {
613     emitErrorFn("expected a 32-bit integer array attribute for 'indices'");
614     return nullptr;
615   }
616   if (!indicesArrayAttr.size()) {
617     emitErrorFn("expected at least one index for spv.CompositeExtract");
618     return nullptr;
619   }
620 
621   SmallVector<int32_t, 2> indexVals;
622   for (auto indexAttr : indicesArrayAttr) {
623     auto indexIntAttr = indexAttr.dyn_cast<IntegerAttr>();
624     if (!indexIntAttr) {
625       emitErrorFn("expected an 32-bit integer for index, but found '")
626           << indexAttr << "'";
627       return nullptr;
628     }
629     indexVals.push_back(indexIntAttr.getInt());
630   }
631   return getElementType(type, indexVals, emitErrorFn);
632 }
633 
634 static Type getElementType(Type type, Attribute indices, Location loc) {
635   auto errorFn = [&](StringRef err) -> InFlightDiagnostic {
636     return ::mlir::emitError(loc, err);
637   };
638   return getElementType(type, indices, errorFn);
639 }
640 
641 static Type getElementType(Type type, Attribute indices, OpAsmParser &parser,
642                            llvm::SMLoc loc) {
643   auto errorFn = [&](StringRef err) -> InFlightDiagnostic {
644     return parser.emitError(loc, err);
645   };
646   return getElementType(type, indices, errorFn);
647 }
648 
649 /// Returns true if the given `block` only contains one `spv.mlir.merge` op.
650 static inline bool isMergeBlock(Block &block) {
651   return !block.empty() && std::next(block.begin()) == block.end() &&
652          isa<spirv::MergeOp>(block.front());
653 }
654 
655 //===----------------------------------------------------------------------===//
656 // Common parsers and printers
657 //===----------------------------------------------------------------------===//
658 
659 // Parses an atomic update op. If the update op does not take a value (like
660 // AtomicIIncrement) `hasValue` must be false.
661 static ParseResult parseAtomicUpdateOp(OpAsmParser &parser,
662                                        OperationState &state, bool hasValue) {
663   spirv::Scope scope;
664   spirv::MemorySemantics memoryScope;
665   SmallVector<OpAsmParser::OperandType, 2> operandInfo;
666   OpAsmParser::OperandType ptrInfo, valueInfo;
667   Type type;
668   llvm::SMLoc loc;
669   if (parseEnumStrAttr(scope, parser, state, kMemoryScopeAttrName) ||
670       parseEnumStrAttr(memoryScope, parser, state, kSemanticsAttrName) ||
671       parser.parseOperandList(operandInfo, (hasValue ? 2 : 1)) ||
672       parser.getCurrentLocation(&loc) || parser.parseColonType(type))
673     return failure();
674 
675   auto ptrType = type.dyn_cast<spirv::PointerType>();
676   if (!ptrType)
677     return parser.emitError(loc, "expected pointer type");
678 
679   SmallVector<Type, 2> operandTypes;
680   operandTypes.push_back(ptrType);
681   if (hasValue)
682     operandTypes.push_back(ptrType.getPointeeType());
683   if (parser.resolveOperands(operandInfo, operandTypes, parser.getNameLoc(),
684                              state.operands))
685     return failure();
686   return parser.addTypeToList(ptrType.getPointeeType(), state.types);
687 }
688 
689 // Prints an atomic update op.
690 static void printAtomicUpdateOp(Operation *op, OpAsmPrinter &printer) {
691   printer << op->getName() << " \"";
692   auto scopeAttr = op->getAttrOfType<IntegerAttr>(kMemoryScopeAttrName);
693   printer << spirv::stringifyScope(
694                  static_cast<spirv::Scope>(scopeAttr.getInt()))
695           << "\" \"";
696   auto memorySemanticsAttr = op->getAttrOfType<IntegerAttr>(kSemanticsAttrName);
697   printer << spirv::stringifyMemorySemantics(
698                  static_cast<spirv::MemorySemantics>(
699                      memorySemanticsAttr.getInt()))
700           << "\" " << op->getOperands() << " : " << op->getOperand(0).getType();
701 }
702 
703 // Verifies an atomic update op.
704 static LogicalResult verifyAtomicUpdateOp(Operation *op) {
705   auto ptrType = op->getOperand(0).getType().cast<spirv::PointerType>();
706   auto elementType = ptrType.getPointeeType();
707   if (!elementType.isa<IntegerType>())
708     return op->emitOpError(
709                "pointer operand must point to an integer value, found ")
710            << elementType;
711 
712   if (op->getNumOperands() > 1) {
713     auto valueType = op->getOperand(1).getType();
714     if (valueType != elementType)
715       return op->emitOpError("expected value to have the same type as the "
716                              "pointer operand's pointee type ")
717              << elementType << ", but found " << valueType;
718   }
719   return success();
720 }
721 
722 static ParseResult parseGroupNonUniformArithmeticOp(OpAsmParser &parser,
723                                                     OperationState &state) {
724   spirv::Scope executionScope;
725   spirv::GroupOperation groupOperation;
726   OpAsmParser::OperandType valueInfo;
727   if (parseEnumStrAttr(executionScope, parser, state,
728                        kExecutionScopeAttrName) ||
729       parseEnumStrAttr(groupOperation, parser, state,
730                        kGroupOperationAttrName) ||
731       parser.parseOperand(valueInfo))
732     return failure();
733 
734   Optional<OpAsmParser::OperandType> clusterSizeInfo;
735   if (succeeded(parser.parseOptionalKeyword(kClusterSize))) {
736     clusterSizeInfo = OpAsmParser::OperandType();
737     if (parser.parseLParen() || parser.parseOperand(*clusterSizeInfo) ||
738         parser.parseRParen())
739       return failure();
740   }
741 
742   Type resultType;
743   if (parser.parseColonType(resultType))
744     return failure();
745 
746   if (parser.resolveOperand(valueInfo, resultType, state.operands))
747     return failure();
748 
749   if (clusterSizeInfo.hasValue()) {
750     Type i32Type = parser.getBuilder().getIntegerType(32);
751     if (parser.resolveOperand(*clusterSizeInfo, i32Type, state.operands))
752       return failure();
753   }
754 
755   return parser.addTypeToList(resultType, state.types);
756 }
757 
758 static void printGroupNonUniformArithmeticOp(Operation *groupOp,
759                                              OpAsmPrinter &printer) {
760   printer << groupOp->getName() << " \""
761           << stringifyScope(static_cast<spirv::Scope>(
762                  groupOp->getAttrOfType<IntegerAttr>(kExecutionScopeAttrName)
763                      .getInt()))
764           << "\" \""
765           << stringifyGroupOperation(static_cast<spirv::GroupOperation>(
766                  groupOp->getAttrOfType<IntegerAttr>(kGroupOperationAttrName)
767                      .getInt()))
768           << "\" " << groupOp->getOperand(0);
769 
770   if (groupOp->getNumOperands() > 1)
771     printer << " " << kClusterSize << '(' << groupOp->getOperand(1) << ')';
772   printer << " : " << groupOp->getResult(0).getType();
773 }
774 
775 static LogicalResult verifyGroupNonUniformArithmeticOp(Operation *groupOp) {
776   spirv::Scope scope = static_cast<spirv::Scope>(
777       groupOp->getAttrOfType<IntegerAttr>(kExecutionScopeAttrName).getInt());
778   if (scope != spirv::Scope::Workgroup && scope != spirv::Scope::Subgroup)
779     return groupOp->emitOpError(
780         "execution scope must be 'Workgroup' or 'Subgroup'");
781 
782   spirv::GroupOperation operation = static_cast<spirv::GroupOperation>(
783       groupOp->getAttrOfType<IntegerAttr>(kGroupOperationAttrName).getInt());
784   if (operation == spirv::GroupOperation::ClusteredReduce &&
785       groupOp->getNumOperands() == 1)
786     return groupOp->emitOpError("cluster size operand must be provided for "
787                                 "'ClusteredReduce' group operation");
788   if (groupOp->getNumOperands() > 1) {
789     Operation *sizeOp = groupOp->getOperand(1).getDefiningOp();
790     int32_t clusterSize = 0;
791 
792     // TODO: support specialization constant here.
793     if (failed(extractValueFromConstOp(sizeOp, clusterSize)))
794       return groupOp->emitOpError(
795           "cluster size operand must come from a constant op");
796 
797     if (!llvm::isPowerOf2_32(clusterSize))
798       return groupOp->emitOpError(
799           "cluster size operand must be a power of two");
800   }
801   return success();
802 }
803 
804 static ParseResult parseUnaryOp(OpAsmParser &parser, OperationState &state) {
805   OpAsmParser::OperandType operandInfo;
806   Type type;
807   if (parser.parseOperand(operandInfo) || parser.parseColonType(type) ||
808       parser.resolveOperands(operandInfo, type, state.operands)) {
809     return failure();
810   }
811   state.addTypes(type);
812   return success();
813 }
814 
815 static void printUnaryOp(Operation *unaryOp, OpAsmPrinter &printer) {
816   printer << unaryOp->getName() << ' ' << unaryOp->getOperand(0) << " : "
817           << unaryOp->getOperand(0).getType();
818 }
819 
820 /// Result of a logical op must be a scalar or vector of boolean type.
821 static Type getUnaryOpResultType(Builder &builder, Type operandType) {
822   Type resultType = builder.getIntegerType(1);
823   if (auto vecType = operandType.dyn_cast<VectorType>()) {
824     return VectorType::get(vecType.getNumElements(), resultType);
825   }
826   return resultType;
827 }
828 
829 static ParseResult parseLogicalUnaryOp(OpAsmParser &parser,
830                                        OperationState &state) {
831   OpAsmParser::OperandType operandInfo;
832   Type type;
833   if (parser.parseOperand(operandInfo) || parser.parseColonType(type) ||
834       parser.resolveOperand(operandInfo, type, state.operands)) {
835     return failure();
836   }
837   state.addTypes(getUnaryOpResultType(parser.getBuilder(), type));
838   return success();
839 }
840 
841 static ParseResult parseLogicalBinaryOp(OpAsmParser &parser,
842                                         OperationState &result) {
843   SmallVector<OpAsmParser::OperandType, 2> ops;
844   Type type;
845   if (parser.parseOperandList(ops, 2) || parser.parseColonType(type) ||
846       parser.resolveOperands(ops, type, result.operands)) {
847     return failure();
848   }
849   result.addTypes(getUnaryOpResultType(parser.getBuilder(), type));
850   return success();
851 }
852 
853 static void printLogicalOp(Operation *logicalOp, OpAsmPrinter &printer) {
854   printer << logicalOp->getName() << ' ' << logicalOp->getOperands() << " : "
855           << logicalOp->getOperand(0).getType();
856 }
857 
858 static ParseResult parseShiftOp(OpAsmParser &parser, OperationState &state) {
859   SmallVector<OpAsmParser::OperandType, 2> operandInfo;
860   Type baseType;
861   Type shiftType;
862   auto loc = parser.getCurrentLocation();
863 
864   if (parser.parseOperandList(operandInfo, 2) || parser.parseColon() ||
865       parser.parseType(baseType) || parser.parseComma() ||
866       parser.parseType(shiftType) ||
867       parser.resolveOperands(operandInfo, {baseType, shiftType}, loc,
868                              state.operands)) {
869     return failure();
870   }
871   state.addTypes(baseType);
872   return success();
873 }
874 
875 static void printShiftOp(Operation *op, OpAsmPrinter &printer) {
876   Value base = op->getOperand(0);
877   Value shift = op->getOperand(1);
878   printer << op->getName() << ' ' << base << ", " << shift << " : "
879           << base.getType() << ", " << shift.getType();
880 }
881 
882 static LogicalResult verifyShiftOp(Operation *op) {
883   if (op->getOperand(0).getType() != op->getResult(0).getType()) {
884     return op->emitError("expected the same type for the first operand and "
885                          "result, but provided ")
886            << op->getOperand(0).getType() << " and "
887            << op->getResult(0).getType();
888   }
889   return success();
890 }
891 
892 static void buildLogicalBinaryOp(OpBuilder &builder, OperationState &state,
893                                  Value lhs, Value rhs) {
894   assert(lhs.getType() == rhs.getType());
895 
896   Type boolType = builder.getI1Type();
897   if (auto vecType = lhs.getType().dyn_cast<VectorType>())
898     boolType = VectorType::get(vecType.getShape(), boolType);
899   state.addTypes(boolType);
900 
901   state.addOperands({lhs, rhs});
902 }
903 
904 static void buildLogicalUnaryOp(OpBuilder &builder, OperationState &state,
905                                 Value value) {
906   Type boolType = builder.getI1Type();
907   if (auto vecType = value.getType().dyn_cast<VectorType>())
908     boolType = VectorType::get(vecType.getShape(), boolType);
909   state.addTypes(boolType);
910 
911   state.addOperands(value);
912 }
913 
914 //===----------------------------------------------------------------------===//
915 // spv.AccessChainOp
916 //===----------------------------------------------------------------------===//
917 
918 static Type getElementPtrType(Type type, ValueRange indices, Location baseLoc) {
919   auto ptrType = type.dyn_cast<spirv::PointerType>();
920   if (!ptrType) {
921     emitError(baseLoc, "'spv.AccessChain' op expected a pointer "
922                        "to composite type, but provided ")
923         << type;
924     return nullptr;
925   }
926 
927   auto resultType = ptrType.getPointeeType();
928   auto resultStorageClass = ptrType.getStorageClass();
929   int32_t index = 0;
930 
931   for (auto indexSSA : indices) {
932     auto cType = resultType.dyn_cast<spirv::CompositeType>();
933     if (!cType) {
934       emitError(baseLoc,
935                 "'spv.AccessChain' op cannot extract from non-composite type ")
936           << resultType << " with index " << index;
937       return nullptr;
938     }
939     index = 0;
940     if (resultType.isa<spirv::StructType>()) {
941       Operation *op = indexSSA.getDefiningOp();
942       if (!op) {
943         emitError(baseLoc, "'spv.AccessChain' op index must be an "
944                            "integer spv.Constant to access "
945                            "element of spv.struct");
946         return nullptr;
947       }
948 
949       // TODO: this should be relaxed to allow
950       // integer literals of other bitwidths.
951       if (failed(extractValueFromConstOp(op, index))) {
952         emitError(baseLoc,
953                   "'spv.AccessChain' index must be an integer spv.Constant to "
954                   "access element of spv.struct, but provided ")
955             << op->getName();
956         return nullptr;
957       }
958       if (index < 0 || static_cast<uint64_t>(index) >= cType.getNumElements()) {
959         emitError(baseLoc, "'spv.AccessChain' op index ")
960             << index << " out of bounds for " << resultType;
961         return nullptr;
962       }
963     }
964     resultType = cType.getElementType(index);
965   }
966   return spirv::PointerType::get(resultType, resultStorageClass);
967 }
968 
969 void spirv::AccessChainOp::build(OpBuilder &builder, OperationState &state,
970                                  Value basePtr, ValueRange indices) {
971   auto type = getElementPtrType(basePtr.getType(), indices, state.location);
972   assert(type && "Unable to deduce return type based on basePtr and indices");
973   build(builder, state, type, basePtr, indices);
974 }
975 
976 static ParseResult parseAccessChainOp(OpAsmParser &parser,
977                                       OperationState &state) {
978   OpAsmParser::OperandType ptrInfo;
979   SmallVector<OpAsmParser::OperandType, 4> indicesInfo;
980   Type type;
981   auto loc = parser.getCurrentLocation();
982   SmallVector<Type, 4> indicesTypes;
983 
984   if (parser.parseOperand(ptrInfo) ||
985       parser.parseOperandList(indicesInfo, OpAsmParser::Delimiter::Square) ||
986       parser.parseColonType(type) ||
987       parser.resolveOperand(ptrInfo, type, state.operands)) {
988     return failure();
989   }
990 
991   // Check that the provided indices list is not empty before parsing their
992   // type list.
993   if (indicesInfo.empty()) {
994     return emitError(state.location, "'spv.AccessChain' op expected at "
995                                      "least one index ");
996   }
997 
998   if (parser.parseComma() || parser.parseTypeList(indicesTypes))
999     return failure();
1000 
1001   // Check that the indices types list is not empty and that it has a one-to-one
1002   // mapping to the provided indices.
1003   if (indicesTypes.size() != indicesInfo.size()) {
1004     return emitError(state.location, "'spv.AccessChain' op indices "
1005                                      "types' count must be equal to indices "
1006                                      "info count");
1007   }
1008 
1009   if (parser.resolveOperands(indicesInfo, indicesTypes, loc, state.operands))
1010     return failure();
1011 
1012   auto resultType = getElementPtrType(
1013       type, llvm::makeArrayRef(state.operands).drop_front(), state.location);
1014   if (!resultType) {
1015     return failure();
1016   }
1017 
1018   state.addTypes(resultType);
1019   return success();
1020 }
1021 
1022 static void print(spirv::AccessChainOp op, OpAsmPrinter &printer) {
1023   printer << spirv::AccessChainOp::getOperationName() << ' ' << op.base_ptr()
1024           << '[' << op.indices() << "] : " << op.base_ptr().getType() << ", "
1025           << op.indices().getTypes();
1026 }
1027 
1028 static LogicalResult verify(spirv::AccessChainOp accessChainOp) {
1029   SmallVector<Value, 4> indices(accessChainOp.indices().begin(),
1030                                 accessChainOp.indices().end());
1031   auto resultType = getElementPtrType(accessChainOp.base_ptr().getType(),
1032                                       indices, accessChainOp.getLoc());
1033   if (!resultType) {
1034     return failure();
1035   }
1036 
1037   auto providedResultType =
1038       accessChainOp.getType().dyn_cast<spirv::PointerType>();
1039   if (!providedResultType) {
1040     return accessChainOp.emitOpError(
1041                "result type must be a pointer, but provided")
1042            << providedResultType;
1043   }
1044 
1045   if (resultType != providedResultType) {
1046     return accessChainOp.emitOpError("invalid result type: expected ")
1047            << resultType << ", but provided " << providedResultType;
1048   }
1049 
1050   return success();
1051 }
1052 
1053 //===----------------------------------------------------------------------===//
1054 // spv.mlir.addressof
1055 //===----------------------------------------------------------------------===//
1056 
1057 void spirv::AddressOfOp::build(OpBuilder &builder, OperationState &state,
1058                                spirv::GlobalVariableOp var) {
1059   build(builder, state, var.type(), builder.getSymbolRefAttr(var));
1060 }
1061 
1062 static LogicalResult verify(spirv::AddressOfOp addressOfOp) {
1063   auto varOp = dyn_cast_or_null<spirv::GlobalVariableOp>(
1064       SymbolTable::lookupNearestSymbolFrom(addressOfOp->getParentOp(),
1065                                            addressOfOp.variable()));
1066   if (!varOp) {
1067     return addressOfOp.emitOpError("expected spv.GlobalVariable symbol");
1068   }
1069   if (addressOfOp.pointer().getType() != varOp.type()) {
1070     return addressOfOp.emitOpError(
1071         "result type mismatch with the referenced global variable's type");
1072   }
1073   return success();
1074 }
1075 
1076 //===----------------------------------------------------------------------===//
1077 // spv.AtomicCompareExchangeWeak
1078 //===----------------------------------------------------------------------===//
1079 
1080 static ParseResult parseAtomicCompareExchangeWeakOp(OpAsmParser &parser,
1081                                                     OperationState &state) {
1082   spirv::Scope memoryScope;
1083   spirv::MemorySemantics equalSemantics, unequalSemantics;
1084   SmallVector<OpAsmParser::OperandType, 3> operandInfo;
1085   Type type;
1086   if (parseEnumStrAttr(memoryScope, parser, state, kMemoryScopeAttrName) ||
1087       parseEnumStrAttr(equalSemantics, parser, state,
1088                        kEqualSemanticsAttrName) ||
1089       parseEnumStrAttr(unequalSemantics, parser, state,
1090                        kUnequalSemanticsAttrName) ||
1091       parser.parseOperandList(operandInfo, 3))
1092     return failure();
1093 
1094   auto loc = parser.getCurrentLocation();
1095   if (parser.parseColonType(type))
1096     return failure();
1097 
1098   auto ptrType = type.dyn_cast<spirv::PointerType>();
1099   if (!ptrType)
1100     return parser.emitError(loc, "expected pointer type");
1101 
1102   if (parser.resolveOperands(
1103           operandInfo,
1104           {ptrType, ptrType.getPointeeType(), ptrType.getPointeeType()},
1105           parser.getNameLoc(), state.operands))
1106     return failure();
1107 
1108   return parser.addTypeToList(ptrType.getPointeeType(), state.types);
1109 }
1110 
1111 static void print(spirv::AtomicCompareExchangeWeakOp atomOp,
1112                   OpAsmPrinter &printer) {
1113   printer << spirv::AtomicCompareExchangeWeakOp::getOperationName() << " \""
1114           << stringifyScope(atomOp.memory_scope()) << "\" \""
1115           << stringifyMemorySemantics(atomOp.equal_semantics()) << "\" \""
1116           << stringifyMemorySemantics(atomOp.unequal_semantics()) << "\" "
1117           << atomOp.getOperands() << " : " << atomOp.pointer().getType();
1118 }
1119 
1120 static LogicalResult verify(spirv::AtomicCompareExchangeWeakOp atomOp) {
1121   // According to the spec:
1122   // "The type of Value must be the same as Result Type. The type of the value
1123   // pointed to by Pointer must be the same as Result Type. This type must also
1124   // match the type of Comparator."
1125   if (atomOp.getType() != atomOp.value().getType())
1126     return atomOp.emitOpError("value operand must have the same type as the op "
1127                               "result, but found ")
1128            << atomOp.value().getType() << " vs " << atomOp.getType();
1129 
1130   if (atomOp.getType() != atomOp.comparator().getType())
1131     return atomOp.emitOpError(
1132                "comparator operand must have the same type as the op "
1133                "result, but found ")
1134            << atomOp.comparator().getType() << " vs " << atomOp.getType();
1135 
1136   Type pointeeType =
1137       atomOp.pointer().getType().cast<spirv::PointerType>().getPointeeType();
1138   if (atomOp.getType() != pointeeType)
1139     return atomOp.emitOpError(
1140                "pointer operand's pointee type must have the same "
1141                "as the op result type, but found ")
1142            << pointeeType << " vs " << atomOp.getType();
1143 
1144   // TODO: Unequal cannot be set to Release or Acquire and Release.
1145   // In addition, Unequal cannot be set to a stronger memory-order then Equal.
1146 
1147   return success();
1148 }
1149 
1150 //===----------------------------------------------------------------------===//
1151 // spv.BitcastOp
1152 //===----------------------------------------------------------------------===//
1153 
1154 static LogicalResult verify(spirv::BitcastOp bitcastOp) {
1155   // TODO: The SPIR-V spec validation rules are different for different
1156   // versions.
1157   auto operandType = bitcastOp.operand().getType();
1158   auto resultType = bitcastOp.result().getType();
1159   if (operandType == resultType) {
1160     return bitcastOp.emitError(
1161         "result type must be different from operand type");
1162   }
1163   if (operandType.isa<spirv::PointerType>() &&
1164       !resultType.isa<spirv::PointerType>()) {
1165     return bitcastOp.emitError(
1166         "unhandled bit cast conversion from pointer type to non-pointer type");
1167   }
1168   if (!operandType.isa<spirv::PointerType>() &&
1169       resultType.isa<spirv::PointerType>()) {
1170     return bitcastOp.emitError(
1171         "unhandled bit cast conversion from non-pointer type to pointer type");
1172   }
1173   auto operandBitWidth = getBitWidth(operandType);
1174   auto resultBitWidth = getBitWidth(resultType);
1175   if (operandBitWidth != resultBitWidth) {
1176     return bitcastOp.emitOpError("mismatch in result type bitwidth ")
1177            << resultBitWidth << " and operand type bitwidth "
1178            << operandBitWidth;
1179   }
1180   return success();
1181 }
1182 
1183 //===----------------------------------------------------------------------===//
1184 // spv.BranchOp
1185 //===----------------------------------------------------------------------===//
1186 
1187 Optional<MutableOperandRange>
1188 spirv::BranchOp::getMutableSuccessorOperands(unsigned index) {
1189   assert(index == 0 && "invalid successor index");
1190   return targetOperandsMutable();
1191 }
1192 
1193 //===----------------------------------------------------------------------===//
1194 // spv.BranchConditionalOp
1195 //===----------------------------------------------------------------------===//
1196 
1197 Optional<MutableOperandRange>
1198 spirv::BranchConditionalOp::getMutableSuccessorOperands(unsigned index) {
1199   assert(index < 2 && "invalid successor index");
1200   return index == kTrueIndex ? trueTargetOperandsMutable()
1201                              : falseTargetOperandsMutable();
1202 }
1203 
1204 static ParseResult parseBranchConditionalOp(OpAsmParser &parser,
1205                                             OperationState &state) {
1206   auto &builder = parser.getBuilder();
1207   OpAsmParser::OperandType condInfo;
1208   Block *dest;
1209 
1210   // Parse the condition.
1211   Type boolTy = builder.getI1Type();
1212   if (parser.parseOperand(condInfo) ||
1213       parser.resolveOperand(condInfo, boolTy, state.operands))
1214     return failure();
1215 
1216   // Parse the optional branch weights.
1217   if (succeeded(parser.parseOptionalLSquare())) {
1218     IntegerAttr trueWeight, falseWeight;
1219     NamedAttrList weights;
1220 
1221     auto i32Type = builder.getIntegerType(32);
1222     if (parser.parseAttribute(trueWeight, i32Type, "weight", weights) ||
1223         parser.parseComma() ||
1224         parser.parseAttribute(falseWeight, i32Type, "weight", weights) ||
1225         parser.parseRSquare())
1226       return failure();
1227 
1228     state.addAttribute(kBranchWeightAttrName,
1229                        builder.getArrayAttr({trueWeight, falseWeight}));
1230   }
1231 
1232   // Parse the true branch.
1233   SmallVector<Value, 4> trueOperands;
1234   if (parser.parseComma() ||
1235       parser.parseSuccessorAndUseList(dest, trueOperands))
1236     return failure();
1237   state.addSuccessors(dest);
1238   state.addOperands(trueOperands);
1239 
1240   // Parse the false branch.
1241   SmallVector<Value, 4> falseOperands;
1242   if (parser.parseComma() ||
1243       parser.parseSuccessorAndUseList(dest, falseOperands))
1244     return failure();
1245   state.addSuccessors(dest);
1246   state.addOperands(falseOperands);
1247   state.addAttribute(
1248       spirv::BranchConditionalOp::getOperandSegmentSizeAttr(),
1249       builder.getI32VectorAttr({1, static_cast<int32_t>(trueOperands.size()),
1250                                 static_cast<int32_t>(falseOperands.size())}));
1251 
1252   return success();
1253 }
1254 
1255 static void print(spirv::BranchConditionalOp branchOp, OpAsmPrinter &printer) {
1256   printer << spirv::BranchConditionalOp::getOperationName() << ' '
1257           << branchOp.condition();
1258 
1259   if (auto weights = branchOp.branch_weights()) {
1260     printer << " [";
1261     llvm::interleaveComma(weights->getValue(), printer, [&](Attribute a) {
1262       printer << a.cast<IntegerAttr>().getInt();
1263     });
1264     printer << "]";
1265   }
1266 
1267   printer << ", ";
1268   printer.printSuccessorAndUseList(branchOp.getTrueBlock(),
1269                                    branchOp.getTrueBlockArguments());
1270   printer << ", ";
1271   printer.printSuccessorAndUseList(branchOp.getFalseBlock(),
1272                                    branchOp.getFalseBlockArguments());
1273 }
1274 
1275 static LogicalResult verify(spirv::BranchConditionalOp branchOp) {
1276   if (auto weights = branchOp.branch_weights()) {
1277     if (weights->getValue().size() != 2) {
1278       return branchOp.emitOpError("must have exactly two branch weights");
1279     }
1280     if (llvm::all_of(*weights, [](Attribute attr) {
1281           return attr.cast<IntegerAttr>().getValue().isNullValue();
1282         }))
1283       return branchOp.emitOpError("branch weights cannot both be zero");
1284   }
1285 
1286   return success();
1287 }
1288 
1289 //===----------------------------------------------------------------------===//
1290 // spv.CompositeConstruct
1291 //===----------------------------------------------------------------------===//
1292 
1293 static ParseResult parseCompositeConstructOp(OpAsmParser &parser,
1294                                              OperationState &state) {
1295   SmallVector<OpAsmParser::OperandType, 4> operands;
1296   Type type;
1297   auto loc = parser.getCurrentLocation();
1298 
1299   if (parser.parseOperandList(operands) || parser.parseColonType(type)) {
1300     return failure();
1301   }
1302   auto cType = type.dyn_cast<spirv::CompositeType>();
1303   if (!cType) {
1304     return parser.emitError(
1305                loc, "result type must be a composite type, but provided ")
1306            << type;
1307   }
1308 
1309   if (cType.hasCompileTimeKnownNumElements() &&
1310       operands.size() != cType.getNumElements()) {
1311     return parser.emitError(loc, "has incorrect number of operands: expected ")
1312            << cType.getNumElements() << ", but provided " << operands.size();
1313   }
1314   // TODO: Add support for constructing a vector type from the vector operands.
1315   // According to the spec: "for constructing a vector, the operands may
1316   // also be vectors with the same component type as the Result Type component
1317   // type".
1318   SmallVector<Type, 4> elementTypes;
1319   elementTypes.reserve(operands.size());
1320   for (auto index : llvm::seq<uint32_t>(0, operands.size())) {
1321     elementTypes.push_back(cType.getElementType(index));
1322   }
1323   state.addTypes(type);
1324   return parser.resolveOperands(operands, elementTypes, loc, state.operands);
1325 }
1326 
1327 static void print(spirv::CompositeConstructOp compositeConstructOp,
1328                   OpAsmPrinter &printer) {
1329   printer << spirv::CompositeConstructOp::getOperationName() << " "
1330           << compositeConstructOp.constituents() << " : "
1331           << compositeConstructOp.getResult().getType();
1332 }
1333 
1334 static LogicalResult verify(spirv::CompositeConstructOp compositeConstructOp) {
1335   auto cType = compositeConstructOp.getType().cast<spirv::CompositeType>();
1336   SmallVector<Value, 4> constituents(compositeConstructOp.constituents());
1337 
1338   if (cType.isa<spirv::CooperativeMatrixNVType>()) {
1339     if (constituents.size() != 1)
1340       return compositeConstructOp.emitError(
1341                  "has incorrect number of operands: expected ")
1342              << "1, but provided " << constituents.size();
1343   } else if (constituents.size() != cType.getNumElements()) {
1344     return compositeConstructOp.emitError(
1345                "has incorrect number of operands: expected ")
1346            << cType.getNumElements() << ", but provided "
1347            << constituents.size();
1348   }
1349 
1350   for (auto index : llvm::seq<uint32_t>(0, constituents.size())) {
1351     if (constituents[index].getType() != cType.getElementType(index)) {
1352       return compositeConstructOp.emitError(
1353                  "operand type mismatch: expected operand type ")
1354              << cType.getElementType(index) << ", but provided "
1355              << constituents[index].getType();
1356     }
1357   }
1358 
1359   return success();
1360 }
1361 
1362 //===----------------------------------------------------------------------===//
1363 // spv.CompositeExtractOp
1364 //===----------------------------------------------------------------------===//
1365 
1366 void spirv::CompositeExtractOp::build(OpBuilder &builder, OperationState &state,
1367                                       Value composite,
1368                                       ArrayRef<int32_t> indices) {
1369   auto indexAttr = builder.getI32ArrayAttr(indices);
1370   auto elementType =
1371       getElementType(composite.getType(), indexAttr, state.location);
1372   if (!elementType) {
1373     return;
1374   }
1375   build(builder, state, elementType, composite, indexAttr);
1376 }
1377 
1378 static ParseResult parseCompositeExtractOp(OpAsmParser &parser,
1379                                            OperationState &state) {
1380   OpAsmParser::OperandType compositeInfo;
1381   Attribute indicesAttr;
1382   Type compositeType;
1383   llvm::SMLoc attrLocation;
1384 
1385   if (parser.parseOperand(compositeInfo) ||
1386       parser.getCurrentLocation(&attrLocation) ||
1387       parser.parseAttribute(indicesAttr, kIndicesAttrName, state.attributes) ||
1388       parser.parseColonType(compositeType) ||
1389       parser.resolveOperand(compositeInfo, compositeType, state.operands)) {
1390     return failure();
1391   }
1392 
1393   Type resultType =
1394       getElementType(compositeType, indicesAttr, parser, attrLocation);
1395   if (!resultType) {
1396     return failure();
1397   }
1398   state.addTypes(resultType);
1399   return success();
1400 }
1401 
1402 static void print(spirv::CompositeExtractOp compositeExtractOp,
1403                   OpAsmPrinter &printer) {
1404   printer << spirv::CompositeExtractOp::getOperationName() << ' '
1405           << compositeExtractOp.composite() << compositeExtractOp.indices()
1406           << " : " << compositeExtractOp.composite().getType();
1407 }
1408 
1409 static LogicalResult verify(spirv::CompositeExtractOp compExOp) {
1410   auto indicesArrayAttr = compExOp.indices().dyn_cast<ArrayAttr>();
1411   auto resultType = getElementType(compExOp.composite().getType(),
1412                                    indicesArrayAttr, compExOp.getLoc());
1413   if (!resultType)
1414     return failure();
1415 
1416   if (resultType != compExOp.getType()) {
1417     return compExOp.emitOpError("invalid result type: expected ")
1418            << resultType << " but provided " << compExOp.getType();
1419   }
1420 
1421   return success();
1422 }
1423 
1424 //===----------------------------------------------------------------------===//
1425 // spv.CompositeInsert
1426 //===----------------------------------------------------------------------===//
1427 
1428 void spirv::CompositeInsertOp::build(OpBuilder &builder, OperationState &state,
1429                                      Value object, Value composite,
1430                                      ArrayRef<int32_t> indices) {
1431   auto indexAttr = builder.getI32ArrayAttr(indices);
1432   build(builder, state, composite.getType(), object, composite, indexAttr);
1433 }
1434 
1435 static ParseResult parseCompositeInsertOp(OpAsmParser &parser,
1436                                           OperationState &state) {
1437   SmallVector<OpAsmParser::OperandType, 2> operands;
1438   Type objectType, compositeType;
1439   Attribute indicesAttr;
1440   auto loc = parser.getCurrentLocation();
1441 
1442   return failure(
1443       parser.parseOperandList(operands, 2) ||
1444       parser.parseAttribute(indicesAttr, kIndicesAttrName, state.attributes) ||
1445       parser.parseColonType(objectType) ||
1446       parser.parseKeywordType("into", compositeType) ||
1447       parser.resolveOperands(operands, {objectType, compositeType}, loc,
1448                              state.operands) ||
1449       parser.addTypesToList(compositeType, state.types));
1450 }
1451 
1452 static LogicalResult verify(spirv::CompositeInsertOp compositeInsertOp) {
1453   auto indicesArrayAttr = compositeInsertOp.indices().dyn_cast<ArrayAttr>();
1454   auto objectType =
1455       getElementType(compositeInsertOp.composite().getType(), indicesArrayAttr,
1456                      compositeInsertOp.getLoc());
1457   if (!objectType)
1458     return failure();
1459 
1460   if (objectType != compositeInsertOp.object().getType()) {
1461     return compositeInsertOp.emitOpError("object operand type should be ")
1462            << objectType << ", but found "
1463            << compositeInsertOp.object().getType();
1464   }
1465 
1466   if (compositeInsertOp.composite().getType() != compositeInsertOp.getType()) {
1467     return compositeInsertOp.emitOpError("result type should be the same as "
1468                                          "the composite type, but found ")
1469            << compositeInsertOp.composite().getType() << " vs "
1470            << compositeInsertOp.getType();
1471   }
1472 
1473   return success();
1474 }
1475 
1476 static void print(spirv::CompositeInsertOp compositeInsertOp,
1477                   OpAsmPrinter &printer) {
1478   printer << spirv::CompositeInsertOp::getOperationName() << " "
1479           << compositeInsertOp.object() << ", " << compositeInsertOp.composite()
1480           << compositeInsertOp.indices() << " : "
1481           << compositeInsertOp.object().getType() << " into "
1482           << compositeInsertOp.composite().getType();
1483 }
1484 
1485 //===----------------------------------------------------------------------===//
1486 // spv.Constant
1487 //===----------------------------------------------------------------------===//
1488 
1489 static ParseResult parseConstantOp(OpAsmParser &parser, OperationState &state) {
1490   Attribute value;
1491   if (parser.parseAttribute(value, kValueAttrName, state.attributes))
1492     return failure();
1493 
1494   Type type = value.getType();
1495   if (type.isa<NoneType, TensorType>()) {
1496     if (parser.parseColonType(type))
1497       return failure();
1498   }
1499 
1500   return parser.addTypeToList(type, state.types);
1501 }
1502 
1503 static void print(spirv::ConstantOp constOp, OpAsmPrinter &printer) {
1504   printer << spirv::ConstantOp::getOperationName() << ' ' << constOp.value();
1505   if (constOp.getType().isa<spirv::ArrayType>())
1506     printer << " : " << constOp.getType();
1507 }
1508 
1509 static LogicalResult verify(spirv::ConstantOp constOp) {
1510   auto opType = constOp.getType();
1511   auto value = constOp.value();
1512   auto valueType = value.getType();
1513 
1514   // ODS already generates checks to make sure the result type is valid. We just
1515   // need to additionally check that the value's attribute type is consistent
1516   // with the result type.
1517   if (value.isa<IntegerAttr, FloatAttr>()) {
1518     if (valueType != opType)
1519       return constOp.emitOpError("result type (")
1520              << opType << ") does not match value type (" << valueType << ")";
1521     return success();
1522   }
1523   if (value.isa<DenseIntOrFPElementsAttr, SparseElementsAttr>()) {
1524     if (valueType == opType)
1525       return success();
1526     auto arrayType = opType.dyn_cast<spirv::ArrayType>();
1527     auto shapedType = valueType.dyn_cast<ShapedType>();
1528     if (!arrayType) {
1529       return constOp.emitOpError(
1530           "must have spv.array result type for array value");
1531     }
1532 
1533     int numElements = arrayType.getNumElements();
1534     auto opElemType = arrayType.getElementType();
1535     while (auto t = opElemType.dyn_cast<spirv::ArrayType>()) {
1536       numElements *= t.getNumElements();
1537       opElemType = t.getElementType();
1538     }
1539     if (!opElemType.isIntOrFloat())
1540       return constOp.emitOpError("only support nested array result type");
1541 
1542     auto valueElemType = shapedType.getElementType();
1543     if (valueElemType != opElemType) {
1544       return constOp.emitOpError("result element type (")
1545              << opElemType << ") does not match value element type ("
1546              << valueElemType << ")";
1547     }
1548 
1549     if (numElements != shapedType.getNumElements()) {
1550       return constOp.emitOpError("result number of elements (")
1551              << numElements << ") does not match value number of elements ("
1552              << shapedType.getNumElements() << ")";
1553     }
1554     return success();
1555   }
1556   if (auto attayAttr = value.dyn_cast<ArrayAttr>()) {
1557     auto arrayType = opType.dyn_cast<spirv::ArrayType>();
1558     if (!arrayType)
1559       return constOp.emitOpError(
1560           "must have spv.array result type for array value");
1561     Type elemType = arrayType.getElementType();
1562     for (Attribute element : attayAttr.getValue()) {
1563       if (element.getType() != elemType)
1564         return constOp.emitOpError("has array element whose type (")
1565                << element.getType()
1566                << ") does not match the result element type (" << elemType
1567                << ')';
1568     }
1569     return success();
1570   }
1571   return constOp.emitOpError("cannot have value of type ") << valueType;
1572 }
1573 
1574 bool spirv::ConstantOp::isBuildableWith(Type type) {
1575   // Must be valid SPIR-V type first.
1576   if (!type.isa<spirv::SPIRVType>())
1577     return false;
1578 
1579   if (isa<SPIRVDialect>(type.getDialect())) {
1580     // TODO: support constant struct
1581     return type.isa<spirv::ArrayType>();
1582   }
1583 
1584   return true;
1585 }
1586 
1587 spirv::ConstantOp spirv::ConstantOp::getZero(Type type, Location loc,
1588                                              OpBuilder &builder) {
1589   if (auto intType = type.dyn_cast<IntegerType>()) {
1590     unsigned width = intType.getWidth();
1591     if (width == 1)
1592       return builder.create<spirv::ConstantOp>(loc, type,
1593                                                builder.getBoolAttr(false));
1594     return builder.create<spirv::ConstantOp>(
1595         loc, type, builder.getIntegerAttr(type, APInt(width, 0)));
1596   }
1597   if (auto floatType = type.dyn_cast<FloatType>()) {
1598     return builder.create<spirv::ConstantOp>(
1599         loc, type, builder.getFloatAttr(floatType, 0.0));
1600   }
1601   if (auto vectorType = type.dyn_cast<VectorType>()) {
1602     Type elemType = vectorType.getElementType();
1603     if (elemType.isa<IntegerType>()) {
1604       return builder.create<spirv::ConstantOp>(
1605           loc, type,
1606           DenseElementsAttr::get(vectorType,
1607                                  IntegerAttr::get(elemType, 0.0).getValue()));
1608     }
1609     if (elemType.isa<FloatType>()) {
1610       return builder.create<spirv::ConstantOp>(
1611           loc, type,
1612           DenseFPElementsAttr::get(vectorType,
1613                                    FloatAttr::get(elemType, 0.0).getValue()));
1614     }
1615   }
1616 
1617   llvm_unreachable("unimplemented types for ConstantOp::getZero()");
1618 }
1619 
1620 spirv::ConstantOp spirv::ConstantOp::getOne(Type type, Location loc,
1621                                             OpBuilder &builder) {
1622   if (auto intType = type.dyn_cast<IntegerType>()) {
1623     unsigned width = intType.getWidth();
1624     if (width == 1)
1625       return builder.create<spirv::ConstantOp>(loc, type,
1626                                                builder.getBoolAttr(true));
1627     return builder.create<spirv::ConstantOp>(
1628         loc, type, builder.getIntegerAttr(type, APInt(width, 1)));
1629   }
1630   if (auto floatType = type.dyn_cast<FloatType>()) {
1631     return builder.create<spirv::ConstantOp>(
1632         loc, type, builder.getFloatAttr(floatType, 1.0));
1633   }
1634   if (auto vectorType = type.dyn_cast<VectorType>()) {
1635     Type elemType = vectorType.getElementType();
1636     if (elemType.isa<IntegerType>()) {
1637       return builder.create<spirv::ConstantOp>(
1638           loc, type,
1639           DenseElementsAttr::get(vectorType,
1640                                  IntegerAttr::get(elemType, 1.0).getValue()));
1641     }
1642     if (elemType.isa<FloatType>()) {
1643       return builder.create<spirv::ConstantOp>(
1644           loc, type,
1645           DenseFPElementsAttr::get(vectorType,
1646                                    FloatAttr::get(elemType, 1.0).getValue()));
1647     }
1648   }
1649 
1650   llvm_unreachable("unimplemented types for ConstantOp::getOne()");
1651 }
1652 
1653 //===----------------------------------------------------------------------===//
1654 // spv.EntryPoint
1655 //===----------------------------------------------------------------------===//
1656 
1657 void spirv::EntryPointOp::build(OpBuilder &builder, OperationState &state,
1658                                 spirv::ExecutionModel executionModel,
1659                                 spirv::FuncOp function,
1660                                 ArrayRef<Attribute> interfaceVars) {
1661   build(builder, state,
1662         spirv::ExecutionModelAttr::get(builder.getContext(), executionModel),
1663         builder.getSymbolRefAttr(function),
1664         builder.getArrayAttr(interfaceVars));
1665 }
1666 
1667 static ParseResult parseEntryPointOp(OpAsmParser &parser,
1668                                      OperationState &state) {
1669   spirv::ExecutionModel execModel;
1670   SmallVector<OpAsmParser::OperandType, 0> identifiers;
1671   SmallVector<Type, 0> idTypes;
1672   SmallVector<Attribute, 4> interfaceVars;
1673 
1674   FlatSymbolRefAttr fn;
1675   if (parseEnumStrAttr(execModel, parser, state) ||
1676       parser.parseAttribute(fn, Type(), kFnNameAttrName, state.attributes)) {
1677     return failure();
1678   }
1679 
1680   if (!parser.parseOptionalComma()) {
1681     // Parse the interface variables
1682     do {
1683       // The name of the interface variable attribute isnt important
1684       auto attrName = "var_symbol";
1685       FlatSymbolRefAttr var;
1686       NamedAttrList attrs;
1687       if (parser.parseAttribute(var, Type(), attrName, attrs)) {
1688         return failure();
1689       }
1690       interfaceVars.push_back(var);
1691     } while (!parser.parseOptionalComma());
1692   }
1693   state.addAttribute(kInterfaceAttrName,
1694                      parser.getBuilder().getArrayAttr(interfaceVars));
1695   return success();
1696 }
1697 
1698 static void print(spirv::EntryPointOp entryPointOp, OpAsmPrinter &printer) {
1699   printer << spirv::EntryPointOp::getOperationName() << " \""
1700           << stringifyExecutionModel(entryPointOp.execution_model()) << "\" ";
1701   printer.printSymbolName(entryPointOp.fn());
1702   auto interfaceVars = entryPointOp.interface().getValue();
1703   if (!interfaceVars.empty()) {
1704     printer << ", ";
1705     llvm::interleaveComma(interfaceVars, printer);
1706   }
1707 }
1708 
1709 static LogicalResult verify(spirv::EntryPointOp entryPointOp) {
1710   // Checks for fn and interface symbol reference are done in spirv::ModuleOp
1711   // verification.
1712   return success();
1713 }
1714 
1715 //===----------------------------------------------------------------------===//
1716 // spv.ExecutionMode
1717 //===----------------------------------------------------------------------===//
1718 
1719 void spirv::ExecutionModeOp::build(OpBuilder &builder, OperationState &state,
1720                                    spirv::FuncOp function,
1721                                    spirv::ExecutionMode executionMode,
1722                                    ArrayRef<int32_t> params) {
1723   build(builder, state, builder.getSymbolRefAttr(function),
1724         spirv::ExecutionModeAttr::get(builder.getContext(), executionMode),
1725         builder.getI32ArrayAttr(params));
1726 }
1727 
1728 static ParseResult parseExecutionModeOp(OpAsmParser &parser,
1729                                         OperationState &state) {
1730   spirv::ExecutionMode execMode;
1731   Attribute fn;
1732   if (parser.parseAttribute(fn, kFnNameAttrName, state.attributes) ||
1733       parseEnumStrAttr(execMode, parser, state)) {
1734     return failure();
1735   }
1736 
1737   SmallVector<int32_t, 4> values;
1738   Type i32Type = parser.getBuilder().getIntegerType(32);
1739   while (!parser.parseOptionalComma()) {
1740     NamedAttrList attr;
1741     Attribute value;
1742     if (parser.parseAttribute(value, i32Type, "value", attr)) {
1743       return failure();
1744     }
1745     values.push_back(value.cast<IntegerAttr>().getInt());
1746   }
1747   state.addAttribute(kValuesAttrName,
1748                      parser.getBuilder().getI32ArrayAttr(values));
1749   return success();
1750 }
1751 
1752 static void print(spirv::ExecutionModeOp execModeOp, OpAsmPrinter &printer) {
1753   printer << spirv::ExecutionModeOp::getOperationName() << " ";
1754   printer.printSymbolName(execModeOp.fn());
1755   printer << " \"" << stringifyExecutionMode(execModeOp.execution_mode())
1756           << "\"";
1757   auto values = execModeOp.values();
1758   if (!values.size())
1759     return;
1760   printer << ", ";
1761   llvm::interleaveComma(values, printer, [&](Attribute a) {
1762     printer << a.cast<IntegerAttr>().getInt();
1763   });
1764 }
1765 
1766 //===----------------------------------------------------------------------===//
1767 // spv.func
1768 //===----------------------------------------------------------------------===//
1769 
1770 static ParseResult parseFuncOp(OpAsmParser &parser, OperationState &state) {
1771   SmallVector<OpAsmParser::OperandType, 4> entryArgs;
1772   SmallVector<NamedAttrList, 4> argAttrs;
1773   SmallVector<NamedAttrList, 4> resultAttrs;
1774   SmallVector<Type, 4> argTypes;
1775   SmallVector<Type, 4> resultTypes;
1776   auto &builder = parser.getBuilder();
1777 
1778   // Parse the name as a symbol.
1779   StringAttr nameAttr;
1780   if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
1781                              state.attributes))
1782     return failure();
1783 
1784   // Parse the function signature.
1785   bool isVariadic = false;
1786   if (impl::parseFunctionSignature(parser, /*allowVariadic=*/false, entryArgs,
1787                                    argTypes, argAttrs, isVariadic, resultTypes,
1788                                    resultAttrs))
1789     return failure();
1790 
1791   auto fnType = builder.getFunctionType(argTypes, resultTypes);
1792   state.addAttribute(impl::getTypeAttrName(), TypeAttr::get(fnType));
1793 
1794   // Parse the optional function control keyword.
1795   spirv::FunctionControl fnControl;
1796   if (parseEnumStrAttr(fnControl, parser, state))
1797     return failure();
1798 
1799   // If additional attributes are present, parse them.
1800   if (parser.parseOptionalAttrDictWithKeyword(state.attributes))
1801     return failure();
1802 
1803   // Add the attributes to the function arguments.
1804   assert(argAttrs.size() == argTypes.size());
1805   assert(resultAttrs.size() == resultTypes.size());
1806   impl::addArgAndResultAttrs(builder, state, argAttrs, resultAttrs);
1807 
1808   // Parse the optional function body.
1809   auto *body = state.addRegion();
1810   OptionalParseResult result = parser.parseOptionalRegion(
1811       *body, entryArgs, entryArgs.empty() ? ArrayRef<Type>() : argTypes);
1812   return failure(result.hasValue() && failed(*result));
1813 }
1814 
1815 static void print(spirv::FuncOp fnOp, OpAsmPrinter &printer) {
1816   // Print function name, signature, and control.
1817   printer << spirv::FuncOp::getOperationName() << " ";
1818   printer.printSymbolName(fnOp.sym_name());
1819   auto fnType = fnOp.getType();
1820   impl::printFunctionSignature(printer, fnOp, fnType.getInputs(),
1821                                /*isVariadic=*/false, fnType.getResults());
1822   printer << " \"" << spirv::stringifyFunctionControl(fnOp.function_control())
1823           << "\"";
1824   impl::printFunctionAttributes(
1825       printer, fnOp, fnType.getNumInputs(), fnType.getNumResults(),
1826       {spirv::attributeName<spirv::FunctionControl>()});
1827 
1828   // Print the body if this is not an external function.
1829   Region &body = fnOp.body();
1830   if (!body.empty())
1831     printer.printRegion(body, /*printEntryBlockArgs=*/false,
1832                         /*printBlockTerminators=*/true);
1833 }
1834 
1835 LogicalResult spirv::FuncOp::verifyType() {
1836   auto type = getTypeAttr().getValue();
1837   if (!type.isa<FunctionType>())
1838     return emitOpError("requires '" + getTypeAttrName() +
1839                        "' attribute of function type");
1840   if (getType().getNumResults() > 1)
1841     return emitOpError("cannot have more than one result");
1842   return success();
1843 }
1844 
1845 LogicalResult spirv::FuncOp::verifyBody() {
1846   FunctionType fnType = getType();
1847 
1848   auto walkResult = walk([fnType](Operation *op) -> WalkResult {
1849     if (auto retOp = dyn_cast<spirv::ReturnOp>(op)) {
1850       if (fnType.getNumResults() != 0)
1851         return retOp.emitOpError("cannot be used in functions returning value");
1852     } else if (auto retOp = dyn_cast<spirv::ReturnValueOp>(op)) {
1853       if (fnType.getNumResults() != 1)
1854         return retOp.emitOpError(
1855                    "returns 1 value but enclosing function requires ")
1856                << fnType.getNumResults() << " results";
1857 
1858       auto retOperandType = retOp.value().getType();
1859       auto fnResultType = fnType.getResult(0);
1860       if (retOperandType != fnResultType)
1861         return retOp.emitOpError(" return value's type (")
1862                << retOperandType << ") mismatch with function's result type ("
1863                << fnResultType << ")";
1864     }
1865     return WalkResult::advance();
1866   });
1867 
1868   // TODO: verify other bits like linkage type.
1869 
1870   return failure(walkResult.wasInterrupted());
1871 }
1872 
1873 void spirv::FuncOp::build(OpBuilder &builder, OperationState &state,
1874                           StringRef name, FunctionType type,
1875                           spirv::FunctionControl control,
1876                           ArrayRef<NamedAttribute> attrs) {
1877   state.addAttribute(SymbolTable::getSymbolAttrName(),
1878                      builder.getStringAttr(name));
1879   state.addAttribute(getTypeAttrName(), TypeAttr::get(type));
1880   state.addAttribute(spirv::attributeName<spirv::FunctionControl>(),
1881                      builder.getI32IntegerAttr(static_cast<uint32_t>(control)));
1882   state.attributes.append(attrs.begin(), attrs.end());
1883   state.addRegion();
1884 }
1885 
1886 // CallableOpInterface
1887 Region *spirv::FuncOp::getCallableRegion() {
1888   return isExternal() ? nullptr : &body();
1889 }
1890 
1891 // CallableOpInterface
1892 ArrayRef<Type> spirv::FuncOp::getCallableResults() {
1893   return getType().getResults();
1894 }
1895 
1896 //===----------------------------------------------------------------------===//
1897 // spv.FunctionCall
1898 //===----------------------------------------------------------------------===//
1899 
1900 static LogicalResult verify(spirv::FunctionCallOp functionCallOp) {
1901   auto fnName = functionCallOp.callee();
1902 
1903   auto funcOp =
1904       dyn_cast_or_null<spirv::FuncOp>(SymbolTable::lookupNearestSymbolFrom(
1905           functionCallOp->getParentOp(), fnName));
1906   if (!funcOp) {
1907     return functionCallOp.emitOpError("callee function '")
1908            << fnName << "' not found in nearest symbol table";
1909   }
1910 
1911   auto functionType = funcOp.getType();
1912 
1913   if (functionCallOp.getNumResults() > 1) {
1914     return functionCallOp.emitOpError(
1915                "expected callee function to have 0 or 1 result, but provided ")
1916            << functionCallOp.getNumResults();
1917   }
1918 
1919   if (functionType.getNumInputs() != functionCallOp.getNumOperands()) {
1920     return functionCallOp.emitOpError(
1921                "has incorrect number of operands for callee: expected ")
1922            << functionType.getNumInputs() << ", but provided "
1923            << functionCallOp.getNumOperands();
1924   }
1925 
1926   for (uint32_t i = 0, e = functionType.getNumInputs(); i != e; ++i) {
1927     if (functionCallOp.getOperand(i).getType() != functionType.getInput(i)) {
1928       return functionCallOp.emitOpError(
1929                  "operand type mismatch: expected operand type ")
1930              << functionType.getInput(i) << ", but provided "
1931              << functionCallOp.getOperand(i).getType() << " for operand number "
1932              << i;
1933     }
1934   }
1935 
1936   if (functionType.getNumResults() != functionCallOp.getNumResults()) {
1937     return functionCallOp.emitOpError(
1938                "has incorrect number of results has for callee: expected ")
1939            << functionType.getNumResults() << ", but provided "
1940            << functionCallOp.getNumResults();
1941   }
1942 
1943   if (functionCallOp.getNumResults() &&
1944       (functionCallOp.getResult(0).getType() != functionType.getResult(0))) {
1945     return functionCallOp.emitOpError("result type mismatch: expected ")
1946            << functionType.getResult(0) << ", but provided "
1947            << functionCallOp.getResult(0).getType();
1948   }
1949 
1950   return success();
1951 }
1952 
1953 CallInterfaceCallable spirv::FunctionCallOp::getCallableForCallee() {
1954   return (*this)->getAttrOfType<SymbolRefAttr>(kCallee);
1955 }
1956 
1957 Operation::operand_range spirv::FunctionCallOp::getArgOperands() {
1958   return arguments();
1959 }
1960 
1961 //===----------------------------------------------------------------------===//
1962 // spv.GlobalVariable
1963 //===----------------------------------------------------------------------===//
1964 
1965 void spirv::GlobalVariableOp::build(OpBuilder &builder, OperationState &state,
1966                                     Type type, StringRef name,
1967                                     unsigned descriptorSet, unsigned binding) {
1968   build(builder, state, TypeAttr::get(type), builder.getStringAttr(name),
1969         nullptr);
1970   state.addAttribute(
1971       spirv::SPIRVDialect::getAttributeName(spirv::Decoration::DescriptorSet),
1972       builder.getI32IntegerAttr(descriptorSet));
1973   state.addAttribute(
1974       spirv::SPIRVDialect::getAttributeName(spirv::Decoration::Binding),
1975       builder.getI32IntegerAttr(binding));
1976 }
1977 
1978 void spirv::GlobalVariableOp::build(OpBuilder &builder, OperationState &state,
1979                                     Type type, StringRef name,
1980                                     spirv::BuiltIn builtin) {
1981   build(builder, state, TypeAttr::get(type), builder.getStringAttr(name),
1982         nullptr);
1983   state.addAttribute(
1984       spirv::SPIRVDialect::getAttributeName(spirv::Decoration::BuiltIn),
1985       builder.getStringAttr(spirv::stringifyBuiltIn(builtin)));
1986 }
1987 
1988 static ParseResult parseGlobalVariableOp(OpAsmParser &parser,
1989                                          OperationState &state) {
1990   // Parse variable name.
1991   StringAttr nameAttr;
1992   if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
1993                              state.attributes)) {
1994     return failure();
1995   }
1996 
1997   // Parse optional initializer
1998   if (succeeded(parser.parseOptionalKeyword(kInitializerAttrName))) {
1999     FlatSymbolRefAttr initSymbol;
2000     if (parser.parseLParen() ||
2001         parser.parseAttribute(initSymbol, Type(), kInitializerAttrName,
2002                               state.attributes) ||
2003         parser.parseRParen())
2004       return failure();
2005   }
2006 
2007   if (parseVariableDecorations(parser, state)) {
2008     return failure();
2009   }
2010 
2011   Type type;
2012   auto loc = parser.getCurrentLocation();
2013   if (parser.parseColonType(type)) {
2014     return failure();
2015   }
2016   if (!type.isa<spirv::PointerType>()) {
2017     return parser.emitError(loc, "expected spv.ptr type");
2018   }
2019   state.addAttribute(kTypeAttrName, TypeAttr::get(type));
2020 
2021   return success();
2022 }
2023 
2024 static void print(spirv::GlobalVariableOp varOp, OpAsmPrinter &printer) {
2025   auto *op = varOp.getOperation();
2026   SmallVector<StringRef, 4> elidedAttrs{
2027       spirv::attributeName<spirv::StorageClass>()};
2028   printer << spirv::GlobalVariableOp::getOperationName();
2029 
2030   // Print variable name.
2031   printer << ' ';
2032   printer.printSymbolName(varOp.sym_name());
2033   elidedAttrs.push_back(SymbolTable::getSymbolAttrName());
2034 
2035   // Print optional initializer
2036   if (auto initializer = varOp.initializer()) {
2037     printer << " " << kInitializerAttrName << '(';
2038     printer.printSymbolName(initializer.getValue());
2039     printer << ')';
2040     elidedAttrs.push_back(kInitializerAttrName);
2041   }
2042 
2043   elidedAttrs.push_back(kTypeAttrName);
2044   printVariableDecorations(op, printer, elidedAttrs);
2045   printer << " : " << varOp.type();
2046 }
2047 
2048 static LogicalResult verify(spirv::GlobalVariableOp varOp) {
2049   // SPIR-V spec: "Storage Class is the Storage Class of the memory holding the
2050   // object. It cannot be Generic. It must be the same as the Storage Class
2051   // operand of the Result Type."
2052   // Also, Function storage class is reserved by spv.Variable.
2053   auto storageClass = varOp.storageClass();
2054   if (storageClass == spirv::StorageClass::Generic ||
2055       storageClass == spirv::StorageClass::Function) {
2056     return varOp.emitOpError("storage class cannot be '")
2057            << stringifyStorageClass(storageClass) << "'";
2058   }
2059 
2060   if (auto init =
2061           varOp->getAttrOfType<FlatSymbolRefAttr>(kInitializerAttrName)) {
2062     Operation *initOp = SymbolTable::lookupNearestSymbolFrom(
2063         varOp->getParentOp(), init.getValue());
2064     // TODO: Currently only variable initialization with specialization
2065     // constants and other variables is supported. They could be normal
2066     // constants in the module scope as well.
2067     if (!initOp ||
2068         !isa<spirv::GlobalVariableOp, spirv::SpecConstantOp>(initOp)) {
2069       return varOp.emitOpError("initializer must be result of a "
2070                                "spv.SpecConstant or spv.GlobalVariable op");
2071     }
2072   }
2073 
2074   return success();
2075 }
2076 
2077 //===----------------------------------------------------------------------===//
2078 // spv.GroupBroadcast
2079 //===----------------------------------------------------------------------===//
2080 
2081 static LogicalResult verify(spirv::GroupBroadcastOp broadcastOp) {
2082   spirv::Scope scope = broadcastOp.execution_scope();
2083   if (scope != spirv::Scope::Workgroup && scope != spirv::Scope::Subgroup)
2084     return broadcastOp.emitOpError(
2085         "execution scope must be 'Workgroup' or 'Subgroup'");
2086 
2087   if (auto localIdTy = broadcastOp.localid().getType().dyn_cast<VectorType>())
2088     if (!(localIdTy.getNumElements() == 2 || localIdTy.getNumElements() == 3))
2089       return broadcastOp.emitOpError("localid is a vector and can be with only "
2090                                      " 2 or 3 components, actual number is ")
2091              << localIdTy.getNumElements();
2092 
2093   return success();
2094 }
2095 
2096 //===----------------------------------------------------------------------===//
2097 // spv.GroupNonUniformBallotOp
2098 //===----------------------------------------------------------------------===//
2099 
2100 static LogicalResult verify(spirv::GroupNonUniformBallotOp ballotOp) {
2101   spirv::Scope scope = ballotOp.execution_scope();
2102   if (scope != spirv::Scope::Workgroup && scope != spirv::Scope::Subgroup)
2103     return ballotOp.emitOpError(
2104         "execution scope must be 'Workgroup' or 'Subgroup'");
2105 
2106   return success();
2107 }
2108 
2109 //===----------------------------------------------------------------------===//
2110 // spv.GroupNonUniformBroadcast
2111 //===----------------------------------------------------------------------===//
2112 
2113 static LogicalResult verify(spirv::GroupNonUniformBroadcastOp broadcastOp) {
2114   spirv::Scope scope = broadcastOp.execution_scope();
2115   if (scope != spirv::Scope::Workgroup && scope != spirv::Scope::Subgroup)
2116     return broadcastOp.emitOpError(
2117         "execution scope must be 'Workgroup' or 'Subgroup'");
2118 
2119   // SPIR-V spec: "Before version 1.5, Id must come from a
2120   // constant instruction.
2121   auto targetEnv = spirv::getDefaultTargetEnv(broadcastOp.getContext());
2122   if (auto spirvModule = broadcastOp->getParentOfType<spirv::ModuleOp>())
2123     targetEnv = spirv::lookupTargetEnvOrDefault(spirvModule);
2124 
2125   if (targetEnv.getVersion() < spirv::Version::V_1_5) {
2126     auto *idOp = broadcastOp.id().getDefiningOp();
2127     if (!idOp || !isa<spirv::ConstantOp,           // for normal constant
2128                       spirv::ReferenceOfOp>(idOp)) // for spec constant
2129       return broadcastOp.emitOpError("id must be the result of a constant op");
2130   }
2131 
2132   return success();
2133 }
2134 
2135 //===----------------------------------------------------------------------===//
2136 // spv.SubgroupBlockReadINTEL
2137 //===----------------------------------------------------------------------===//
2138 
2139 static ParseResult parseSubgroupBlockReadINTELOp(OpAsmParser &parser,
2140                                                  OperationState &state) {
2141   // Parse the storage class specification
2142   spirv::StorageClass storageClass;
2143   OpAsmParser::OperandType ptrInfo;
2144   Type elementType;
2145   if (parseEnumStrAttr(storageClass, parser) || parser.parseOperand(ptrInfo) ||
2146       parser.parseColon() || parser.parseType(elementType)) {
2147     return failure();
2148   }
2149 
2150   auto ptrType = spirv::PointerType::get(elementType, storageClass);
2151   if (auto valVecTy = elementType.dyn_cast<VectorType>())
2152     ptrType = spirv::PointerType::get(valVecTy.getElementType(), storageClass);
2153 
2154   if (parser.resolveOperand(ptrInfo, ptrType, state.operands)) {
2155     return failure();
2156   }
2157 
2158   state.addTypes(elementType);
2159   return success();
2160 }
2161 
2162 static void print(spirv::SubgroupBlockReadINTELOp blockReadOp,
2163                   OpAsmPrinter &printer) {
2164   SmallVector<StringRef, 4> elidedAttrs;
2165   printer << spirv::SubgroupBlockReadINTELOp::getOperationName() << " "
2166           << blockReadOp.ptr();
2167   printer << " : " << blockReadOp.getType();
2168 }
2169 
2170 static LogicalResult verify(spirv::SubgroupBlockReadINTELOp blockReadOp) {
2171   if (failed(verifyBlockReadWritePtrAndValTypes(blockReadOp, blockReadOp.ptr(),
2172                                                 blockReadOp.value())))
2173     return failure();
2174 
2175   return success();
2176 }
2177 
2178 //===----------------------------------------------------------------------===//
2179 // spv.SubgroupBlockWriteINTEL
2180 //===----------------------------------------------------------------------===//
2181 
2182 static ParseResult parseSubgroupBlockWriteINTELOp(OpAsmParser &parser,
2183                                                   OperationState &state) {
2184   // Parse the storage class specification
2185   spirv::StorageClass storageClass;
2186   SmallVector<OpAsmParser::OperandType, 2> operandInfo;
2187   auto loc = parser.getCurrentLocation();
2188   Type elementType;
2189   if (parseEnumStrAttr(storageClass, parser) ||
2190       parser.parseOperandList(operandInfo, 2) || parser.parseColon() ||
2191       parser.parseType(elementType)) {
2192     return failure();
2193   }
2194 
2195   auto ptrType = spirv::PointerType::get(elementType, storageClass);
2196   if (auto valVecTy = elementType.dyn_cast<VectorType>())
2197     ptrType = spirv::PointerType::get(valVecTy.getElementType(), storageClass);
2198 
2199   if (parser.resolveOperands(operandInfo, {ptrType, elementType}, loc,
2200                              state.operands)) {
2201     return failure();
2202   }
2203   return success();
2204 }
2205 
2206 static void print(spirv::SubgroupBlockWriteINTELOp blockWriteOp,
2207                   OpAsmPrinter &printer) {
2208   SmallVector<StringRef, 4> elidedAttrs;
2209   printer << spirv::SubgroupBlockWriteINTELOp::getOperationName() << " "
2210           << blockWriteOp.ptr() << ", " << blockWriteOp.value();
2211   printer << " : " << blockWriteOp.value().getType();
2212 }
2213 
2214 static LogicalResult verify(spirv::SubgroupBlockWriteINTELOp blockWriteOp) {
2215   if (failed(verifyBlockReadWritePtrAndValTypes(
2216           blockWriteOp, blockWriteOp.ptr(), blockWriteOp.value())))
2217     return failure();
2218 
2219   return success();
2220 }
2221 
2222 //===----------------------------------------------------------------------===//
2223 // spv.GroupNonUniformElectOp
2224 //===----------------------------------------------------------------------===//
2225 
2226 void spirv::GroupNonUniformElectOp::build(OpBuilder &builder,
2227                                           OperationState &state,
2228                                           spirv::Scope scope) {
2229   build(builder, state, builder.getI1Type(), scope);
2230 }
2231 
2232 static LogicalResult verify(spirv::GroupNonUniformElectOp groupOp) {
2233   spirv::Scope scope = groupOp.execution_scope();
2234   if (scope != spirv::Scope::Workgroup && scope != spirv::Scope::Subgroup)
2235     return groupOp.emitOpError(
2236         "execution scope must be 'Workgroup' or 'Subgroup'");
2237 
2238   return success();
2239 }
2240 
2241 //===----------------------------------------------------------------------===//
2242 // spv.LoadOp
2243 //===----------------------------------------------------------------------===//
2244 
2245 void spirv::LoadOp::build(OpBuilder &builder, OperationState &state,
2246                           Value basePtr, MemoryAccessAttr memoryAccess,
2247                           IntegerAttr alignment) {
2248   auto ptrType = basePtr.getType().cast<spirv::PointerType>();
2249   build(builder, state, ptrType.getPointeeType(), basePtr, memoryAccess,
2250         alignment);
2251 }
2252 
2253 static ParseResult parseLoadOp(OpAsmParser &parser, OperationState &state) {
2254   // Parse the storage class specification
2255   spirv::StorageClass storageClass;
2256   OpAsmParser::OperandType ptrInfo;
2257   Type elementType;
2258   if (parseEnumStrAttr(storageClass, parser) || parser.parseOperand(ptrInfo) ||
2259       parseMemoryAccessAttributes(parser, state) ||
2260       parser.parseOptionalAttrDict(state.attributes) || parser.parseColon() ||
2261       parser.parseType(elementType)) {
2262     return failure();
2263   }
2264 
2265   auto ptrType = spirv::PointerType::get(elementType, storageClass);
2266   if (parser.resolveOperand(ptrInfo, ptrType, state.operands)) {
2267     return failure();
2268   }
2269 
2270   state.addTypes(elementType);
2271   return success();
2272 }
2273 
2274 static void print(spirv::LoadOp loadOp, OpAsmPrinter &printer) {
2275   auto *op = loadOp.getOperation();
2276   SmallVector<StringRef, 4> elidedAttrs;
2277   StringRef sc = stringifyStorageClass(
2278       loadOp.ptr().getType().cast<spirv::PointerType>().getStorageClass());
2279   printer << spirv::LoadOp::getOperationName() << " \"" << sc << "\" "
2280           << loadOp.ptr();
2281 
2282   printMemoryAccessAttribute(loadOp, printer, elidedAttrs);
2283 
2284   printer.printOptionalAttrDict(op->getAttrs(), elidedAttrs);
2285   printer << " : " << loadOp.getType();
2286 }
2287 
2288 static LogicalResult verify(spirv::LoadOp loadOp) {
2289   // SPIR-V spec : "Result Type is the type of the loaded object. It must be a
2290   // type with fixed size; i.e., it cannot be, nor include, any
2291   // OpTypeRuntimeArray types."
2292   if (failed(verifyLoadStorePtrAndValTypes(loadOp, loadOp.ptr(),
2293                                            loadOp.value()))) {
2294     return failure();
2295   }
2296   return verifyMemoryAccessAttribute(loadOp);
2297 }
2298 
2299 //===----------------------------------------------------------------------===//
2300 // spv.mlir.loop
2301 //===----------------------------------------------------------------------===//
2302 
2303 void spirv::LoopOp::build(OpBuilder &builder, OperationState &state) {
2304   state.addAttribute("loop_control",
2305                      builder.getI32IntegerAttr(
2306                          static_cast<uint32_t>(spirv::LoopControl::None)));
2307   state.addRegion();
2308 }
2309 
2310 static ParseResult parseLoopOp(OpAsmParser &parser, OperationState &state) {
2311   if (parseControlAttribute<spirv::LoopControl>(parser, state))
2312     return failure();
2313   return parser.parseRegion(*state.addRegion(), /*arguments=*/{},
2314                             /*argTypes=*/{});
2315 }
2316 
2317 static void print(spirv::LoopOp loopOp, OpAsmPrinter &printer) {
2318   auto *op = loopOp.getOperation();
2319 
2320   printer << spirv::LoopOp::getOperationName();
2321   auto control = loopOp.loop_control();
2322   if (control != spirv::LoopControl::None)
2323     printer << " control(" << spirv::stringifyLoopControl(control) << ")";
2324   printer.printRegion(op->getRegion(0), /*printEntryBlockArgs=*/false,
2325                       /*printBlockTerminators=*/true);
2326 }
2327 
2328 /// Returns true if the given `srcBlock` contains only one `spv.Branch` to the
2329 /// given `dstBlock`.
2330 static inline bool hasOneBranchOpTo(Block &srcBlock, Block &dstBlock) {
2331   // Check that there is only one op in the `srcBlock`.
2332   if (!llvm::hasSingleElement(srcBlock))
2333     return false;
2334 
2335   auto branchOp = dyn_cast<spirv::BranchOp>(srcBlock.back());
2336   return branchOp && branchOp.getSuccessor() == &dstBlock;
2337 }
2338 
2339 static LogicalResult verify(spirv::LoopOp loopOp) {
2340   auto *op = loopOp.getOperation();
2341 
2342   // We need to verify that the blocks follow the following layout:
2343   //
2344   //                     +-------------+
2345   //                     | entry block |
2346   //                     +-------------+
2347   //                            |
2348   //                            v
2349   //                     +-------------+
2350   //                     | loop header | <-----+
2351   //                     +-------------+       |
2352   //                                           |
2353   //                           ...             |
2354   //                          \ | /            |
2355   //                            v              |
2356   //                    +---------------+      |
2357   //                    | loop continue | -----+
2358   //                    +---------------+
2359   //
2360   //                           ...
2361   //                          \ | /
2362   //                            v
2363   //                     +-------------+
2364   //                     | merge block |
2365   //                     +-------------+
2366 
2367   auto &region = op->getRegion(0);
2368   // Allow empty region as a degenerated case, which can come from
2369   // optimizations.
2370   if (region.empty())
2371     return success();
2372 
2373   // The last block is the merge block.
2374   Block &merge = region.back();
2375   if (!isMergeBlock(merge))
2376     return loopOp.emitOpError(
2377         "last block must be the merge block with only one 'spv.mlir.merge' op");
2378 
2379   if (std::next(region.begin()) == region.end())
2380     return loopOp.emitOpError(
2381         "must have an entry block branching to the loop header block");
2382   // The first block is the entry block.
2383   Block &entry = region.front();
2384 
2385   if (std::next(region.begin(), 2) == region.end())
2386     return loopOp.emitOpError(
2387         "must have a loop header block branched from the entry block");
2388   // The second block is the loop header block.
2389   Block &header = *std::next(region.begin(), 1);
2390 
2391   if (!hasOneBranchOpTo(entry, header))
2392     return loopOp.emitOpError(
2393         "entry block must only have one 'spv.Branch' op to the second block");
2394 
2395   if (std::next(region.begin(), 3) == region.end())
2396     return loopOp.emitOpError(
2397         "requires a loop continue block branching to the loop header block");
2398   // The second to last block is the loop continue block.
2399   Block &cont = *std::prev(region.end(), 2);
2400 
2401   // Make sure that we have a branch from the loop continue block to the loop
2402   // header block.
2403   if (llvm::none_of(
2404           llvm::seq<unsigned>(0, cont.getNumSuccessors()),
2405           [&](unsigned index) { return cont.getSuccessor(index) == &header; }))
2406     return loopOp.emitOpError("second to last block must be the loop continue "
2407                               "block that branches to the loop header block");
2408 
2409   // Make sure that no other blocks (except the entry and loop continue block)
2410   // branches to the loop header block.
2411   for (auto &block : llvm::make_range(std::next(region.begin(), 2),
2412                                       std::prev(region.end(), 2))) {
2413     for (auto i : llvm::seq<unsigned>(0, block.getNumSuccessors())) {
2414       if (block.getSuccessor(i) == &header) {
2415         return loopOp.emitOpError("can only have the entry and loop continue "
2416                                   "block branching to the loop header block");
2417       }
2418     }
2419   }
2420 
2421   return success();
2422 }
2423 
2424 Block *spirv::LoopOp::getEntryBlock() {
2425   assert(!body().empty() && "op region should not be empty!");
2426   return &body().front();
2427 }
2428 
2429 Block *spirv::LoopOp::getHeaderBlock() {
2430   assert(!body().empty() && "op region should not be empty!");
2431   // The second block is the loop header block.
2432   return &*std::next(body().begin());
2433 }
2434 
2435 Block *spirv::LoopOp::getContinueBlock() {
2436   assert(!body().empty() && "op region should not be empty!");
2437   // The second to last block is the loop continue block.
2438   return &*std::prev(body().end(), 2);
2439 }
2440 
2441 Block *spirv::LoopOp::getMergeBlock() {
2442   assert(!body().empty() && "op region should not be empty!");
2443   // The last block is the loop merge block.
2444   return &body().back();
2445 }
2446 
2447 void spirv::LoopOp::addEntryAndMergeBlock() {
2448   assert(body().empty() && "entry and merge block already exist");
2449   body().push_back(new Block());
2450   auto *mergeBlock = new Block();
2451   body().push_back(mergeBlock);
2452   OpBuilder builder = OpBuilder::atBlockEnd(mergeBlock);
2453 
2454   // Add a spv.mlir.merge op into the merge block.
2455   builder.create<spirv::MergeOp>(getLoc());
2456 }
2457 
2458 //===----------------------------------------------------------------------===//
2459 // spv.mlir.merge
2460 //===----------------------------------------------------------------------===//
2461 
2462 static LogicalResult verify(spirv::MergeOp mergeOp) {
2463   auto *parentOp = mergeOp->getParentOp();
2464   if (!parentOp || !isa<spirv::SelectionOp, spirv::LoopOp>(parentOp))
2465     return mergeOp.emitOpError(
2466         "expected parent op to be 'spv.mlir.selection' or 'spv.mlir.loop'");
2467 
2468   Block &parentLastBlock = mergeOp->getParentRegion()->back();
2469   if (mergeOp.getOperation() != parentLastBlock.getTerminator())
2470     return mergeOp.emitOpError("can only be used in the last block of "
2471                                "'spv.mlir.selection' or 'spv.mlir.loop'");
2472   return success();
2473 }
2474 
2475 //===----------------------------------------------------------------------===//
2476 // spv.module
2477 //===----------------------------------------------------------------------===//
2478 
2479 void spirv::ModuleOp::build(OpBuilder &builder, OperationState &state,
2480                             Optional<StringRef> name) {
2481   ensureTerminator(*state.addRegion(), builder, state.location);
2482   if (name) {
2483     state.attributes.append(mlir::SymbolTable::getSymbolAttrName(),
2484                             builder.getStringAttr(*name));
2485   }
2486 }
2487 
2488 void spirv::ModuleOp::build(OpBuilder &builder, OperationState &state,
2489                             spirv::AddressingModel addressingModel,
2490                             spirv::MemoryModel memoryModel,
2491                             Optional<StringRef> name) {
2492   state.addAttribute(
2493       "addressing_model",
2494       builder.getI32IntegerAttr(static_cast<int32_t>(addressingModel)));
2495   state.addAttribute("memory_model", builder.getI32IntegerAttr(
2496                                          static_cast<int32_t>(memoryModel)));
2497   ensureTerminator(*state.addRegion(), builder, state.location);
2498   if (name) {
2499     state.attributes.append(mlir::SymbolTable::getSymbolAttrName(),
2500                             builder.getStringAttr(*name));
2501   }
2502 }
2503 
2504 static ParseResult parseModuleOp(OpAsmParser &parser, OperationState &state) {
2505   Region *body = state.addRegion();
2506 
2507   // If the name is present, parse it.
2508   StringAttr nameAttr;
2509   parser.parseOptionalSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
2510                                  state.attributes);
2511 
2512   // Parse attributes
2513   spirv::AddressingModel addrModel;
2514   spirv::MemoryModel memoryModel;
2515   if (parseEnumKeywordAttr(addrModel, parser, state) ||
2516       parseEnumKeywordAttr(memoryModel, parser, state))
2517     return failure();
2518 
2519   if (succeeded(parser.parseOptionalKeyword("requires"))) {
2520     spirv::VerCapExtAttr vceTriple;
2521     if (parser.parseAttribute(vceTriple,
2522                               spirv::ModuleOp::getVCETripleAttrName(),
2523                               state.attributes))
2524       return failure();
2525   }
2526 
2527   if (parser.parseOptionalAttrDictWithKeyword(state.attributes))
2528     return failure();
2529 
2530   if (parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{}))
2531     return failure();
2532 
2533   spirv::ModuleOp::ensureTerminator(*body, parser.getBuilder(), state.location);
2534   return success();
2535 }
2536 
2537 static void print(spirv::ModuleOp moduleOp, OpAsmPrinter &printer) {
2538   printer << spirv::ModuleOp::getOperationName();
2539 
2540   if (Optional<StringRef> name = moduleOp.getName()) {
2541     printer << ' ';
2542     printer.printSymbolName(*name);
2543   }
2544 
2545   SmallVector<StringRef, 2> elidedAttrs;
2546 
2547   printer << " " << spirv::stringifyAddressingModel(moduleOp.addressing_model())
2548           << " " << spirv::stringifyMemoryModel(moduleOp.memory_model());
2549   auto addressingModelAttrName = spirv::attributeName<spirv::AddressingModel>();
2550   auto memoryModelAttrName = spirv::attributeName<spirv::MemoryModel>();
2551   elidedAttrs.assign({addressingModelAttrName, memoryModelAttrName,
2552                       SymbolTable::getSymbolAttrName()});
2553 
2554   if (Optional<spirv::VerCapExtAttr> triple = moduleOp.vce_triple()) {
2555     printer << " requires " << *triple;
2556     elidedAttrs.push_back(spirv::ModuleOp::getVCETripleAttrName());
2557   }
2558 
2559   printer.printOptionalAttrDictWithKeyword(moduleOp->getAttrs(), elidedAttrs);
2560   printer.printRegion(moduleOp.body(), /*printEntryBlockArgs=*/false,
2561                       /*printBlockTerminators=*/false);
2562 }
2563 
2564 static LogicalResult verify(spirv::ModuleOp moduleOp) {
2565   auto &op = *moduleOp.getOperation();
2566   auto *dialect = op.getDialect();
2567   DenseMap<std::pair<spirv::FuncOp, spirv::ExecutionModel>, spirv::EntryPointOp>
2568       entryPoints;
2569   SymbolTable table(moduleOp);
2570 
2571   for (auto &op : moduleOp.getBlock()) {
2572     if (op.getDialect() != dialect)
2573       return op.emitError("'spv.module' can only contain spv.* ops");
2574 
2575     // For EntryPoint op, check that the function and execution model is not
2576     // duplicated in EntryPointOps. Also verify that the interface specified
2577     // comes from globalVariables here to make this check cheaper.
2578     if (auto entryPointOp = dyn_cast<spirv::EntryPointOp>(op)) {
2579       auto funcOp = table.lookup<spirv::FuncOp>(entryPointOp.fn());
2580       if (!funcOp) {
2581         return entryPointOp.emitError("function '")
2582                << entryPointOp.fn() << "' not found in 'spv.module'";
2583       }
2584       if (auto interface = entryPointOp.interface()) {
2585         for (Attribute varRef : interface) {
2586           auto varSymRef = varRef.dyn_cast<FlatSymbolRefAttr>();
2587           if (!varSymRef) {
2588             return entryPointOp.emitError(
2589                        "expected symbol reference for interface "
2590                        "specification instead of '")
2591                    << varRef;
2592           }
2593           auto variableOp =
2594               table.lookup<spirv::GlobalVariableOp>(varSymRef.getValue());
2595           if (!variableOp) {
2596             return entryPointOp.emitError("expected spv.GlobalVariable "
2597                                           "symbol reference instead of'")
2598                    << varSymRef << "'";
2599           }
2600         }
2601       }
2602 
2603       auto key = std::pair<spirv::FuncOp, spirv::ExecutionModel>(
2604           funcOp, entryPointOp.execution_model());
2605       auto entryPtIt = entryPoints.find(key);
2606       if (entryPtIt != entryPoints.end()) {
2607         return entryPointOp.emitError("duplicate of a previous EntryPointOp");
2608       }
2609       entryPoints[key] = entryPointOp;
2610     } else if (auto funcOp = dyn_cast<spirv::FuncOp>(op)) {
2611       if (funcOp.isExternal())
2612         return op.emitError("'spv.module' cannot contain external functions");
2613 
2614       // TODO: move this check to spv.func.
2615       for (auto &block : funcOp)
2616         for (auto &op : block) {
2617           if (op.getDialect() != dialect)
2618             return op.emitError(
2619                 "functions in 'spv.module' can only contain spv.* ops");
2620         }
2621     }
2622   }
2623 
2624   return success();
2625 }
2626 
2627 //===----------------------------------------------------------------------===//
2628 // spv.mlir.referenceof
2629 //===----------------------------------------------------------------------===//
2630 
2631 static LogicalResult verify(spirv::ReferenceOfOp referenceOfOp) {
2632   auto *specConstSym = SymbolTable::lookupNearestSymbolFrom(
2633       referenceOfOp->getParentOp(), referenceOfOp.spec_const());
2634   Type constType;
2635 
2636   auto specConstOp = dyn_cast_or_null<spirv::SpecConstantOp>(specConstSym);
2637   if (specConstOp)
2638     constType = specConstOp.default_value().getType();
2639 
2640   auto specConstCompositeOp =
2641       dyn_cast_or_null<spirv::SpecConstantCompositeOp>(specConstSym);
2642   if (specConstCompositeOp)
2643     constType = specConstCompositeOp.type();
2644 
2645   if (!specConstOp && !specConstCompositeOp)
2646     return referenceOfOp.emitOpError(
2647         "expected spv.SpecConstant or spv.SpecConstantComposite symbol");
2648 
2649   if (referenceOfOp.reference().getType() != constType)
2650     return referenceOfOp.emitOpError("result type mismatch with the referenced "
2651                                      "specialization constant's type");
2652 
2653   return success();
2654 }
2655 
2656 //===----------------------------------------------------------------------===//
2657 // spv.Return
2658 //===----------------------------------------------------------------------===//
2659 
2660 static LogicalResult verify(spirv::ReturnOp returnOp) {
2661   // Verification is performed in spv.func op.
2662   return success();
2663 }
2664 
2665 //===----------------------------------------------------------------------===//
2666 // spv.ReturnValue
2667 //===----------------------------------------------------------------------===//
2668 
2669 static LogicalResult verify(spirv::ReturnValueOp retValOp) {
2670   // Verification is performed in spv.func op.
2671   return success();
2672 }
2673 
2674 //===----------------------------------------------------------------------===//
2675 // spv.Select
2676 //===----------------------------------------------------------------------===//
2677 
2678 void spirv::SelectOp::build(OpBuilder &builder, OperationState &state,
2679                             Value cond, Value trueValue, Value falseValue) {
2680   build(builder, state, trueValue.getType(), cond, trueValue, falseValue);
2681 }
2682 
2683 static LogicalResult verify(spirv::SelectOp op) {
2684   if (auto conditionTy = op.condition().getType().dyn_cast<VectorType>()) {
2685     auto resultVectorTy = op.result().getType().dyn_cast<VectorType>();
2686     if (!resultVectorTy) {
2687       return op.emitOpError("result expected to be of vector type when "
2688                             "condition is of vector type");
2689     }
2690     if (resultVectorTy.getNumElements() != conditionTy.getNumElements()) {
2691       return op.emitOpError("result should have the same number of elements as "
2692                             "the condition when condition is of vector type");
2693     }
2694   }
2695   return success();
2696 }
2697 
2698 //===----------------------------------------------------------------------===//
2699 // spv.mlir.selection
2700 //===----------------------------------------------------------------------===//
2701 
2702 static ParseResult parseSelectionOp(OpAsmParser &parser,
2703                                     OperationState &state) {
2704   if (parseControlAttribute<spirv::SelectionControl>(parser, state))
2705     return failure();
2706   return parser.parseRegion(*state.addRegion(), /*arguments=*/{},
2707                             /*argTypes=*/{});
2708 }
2709 
2710 static void print(spirv::SelectionOp selectionOp, OpAsmPrinter &printer) {
2711   auto *op = selectionOp.getOperation();
2712 
2713   printer << spirv::SelectionOp::getOperationName();
2714   auto control = selectionOp.selection_control();
2715   if (control != spirv::SelectionControl::None)
2716     printer << " control(" << spirv::stringifySelectionControl(control) << ")";
2717   printer.printRegion(op->getRegion(0), /*printEntryBlockArgs=*/false,
2718                       /*printBlockTerminators=*/true);
2719 }
2720 
2721 static LogicalResult verify(spirv::SelectionOp selectionOp) {
2722   auto *op = selectionOp.getOperation();
2723 
2724   // We need to verify that the blocks follow the following layout:
2725   //
2726   //                     +--------------+
2727   //                     | header block |
2728   //                     +--------------+
2729   //                          / | \
2730   //                           ...
2731   //
2732   //
2733   //         +---------+   +---------+   +---------+
2734   //         | case #0 |   | case #1 |   | case #2 |  ...
2735   //         +---------+   +---------+   +---------+
2736   //
2737   //
2738   //                           ...
2739   //                          \ | /
2740   //                            v
2741   //                     +-------------+
2742   //                     | merge block |
2743   //                     +-------------+
2744 
2745   auto &region = op->getRegion(0);
2746   // Allow empty region as a degenerated case, which can come from
2747   // optimizations.
2748   if (region.empty())
2749     return success();
2750 
2751   // The last block is the merge block.
2752   if (!isMergeBlock(region.back()))
2753     return selectionOp.emitOpError(
2754         "last block must be the merge block with only one 'spv.mlir.merge' op");
2755 
2756   if (std::next(region.begin()) == region.end())
2757     return selectionOp.emitOpError("must have a selection header block");
2758 
2759   return success();
2760 }
2761 
2762 Block *spirv::SelectionOp::getHeaderBlock() {
2763   assert(!body().empty() && "op region should not be empty!");
2764   // The first block is the loop header block.
2765   return &body().front();
2766 }
2767 
2768 Block *spirv::SelectionOp::getMergeBlock() {
2769   assert(!body().empty() && "op region should not be empty!");
2770   // The last block is the loop merge block.
2771   return &body().back();
2772 }
2773 
2774 void spirv::SelectionOp::addMergeBlock() {
2775   assert(body().empty() && "entry and merge block already exist");
2776   auto *mergeBlock = new Block();
2777   body().push_back(mergeBlock);
2778   OpBuilder builder = OpBuilder::atBlockEnd(mergeBlock);
2779 
2780   // Add a spv.mlir.merge op into the merge block.
2781   builder.create<spirv::MergeOp>(getLoc());
2782 }
2783 
2784 spirv::SelectionOp spirv::SelectionOp::createIfThen(
2785     Location loc, Value condition,
2786     function_ref<void(OpBuilder &builder)> thenBody, OpBuilder &builder) {
2787   auto selectionOp =
2788       builder.create<spirv::SelectionOp>(loc, spirv::SelectionControl::None);
2789 
2790   selectionOp.addMergeBlock();
2791   Block *mergeBlock = selectionOp.getMergeBlock();
2792   Block *thenBlock = nullptr;
2793 
2794   // Build the "then" block.
2795   {
2796     OpBuilder::InsertionGuard guard(builder);
2797     thenBlock = builder.createBlock(mergeBlock);
2798     thenBody(builder);
2799     builder.create<spirv::BranchOp>(loc, mergeBlock);
2800   }
2801 
2802   // Build the header block.
2803   {
2804     OpBuilder::InsertionGuard guard(builder);
2805     builder.createBlock(thenBlock);
2806     builder.create<spirv::BranchConditionalOp>(
2807         loc, condition, thenBlock,
2808         /*trueArguments=*/ArrayRef<Value>(), mergeBlock,
2809         /*falseArguments=*/ArrayRef<Value>());
2810   }
2811 
2812   return selectionOp;
2813 }
2814 
2815 //===----------------------------------------------------------------------===//
2816 // spv.SpecConstant
2817 //===----------------------------------------------------------------------===//
2818 
2819 static ParseResult parseSpecConstantOp(OpAsmParser &parser,
2820                                        OperationState &state) {
2821   StringAttr nameAttr;
2822   Attribute valueAttr;
2823 
2824   if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
2825                              state.attributes))
2826     return failure();
2827 
2828   // Parse optional spec_id.
2829   if (succeeded(parser.parseOptionalKeyword(kSpecIdAttrName))) {
2830     IntegerAttr specIdAttr;
2831     if (parser.parseLParen() ||
2832         parser.parseAttribute(specIdAttr, kSpecIdAttrName, state.attributes) ||
2833         parser.parseRParen())
2834       return failure();
2835   }
2836 
2837   if (parser.parseEqual() ||
2838       parser.parseAttribute(valueAttr, kDefaultValueAttrName, state.attributes))
2839     return failure();
2840 
2841   return success();
2842 }
2843 
2844 static void print(spirv::SpecConstantOp constOp, OpAsmPrinter &printer) {
2845   printer << spirv::SpecConstantOp::getOperationName() << ' ';
2846   printer.printSymbolName(constOp.sym_name());
2847   if (auto specID = constOp->getAttrOfType<IntegerAttr>(kSpecIdAttrName))
2848     printer << ' ' << kSpecIdAttrName << '(' << specID.getInt() << ')';
2849   printer << " = " << constOp.default_value();
2850 }
2851 
2852 static LogicalResult verify(spirv::SpecConstantOp constOp) {
2853   if (auto specID = constOp->getAttrOfType<IntegerAttr>(kSpecIdAttrName))
2854     if (specID.getValue().isNegative())
2855       return constOp.emitOpError("SpecId cannot be negative");
2856 
2857   auto value = constOp.default_value();
2858   if (value.isa<IntegerAttr, FloatAttr>()) {
2859     // Make sure bitwidth is allowed.
2860     if (!value.getType().isa<spirv::SPIRVType>())
2861       return constOp.emitOpError("default value bitwidth disallowed");
2862     return success();
2863   }
2864   return constOp.emitOpError(
2865       "default value can only be a bool, integer, or float scalar");
2866 }
2867 
2868 //===----------------------------------------------------------------------===//
2869 // spv.StoreOp
2870 //===----------------------------------------------------------------------===//
2871 
2872 static ParseResult parseStoreOp(OpAsmParser &parser, OperationState &state) {
2873   // Parse the storage class specification
2874   spirv::StorageClass storageClass;
2875   SmallVector<OpAsmParser::OperandType, 2> operandInfo;
2876   auto loc = parser.getCurrentLocation();
2877   Type elementType;
2878   if (parseEnumStrAttr(storageClass, parser) ||
2879       parser.parseOperandList(operandInfo, 2) ||
2880       parseMemoryAccessAttributes(parser, state) || parser.parseColon() ||
2881       parser.parseType(elementType)) {
2882     return failure();
2883   }
2884 
2885   auto ptrType = spirv::PointerType::get(elementType, storageClass);
2886   if (parser.resolveOperands(operandInfo, {ptrType, elementType}, loc,
2887                              state.operands)) {
2888     return failure();
2889   }
2890   return success();
2891 }
2892 
2893 static void print(spirv::StoreOp storeOp, OpAsmPrinter &printer) {
2894   auto *op = storeOp.getOperation();
2895   SmallVector<StringRef, 4> elidedAttrs;
2896   StringRef sc = stringifyStorageClass(
2897       storeOp.ptr().getType().cast<spirv::PointerType>().getStorageClass());
2898   printer << spirv::StoreOp::getOperationName() << " \"" << sc << "\" "
2899           << storeOp.ptr() << ", " << storeOp.value();
2900 
2901   printMemoryAccessAttribute(storeOp, printer, elidedAttrs);
2902 
2903   printer << " : " << storeOp.value().getType();
2904   printer.printOptionalAttrDict(op->getAttrs(), elidedAttrs);
2905 }
2906 
2907 static LogicalResult verify(spirv::StoreOp storeOp) {
2908   // SPIR-V spec : "Pointer is the pointer to store through. Its type must be an
2909   // OpTypePointer whose Type operand is the same as the type of Object."
2910   if (failed(verifyLoadStorePtrAndValTypes(storeOp, storeOp.ptr(),
2911                                            storeOp.value()))) {
2912     return failure();
2913   }
2914   return verifyMemoryAccessAttribute(storeOp);
2915 }
2916 
2917 //===----------------------------------------------------------------------===//
2918 // spv.Unreachable
2919 //===----------------------------------------------------------------------===//
2920 
2921 static LogicalResult verify(spirv::UnreachableOp unreachableOp) {
2922   auto *op = unreachableOp.getOperation();
2923   auto *block = op->getBlock();
2924   // Fast track: if this is in entry block, its invalid. Otherwise, if no
2925   // predecessors, it's valid.
2926   if (block->isEntryBlock())
2927     return unreachableOp.emitOpError("cannot be used in reachable block");
2928   if (block->hasNoPredecessors())
2929     return success();
2930 
2931   // TODO: further verification needs to analyze reachability from
2932   // the entry block.
2933 
2934   return success();
2935 }
2936 
2937 //===----------------------------------------------------------------------===//
2938 // spv.Variable
2939 //===----------------------------------------------------------------------===//
2940 
2941 static ParseResult parseVariableOp(OpAsmParser &parser, OperationState &state) {
2942   // Parse optional initializer
2943   Optional<OpAsmParser::OperandType> initInfo;
2944   if (succeeded(parser.parseOptionalKeyword("init"))) {
2945     initInfo = OpAsmParser::OperandType();
2946     if (parser.parseLParen() || parser.parseOperand(*initInfo) ||
2947         parser.parseRParen())
2948       return failure();
2949   }
2950 
2951   if (parseVariableDecorations(parser, state)) {
2952     return failure();
2953   }
2954 
2955   // Parse result pointer type
2956   Type type;
2957   if (parser.parseColon())
2958     return failure();
2959   auto loc = parser.getCurrentLocation();
2960   if (parser.parseType(type))
2961     return failure();
2962 
2963   auto ptrType = type.dyn_cast<spirv::PointerType>();
2964   if (!ptrType)
2965     return parser.emitError(loc, "expected spv.ptr type");
2966   state.addTypes(ptrType);
2967 
2968   // Resolve the initializer operand
2969   if (initInfo) {
2970     if (parser.resolveOperand(*initInfo, ptrType.getPointeeType(),
2971                               state.operands))
2972       return failure();
2973   }
2974 
2975   auto attr = parser.getBuilder().getI32IntegerAttr(
2976       llvm::bit_cast<int32_t>(ptrType.getStorageClass()));
2977   state.addAttribute(spirv::attributeName<spirv::StorageClass>(), attr);
2978 
2979   return success();
2980 }
2981 
2982 static void print(spirv::VariableOp varOp, OpAsmPrinter &printer) {
2983   SmallVector<StringRef, 4> elidedAttrs{
2984       spirv::attributeName<spirv::StorageClass>()};
2985   printer << spirv::VariableOp::getOperationName();
2986 
2987   // Print optional initializer
2988   if (varOp.getNumOperands() != 0)
2989     printer << " init(" << varOp.initializer() << ")";
2990 
2991   printVariableDecorations(varOp, printer, elidedAttrs);
2992   printer << " : " << varOp.getType();
2993 }
2994 
2995 static LogicalResult verify(spirv::VariableOp varOp) {
2996   // SPIR-V spec: "Storage Class is the Storage Class of the memory holding the
2997   // object. It cannot be Generic. It must be the same as the Storage Class
2998   // operand of the Result Type."
2999   if (varOp.storage_class() != spirv::StorageClass::Function) {
3000     return varOp.emitOpError(
3001         "can only be used to model function-level variables. Use "
3002         "spv.GlobalVariable for module-level variables.");
3003   }
3004 
3005   auto pointerType = varOp.pointer().getType().cast<spirv::PointerType>();
3006   if (varOp.storage_class() != pointerType.getStorageClass())
3007     return varOp.emitOpError(
3008         "storage class must match result pointer's storage class");
3009 
3010   if (varOp.getNumOperands() != 0) {
3011     // SPIR-V spec: "Initializer must be an <id> from a constant instruction or
3012     // a global (module scope) OpVariable instruction".
3013     auto *initOp = varOp.getOperand(0).getDefiningOp();
3014     if (!initOp || !isa<spirv::ConstantOp,    // for normal constant
3015                         spirv::ReferenceOfOp, // for spec constant
3016                         spirv::AddressOfOp>(initOp))
3017       return varOp.emitOpError("initializer must be the result of a "
3018                                "constant or spv.GlobalVariable op");
3019   }
3020 
3021   // TODO: generate these strings using ODS.
3022   auto *op = varOp.getOperation();
3023   auto descriptorSetName = llvm::convertToSnakeFromCamelCase(
3024       stringifyDecoration(spirv::Decoration::DescriptorSet));
3025   auto bindingName = llvm::convertToSnakeFromCamelCase(
3026       stringifyDecoration(spirv::Decoration::Binding));
3027   auto builtInName = llvm::convertToSnakeFromCamelCase(
3028       stringifyDecoration(spirv::Decoration::BuiltIn));
3029 
3030   for (const auto &attr : {descriptorSetName, bindingName, builtInName}) {
3031     if (op->getAttr(attr))
3032       return varOp.emitOpError("cannot have '")
3033              << attr << "' attribute (only allowed in spv.GlobalVariable)";
3034   }
3035 
3036   return success();
3037 }
3038 
3039 //===----------------------------------------------------------------------===//
3040 // spv.VectorShuffle
3041 //===----------------------------------------------------------------------===//
3042 
3043 static LogicalResult verify(spirv::VectorShuffleOp shuffleOp) {
3044   VectorType resultType = shuffleOp.getType().cast<VectorType>();
3045 
3046   size_t numResultElements = resultType.getNumElements();
3047   if (numResultElements != shuffleOp.components().size())
3048     return shuffleOp.emitOpError("result type element count (")
3049            << numResultElements
3050            << ") mismatch with the number of component selectors ("
3051            << shuffleOp.components().size() << ")";
3052 
3053   size_t totalSrcElements =
3054       shuffleOp.vector1().getType().cast<VectorType>().getNumElements() +
3055       shuffleOp.vector2().getType().cast<VectorType>().getNumElements();
3056 
3057   for (const auto &selector :
3058        shuffleOp.components().getAsValueRange<IntegerAttr>()) {
3059     uint32_t index = selector.getZExtValue();
3060     if (index >= totalSrcElements &&
3061         index != std::numeric_limits<uint32_t>().max())
3062       return shuffleOp.emitOpError("component selector ")
3063              << index << " out of range: expected to be in [0, "
3064              << totalSrcElements << ") or 0xffffffff";
3065   }
3066   return success();
3067 }
3068 
3069 //===----------------------------------------------------------------------===//
3070 // spv.CooperativeMatrixLoadNV
3071 //===----------------------------------------------------------------------===//
3072 
3073 static ParseResult parseCooperativeMatrixLoadNVOp(OpAsmParser &parser,
3074                                                   OperationState &state) {
3075   SmallVector<OpAsmParser::OperandType, 3> operandInfo;
3076   Type strideType = parser.getBuilder().getIntegerType(32);
3077   Type columnMajorType = parser.getBuilder().getIntegerType(1);
3078   Type ptrType;
3079   Type elementType;
3080   if (parser.parseOperandList(operandInfo, 3) ||
3081       parseMemoryAccessAttributes(parser, state) || parser.parseColon() ||
3082       parser.parseType(ptrType) || parser.parseKeywordType("as", elementType)) {
3083     return failure();
3084   }
3085   if (parser.resolveOperands(operandInfo,
3086                              {ptrType, strideType, columnMajorType},
3087                              parser.getNameLoc(), state.operands)) {
3088     return failure();
3089   }
3090 
3091   state.addTypes(elementType);
3092   return success();
3093 }
3094 
3095 static void print(spirv::CooperativeMatrixLoadNVOp M, OpAsmPrinter &printer) {
3096   printer << spirv::CooperativeMatrixLoadNVOp::getOperationName() << " "
3097           << M.pointer() << ", " << M.stride() << ", " << M.columnmajor();
3098   // Print optional memory access attribute.
3099   if (auto memAccess = M.memory_access())
3100     printer << " [\"" << stringifyMemoryAccess(*memAccess) << "\"]";
3101   printer << " : " << M.pointer().getType() << " as " << M.getType();
3102 }
3103 
3104 static LogicalResult verifyPointerAndCoopMatrixType(Operation *op, Type pointer,
3105                                                     Type coopMatrix) {
3106   Type pointeeType = pointer.cast<spirv::PointerType>().getPointeeType();
3107   if (!pointeeType.isa<spirv::ScalarType>() && !pointeeType.isa<VectorType>())
3108     return op->emitError(
3109                "Pointer must point to a scalar or vector type but provided ")
3110            << pointeeType;
3111   spirv::StorageClass storage =
3112       pointer.cast<spirv::PointerType>().getStorageClass();
3113   if (storage != spirv::StorageClass::Workgroup &&
3114       storage != spirv::StorageClass::StorageBuffer &&
3115       storage != spirv::StorageClass::PhysicalStorageBuffer)
3116     return op->emitError(
3117                "Pointer storage class must be Workgroup, StorageBuffer or "
3118                "PhysicalStorageBufferEXT but provided ")
3119            << stringifyStorageClass(storage);
3120   return success();
3121 }
3122 
3123 //===----------------------------------------------------------------------===//
3124 // spv.CooperativeMatrixStoreNV
3125 //===----------------------------------------------------------------------===//
3126 
3127 static ParseResult parseCooperativeMatrixStoreNVOp(OpAsmParser &parser,
3128                                                    OperationState &state) {
3129   SmallVector<OpAsmParser::OperandType, 4> operandInfo;
3130   Type strideType = parser.getBuilder().getIntegerType(32);
3131   Type columnMajorType = parser.getBuilder().getIntegerType(1);
3132   Type ptrType;
3133   Type elementType;
3134   if (parser.parseOperandList(operandInfo, 4) ||
3135       parseMemoryAccessAttributes(parser, state) || parser.parseColon() ||
3136       parser.parseType(ptrType) || parser.parseComma() ||
3137       parser.parseType(elementType)) {
3138     return failure();
3139   }
3140   if (parser.resolveOperands(
3141           operandInfo, {ptrType, elementType, strideType, columnMajorType},
3142           parser.getNameLoc(), state.operands)) {
3143     return failure();
3144   }
3145 
3146   return success();
3147 }
3148 
3149 static void print(spirv::CooperativeMatrixStoreNVOp coopMatrix,
3150                   OpAsmPrinter &printer) {
3151   printer << spirv::CooperativeMatrixStoreNVOp::getOperationName() << " "
3152           << coopMatrix.pointer() << ", " << coopMatrix.object() << ", "
3153           << coopMatrix.stride() << ", " << coopMatrix.columnmajor();
3154   // Print optional memory access attribute.
3155   if (auto memAccess = coopMatrix.memory_access())
3156     printer << " [\"" << stringifyMemoryAccess(*memAccess) << "\"]";
3157   printer << " : " << coopMatrix.pointer().getType() << ", "
3158           << coopMatrix.getOperand(1).getType();
3159 }
3160 
3161 //===----------------------------------------------------------------------===//
3162 // spv.CooperativeMatrixMulAddNV
3163 //===----------------------------------------------------------------------===//
3164 
3165 static LogicalResult
3166 verifyCoopMatrixMulAdd(spirv::CooperativeMatrixMulAddNVOp op) {
3167   if (op.c().getType() != op.result().getType())
3168     return op.emitOpError("result and third operand must have the same type");
3169   auto typeA = op.a().getType().cast<spirv::CooperativeMatrixNVType>();
3170   auto typeB = op.b().getType().cast<spirv::CooperativeMatrixNVType>();
3171   auto typeC = op.c().getType().cast<spirv::CooperativeMatrixNVType>();
3172   auto typeR = op.result().getType().cast<spirv::CooperativeMatrixNVType>();
3173   if (typeA.getRows() != typeR.getRows() ||
3174       typeA.getColumns() != typeB.getRows() ||
3175       typeB.getColumns() != typeR.getColumns())
3176     return op.emitOpError("matrix size must match");
3177   if (typeR.getScope() != typeA.getScope() ||
3178       typeR.getScope() != typeB.getScope() ||
3179       typeR.getScope() != typeC.getScope())
3180     return op.emitOpError("matrix scope must match");
3181   if (typeA.getElementType() != typeB.getElementType() ||
3182       typeR.getElementType() != typeC.getElementType())
3183     return op.emitOpError("matrix element type must match");
3184   return success();
3185 }
3186 
3187 //===----------------------------------------------------------------------===//
3188 // spv.MatrixTimesScalar
3189 //===----------------------------------------------------------------------===//
3190 
3191 static LogicalResult verifyMatrixTimesScalar(spirv::MatrixTimesScalarOp op) {
3192   // We already checked that result and matrix are both of matrix type in the
3193   // auto-generated verify method.
3194 
3195   auto inputMatrix = op.matrix().getType().cast<spirv::MatrixType>();
3196   auto resultMatrix = op.result().getType().cast<spirv::MatrixType>();
3197 
3198   // Check that the scalar type is the same as the matrix element type.
3199   if (op.scalar().getType() != inputMatrix.getElementType())
3200     return op.emitError("input matrix components' type and scaling value must "
3201                         "have the same type");
3202 
3203   // Note that the next three checks could be done using the AllTypesMatch
3204   // trait in the Op definition file but it generates a vague error message.
3205 
3206   // Check that the input and result matrices have the same columns' count
3207   if (inputMatrix.getNumColumns() != resultMatrix.getNumColumns())
3208     return op.emitError("input and result matrices must have the same "
3209                         "number of columns");
3210 
3211   // Check that the input and result matrices' have the same rows count
3212   if (inputMatrix.getNumRows() != resultMatrix.getNumRows())
3213     return op.emitError("input and result matrices' columns must have "
3214                         "the same size");
3215 
3216   // Check that the input and result matrices' have the same component type
3217   if (inputMatrix.getElementType() != resultMatrix.getElementType())
3218     return op.emitError("input and result matrices' columns must have "
3219                         "the same component type");
3220 
3221   return success();
3222 }
3223 
3224 //===----------------------------------------------------------------------===//
3225 // spv.CopyMemory
3226 //===----------------------------------------------------------------------===//
3227 
3228 static void print(spirv::CopyMemoryOp copyMemory, OpAsmPrinter &printer) {
3229   auto *op = copyMemory.getOperation();
3230   printer << spirv::CopyMemoryOp::getOperationName() << ' ';
3231 
3232   StringRef targetStorageClass =
3233       stringifyStorageClass(copyMemory.target()
3234                                 .getType()
3235                                 .cast<spirv::PointerType>()
3236                                 .getStorageClass());
3237   printer << " \"" << targetStorageClass << "\" " << copyMemory.target()
3238           << ", ";
3239 
3240   StringRef sourceStorageClass =
3241       stringifyStorageClass(copyMemory.source()
3242                                 .getType()
3243                                 .cast<spirv::PointerType>()
3244                                 .getStorageClass());
3245   printer << " \"" << sourceStorageClass << "\" " << copyMemory.source();
3246 
3247   SmallVector<StringRef, 4> elidedAttrs;
3248   printMemoryAccessAttribute(copyMemory, printer, elidedAttrs);
3249   printSourceMemoryAccessAttribute(copyMemory, printer, elidedAttrs,
3250                                    copyMemory.source_memory_access(),
3251                                    copyMemory.source_alignment());
3252 
3253   printer.printOptionalAttrDict(op->getAttrs(), elidedAttrs);
3254 
3255   Type pointeeType =
3256       copyMemory.target().getType().cast<spirv::PointerType>().getPointeeType();
3257   printer << " : " << pointeeType;
3258 }
3259 
3260 static ParseResult parseCopyMemoryOp(OpAsmParser &parser,
3261                                      OperationState &state) {
3262   spirv::StorageClass targetStorageClass;
3263   OpAsmParser::OperandType targetPtrInfo;
3264 
3265   spirv::StorageClass sourceStorageClass;
3266   OpAsmParser::OperandType sourcePtrInfo;
3267 
3268   Type elementType;
3269 
3270   if (parseEnumStrAttr(targetStorageClass, parser) ||
3271       parser.parseOperand(targetPtrInfo) || parser.parseComma() ||
3272       parseEnumStrAttr(sourceStorageClass, parser) ||
3273       parser.parseOperand(sourcePtrInfo) ||
3274       parseMemoryAccessAttributes(parser, state)) {
3275     return failure();
3276   }
3277 
3278   if (!parser.parseOptionalComma()) {
3279     // Parse 2nd memory access attributes.
3280     if (parseSourceMemoryAccessAttributes(parser, state)) {
3281       return failure();
3282     }
3283   }
3284 
3285   if (parser.parseColon() || parser.parseType(elementType))
3286     return failure();
3287 
3288   if (parser.parseOptionalAttrDict(state.attributes))
3289     return failure();
3290 
3291   auto targetPtrType = spirv::PointerType::get(elementType, targetStorageClass);
3292   auto sourcePtrType = spirv::PointerType::get(elementType, sourceStorageClass);
3293 
3294   if (parser.resolveOperand(targetPtrInfo, targetPtrType, state.operands) ||
3295       parser.resolveOperand(sourcePtrInfo, sourcePtrType, state.operands)) {
3296     return failure();
3297   }
3298 
3299   return success();
3300 }
3301 
3302 static LogicalResult verifyCopyMemory(spirv::CopyMemoryOp copyMemory) {
3303   Type targetType =
3304       copyMemory.target().getType().cast<spirv::PointerType>().getPointeeType();
3305 
3306   Type sourceType =
3307       copyMemory.source().getType().cast<spirv::PointerType>().getPointeeType();
3308 
3309   if (targetType != sourceType) {
3310     return copyMemory.emitOpError(
3311         "both operands must be pointers to the same type");
3312   }
3313 
3314   if (failed(verifyMemoryAccessAttribute(copyMemory))) {
3315     return failure();
3316   }
3317 
3318   // TODO - According to the spec:
3319   //
3320   // If two masks are present, the first applies to Target and cannot include
3321   // MakePointerVisible, and the second applies to Source and cannot include
3322   // MakePointerAvailable.
3323   //
3324   // Add such verification here.
3325 
3326   return verifySourceMemoryAccessAttribute(copyMemory);
3327 }
3328 
3329 //===----------------------------------------------------------------------===//
3330 // spv.Transpose
3331 //===----------------------------------------------------------------------===//
3332 
3333 static LogicalResult verifyTranspose(spirv::TransposeOp op) {
3334   auto inputMatrix = op.matrix().getType().cast<spirv::MatrixType>();
3335   auto resultMatrix = op.result().getType().cast<spirv::MatrixType>();
3336 
3337   // Verify that the input and output matrices have correct shapes.
3338   if (inputMatrix.getNumRows() != resultMatrix.getNumColumns())
3339     return op.emitError("input matrix rows count must be equal to "
3340                         "output matrix columns count");
3341 
3342   if (inputMatrix.getNumColumns() != resultMatrix.getNumRows())
3343     return op.emitError("input matrix columns count must be equal to "
3344                         "output matrix rows count");
3345 
3346   // Verify that the input and output matrices have the same component type
3347   if (inputMatrix.getElementType() != resultMatrix.getElementType())
3348     return op.emitError("input and output matrices must have the same "
3349                         "component type");
3350 
3351   return success();
3352 }
3353 
3354 //===----------------------------------------------------------------------===//
3355 // spv.MatrixTimesMatrix
3356 //===----------------------------------------------------------------------===//
3357 
3358 static LogicalResult verifyMatrixTimesMatrix(spirv::MatrixTimesMatrixOp op) {
3359   auto leftMatrix = op.leftmatrix().getType().cast<spirv::MatrixType>();
3360   auto rightMatrix = op.rightmatrix().getType().cast<spirv::MatrixType>();
3361   auto resultMatrix = op.result().getType().cast<spirv::MatrixType>();
3362 
3363   // left matrix columns' count and right matrix rows' count must be equal
3364   if (leftMatrix.getNumColumns() != rightMatrix.getNumRows())
3365     return op.emitError("left matrix columns' count must be equal to "
3366                         "the right matrix rows' count");
3367 
3368   // right and result matrices columns' count must be the same
3369   if (rightMatrix.getNumColumns() != resultMatrix.getNumColumns())
3370     return op.emitError(
3371         "right and result matrices must have equal columns' count");
3372 
3373   // right and result matrices component type must be the same
3374   if (rightMatrix.getElementType() != resultMatrix.getElementType())
3375     return op.emitError("right and result matrices' component type must"
3376                         " be the same");
3377 
3378   // left and result matrices component type must be the same
3379   if (leftMatrix.getElementType() != resultMatrix.getElementType())
3380     return op.emitError("left and result matrices' component type"
3381                         " must be the same");
3382 
3383   // left and result matrices rows count must be the same
3384   if (leftMatrix.getNumRows() != resultMatrix.getNumRows())
3385     return op.emitError("left and result matrices must have equal rows'"
3386                         " count");
3387 
3388   return success();
3389 }
3390 
3391 //===----------------------------------------------------------------------===//
3392 // spv.SpecConstantComposite
3393 //===----------------------------------------------------------------------===//
3394 
3395 static ParseResult parseSpecConstantCompositeOp(OpAsmParser &parser,
3396                                                 OperationState &state) {
3397 
3398   StringAttr compositeName;
3399   if (parser.parseSymbolName(compositeName, SymbolTable::getSymbolAttrName(),
3400                              state.attributes))
3401     return failure();
3402 
3403   if (parser.parseLParen())
3404     return failure();
3405 
3406   SmallVector<Attribute, 4> constituents;
3407 
3408   do {
3409     // The name of the constituent attribute isn't important
3410     const char *attrName = "spec_const";
3411     FlatSymbolRefAttr specConstRef;
3412     NamedAttrList attrs;
3413 
3414     if (parser.parseAttribute(specConstRef, Type(), attrName, attrs))
3415       return failure();
3416 
3417     constituents.push_back(specConstRef);
3418   } while (!parser.parseOptionalComma());
3419 
3420   if (parser.parseRParen())
3421     return failure();
3422 
3423   state.addAttribute(kCompositeSpecConstituentsName,
3424                      parser.getBuilder().getArrayAttr(constituents));
3425 
3426   Type type;
3427   if (parser.parseColonType(type))
3428     return failure();
3429 
3430   state.addAttribute(kTypeAttrName, TypeAttr::get(type));
3431 
3432   return success();
3433 }
3434 
3435 static void print(spirv::SpecConstantCompositeOp op, OpAsmPrinter &printer) {
3436   printer << spirv::SpecConstantCompositeOp::getOperationName() << " ";
3437   printer.printSymbolName(op.sym_name());
3438   printer << " (";
3439   auto constituents = op.constituents().getValue();
3440 
3441   if (!constituents.empty())
3442     llvm::interleaveComma(constituents, printer);
3443 
3444   printer << ") : " << op.type();
3445 }
3446 
3447 static LogicalResult verify(spirv::SpecConstantCompositeOp constOp) {
3448   auto cType = constOp.type().dyn_cast<spirv::CompositeType>();
3449   auto constituents = constOp.constituents().getValue();
3450 
3451   if (!cType)
3452     return constOp.emitError(
3453                "result type must be a composite type, but provided ")
3454            << constOp.type();
3455 
3456   if (cType.isa<spirv::CooperativeMatrixNVType>())
3457     return constOp.emitError("unsupported composite type  ") << cType;
3458   else if (constituents.size() != cType.getNumElements())
3459     return constOp.emitError("has incorrect number of operands: expected ")
3460            << cType.getNumElements() << ", but provided "
3461            << constituents.size();
3462 
3463   for (auto index : llvm::seq<uint32_t>(0, constituents.size())) {
3464     auto constituent = constituents[index].dyn_cast<FlatSymbolRefAttr>();
3465 
3466     auto constituentSpecConstOp =
3467         dyn_cast<spirv::SpecConstantOp>(SymbolTable::lookupNearestSymbolFrom(
3468             constOp->getParentOp(), constituent.getValue()));
3469 
3470     if (constituentSpecConstOp.default_value().getType() !=
3471         cType.getElementType(index))
3472       return constOp.emitError("has incorrect types of operands: expected ")
3473              << cType.getElementType(index) << ", but provided "
3474              << constituentSpecConstOp.default_value().getType();
3475   }
3476 
3477   return success();
3478 }
3479 
3480 //===----------------------------------------------------------------------===//
3481 // spv.SpecConstantOperation
3482 //===----------------------------------------------------------------------===//
3483 
3484 static ParseResult parseSpecConstantOperationOp(OpAsmParser &parser,
3485                                                 OperationState &state) {
3486   Region *body = state.addRegion();
3487 
3488   if (parser.parseKeyword("wraps"))
3489     return failure();
3490 
3491   body->push_back(new Block);
3492   Block &block = body->back();
3493   Operation *wrappedOp = parser.parseGenericOperation(&block, block.begin());
3494 
3495   if (!wrappedOp)
3496     return failure();
3497 
3498   OpBuilder builder(parser.getBuilder().getContext());
3499   builder.setInsertionPointToEnd(&block);
3500   builder.create<spirv::YieldOp>(wrappedOp->getLoc(), wrappedOp->getResult(0));
3501   state.location = wrappedOp->getLoc();
3502 
3503   state.addTypes(wrappedOp->getResult(0).getType());
3504 
3505   if (parser.parseOptionalAttrDict(state.attributes))
3506     return failure();
3507 
3508   return success();
3509 }
3510 
3511 static void print(spirv::SpecConstantOperationOp op, OpAsmPrinter &printer) {
3512   printer << op.getOperationName() << " wraps ";
3513   printer.printGenericOp(&op.body().front().front());
3514 }
3515 
3516 static LogicalResult verify(spirv::SpecConstantOperationOp constOp) {
3517   Block &block = constOp.getRegion().getBlocks().front();
3518 
3519   if (block.getOperations().size() != 2)
3520     return constOp.emitOpError("expected exactly 2 nested ops");
3521 
3522   Operation &enclosedOp = block.getOperations().front();
3523 
3524   if (!enclosedOp.hasTrait<OpTrait::spirv::UsableInSpecConstantOp>())
3525     return constOp.emitOpError("invalid enclosed op");
3526 
3527   for (auto operand : enclosedOp.getOperands())
3528     if (!isa<spirv::ConstantOp, spirv::ReferenceOfOp,
3529              spirv::SpecConstantOperationOp>(operand.getDefiningOp()))
3530       return constOp.emitOpError(
3531           "invalid operand, must be defined by a constant operation");
3532 
3533   return success();
3534 }
3535 
3536 //===----------------------------------------------------------------------===//
3537 // spv.GLSL.FrexpStruct
3538 //===----------------------------------------------------------------------===//
3539 static LogicalResult
3540 verifyGLSLFrexpStructOp(spirv::GLSLFrexpStructOp frexpStructOp) {
3541   spirv::StructType structTy =
3542       frexpStructOp.result().getType().dyn_cast<spirv::StructType>();
3543 
3544   if (structTy.getNumElements() != 2)
3545     return frexpStructOp.emitError("result type must be a struct  type "
3546                                    "with two memebers");
3547 
3548   Type significandTy = structTy.getElementType(0);
3549   Type exponentTy = structTy.getElementType(1);
3550   VectorType exponentVecTy = exponentTy.dyn_cast<VectorType>();
3551   IntegerType exponentIntTy = exponentTy.dyn_cast<IntegerType>();
3552 
3553   Type operandTy = frexpStructOp.operand().getType();
3554   VectorType operandVecTy = operandTy.dyn_cast<VectorType>();
3555   FloatType operandFTy = operandTy.dyn_cast<FloatType>();
3556 
3557   if (significandTy != operandTy)
3558     return frexpStructOp.emitError("member zero of the resulting struct type "
3559                                    "must be the same type as the operand");
3560 
3561   if (exponentVecTy) {
3562     IntegerType componentIntTy =
3563         exponentVecTy.getElementType().dyn_cast<IntegerType>();
3564     if (!(componentIntTy && componentIntTy.getWidth() == 32))
3565       return frexpStructOp.emitError(
3566           "member one of the resulting struct type must"
3567           "be a scalar or vector of 32 bit integer type");
3568   } else if (!(exponentIntTy && exponentIntTy.getWidth() == 32)) {
3569     return frexpStructOp.emitError(
3570         "member one of the resulting struct type "
3571         "must be a scalar or vector of 32 bit integer type");
3572   }
3573 
3574   // Check that the two member types have the same number of components
3575   if (operandVecTy && exponentVecTy &&
3576       (exponentVecTy.getNumElements() == operandVecTy.getNumElements()))
3577     return success();
3578 
3579   if (operandFTy && exponentIntTy)
3580     return success();
3581 
3582   return frexpStructOp.emitError(
3583       "member one of the resulting struct type "
3584       "must have the same number of components as the operand type");
3585 }
3586 
3587 //===----------------------------------------------------------------------===//
3588 // spv.GLSL.Ldexp
3589 //===----------------------------------------------------------------------===//
3590 
3591 static LogicalResult verify(spirv::GLSLLdexpOp ldexpOp) {
3592   Type significandType = ldexpOp.x().getType();
3593   Type exponentType = ldexpOp.exp().getType();
3594 
3595   if (significandType.isa<FloatType>() != exponentType.isa<IntegerType>())
3596     return ldexpOp.emitOpError("operands must both be scalars or vectors");
3597 
3598   auto getNumElements = [](Type type) -> unsigned {
3599     if (auto vectorType = type.dyn_cast<VectorType>())
3600       return vectorType.getNumElements();
3601     return 1;
3602   };
3603 
3604   if (getNumElements(significandType) != getNumElements(exponentType))
3605     return ldexpOp.emitOpError(
3606         "operands must have the same number of elements");
3607 
3608   return success();
3609 }
3610 
3611 namespace mlir {
3612 namespace spirv {
3613 
3614 // TableGen'erated operation interfaces for querying versions, extensions, and
3615 // capabilities.
3616 #include "mlir/Dialect/SPIRV/IR/SPIRVAvailability.cpp.inc"
3617 } // namespace spirv
3618 } // namespace mlir
3619 
3620 // TablenGen'erated operation definitions.
3621 #define GET_OP_CLASSES
3622 #include "mlir/Dialect/SPIRV/IR/SPIRVOps.cpp.inc"
3623 
3624 namespace mlir {
3625 namespace spirv {
3626 // TableGen'erated operation availability interface implementations.
3627 #include "mlir/Dialect/SPIRV/IR/SPIRVOpAvailabilityImpl.inc"
3628 
3629 } // namespace spirv
3630 } // namespace mlir
3631