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