MLIR 24.0.0git
SPIRVDialect.cpp
Go to the documentation of this file.
1//===- LLVMDialect.cpp - MLIR SPIR-V dialect ------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM
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 SPIR-V dialect in MLIR.
10//
11//===----------------------------------------------------------------------===//
12
14
15#include "SPIRVParsingUtils.h"
16
22#include "mlir/IR/Builders.h"
25#include "mlir/IR/MLIRContext.h"
26#include "mlir/Parser/Parser.h"
28#include "llvm/ADT/Sequence.h"
29#include "llvm/ADT/StringExtras.h"
30#include "llvm/ADT/TypeSwitch.h"
31
32#include <optional>
33
34using namespace mlir;
35using namespace mlir::spirv;
36
37#include "mlir/Dialect/SPIRV/IR/SPIRVOpsDialect.cpp.inc"
38
39//===----------------------------------------------------------------------===//
40// InlinerInterface
41//===----------------------------------------------------------------------===//
42
43/// Returns true if the given region contains spirv.Return or spirv.ReturnValue
44/// ops.
45static inline bool containsReturn(Region &region) {
46 return llvm::any_of(region, [](Block &block) {
47 Operation *terminator = block.getTerminator();
48 return isa<spirv::ReturnOp, spirv::ReturnValueOp>(terminator);
49 });
50}
51
52namespace {
53/// This class defines the interface for inlining within the SPIR-V dialect.
54struct SPIRVInlinerInterface : public DialectInlinerInterface {
55 using DialectInlinerInterface::DialectInlinerInterface;
56
57 /// All call operations within SPIRV can be inlined.
58 bool isLegalToInline(Operation *call, Operation *callable,
59 bool wouldBeCloned) const final {
60 return true;
61 }
62
63 /// Returns true if the given region 'src' can be inlined into the region
64 /// 'dest' that is attached to an operation registered to the current dialect.
65 bool isLegalToInline(Region *dest, Region *src, bool wouldBeCloned,
66 IRMapping &) const final {
67 // Return true here when inlining into spirv.func, spirv.mlir.selection, and
68 // spirv.mlir.loop operations.
69 auto *op = dest->getParentOp();
70 return isa<spirv::FuncOp, spirv::SelectionOp, spirv::LoopOp>(op);
71 }
72
73 /// Returns true if the given operation 'op', that is registered to this
74 /// dialect, can be inlined into the region 'dest' that is attached to an
75 /// operation registered to the current dialect.
76 bool isLegalToInline(Operation *op, Region *dest, bool wouldBeCloned,
77 IRMapping &) const final {
78 // TODO: Enable inlining structured control flows with return.
79 if ((isa<spirv::SelectionOp, spirv::LoopOp>(op)) &&
80 containsReturn(op->getRegion(0)))
81 return false;
82 // TODO: we need to filter OpKill here to avoid inlining it to
83 // a loop continue construct:
84 // https://github.com/KhronosGroup/SPIRV-Headers/issues/86
85 // For now, we just disallow inlining OpKill anywhere in the code,
86 // but this restriction should be relaxed, as pointed above.
87 if (isa<spirv::KillOp>(op))
88 return false;
89
90 return true;
91 }
92
93 /// Handle the given inlined terminator by replacing it with a new operation
94 /// as necessary.
95 void handleTerminator(Operation *op, Block *newDest) const final {
96 if (auto returnOp = dyn_cast<spirv::ReturnOp>(op)) {
97 auto builder = OpBuilder(op);
98 spirv::BranchOp::create(builder, op->getLoc(), newDest);
99 op->erase();
100 } else if (auto retValOp = dyn_cast<spirv::ReturnValueOp>(op)) {
101 auto builder = OpBuilder(op);
102 spirv::BranchOp::create(builder, retValOp->getLoc(), newDest,
103 retValOp->getOperands());
104 op->erase();
105 }
106 }
107
108 /// Handle the given inlined terminator by replacing it with a new operation
109 /// as necessary.
110 void handleTerminator(Operation *op, ValueRange valuesToRepl) const final {
111 // Only spirv.ReturnValue needs to be handled here.
112 auto retValOp = dyn_cast<spirv::ReturnValueOp>(op);
113 if (!retValOp)
114 return;
115
116 // Replace the values directly with the return operands.
117 assert(valuesToRepl.size() == 1 &&
118 "spirv.ReturnValue expected to only handle one result");
119 valuesToRepl.front().replaceAllUsesWith(retValOp.getValue());
120 }
121};
122} // namespace
123
124//===----------------------------------------------------------------------===//
125// SPIR-V Dialect
126//===----------------------------------------------------------------------===//
127
128void SPIRVDialect::initialize() {
129 registerAttributes();
130 registerTypes();
131
132 addInterfaces<SPIRVInlinerInterface>();
133
134 // Allow unknown operations because SPIR-V is extensible.
135 allowUnknownOperations();
136 declarePromisedInterface<gpu::TargetAttrInterface, TargetEnvAttr>();
137}
138
139std::string SPIRVDialect::getAttributeName(Decoration decoration) {
140 return getDecorationString(decoration);
141}
142
143//===----------------------------------------------------------------------===//
144// Type Parsing
145//===----------------------------------------------------------------------===//
146
147// Forward declarations.
148template <typename ValTy>
149static std::optional<ValTy> parseAndVerify(SPIRVDialect const &dialect,
150 DialectAsmParser &parser);
151template <>
152std::optional<Type> parseAndVerify<Type>(SPIRVDialect const &dialect,
153 DialectAsmParser &parser);
154
155template <>
156std::optional<unsigned> parseAndVerify<unsigned>(SPIRVDialect const &dialect,
157 DialectAsmParser &parser);
158
159static Type parseAndVerifyType(SPIRVDialect const &dialect,
160 DialectAsmParser &parser,
161 bool allowFunctionType = false) {
162 Type type;
163 SMLoc typeLoc = parser.getCurrentLocation();
164 if (parser.parseType(type))
165 return Type();
166
167 // Allow SPIR-V dialect types.
168 if (&type.getDialect() == &dialect)
169 return type;
170
171 // Check other allowed types.
172 if (auto t = dyn_cast<FunctionType>(type); t && allowFunctionType) {
173 if (t.getNumResults() > 1) {
174 parser.emitError(typeLoc, "function type must have at most one result");
175 return Type();
176 }
177 for (Type elementType :
178 llvm::concat<const Type>(t.getInputs(), t.getResults())) {
179 if (!isa<SPIRVType>(elementType)) {
180 parser.emitError(typeLoc, "cannot use ")
181 << elementType << " to compose SPIR-V types";
182 return Type();
183 }
184 }
185 } else if (auto t = dyn_cast<FloatType>(type)) {
186 if (!ScalarType::isValid(t)) {
187 parser.emitError(typeLoc,
188 "only 8/16/32/64-bit float type allowed but found ")
189 << type;
190 return Type();
191 }
192 } else if (auto t = dyn_cast<IntegerType>(type)) {
193 if (!ScalarType::isValid(t)) {
194 parser.emitError(typeLoc,
195 "only 1/8/16/32/64-bit integer type allowed but found ")
196 << type;
197 return Type();
198 }
199 } else if (auto t = dyn_cast<VectorType>(type)) {
200 if (t.getRank() != 1) {
201 parser.emitError(typeLoc, "only 1-D vector allowed but found ") << t;
202 return Type();
203 }
204 if (t.getNumElements() < 2) {
205 parser.emitError(typeLoc, "SPIR-V does not allow one-element vectors");
206 return Type();
207 }
208 if (t.getNumElements() > 4) {
209 parser.emitError(
210 typeLoc, "vector length has to be less than or equal to 4 but found ")
211 << t.getNumElements();
212 return Type();
213 }
214 if (!isa<ScalarType>(t.getElementType())) {
215 parser.emitError(
216 typeLoc,
217 "vector element type must be a SPIR-V scalar type but found ")
218 << t.getElementType();
219 return Type();
220 }
221 } else if (auto t = dyn_cast<TensorArmType>(type)) {
222 if (!isa<ScalarType>(t.getElementType())) {
223 parser.emitError(
224 typeLoc, "only scalar element type allowed in tensor type but found ")
225 << t.getElementType();
226 return Type();
227 }
228 } else {
229 parser.emitError(typeLoc, "cannot use ")
230 << type << " to compose SPIR-V types";
231 return Type();
232 }
233
234 return type;
235}
236
237static Type parseAndVerifyMatrixType(SPIRVDialect const &dialect,
238 DialectAsmParser &parser) {
239 Type type;
240 SMLoc typeLoc = parser.getCurrentLocation();
241 if (parser.parseType(type))
242 return Type();
243
244 if (auto t = dyn_cast<VectorType>(type)) {
245 if (t.getRank() != 1) {
246 parser.emitError(typeLoc, "only 1-D vector allowed but found ") << t;
247 return Type();
248 }
249 if (t.getNumElements() > 4 || t.getNumElements() < 2) {
250 parser.emitError(typeLoc,
251 "matrix columns size has to be less than or equal "
252 "to 4 and greater than or equal 2, but found ")
253 << t.getNumElements();
254 return Type();
255 }
256
257 if (!isa<FloatType>(t.getElementType())) {
258 parser.emitError(typeLoc, "matrix columns' elements must be of "
259 "Float type, got ")
260 << t.getElementType();
261 return Type();
262 }
263 } else {
264 parser.emitError(typeLoc, "matrix must be composed using vector "
265 "type, got ")
266 << type;
267 return Type();
268 }
269
270 return type;
271}
272
273static Type parseAndVerifySampledImageType(SPIRVDialect const &dialect,
274 DialectAsmParser &parser) {
275 Type type;
276 SMLoc typeLoc = parser.getCurrentLocation();
277 if (parser.parseType(type))
278 return Type();
279
280 auto imageType = dyn_cast<ImageType>(type);
281 if (!imageType) {
282 parser.emitError(typeLoc,
283 "sampled image must be composed using image type, got ")
284 << type;
285 return Type();
286 }
287
288 if (llvm::is_contained({Dim::SubpassData, Dim::Buffer}, imageType.getDim())) {
289 parser.emitError(
290 typeLoc, "sampled image Dim must not be SubpassData or Buffer, got ")
291 << stringifyDim(imageType.getDim());
292 return Type();
293 }
294
295 return type;
296}
297
298/// Parses an optional `, stride = N` assembly segment. If no parsing failure
299/// occurs, writes `N` to `stride` if existing and writes 0 to `stride` if
300/// missing.
301static LogicalResult parseOptionalArrayStride(const SPIRVDialect &dialect,
302 DialectAsmParser &parser,
303 unsigned &stride) {
304 if (failed(parser.parseOptionalComma())) {
305 stride = 0;
306 return success();
307 }
308
309 if (parser.parseKeyword("stride") || parser.parseEqual())
310 return failure();
311
312 SMLoc strideLoc = parser.getCurrentLocation();
313 std::optional<unsigned> optStride = parseAndVerify<unsigned>(dialect, parser);
314 if (!optStride)
315 return failure();
316
317 if (!(stride = *optStride)) {
318 parser.emitError(strideLoc, "ArrayStride must be greater than zero");
319 return failure();
320 }
321 return success();
322}
323
324// element-type ::= integer-type
325// | floating-point-type
326// | vector-type
327// | spirv-type
328//
329// array-type ::= `!spirv.array` `<` integer-literal `x` element-type
330// (`,` `stride` `=` integer-literal)? `>`
331static Type parseArrayType(SPIRVDialect const &dialect,
332 DialectAsmParser &parser) {
333 if (parser.parseLess())
334 return Type();
335
336 SmallVector<int64_t, 1> countDims;
337 SMLoc countLoc = parser.getCurrentLocation();
338 if (parser.parseDimensionList(countDims, /*allowDynamic=*/false))
339 return Type();
340 if (countDims.size() != 1) {
341 parser.emitError(countLoc,
342 "expected single integer for array element count");
343 return Type();
344 }
345
346 // According to the SPIR-V spec:
347 // "Length is the number of elements in the array. It must be at least 1."
348 int64_t count = countDims[0];
349 if (count == 0) {
350 parser.emitError(countLoc, "expected array length greater than 0");
351 return Type();
352 }
353
354 Type elementType = parseAndVerifyType(dialect, parser);
355 if (!elementType)
356 return Type();
357
358 unsigned stride = 0;
359 if (failed(parseOptionalArrayStride(dialect, parser, stride)))
360 return Type();
361
362 if (parser.parseGreater())
363 return Type();
364 return ArrayType::get(elementType, count, stride);
365}
366
367// cooperative-matrix-type ::=
368// `!spirv.coopmatrix` `<` rows `x` columns `x` element-type `,`
369// scope `,` use `>`
370static Type parseCooperativeMatrixType(SPIRVDialect const &dialect,
371 DialectAsmParser &parser) {
372 if (parser.parseLess())
373 return {};
374
376 SMLoc countLoc = parser.getCurrentLocation();
377 if (parser.parseDimensionList(dims, /*allowDynamic=*/false))
378 return {};
379
380 if (dims.size() != 2) {
381 parser.emitError(countLoc, "expected row and column count");
382 return {};
383 }
384
385 auto elementTy = parseAndVerifyType(dialect, parser);
386 if (!elementTy)
387 return {};
388
389 Scope scope;
390 if (parser.parseComma() ||
391 spirv::parseEnumKeywordAttr(scope, parser, "scope <id>"))
392 return {};
393
394 CooperativeMatrixUseKHR use;
395 if (parser.parseComma() ||
396 spirv::parseEnumKeywordAttr(use, parser, "use <id>"))
397 return {};
398
399 if (parser.parseGreater())
400 return {};
401
403 [&] { return parser.emitError(parser.getNameLoc()); },
404 elementTy.getContext(), elementTy, dims[0], dims[1], scope, use);
405}
406
407// tensor-arm-type ::=
408// `!spirv.arm.tensor` `<` dim0 `x` dim1 `x` ... `x` dimN `x` element-type`>`
409static Type parseTensorArmType(SPIRVDialect const &dialect,
410 DialectAsmParser &parser) {
411 if (parser.parseLess())
412 return {};
413
414 bool unranked = false;
416 SMLoc countLoc = parser.getCurrentLocation();
417
418 if (parser.parseOptionalStar().succeeded()) {
419 unranked = true;
420 if (parser.parseXInDimensionList())
421 return {};
422 } else if (parser.parseDimensionList(dims, /*allowDynamic=*/true)) {
423 return {};
424 }
425
426 if (!unranked && dims.empty()) {
427 parser.emitError(countLoc, "arm.tensors do not support rank zero");
428 return {};
429 }
430
431 if (llvm::is_contained(dims, 0)) {
432 parser.emitError(countLoc, "arm.tensors do not support zero dimensions");
433 return {};
434 }
435
436 if (llvm::any_of(dims, [](int64_t dim) { return dim < 0; }) &&
437 llvm::any_of(dims, [](int64_t dim) { return dim > 0; })) {
438 parser.emitError(countLoc, "arm.tensor shape dimensions must be either "
439 "fully dynamic or completed shaped");
440 return {};
441 }
442
443 auto elementTy = parseAndVerifyType(dialect, parser);
444 if (!elementTy)
445 return {};
446
447 if (parser.parseGreater())
448 return {};
449
450 return TensorArmType::get(dims, elementTy);
451}
452
453// TODO: Reorder methods to be utilities first and parse*Type
454// methods in alphabetical order
455//
456// storage-class ::= `UniformConstant`
457// | `Uniform`
458// | `Workgroup`
459// | <and other storage classes...>
460//
461// pointer-type ::= `!spirv.ptr<` element-type `,` storage-class `>`
462static Type parsePointerType(SPIRVDialect const &dialect,
463 DialectAsmParser &parser) {
464 if (parser.parseLess())
465 return Type();
466
467 auto pointeeType =
468 parseAndVerifyType(dialect, parser, /*allowFunctionType=*/true);
469 if (!pointeeType)
470 return Type();
471
472 StringRef storageClassSpec;
473 SMLoc storageClassLoc = parser.getCurrentLocation();
474 if (parser.parseComma() || parser.parseKeyword(&storageClassSpec))
475 return Type();
476
477 auto storageClass = symbolizeStorageClass(storageClassSpec);
478 if (!storageClass) {
479 parser.emitError(storageClassLoc, "unknown storage class: ")
480 << storageClassSpec;
481 return Type();
482 }
483 if (parser.parseGreater())
484 return Type();
486 [&] { return parser.emitError(storageClassLoc); },
487 pointeeType.getContext(), pointeeType, *storageClass);
488}
489
490// untyped-pointer-type ::= `!spirv.untyped_ptr<` storage-class `>`
491static Type parseUntypedPointerType(SPIRVDialect const &dialect,
492 DialectAsmParser &parser) {
493 if (parser.parseLess())
494 return Type();
495
496 StringRef storageClassSpec;
497 SMLoc storageClassLoc = parser.getCurrentLocation();
498 if (parser.parseKeyword(&storageClassSpec))
499 return Type();
500
501 auto storageClass = symbolizeStorageClass(storageClassSpec);
502 if (!storageClass) {
503 parser.emitError(storageClassLoc, "unknown storage class: ")
504 << storageClassSpec;
505 return Type();
506 }
507 if (parser.parseGreater())
508 return Type();
509 return UntypedPointerType::get(dialect.getContext(), *storageClass);
510}
511
512// runtime-array-type ::= `!spirv.rtarray` `<` element-type
513// (`,` `stride` `=` integer-literal)? `>`
514static Type parseRuntimeArrayType(SPIRVDialect const &dialect,
515 DialectAsmParser &parser) {
516 if (parser.parseLess())
517 return Type();
518
519 Type elementType = parseAndVerifyType(dialect, parser);
520 if (!elementType)
521 return Type();
522
523 unsigned stride = 0;
524 if (failed(parseOptionalArrayStride(dialect, parser, stride)))
525 return Type();
526
527 if (parser.parseGreater())
528 return Type();
529 return RuntimeArrayType::get(elementType, stride);
530}
531
532// matrix-type ::= `!spirv.matrix` `<` integer-literal `x` element-type `>`
533static Type parseMatrixType(SPIRVDialect const &dialect,
534 DialectAsmParser &parser) {
535 if (parser.parseLess())
536 return Type();
537
538 SmallVector<int64_t, 1> countDims;
539 SMLoc countLoc = parser.getCurrentLocation();
540 if (parser.parseDimensionList(countDims, /*allowDynamic=*/false))
541 return Type();
542 if (countDims.size() != 1) {
543 parser.emitError(countLoc, "expected single unsigned "
544 "integer for number of columns");
545 return Type();
546 }
547
548 int64_t columnCount = countDims[0];
549 // According to the specification, Matrices can have 2, 3, or 4 columns
550 if (columnCount < 2 || columnCount > 4) {
551 parser.emitError(countLoc, "matrix is expected to have 2, 3, or 4 "
552 "columns");
553 return Type();
554 }
555
556 Type columnType = parseAndVerifyMatrixType(dialect, parser);
557 if (!columnType)
558 return Type();
559
560 if (parser.parseGreater())
561 return Type();
562
564 [&] { return parser.emitError(parser.getNameLoc()); }, columnType,
565 columnCount);
566}
567
568// Specialize this function to parse each of the parameters that define an
569// ImageType. By default it assumes this is an enum type.
570template <typename ValTy>
571static std::optional<ValTy> parseAndVerify(SPIRVDialect const &dialect,
572 DialectAsmParser &parser) {
573 StringRef enumSpec;
574 SMLoc enumLoc = parser.getCurrentLocation();
575 if (parser.parseKeyword(&enumSpec)) {
576 return std::nullopt;
577 }
578
579 auto val = spirv::symbolizeEnum<ValTy>(enumSpec);
580 if (!val)
581 parser.emitError(enumLoc, "unknown attribute: '") << enumSpec << "'";
582 return val;
583}
584
585template <>
586std::optional<Type> parseAndVerify<Type>(SPIRVDialect const &dialect,
587 DialectAsmParser &parser) {
588 // TODO: Further verify that the element type can be sampled
589 auto ty = parseAndVerifyType(dialect, parser);
590 if (!ty)
591 return std::nullopt;
592 return ty;
593}
594
595template <typename IntTy>
596static std::optional<IntTy> parseAndVerifyInteger(SPIRVDialect const &dialect,
597 DialectAsmParser &parser) {
598 IntTy offsetVal = std::numeric_limits<IntTy>::max();
599 if (parser.parseInteger(offsetVal))
600 return std::nullopt;
601 return offsetVal;
602}
603
604template <>
605std::optional<unsigned> parseAndVerify<unsigned>(SPIRVDialect const &dialect,
606 DialectAsmParser &parser) {
607 return parseAndVerifyInteger<unsigned>(dialect, parser);
608}
609
610namespace {
611// Functor object to parse a comma separated list of specs. The function
612// parseAndVerify does the actual parsing and verification of individual
613// elements. This is a functor since parsing the last element of the list
614// (termination condition) needs partial specialization.
615template <typename ParseType, typename... Args>
616struct ParseCommaSeparatedList {
617 std::optional<std::tuple<ParseType, Args...>>
618 operator()(SPIRVDialect const &dialect, DialectAsmParser &parser) const {
619 auto parseVal = parseAndVerify<ParseType>(dialect, parser);
620 if (!parseVal)
621 return std::nullopt;
622
623 auto numArgs = std::tuple_size<std::tuple<Args...>>::value;
624 if (numArgs != 0 && failed(parser.parseComma()))
625 return std::nullopt;
626 auto remainingValues = ParseCommaSeparatedList<Args...>{}(dialect, parser);
627 if (!remainingValues)
628 return std::nullopt;
629 return std::tuple_cat(std::tuple<ParseType>(parseVal.value()),
630 remainingValues.value());
631 }
632};
633
634// Partial specialization of the function to parse a comma separated list of
635// specs to parse the last element of the list.
636template <typename ParseType>
637struct ParseCommaSeparatedList<ParseType> {
638 std::optional<std::tuple<ParseType>>
639 operator()(SPIRVDialect const &dialect, DialectAsmParser &parser) const {
640 if (auto value = parseAndVerify<ParseType>(dialect, parser))
641 return std::tuple<ParseType>(*value);
642 return std::nullopt;
643 }
644};
645} // namespace
646
647// dim ::= `1D` | `2D` | `3D` | `Cube` | <and other SPIR-V Dim specifiers...>
648//
649// depth-info ::= `NoDepth` | `IsDepth` | `DepthUnknown`
650//
651// arrayed-info ::= `NonArrayed` | `Arrayed`
652//
653// sampling-info ::= `SingleSampled` | `MultiSampled`
654//
655// sampler-use-info ::= `SamplerUnknown` | `NeedSampler` | `NoSampler`
656//
657// format ::= `Unknown` | `Rgba32f` | <and other SPIR-V Image formats...>
658//
659// image-type ::= `!spirv.image<` element-type `,` dim `,` depth-info `,`
660// arrayed-info `,` sampling-info `,`
661// sampler-use-info `,` format `>`
662static Type parseImageType(SPIRVDialect const &dialect,
663 DialectAsmParser &parser) {
664 if (parser.parseLess())
665 return Type();
666
667 auto value =
668 ParseCommaSeparatedList<Type, Dim, ImageDepthInfo, ImageArrayedInfo,
669 ImageSamplingInfo, ImageSamplerUseInfo,
670 ImageFormat>{}(dialect, parser);
671 if (!value)
672 return Type();
673
674 if (parser.parseGreater())
675 return Type();
677 [&] { return parser.emitError(parser.getNameLoc()); },
678 std::get<0>(*value).getContext(), *value);
679}
680
681// sampledImage-type :: = `!spirv.sampledImage<` image-type `>`
682static Type parseSampledImageType(SPIRVDialect const &dialect,
683 DialectAsmParser &parser) {
684 if (parser.parseLess())
685 return Type();
686
687 Type parsedType = parseAndVerifySampledImageType(dialect, parser);
688 if (!parsedType)
689 return Type();
690
691 if (parser.parseGreater())
692 return Type();
693 return SampledImageType::get(parsedType);
694}
695
696// Parse decorations associated with a member.
698 SPIRVDialect const &dialect, DialectAsmParser &parser,
699 ArrayRef<Type> memberTypes,
702
703 // Check if the first element is offset.
704 SMLoc offsetLoc = parser.getCurrentLocation();
705 StructType::OffsetInfo offset = 0;
706 OptionalParseResult offsetParseResult = parser.parseOptionalInteger(offset);
707 if (offsetParseResult.has_value()) {
708 if (failed(*offsetParseResult))
709 return failure();
710
711 if (offsetInfo.size() != memberTypes.size() - 1) {
712 return parser.emitError(offsetLoc,
713 "offset specification must be given for "
714 "all members");
715 }
716 offsetInfo.push_back(offset);
717 }
718
719 // Check for no spirv::Decorations.
720 if (succeeded(parser.parseOptionalRSquare()))
721 return success();
722
723 // If there was an offset, make sure to parse the comma.
724 if (offsetParseResult.has_value() && parser.parseComma())
725 return failure();
726
727 // Check for spirv::Decorations.
728 auto parseDecorations = [&]() {
729 auto memberDecoration = parseAndVerify<spirv::Decoration>(dialect, parser);
730 if (!memberDecoration)
731 return failure();
732
733 // Parse member decoration value if it exists.
734 if (succeeded(parser.parseOptionalEqual())) {
735 Attribute memberDecorationValue;
736 if (failed(parser.parseAttribute(memberDecorationValue)))
737 return failure();
738
739 memberDecorationInfo.emplace_back(
740 static_cast<uint32_t>(memberTypes.size() - 1),
741 memberDecoration.value(), memberDecorationValue);
742 } else {
743 memberDecorationInfo.emplace_back(
744 static_cast<uint32_t>(memberTypes.size() - 1),
745 memberDecoration.value(), UnitAttr::get(dialect.getContext()));
746 }
747 return success();
748 };
749 if (failed(parser.parseCommaSeparatedList(parseDecorations)) ||
750 failed(parser.parseRSquare()))
751 return failure();
752
753 return success();
754}
755
756// struct-member-decoration ::= integer-literal? spirv-decoration*
757// struct-type ::=
758// `!spirv.struct<` (id `,`)?
759// `(`
760// (spirv-type (`[` struct-member-decoration `]`)?)*
761// `)`
762// (`,` struct-decoration)?
763// `>`
764static Type parseStructType(SPIRVDialect const &dialect,
765 DialectAsmParser &parser) {
766 // TODO: This function is quite lengthy. Break it down into smaller chunks.
767
768 if (parser.parseLess())
769 return Type();
770
771 StringRef identifier;
772 FailureOr<DialectAsmParser::CyclicParseReset> cyclicParse;
773
774 // Check if this is an identified struct type.
775 if (succeeded(parser.parseOptionalKeyword(&identifier))) {
776 // Check if this is a possible recursive reference.
777 auto structType =
778 StructType::getIdentified(dialect.getContext(), identifier);
779 cyclicParse = parser.tryStartCyclicParse(structType);
780 if (succeeded(parser.parseOptionalGreater())) {
781 if (succeeded(cyclicParse)) {
782 parser.emitError(
783 parser.getNameLoc(),
784 "recursive struct reference not nested in struct definition");
785
786 return Type();
787 }
788
789 return structType;
790 }
791
792 if (failed(parser.parseComma()))
793 return Type();
794
795 if (failed(cyclicParse)) {
796 parser.emitError(parser.getNameLoc(),
797 "identifier already used for an enclosing struct");
798 return Type();
799 }
800 }
801
802 if (failed(parser.parseLParen()))
803 return Type();
804
805 if (succeeded(parser.parseOptionalRParen()) &&
806 succeeded(parser.parseOptionalGreater())) {
807 return StructType::getEmpty(dialect.getContext(), identifier);
808 }
809
810 StructType idStructTy;
811
812 if (!identifier.empty())
813 idStructTy = StructType::getIdentified(dialect.getContext(), identifier);
814
815 SmallVector<Type, 4> memberTypes;
818
819 do {
820 Type memberType;
821 if (parser.parseType(memberType))
822 return Type();
823 if (!isa<SPIRVType>(memberType)) {
824 parser.emitError(parser.getNameLoc(),
825 "member type must be a valid SPIR-V type");
826 return Type();
827 }
828 memberTypes.push_back(memberType);
829
830 if (succeeded(parser.parseOptionalLSquare()))
831 if (parseStructMemberDecorations(dialect, parser, memberTypes, offsetInfo,
832 memberDecorationInfo))
833 return Type();
834 } while (succeeded(parser.parseOptionalComma()));
835
836 if (!offsetInfo.empty() && memberTypes.size() != offsetInfo.size()) {
837 parser.emitError(parser.getNameLoc(),
838 "offset specification must be given for all members");
839 return Type();
840 }
841
842 if (failed(parser.parseRParen()))
843 return Type();
844
846
847 auto parseStructDecoration = [&]() {
848 std::optional<spirv::Decoration> decoration =
849 parseAndVerify<spirv::Decoration>(dialect, parser);
850 if (!decoration)
851 return failure();
852
853 // Parse decoration value if it exists.
854 if (succeeded(parser.parseOptionalEqual())) {
855 Attribute decorationValue;
856 if (failed(parser.parseAttribute(decorationValue)))
857 return failure();
858
859 structDecorationInfo.emplace_back(decoration.value(), decorationValue);
860 } else {
861 structDecorationInfo.emplace_back(decoration.value(),
862 UnitAttr::get(dialect.getContext()));
863 }
864 return success();
865 };
866
867 while (succeeded(parser.parseOptionalComma()))
868 if (failed(parseStructDecoration()))
869 return Type();
870
871 if (failed(parser.parseGreater()))
872 return Type();
873
874 if (!identifier.empty()) {
875 if (failed(idStructTy.trySetBody(memberTypes, offsetInfo,
876 memberDecorationInfo,
877 structDecorationInfo)))
878 return Type();
879 return idStructTy;
880 }
881
882 return StructType::get(memberTypes, offsetInfo, memberDecorationInfo,
883 structDecorationInfo);
884}
885
886// spirv-type ::= array-type
887// | element-type
888// | image-type
889// | pointer-type
890// | runtime-array-type
891// | sampled-image-type
892// | struct-type
893Type SPIRVDialect::parseType(DialectAsmParser &parser) const {
894 StringRef keyword;
895 if (parser.parseKeyword(&keyword))
896 return Type();
897
898 if (keyword == "array")
899 return parseArrayType(*this, parser);
900 if (keyword == "coopmatrix")
901 return parseCooperativeMatrixType(*this, parser);
902 if (keyword == "image")
903 return parseImageType(*this, parser);
904 if (keyword == "ptr")
905 return parsePointerType(*this, parser);
906 if (keyword == "rtarray")
907 return parseRuntimeArrayType(*this, parser);
908 if (keyword == "sampled_image")
909 return parseSampledImageType(*this, parser);
910 if (keyword == "sampler")
912 if (keyword == "named_barrier")
914 if (keyword == "untyped_ptr")
915 return parseUntypedPointerType(*this, parser);
916 if (keyword == "struct")
917 return parseStructType(*this, parser);
918 if (keyword == "matrix")
919 return parseMatrixType(*this, parser);
920 if (keyword == "arm.tensor")
921 return parseTensorArmType(*this, parser);
922 parser.emitError(parser.getNameLoc(), "unknown SPIR-V type: ") << keyword;
923 return Type();
924}
925
926//===----------------------------------------------------------------------===//
927// Type Printing
928//===----------------------------------------------------------------------===//
929
930static void print(ArrayType type, DialectAsmPrinter &os) {
931 os << "array<" << type.getNumElements() << " x " << type.getElementType();
932 if (unsigned stride = type.getArrayStride())
933 os << ", stride=" << stride;
934 os << ">";
935}
936
938 os << "rtarray<" << type.getElementType();
939 if (unsigned stride = type.getArrayStride())
940 os << ", stride=" << stride;
941 os << ">";
942}
943
944static void print(PointerType type, DialectAsmPrinter &os) {
945 os << "ptr<" << type.getPointeeType() << ", "
946 << stringifyStorageClass(type.getStorageClass()) << ">";
947}
948
949static void print(ImageType type, DialectAsmPrinter &os) {
950 os << "image<" << type.getElementType() << ", " << stringifyDim(type.getDim())
951 << ", " << stringifyImageDepthInfo(type.getDepthInfo()) << ", "
952 << stringifyImageArrayedInfo(type.getArrayedInfo()) << ", "
953 << stringifyImageSamplingInfo(type.getSamplingInfo()) << ", "
954 << stringifyImageSamplerUseInfo(type.getSamplerUseInfo()) << ", "
955 << stringifyImageFormat(type.getImageFormat()) << ">";
956}
957
959 os << "sampled_image<" << type.getImageType() << ">";
960}
961
962static void print(SamplerType type, DialectAsmPrinter &os) { os << "sampler"; }
963
965 os << "named_barrier";
966}
967
969 os << "untyped_ptr<" << stringifyStorageClass(type.getStorageClass()) << ">";
970}
971
972static void print(StructType type, DialectAsmPrinter &os) {
973 FailureOr<AsmPrinter::CyclicPrintReset> cyclicPrint;
974
975 os << "struct<";
976
977 if (type.isIdentified()) {
978 os << type.getIdentifier();
979
980 cyclicPrint = os.tryStartCyclicPrint(type);
981 if (failed(cyclicPrint)) {
982 os << ">";
983 return;
984 }
985
986 os << ", ";
987 }
988
989 os << "(";
990
991 auto printMember = [&](unsigned i) {
992 os << type.getElementType(i);
994 type.getMemberDecorations(i, decorations);
995 if (type.hasOffset() || !decorations.empty()) {
996 os << " [";
997 if (type.hasOffset()) {
998 os << type.getMemberOffset(i);
999 if (!decorations.empty())
1000 os << ", ";
1001 }
1002 auto eachFn = [&os](spirv::StructType::MemberDecorationInfo decoration) {
1003 os << stringifyDecoration(decoration.decoration);
1004 if (decoration.hasValue()) {
1005 os << "=";
1006 os.printAttributeWithoutType(decoration.decorationValue);
1007 }
1008 };
1009 llvm::interleaveComma(decorations, os, eachFn);
1010 os << "]";
1011 }
1012 };
1013 llvm::interleaveComma(llvm::seq<unsigned>(0, type.getNumElements()), os,
1014 printMember);
1015 os << ")";
1016
1018 type.getStructDecorations(decorations);
1019 if (!decorations.empty()) {
1020 os << ", ";
1021 auto eachFn = [&os](spirv::StructType::StructDecorationInfo decoration) {
1022 os << stringifyDecoration(decoration.decoration);
1023 if (decoration.hasValue()) {
1024 os << "=";
1025 os.printAttributeWithoutType(decoration.decorationValue);
1026 }
1027 };
1028 llvm::interleaveComma(decorations, os, eachFn);
1029 }
1030
1031 os << ">";
1032}
1033
1035 os << "coopmatrix<" << type.getRows() << "x" << type.getColumns() << "x"
1036 << type.getElementType() << ", " << type.getScope() << ", "
1037 << type.getUse() << ">";
1038}
1039
1040static void print(MatrixType type, DialectAsmPrinter &os) {
1041 os << "matrix<" << type.getNumColumns() << " x " << type.getColumnType();
1042 os << ">";
1043}
1044
1045static void print(TensorArmType type, DialectAsmPrinter &os) {
1046 os << "arm.tensor<";
1047
1048 llvm::interleave(
1049 type.getShape(), os,
1050 [&](int64_t dim) {
1051 if (ShapedType::isDynamic(dim))
1052 os << '?';
1053 else
1054 os << dim;
1055 },
1056 "x");
1057 if (!type.hasRank()) {
1058 os << "*";
1059 }
1060 os << "x" << type.getElementType() << ">";
1061}
1062
1063void SPIRVDialect::printType(Type type, DialectAsmPrinter &os) const {
1064 TypeSwitch<Type>(type)
1068 [&](auto type) { print(type, os); })
1069 .DefaultUnreachable("Unhandled SPIR-V type");
1070}
1071
1072//===----------------------------------------------------------------------===//
1073// Constant
1074//===----------------------------------------------------------------------===//
1075
1076Operation *SPIRVDialect::materializeConstant(OpBuilder &builder,
1077 Attribute value, Type type,
1078 Location loc) {
1079 if (auto poison = dyn_cast<ub::PoisonAttr>(value))
1080 return ub::PoisonOp::create(builder, loc, type, poison);
1081
1082 if (!spirv::ConstantOp::isBuildableWith(type))
1083 return nullptr;
1084
1085 return spirv::ConstantOp::create(builder, loc, type, value);
1086}
1087
1088//===----------------------------------------------------------------------===//
1089// Shader Interface ABI
1090//===----------------------------------------------------------------------===//
1091
1092LogicalResult SPIRVDialect::verifyOperationAttribute(Operation *op,
1093 NamedAttribute attribute) {
1094 StringRef symbol = attribute.getName().strref();
1095 Attribute attr = attribute.getValue();
1096
1097 if (symbol == spirv::getEntryPointABIAttrName()) {
1098 if (!isa<spirv::EntryPointABIAttr>(attr)) {
1099 return op->emitError("'")
1100 << symbol << "' attribute must be an entry point ABI attribute";
1101 }
1102 } else if (symbol == spirv::getTargetEnvAttrName()) {
1103 if (!isa<spirv::TargetEnvAttr>(attr))
1104 return op->emitError("'") << symbol << "' must be a spirv::TargetEnvAttr";
1105 } else if (symbol == spirv::getLoopControlAttrName()) {
1106 if (!isa<spirv::LoopControlAttr>(attr))
1107 return op->emitError("'")
1108 << symbol << "' must be a spirv::LoopControlAttr";
1109 } else if (symbol == spirv::getSelectionControlAttrName()) {
1110 if (!isa<spirv::SelectionControlAttr>(attr))
1111 return op->emitError("'")
1112 << symbol << "' must be a spirv::SelectionControlAttr";
1113 } else {
1114 return op->emitError("found unsupported '")
1115 << symbol << "' attribute on operation";
1116 }
1117
1118 return success();
1119}
1120
1121/// Verifies the given SPIR-V `attribute` attached to a value of the given
1122/// `valueType` is valid.
1123static LogicalResult verifyRegionAttribute(Location loc, Type valueType,
1124 NamedAttribute attribute) {
1125 StringRef symbol = attribute.getName().strref();
1126 Attribute attr = attribute.getValue();
1127
1128 if (symbol == spirv::getInterfaceVarABIAttrName()) {
1129 auto varABIAttr = dyn_cast<spirv::InterfaceVarABIAttr>(attr);
1130 if (!varABIAttr)
1131 return emitError(loc, "'")
1132 << symbol << "' must be a spirv::InterfaceVarABIAttr";
1133
1134 if (varABIAttr.getStorageClass() && !valueType.isIntOrIndexOrFloat())
1135 return emitError(loc, "'") << symbol
1136 << "' attribute cannot specify storage class "
1137 "when attaching to a non-scalar value";
1138 return success();
1139 }
1140 if (symbol == spirv::DecorationAttr::name) {
1141 if (!isa<spirv::DecorationAttr>(attr))
1142 return emitError(loc, "'")
1143 << symbol << "' must be a spirv::DecorationAttr";
1144 return success();
1145 }
1146
1147 return emitError(loc, "found unsupported '")
1148 << symbol << "' attribute on region argument";
1149}
1150
1151/// Verifies FuncParamAttr decorations. A missing index denotes a function
1152/// result.
1154 Location loc, Type type, Attribute attr,
1155 std::optional<unsigned> index = std::nullopt) {
1156 auto attrs = dyn_cast<ArrayAttr>(attr);
1157 if (!attrs || attrs.empty() ||
1158 !llvm::all_of(attrs,
1159 llvm::IsaPred<spirv::FunctionParameterAttributeAttr>))
1160 return emitError(loc, "'") << spirv::getFuncParamAttrName()
1161 << "' must be a non-empty array of "
1162 "spirv::FunctionParameterAttributeAttr";
1163
1165 bool hasZext = false, hasSext = false;
1166 for (Attribute element : attrs) {
1167 auto value =
1168 cast<spirv::FunctionParameterAttributeAttr>(element).getValue();
1169 if (llvm::is_contained(seen, value))
1170 return emitError(loc, "duplicate function parameter attribute '")
1171 << spirv::stringifyFunctionParameterAttribute(value) << "'";
1172 seen.push_back(value);
1173
1174 switch (value) {
1175 case spirv::FunctionParameterAttribute::Zext:
1176 case spirv::FunctionParameterAttribute::Sext:
1177 if (!isa<IntegerType>(type))
1178 return emitError(loc, "function parameter attribute '")
1179 << spirv::stringifyFunctionParameterAttribute(value)
1180 << "' requires an integer " << (index ? "parameter" : "result");
1181 hasZext |= value == spirv::FunctionParameterAttribute::Zext;
1182 hasSext |= value == spirv::FunctionParameterAttribute::Sext;
1183 break;
1184 default:
1185 if (!index)
1186 return emitError(loc, "function parameter attribute '")
1187 << spirv::stringifyFunctionParameterAttribute(value)
1188 << "' is not valid on function results";
1189 if (!isa<spirv::PointerType>(type))
1190 return emitError(loc, "function parameter attribute '")
1191 << spirv::stringifyFunctionParameterAttribute(value)
1192 << "' requires a pointer parameter";
1193 if (value == spirv::FunctionParameterAttribute::Sret && *index != 0)
1194 return emitError(loc,
1195 "function parameter attribute 'Sret' requires the "
1196 "first parameter");
1197 break;
1198 }
1199 }
1200 if (hasZext && hasSext)
1201 return emitError(loc, "function parameter attributes 'Zext' and 'Sext' are "
1202 "mutually exclusive");
1203 return success();
1204}
1205
1206LogicalResult SPIRVDialect::verifyRegionArgAttribute(Operation *op,
1207 unsigned regionIndex,
1208 unsigned argIndex,
1209 NamedAttribute attribute) {
1210 auto funcOp = dyn_cast<FunctionOpInterface>(op);
1211 if (!funcOp)
1212 return success();
1213 Type argType = funcOp.getArgumentTypes()[argIndex];
1214
1215 if (attribute.getName() == spirv::getFuncParamAlignmentAttrName()) {
1216 auto alignment = dyn_cast<IntegerAttr>(attribute.getValue());
1217 if (!alignment || !alignment.getType().isSignlessInteger(32))
1218 return op->emitError("'")
1220 << "' must be a 32-bit signless integer attribute";
1221 if (!isa<spirv::PointerType>(argType))
1223 << "' requires a pointer parameter";
1224 return success();
1225 }
1226 if (attribute.getName() == spirv::getFuncParamAttrName())
1227 return verifyFunctionParameterAttributes(op->getLoc(), argType,
1228 attribute.getValue(), argIndex);
1229
1230 return verifyRegionAttribute(op->getLoc(), argType, attribute);
1231}
1232
1233LogicalResult SPIRVDialect::verifyRegionResultAttribute(
1234 Operation *op, unsigned /*regionIndex*/, unsigned resultIndex,
1235 NamedAttribute attribute) {
1236 if (auto funcOp = dyn_cast<spirv::FuncOp>(op)) {
1237 if (attribute.getName() == spirv::getFuncParamAttrName())
1239 op->getLoc(), funcOp.getResultTypes()[resultIndex],
1240 attribute.getValue());
1241 return op->emitError("found unsupported '")
1242 << attribute.getName().strref() << "' attribute on function result";
1243 }
1244 if (auto graphOp = dyn_cast<spirv::GraphARMOp>(op))
1245 return verifyRegionAttribute(
1246 op->getLoc(), graphOp.getResultTypes()[resultIndex], attribute);
1247 return op->emitError(
1248 "cannot attach SPIR-V attributes to region result which is "
1249 "not part of a spirv::GraphARMOp type");
1250}
return success()
static bool isLegalToInline(InlinerInterface &interface, Region *src, Region *insertRegion, bool shouldCloneInlinedRegion, IRMapping &valueMapping)
Utility to check that all of the operations within 'src' can be inlined.
b getContext())
std::optional< unsigned > parseAndVerify< unsigned >(SPIRVDialect const &dialect, DialectAsmParser &parser)
static std::optional< IntTy > parseAndVerifyInteger(SPIRVDialect const &dialect, DialectAsmParser &parser)
static LogicalResult parseOptionalArrayStride(const SPIRVDialect &dialect, DialectAsmParser &parser, unsigned &stride)
Parses an optional , stride = N assembly segment.
static LogicalResult verifyRegionAttribute(Location loc, Type valueType, NamedAttribute attribute)
Verifies the given SPIR-V attribute attached to a value of the given valueType is valid.
static Type parseTensorArmType(SPIRVDialect const &dialect, DialectAsmParser &parser)
static void print(ArrayType type, DialectAsmPrinter &os)
static LogicalResult verifyFunctionParameterAttributes(Location loc, Type type, Attribute attr, std::optional< unsigned > index=std::nullopt)
Verifies FuncParamAttr decorations.
static Type parseSampledImageType(SPIRVDialect const &dialect, DialectAsmParser &parser)
static ParseResult parseStructMemberDecorations(SPIRVDialect const &dialect, DialectAsmParser &parser, ArrayRef< Type > memberTypes, SmallVectorImpl< StructType::OffsetInfo > &offsetInfo, SmallVectorImpl< StructType::MemberDecorationInfo > &memberDecorationInfo)
static Type parseAndVerifyType(SPIRVDialect const &dialect, DialectAsmParser &parser, bool allowFunctionType=false)
static Type parseAndVerifySampledImageType(SPIRVDialect const &dialect, DialectAsmParser &parser)
static Type parseUntypedPointerType(SPIRVDialect const &dialect, DialectAsmParser &parser)
static Type parseCooperativeMatrixType(SPIRVDialect const &dialect, DialectAsmParser &parser)
std::optional< Type > parseAndVerify< Type >(SPIRVDialect const &dialect, DialectAsmParser &parser)
static Type parseAndVerifyMatrixType(SPIRVDialect const &dialect, DialectAsmParser &parser)
static Type parseArrayType(SPIRVDialect const &dialect, DialectAsmParser &parser)
static bool containsReturn(Region &region)
Returns true if the given region contains spirv.Return or spirv.ReturnValue ops.
static Type parseStructType(SPIRVDialect const &dialect, DialectAsmParser &parser)
static Type parseRuntimeArrayType(SPIRVDialect const &dialect, DialectAsmParser &parser)
static Type parseMatrixType(SPIRVDialect const &dialect, DialectAsmParser &parser)
static Type parseImageType(SPIRVDialect const &dialect, DialectAsmParser &parser)
static std::optional< ValTy > parseAndVerify(SPIRVDialect const &dialect, DialectAsmParser &parser)
static Type parsePointerType(SPIRVDialect const &dialect, DialectAsmParser &parser)
virtual OptionalParseResult parseOptionalInteger(APInt &result)=0
Parse an optional integer value from the stream.
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
virtual ParseResult parseOptionalEqual()=0
Parse a = token if present.
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
virtual ParseResult parseRParen()=0
Parse a ) token.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual ParseResult parseRSquare()=0
Parse a ] token.
ParseResult parseInteger(IntT &result)
Parse an integer value from the stream.
virtual ParseResult parseOptionalRParen()=0
Parse a ) token if present.
virtual ParseResult parseLess()=0
Parse a '<' token.
virtual ParseResult parseDimensionList(SmallVectorImpl< int64_t > &dimensions, bool allowDynamic=true, bool withTrailingX=true)=0
Parse a dimension list of a tensor or memref type.
virtual ParseResult parseOptionalGreater()=0
Parse a '>' token if present.
virtual ParseResult parseEqual()=0
Parse a = token.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseOptionalComma()=0
Parse a , token if present.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseOptionalStar()=0
Parse a '*' token if present.
FailureOr< CyclicParseReset > tryStartCyclicParse(AttrOrTypeT attrOrType)
Attempts to start a cyclic parsing region for attrOrType.
virtual ParseResult parseOptionalRSquare()=0
Parse a ] token if present.
virtual ParseResult parseGreater()=0
Parse a '>' token.
virtual ParseResult parseLParen()=0
Parse a ( token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseComma()=0
Parse a , token.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual ParseResult parseOptionalLSquare()=0
Parse a [ token if present.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
virtual ParseResult parseXInDimensionList()=0
Parse an 'x' token in a dimension list, handling the case where the x is juxtaposed with an element t...
virtual void printAttributeWithoutType(Attribute attr)
Print the given attribute without its type.
FailureOr< CyclicPrintReset > tryStartCyclicPrint(AttrOrTypeT attrOrType)
Attempts to start a cyclic printing region for attrOrType.
Attributes are known-constant values of operations.
Definition Attributes.h:25
Block represents an ordered list of Operations.
Definition Block.h:34
Operation * getTerminator()
Get the terminator operation of this block.
Definition Block.cpp:249
The DialectAsmParser has methods for interacting with the asm parser when parsing attributes and type...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:166
StringAttr getName() const
Return the name of the attribute.
Attribute getValue() const
Return the value of the attribute.
Definition Attributes.h:181
This class helps build Operations.
Definition Builders.h:210
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
This class implements Optional functionality for ParseResult.
bool has_value() const
Returns true if we contain a valid ParseResult value.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
Dialect & getDialect() const
Get the dialect this type is registered to.
Definition Types.h:107
bool isIntOrIndexOrFloat() const
Return true if this is an integer (of any signedness), index, or float type.
Definition Types.cpp:122
Type getElementType() const
unsigned getArrayStride() const
Returns the array stride in bytes.
unsigned getNumElements() const
static ArrayType get(Type elementType, unsigned elementCount)
Scope getScope() const
Returns the scope of the matrix.
uint32_t getRows() const
Returns the number of rows of the matrix.
uint32_t getColumns() const
Returns the number of columns of the matrix.
static CooperativeMatrixType getChecked(function_ref< InFlightDiagnostic()> emitError, MLIRContext *context, Type elementType, uint32_t rows, uint32_t columns, Scope scope, CooperativeMatrixUseKHR use)
CooperativeMatrixUseKHR getUse() const
Returns the use parameter of the cooperative matrix.
ImageDepthInfo getDepthInfo() const
ImageArrayedInfo getArrayedInfo() const
ImageFormat getImageFormat() const
ImageSamplerUseInfo getSamplerUseInfo() const
static ImageType getChecked(function_ref< InFlightDiagnostic()> emitError, MLIRContext *context, std::tuple< Type, Dim, ImageDepthInfo, ImageArrayedInfo, ImageSamplingInfo, ImageSamplerUseInfo, ImageFormat > value)
Type getElementType() const
ImageSamplingInfo getSamplingInfo() const
static MatrixType getChecked(function_ref< InFlightDiagnostic()> emitError, Type columnType, uint32_t columnCount)
unsigned getNumColumns() const
Returns the number of columns.
static NamedBarrierType get(MLIRContext *context)
StorageClass getStorageClass() const
static PointerType getChecked(function_ref< InFlightDiagnostic()> emitError, MLIRContext *context, Type pointeeType, StorageClass storageClass)
unsigned getArrayStride() const
Returns the array stride in bytes.
static RuntimeArrayType get(Type elementType)
static SampledImageType get(Type imageType)
static SamplerType get(MLIRContext *context)
static bool isValid(FloatType)
Returns true if the given float type is valid for the SPIR-V dialect.
SPIR-V struct type.
Definition SPIRVTypes.h:314
void getStructDecorations(SmallVectorImpl< StructType::StructDecorationInfo > &structDecorations) const
void getMemberDecorations(SmallVectorImpl< StructType::MemberDecorationInfo > &memberDecorations) const
static StructType getIdentified(MLIRContext *context, StringRef identifier)
Construct an identified StructType.
bool isIdentified() const
Returns true if the StructType is identified.
StringRef getIdentifier() const
For literal structs, return an empty string.
static StructType getEmpty(MLIRContext *context, StringRef identifier="")
Construct a (possibly identified) StructType with no members.
unsigned getNumElements() const
Type getElementType(unsigned) const
LogicalResult trySetBody(ArrayRef< Type > memberTypes, ArrayRef< OffsetInfo > offsetInfo={}, ArrayRef< MemberDecorationInfo > memberDecorations={}, ArrayRef< StructDecorationInfo > structDecorations={})
Sets the contents of an incomplete identified StructType.
static StructType get(ArrayRef< Type > memberTypes, ArrayRef< OffsetInfo > offsetInfo={}, ArrayRef< MemberDecorationInfo > memberDecorations={}, ArrayRef< StructDecorationInfo > structDecorations={})
Construct a literal StructType with at least one member.
uint64_t getMemberOffset(unsigned) const
SPIR-V TensorARM Type.
Definition SPIRVTypes.h:559
static TensorArmType get(ArrayRef< int64_t > shape, Type elementType)
ArrayRef< int64_t > getShape() const
StorageClass getStorageClass() const
static UntypedPointerType get(MLIRContext *context, StorageClass storageClass)
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
StringRef getInterfaceVarABIAttrName()
Returns the attribute name for specifying argument ABI information.
StringRef getLoopControlAttrName()
Returns the attribute name for specifying loop control.
ParseResult parseEnumKeywordAttr(EnumClass &value, ParserType &parser, StringRef attrName=spirv::attributeName< EnumClass >())
Parses the next keyword in parser as an enumerant of the given EnumClass.
StringRef getTargetEnvAttrName()
Returns the attribute name for specifying SPIR-V target environment.
StringRef getFuncParamAttrName()
Returns the attribute name for specifying function parameter and result attributes.
StringRef getFuncParamAlignmentAttrName()
Returns the attribute name for specifying function parameter alignment.
std::string getDecorationString(Decoration decoration)
Converts a SPIR-V Decoration enum value to its snake_case string representation for use in MLIR attri...
StringRef getSelectionControlAttrName()
Returns the attribute name for specifying selection control.
StringRef getEntryPointABIAttrName()
Returns the attribute name for specifying entry point information.
Include the generated interface declarations.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:147