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