MLIR 23.0.0git
Deserializer.cpp
Go to the documentation of this file.
1//===- Deserializer.cpp - MLIR SPIR-V Deserializer ------------------------===//
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 SPIR-V binary to MLIR SPIR-V module deserializer.
10//
11//===----------------------------------------------------------------------===//
12
13#include "Deserializer.h"
14
19#include "mlir/IR/Builders.h"
20#include "mlir/IR/IRMapping.h"
21#include "mlir/IR/Location.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/Sequence.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringExtras.h"
27#include "llvm/ADT/bit.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/SaveAndRestore.h"
30#include "llvm/Support/raw_ostream.h"
31#include <optional>
32
33using namespace mlir;
34
35#define DEBUG_TYPE "spirv-deserialization"
36
37//===----------------------------------------------------------------------===//
38// Utility Functions
39//===----------------------------------------------------------------------===//
40
41/// Returns true if the given `block` is a function entry block.
42static inline bool isFnEntryBlock(Block *block) {
43 return block->isEntryBlock() &&
44 isa_and_nonnull<spirv::FuncOp>(block->getParentOp());
45}
46
47//===----------------------------------------------------------------------===//
48// Deserializer Method Definitions
49//===----------------------------------------------------------------------===//
50
51spirv::Deserializer::Deserializer(ArrayRef<uint32_t> binary,
52 MLIRContext *context,
54 : binary(binary), context(context), unknownLoc(UnknownLoc::get(context)),
55 module(createModuleOp()), opBuilder(module->getRegion()), options(options)
56#ifndef NDEBUG
57 ,
58 logger(llvm::dbgs())
59#endif
60{
61}
62
63LogicalResult spirv::Deserializer::deserialize() {
64 LLVM_DEBUG({
65 logger.resetIndent();
66 logger.startLine()
67 << "//+++---------- start deserialization ----------+++//\n";
68 });
69
70 if (failed(processHeader()))
71 return failure();
72
73 spirv::Opcode opcode = spirv::Opcode::OpNop;
74 ArrayRef<uint32_t> operands;
75 auto binarySize = binary.size();
76 while (curOffset < binarySize) {
77 // Slice the next instruction out and populate `opcode` and `operands`.
78 // Internally this also updates `curOffset`.
79 if (failed(sliceInstruction(opcode, operands)))
80 return failure();
81
82 if (failed(processInstruction(opcode, operands)))
83 return failure();
84 }
85
86 assert(curOffset == binarySize &&
87 "deserializer should never index beyond the binary end");
88
89 for (auto &deferred : deferredInstructions) {
90 if (failed(processInstruction(deferred.first, deferred.second, false))) {
91 return failure();
92 }
93 }
94
95 attachVCETriple();
96
97 LLVM_DEBUG(logger.startLine()
98 << "//+++-------- completed deserialization --------+++//\n");
99 return success();
100}
101
102OwningOpRef<spirv::ModuleOp> spirv::Deserializer::collect() {
103 return std::move(module);
104}
105
106//===----------------------------------------------------------------------===//
107// Module structure
108//===----------------------------------------------------------------------===//
109
110OwningOpRef<spirv::ModuleOp> spirv::Deserializer::createModuleOp() {
111 OpBuilder builder(context);
112 OperationState state(unknownLoc, spirv::ModuleOp::getOperationName());
113 spirv::ModuleOp::build(builder, state);
114 return cast<spirv::ModuleOp>(Operation::create(state));
115}
116
117LogicalResult spirv::Deserializer::processHeader() {
118 if (binary.size() < spirv::kHeaderWordCount)
119 return emitError(unknownLoc,
120 "SPIR-V binary module must have a 5-word header");
121
122 if (binary[0] != spirv::kMagicNumber)
123 return emitError(unknownLoc, "incorrect magic number");
124
125 // Version number bytes: 0 | major number | minor number | 0
126 uint32_t majorVersion = (binary[1] << 8) >> 24;
127 uint32_t minorVersion = (binary[1] << 16) >> 24;
128 if (majorVersion == 1) {
129 switch (minorVersion) {
130#define MIN_VERSION_CASE(v) \
131 case v: \
132 version = spirv::Version::V_1_##v; \
133 break
134
142#undef MIN_VERSION_CASE
143 default:
144 return emitError(unknownLoc, "unsupported SPIR-V minor version: ")
145 << minorVersion;
146 }
147 } else {
148 return emitError(unknownLoc, "unsupported SPIR-V major version: ")
149 << majorVersion;
150 }
151
152 // TODO: generator number, bound, schema
153 curOffset = spirv::kHeaderWordCount;
154 return success();
155}
156
157LogicalResult
158spirv::Deserializer::processCapability(ArrayRef<uint32_t> operands) {
159 if (operands.size() != 1)
160 return emitError(unknownLoc, "OpCapability must have one parameter");
161
162 auto cap = spirv::symbolizeCapability(operands[0]);
163 if (!cap)
164 return emitError(unknownLoc, "unknown capability: ") << operands[0];
165
166 capabilities.insert(*cap);
167 return success();
168}
169
170LogicalResult spirv::Deserializer::processExtension(ArrayRef<uint32_t> words) {
171 if (words.empty()) {
172 return emitError(
173 unknownLoc,
174 "OpExtension must have a literal string for the extension name");
175 }
176
177 unsigned wordIndex = 0;
178 StringRef extName = decodeStringLiteral(words, wordIndex);
179 if (wordIndex != words.size())
180 return emitError(unknownLoc,
181 "unexpected trailing words in OpExtension instruction");
182 auto ext = spirv::symbolizeExtension(extName);
183 if (!ext)
184 return emitError(unknownLoc, "unknown extension: ") << extName;
185
186 extensions.insert(*ext);
187 return success();
188}
189
190LogicalResult
191spirv::Deserializer::processExtInstImport(ArrayRef<uint32_t> words) {
192 if (words.size() < 2) {
193 return emitError(unknownLoc,
194 "OpExtInstImport must have a result <id> and a literal "
195 "string for the extended instruction set name");
196 }
197
198 unsigned wordIndex = 1;
199 extendedInstSets[words[0]] = decodeStringLiteral(words, wordIndex);
200 if (wordIndex != words.size()) {
201 return emitError(unknownLoc,
202 "unexpected trailing words in OpExtInstImport");
203 }
204 return success();
205}
206
207void spirv::Deserializer::attachVCETriple() {
208 (*module)->setAttr(
209 spirv::ModuleOp::getVCETripleAttrName(),
210 spirv::VerCapExtAttr::get(version, capabilities.getArrayRef(),
211 extensions.getArrayRef(), context));
212}
213
214LogicalResult
215spirv::Deserializer::processMemoryModel(ArrayRef<uint32_t> operands) {
216 if (operands.size() != 2)
217 return emitError(unknownLoc, "OpMemoryModel must have two operands");
218
219 (*module)->setAttr(
220 module->getAddressingModelAttrName(),
221 opBuilder.getAttr<spirv::AddressingModelAttr>(
222 static_cast<spirv::AddressingModel>(operands.front())));
223
224 (*module)->setAttr(module->getMemoryModelAttrName(),
225 opBuilder.getAttr<spirv::MemoryModelAttr>(
226 static_cast<spirv::MemoryModel>(operands.back())));
227
228 return success();
229}
230
231template <typename AttrTy, typename EnumAttrTy, typename EnumTy>
233 Location loc, OpBuilder &opBuilder,
235 StringAttr symbol, StringRef decorationName, StringRef cacheControlKind) {
236 if (words.size() != 4) {
237 return emitError(loc, "OpDecorate with ")
238 << decorationName << " needs a cache control integer literal and a "
239 << cacheControlKind << " cache control literal";
240 }
241 unsigned cacheLevel = words[2];
242 auto cacheControlAttr = static_cast<EnumTy>(words[3]);
243 auto value = opBuilder.getAttr<AttrTy>(cacheLevel, cacheControlAttr);
245 if (auto attrList =
246 dyn_cast_or_null<ArrayAttr>(decorations[words[0]].get(symbol)))
247 llvm::append_range(attrs, attrList);
248 attrs.push_back(value);
249 decorations[words[0]].set(symbol, opBuilder.getArrayAttr(attrs));
250 return success();
251}
252
253LogicalResult spirv::Deserializer::processDecoration(ArrayRef<uint32_t> words) {
254 // TODO: This function should also be auto-generated. For now, since only a
255 // few decorations are processed/handled in a meaningful manner, going with a
256 // manual implementation.
257 if (words.size() < 2) {
258 return emitError(
259 unknownLoc, "OpDecorate must have at least result <id> and Decoration");
260 }
261 auto decorationName =
262 stringifyDecoration(static_cast<spirv::Decoration>(words[1]));
263 if (decorationName.empty()) {
264 return emitError(unknownLoc, "invalid Decoration code : ") << words[1];
265 }
266 auto symbol = getSymbolDecoration(decorationName);
267 switch (static_cast<spirv::Decoration>(words[1])) {
268 case spirv::Decoration::FPFastMathMode:
269 if (words.size() != 3) {
270 return emitError(unknownLoc, "OpDecorate with ")
271 << decorationName << " needs a single integer literal";
272 }
273 decorations[words[0]].set(
274 symbol, FPFastMathModeAttr::get(opBuilder.getContext(),
275 static_cast<FPFastMathMode>(words[2])));
276 break;
277 case spirv::Decoration::FPRoundingMode:
278 if (words.size() != 3) {
279 return emitError(unknownLoc, "OpDecorate with ")
280 << decorationName << " needs a single integer literal";
281 }
282 decorations[words[0]].set(
283 symbol, FPRoundingModeAttr::get(opBuilder.getContext(),
284 static_cast<FPRoundingMode>(words[2])));
285 break;
286 case spirv::Decoration::DescriptorSet:
287 case spirv::Decoration::Binding:
288 case spirv::Decoration::Location:
289 case spirv::Decoration::SpecId:
290 case spirv::Decoration::Index:
291 case spirv::Decoration::Offset:
292 case spirv::Decoration::XfbBuffer:
293 case spirv::Decoration::XfbStride:
294 if (words.size() != 3) {
295 return emitError(unknownLoc, "OpDecorate with ")
296 << decorationName << " needs a single integer literal";
297 }
298 decorations[words[0]].set(
299 symbol, opBuilder.getI32IntegerAttr(static_cast<int32_t>(words[2])));
300 break;
301 case spirv::Decoration::BuiltIn:
302 if (words.size() != 3) {
303 return emitError(unknownLoc, "OpDecorate with ")
304 << decorationName << " needs a single integer literal";
305 }
306 decorations[words[0]].set(
307 symbol, opBuilder.getStringAttr(
308 stringifyBuiltIn(static_cast<spirv::BuiltIn>(words[2]))));
309 break;
310 case spirv::Decoration::ArrayStride:
311 if (words.size() != 3) {
312 return emitError(unknownLoc, "OpDecorate with ")
313 << decorationName << " needs a single integer literal";
314 }
315 typeDecorations[words[0]] = words[2];
316 break;
317 case spirv::Decoration::LinkageAttributes: {
318 if (words.size() < 4) {
319 return emitError(unknownLoc, "OpDecorate with ")
320 << decorationName
321 << " needs at least 1 string and 1 integer literal";
322 }
323 // LinkageAttributes has two parameters ["linkageName", linkageType]
324 // e.g., OpDecorate %imported_func LinkageAttributes "outside.func" Import
325 // "linkageName" is a stringliteral encoded as uint32_t,
326 // hence the size of name is variable length which results in words.size()
327 // being variable length, words.size() = 3 + strlen(name)/4 + 1 or
328 // 3 + ceildiv(strlen(name), 4).
329 unsigned wordIndex = 2;
330 auto linkageName = spirv::decodeStringLiteral(words, wordIndex).str();
331 auto linkageTypeAttr = opBuilder.getAttr<::mlir::spirv::LinkageTypeAttr>(
332 static_cast<::mlir::spirv::LinkageType>(words[wordIndex++]));
333 auto linkageAttr = opBuilder.getAttr<::mlir::spirv::LinkageAttributesAttr>(
334 StringAttr::get(context, linkageName), linkageTypeAttr);
335 decorations[words[0]].set(symbol, dyn_cast<Attribute>(linkageAttr));
336 break;
337 }
338 case spirv::Decoration::Aliased:
339 case spirv::Decoration::AliasedPointer:
340 case spirv::Decoration::Block:
341 case spirv::Decoration::BufferBlock:
342 case spirv::Decoration::Flat:
343 case spirv::Decoration::NonReadable:
344 case spirv::Decoration::NonWritable:
345 case spirv::Decoration::NoPerspective:
346 case spirv::Decoration::NoSignedWrap:
347 case spirv::Decoration::NoUnsignedWrap:
348 case spirv::Decoration::RelaxedPrecision:
349 case spirv::Decoration::Restrict:
350 case spirv::Decoration::RestrictPointer:
351 case spirv::Decoration::NoContraction:
352 case spirv::Decoration::Constant:
353 case spirv::Decoration::Invariant:
354 case spirv::Decoration::Patch:
355 case spirv::Decoration::Coherent:
356 if (words.size() != 2) {
357 return emitError(unknownLoc, "OpDecorate with ")
358 << decorationName << " needs a single target <id>";
359 }
360 decorations[words[0]].set(symbol, opBuilder.getUnitAttr());
361 break;
362 case spirv::Decoration::CacheControlLoadINTEL: {
363 LogicalResult res = deserializeCacheControlDecoration<
364 CacheControlLoadINTELAttr, LoadCacheControlAttr, LoadCacheControl>(
365 unknownLoc, opBuilder, decorations, words, symbol, decorationName,
366 "load");
367 if (failed(res))
368 return res;
369 break;
370 }
371 case spirv::Decoration::CacheControlStoreINTEL: {
372 LogicalResult res = deserializeCacheControlDecoration<
373 CacheControlStoreINTELAttr, StoreCacheControlAttr, StoreCacheControl>(
374 unknownLoc, opBuilder, decorations, words, symbol, decorationName,
375 "store");
376 if (failed(res))
377 return res;
378 break;
379 }
380 default:
381 return emitError(unknownLoc, "unhandled Decoration : '") << decorationName;
382 }
383 return success();
384}
385
386LogicalResult
387spirv::Deserializer::processMemberDecoration(ArrayRef<uint32_t> words) {
388 // The binary layout of OpMemberDecorate is different comparing to OpDecorate
389 if (words.size() < 3) {
390 return emitError(unknownLoc,
391 "OpMemberDecorate must have at least 3 operands");
392 }
393
394 auto decoration = static_cast<spirv::Decoration>(words[2]);
395 if (decoration == spirv::Decoration::Offset && words.size() != 4) {
396 return emitError(unknownLoc,
397 " missing offset specification in OpMemberDecorate with "
398 "Offset decoration");
399 }
400 ArrayRef<uint32_t> decorationOperands;
401 if (words.size() > 3) {
402 decorationOperands = words.slice(3);
403 }
404 memberDecorationMap[words[0]][words[1]][decoration] = decorationOperands;
405 return success();
406}
407
408LogicalResult spirv::Deserializer::processMemberName(ArrayRef<uint32_t> words) {
409 if (words.size() < 3) {
410 return emitError(unknownLoc, "OpMemberName must have at least 3 operands");
411 }
412 unsigned wordIndex = 2;
413 auto name = decodeStringLiteral(words, wordIndex);
414 if (wordIndex != words.size()) {
415 return emitError(unknownLoc,
416 "unexpected trailing words in OpMemberName instruction");
417 }
418 memberNameMap[words[0]][words[1]] = name;
419 return success();
420}
421
423 uint32_t argID, SmallVectorImpl<Attribute> &argAttrs, size_t argIndex) {
424 if (!decorations.contains(argID)) {
425 argAttrs[argIndex] = DictionaryAttr::get(context, {});
426 return success();
427 }
428
429 spirv::DecorationAttr foundDecorationAttr;
430 for (NamedAttribute decAttr : decorations[argID]) {
431 for (auto decoration :
432 {spirv::Decoration::Aliased, spirv::Decoration::Restrict,
433 spirv::Decoration::AliasedPointer,
434 spirv::Decoration::RestrictPointer}) {
435
436 if (decAttr.getName() !=
437 getSymbolDecoration(stringifyDecoration(decoration)))
438 continue;
439
440 if (foundDecorationAttr)
441 return emitError(unknownLoc,
442 "more than one Aliased/Restrict decorations for "
443 "function argument with result <id> ")
444 << argID;
445
446 foundDecorationAttr = spirv::DecorationAttr::get(context, decoration);
447 break;
448 }
449
450 if (decAttr.getName() == getSymbolDecoration(stringifyDecoration(
451 spirv::Decoration::RelaxedPrecision))) {
452 // TODO: Current implementation supports only one decoration per function
453 // parameter so RelaxedPrecision cannot be applied at the same time as,
454 // for example, Aliased/Restrict/etc. This should be relaxed to allow any
455 // combination of decoration allowed by the spec to be supported.
456 if (foundDecorationAttr)
457 return emitError(unknownLoc, "already found a decoration for function "
458 "argument with result <id> ")
459 << argID;
460
461 foundDecorationAttr = spirv::DecorationAttr::get(
462 context, spirv::Decoration::RelaxedPrecision);
463 }
464 }
465
466 if (!foundDecorationAttr)
467 return emitError(unknownLoc, "unimplemented decoration support for "
468 "function argument with result <id> ")
469 << argID;
470
471 NamedAttribute attr(StringAttr::get(context, spirv::DecorationAttr::name),
472 foundDecorationAttr);
473 argAttrs[argIndex] = DictionaryAttr::get(context, attr);
474 return success();
475}
476
477LogicalResult
479 if (curFunction) {
480 return emitError(unknownLoc, "found function inside function");
481 }
482
483 // Get the result type
484 if (operands.size() != 4) {
485 return emitError(unknownLoc, "OpFunction must have 4 parameters");
486 }
487 Type resultType = getType(operands[0]);
488 if (!resultType) {
489 return emitError(unknownLoc, "undefined result type from <id> ")
490 << operands[0];
491 }
492
493 uint32_t fnID = operands[1];
494 if (funcMap.count(fnID)) {
495 return emitError(unknownLoc, "duplicate function definition/declaration");
496 }
497
498 auto fnControl = spirv::symbolizeFunctionControl(operands[2]);
499 if (!fnControl) {
500 return emitError(unknownLoc, "unknown Function Control: ") << operands[2];
501 }
502
503 Type fnType = getType(operands[3]);
504 if (!fnType || !isa<FunctionType>(fnType)) {
505 return emitError(unknownLoc, "unknown function type from <id> ")
506 << operands[3];
507 }
508 auto functionType = cast<FunctionType>(fnType);
509
510 if ((isVoidType(resultType) && functionType.getNumResults() != 0) ||
511 (functionType.getNumResults() == 1 &&
512 functionType.getResult(0) != resultType)) {
513 return emitError(unknownLoc, "mismatch in function type ")
514 << functionType << " and return type " << resultType << " specified";
515 }
516
517 std::string fnName = getFunctionSymbol(fnID);
518 auto funcOp = spirv::FuncOp::create(opBuilder, unknownLoc, fnName,
519 functionType, fnControl.value());
520 // Processing other function attributes.
521 if (decorations.count(fnID)) {
522 for (auto attr : decorations[fnID].getAttrs()) {
523 funcOp->setAttr(attr.getName(), attr.getValue());
524 }
525 }
526 curFunction = funcMap[fnID] = funcOp;
527 auto *entryBlock = funcOp.addEntryBlock();
528 LLVM_DEBUG({
529 logger.startLine()
530 << "//===-------------------------------------------===//\n";
531 logger.startLine() << "[fn] name: " << fnName << "\n";
532 logger.startLine() << "[fn] type: " << fnType << "\n";
533 logger.startLine() << "[fn] ID: " << fnID << "\n";
534 logger.startLine() << "[fn] entry block: " << entryBlock << "\n";
535 logger.indent();
536 });
537
538 SmallVector<Attribute> argAttrs;
539 argAttrs.resize(functionType.getNumInputs());
540
541 // Parse the op argument instructions
542 if (functionType.getNumInputs()) {
543 for (size_t i = 0, e = functionType.getNumInputs(); i != e; ++i) {
544 auto argType = functionType.getInput(i);
545 spirv::Opcode opcode = spirv::Opcode::OpNop;
546 ArrayRef<uint32_t> operands;
547 if (failed(sliceInstruction(opcode, operands,
548 spirv::Opcode::OpFunctionParameter))) {
549 return failure();
550 }
551 if (opcode != spirv::Opcode::OpFunctionParameter) {
552 return emitError(
553 unknownLoc,
554 "missing OpFunctionParameter instruction for argument ")
555 << i;
556 }
557 if (operands.size() != 2) {
558 return emitError(
559 unknownLoc,
560 "expected result type and result <id> for OpFunctionParameter");
561 }
562 auto argDefinedType = getType(operands[0]);
563 if (!argDefinedType || argDefinedType != argType) {
564 return emitError(unknownLoc,
565 "mismatch in argument type between function type "
566 "definition ")
567 << functionType << " and argument type definition "
568 << argDefinedType << " at argument " << i;
569 }
570 if (getValue(operands[1])) {
571 return emitError(unknownLoc, "duplicate definition of result <id> ")
572 << operands[1];
573 }
574 if (failed(setFunctionArgAttrs(operands[1], argAttrs, i))) {
575 return failure();
576 }
577
578 auto argValue = funcOp.getArgument(i);
579 valueMap[operands[1]] = argValue;
580 }
581 }
582
583 if (llvm::any_of(argAttrs, [](Attribute attr) {
584 auto argAttr = cast<DictionaryAttr>(attr);
585 return !argAttr.empty();
586 }))
587 funcOp.setArgAttrsAttr(ArrayAttr::get(context, argAttrs));
588
589 // entryBlock is needed to access the arguments, Once that is done, we can
590 // erase the block for functions with 'Import' LinkageAttributes, since these
591 // are essentially function declarations, so they have no body.
592 auto linkageAttr = funcOp.getLinkageAttributes();
593 auto hasImportLinkage =
594 linkageAttr && (linkageAttr.value().getLinkageType().getValue() ==
595 spirv::LinkageType::Import);
596 if (hasImportLinkage)
597 funcOp.eraseBody();
598
599 // RAII guard to reset the insertion point to the module's region after
600 // deserializing the body of this function.
601 OpBuilder::InsertionGuard moduleInsertionGuard(opBuilder);
602
603 spirv::Opcode opcode = spirv::Opcode::OpNop;
604 ArrayRef<uint32_t> instOperands;
605
606 // Special handling for the entry block. We need to make sure it starts with
607 // an OpLabel instruction. The entry block takes the same parameters as the
608 // function. All other blocks do not take any parameter. We have already
609 // created the entry block, here we need to register it to the correct label
610 // <id>.
611 if (failed(sliceInstruction(opcode, instOperands,
612 spirv::Opcode::OpFunctionEnd))) {
613 return failure();
614 }
615 if (opcode == spirv::Opcode::OpFunctionEnd) {
616 return processFunctionEnd(instOperands);
617 }
618 if (opcode != spirv::Opcode::OpLabel) {
619 return emitError(unknownLoc, "a basic block must start with OpLabel");
620 }
621 if (instOperands.size() != 1) {
622 return emitError(unknownLoc, "OpLabel should only have result <id>");
623 }
624 blockMap[instOperands[0]] = entryBlock;
625 if (failed(processLabel(instOperands))) {
626 return failure();
627 }
628
629 // Then process all the other instructions in the function until we hit
630 // OpFunctionEnd.
631 while (succeeded(sliceInstruction(opcode, instOperands,
632 spirv::Opcode::OpFunctionEnd)) &&
633 opcode != spirv::Opcode::OpFunctionEnd) {
634 if (failed(processInstruction(opcode, instOperands))) {
635 return failure();
636 }
637 }
638 if (opcode != spirv::Opcode::OpFunctionEnd) {
639 return failure();
640 }
641
642 return processFunctionEnd(instOperands);
643}
644
645LogicalResult
647 // Process OpFunctionEnd.
648 if (!operands.empty()) {
649 return emitError(unknownLoc, "unexpected operands for OpFunctionEnd");
650 }
651
652 // Wire up block arguments from OpPhi instructions.
653 // Put all structured control flow in spirv.mlir.selection/spirv.mlir.loop
654 // ops.
655 if (failed(wireUpBlockArgument()) || failed(structurizeControlFlow())) {
656 return failure();
657 }
658
659 curBlock = nullptr;
660 curFunction = std::nullopt;
661
662 LLVM_DEBUG({
663 logger.unindent();
664 logger.startLine()
665 << "//===-------------------------------------------===//\n";
666 });
667 return success();
668}
669
670LogicalResult
672 if (operands.size() < 2) {
673 return emitError(unknownLoc,
674 "missing graph defintion in OpGraphEntryPointARM");
675 }
676
677 unsigned wordIndex = 0;
678 uint32_t graphID = operands[wordIndex++];
679 if (!graphMap.contains(graphID)) {
680 return emitError(unknownLoc,
681 "missing graph definition/declaration with id ")
682 << graphID;
683 }
684
685 spirv::GraphARMOp graphARM = graphMap[graphID];
686 StringRef name = decodeStringLiteral(operands, wordIndex);
687 graphARM.setSymName(name);
688 graphARM.setEntryPoint(true);
689
691 for (int64_t size = operands.size(); wordIndex < size; ++wordIndex) {
692 if (spirv::GlobalVariableOp arg = getGlobalVariable(operands[wordIndex])) {
693 interface.push_back(SymbolRefAttr::get(arg.getOperation()));
694 } else {
695 return emitError(unknownLoc, "undefined result <id> ")
696 << operands[wordIndex] << " while decoding OpGraphEntryPoint";
697 }
698 }
699
700 // RAII guard to reset the insertion point to previous value when done.
701 OpBuilder::InsertionGuard insertionGuard(opBuilder);
702 opBuilder.setInsertionPoint(graphARM);
703 spirv::GraphEntryPointARMOp::create(
704 opBuilder, unknownLoc, SymbolRefAttr::get(opBuilder.getContext(), name),
705 opBuilder.getArrayAttr(interface));
706
707 return success();
708}
709
710LogicalResult
712 if (curGraph) {
713 return emitError(unknownLoc, "found graph inside graph");
714 }
715 // Get the result type.
716 if (operands.size() < 2) {
717 return emitError(unknownLoc, "OpGraphARM must have at least 2 parameters");
718 }
719
720 Type type = getType(operands[0]);
721 if (!type || !isa<GraphType>(type)) {
722 return emitError(unknownLoc, "unknown graph type from <id> ")
723 << operands[0];
724 }
725 auto graphType = cast<GraphType>(type);
726 if (graphType.getNumResults() <= 0) {
727 return emitError(unknownLoc, "expected at least one result");
728 }
729
730 uint32_t graphID = operands[1];
731 if (graphMap.count(graphID)) {
732 return emitError(unknownLoc, "duplicate graph definition/declaration");
733 }
734
735 std::string graphName = getGraphSymbol(graphID);
736 auto graphOp =
737 spirv::GraphARMOp::create(opBuilder, unknownLoc, graphName, graphType);
738 curGraph = graphMap[graphID] = graphOp;
739 Block *entryBlock = graphOp.addEntryBlock();
740 LLVM_DEBUG({
741 logger.startLine()
742 << "//===-------------------------------------------===//\n";
743 logger.startLine() << "[graph] name: " << graphName << "\n";
744 logger.startLine() << "[graph] type: " << graphType << "\n";
745 logger.startLine() << "[graph] ID: " << graphID << "\n";
746 logger.startLine() << "[graph] entry block: " << entryBlock << "\n";
747 logger.indent();
748 });
749
750 // Parse the op argument instructions.
751 for (auto [index, argType] : llvm::enumerate(graphType.getInputs())) {
752 spirv::Opcode opcode;
753 ArrayRef<uint32_t> operands;
754 if (failed(sliceInstruction(opcode, operands,
755 spirv::Opcode::OpGraphInputARM))) {
756 return failure();
757 }
758 if (operands.size() != 3) {
759 return emitError(unknownLoc, "expected result type, result <id> and "
760 "input index for OpGraphInputARM");
761 }
762
763 Type argDefinedType = getType(operands[0]);
764 if (!argDefinedType) {
765 return emitError(unknownLoc, "unknown operand type <id> ") << operands[0];
766 }
767
768 if (argDefinedType != argType) {
769 return emitError(unknownLoc,
770 "mismatch in argument type between graph type "
771 "definition ")
772 << graphType << " and argument type definition " << argDefinedType
773 << " at argument " << index;
774 }
775 if (getValue(operands[1])) {
776 return emitError(unknownLoc, "duplicate definition of result <id> ")
777 << operands[1];
778 }
779
780 IntegerAttr inputIndexAttr = getConstantInt(operands[2]);
781 if (!inputIndexAttr) {
782 return emitError(unknownLoc,
783 "unable to read inputIndex value from constant op ")
784 << operands[2];
785 }
786 BlockArgument argValue = graphOp.getArgument(inputIndexAttr.getInt());
787 valueMap[operands[1]] = argValue;
788 }
789
790 graphOutputs.resize(graphType.getNumResults());
791
792 // RAII guard to reset the insertion point to the module's region after
793 // deserializing the body of this function.
794 OpBuilder::InsertionGuard moduleInsertionGuard(opBuilder);
795
796 blockMap[graphID] = entryBlock;
797 if (failed(createGraphBlock(graphID))) {
798 return failure();
799 }
800
801 // Process all the instructions in the graph until and including
802 // OpGraphEndARM.
803 spirv::Opcode opcode;
804 ArrayRef<uint32_t> instOperands;
805 do {
806 if (failed(sliceInstruction(opcode, instOperands, std::nullopt))) {
807 return failure();
808 }
809
810 if (failed(processInstruction(opcode, instOperands))) {
811 return failure();
812 }
813 } while (opcode != spirv::Opcode::OpGraphEndARM);
814
815 return success();
816}
817
818LogicalResult
820 if (operands.size() != 2) {
821 return emitError(
822 unknownLoc,
823 "expected value id and output index for OpGraphSetOutputARM");
824 }
825
826 uint32_t id = operands[0];
827 Value value = getValue(id);
828 if (!value) {
829 return emitError(unknownLoc, "could not find result <id> ") << id;
830 }
831
832 IntegerAttr outputIndexAttr = getConstantInt(operands[1]);
833 if (!outputIndexAttr) {
834 return emitError(unknownLoc,
835 "unable to read outputIndex value from constant op ")
836 << operands[1];
837 }
838 graphOutputs[outputIndexAttr.getInt()] = value;
839 return success();
840}
841
842LogicalResult
844 // Create GraphOutputsARM instruction.
845 spirv::GraphOutputsARMOp::create(opBuilder, unknownLoc, graphOutputs);
846
847 // Process OpGraphEndARM.
848 if (!operands.empty()) {
849 return emitError(unknownLoc, "unexpected operands for OpGraphEndARM");
850 }
851
852 curBlock = nullptr;
853 curGraph = std::nullopt;
854 graphOutputs.clear();
855
856 LLVM_DEBUG({
857 logger.unindent();
858 logger.startLine()
859 << "//===-------------------------------------------===//\n";
860 });
861 return success();
862}
863
864std::optional<std::pair<Attribute, Type>>
866 auto constIt = constantMap.find(id);
867 if (constIt == constantMap.end())
868 return std::nullopt;
869 return constIt->getSecond();
870}
871
872std::optional<std::pair<Attribute, Type>>
874 if (auto it = constantCompositeReplicateMap.find(id);
875 it != constantCompositeReplicateMap.end())
876 return it->second;
877 return std::nullopt;
878}
879
880std::optional<spirv::SpecConstOperationMaterializationInfo>
882 auto constIt = specConstOperationMap.find(id);
883 if (constIt == specConstOperationMap.end())
884 return std::nullopt;
885 return constIt->getSecond();
886}
887
889 auto funcName = nameMap.lookup(id).str();
890 if (funcName.empty()) {
891 funcName = "spirv_fn_" + std::to_string(id);
892 }
893 return funcName;
894}
895
896std::string spirv::Deserializer::getGraphSymbol(uint32_t id) {
897 std::string graphName = nameMap.lookup(id).str();
898 if (graphName.empty()) {
899 graphName = "spirv_graph_" + std::to_string(id);
900 }
901 return graphName;
902}
903
905 auto constName = nameMap.lookup(id).str();
906 if (constName.empty()) {
907 constName = "spirv_spec_const_" + std::to_string(id);
908 }
909 return constName;
910}
911
912spirv::SpecConstantOp
914 TypedAttr defaultValue) {
915 auto symName = opBuilder.getStringAttr(getSpecConstantSymbol(resultID));
916 auto op = spirv::SpecConstantOp::create(opBuilder, unknownLoc, symName,
917 defaultValue);
918 if (decorations.count(resultID)) {
919 for (auto attr : decorations[resultID].getAttrs())
920 op->setAttr(attr.getName(), attr.getValue());
921 }
922 specConstMap[resultID] = op;
923 return op;
924}
925
926std::optional<spirv::GraphConstantARMOpMaterializationInfo>
928 auto graphConstIt = graphConstantMap.find(id);
929 if (graphConstIt == graphConstantMap.end())
930 return std::nullopt;
931 return graphConstIt->getSecond();
932}
933
934LogicalResult
936 unsigned wordIndex = 0;
937 if (operands.size() < 3) {
938 return emitError(
939 unknownLoc,
940 "OpVariable needs at least 3 operands, type, <id> and storage class");
941 }
942
943 // Result Type.
944 auto type = getType(operands[wordIndex]);
945 if (!type) {
946 return emitError(unknownLoc, "unknown result type <id> : ")
947 << operands[wordIndex];
948 }
949 auto ptrType = dyn_cast<spirv::PointerType>(type);
950 if (!ptrType) {
951 return emitError(unknownLoc,
952 "expected a result type <id> to be a spirv.ptr, found : ")
953 << type;
954 }
955 wordIndex++;
956
957 // Result <id>.
958 auto variableID = operands[wordIndex];
959 auto variableName = nameMap.lookup(variableID).str();
960 if (variableName.empty()) {
961 variableName = "spirv_var_" + std::to_string(variableID);
962 }
963 wordIndex++;
964
965 // Storage class.
966 auto storageClass = static_cast<spirv::StorageClass>(operands[wordIndex]);
967 if (ptrType.getStorageClass() != storageClass) {
968 return emitError(unknownLoc, "mismatch in storage class of pointer type ")
969 << type << " and that specified in OpVariable instruction : "
970 << stringifyStorageClass(storageClass);
971 }
972 wordIndex++;
973
974 // Initializer.
975 FlatSymbolRefAttr initializer = nullptr;
976
977 if (wordIndex < operands.size()) {
978 Operation *op = nullptr;
979
980 if (auto initOp = getGlobalVariable(operands[wordIndex]))
981 op = initOp;
982 else if (auto initOp = getSpecConstant(operands[wordIndex]))
983 op = initOp;
984 else if (auto initOp = getSpecConstantComposite(operands[wordIndex]))
985 op = initOp;
986 else
987 return emitError(unknownLoc, "unknown <id> ")
988 << operands[wordIndex] << "used as initializer";
989
990 initializer = SymbolRefAttr::get(op);
991 wordIndex++;
992 }
993 if (wordIndex != operands.size()) {
994 return emitError(unknownLoc,
995 "found more operands than expected when deserializing "
996 "OpVariable instruction, only ")
997 << wordIndex << " of " << operands.size() << " processed";
998 }
999 auto loc = createFileLineColLoc(opBuilder);
1000 auto varOp = spirv::GlobalVariableOp::create(
1001 opBuilder, loc, TypeAttr::get(type),
1002 opBuilder.getStringAttr(variableName), initializer);
1003
1004 // Decorations.
1005 if (decorations.count(variableID)) {
1006 for (auto attr : decorations[variableID].getAttrs())
1007 varOp->setAttr(attr.getName(), attr.getValue());
1008 }
1009 globalVariableMap[variableID] = varOp;
1010 return success();
1011}
1012
1013IntegerAttr spirv::Deserializer::getConstantInt(uint32_t id) {
1014 auto constInfo = getConstant(id);
1015 if (!constInfo) {
1016 return nullptr;
1017 }
1018 return dyn_cast<IntegerAttr>(constInfo->first);
1019}
1020
1021LogicalResult spirv::Deserializer::processName(ArrayRef<uint32_t> operands) {
1022 if (operands.size() < 2) {
1023 return emitError(unknownLoc, "OpName needs at least 2 operands");
1024 }
1025 if (!nameMap.lookup(operands[0]).empty()) {
1026 return emitError(unknownLoc, "duplicate name found for result <id> ")
1027 << operands[0];
1028 }
1029 unsigned wordIndex = 1;
1030 StringRef name = decodeStringLiteral(operands, wordIndex);
1031 if (wordIndex != operands.size()) {
1032 return emitError(unknownLoc,
1033 "unexpected trailing words in OpName instruction");
1034 }
1035 nameMap[operands[0]] = name;
1036 return success();
1037}
1038
1039//===----------------------------------------------------------------------===//
1040// Type
1041//===----------------------------------------------------------------------===//
1042
1043LogicalResult spirv::Deserializer::processType(spirv::Opcode opcode,
1044 ArrayRef<uint32_t> operands) {
1045 if (operands.empty()) {
1046 return emitError(unknownLoc, "type instruction with opcode ")
1047 << spirv::stringifyOpcode(opcode) << " needs at least one <id>";
1048 }
1049
1050 /// TODO: Types might be forward declared in some instructions and need to be
1051 /// handled appropriately.
1052 if (typeMap.count(operands[0])) {
1053 return emitError(unknownLoc, "duplicate definition for result <id> ")
1054 << operands[0];
1055 }
1056
1057 switch (opcode) {
1058 case spirv::Opcode::OpTypeVoid:
1059 if (operands.size() != 1)
1060 return emitError(unknownLoc, "OpTypeVoid must have no parameters");
1061 typeMap[operands[0]] = opBuilder.getNoneType();
1062 break;
1063 case spirv::Opcode::OpTypeBool:
1064 if (operands.size() != 1)
1065 return emitError(unknownLoc, "OpTypeBool must have no parameters");
1066 typeMap[operands[0]] = opBuilder.getI1Type();
1067 break;
1068 case spirv::Opcode::OpTypeInt: {
1069 if (operands.size() != 3)
1070 return emitError(
1071 unknownLoc, "OpTypeInt must have bitwidth and signedness parameters");
1072
1073 // SPIR-V OpTypeInt "Signedness specifies whether there are signed semantics
1074 // to preserve or validate.
1075 // 0 indicates unsigned, or no signedness semantics
1076 // 1 indicates signed semantics."
1077 //
1078 // So we cannot differentiate signless and unsigned integers; always use
1079 // signless semantics for such cases.
1080 auto sign = operands[2] == 1 ? IntegerType::SignednessSemantics::Signed
1081 : IntegerType::SignednessSemantics::Signless;
1082 typeMap[operands[0]] = IntegerType::get(context, operands[1], sign);
1083 } break;
1084 case spirv::Opcode::OpTypeFloat: {
1085 if (operands.size() != 2 && operands.size() != 3)
1086 return emitError(unknownLoc,
1087 "OpTypeFloat expects either 2 operands (type, bitwidth) "
1088 "or 3 operands (type, bitwidth, encoding), but got ")
1089 << operands.size();
1090 uint32_t bitWidth = operands[1];
1091
1092 Type floatTy;
1093 if (operands.size() == 2) {
1094 switch (bitWidth) {
1095 case 16:
1096 floatTy = opBuilder.getF16Type();
1097 break;
1098 case 32:
1099 floatTy = opBuilder.getF32Type();
1100 break;
1101 case 64:
1102 floatTy = opBuilder.getF64Type();
1103 break;
1104 default:
1105 return emitError(unknownLoc, "unsupported OpTypeFloat bitwidth: ")
1106 << bitWidth;
1107 }
1108 }
1109
1110 if (operands.size() == 3) {
1111 if (spirv::FPEncoding(operands[2]) == spirv::FPEncoding::BFloat16KHR &&
1112 bitWidth == 16)
1113 floatTy = opBuilder.getBF16Type();
1114 else if (spirv::FPEncoding(operands[2]) ==
1115 spirv::FPEncoding::Float8E4M3EXT &&
1116 bitWidth == 8)
1117 floatTy = opBuilder.getF8E4M3FNType();
1118 else if (spirv::FPEncoding(operands[2]) ==
1119 spirv::FPEncoding::Float8E5M2EXT &&
1120 bitWidth == 8)
1121 floatTy = opBuilder.getF8E5M2Type();
1122 else
1123 return emitError(unknownLoc, "unsupported OpTypeFloat FP encoding: ")
1124 << operands[2] << " and bitWidth " << bitWidth;
1125 }
1126
1127 typeMap[operands[0]] = floatTy;
1128 } break;
1129 case spirv::Opcode::OpTypeVector: {
1130 if (operands.size() != 3) {
1131 return emitError(
1132 unknownLoc,
1133 "OpTypeVector must have element type and count parameters");
1134 }
1135 Type elementTy = getType(operands[1]);
1136 if (!elementTy) {
1137 return emitError(unknownLoc, "OpTypeVector references undefined <id> ")
1138 << operands[1];
1139 }
1140 typeMap[operands[0]] = VectorType::get({operands[2]}, elementTy);
1141 } break;
1142 case spirv::Opcode::OpTypePointer: {
1143 return processOpTypePointer(operands);
1144 } break;
1145 case spirv::Opcode::OpTypeArray:
1146 return processArrayType(operands);
1147 case spirv::Opcode::OpTypeCooperativeMatrixKHR:
1148 return processCooperativeMatrixTypeKHR(operands);
1149 case spirv::Opcode::OpTypeFunction:
1150 return processFunctionType(operands);
1151 case spirv::Opcode::OpTypeImage:
1152 return processImageType(operands);
1153 case spirv::Opcode::OpTypeSampledImage:
1154 return processSampledImageType(operands);
1155 case spirv::Opcode::OpTypeRuntimeArray:
1156 return processRuntimeArrayType(operands);
1157 case spirv::Opcode::OpTypeStruct:
1158 return processStructType(operands);
1159 case spirv::Opcode::OpTypeMatrix:
1160 return processMatrixType(operands);
1161 case spirv::Opcode::OpTypeTensorARM:
1162 return processTensorARMType(operands);
1163 case spirv::Opcode::OpTypeGraphARM:
1164 return processGraphTypeARM(operands);
1165 default:
1166 return emitError(unknownLoc, "unhandled type instruction");
1167 }
1168 return success();
1169}
1170
1171LogicalResult
1173 if (operands.size() != 3)
1174 return emitError(unknownLoc, "OpTypePointer must have two parameters");
1175
1176 auto pointeeType = getType(operands[2]);
1177 if (!pointeeType)
1178 return emitError(unknownLoc, "unknown OpTypePointer pointee type <id> ")
1179 << operands[2];
1180
1181 uint32_t typePointerID = operands[0];
1182 auto storageClass = static_cast<spirv::StorageClass>(operands[1]);
1183 typeMap[typePointerID] = spirv::PointerType::get(pointeeType, storageClass);
1184
1185 for (auto *deferredStructIt = std::begin(deferredStructTypesInfos);
1186 deferredStructIt != std::end(deferredStructTypesInfos);) {
1187 for (auto *unresolvedMemberIt =
1188 std::begin(deferredStructIt->unresolvedMemberTypes);
1189 unresolvedMemberIt !=
1190 std::end(deferredStructIt->unresolvedMemberTypes);) {
1191 if (unresolvedMemberIt->first == typePointerID) {
1192 // The newly constructed pointer type can resolve one of the
1193 // deferred struct type members; update the memberTypes list and
1194 // clean the unresolvedMemberTypes list accordingly.
1195 deferredStructIt->memberTypes[unresolvedMemberIt->second] =
1196 typeMap[typePointerID];
1197 unresolvedMemberIt =
1198 deferredStructIt->unresolvedMemberTypes.erase(unresolvedMemberIt);
1199 } else {
1200 ++unresolvedMemberIt;
1201 }
1202 }
1203
1204 if (deferredStructIt->unresolvedMemberTypes.empty()) {
1205 // All deferred struct type members are now resolved, set the struct body.
1206 auto structType = deferredStructIt->deferredStructType;
1207
1208 assert(structType && "expected a spirv::StructType");
1209 assert(structType.isIdentified() && "expected an indentified struct");
1210
1211 if (failed(structType.trySetBody(
1212 deferredStructIt->memberTypes, deferredStructIt->offsetInfo,
1213 deferredStructIt->memberDecorationsInfo,
1214 deferredStructIt->structDecorationsInfo)))
1215 return failure();
1216
1217 deferredStructIt = deferredStructTypesInfos.erase(deferredStructIt);
1218 } else {
1219 ++deferredStructIt;
1220 }
1221 }
1222
1223 return success();
1224}
1225
1226LogicalResult
1228 if (operands.size() != 3) {
1229 return emitError(unknownLoc,
1230 "OpTypeArray must have element type and count parameters");
1231 }
1232
1233 Type elementTy = getType(operands[1]);
1234 if (!elementTy) {
1235 return emitError(unknownLoc, "OpTypeArray references undefined <id> ")
1236 << operands[1];
1237 }
1238
1239 unsigned count = 0;
1240 // TODO: The count can also come frome a specialization constant.
1241 auto countInfo = getConstant(operands[2]);
1242 if (!countInfo) {
1243 return emitError(unknownLoc, "OpTypeArray count <id> ")
1244 << operands[2] << "can only come from normal constant right now";
1245 }
1246
1247 if (auto intVal = dyn_cast<IntegerAttr>(countInfo->first)) {
1248 count = intVal.getValue().getZExtValue();
1249 } else {
1250 return emitError(unknownLoc, "OpTypeArray count must come from a "
1251 "scalar integer constant instruction");
1252 }
1253
1254 typeMap[operands[0]] = spirv::ArrayType::get(
1255 elementTy, count, typeDecorations.lookup(operands[0]));
1256 return success();
1257}
1258
1259LogicalResult
1261 assert(!operands.empty() && "No operands for processing function type");
1262 if (operands.size() == 1) {
1263 return emitError(unknownLoc, "missing return type for OpTypeFunction");
1264 }
1265 auto returnType = getType(operands[1]);
1266 if (!returnType) {
1267 return emitError(unknownLoc, "unknown return type in OpTypeFunction");
1268 }
1269 SmallVector<Type, 1> argTypes;
1270 for (size_t i = 2, e = operands.size(); i < e; ++i) {
1271 auto ty = getType(operands[i]);
1272 if (!ty) {
1273 return emitError(unknownLoc, "unknown argument type in OpTypeFunction");
1274 }
1275 argTypes.push_back(ty);
1276 }
1277 ArrayRef<Type> returnTypes;
1278 if (!isVoidType(returnType)) {
1279 returnTypes = llvm::ArrayRef(returnType);
1280 }
1281 typeMap[operands[0]] = FunctionType::get(context, argTypes, returnTypes);
1282 return success();
1283}
1284
1286 ArrayRef<uint32_t> operands) {
1287 if (operands.size() != 6) {
1288 return emitError(unknownLoc,
1289 "OpTypeCooperativeMatrixKHR must have element type, "
1290 "scope, row and column parameters, and use");
1291 }
1292
1293 Type elementTy = getType(operands[1]);
1294 if (!elementTy) {
1295 return emitError(unknownLoc,
1296 "OpTypeCooperativeMatrixKHR references undefined <id> ")
1297 << operands[1];
1298 }
1299
1300 std::optional<spirv::Scope> scope =
1301 spirv::symbolizeScope(getConstantInt(operands[2]).getInt());
1302 if (!scope) {
1303 return emitError(
1304 unknownLoc,
1305 "OpTypeCooperativeMatrixKHR references undefined scope <id> ")
1306 << operands[2];
1307 }
1308
1309 IntegerAttr rowsAttr = getConstantInt(operands[3]);
1310 IntegerAttr columnsAttr = getConstantInt(operands[4]);
1311 IntegerAttr useAttr = getConstantInt(operands[5]);
1312
1313 if (!rowsAttr)
1314 return emitError(unknownLoc, "OpTypeCooperativeMatrixKHR `Rows` references "
1315 "undefined constant <id> ")
1316 << operands[3];
1317
1318 if (!columnsAttr)
1319 return emitError(unknownLoc, "OpTypeCooperativeMatrixKHR `Columns` "
1320 "references undefined constant <id> ")
1321 << operands[4];
1322
1323 if (!useAttr)
1324 return emitError(unknownLoc, "OpTypeCooperativeMatrixKHR `Use` references "
1325 "undefined constant <id> ")
1326 << operands[5];
1327
1328 unsigned rows = rowsAttr.getInt();
1329 unsigned columns = columnsAttr.getInt();
1330
1331 std::optional<spirv::CooperativeMatrixUseKHR> use =
1332 spirv::symbolizeCooperativeMatrixUseKHR(useAttr.getInt());
1333 if (!use) {
1334 return emitError(
1335 unknownLoc,
1336 "OpTypeCooperativeMatrixKHR references undefined use <id> ")
1337 << operands[5];
1338 }
1339
1340 typeMap[operands[0]] =
1341 spirv::CooperativeMatrixType::get(elementTy, rows, columns, *scope, *use);
1342 return success();
1343}
1344
1345LogicalResult
1347 if (operands.size() != 2) {
1348 return emitError(unknownLoc, "OpTypeRuntimeArray must have two operands");
1349 }
1350 Type memberType = getType(operands[1]);
1351 if (!memberType) {
1352 return emitError(unknownLoc,
1353 "OpTypeRuntimeArray references undefined <id> ")
1354 << operands[1];
1355 }
1356 typeMap[operands[0]] = spirv::RuntimeArrayType::get(
1357 memberType, typeDecorations.lookup(operands[0]));
1358 return success();
1359}
1360
1361LogicalResult
1363 // TODO: Find a way to handle identified structs when debug info is stripped.
1364
1365 if (operands.empty()) {
1366 return emitError(unknownLoc, "OpTypeStruct must have at least result <id>");
1367 }
1368
1369 if (operands.size() == 1) {
1370 // Handle empty struct.
1371 typeMap[operands[0]] =
1372 spirv::StructType::getEmpty(context, nameMap.lookup(operands[0]).str());
1373 return success();
1374 }
1375
1376 // First element is operand ID, second element is member index in the struct.
1377 SmallVector<std::pair<uint32_t, unsigned>, 0> unresolvedMemberTypes;
1378 SmallVector<Type, 4> memberTypes;
1379
1380 for (auto op : llvm::drop_begin(operands, 1)) {
1381 Type memberType = getType(op);
1382 bool typeForwardPtr = (typeForwardPointerIDs.count(op) != 0);
1383
1384 if (!memberType && !typeForwardPtr)
1385 return emitError(unknownLoc, "OpTypeStruct references undefined <id> ")
1386 << op;
1387
1388 if (!memberType)
1389 unresolvedMemberTypes.emplace_back(op, memberTypes.size());
1390
1391 memberTypes.push_back(memberType);
1392 }
1393
1396 if (memberDecorationMap.count(operands[0])) {
1397 auto &allMemberDecorations = memberDecorationMap[operands[0]];
1398 for (auto memberIndex : llvm::seq<uint32_t>(0, memberTypes.size())) {
1399 if (allMemberDecorations.count(memberIndex)) {
1400 for (auto &memberDecoration : allMemberDecorations[memberIndex]) {
1401 // Check for offset.
1402 if (memberDecoration.first == spirv::Decoration::Offset) {
1403 // If offset info is empty, resize to the number of members;
1404 if (offsetInfo.empty()) {
1405 offsetInfo.resize(memberTypes.size());
1406 }
1407 offsetInfo[memberIndex] = memberDecoration.second[0];
1408 } else {
1409 auto intType = mlir::IntegerType::get(context, 32);
1410 if (!memberDecoration.second.empty()) {
1411 memberDecorationsInfo.emplace_back(
1412 memberIndex, memberDecoration.first,
1413 IntegerAttr::get(intType, memberDecoration.second[0]));
1414 } else {
1415 memberDecorationsInfo.emplace_back(
1416 memberIndex, memberDecoration.first, UnitAttr::get(context));
1417 }
1418 }
1419 }
1420 }
1421 }
1422 }
1423
1425 if (decorations.count(operands[0])) {
1426 NamedAttrList &allDecorations = decorations[operands[0]];
1427 for (NamedAttribute &decorationAttr : allDecorations) {
1428 std::optional<spirv::Decoration> decoration = spirv::symbolizeDecoration(
1429 llvm::convertToCamelFromSnakeCase(decorationAttr.getName(), true));
1430 assert(decoration.has_value());
1431 structDecorationsInfo.emplace_back(decoration.value(),
1432 decorationAttr.getValue());
1433 }
1434 }
1435
1436 uint32_t structID = operands[0];
1437 std::string structIdentifier = nameMap.lookup(structID).str();
1438
1439 if (structIdentifier.empty()) {
1440 assert(unresolvedMemberTypes.empty() &&
1441 "didn't expect unresolved member types");
1442 typeMap[structID] = spirv::StructType::get(
1443 memberTypes, offsetInfo, memberDecorationsInfo, structDecorationsInfo);
1444 } else {
1445 auto structTy = spirv::StructType::getIdentified(context, structIdentifier);
1446 typeMap[structID] = structTy;
1447
1448 if (!unresolvedMemberTypes.empty())
1449 deferredStructTypesInfos.push_back(
1450 {structTy, unresolvedMemberTypes, memberTypes, offsetInfo,
1451 memberDecorationsInfo, structDecorationsInfo});
1452 else if (failed(structTy.trySetBody(memberTypes, offsetInfo,
1453 memberDecorationsInfo,
1454 structDecorationsInfo)))
1455 return failure();
1456 }
1457
1458 // TODO: Update StructType to have member name as attribute as
1459 // well.
1460 return success();
1461}
1462
1463LogicalResult
1465 if (operands.size() != 3) {
1466 // Three operands are needed: result_id, column_type, and column_count
1467 return emitError(unknownLoc, "OpTypeMatrix must have 3 operands"
1468 " (result_id, column_type, and column_count)");
1469 }
1470 // Matrix columns must be of vector type
1471 Type elementTy = getType(operands[1]);
1472 if (!elementTy) {
1473 return emitError(unknownLoc,
1474 "OpTypeMatrix references undefined column type.")
1475 << operands[1];
1476 }
1477
1478 uint32_t colsCount = operands[2];
1479 typeMap[operands[0]] = spirv::MatrixType::get(elementTy, colsCount);
1480 return success();
1481}
1482
1483LogicalResult
1485 unsigned size = operands.size();
1486 if (size < 2 || size > 4)
1487 return emitError(unknownLoc, "OpTypeTensorARM must have 2-4 operands "
1488 "(result_id, element_type, (rank), (shape)) ")
1489 << size;
1490
1491 Type elementTy = getType(operands[1]);
1492 if (!elementTy)
1493 return emitError(unknownLoc,
1494 "OpTypeTensorARM references undefined element type ")
1495 << operands[1];
1496
1497 if (size == 2) {
1498 typeMap[operands[0]] = TensorArmType::get({}, elementTy);
1499 return success();
1500 }
1501
1502 IntegerAttr rankAttr = getConstantInt(operands[2]);
1503 if (!rankAttr)
1504 return emitError(unknownLoc, "OpTypeTensorARM rank must come from a "
1505 "scalar integer constant instruction");
1506 unsigned rank = rankAttr.getValue().getZExtValue();
1507 if (size == 3) {
1508 SmallVector<int64_t, 4> shape(rank, ShapedType::kDynamic);
1509 typeMap[operands[0]] = TensorArmType::get(shape, elementTy);
1510 return success();
1511 }
1512
1513 std::optional<std::pair<Attribute, Type>> shapeInfo =
1514 getConstant(operands[3]);
1515 if (!shapeInfo)
1516 return emitError(unknownLoc, "OpTypeTensorARM shape must come from a "
1517 "constant instruction of type OpTypeArray");
1518
1519 ArrayAttr shapeArrayAttr = dyn_cast<ArrayAttr>(shapeInfo->first);
1521 for (auto dimAttr : shapeArrayAttr.getValue()) {
1522 auto dimIntAttr = dyn_cast<IntegerAttr>(dimAttr);
1523 if (!dimIntAttr)
1524 return emitError(unknownLoc, "OpTypeTensorARM shape has an invalid "
1525 "dimension size");
1526 shape.push_back(dimIntAttr.getValue().getSExtValue());
1527 }
1528 typeMap[operands[0]] = TensorArmType::get(shape, elementTy);
1529 return success();
1530}
1531
1532LogicalResult
1534 unsigned size = operands.size();
1535 if (size < 2) {
1536 return emitError(unknownLoc, "OpTypeGraphARM must have at least 2 operands "
1537 "(result_id, num_inputs, (inout0_type, "
1538 "inout1_type, ...))")
1539 << size;
1540 }
1541 uint32_t numInputs = operands[1];
1542 SmallVector<Type, 1> argTypes;
1543 SmallVector<Type, 1> returnTypes;
1544 for (unsigned i = 2; i < size; ++i) {
1545 Type inOutTy = getType(operands[i]);
1546 if (!inOutTy) {
1547 return emitError(unknownLoc,
1548 "OpTypeGraphARM references undefined element type.")
1549 << operands[i];
1550 }
1551 if (i - 2 >= numInputs) {
1552 returnTypes.push_back(inOutTy);
1553 } else {
1554 argTypes.push_back(inOutTy);
1555 }
1556 }
1557 typeMap[operands[0]] = GraphType::get(context, argTypes, returnTypes);
1558 return success();
1559}
1560
1561LogicalResult
1563 if (operands.size() != 2)
1564 return emitError(unknownLoc,
1565 "OpTypeForwardPointer instruction must have two operands");
1566
1567 typeForwardPointerIDs.insert(operands[0]);
1568 // TODO: Use the 2nd operand (Storage Class) to validate the OpTypePointer
1569 // instruction that defines the actual type.
1570
1571 return success();
1572}
1573
1574LogicalResult
1576 // TODO: Add support for Access Qualifier.
1577 if (operands.size() != 8)
1578 return emitError(
1579 unknownLoc,
1580 "OpTypeImage with non-eight operands are not supported yet");
1581
1582 Type elementTy = getType(operands[1]);
1583 if (!elementTy)
1584 return emitError(unknownLoc, "OpTypeImage references undefined <id>: ")
1585 << operands[1];
1586
1587 auto dim = spirv::symbolizeDim(operands[2]);
1588 if (!dim)
1589 return emitError(unknownLoc, "unknown Dim for OpTypeImage: ")
1590 << operands[2];
1591
1592 auto depthInfo = spirv::symbolizeImageDepthInfo(operands[3]);
1593 if (!depthInfo)
1594 return emitError(unknownLoc, "unknown Depth for OpTypeImage: ")
1595 << operands[3];
1596
1597 auto arrayedInfo = spirv::symbolizeImageArrayedInfo(operands[4]);
1598 if (!arrayedInfo)
1599 return emitError(unknownLoc, "unknown Arrayed for OpTypeImage: ")
1600 << operands[4];
1601
1602 auto samplingInfo = spirv::symbolizeImageSamplingInfo(operands[5]);
1603 if (!samplingInfo)
1604 return emitError(unknownLoc, "unknown MS for OpTypeImage: ") << operands[5];
1605
1606 auto samplerUseInfo = spirv::symbolizeImageSamplerUseInfo(operands[6]);
1607 if (!samplerUseInfo)
1608 return emitError(unknownLoc, "unknown Sampled for OpTypeImage: ")
1609 << operands[6];
1610
1611 auto format = spirv::symbolizeImageFormat(operands[7]);
1612 if (!format)
1613 return emitError(unknownLoc, "unknown Format for OpTypeImage: ")
1614 << operands[7];
1615
1616 typeMap[operands[0]] = spirv::ImageType::get(
1617 elementTy, dim.value(), depthInfo.value(), arrayedInfo.value(),
1618 samplingInfo.value(), samplerUseInfo.value(), format.value());
1619 return success();
1620}
1621
1622LogicalResult
1624 if (operands.size() != 2)
1625 return emitError(unknownLoc, "OpTypeSampledImage must have two operands");
1626
1627 Type elementTy = getType(operands[1]);
1628 if (!elementTy)
1629 return emitError(unknownLoc,
1630 "OpTypeSampledImage references undefined <id>: ")
1631 << operands[1];
1632
1633 typeMap[operands[0]] = spirv::SampledImageType::get(elementTy);
1634 return success();
1635}
1636
1637//===----------------------------------------------------------------------===//
1638// Constant
1639//===----------------------------------------------------------------------===//
1640
1642 bool isSpec) {
1643 StringRef opname = isSpec ? "OpSpecConstant" : "OpConstant";
1644
1645 if (operands.size() < 2) {
1646 return emitError(unknownLoc)
1647 << opname << " must have type <id> and result <id>";
1648 }
1649 if (operands.size() < 3) {
1650 return emitError(unknownLoc)
1651 << opname << " must have at least 1 more parameter";
1652 }
1653
1654 Type resultType = getType(operands[0]);
1655 if (!resultType) {
1656 return emitError(unknownLoc, "undefined result type from <id> ")
1657 << operands[0];
1658 }
1659
1660 auto checkOperandSizeForBitwidth = [&](unsigned bitwidth) -> LogicalResult {
1661 if (bitwidth == 64) {
1662 if (operands.size() == 4) {
1663 return success();
1664 }
1665 return emitError(unknownLoc)
1666 << opname << " should have 2 parameters for 64-bit values";
1667 }
1668 if (bitwidth <= 32) {
1669 if (operands.size() == 3) {
1670 return success();
1671 }
1672
1673 return emitError(unknownLoc)
1674 << opname
1675 << " should have 1 parameter for values with no more than 32 bits";
1676 }
1677 return emitError(unknownLoc, "unsupported OpConstant bitwidth: ")
1678 << bitwidth;
1679 };
1680
1681 auto resultID = operands[1];
1682
1683 if (auto intType = dyn_cast<IntegerType>(resultType)) {
1684 auto bitwidth = intType.getWidth();
1685 if (failed(checkOperandSizeForBitwidth(bitwidth))) {
1686 return failure();
1687 }
1688
1689 APInt value;
1690 if (bitwidth == 64) {
1691 // 64-bit integers are represented with two SPIR-V words. According to
1692 // SPIR-V spec: "When the type’s bit width is larger than one word, the
1693 // literal’s low-order words appear first."
1694 struct DoubleWord {
1695 uint32_t word1;
1696 uint32_t word2;
1697 } words = {operands[2], operands[3]};
1698 value = APInt(64, llvm::bit_cast<uint64_t>(words), /*isSigned=*/true);
1699 } else if (bitwidth <= 32) {
1700 value = APInt(bitwidth, operands[2], /*isSigned=*/true,
1701 /*implicitTrunc=*/true);
1702 }
1703
1704 auto attr = opBuilder.getIntegerAttr(intType, value);
1705
1706 if (isSpec) {
1707 createSpecConstant(unknownLoc, resultID, attr);
1708 } else {
1709 // For normal constants, we just record the attribute (and its type) for
1710 // later materialization at use sites.
1711 constantMap.try_emplace(resultID, attr, intType);
1712 }
1713
1714 return success();
1715 }
1716
1717 if (auto floatType = dyn_cast<FloatType>(resultType)) {
1718 auto bitwidth = floatType.getWidth();
1719 if (failed(checkOperandSizeForBitwidth(bitwidth))) {
1720 return failure();
1721 }
1722
1723 APFloat value(0.f);
1724 if (floatType.isF64()) {
1725 // Double values are represented with two SPIR-V words. According to
1726 // SPIR-V spec: "When the type’s bit width is larger than one word, the
1727 // literal’s low-order words appear first."
1728 struct DoubleWord {
1729 uint32_t word1;
1730 uint32_t word2;
1731 } words = {operands[2], operands[3]};
1732 value = APFloat(llvm::bit_cast<double>(words));
1733 } else if (floatType.isF32()) {
1734 value = APFloat(llvm::bit_cast<float>(operands[2]));
1735 } else if (floatType.isF16()) {
1736 APInt data(16, operands[2]);
1737 value = APFloat(APFloat::IEEEhalf(), data);
1738 } else if (floatType.isBF16()) {
1739 APInt data(16, operands[2]);
1740 value = APFloat(APFloat::BFloat(), data);
1741 } else if (floatType.isF8E4M3FN()) {
1742 APInt data(8, operands[2]);
1743 value = APFloat(APFloat::Float8E4M3FN(), data);
1744 } else if (floatType.isF8E5M2()) {
1745 APInt data(8, operands[2]);
1746 value = APFloat(APFloat::Float8E5M2(), data);
1747 }
1748
1749 auto attr = opBuilder.getFloatAttr(floatType, value);
1750 if (isSpec) {
1751 createSpecConstant(unknownLoc, resultID, attr);
1752 } else {
1753 // For normal constants, we just record the attribute (and its type) for
1754 // later materialization at use sites.
1755 constantMap.try_emplace(resultID, attr, floatType);
1756 }
1757
1758 return success();
1759 }
1760
1761 return emitError(unknownLoc, "OpConstant can only generate values of "
1762 "scalar integer or floating-point type");
1763}
1764
1766 bool isTrue, ArrayRef<uint32_t> operands, bool isSpec) {
1767 if (operands.size() != 2) {
1768 return emitError(unknownLoc, "Op")
1769 << (isSpec ? "Spec" : "") << "Constant"
1770 << (isTrue ? "True" : "False")
1771 << " must have type <id> and result <id>";
1772 }
1773
1774 auto attr = opBuilder.getBoolAttr(isTrue);
1775 auto resultID = operands[1];
1776 if (isSpec) {
1777 createSpecConstant(unknownLoc, resultID, attr);
1778 } else {
1779 // For normal constants, we just record the attribute (and its type) for
1780 // later materialization at use sites.
1781 constantMap.try_emplace(resultID, attr, opBuilder.getI1Type());
1782 }
1783
1784 return success();
1785}
1786
1787LogicalResult
1789 if (operands.size() < 2) {
1790 return emitError(unknownLoc,
1791 "OpConstantComposite must have type <id> and result <id>");
1792 }
1793 if (operands.size() < 3) {
1794 return emitError(unknownLoc,
1795 "OpConstantComposite must have at least 1 parameter");
1796 }
1797
1798 Type resultType = getType(operands[0]);
1799 if (!resultType) {
1800 return emitError(unknownLoc, "undefined result type from <id> ")
1801 << operands[0];
1802 }
1803
1805 elements.reserve(operands.size() - 2);
1806 for (unsigned i = 2, e = operands.size(); i < e; ++i) {
1807 auto elementInfo = getConstant(operands[i]);
1808 if (!elementInfo) {
1809 return emitError(unknownLoc, "OpConstantComposite component <id> ")
1810 << operands[i] << " must come from a normal constant";
1811 }
1812 elements.push_back(elementInfo->first);
1813 }
1814
1815 auto resultID = operands[1];
1816 if (auto tensorType = dyn_cast<TensorArmType>(resultType)) {
1817 SmallVector<Attribute> flattenedElems;
1818 for (Attribute element : elements) {
1819 if (auto denseElemAttr = dyn_cast<DenseElementsAttr>(element)) {
1820 for (auto value : denseElemAttr.getValues<Attribute>())
1821 flattenedElems.push_back(value);
1822 } else {
1823 flattenedElems.push_back(element);
1824 }
1825 }
1826 auto attr = DenseElementsAttr::get(tensorType, flattenedElems);
1827 constantMap.try_emplace(resultID, attr, tensorType);
1828 } else if (auto shapedType = dyn_cast<ShapedType>(resultType)) {
1829 auto attr = DenseElementsAttr::get(shapedType, elements);
1830 // For normal constants, we just record the attribute (and its type) for
1831 // later materialization at use sites.
1832 constantMap.try_emplace(resultID, attr, shapedType);
1833 } else if (auto arrayType = dyn_cast<spirv::ArrayType>(resultType)) {
1834 auto attr = opBuilder.getArrayAttr(elements);
1835 constantMap.try_emplace(resultID, attr, resultType);
1836 } else {
1837 return emitError(unknownLoc, "unsupported OpConstantComposite type: ")
1838 << resultType;
1839 }
1840
1841 return success();
1842}
1843
1845 ArrayRef<uint32_t> operands) {
1846 if (operands.size() != 3) {
1847 return emitError(
1848 unknownLoc,
1849 "OpConstantCompositeReplicateEXT expects 3 operands but found ")
1850 << operands.size();
1851 }
1852
1853 Type resultType = getType(operands[0]);
1854 if (!resultType) {
1855 return emitError(unknownLoc, "undefined result type from <id> ")
1856 << operands[0];
1857 }
1858
1859 auto compositeType = dyn_cast<CompositeType>(resultType);
1860 if (!compositeType) {
1861 return emitError(unknownLoc,
1862 "result type from <id> is not a composite type")
1863 << operands[0];
1864 }
1865
1866 uint32_t resultID = operands[1];
1867 uint32_t constantID = operands[2];
1868
1869 std::optional<std::pair<Attribute, Type>> constantInfo =
1870 getConstant(constantID);
1871 if (constantInfo.has_value()) {
1872 constantCompositeReplicateMap.try_emplace(
1873 resultID, constantInfo.value().first, resultType);
1874 return success();
1875 }
1876
1877 std::optional<std::pair<Attribute, Type>> replicatedConstantCompositeInfo =
1879 if (replicatedConstantCompositeInfo.has_value()) {
1880 constantCompositeReplicateMap.try_emplace(
1881 resultID, replicatedConstantCompositeInfo.value().first, resultType);
1882 return success();
1883 }
1884
1885 return emitError(unknownLoc, "OpConstantCompositeReplicateEXT operand <id> ")
1886 << constantID
1887 << " must come from a normal constant or a "
1888 "OpConstantCompositeReplicateEXT";
1889}
1890
1891LogicalResult
1893 if (operands.size() < 2) {
1894 return emitError(
1895 unknownLoc,
1896 "OpSpecConstantComposite must have type <id> and result <id>");
1897 }
1898 if (operands.size() < 3) {
1899 return emitError(unknownLoc,
1900 "OpSpecConstantComposite must have at least 1 parameter");
1901 }
1902
1903 Type resultType = getType(operands[0]);
1904 if (!resultType) {
1905 return emitError(unknownLoc, "undefined result type from <id> ")
1906 << operands[0];
1907 }
1908
1909 auto resultID = operands[1];
1910 auto symName = opBuilder.getStringAttr(getSpecConstantSymbol(resultID));
1911
1913 elements.reserve(operands.size() - 2);
1914 for (unsigned i = 2, e = operands.size(); i < e; ++i) {
1915 auto elementInfo = getSpecConstant(operands[i]);
1916 elements.push_back(SymbolRefAttr::get(elementInfo));
1917 }
1918
1919 auto op = spirv::SpecConstantCompositeOp::create(
1920 opBuilder, unknownLoc, TypeAttr::get(resultType), symName,
1921 opBuilder.getArrayAttr(elements));
1922 specConstCompositeMap[resultID] = op;
1923
1924 return success();
1925}
1926
1928 ArrayRef<uint32_t> operands) {
1929 if (operands.size() != 3) {
1930 return emitError(unknownLoc, "OpSpecConstantCompositeReplicateEXT expects "
1931 "3 operands but found ")
1932 << operands.size();
1933 }
1934
1935 Type resultType = getType(operands[0]);
1936 if (!resultType) {
1937 return emitError(unknownLoc, "undefined result type from <id> ")
1938 << operands[0];
1939 }
1940
1941 auto compositeType = dyn_cast<CompositeType>(resultType);
1942 if (!compositeType) {
1943 return emitError(unknownLoc,
1944 "result type from <id> is not a composite type")
1945 << operands[0];
1946 }
1947
1948 uint32_t resultID = operands[1];
1949
1950 auto symName = opBuilder.getStringAttr(getSpecConstantSymbol(resultID));
1951 spirv::SpecConstantOp constituentSpecConstantOp =
1952 getSpecConstant(operands[2]);
1953 auto op = spirv::EXTSpecConstantCompositeReplicateOp::create(
1954 opBuilder, unknownLoc, TypeAttr::get(resultType), symName,
1955 SymbolRefAttr::get(constituentSpecConstantOp));
1956
1957 specConstCompositeReplicateMap[resultID] = op;
1958
1959 return success();
1960}
1961
1962LogicalResult
1964 if (operands.size() < 3)
1965 return emitError(unknownLoc, "OpConstantOperation must have type <id>, "
1966 "result <id>, and operand opcode");
1967
1968 uint32_t resultTypeID = operands[0];
1969
1970 if (!getType(resultTypeID))
1971 return emitError(unknownLoc, "undefined result type from <id> ")
1972 << resultTypeID;
1973
1974 uint32_t resultID = operands[1];
1975 spirv::Opcode enclosedOpcode = static_cast<spirv::Opcode>(operands[2]);
1976 auto emplaceResult = specConstOperationMap.try_emplace(
1977 resultID,
1979 enclosedOpcode, resultTypeID,
1980 SmallVector<uint32_t>{operands.begin() + 3, operands.end()}});
1981
1982 if (!emplaceResult.second)
1983 return emitError(unknownLoc, "value with <id>: ")
1984 << resultID << " is probably defined before.";
1985
1986 return success();
1987}
1988
1990 uint32_t resultID, spirv::Opcode enclosedOpcode, uint32_t resultTypeID,
1991 ArrayRef<uint32_t> enclosedOpOperands) {
1992
1993 Type resultType = getType(resultTypeID);
1994
1995 // Instructions wrapped by OpSpecConstantOp need an ID for their
1996 // Deserializer::processOp<op_name>(...) to emit the corresponding SPIR-V
1997 // dialect wrapped op. For that purpose, a new value map is created and "fake"
1998 // ID in that map is assigned to the result of the enclosed instruction. Note
1999 // that there is no need to update this fake ID since we only need to
2000 // reference the created Value for the enclosed op from the spv::YieldOp
2001 // created later in this method (both of which are the only values in their
2002 // region: the SpecConstantOperation's region). If we encounter another
2003 // SpecConstantOperation in the module, we simply re-use the fake ID since the
2004 // previous Value assigned to it isn't visible in the current scope anyway.
2005 DenseMap<uint32_t, Value> newValueMap;
2006 llvm::SaveAndRestore valueMapGuard(valueMap, newValueMap);
2007 constexpr uint32_t fakeID = static_cast<uint32_t>(-3);
2008
2009 SmallVector<uint32_t, 4> enclosedOpResultTypeAndOperands;
2010 enclosedOpResultTypeAndOperands.push_back(resultTypeID);
2011 enclosedOpResultTypeAndOperands.push_back(fakeID);
2012 enclosedOpResultTypeAndOperands.append(enclosedOpOperands.begin(),
2013 enclosedOpOperands.end());
2014
2015 // Process enclosed instruction before creating the enclosing
2016 // specConstantOperation (and its region). This way, references to constants,
2017 // global variables, and spec constants will be materialized outside the new
2018 // op's region. For more info, see Deserializer::getValue's implementation.
2019 if (failed(
2020 processInstruction(enclosedOpcode, enclosedOpResultTypeAndOperands)))
2021 return Value();
2022
2023 // Since the enclosed op is emitted in the current block, split it in a
2024 // separate new block.
2025 Block *enclosedBlock = curBlock->splitBlock(&curBlock->back());
2026
2027 auto loc = createFileLineColLoc(opBuilder);
2028 auto specConstOperationOp =
2029 spirv::SpecConstantOperationOp::create(opBuilder, loc, resultType);
2030
2031 Region &body = specConstOperationOp.getBody();
2032 // Move the new block into SpecConstantOperation's body.
2033 body.getBlocks().splice(body.end(), curBlock->getParent()->getBlocks(),
2034 Region::iterator(enclosedBlock));
2035 Block &block = body.back();
2036
2037 // RAII guard to reset the insertion point to the module's region after
2038 // deserializing the body of the specConstantOperation.
2039 OpBuilder::InsertionGuard moduleInsertionGuard(opBuilder);
2040 opBuilder.setInsertionPointToEnd(&block);
2041
2042 spirv::YieldOp::create(opBuilder, loc, block.front().getResult(0));
2043 return specConstOperationOp.getResult();
2044}
2045
2046LogicalResult
2048 if (operands.size() != 2) {
2049 return emitError(unknownLoc,
2050 "OpConstantNull must only have type <id> and result <id>");
2051 }
2052
2053 Type resultType = getType(operands[0]);
2054 if (!resultType) {
2055 return emitError(unknownLoc, "undefined result type from <id> ")
2056 << operands[0];
2057 }
2058
2059 auto resultID = operands[1];
2060 Attribute attr;
2061 if (resultType.isIntOrFloat() || isa<VectorType>(resultType)) {
2062 attr = opBuilder.getZeroAttr(resultType);
2063 } else if (auto tensorType = dyn_cast<TensorArmType>(resultType)) {
2064 if (auto element = opBuilder.getZeroAttr(tensorType.getElementType()))
2065 attr = DenseElementsAttr::get(tensorType, element);
2066 }
2067
2068 if (attr) {
2069 // For normal constants, we just record the attribute (and its type) for
2070 // later materialization at use sites.
2071 constantMap.try_emplace(resultID, attr, resultType);
2072 return success();
2073 }
2074
2075 return emitError(unknownLoc, "unsupported OpConstantNull type: ")
2076 << resultType;
2077}
2078
2079LogicalResult
2081 if (operands.size() < 3) {
2082 return emitError(unknownLoc)
2083 << "OpGraphConstantARM must have at least 2 operands";
2084 }
2085
2086 Type resultType = getType(operands[0]);
2087 if (!resultType) {
2088 return emitError(unknownLoc, "undefined result type from <id> ")
2089 << operands[0];
2090 }
2091
2092 uint32_t resultID = operands[1];
2093
2094 if (!dyn_cast<spirv::TensorArmType>(resultType)) {
2095 return emitError(unknownLoc, "result must be of type OpTypeTensorARM");
2096 }
2097
2098 APInt graph_constant_id = APInt(32, operands[2], /*isSigned=*/true);
2099 Type i32Ty = opBuilder.getIntegerType(32);
2100 IntegerAttr attr = opBuilder.getIntegerAttr(i32Ty, graph_constant_id);
2101 graphConstantMap.try_emplace(
2102 resultID, GraphConstantARMOpMaterializationInfo{resultType, attr});
2103
2104 return success();
2105}
2106
2107//===----------------------------------------------------------------------===//
2108// Control flow
2109//===----------------------------------------------------------------------===//
2110
2112 if (auto *block = getBlock(id)) {
2113 LLVM_DEBUG(logger.startLine() << "[block] got exiting block for id = " << id
2114 << " @ " << block << "\n");
2115 return block;
2116 }
2117
2118 // We don't know where this block will be placed finally (in a
2119 // spirv.mlir.selection or spirv.mlir.loop or function). Create it into the
2120 // function for now and sort out the proper place later.
2121 auto *block = curFunction->addBlock();
2122 LLVM_DEBUG(logger.startLine() << "[block] created block for id = " << id
2123 << " @ " << block << "\n");
2124 return blockMap[id] = block;
2125}
2126
2128 if (!curBlock) {
2129 return emitError(unknownLoc, "OpBranch must appear inside a block");
2130 }
2131
2132 if (operands.size() != 1) {
2133 return emitError(unknownLoc, "OpBranch must take exactly one target label");
2134 }
2135
2136 auto *target = getOrCreateBlock(operands[0]);
2137 auto loc = createFileLineColLoc(opBuilder);
2138 // The preceding instruction for the OpBranch instruction could be an
2139 // OpLoopMerge or an OpSelectionMerge instruction, in this case they will have
2140 // the same OpLine information.
2141 spirv::BranchOp::create(opBuilder, loc, target);
2142
2144 return success();
2145}
2146
2147LogicalResult
2149 if (!curBlock) {
2150 return emitError(unknownLoc,
2151 "OpBranchConditional must appear inside a block");
2152 }
2153
2154 if (operands.size() != 3 && operands.size() != 5) {
2155 return emitError(unknownLoc,
2156 "OpBranchConditional must have condition, true label, "
2157 "false label, and optionally two branch weights");
2158 }
2159
2160 auto condition = getValue(operands[0]);
2161 auto *trueBlock = getOrCreateBlock(operands[1]);
2162 auto *falseBlock = getOrCreateBlock(operands[2]);
2163
2164 std::optional<std::pair<uint32_t, uint32_t>> weights;
2165 if (operands.size() == 5) {
2166 weights = std::make_pair(operands[3], operands[4]);
2167 }
2168 // The preceding instruction for the OpBranchConditional instruction could be
2169 // an OpSelectionMerge instruction, in this case they will have the same
2170 // OpLine information.
2171 auto loc = createFileLineColLoc(opBuilder);
2172 spirv::BranchConditionalOp::create(
2173 opBuilder, loc, condition, trueBlock,
2174 /*trueArguments=*/ArrayRef<Value>(), falseBlock,
2175 /*falseArguments=*/ArrayRef<Value>(), weights);
2176
2178 return success();
2179}
2180
2182 if (!curFunction) {
2183 return emitError(unknownLoc, "OpLabel must appear inside a function");
2184 }
2185
2186 if (operands.size() != 1) {
2187 return emitError(unknownLoc, "OpLabel should only have result <id>");
2188 }
2189
2190 auto labelID = operands[0];
2191 // We may have forward declared this block.
2192 auto *block = getOrCreateBlock(labelID);
2193 LLVM_DEBUG(logger.startLine()
2194 << "[block] populating block " << block << "\n");
2195 // If we have seen this block, make sure it was just a forward declaration.
2196 assert(block->empty() && "re-deserialize the same block!");
2197
2198 opBuilder.setInsertionPointToStart(block);
2199 blockMap[labelID] = curBlock = block;
2200
2201 return success();
2202}
2203
2204LogicalResult spirv::Deserializer::createGraphBlock(uint32_t graphID) {
2205 if (!curGraph) {
2206 return emitError(unknownLoc, "a graph block must appear inside a graph");
2207 }
2208
2209 // We may have forward declared this block.
2210 Block *block = getOrCreateBlock(graphID);
2211 LLVM_DEBUG(logger.startLine()
2212 << "[block] populating block " << block << "\n");
2213 // If we have seen this block, make sure it was just a forward declaration.
2214 assert(block->empty() && "re-deserialize the same block!");
2215
2216 opBuilder.setInsertionPointToStart(block);
2217 blockMap[graphID] = curBlock = block;
2218
2219 return success();
2220}
2221
2222LogicalResult
2224 if (!curBlock) {
2225 return emitError(unknownLoc, "OpSelectionMerge must appear in a block");
2226 }
2227
2228 if (operands.size() < 2) {
2229 return emitError(
2230 unknownLoc,
2231 "OpSelectionMerge must specify merge target and selection control");
2232 }
2233
2234 auto *mergeBlock = getOrCreateBlock(operands[0]);
2235 auto loc = createFileLineColLoc(opBuilder);
2236 auto selectionControl = operands[1];
2237
2238 if (!blockMergeInfo.try_emplace(curBlock, loc, selectionControl, mergeBlock)
2239 .second) {
2240 return emitError(
2241 unknownLoc,
2242 "a block cannot have more than one OpSelectionMerge instruction");
2243 }
2244
2245 return success();
2246}
2247
2248LogicalResult
2250 if (!curBlock) {
2251 return emitError(unknownLoc, "OpLoopMerge must appear in a block");
2252 }
2253
2254 if (operands.size() < 3) {
2255 return emitError(unknownLoc, "OpLoopMerge must specify merge target, "
2256 "continue target and loop control");
2257 }
2258
2259 auto *mergeBlock = getOrCreateBlock(operands[0]);
2260 auto *continueBlock = getOrCreateBlock(operands[1]);
2261 auto loc = createFileLineColLoc(opBuilder);
2262 uint32_t loopControl = operands[2];
2263
2264 if (!blockMergeInfo
2265 .try_emplace(curBlock, loc, loopControl, mergeBlock, continueBlock)
2266 .second) {
2267 return emitError(
2268 unknownLoc,
2269 "a block cannot have more than one OpLoopMerge instruction");
2270 }
2271
2272 return success();
2273}
2274
2276 if (!curBlock) {
2277 return emitError(unknownLoc, "OpPhi must appear in a block");
2278 }
2279
2280 if (operands.size() < 4) {
2281 return emitError(unknownLoc, "OpPhi must specify result type, result <id>, "
2282 "and variable-parent pairs");
2283 }
2284
2285 // Create a block argument for this OpPhi instruction.
2286 Type blockArgType = getType(operands[0]);
2287 BlockArgument blockArg = curBlock->addArgument(blockArgType, unknownLoc);
2288 valueMap[operands[1]] = blockArg;
2289 LLVM_DEBUG(logger.startLine()
2290 << "[phi] created block argument " << blockArg
2291 << " id = " << operands[1] << " of type " << blockArgType << "\n");
2292
2293 // For each (value, predecessor) pair, insert the value to the predecessor's
2294 // blockPhiInfo entry so later we can fix the block argument there.
2295 for (unsigned i = 2, e = operands.size(); i < e; i += 2) {
2296 uint32_t value = operands[i];
2297 Block *predecessor = getOrCreateBlock(operands[i + 1]);
2298 std::pair<Block *, Block *> predecessorTargetPair{predecessor, curBlock};
2299 blockPhiInfo[predecessorTargetPair].push_back(value);
2300 LLVM_DEBUG(logger.startLine() << "[phi] predecessor @ " << predecessor
2301 << " with arg id = " << value << "\n");
2302 }
2303
2304 return success();
2305}
2306
2308 if (!curBlock)
2309 return emitError(unknownLoc, "OpSwitch must appear in a block");
2310
2311 if (operands.size() < 2)
2312 return emitError(unknownLoc, "OpSwitch must at least specify selector and "
2313 "a default target");
2314
2315 if (operands.size() % 2)
2316 return emitError(unknownLoc,
2317 "OpSwitch must at have an even number of operands: "
2318 "selector, default target and any number of literal and "
2319 "label <id> pairs");
2320
2321 Value selector = getValue(operands[0]);
2322 Block *defaultBlock = getOrCreateBlock(operands[1]);
2323 Location loc = createFileLineColLoc(opBuilder);
2324
2325 SmallVector<int32_t> literals;
2326 SmallVector<Block *> blocks;
2327 for (unsigned i = 2, e = operands.size(); i < e; i += 2) {
2328 literals.push_back(operands[i]);
2329 blocks.push_back(getOrCreateBlock(operands[i + 1]));
2330 }
2331
2332 SmallVector<ValueRange> targetOperands(blocks.size(), {});
2333 spirv::SwitchOp::create(opBuilder, loc, selector, defaultBlock,
2334 ArrayRef<Value>(), literals, blocks, targetOperands);
2335
2336 return success();
2337}
2338
2339namespace {
2340/// A class for putting all blocks in a structured selection/loop in a
2341/// spirv.mlir.selection/spirv.mlir.loop op.
2342class ControlFlowStructurizer {
2343public:
2344#ifndef NDEBUG
2345 ControlFlowStructurizer(Location loc, uint32_t control,
2346 spirv::BlockMergeInfoMap &mergeInfo, Block *header,
2347 Block *merge, Block *cont,
2348 llvm::ScopedPrinter &logger)
2349 : location(loc), control(control), blockMergeInfo(mergeInfo),
2350 headerBlock(header), mergeBlock(merge), continueBlock(cont),
2351 logger(logger) {}
2352#else
2353 ControlFlowStructurizer(Location loc, uint32_t control,
2354 spirv::BlockMergeInfoMap &mergeInfo, Block *header,
2355 Block *merge, Block *cont)
2356 : location(loc), control(control), blockMergeInfo(mergeInfo),
2357 headerBlock(header), mergeBlock(merge), continueBlock(cont) {}
2358#endif
2359
2360 /// Structurizes the loop at the given `headerBlock`.
2361 ///
2362 /// This method will create an spirv.mlir.loop op in the `mergeBlock` and move
2363 /// all blocks in the structured loop into the spirv.mlir.loop's region. All
2364 /// branches to the `headerBlock` will be redirected to the `mergeBlock`. This
2365 /// method will also update `mergeInfo` by remapping all blocks inside to the
2366 /// newly cloned ones inside structured control flow op's regions.
2367 LogicalResult structurize();
2368
2369private:
2370 /// Creates a new spirv.mlir.selection op at the beginning of the
2371 /// `mergeBlock`.
2372 spirv::SelectionOp createSelectionOp(uint32_t selectionControl);
2373
2374 /// Creates a new spirv.mlir.loop op at the beginning of the `mergeBlock`.
2375 spirv::LoopOp createLoopOp(uint32_t loopControl);
2376
2377 /// Collects all blocks reachable from `headerBlock` except `mergeBlock`.
2378 void collectBlocksInConstruct();
2379
2380 Location location;
2381 uint32_t control;
2382
2383 spirv::BlockMergeInfoMap &blockMergeInfo;
2384
2385 Block *headerBlock;
2386 Block *mergeBlock;
2387 Block *continueBlock; // nullptr for spirv.mlir.selection
2388
2389 SetVector<Block *> constructBlocks;
2390
2391#ifndef NDEBUG
2392 /// A logger used to emit information during the deserialzation process.
2393 llvm::ScopedPrinter &logger;
2394#endif
2395};
2396} // namespace
2397
2398spirv::SelectionOp
2399ControlFlowStructurizer::createSelectionOp(uint32_t selectionControl) {
2400 // Create a builder and set the insertion point to the beginning of the
2401 // merge block so that the newly created SelectionOp will be inserted there.
2402 OpBuilder builder(&mergeBlock->front());
2403
2404 auto control = static_cast<spirv::SelectionControl>(selectionControl);
2405 auto selectionOp = spirv::SelectionOp::create(builder, location, control);
2406 selectionOp.addMergeBlock(builder);
2407
2408 return selectionOp;
2409}
2410
2411spirv::LoopOp ControlFlowStructurizer::createLoopOp(uint32_t loopControl) {
2412 // Create a builder and set the insertion point to the beginning of the
2413 // merge block so that the newly created LoopOp will be inserted there.
2414 OpBuilder builder(&mergeBlock->front());
2415
2416 auto control = static_cast<spirv::LoopControl>(loopControl);
2417 auto loopOp = spirv::LoopOp::create(builder, location, control);
2418 loopOp.addEntryAndMergeBlock(builder);
2419
2420 return loopOp;
2421}
2422
2423void ControlFlowStructurizer::collectBlocksInConstruct() {
2424 assert(constructBlocks.empty() && "expected empty constructBlocks");
2425
2426 // Put the header block in the work list first.
2427 constructBlocks.insert(headerBlock);
2428
2429 // For each item in the work list, add its successors excluding the merge
2430 // block.
2431 for (unsigned i = 0; i < constructBlocks.size(); ++i) {
2432 for (auto *successor : constructBlocks[i]->getSuccessors())
2433 if (successor != mergeBlock)
2434 constructBlocks.insert(successor);
2435 }
2436}
2437
2438LogicalResult ControlFlowStructurizer::structurize() {
2439 Operation *op = nullptr;
2440 bool isLoop = continueBlock != nullptr;
2441 if (isLoop) {
2442 if (auto loopOp = createLoopOp(control))
2443 op = loopOp.getOperation();
2444 } else {
2445 if (auto selectionOp = createSelectionOp(control))
2446 op = selectionOp.getOperation();
2447 }
2448 if (!op)
2449 return failure();
2450 Region &body = op->getRegion(0);
2451
2452 IRMapping mapper;
2453 // All references to the old merge block should be directed to the
2454 // selection/loop merge block in the SelectionOp/LoopOp's region.
2455 mapper.map(mergeBlock, &body.back());
2456
2457 collectBlocksInConstruct();
2458
2459 // We've identified all blocks belonging to the selection/loop's region. Now
2460 // need to "move" them into the selection/loop. Instead of really moving the
2461 // blocks, in the following we copy them and remap all values and branches.
2462 // This is because:
2463 // * Inserting a block into a region requires the block not in any region
2464 // before. But selections/loops can nest so we can create selection/loop ops
2465 // in a nested manner, which means some blocks may already be in a
2466 // selection/loop region when to be moved again.
2467 // * It's much trickier to fix up the branches into and out of the loop's
2468 // region: we need to treat not-moved blocks and moved blocks differently:
2469 // Not-moved blocks jumping to the loop header block need to jump to the
2470 // merge point containing the new loop op but not the loop continue block's
2471 // back edge. Moved blocks jumping out of the loop need to jump to the
2472 // merge block inside the loop region but not other not-moved blocks.
2473 // We cannot use replaceAllUsesWith clearly and it's harder to follow the
2474 // logic.
2475
2476 // Create a corresponding block in the SelectionOp/LoopOp's region for each
2477 // block in this loop construct.
2478 OpBuilder builder(body);
2479 for (auto *block : constructBlocks) {
2480 // Create a block and insert it before the selection/loop merge block in the
2481 // SelectionOp/LoopOp's region.
2482 auto *newBlock = builder.createBlock(&body.back());
2483 mapper.map(block, newBlock);
2484 LLVM_DEBUG(logger.startLine() << "[cf] cloned block " << newBlock
2485 << " from block " << block << "\n");
2486 if (!isFnEntryBlock(block)) {
2487 for (BlockArgument blockArg : block->getArguments()) {
2488 auto newArg =
2489 newBlock->addArgument(blockArg.getType(), blockArg.getLoc());
2490 mapper.map(blockArg, newArg);
2491 LLVM_DEBUG(logger.startLine() << "[cf] remapped block argument "
2492 << blockArg << " to " << newArg << "\n");
2493 }
2494 } else {
2495 LLVM_DEBUG(logger.startLine()
2496 << "[cf] block " << block << " is a function entry block\n");
2497 }
2498
2499 for (auto &op : *block)
2500 newBlock->push_back(op.clone(mapper));
2501 }
2502
2503 // Go through all ops and remap the operands.
2504 auto remapOperands = [&](Operation *op) {
2505 for (auto &operand : op->getOpOperands())
2506 if (Value mappedOp = mapper.lookupOrNull(operand.get()))
2507 operand.set(mappedOp);
2508 for (auto &succOp : op->getBlockOperands())
2509 if (Block *mappedOp = mapper.lookupOrNull(succOp.get()))
2510 succOp.set(mappedOp);
2511 };
2512 for (auto &block : body)
2513 block.walk(remapOperands);
2514
2515 // We have created the SelectionOp/LoopOp and "moved" all blocks belonging to
2516 // the selection/loop construct into its region. Next we need to fix the
2517 // connections between this new SelectionOp/LoopOp with existing blocks.
2518
2519 // All existing incoming branches should go to the merge block, where the
2520 // SelectionOp/LoopOp resides right now.
2521 headerBlock->replaceAllUsesWith(mergeBlock);
2522
2523 LLVM_DEBUG({
2524 logger.startLine() << "[cf] after cloning and fixing references:\n";
2525 headerBlock->getParentOp()->print(logger.getOStream());
2526 logger.startLine() << "\n";
2527 });
2528
2529 if (isLoop) {
2530 if (!mergeBlock->args_empty()) {
2531 return mergeBlock->getParentOp()->emitError(
2532 "OpPhi in loop merge block unsupported");
2533 }
2534
2535 // The loop header block may have block arguments. Since now we place the
2536 // loop op inside the old merge block, we need to make sure the old merge
2537 // block has the same block argument list.
2538 for (BlockArgument blockArg : headerBlock->getArguments())
2539 mergeBlock->addArgument(blockArg.getType(), blockArg.getLoc());
2540
2541 // If the loop header block has block arguments, make sure the spirv.Branch
2542 // op matches.
2543 SmallVector<Value, 4> blockArgs;
2544 if (!headerBlock->args_empty())
2545 blockArgs = {mergeBlock->args_begin(), mergeBlock->args_end()};
2546
2547 // The loop entry block should have a unconditional branch jumping to the
2548 // loop header block.
2549 builder.setInsertionPointToEnd(&body.front());
2550 spirv::BranchOp::create(builder, location, mapper.lookupOrNull(headerBlock),
2551 ArrayRef<Value>(blockArgs));
2552 }
2553
2554 // Values defined inside the selection region that need to be yielded outside
2555 // the region.
2556 SmallVector<Value> valuesToYield;
2557 // Outside uses of values that were sunk into the selection region. Those uses
2558 // will be replaced with values returned by the SelectionOp.
2559 SmallVector<Value> outsideUses;
2560
2561 // Move block arguments of the original block (`mergeBlock`) into the merge
2562 // block inside the selection (`body.back()`). Values produced by block
2563 // arguments will be yielded by the selection region. We do not update uses or
2564 // erase original block arguments yet. It will be done later in the code.
2565 //
2566 // Code below is not executed for loops as it would interfere with the logic
2567 // above. Currently block arguments in the merge block are not supported, but
2568 // instead, the code above copies those arguments from the header block into
2569 // the merge block. As such, running the code would yield those copied
2570 // arguments that is most likely not a desired behaviour. This may need to be
2571 // revisited in the future.
2572 if (!isLoop)
2573 for (BlockArgument blockArg : mergeBlock->getArguments()) {
2574 // Create new block arguments in the last block ("merge block") of the
2575 // selection region. We create one argument for each argument in
2576 // `mergeBlock`. This new value will need to be yielded, and the original
2577 // value replaced, so add them to appropriate vectors.
2578 body.back().addArgument(blockArg.getType(), blockArg.getLoc());
2579 valuesToYield.push_back(body.back().getArguments().back());
2580 outsideUses.push_back(blockArg);
2581 }
2582
2583 // All the blocks cloned into the SelectionOp/LoopOp's region can now be
2584 // cleaned up.
2585 LLVM_DEBUG(logger.startLine() << "[cf] cleaning up blocks after clone\n");
2586 // First we need to drop all operands' references inside all blocks. This is
2587 // needed because we can have blocks referencing SSA values from one another.
2588 for (auto *block : constructBlocks)
2589 block->dropAllReferences();
2590
2591 // All internal uses should be removed from original blocks by now, so
2592 // whatever is left is an outside use and will need to be yielded from
2593 // the newly created selection / loop region.
2594 for (Block *block : constructBlocks) {
2595 for (Operation &op : *block) {
2596 if (!op.use_empty())
2597 for (Value result : op.getResults()) {
2598 valuesToYield.push_back(mapper.lookupOrNull(result));
2599 outsideUses.push_back(result);
2600 }
2601 }
2602 for (BlockArgument &arg : block->getArguments()) {
2603 if (!arg.use_empty()) {
2604 valuesToYield.push_back(mapper.lookupOrNull(arg));
2605 outsideUses.push_back(arg);
2606 }
2607 }
2608 }
2609
2610 assert(valuesToYield.size() == outsideUses.size());
2611
2612 // If we need to yield any values from the selection / loop region we will
2613 // take care of it here.
2614 if (!valuesToYield.empty()) {
2615 LLVM_DEBUG(logger.startLine()
2616 << "[cf] yielding values from the selection / loop region\n");
2617
2618 // Update `mlir.merge` with values to be yield.
2619 auto mergeOps = body.back().getOps<spirv::MergeOp>();
2620 Operation *merge = llvm::getSingleElement(mergeOps);
2621 assert(merge);
2622 merge->setOperands(valuesToYield);
2623
2624 // MLIR does not allow changing the number of results of an operation, so
2625 // we create a new SelectionOp / LoopOp with required list of results and
2626 // move the region from the initial SelectionOp / LoopOp. The initial
2627 // operation is then removed. Since we move the region to the new op all
2628 // links between blocks and remapping we have previously done should be
2629 // preserved.
2630 builder.setInsertionPoint(&mergeBlock->front());
2631
2632 Operation *newOp = nullptr;
2633
2634 if (isLoop)
2635 newOp = spirv::LoopOp::create(builder, location,
2636 TypeRange(ValueRange(outsideUses)),
2637 static_cast<spirv::LoopControl>(control));
2638 else
2639 newOp = spirv::SelectionOp::create(
2640 builder, location, TypeRange(ValueRange(outsideUses)),
2641 static_cast<spirv::SelectionControl>(control));
2642
2643 newOp->getRegion(0).takeBody(body);
2644
2645 // Remove initial op and swap the pointer to the newly created one.
2646 op->erase();
2647 op = newOp;
2648
2649 // Update all outside uses to use results of the SelectionOp / LoopOp and
2650 // remove block arguments from the original merge block.
2651 for (unsigned i = 0, e = outsideUses.size(); i != e; ++i)
2652 outsideUses[i].replaceAllUsesWith(op->getResult(i));
2653
2654 // We do not support block arguments in loop merge block. Also running this
2655 // function with loop would break some of the loop specific code above
2656 // dealing with block arguments.
2657 if (!isLoop)
2658 mergeBlock->eraseArguments(0, mergeBlock->getNumArguments());
2659 }
2660
2661 // Check that whether some op in the to-be-erased blocks still has uses. Those
2662 // uses come from blocks that won't be sinked into the SelectionOp/LoopOp's
2663 // region. We cannot handle such cases given that once a value is sinked into
2664 // the SelectionOp/LoopOp's region, there is no escape for it.
2665 for (auto *block : constructBlocks) {
2666 if (!block->use_empty())
2667 return emitError(block->getParent()->getLoc(),
2668 "failed control flow structurization: "
2669 "block has uses outside of the "
2670 "enclosing selection/loop construct");
2671 for (Operation &op : *block)
2672 if (!op.use_empty())
2673 return op.emitOpError("failed control flow structurization: value has "
2674 "uses outside of the "
2675 "enclosing selection/loop construct");
2676 for (BlockArgument &arg : block->getArguments())
2677 if (!arg.use_empty())
2678 return emitError(arg.getLoc(), "failed control flow structurization: "
2679 "block argument has uses outside of the "
2680 "enclosing selection/loop construct");
2681 }
2682
2683 // Then erase all old blocks.
2684 for (auto *block : constructBlocks) {
2685 // We've cloned all blocks belonging to this construct into the structured
2686 // control flow op's region. Among these blocks, some may compose another
2687 // selection/loop. If so, they will be recorded within blockMergeInfo.
2688 // We need to update the pointers there to the newly remapped ones so we can
2689 // continue structurizing them later.
2690 //
2691 // We need to walk each block as constructBlocks do not include blocks
2692 // internal to ops already structured within those blocks. It is not
2693 // fully clear to me why the mergeInfo of blocks (yet to be structured)
2694 // inside already structured selections/loops get invalidated and needs
2695 // updating, however the following example code can cause a crash (depending
2696 // on the structuring order), when the most inner selection is being
2697 // structured after the outer selection and loop have been already
2698 // structured:
2699 //
2700 // spirv.mlir.for {
2701 // // ...
2702 // spirv.mlir.selection {
2703 // // ..
2704 // // A selection region that hasn't been yet structured!
2705 // // ..
2706 // }
2707 // // ...
2708 // }
2709 //
2710 // If the loop gets structured after the outer selection, but before the
2711 // inner selection. Moving the already structured selection inside the loop
2712 // will invalidate the mergeInfo of the region that is not yet structured.
2713 // Just going over constructBlocks will not check and updated header blocks
2714 // inside the already structured selection region. Walking block fixes that.
2715 //
2716 // TODO: If structuring was done in a fixed order starting with inner
2717 // most constructs this most likely not be an issue and the whole code
2718 // section could be removed. However, with the current non-deterministic
2719 // order this is not possible.
2720 //
2721 // TODO: The asserts in the following assumes input SPIR-V blob forms
2722 // correctly nested selection/loop constructs. We should relax this and
2723 // support error cases better.
2724 auto updateMergeInfo = [&](Block *block) -> WalkResult {
2725 auto it = blockMergeInfo.find(block);
2726 if (it != blockMergeInfo.end()) {
2727 // Use the original location for nested selection/loop ops.
2728 Location loc = it->second.loc;
2729
2730 Block *newHeader = mapper.lookupOrNull(block);
2731 if (!newHeader)
2732 return emitError(loc, "failed control flow structurization: nested "
2733 "loop header block should be remapped!");
2734
2735 Block *newContinue = it->second.continueBlock;
2736 if (newContinue) {
2737 newContinue = mapper.lookupOrNull(newContinue);
2738 if (!newContinue)
2739 return emitError(loc, "failed control flow structurization: nested "
2740 "loop continue block should be remapped!");
2741 }
2742
2743 Block *newMerge = it->second.mergeBlock;
2744 if (Block *mappedTo = mapper.lookupOrNull(newMerge))
2745 newMerge = mappedTo;
2746
2747 // The iterator should be erased before adding a new entry into
2748 // blockMergeInfo to avoid iterator invalidation.
2749 blockMergeInfo.erase(it);
2750 blockMergeInfo.try_emplace(newHeader, loc, it->second.control, newMerge,
2751 newContinue);
2752 }
2753
2754 return WalkResult::advance();
2755 };
2756
2757 if (block->walk(updateMergeInfo).wasInterrupted())
2758 return failure();
2759
2760 // The structured selection/loop's entry block does not have arguments.
2761 // If the function's header block is also part of the structured control
2762 // flow, we cannot just simply erase it because it may contain arguments
2763 // matching the function signature and used by the cloned blocks.
2764 if (isFnEntryBlock(block)) {
2765 LLVM_DEBUG(logger.startLine() << "[cf] changing entry block " << block
2766 << " to only contain a spirv.Branch op\n");
2767 // Still keep the function entry block for the potential block arguments,
2768 // but replace all ops inside with a branch to the merge block.
2769 block->clear();
2770 builder.setInsertionPointToEnd(block);
2771 spirv::BranchOp::create(builder, location, mergeBlock);
2772 } else {
2773 LLVM_DEBUG(logger.startLine() << "[cf] erasing block " << block << "\n");
2774 block->erase();
2775 }
2776 }
2777
2778 LLVM_DEBUG(logger.startLine()
2779 << "[cf] after structurizing construct with header block "
2780 << headerBlock << ":\n"
2781 << *op << "\n");
2782
2783 return success();
2784}
2785
2787 LLVM_DEBUG({
2788 logger.startLine()
2789 << "//----- [phi] start wiring up block arguments -----//\n";
2790 logger.indent();
2791 });
2792
2793 OpBuilder::InsertionGuard guard(opBuilder);
2794
2795 for (const auto &info : blockPhiInfo) {
2796 Block *block = info.first.first;
2797 Block *target = info.first.second;
2798 const BlockPhiInfo &phiInfo = info.second;
2799 LLVM_DEBUG({
2800 logger.startLine() << "[phi] block " << block << "\n";
2801 logger.startLine() << "[phi] before creating block argument:\n";
2802 block->getParentOp()->print(logger.getOStream());
2803 logger.startLine() << "\n";
2804 });
2805
2806 // Set insertion point to before this block's terminator early because we
2807 // may materialize ops via getValue() call.
2808 auto *op = block->getTerminator();
2809 opBuilder.setInsertionPoint(op);
2810
2811 SmallVector<Value, 4> blockArgs;
2812 blockArgs.reserve(phiInfo.size());
2813 for (uint32_t valueId : phiInfo) {
2814 if (Value value = getValue(valueId)) {
2815 blockArgs.push_back(value);
2816 LLVM_DEBUG(logger.startLine() << "[phi] block argument " << value
2817 << " id = " << valueId << "\n");
2818 } else {
2819 return emitError(unknownLoc, "OpPhi references undefined value!");
2820 }
2821 }
2822
2823 if (auto branchOp = dyn_cast<spirv::BranchOp>(op)) {
2824 // Replace the previous branch op with a new one with block arguments.
2825 spirv::BranchOp::create(opBuilder, branchOp.getLoc(),
2826 branchOp.getTarget(), blockArgs);
2827 branchOp.erase();
2828 } else if (auto branchCondOp = dyn_cast<spirv::BranchConditionalOp>(op)) {
2829 assert((branchCondOp.getTrueBlock() == target ||
2830 branchCondOp.getFalseBlock() == target) &&
2831 "expected target to be either the true or false target");
2832 if (target == branchCondOp.getTrueTarget())
2833 spirv::BranchConditionalOp::create(
2834 opBuilder, branchCondOp.getLoc(), branchCondOp.getCondition(),
2835 blockArgs, branchCondOp.getFalseBlockArguments(),
2836 branchCondOp.getBranchWeightsAttr(), branchCondOp.getTrueTarget(),
2837 branchCondOp.getFalseTarget());
2838 else
2839 spirv::BranchConditionalOp::create(
2840 opBuilder, branchCondOp.getLoc(), branchCondOp.getCondition(),
2841 branchCondOp.getTrueBlockArguments(), blockArgs,
2842 branchCondOp.getBranchWeightsAttr(), branchCondOp.getTrueBlock(),
2843 branchCondOp.getFalseBlock());
2844
2845 branchCondOp.erase();
2846 } else if (auto switchOp = dyn_cast<spirv::SwitchOp>(op)) {
2847 if (target == switchOp.getDefaultTarget()) {
2848 SmallVector<ValueRange> targetOperands(switchOp.getTargetOperands());
2849 DenseIntElementsAttr literals =
2850 switchOp.getLiterals().value_or(DenseIntElementsAttr());
2851 spirv::SwitchOp::create(
2852 opBuilder, switchOp.getLoc(), switchOp.getSelector(),
2853 switchOp.getDefaultTarget(), blockArgs, literals,
2854 switchOp.getTargets(), targetOperands);
2855 switchOp.erase();
2856 } else {
2857 SuccessorRange targets = switchOp.getTargets();
2858 auto it = llvm::find(targets, target);
2859 assert(it != targets.end());
2860 size_t index = std::distance(targets.begin(), it);
2861 switchOp.getTargetOperandsMutable(index).assign(blockArgs);
2862 }
2863 } else {
2864 return emitError(unknownLoc, "unimplemented terminator for Phi creation");
2865 }
2866
2867 LLVM_DEBUG({
2868 logger.startLine() << "[phi] after creating block argument:\n";
2869 block->getParentOp()->print(logger.getOStream());
2870 logger.startLine() << "\n";
2871 });
2872 }
2873 blockPhiInfo.clear();
2874
2875 LLVM_DEBUG({
2876 logger.unindent();
2877 logger.startLine()
2878 << "//--- [phi] completed wiring up block arguments ---//\n";
2879 });
2880 return success();
2881}
2882
2884 // Create a copy, so we can modify keys in the original.
2885 BlockMergeInfoMap blockMergeInfoCopy = blockMergeInfo;
2886 for (auto it = blockMergeInfoCopy.begin(), e = blockMergeInfoCopy.end();
2887 it != e; ++it) {
2888 auto &[block, mergeInfo] = *it;
2889
2890 // Skip processing loop regions. For loop regions continueBlock is non-null.
2891 if (mergeInfo.continueBlock)
2892 continue;
2893
2894 if (!block->mightHaveTerminator())
2895 continue;
2896
2897 Operation *terminator = block->getTerminator();
2898 assert(terminator);
2899
2900 if (!isa<spirv::BranchConditionalOp, spirv::SwitchOp>(terminator))
2901 continue;
2902
2903 // Check if the current header block is a merge block of another construct.
2904 bool splitHeaderMergeBlock = false;
2905 for (const auto &[_, mergeInfo] : blockMergeInfo) {
2906 if (mergeInfo.mergeBlock == block)
2907 splitHeaderMergeBlock = true;
2908 }
2909
2910 // Do not split a block that only contains a conditional branch / switch,
2911 // unless it is also a merge block of another construct - in that case we
2912 // want to split the block. We do not want two constructs to share header /
2913 // merge block.
2914 if (!llvm::hasSingleElement(*block) || splitHeaderMergeBlock) {
2915 Block *newBlock = block->splitBlock(terminator);
2916 OpBuilder builder(block, block->end());
2917 spirv::BranchOp::create(builder, block->getParent()->getLoc(), newBlock);
2918
2919 // After splitting we need to update the map to use the new block as a
2920 // header.
2921 blockMergeInfo.erase(block);
2922 blockMergeInfo.try_emplace(newBlock, mergeInfo);
2923 }
2924 }
2925
2926 return success();
2927}
2928
2930 if (!options.enableControlFlowStructurization) {
2931 LLVM_DEBUG(
2932 {
2933 logger.startLine()
2934 << "//----- [cf] skip structurizing control flow -----//\n";
2935 logger.indent();
2936 });
2937 return success();
2938 }
2939
2940 LLVM_DEBUG({
2941 logger.startLine()
2942 << "//----- [cf] start structurizing control flow -----//\n";
2943 logger.indent();
2944 });
2945
2946 LLVM_DEBUG({
2947 logger.startLine() << "[cf] split conditional blocks\n";
2948 logger.startLine() << "\n";
2949 });
2950
2951 if (failed(splitSelectionHeader())) {
2952 return failure();
2953 }
2954
2955 while (!blockMergeInfo.empty()) {
2956 Block *headerBlock = blockMergeInfo.begin()->first;
2957 BlockMergeInfo mergeInfo = blockMergeInfo.begin()->second;
2958
2959 LLVM_DEBUG({
2960 logger.startLine() << "[cf] header block " << headerBlock << ":\n";
2961 headerBlock->print(logger.getOStream());
2962 logger.startLine() << "\n";
2963 });
2964
2965 auto *mergeBlock = mergeInfo.mergeBlock;
2966 assert(mergeBlock && "merge block cannot be nullptr");
2967 if (mergeInfo.continueBlock && !mergeBlock->args_empty())
2968 return emitError(unknownLoc, "OpPhi in loop merge block unimplemented");
2969 LLVM_DEBUG({
2970 logger.startLine() << "[cf] merge block " << mergeBlock << ":\n";
2971 mergeBlock->print(logger.getOStream());
2972 logger.startLine() << "\n";
2973 });
2974
2975 auto *continueBlock = mergeInfo.continueBlock;
2976 LLVM_DEBUG(if (continueBlock) {
2977 logger.startLine() << "[cf] continue block " << continueBlock << ":\n";
2978 continueBlock->print(logger.getOStream());
2979 logger.startLine() << "\n";
2980 });
2981 // Erase this case before calling into structurizer, who will update
2982 // blockMergeInfo.
2983 blockMergeInfo.erase(blockMergeInfo.begin());
2984 ControlFlowStructurizer structurizer(mergeInfo.loc, mergeInfo.control,
2985 blockMergeInfo, headerBlock,
2986 mergeBlock, continueBlock
2987#ifndef NDEBUG
2988 ,
2989 logger
2990#endif
2991 );
2992 if (failed(structurizer.structurize()))
2993 return failure();
2994 }
2995
2996 LLVM_DEBUG({
2997 logger.unindent();
2998 logger.startLine()
2999 << "//--- [cf] completed structurizing control flow ---//\n";
3000 });
3001 return success();
3002}
3003
3004//===----------------------------------------------------------------------===//
3005// Debug
3006//===----------------------------------------------------------------------===//
3007
3009 if (!debugLine)
3010 return unknownLoc;
3011
3012 auto fileName = debugInfoMap.lookup(debugLine->fileID).str();
3013 if (fileName.empty())
3014 fileName = "<unknown>";
3015 return FileLineColLoc::get(opBuilder.getStringAttr(fileName), debugLine->line,
3016 debugLine->column);
3017}
3018
3019LogicalResult
3021 // According to SPIR-V spec:
3022 // "This location information applies to the instructions physically
3023 // following this instruction, up to the first occurrence of any of the
3024 // following: the next end of block, the next OpLine instruction, or the next
3025 // OpNoLine instruction."
3026 if (operands.size() != 3)
3027 return emitError(unknownLoc, "OpLine must have 3 operands");
3028 debugLine = DebugLine{operands[0], operands[1], operands[2]};
3029 return success();
3030}
3031
3032void spirv::Deserializer::clearDebugLine() { debugLine = std::nullopt; }
3033
3034LogicalResult
3036 if (operands.size() < 2)
3037 return emitError(unknownLoc, "OpString needs at least 2 operands");
3038
3039 if (!debugInfoMap.lookup(operands[0]).empty())
3040 return emitError(unknownLoc,
3041 "duplicate debug string found for result <id> ")
3042 << operands[0];
3043
3044 unsigned wordIndex = 1;
3045 StringRef debugString = decodeStringLiteral(operands, wordIndex);
3046 if (wordIndex != operands.size())
3047 return emitError(unknownLoc,
3048 "unexpected trailing words in OpString instruction");
3049
3050 debugInfoMap[operands[0]] = debugString;
3051 return success();
3052}
return success()
static bool isLoop(Operation *op)
Returns true if the given operation represents a loop by testing whether it implements the LoopLikeOp...
static bool isFnEntryBlock(Block *block)
Returns true if the given block is a function entry block.
#define MIN_VERSION_CASE(v)
static LogicalResult deserializeCacheControlDecoration(Location loc, OpBuilder &opBuilder, DenseMap< uint32_t, NamedAttrList > &decorations, ArrayRef< uint32_t > words, StringAttr symbol, StringRef decorationName, StringRef cacheControlKind)
static llvm::ManagedStatic< PassManagerOptions > options
Attributes are known-constant values of operations.
Definition Attributes.h:25
This class represents an argument of a Block.
Definition Value.h:309
Block represents an ordered list of Operations.
Definition Block.h:33
bool empty()
Definition Block.h:158
void erase()
Unlink this Block from its parent region and delete it.
Definition Block.cpp:66
Block * splitBlock(iterator splitBefore)
Split the block into two blocks before the specified operation or iterator.
Definition Block.cpp:323
Operation & front()
Definition Block.h:163
Operation * getTerminator()
Get the terminator operation of this block.
Definition Block.cpp:249
void print(raw_ostream &os)
bool args_empty()
Definition Block.h:109
iterator begin()
Definition Block.h:153
bool isEntryBlock()
Return if this block is the entry block in the parent region.
Definition Block.cpp:36
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
Definition Block.cpp:31
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
Definition Builders.cpp:270
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
Definition Builders.h:100
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
An attribute that represents a reference to a dense integer vector or tensor object.
static FileLineColLoc get(StringAttr filename, unsigned line, unsigned column)
Definition Location.cpp:157
A symbol reference with a reference path containing a single element.
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
Definition IRMapping.h:30
auto lookupOrNull(T from) const
Lookup a mapped value within the map.
Definition IRMapping.h:58
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:63
NamedAttrList is array of NamedAttributes that tracks whether it is sorted and does some basic work t...
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:164
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:350
This class helps build Operations.
Definition Builders.h:209
Operation is the basic unit of execution within MLIR.
Definition Operation.h:88
MutableArrayRef< BlockOperand > getBlockOperands()
Definition Operation.h:724
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
Definition Operation.h:715
bool use_empty()
Returns true if this operation has no uses.
Definition Operation.h:881
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:436
MutableArrayRef< OpOperand > getOpOperands()
Definition Operation.h:412
static Operation * create(Location location, OperationName name, TypeRange resultTypes, ValueRange operands, NamedAttrList &&attributes, OpaqueProperties properties, BlockRange successors, unsigned numRegions)
Create a new Operation with the specific fields.
Definition Operation.cpp:67
void print(raw_ostream &os, const OpPrintingFlags &flags={})
result_range getResults()
Definition Operation.h:444
Operation * clone(IRMapping &mapper, const CloneOptions &options=CloneOptions::all())
Create a deep copy of this operation, remapping any operands that use values outside of the operation...
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
void erase()
Remove this operation from its parent block and delete it.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
Block & back()
Definition Region.h:64
iterator end()
Definition Region.h:56
BlockListType & getBlocks()
Definition Region.h:45
BlockListType::iterator iterator
Definition Region.h:52
void takeBody(Region &other)
Takes body of another region (that region will have no body after this operation completes).
Definition Region.h:252
This class implements the successor iterators for Block.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Definition Types.cpp:118
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
static WalkResult advance()
Definition WalkResult.h:47
static ArrayType get(Type elementType, unsigned elementCount)
static CooperativeMatrixType get(Type elementType, uint32_t rows, uint32_t columns, Scope scope, CooperativeMatrixUseKHR use)
LogicalResult wireUpBlockArgument()
Creates block arguments on predecessors previously recorded when handling OpPhi instructions.
Value materializeSpecConstantOperation(uint32_t resultID, spirv::Opcode enclosedOpcode, uint32_t resultTypeID, ArrayRef< uint32_t > enclosedOpOperands)
Materializes/emits an OpSpecConstantOp instruction.
LogicalResult processOpTypePointer(ArrayRef< uint32_t > operands)
Value getValue(uint32_t id)
Get the Value associated with a result <id>.
LogicalResult processMatrixType(ArrayRef< uint32_t > operands)
LogicalResult processGlobalVariable(ArrayRef< uint32_t > operands)
Processes the OpVariable instructions at current offset into binary.
std::optional< SpecConstOperationMaterializationInfo > getSpecConstantOperation(uint32_t id)
Gets the info needed to materialize the spec constant operation op associated with the given <id>.
LogicalResult processConstantNull(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpConstantNull instruction with the given operands.
LogicalResult processSpecConstantComposite(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpSpecConstantComposite instruction with the given operands.
LogicalResult processInstruction(spirv::Opcode opcode, ArrayRef< uint32_t > operands, bool deferInstructions=true)
Processes a SPIR-V instruction with the given opcode and operands.
LogicalResult processBranchConditional(ArrayRef< uint32_t > operands)
spirv::GlobalVariableOp getGlobalVariable(uint32_t id)
Gets the global variable associated with a result <id> of OpVariable.
LogicalResult createGraphBlock(uint32_t graphID)
Creates a block for graph with the given graphID.
LogicalResult processStructType(ArrayRef< uint32_t > operands)
LogicalResult processGraphARM(ArrayRef< uint32_t > operands)
LogicalResult setFunctionArgAttrs(uint32_t argID, SmallVectorImpl< Attribute > &argAttrs, size_t argIndex)
Sets the function argument's attributes.
LogicalResult structurizeControlFlow()
Extracts blocks belonging to a structured selection/loop into a spirv.mlir.selection/spirv....
LogicalResult processLabel(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpLabel instruction with the given operands.
LogicalResult processSampledImageType(ArrayRef< uint32_t > operands)
LogicalResult processTensorARMType(ArrayRef< uint32_t > operands)
std::optional< spirv::GraphConstantARMOpMaterializationInfo > getGraphConstantARM(uint32_t id)
Gets the GraphConstantARM ID attribute and result type with the given result <id>.
std::optional< std::pair< Attribute, Type > > getConstant(uint32_t id)
Gets the constant's attribute and type associated with the given <id>.
LogicalResult processType(spirv::Opcode opcode, ArrayRef< uint32_t > operands)
Processes a SPIR-V type instruction with given opcode and operands and registers the type into module...
LogicalResult processLoopMerge(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpLoopMerge instruction with the given operands.
LogicalResult processArrayType(ArrayRef< uint32_t > operands)
LogicalResult sliceInstruction(spirv::Opcode &opcode, ArrayRef< uint32_t > &operands, std::optional< spirv::Opcode > expectedOpcode=std::nullopt)
Slices the first instruction out of binary and returns its opcode and operands via opcode and operand...
spirv::SpecConstantCompositeOp getSpecConstantComposite(uint32_t id)
Gets the composite specialization constant with the given result <id>.
SmallVector< uint32_t, 2 > BlockPhiInfo
For OpPhi instructions, we use block arguments to represent them.
LogicalResult processSpecConstantCompositeReplicateEXT(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpSpecConstantCompositeReplicateEXT instruction with the given operands.
LogicalResult processCooperativeMatrixTypeKHR(ArrayRef< uint32_t > operands)
LogicalResult processGraphEntryPointARM(ArrayRef< uint32_t > operands)
LogicalResult processFunction(ArrayRef< uint32_t > operands)
Creates a deserializer for the given SPIR-V binary module.
StringAttr getSymbolDecoration(StringRef decorationName)
Gets the symbol name from the name of decoration.
Block * getOrCreateBlock(uint32_t id)
Gets or creates the block corresponding to the given label <id>.
bool isVoidType(Type type) const
Returns true if the given type is for SPIR-V void type.
std::string getSpecConstantSymbol(uint32_t id)
Returns a symbol to be used for the specialization constant with the given result <id>.
LogicalResult processDebugString(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpString instruction with the given operands.
LogicalResult processPhi(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpPhi instruction with the given operands.
std::string getFunctionSymbol(uint32_t id)
Returns a symbol to be used for the function name with the given result <id>.
void clearDebugLine()
Discontinues any source-level location information that might be active from a previous OpLine instru...
LogicalResult processFunctionType(ArrayRef< uint32_t > operands)
IntegerAttr getConstantInt(uint32_t id)
Gets the constant's integer attribute with the given <id>.
LogicalResult processTypeForwardPointer(ArrayRef< uint32_t > operands)
LogicalResult processSwitch(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpSwitch instruction with the given operands.
LogicalResult processGraphEndARM(ArrayRef< uint32_t > operands)
LogicalResult processImageType(ArrayRef< uint32_t > operands)
LogicalResult processConstantComposite(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpConstantComposite instruction with the given operands.
spirv::SpecConstantOp createSpecConstant(Location loc, uint32_t resultID, TypedAttr defaultValue)
Creates a spirv::SpecConstantOp.
Block * getBlock(uint32_t id) const
Returns the block for the given label <id>.
LogicalResult processGraphTypeARM(ArrayRef< uint32_t > operands)
LogicalResult processBranch(ArrayRef< uint32_t > operands)
std::optional< std::pair< Attribute, Type > > getConstantCompositeReplicate(uint32_t id)
Gets the replicated composite constant's attribute and type associated with the given <id>.
LogicalResult processFunctionEnd(ArrayRef< uint32_t > operands)
Processes OpFunctionEnd and finalizes function.
LogicalResult processRuntimeArrayType(ArrayRef< uint32_t > operands)
LogicalResult processSpecConstantOperation(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpSpecConstantOp instruction with the given operands.
LogicalResult processConstant(ArrayRef< uint32_t > operands, bool isSpec)
Processes a SPIR-V Op{|Spec}Constant instruction with the given operands.
Location createFileLineColLoc(OpBuilder opBuilder)
Creates a FileLineColLoc with the OpLine location information.
LogicalResult processGraphConstantARM(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpGraphConstantARM instruction with the given operands.
LogicalResult processConstantBool(bool isTrue, ArrayRef< uint32_t > operands, bool isSpec)
Processes a SPIR-V Op{|Spec}Constant{True|False} instruction with the given operands.
spirv::SpecConstantOp getSpecConstant(uint32_t id)
Gets the specialization constant with the given result <id>.
LogicalResult processConstantCompositeReplicateEXT(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpConstantCompositeReplicateEXT instruction with the given operands.
LogicalResult processSelectionMerge(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpSelectionMerge instruction with the given operands.
LogicalResult processOpGraphSetOutputARM(ArrayRef< uint32_t > operands)
LogicalResult processDebugLine(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpLine instruction with the given operands.
LogicalResult splitSelectionHeader()
Move a conditional branch or a switch into a separate basic block to avoid unnecessary sinking of def...
std::string getGraphSymbol(uint32_t id)
Returns a symbol to be used for the graph name with the given result <id>.
static ImageType get(Type elementType, Dim dim, ImageDepthInfo depth=ImageDepthInfo::DepthUnknown, ImageArrayedInfo arrayed=ImageArrayedInfo::NonArrayed, ImageSamplingInfo samplingInfo=ImageSamplingInfo::SingleSampled, ImageSamplerUseInfo samplerUse=ImageSamplerUseInfo::SamplerUnknown, ImageFormat format=ImageFormat::Unknown)
Definition SPIRVTypes.h:147
static MatrixType get(Type columnType, uint32_t columnCount)
static PointerType get(Type pointeeType, StorageClass storageClass)
static RuntimeArrayType get(Type elementType)
static SampledImageType get(Type imageType)
static StructType getIdentified(MLIRContext *context, StringRef identifier)
Construct an identified StructType.
static StructType getEmpty(MLIRContext *context, StringRef identifier="")
Construct a (possibly identified) StructType with no members.
static StructType get(ArrayRef< Type > memberTypes, ArrayRef< OffsetInfo > offsetInfo={}, ArrayRef< MemberDecorationInfo > memberDecorations={}, ArrayRef< StructDecorationInfo > structDecorations={})
Construct a literal StructType with at least one member.
static TensorArmType get(ArrayRef< int64_t > shape, Type elementType)
static VerCapExtAttr get(Version version, ArrayRef< Capability > capabilities, ArrayRef< Extension > extensions, MLIRContext *context)
Gets a VerCapExtAttr instance.
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition CallGraph.h:229
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:717
constexpr uint32_t kMagicNumber
SPIR-V magic number.
llvm::MapVector< Block *, BlockMergeInfo > BlockMergeInfoMap
Map from a selection/loop's header block to its merge (and continue) target.
StringRef decodeStringLiteral(ArrayRef< uint32_t > words, unsigned &wordIndex)
Decodes a string literal in words starting at wordIndex.
constexpr unsigned kHeaderWordCount
SPIR-V binary header word count.
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:305
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
static std::string debugString(T &&op)
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:123
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:118
A struct for containing a header block's merge and continue targets.
A struct for containing OpLine instruction information.
A struct that collects the info needed to materialize/emit a GraphConstantARMOp.
A struct that collects the info needed to materialize/emit a SpecConstantOperation op.