24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/Sequence.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringExtras.h"
28#include "llvm/ADT/bit.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/MathExtras.h"
31#include "llvm/Support/SaveAndRestore.h"
32#include "llvm/Support/raw_ostream.h"
38#define DEBUG_TYPE "spirv-deserialization"
47 isa_and_nonnull<spirv::FuncOp>(block->
getParentOp());
66 : binary(binary), context(context), unknownLoc(UnknownLoc::
get(context)),
67 module(createModuleOp()), opBuilder(module->getRegion()),
options(
options)
75LogicalResult spirv::Deserializer::deserialize() {
79 <<
"//+++---------- start deserialization ----------+++//\n";
82 if (
failed(processHeader()))
85 spirv::Opcode opcode = spirv::Opcode::OpNop;
86 ArrayRef<uint32_t> operands;
87 auto binarySize = binary.size();
88 while (curOffset < binarySize) {
98 assert(curOffset == binarySize &&
99 "deserializer should never index beyond the binary end");
101 for (
auto &deferred : deferredInstructions) {
107 if (
failed(resolveDeferredIdDecorations()))
110 if (!functionParameterAttrs.empty())
111 return emitError(unknownLoc,
"FuncParamAttr decoration on result <id> ")
112 << functionParameterAttrs.begin()->first
113 <<
" is not supported: expected OpFunctionParameter or OpFunction";
117 LLVM_DEBUG(logger.startLine()
118 <<
"//+++-------- completed deserialization --------+++//\n");
122OwningOpRef<spirv::ModuleOp> spirv::Deserializer::collect() {
123 return std::move(module);
130OwningOpRef<spirv::ModuleOp> spirv::Deserializer::createModuleOp() {
131 OpBuilder builder(context);
132 OperationState state(unknownLoc, spirv::ModuleOp::getOperationName());
133 spirv::ModuleOp::build(builder, state);
137LogicalResult spirv::Deserializer::processHeader() {
140 "SPIR-V binary module must have a 5-word header");
143 return emitError(unknownLoc,
"incorrect magic number");
146 uint32_t majorVersion = (binary[1] << 8) >> 24;
147 uint32_t minorVersion = (binary[1] << 16) >> 24;
148 if (majorVersion == 1) {
149 switch (minorVersion) {
150#define MIN_VERSION_CASE(v) \
152 version = spirv::Version::V_1_##v; \
162#undef MIN_VERSION_CASE
164 return emitError(unknownLoc,
"unsupported SPIR-V minor version: ")
168 return emitError(unknownLoc,
"unsupported SPIR-V major version: ")
178spirv::Deserializer::processCapability(ArrayRef<uint32_t> operands) {
179 if (operands.size() != 1)
180 return emitError(unknownLoc,
"OpCapability must have one parameter");
182 auto cap = spirv::symbolizeCapability(operands[0]);
184 return emitError(unknownLoc,
"unknown capability: ") << operands[0];
186 capabilities.insert(*cap);
190LogicalResult spirv::Deserializer::processExtension(ArrayRef<uint32_t> words) {
194 "OpExtension must have a literal string for the extension name");
197 unsigned wordIndex = 0;
199 if (wordIndex != words.size())
201 "unexpected trailing words in OpExtension instruction");
202 auto ext = spirv::symbolizeExtension(extName);
204 return emitError(unknownLoc,
"unknown extension: ") << extName;
206 extensions.insert(*ext);
211spirv::Deserializer::processExtInstImport(ArrayRef<uint32_t> words) {
212 if (words.size() < 2) {
214 "OpExtInstImport must have a result <id> and a literal "
215 "string for the extended instruction set name");
218 unsigned wordIndex = 1;
220 if (wordIndex != words.size()) {
222 "unexpected trailing words in OpExtInstImport");
227void spirv::Deserializer::attachVCETriple() {
228 module->setVceTripleAttr(spirv::VerCapExtAttr::get(
229 version, capabilities.getArrayRef(), extensions.getArrayRef(), context));
233spirv::Deserializer::processMemoryModel(ArrayRef<uint32_t> operands) {
234 if (operands.size() != 2)
235 return emitError(unknownLoc,
"OpMemoryModel must have two operands");
237 module->setAddressingModel(
238 static_cast<spirv::AddressingModel>(operands.front()));
240 module->setMemoryModel(static_cast<spirv::MemoryModel>(operands.back()));
245template <
typename AttrTy,
typename EnumAttrTy,
typename EnumTy>
249 StringAttr symbol, StringRef decorationName, StringRef cacheControlKind) {
250 if (words.size() != 4) {
251 return emitError(loc,
"OpDecorate with ")
252 << decorationName <<
" needs a cache control integer literal and a "
253 << cacheControlKind <<
" cache control literal";
255 unsigned cacheLevel = words[2];
256 auto cacheControlAttr =
static_cast<EnumTy
>(words[3]);
257 auto value = opBuilder.
getAttr<AttrTy>(cacheLevel, cacheControlAttr);
260 dyn_cast_or_null<ArrayAttr>(decorations[words[0]].
get(symbol)))
261 llvm::append_range(attrs, attrList);
262 attrs.push_back(value);
263 decorations[words[0]].set(symbol, opBuilder.
getArrayAttr(attrs));
267LogicalResult spirv::Deserializer::processDecoration(ArrayRef<uint32_t> words) {
271 if (words.size() < 2) {
273 unknownLoc,
"OpDecorate must have at least result <id> and Decoration");
275 auto decorationName =
276 stringifyDecoration(
static_cast<spirv::Decoration
>(words[1]));
277 if (decorationName.empty()) {
278 return emitError(unknownLoc,
"invalid Decoration code : ") << words[1];
280 auto symbol = getSymbolDecoration(decorationName);
281 switch (
static_cast<spirv::Decoration
>(words[1])) {
282 case spirv::Decoration::FPFastMathMode:
283 if (words.size() != 3) {
284 return emitError(unknownLoc,
"OpDecorate with ")
285 << decorationName <<
" needs a single integer literal";
287 decorations[words[0]].set(
288 symbol, FPFastMathModeAttr::get(opBuilder.getContext(),
289 static_cast<FPFastMathMode
>(words[2])));
291 case spirv::Decoration::FPRoundingMode:
292 if (words.size() != 3) {
293 return emitError(unknownLoc,
"OpDecorate with ")
294 << decorationName <<
" needs a single integer literal";
296 decorations[words[0]].set(
297 symbol, FPRoundingModeAttr::get(opBuilder.getContext(),
298 static_cast<FPRoundingMode
>(words[2])));
300 case spirv::Decoration::FuncParamAttr: {
301 if (words.size() != 3)
303 "OpDecorate with FuncParamAttr needs a single "
304 "function parameter attribute");
305 auto value = spirv::symbolizeFunctionParameterAttribute(words[2]);
307 return emitError(unknownLoc,
"invalid FunctionParameterAttribute code: ")
309 SmallVector<Attribute> attrs;
310 if (
auto previous = functionParameterAttrs.lookup(words[0]))
311 llvm::append_range(attrs, previous);
313 spirv::FunctionParameterAttributeAttr::get(context, *value));
314 functionParameterAttrs[words[0]] = opBuilder.getArrayAttr(attrs);
317 case spirv::Decoration::Alignment:
318 case spirv::Decoration::MaxByteOffset:
319 case spirv::Decoration::DescriptorSet:
320 case spirv::Decoration::Binding:
321 case spirv::Decoration::Location:
322 case spirv::Decoration::SpecId:
323 case spirv::Decoration::Index:
324 case spirv::Decoration::Offset:
325 case spirv::Decoration::XfbBuffer:
326 case spirv::Decoration::XfbStride:
327 if (words.size() != 3) {
328 return emitError(unknownLoc,
"OpDecorate with ")
329 << decorationName <<
" needs a single integer literal";
331 decorations[words[0]].set(
332 symbol, opBuilder.getI32IntegerAttr(
static_cast<int32_t
>(words[2])));
334 case spirv::Decoration::BuiltIn:
335 if (words.size() != 3) {
336 return emitError(unknownLoc,
"OpDecorate with ")
337 << decorationName <<
" needs a single integer literal";
339 decorations[words[0]].set(
340 symbol, opBuilder.getStringAttr(
341 stringifyBuiltIn(
static_cast<spirv::BuiltIn
>(words[2]))));
343 case spirv::Decoration::ArrayStride:
344 if (words.size() != 3) {
345 return emitError(unknownLoc,
"OpDecorate with ")
346 << decorationName <<
" needs a single integer literal";
348 typeDecorations[words[0]] = words[2];
350 case spirv::Decoration::LinkageAttributes: {
351 if (words.size() < 4) {
352 return emitError(unknownLoc,
"OpDecorate with ")
354 <<
" needs at least 1 string and 1 integer literal";
362 unsigned wordIndex = 2;
364 auto linkageTypeAttr = opBuilder.getAttr<::mlir::spirv::LinkageTypeAttr>(
365 static_cast<::mlir::spirv::LinkageType
>(words[wordIndex++]));
366 auto linkageAttr = opBuilder.getAttr<::mlir::spirv::LinkageAttributesAttr>(
367 StringAttr::get(context, linkageName), linkageTypeAttr);
368 decorations[words[0]].set(symbol, dyn_cast<Attribute>(linkageAttr));
371 case spirv::Decoration::Aliased:
372 case spirv::Decoration::AliasedPointer:
373 case spirv::Decoration::Block:
374 case spirv::Decoration::BufferBlock:
375 case spirv::Decoration::CPacked:
376 case spirv::Decoration::Flat:
377 case spirv::Decoration::NonReadable:
378 case spirv::Decoration::NonWritable:
379 case spirv::Decoration::NoPerspective:
380 case spirv::Decoration::NoSignedWrap:
381 case spirv::Decoration::NoUnsignedWrap:
382 case spirv::Decoration::RelaxedPrecision:
383 case spirv::Decoration::Restrict:
384 case spirv::Decoration::RestrictPointer:
385 case spirv::Decoration::NoContraction:
386 case spirv::Decoration::Constant:
387 case spirv::Decoration::Invariant:
388 case spirv::Decoration::Patch:
389 case spirv::Decoration::Coherent:
390 case spirv::Decoration::Volatile:
391 case spirv::Decoration::SaturatedConversion:
392 if (words.size() != 2) {
393 return emitError(unknownLoc,
"OpDecorate with ")
394 << decorationName <<
" needs a single target <id>";
396 decorations[words[0]].set(symbol, opBuilder.getUnitAttr());
398 case spirv::Decoration::CacheControlLoadINTEL: {
400 CacheControlLoadINTELAttr, LoadCacheControlAttr, LoadCacheControl>(
401 unknownLoc, opBuilder, decorations, words, symbol, decorationName,
407 case spirv::Decoration::CacheControlStoreINTEL: {
409 CacheControlStoreINTELAttr, StoreCacheControlAttr, StoreCacheControl>(
410 unknownLoc, opBuilder, decorations, words, symbol, decorationName,
416 case spirv::Decoration::AlignmentId:
417 case spirv::Decoration::MaxByteOffsetId:
418 case spirv::Decoration::CounterBuffer:
419 if (words.size() != 3) {
420 return emitError(unknownLoc,
"OpDecorateId with ")
421 << decorationName <<
" needs a single <id> operand";
423 pendingIdDecorations.push_back({words[0],
424 static_cast<spirv::Decoration
>(words[1]),
425 words[2], unknownLoc});
428 return emitError(unknownLoc,
"unhandled Decoration : '") << decorationName;
433LogicalResult spirv::Deserializer::resolveDeferredIdDecorations() {
434 for (
const DeferredIdDecoration &entry : pendingIdDecorations) {
435 StringRef decorationName = stringifyDecoration(entry.decoration);
436 StringAttr symbol = getSymbolDecoration(decorationName);
440 StringRef operandSymName;
441 if (spirv::GlobalVariableOp varOp =
442 globalVariableMap.lookup(entry.operandID))
443 operandSymName = varOp.getSymName();
444 else if (spirv::SpecConstantOp specOp =
445 specConstMap.lookup(entry.operandID))
446 operandSymName = specOp.getSymName();
448 return emitError(entry.loc,
"OpDecorateId with ")
449 << decorationName <<
" references <id> " << entry.operandID
450 <<
" which is not a global variable or specialization constant";
457 Operation *targetOp =
nullptr;
458 if (spirv::GlobalVariableOp varOp =
459 globalVariableMap.lookup(entry.targetID))
461 else if (spirv::SpecConstantOp specOp = specConstMap.lookup(entry.targetID))
463 else if (spirv::FuncOp fnOp = funcMap.lookup(entry.targetID))
465 else if (Value v = valueMap.lookup(entry.targetID))
466 targetOp = v.getDefiningOp();
469 return emitError(entry.loc,
"OpDecorateId with ")
470 << decorationName <<
" references unknown target <id> "
479spirv::Deserializer::processMemberDecoration(ArrayRef<uint32_t> words) {
481 if (words.size() < 3) {
483 "OpMemberDecorate must have at least 3 operands");
486 auto decoration =
static_cast<spirv::Decoration
>(words[2]);
487 if (decoration == spirv::Decoration::Offset && words.size() != 4) {
489 " missing offset specification in OpMemberDecorate with "
490 "Offset decoration");
492 ArrayRef<uint32_t> decorationOperands;
493 if (words.size() > 3) {
494 decorationOperands = words.slice(3);
496 memberDecorationMap[words[0]][words[1]][decoration] = decorationOperands;
500LogicalResult spirv::Deserializer::processMemberName(ArrayRef<uint32_t> words) {
501 if (words.size() < 3) {
502 return emitError(unknownLoc,
"OpMemberName must have at least 3 operands");
504 unsigned wordIndex = 2;
506 if (wordIndex != words.size()) {
508 "unexpected trailing words in OpMemberName instruction");
510 memberNameMap[words[0]][words[1]] = name;
516 spirv::DecorationAttr foundDecorationAttr;
518 if (
auto it = functionParameterAttrs.find(argID);
519 it != functionParameterAttrs.end()) {
521 functionParameterAttrs.erase(it);
525 spirv::Decoration::Alignment))) {
530 if (!isa<UnitAttr>(decAttr.getValue()))
531 return emitError(unknownLoc,
"unhandled decoration '")
532 << decAttr.getName().getValue()
533 <<
"' on function argument with result <id> " << argID;
536 if (foundDecorationAttr)
537 return emitError(unknownLoc,
"already found a decoration for function "
538 "argument with result <id> ")
541 std::optional<spirv::Decoration> decoration = spirv::symbolizeDecoration(
542 llvm::convertToCamelFromSnakeCase(decAttr.getName(),
true));
544 return emitError(unknownLoc,
"unknown decoration '")
545 << decAttr.getName().getValue()
546 <<
"' on function argument with result <id> " << argID;
547 foundDecorationAttr = spirv::DecorationAttr::get(context, *decoration);
550 if (foundDecorationAttr)
551 attributes.
set(spirv::DecorationAttr::name, foundDecorationAttr);
559 return emitError(unknownLoc,
"found function inside function");
563 if (operands.size() != 4) {
564 return emitError(unknownLoc,
"OpFunction must have 4 parameters");
568 return emitError(unknownLoc,
"undefined result type from <id> ")
572 uint32_t fnID = operands[1];
573 if (funcMap.count(fnID)) {
574 return emitError(unknownLoc,
"duplicate function definition/declaration");
577 auto fnControl = spirv::symbolizeFunctionControl(operands[2]);
579 return emitError(unknownLoc,
"unknown Function Control: ") << operands[2];
583 if (!fnType || !isa<FunctionType>(fnType)) {
584 return emitError(unknownLoc,
"unknown function type from <id> ")
587 auto functionType = cast<FunctionType>(fnType);
589 if ((
isVoidType(resultType) && functionType.getNumResults() != 0) ||
590 (functionType.getNumResults() == 1 &&
591 functionType.getResult(0) != resultType)) {
592 return emitError(unknownLoc,
"mismatch in function type ")
593 << functionType <<
" and return type " << resultType <<
" specified";
597 auto funcOp = spirv::FuncOp::create(opBuilder, unknownLoc, fnName,
598 functionType, fnControl.value());
599 if (
auto it = functionParameterAttrs.find(fnID);
600 it != functionParameterAttrs.end()) {
601 if (functionType.getNumResults() == 0)
603 "FuncParamAttr decoration requires a non-void function "
606 functionParameterAttrs.erase(it);
609 if (decorations.count(fnID)) {
610 for (
auto attr : decorations[fnID].getAttrs()) {
614 curFunction = funcMap[fnID] = funcOp;
615 auto *entryBlock = funcOp.addEntryBlock();
618 <<
"//===-------------------------------------------===//\n";
619 logger.startLine() <<
"[fn] name: " << fnName <<
"\n";
620 logger.startLine() <<
"[fn] type: " << fnType <<
"\n";
621 logger.startLine() <<
"[fn] ID: " << fnID <<
"\n";
622 logger.startLine() <<
"[fn] entry block: " << entryBlock <<
"\n";
627 argAttrs.resize(functionType.getNumInputs());
630 if (functionType.getNumInputs()) {
631 for (
size_t i = 0, e = functionType.getNumInputs(); i != e; ++i) {
632 auto argType = functionType.getInput(i);
633 spirv::Opcode opcode = spirv::Opcode::OpNop;
636 spirv::Opcode::OpFunctionParameter))) {
639 if (opcode != spirv::Opcode::OpFunctionParameter) {
642 "missing OpFunctionParameter instruction for argument ")
645 if (operands.size() != 2) {
648 "expected result type and result <id> for OpFunctionParameter");
650 auto argDefinedType =
getType(operands[0]);
651 if (!argDefinedType || argDefinedType != argType) {
653 "mismatch in argument type between function type "
655 << functionType <<
" and argument type definition "
656 << argDefinedType <<
" at argument " << i;
659 return emitError(unknownLoc,
"duplicate definition of result <id> ")
666 auto argValue = funcOp.getArgument(i);
667 valueMap[operands[1]] = argValue;
671 if (llvm::any_of(argAttrs, [](
Attribute attr) {
672 auto argAttr = cast<DictionaryAttr>(attr);
673 return !argAttr.empty();
675 funcOp.setArgAttrsAttr(ArrayAttr::get(context, argAttrs));
680 auto linkageAttr = funcOp.getLinkageAttributes();
681 auto hasImportLinkage =
682 linkageAttr && (linkageAttr.value().getLinkageType().
getValue() ==
683 spirv::LinkageType::Import);
684 if (hasImportLinkage)
691 spirv::Opcode opcode = spirv::Opcode::OpNop;
700 spirv::Opcode::OpFunctionEnd))) {
703 if (opcode == spirv::Opcode::OpFunctionEnd) {
706 if (opcode != spirv::Opcode::OpLabel) {
707 return emitError(unknownLoc,
"a basic block must start with OpLabel");
709 if (instOperands.size() != 1) {
710 return emitError(unknownLoc,
"OpLabel should only have result <id>");
712 blockMap[instOperands[0]] = entryBlock;
720 spirv::Opcode::OpFunctionEnd)) &&
721 opcode != spirv::Opcode::OpFunctionEnd) {
726 if (opcode != spirv::Opcode::OpFunctionEnd) {
736 if (!operands.empty()) {
737 return emitError(unknownLoc,
"unexpected operands for OpFunctionEnd");
748 curFunction = std::nullopt;
753 <<
"//===-------------------------------------------===//\n";
760 if (operands.size() < 2) {
762 "missing graph defintion in OpGraphEntryPointARM");
765 unsigned wordIndex = 0;
766 uint32_t graphID = operands[wordIndex++];
767 if (!graphMap.contains(graphID)) {
769 "missing graph definition/declaration with id ")
773 spirv::GraphARMOp graphARM = graphMap[graphID];
775 graphARM.setSymName(name);
776 graphARM.setEntryPoint(
true);
779 for (
int64_t size = operands.size(); wordIndex < size; ++wordIndex) {
781 interface.push_back(SymbolRefAttr::get(arg.getOperation()));
783 return emitError(unknownLoc,
"undefined result <id> ")
784 << operands[wordIndex] <<
" while decoding OpGraphEntryPoint";
790 opBuilder.setInsertionPoint(graphARM);
791 spirv::GraphEntryPointARMOp::create(
792 opBuilder, unknownLoc, SymbolRefAttr::get(opBuilder.getContext(), name),
793 opBuilder.getArrayAttr(interface));
801 return emitError(unknownLoc,
"found graph inside graph");
804 if (operands.size() < 2) {
805 return emitError(unknownLoc,
"OpGraphARM must have at least 2 parameters");
809 if (!type || !isa<GraphType>(type)) {
810 return emitError(unknownLoc,
"unknown graph type from <id> ")
813 auto graphType = cast<GraphType>(type);
814 if (graphType.getNumResults() <= 0) {
815 return emitError(unknownLoc,
"expected at least one result");
818 uint32_t graphID = operands[1];
819 if (graphMap.count(graphID)) {
820 return emitError(unknownLoc,
"duplicate graph definition/declaration");
825 spirv::GraphARMOp::create(opBuilder, unknownLoc, graphName, graphType);
826 curGraph = graphMap[graphID] = graphOp;
827 Block *entryBlock = graphOp.addEntryBlock();
830 <<
"//===-------------------------------------------===//\n";
831 logger.startLine() <<
"[graph] name: " << graphName <<
"\n";
832 logger.startLine() <<
"[graph] type: " << graphType <<
"\n";
833 logger.startLine() <<
"[graph] ID: " << graphID <<
"\n";
834 logger.startLine() <<
"[graph] entry block: " << entryBlock <<
"\n";
839 for (
auto [
index, argType] : llvm::enumerate(graphType.getInputs())) {
840 spirv::Opcode opcode;
843 spirv::Opcode::OpGraphInputARM))) {
846 if (operands.size() != 3) {
847 return emitError(unknownLoc,
"expected result type, result <id> and "
848 "input index for OpGraphInputARM");
852 if (!argDefinedType) {
853 return emitError(unknownLoc,
"unknown operand type <id> ") << operands[0];
856 if (argDefinedType != argType) {
858 "mismatch in argument type between graph type "
860 << graphType <<
" and argument type definition " << argDefinedType
861 <<
" at argument " <<
index;
864 return emitError(unknownLoc,
"duplicate definition of result <id> ")
869 if (!inputIndexAttr) {
871 "unable to read inputIndex value from constant op ")
874 BlockArgument argValue = graphOp.getArgument(inputIndexAttr.getInt());
875 valueMap[operands[1]] = argValue;
878 graphOutputs.resize(graphType.getNumResults());
884 blockMap[graphID] = entryBlock;
891 spirv::Opcode opcode;
901 }
while (opcode != spirv::Opcode::OpGraphEndARM);
908 if (operands.size() != 2) {
911 "expected value id and output index for OpGraphSetOutputARM");
914 uint32_t
id = operands[0];
917 return emitError(unknownLoc,
"could not find result <id> ") << id;
921 if (!outputIndexAttr) {
923 "unable to read outputIndex value from constant op ")
926 graphOutputs[outputIndexAttr.getInt()] = value;
933 spirv::GraphOutputsARMOp::create(opBuilder, unknownLoc, graphOutputs);
936 if (!operands.empty()) {
937 return emitError(unknownLoc,
"unexpected operands for OpGraphEndARM");
941 curGraph = std::nullopt;
942 graphOutputs.clear();
947 <<
"//===-------------------------------------------===//\n";
952std::optional<std::pair<Attribute, Type>>
954 auto constIt = constantMap.find(
id);
955 if (constIt != constantMap.end())
956 return constIt->getSecond();
958 auto replicatedConstIt = constantCompositeReplicateMap.find(
id);
959 if (replicatedConstIt == constantCompositeReplicateMap.end())
962 auto [value, type] = replicatedConstIt->getSecond();
963 auto shapedType = dyn_cast<ShapedType>(type);
969std::optional<std::pair<Attribute, Type>>
971 if (
auto it = constantCompositeReplicateMap.find(
id);
972 it != constantCompositeReplicateMap.end())
977std::optional<spirv::SpecConstOperationMaterializationInfo>
979 auto constIt = specConstOperationMap.find(
id);
980 if (constIt == specConstOperationMap.end())
982 return constIt->getSecond();
986 auto funcName = nameMap.lookup(
id).str();
987 if (funcName.empty()) {
988 funcName =
"spirv_fn_" + std::to_string(
id);
994 std::string graphName = nameMap.lookup(
id).str();
995 if (graphName.empty()) {
996 graphName =
"spirv_graph_" + std::to_string(
id);
1002 auto constName = nameMap.lookup(
id).str();
1003 if (constName.empty()) {
1004 constName =
"spirv_spec_const_" + std::to_string(
id);
1009spirv::SpecConstantOp
1011 TypedAttr defaultValue) {
1013 auto op = spirv::SpecConstantOp::create(opBuilder, unknownLoc, symName,
1016 if (decorations.count(resultID)) {
1017 for (
auto attr : decorations[resultID].getAttrs())
1020 specConstMap[resultID] = op;
1024std::optional<spirv::GraphConstantARMOpMaterializationInfo>
1026 auto graphConstIt = graphConstantMap.find(
id);
1027 if (graphConstIt == graphConstantMap.end())
1028 return std::nullopt;
1029 return graphConstIt->getSecond();
1034 unsigned wordIndex = 0;
1035 if (operands.size() < 3) {
1038 "OpVariable needs at least 3 operands, type, <id> and storage class");
1042 auto type =
getType(operands[wordIndex]);
1044 return emitError(unknownLoc,
"unknown result type <id> : ")
1045 << operands[wordIndex];
1047 auto ptrType = dyn_cast<spirv::PointerType>(type);
1050 "expected a result type <id> to be a spirv.ptr, found : ")
1056 auto variableID = operands[wordIndex];
1057 auto variableName = nameMap.lookup(variableID).str();
1058 if (variableName.empty()) {
1059 variableName =
"spirv_var_" + std::to_string(variableID);
1064 auto storageClass =
static_cast<spirv::StorageClass
>(operands[wordIndex]);
1065 if (ptrType.getStorageClass() != storageClass) {
1066 return emitError(unknownLoc,
"mismatch in storage class of pointer type ")
1067 << type <<
" and that specified in OpVariable instruction : "
1068 << stringifyStorageClass(storageClass);
1075 if (wordIndex < operands.size()) {
1085 return emitError(unknownLoc,
"unknown <id> ")
1086 << operands[wordIndex] <<
"used as initializer";
1088 initializer = SymbolRefAttr::get(op);
1091 if (wordIndex != operands.size()) {
1093 "found more operands than expected when deserializing "
1094 "OpVariable instruction, only ")
1095 << wordIndex <<
" of " << operands.size() <<
" processed";
1098 auto varOp = spirv::GlobalVariableOp::create(
1099 opBuilder, loc, TypeAttr::get(type),
1100 opBuilder.getStringAttr(variableName), initializer);
1103 if (decorations.count(variableID)) {
1104 for (
auto attr : decorations[variableID].getAttrs())
1107 globalVariableMap[variableID] = varOp;
1116 return dyn_cast<IntegerAttr>(constInfo->first);
1120 if (operands.size() < 2) {
1121 return emitError(unknownLoc,
"OpName needs at least 2 operands");
1124 unsigned wordIndex = 1;
1126 if (wordIndex != operands.size()) {
1128 "unexpected trailing words in OpName instruction");
1133 nameMap.emplace_or_assign(operands[0], name);
1144 if (operands.empty()) {
1145 return emitError(unknownLoc,
"type instruction with opcode ")
1146 << spirv::stringifyOpcode(opcode) <<
" needs at least one <id>";
1151 if (typeMap.count(operands[0])) {
1152 return emitError(unknownLoc,
"duplicate definition for result <id> ")
1157 case spirv::Opcode::OpTypeVoid:
1158 if (operands.size() != 1)
1159 return emitError(unknownLoc,
"OpTypeVoid must have no parameters");
1160 typeMap[operands[0]] = opBuilder.getNoneType();
1162 case spirv::Opcode::OpTypeBool:
1163 if (operands.size() != 1)
1164 return emitError(unknownLoc,
"OpTypeBool must have no parameters");
1165 typeMap[operands[0]] = opBuilder.getI1Type();
1167 case spirv::Opcode::OpTypeInt: {
1168 if (operands.size() != 3)
1170 unknownLoc,
"OpTypeInt must have bitwidth and signedness parameters");
1179 auto sign = operands[2] == 1 ? IntegerType::SignednessSemantics::Signed
1180 : IntegerType::SignednessSemantics::Signless;
1181 typeMap[operands[0]] = IntegerType::get(context, operands[1], sign);
1183 case spirv::Opcode::OpTypeFloat: {
1184 if (operands.size() != 2 && operands.size() != 3)
1186 "OpTypeFloat expects either 2 operands (type, bitwidth) "
1187 "or 3 operands (type, bitwidth, encoding), but got ")
1189 uint32_t bitWidth = operands[1];
1192 if (operands.size() == 2) {
1195 floatTy = opBuilder.getF16Type();
1198 floatTy = opBuilder.getF32Type();
1201 floatTy = opBuilder.getF64Type();
1204 return emitError(unknownLoc,
"unsupported OpTypeFloat bitwidth: ")
1209 if (operands.size() == 3) {
1210 if (spirv::FPEncoding(operands[2]) == spirv::FPEncoding::BFloat16KHR &&
1212 floatTy = opBuilder.getBF16Type();
1213 else if (spirv::FPEncoding(operands[2]) ==
1214 spirv::FPEncoding::Float8E4M3EXT &&
1216 floatTy = opBuilder.getF8E4M3FNType();
1217 else if (spirv::FPEncoding(operands[2]) ==
1218 spirv::FPEncoding::Float8E5M2EXT &&
1220 floatTy = opBuilder.getF8E5M2Type();
1222 return emitError(unknownLoc,
"unsupported OpTypeFloat FP encoding: ")
1223 << operands[2] <<
" and bitWidth " << bitWidth;
1226 typeMap[operands[0]] = floatTy;
1228 case spirv::Opcode::OpTypeVector: {
1229 if (operands.size() != 3) {
1232 "OpTypeVector must have element type and count parameters");
1236 return emitError(unknownLoc,
"OpTypeVector references undefined <id> ")
1239 typeMap[operands[0]] = VectorType::get({operands[2]}, elementTy);
1241 case spirv::Opcode::OpTypePointer: {
1244 case spirv::Opcode::OpTypeArray:
1246 case spirv::Opcode::OpTypeCooperativeMatrixKHR:
1248 case spirv::Opcode::OpTypeFunction:
1250 case spirv::Opcode::OpTypeImage:
1252 case spirv::Opcode::OpTypeSampler:
1254 case spirv::Opcode::OpTypeNamedBarrier:
1256 case spirv::Opcode::OpTypeSampledImage:
1258 case spirv::Opcode::OpTypeRuntimeArray:
1260 case spirv::Opcode::OpTypeStruct:
1262 case spirv::Opcode::OpTypeMatrix:
1264 case spirv::Opcode::OpTypeTensorARM:
1266 case spirv::Opcode::OpTypeGraphARM:
1269 return emitError(unknownLoc,
"unhandled type instruction");
1276 if (operands.size() != 3)
1277 return emitError(unknownLoc,
"OpTypePointer must have two parameters");
1279 auto pointeeType =
getType(operands[2]);
1281 return emitError(unknownLoc,
"unknown OpTypePointer pointee type <id> ")
1284 uint32_t typePointerID = operands[0];
1285 auto storageClass =
static_cast<spirv::StorageClass
>(operands[1]);
1288 for (
auto *deferredStructIt = std::begin(deferredStructTypesInfos);
1289 deferredStructIt != std::end(deferredStructTypesInfos);) {
1290 for (
auto *unresolvedMemberIt =
1291 std::begin(deferredStructIt->unresolvedMemberTypes);
1292 unresolvedMemberIt !=
1293 std::end(deferredStructIt->unresolvedMemberTypes);) {
1294 if (unresolvedMemberIt->first == typePointerID) {
1298 deferredStructIt->memberTypes[unresolvedMemberIt->second] =
1299 typeMap[typePointerID];
1300 unresolvedMemberIt =
1301 deferredStructIt->unresolvedMemberTypes.erase(unresolvedMemberIt);
1303 ++unresolvedMemberIt;
1307 if (deferredStructIt->unresolvedMemberTypes.empty()) {
1309 auto structType = deferredStructIt->deferredStructType;
1311 assert(structType &&
"expected a spirv::StructType");
1312 assert(structType.isIdentified() &&
"expected an indentified struct");
1314 if (failed(structType.trySetBody(
1315 deferredStructIt->memberTypes, deferredStructIt->offsetInfo,
1316 deferredStructIt->memberDecorationsInfo,
1317 deferredStructIt->structDecorationsInfo)))
1320 deferredStructIt = deferredStructTypesInfos.erase(deferredStructIt);
1331 if (operands.size() != 3) {
1333 "OpTypeArray must have element type and count parameters");
1338 return emitError(unknownLoc,
"OpTypeArray references undefined <id> ")
1346 return emitError(unknownLoc,
"OpTypeArray count <id> ")
1347 << operands[2] <<
"can only come from normal constant right now";
1350 if (
auto intVal = dyn_cast<IntegerAttr>(countInfo->first)) {
1351 count = intVal.getValue().getZExtValue();
1353 return emitError(unknownLoc,
"OpTypeArray count must come from a "
1354 "scalar integer constant instruction");
1358 elementTy, count, typeDecorations.lookup(operands[0]));
1364 assert(!operands.empty() &&
"No operands for processing function type");
1365 if (operands.size() == 1) {
1366 return emitError(unknownLoc,
"missing return type for OpTypeFunction");
1368 auto returnType =
getType(operands[1]);
1370 return emitError(unknownLoc,
"unknown return type in OpTypeFunction");
1373 for (
size_t i = 2, e = operands.size(); i < e; ++i) {
1374 auto ty =
getType(operands[i]);
1376 return emitError(unknownLoc,
"unknown argument type in OpTypeFunction");
1378 argTypes.push_back(ty);
1384 typeMap[operands[0]] = FunctionType::get(context, argTypes, returnTypes);
1390 if (operands.size() != 6) {
1392 "OpTypeCooperativeMatrixKHR must have element type, "
1393 "scope, row and column parameters, and use");
1399 "OpTypeCooperativeMatrixKHR references undefined <id> ")
1403 std::optional<spirv::Scope> scope =
1408 "OpTypeCooperativeMatrixKHR references undefined scope <id> ")
1417 return emitError(unknownLoc,
"OpTypeCooperativeMatrixKHR `Rows` references "
1418 "undefined constant <id> ")
1422 return emitError(unknownLoc,
"OpTypeCooperativeMatrixKHR `Columns` "
1423 "references undefined constant <id> ")
1427 return emitError(unknownLoc,
"OpTypeCooperativeMatrixKHR `Use` references "
1428 "undefined constant <id> ")
1431 unsigned rows = rowsAttr.getInt();
1432 unsigned columns = columnsAttr.getInt();
1434 std::optional<spirv::CooperativeMatrixUseKHR> use =
1435 spirv::symbolizeCooperativeMatrixUseKHR(useAttr.getInt());
1439 "OpTypeCooperativeMatrixKHR references undefined use <id> ")
1443 typeMap[operands[0]] =
1450 if (operands.size() != 2) {
1451 return emitError(unknownLoc,
"OpTypeRuntimeArray must have two operands");
1456 "OpTypeRuntimeArray references undefined <id> ")
1460 memberType, typeDecorations.lookup(operands[0]));
1468 if (operands.empty()) {
1469 return emitError(unknownLoc,
"OpTypeStruct must have at least result <id>");
1472 if (operands.size() == 1) {
1474 typeMap[operands[0]] =
1483 for (
auto op : llvm::drop_begin(operands, 1)) {
1485 bool typeForwardPtr = (typeForwardPointerIDs.count(op) != 0);
1487 if (!memberType && !typeForwardPtr)
1488 return emitError(unknownLoc,
"OpTypeStruct references undefined <id> ")
1492 unresolvedMemberTypes.emplace_back(op, memberTypes.size());
1494 memberTypes.push_back(memberType);
1499 if (memberDecorationMap.count(operands[0])) {
1500 auto &allMemberDecorations = memberDecorationMap[operands[0]];
1501 for (
auto memberIndex : llvm::seq<uint32_t>(0, memberTypes.size())) {
1502 if (allMemberDecorations.count(memberIndex)) {
1503 for (
auto &memberDecoration : allMemberDecorations[memberIndex]) {
1505 if (memberDecoration.first == spirv::Decoration::Offset) {
1507 if (offsetInfo.empty()) {
1508 offsetInfo.resize(memberTypes.size());
1510 offsetInfo[memberIndex] = memberDecoration.second[0];
1512 auto intType = mlir::IntegerType::get(context, 32);
1513 if (!memberDecoration.second.empty()) {
1514 memberDecorationsInfo.emplace_back(
1515 memberIndex, memberDecoration.first,
1516 IntegerAttr::get(intType, memberDecoration.second[0]));
1518 memberDecorationsInfo.emplace_back(
1519 memberIndex, memberDecoration.first, UnitAttr::get(context));
1528 if (decorations.count(operands[0])) {
1531 std::optional<spirv::Decoration> decoration = spirv::symbolizeDecoration(
1532 llvm::convertToCamelFromSnakeCase(decorationAttr.getName(),
true));
1533 assert(decoration.has_value());
1534 structDecorationsInfo.emplace_back(decoration.value(),
1535 decorationAttr.getValue());
1539 uint32_t structID = operands[0];
1540 std::string structIdentifier = nameMap.lookup(structID).str();
1542 if (structIdentifier.empty()) {
1543 assert(unresolvedMemberTypes.empty() &&
1544 "didn't expect unresolved member types");
1546 memberTypes, offsetInfo, memberDecorationsInfo, structDecorationsInfo);
1549 typeMap[structID] = structTy;
1551 if (!unresolvedMemberTypes.empty())
1552 deferredStructTypesInfos.push_back(
1553 {structTy, std::move(unresolvedMemberTypes), std::move(memberTypes),
1554 std::move(offsetInfo), std::move(memberDecorationsInfo),
1555 std::move(structDecorationsInfo)});
1556 else if (failed(structTy.trySetBody(memberTypes, offsetInfo,
1557 memberDecorationsInfo,
1558 structDecorationsInfo)))
1569 if (operands.size() != 3) {
1571 return emitError(unknownLoc,
"OpTypeMatrix must have 3 operands"
1572 " (result_id, column_type, and column_count)");
1578 "OpTypeMatrix references undefined column type.")
1582 uint32_t colsCount = operands[2];
1589 unsigned size = operands.size();
1590 if (size < 2 || size > 4)
1591 return emitError(unknownLoc,
"OpTypeTensorARM must have 2-4 operands "
1592 "(result_id, element_type, (rank), (shape)) ")
1598 "OpTypeTensorARM references undefined element type ")
1608 return emitError(unknownLoc,
"OpTypeTensorARM rank must come from a "
1609 "scalar integer constant instruction");
1610 unsigned rank = rankAttr.getValue().getZExtValue();
1617 std::optional<std::pair<Attribute, Type>> shapeInfo =
1620 return emitError(unknownLoc,
"OpTypeTensorARM shape must come from a "
1621 "constant instruction of type OpTypeArray");
1623 ArrayAttr shapeArrayAttr = dyn_cast<ArrayAttr>(shapeInfo->first);
1625 for (
auto dimAttr : shapeArrayAttr.getValue()) {
1626 auto dimIntAttr = dyn_cast<IntegerAttr>(dimAttr);
1628 return emitError(unknownLoc,
"OpTypeTensorARM shape has an invalid "
1630 shape.push_back(dimIntAttr.getValue().getSExtValue());
1638 unsigned size = operands.size();
1640 return emitError(unknownLoc,
"OpTypeGraphARM must have at least 2 operands "
1641 "(result_id, num_inputs, (inout0_type, "
1642 "inout1_type, ...))")
1645 uint32_t numInputs = operands[1];
1648 for (
unsigned i = 2; i < size; ++i) {
1652 "OpTypeGraphARM references undefined element type.")
1655 if (i - 2 >= numInputs) {
1656 returnTypes.push_back(inOutTy);
1658 argTypes.push_back(inOutTy);
1661 typeMap[operands[0]] = GraphType::get(context, argTypes, returnTypes);
1667 if (operands.size() != 2)
1669 "OpTypeForwardPointer instruction must have two operands");
1671 typeForwardPointerIDs.insert(operands[0]);
1681 if (operands.size() != 8)
1684 "OpTypeImage with non-eight operands are not supported yet");
1688 return emitError(unknownLoc,
"OpTypeImage references undefined <id>: ")
1691 auto dim = spirv::symbolizeDim(operands[2]);
1693 return emitError(unknownLoc,
"unknown Dim for OpTypeImage: ")
1696 auto depthInfo = spirv::symbolizeImageDepthInfo(operands[3]);
1698 return emitError(unknownLoc,
"unknown Depth for OpTypeImage: ")
1701 auto arrayedInfo = spirv::symbolizeImageArrayedInfo(operands[4]);
1703 return emitError(unknownLoc,
"unknown Arrayed for OpTypeImage: ")
1706 auto samplingInfo = spirv::symbolizeImageSamplingInfo(operands[5]);
1708 return emitError(unknownLoc,
"unknown MS for OpTypeImage: ") << operands[5];
1710 auto samplerUseInfo = spirv::symbolizeImageSamplerUseInfo(operands[6]);
1711 if (!samplerUseInfo)
1712 return emitError(unknownLoc,
"unknown Sampled for OpTypeImage: ")
1715 auto format = spirv::symbolizeImageFormat(operands[7]);
1717 return emitError(unknownLoc,
"unknown Format for OpTypeImage: ")
1721 elementTy, dim.value(), depthInfo.value(), arrayedInfo.value(),
1722 samplingInfo.value(), samplerUseInfo.value(), format.value());
1728 if (operands.size() != 2)
1729 return emitError(unknownLoc,
"OpTypeSampledImage must have two operands");
1734 "OpTypeSampledImage references undefined <id>: ")
1743 if (operands.size() != 1)
1744 return emitError(unknownLoc,
"OpTypeSampler must have no parameters");
1752 if (operands.size() != 1)
1753 return emitError(unknownLoc,
"OpTypeNamedBarrier must have no parameters");
1765 StringRef opname = isSpec ?
"OpSpecConstant" :
"OpConstant";
1767 if (operands.size() < 2) {
1769 << opname <<
" must have type <id> and result <id>";
1771 if (operands.size() < 3) {
1773 << opname <<
" must have at least 1 more parameter";
1778 return emitError(unknownLoc,
"undefined result type from <id> ")
1782 auto checkOperandSizeForBitwidth = [&](
unsigned bitwidth) -> LogicalResult {
1783 if (bitwidth == 64) {
1784 if (operands.size() == 4) {
1788 << opname <<
" should have 2 parameters for 64-bit values";
1790 if (bitwidth <= 32) {
1791 if (operands.size() == 3) {
1797 <<
" should have 1 parameter for values with no more than 32 bits";
1799 return emitError(unknownLoc,
"unsupported OpConstant bitwidth: ")
1803 auto resultID = operands[1];
1805 if (
auto intType = dyn_cast<IntegerType>(resultType)) {
1806 auto bitwidth = intType.getWidth();
1807 if (failed(checkOperandSizeForBitwidth(bitwidth))) {
1812 if (bitwidth == 64) {
1819 } words = {operands[2], operands[3]};
1820 value = APInt(64, llvm::bit_cast<uint64_t>(words),
true);
1821 }
else if (bitwidth <= 32) {
1822 value = APInt(bitwidth, operands[2],
true,
1826 auto attr = opBuilder.getIntegerAttr(intType, value);
1833 constantMap.try_emplace(resultID, attr, intType);
1839 if (
auto floatType = dyn_cast<FloatType>(resultType)) {
1840 auto bitwidth = floatType.getWidth();
1841 if (failed(checkOperandSizeForBitwidth(bitwidth))) {
1846 if (floatType.isF64()) {
1853 } words = {operands[2], operands[3]};
1854 value = APFloat(llvm::bit_cast<double>(words));
1855 }
else if (floatType.isF32()) {
1856 value = APFloat(llvm::bit_cast<float>(operands[2]));
1857 }
else if (floatType.isF16()) {
1858 APInt data(16, operands[2]);
1859 value = APFloat(APFloat::IEEEhalf(), data);
1860 }
else if (floatType.isBF16()) {
1861 APInt data(16, operands[2]);
1862 value = APFloat(APFloat::BFloat(), data);
1863 }
else if (floatType.isF8E4M3FN()) {
1864 APInt data(8, operands[2]);
1865 value = APFloat(APFloat::Float8E4M3FN(), data);
1866 }
else if (floatType.isF8E5M2()) {
1867 APInt data(8, operands[2]);
1868 value = APFloat(APFloat::Float8E5M2(), data);
1871 auto attr = opBuilder.getFloatAttr(floatType, value);
1877 constantMap.try_emplace(resultID, attr, floatType);
1883 return emitError(unknownLoc,
"OpConstant can only generate values of "
1884 "scalar integer or floating-point type");
1889 if (operands.size() != 2) {
1891 << (isSpec ?
"Spec" :
"") <<
"Constant"
1892 << (isTrue ?
"True" :
"False")
1893 <<
" must have type <id> and result <id>";
1896 auto attr = opBuilder.getBoolAttr(isTrue);
1897 auto resultID = operands[1];
1903 constantMap.try_emplace(resultID, attr, opBuilder.getI1Type());
1911 if (operands.size() < 2) {
1913 "OpConstantComposite must have type <id> and result <id>");
1915 if (operands.size() < 3) {
1917 "OpConstantComposite must have at least 1 parameter");
1922 return emitError(unknownLoc,
"undefined result type from <id> ")
1927 elements.reserve(operands.size() - 2);
1928 for (
unsigned i = 2, e = operands.size(); i < e; ++i) {
1931 return emitError(unknownLoc,
"OpConstantComposite component <id> ")
1932 << operands[i] <<
" must come from a normal constant";
1934 elements.push_back(elementInfo->first);
1937 auto resultID = operands[1];
1938 if (
auto tensorType = dyn_cast<TensorArmType>(resultType)) {
1941 if (
auto denseElemAttr = dyn_cast<DenseElementsAttr>(element)) {
1942 for (
auto value : denseElemAttr.getValues<
Attribute>())
1943 flattenedElems.push_back(value);
1945 flattenedElems.push_back(element);
1949 constantMap.try_emplace(resultID, attr, tensorType);
1950 }
else if (
auto shapedType = dyn_cast<ShapedType>(resultType)) {
1954 constantMap.try_emplace(resultID, attr, shapedType);
1955 }
else if (isa<spirv::ArrayType, spirv::StructType>(resultType)) {
1956 auto attr = opBuilder.getArrayAttr(elements);
1957 constantMap.try_emplace(resultID, attr, resultType);
1959 return emitError(unknownLoc,
"unsupported OpConstantComposite type: ")
1968 if (operands.size() != 3) {
1971 "OpConstantCompositeReplicateEXT expects 3 operands but found ")
1977 return emitError(unknownLoc,
"undefined result type from <id> ")
1981 auto compositeType = dyn_cast<CompositeType>(resultType);
1982 if (!compositeType) {
1984 "result type from <id> is not a composite type")
1988 uint32_t resultID = operands[1];
1989 uint32_t constantID = operands[2];
1991 std::optional<std::pair<Attribute, Type>> replicatedConstantCompositeInfo =
1993 if (replicatedConstantCompositeInfo.has_value()) {
1994 constantCompositeReplicateMap.try_emplace(
1995 resultID, replicatedConstantCompositeInfo.value().first, resultType);
1999 std::optional<std::pair<Attribute, Type>> constantInfo =
2001 if (constantInfo.has_value()) {
2002 constantCompositeReplicateMap.try_emplace(
2003 resultID, constantInfo.value().first, resultType);
2007 return emitError(unknownLoc,
"OpConstantCompositeReplicateEXT operand <id> ")
2009 <<
" must come from a normal constant or a "
2010 "OpConstantCompositeReplicateEXT";
2015 if (operands.size() < 2) {
2018 "OpSpecConstantComposite must have type <id> and result <id>");
2020 if (operands.size() < 3) {
2022 "OpSpecConstantComposite must have at least 1 parameter");
2027 return emitError(unknownLoc,
"undefined result type from <id> ")
2031 auto resultID = operands[1];
2035 elements.reserve(operands.size() - 2);
2036 for (
unsigned i = 2, e = operands.size(); i < e; ++i) {
2038 elements.push_back(SymbolRefAttr::get(elementInfo));
2041 auto op = spirv::SpecConstantCompositeOp::create(
2042 opBuilder, unknownLoc, TypeAttr::get(resultType), symName,
2043 opBuilder.getArrayAttr(elements),
nullptr);
2044 specConstCompositeMap[resultID] = op;
2051 if (operands.size() != 3) {
2052 return emitError(unknownLoc,
"OpSpecConstantCompositeReplicateEXT expects "
2053 "3 operands but found ")
2059 return emitError(unknownLoc,
"undefined result type from <id> ")
2063 auto compositeType = dyn_cast<CompositeType>(resultType);
2064 if (!compositeType) {
2066 "result type from <id> is not a composite type")
2070 uint32_t resultID = operands[1];
2073 spirv::SpecConstantOp constituentSpecConstantOp =
2075 auto op = spirv::EXTSpecConstantCompositeReplicateOp::create(
2076 opBuilder, unknownLoc, TypeAttr::get(resultType), symName,
2077 SymbolRefAttr::get(constituentSpecConstantOp),
2080 specConstCompositeReplicateMap[resultID] = op;
2087 if (operands.size() < 3)
2088 return emitError(unknownLoc,
"OpConstantOperation must have type <id>, "
2089 "result <id>, and operand opcode");
2091 uint32_t resultTypeID = operands[0];
2094 return emitError(unknownLoc,
"undefined result type from <id> ")
2097 uint32_t resultID = operands[1];
2098 spirv::Opcode enclosedOpcode =
static_cast<spirv::Opcode
>(operands[2]);
2099 auto emplaceResult = specConstOperationMap.try_emplace(
2102 enclosedOpcode, resultTypeID,
2105 if (!emplaceResult.second)
2106 return emitError(unknownLoc,
"value with <id>: ")
2107 << resultID <<
" is probably defined before.";
2113 uint32_t resultID, spirv::Opcode enclosedOpcode, uint32_t resultTypeID,
2129 llvm::SaveAndRestore valueMapGuard(valueMap, newValueMap);
2130 constexpr uint32_t fakeID =
static_cast<uint32_t
>(-3);
2133 enclosedOpResultTypeAndOperands.push_back(resultTypeID);
2134 enclosedOpResultTypeAndOperands.push_back(fakeID);
2135 enclosedOpResultTypeAndOperands.append(enclosedOpOperands.begin(),
2136 enclosedOpOperands.end());
2151 auto specConstOperationOp =
2152 spirv::SpecConstantOperationOp::create(opBuilder, loc, resultType);
2154 Region &body = specConstOperationOp.getBody();
2156 body.
getBlocks().splice(body.
end(), curBlock->getParent()->getBlocks(),
2163 opBuilder.setInsertionPointToEnd(&block);
2165 spirv::YieldOp::create(opBuilder, loc, block.
front().
getResult(0));
2166 return specConstOperationOp.getResult();
2171 if (operands.size() != 2) {
2173 "OpConstantNull must only have type <id> and result <id>");
2178 return emitError(unknownLoc,
"undefined result type from <id> ")
2182 auto resultID = operands[1];
2184 if (resultType.
isIntOrFloat() || isa<VectorType>(resultType)) {
2185 attr = opBuilder.getZeroAttr(resultType);
2186 }
else if (
auto tensorType = dyn_cast<TensorArmType>(resultType)) {
2187 if (
auto element = opBuilder.getZeroAttr(tensorType.getElementType()))
2194 constantMap.try_emplace(resultID, attr, resultType);
2198 return emitError(unknownLoc,
"unsupported OpConstantNull type: ")
2204 if (operands.size() < 3) {
2206 <<
"OpGraphConstantARM must have at least 2 operands";
2211 return emitError(unknownLoc,
"undefined result type from <id> ")
2215 uint32_t resultID = operands[1];
2217 if (!dyn_cast<spirv::TensorArmType>(resultType)) {
2218 return emitError(unknownLoc,
"result must be of type OpTypeTensorARM");
2221 APInt graph_constant_id = APInt(32, operands[2],
true);
2222 Type i32Ty = opBuilder.getIntegerType(32);
2223 IntegerAttr attr = opBuilder.getIntegerAttr(i32Ty, graph_constant_id);
2224 graphConstantMap.try_emplace(
2236 LLVM_DEBUG(logger.startLine() <<
"[block] got exiting block for id = " <<
id
2237 <<
" @ " << block <<
"\n");
2244 auto *block = curFunction->addBlock();
2245 LLVM_DEBUG(logger.startLine() <<
"[block] created block for id = " <<
id
2246 <<
" @ " << block <<
"\n");
2247 return blockMap[id] = block;
2252 return emitError(unknownLoc,
"OpBranch must appear inside a block");
2255 if (operands.size() != 1) {
2256 return emitError(unknownLoc,
"OpBranch must take exactly one target label");
2264 spirv::BranchOp::create(opBuilder, loc,
target);
2274 "OpBranchConditional must appear inside a block");
2277 if (operands.size() != 3 && operands.size() != 5) {
2279 "OpBranchConditional must have condition, true label, "
2280 "false label, and optionally two branch weights");
2283 auto condition =
getValue(operands[0]);
2287 std::optional<std::pair<uint32_t, uint32_t>> weights;
2288 if (operands.size() == 5) {
2289 weights = std::make_pair(operands[3], operands[4]);
2295 spirv::BranchConditionalOp::create(
2296 opBuilder, loc, condition, trueBlock,
2306 return emitError(unknownLoc,
"OpLabel must appear inside a function");
2309 if (operands.size() != 1) {
2310 return emitError(unknownLoc,
"OpLabel should only have result <id>");
2313 auto labelID = operands[0];
2316 LLVM_DEBUG(logger.startLine()
2317 <<
"[block] populating block " << block <<
"\n");
2319 assert(block->empty() &&
"re-deserialize the same block!");
2321 opBuilder.setInsertionPointToStart(block);
2322 blockMap[labelID] = curBlock = block;
2329 return emitError(unknownLoc,
"a graph block must appear inside a graph");
2334 LLVM_DEBUG(logger.startLine()
2335 <<
"[block] populating block " << block <<
"\n");
2337 assert(block->
empty() &&
"re-deserialize the same block!");
2339 opBuilder.setInsertionPointToStart(block);
2340 blockMap[graphID] = curBlock = block;
2348 return emitError(unknownLoc,
"OpSelectionMerge must appear in a block");
2351 if (operands.size() < 2) {
2354 "OpSelectionMerge must specify merge target and selection control");
2359 auto selectionControl = operands[1];
2361 if (!blockMergeInfo.try_emplace(curBlock, loc, selectionControl, mergeBlock)
2365 "a block cannot have more than one OpSelectionMerge instruction");
2374 return emitError(unknownLoc,
"OpLoopMerge must appear in a block");
2377 if (operands.size() < 3) {
2378 return emitError(unknownLoc,
"OpLoopMerge must specify merge target, "
2379 "continue target and loop control");
2385 uint32_t loopControl = operands[2];
2388 .try_emplace(curBlock, loc, loopControl, mergeBlock, continueBlock)
2392 "a block cannot have more than one OpLoopMerge instruction");
2400 return emitError(unknownLoc,
"OpPhi must appear in a block");
2403 if (operands.size() < 4) {
2404 return emitError(unknownLoc,
"OpPhi must specify result type, result <id>, "
2405 "and variable-parent pairs");
2410 BlockArgument blockArg = curBlock->addArgument(blockArgType, unknownLoc);
2411 valueMap[operands[1]] = blockArg;
2412 LLVM_DEBUG(logger.startLine()
2413 <<
"[phi] created block argument " << blockArg
2414 <<
" id = " << operands[1] <<
" of type " << blockArgType <<
"\n");
2418 for (
unsigned i = 2, e = operands.size(); i < e; i += 2) {
2419 uint32_t value = operands[i];
2421 std::pair<Block *, Block *> predecessorTargetPair{predecessor, curBlock};
2422 blockPhiInfo[predecessorTargetPair].push_back(value);
2423 LLVM_DEBUG(logger.startLine() <<
"[phi] predecessor @ " << predecessor
2424 <<
" with arg id = " << value <<
"\n");
2432 return emitError(unknownLoc,
"OpSwitch must appear in a block");
2434 if (operands.size() < 2)
2435 return emitError(unknownLoc,
"OpSwitch must at least specify selector and "
2436 "a default target");
2440 return emitError(unknownLoc,
"unknown OpSwitch selector <id>: ")
2442 auto selectorType = dyn_cast<IntegerType>(selector.
getType());
2444 return emitError(unknownLoc,
"OpSwitch selector must be an integer");
2448 unsigned bitWidth = selectorType.getWidth();
2449 unsigned literalWords = llvm::divideCeil(bitWidth, 32);
2450 unsigned wordsPerCase = literalWords + 1;
2451 if ((operands.size() - 2) % wordsPerCase != 0)
2452 return emitError(unknownLoc,
"OpSwitch must specify selector, default "
2453 "target and any number of literal and label "
2454 "<id> pairs, where each literal of a ")
2455 << bitWidth <<
"-bit selector spans " << literalWords <<
" word(s)";
2462 for (
unsigned i = 2, e = operands.size(); i < e; i += wordsPerCase) {
2464 if (bitWidth <= 32) {
2468 literal = APInt(bitWidth, operands[i],
true,
2471 literal = APInt(bitWidth, 0);
2472 for (
unsigned w = 0; w < literalWords; ++w)
2473 literal.insertBits(APInt(32, operands[i + w]), w * 32);
2475 literals.push_back(literal);
2480 spirv::SwitchOp::create(opBuilder, loc, selector, defaultBlock,
2490class ControlFlowStructurizer {
2493 ControlFlowStructurizer(
Location loc, uint32_t control,
2496 llvm::ScopedPrinter &logger)
2497 : location(loc), control(control), blockMergeInfo(mergeInfo),
2498 headerBlock(header), mergeBlock(merge), continueBlock(cont),
2501 ControlFlowStructurizer(
Location loc, uint32_t control,
2504 : location(loc), control(control), blockMergeInfo(mergeInfo),
2505 headerBlock(header), mergeBlock(merge), continueBlock(cont) {}
2515 LogicalResult structurize();
2520 spirv::SelectionOp createSelectionOp(uint32_t selectionControl);
2523 spirv::LoopOp createLoopOp(uint32_t loopControl);
2526 void collectBlocksInConstruct();
2535 Block *continueBlock;
2541 llvm::ScopedPrinter &logger;
2547ControlFlowStructurizer::createSelectionOp(uint32_t selectionControl) {
2550 OpBuilder builder(&mergeBlock->front());
2552 auto control =
static_cast<spirv::SelectionControl
>(selectionControl);
2553 auto selectionOp = spirv::SelectionOp::create(builder, location, control);
2554 selectionOp.addMergeBlock(builder);
2559spirv::LoopOp ControlFlowStructurizer::createLoopOp(uint32_t loopControl) {
2562 OpBuilder builder(&mergeBlock->front());
2564 auto control =
static_cast<spirv::LoopControl
>(loopControl);
2565 auto loopOp = spirv::LoopOp::create(builder, location, control);
2566 loopOp.addEntryAndMergeBlock(builder);
2571void ControlFlowStructurizer::collectBlocksInConstruct() {
2572 assert(constructBlocks.empty() &&
"expected empty constructBlocks");
2575 constructBlocks.insert(headerBlock);
2579 for (
unsigned i = 0; i < constructBlocks.size(); ++i) {
2580 for (
auto *successor : constructBlocks[i]->getSuccessors())
2581 if (successor != mergeBlock)
2582 constructBlocks.insert(successor);
2586LogicalResult ControlFlowStructurizer::structurize() {
2587 Operation *op =
nullptr;
2588 bool isLoop = continueBlock !=
nullptr;
2590 if (
auto loopOp = createLoopOp(control))
2591 op = loopOp.getOperation();
2593 if (
auto selectionOp = createSelectionOp(control))
2594 op = selectionOp.getOperation();
2603 mapper.
map(mergeBlock, &body.
back());
2605 collectBlocksInConstruct();
2626 OpBuilder builder(body);
2627 for (
auto *block : constructBlocks) {
2630 auto *newBlock = builder.createBlock(&body.
back());
2631 mapper.
map(block, newBlock);
2632 LLVM_DEBUG(logger.startLine() <<
"[cf] cloned block " << newBlock
2633 <<
" from block " << block <<
"\n");
2635 for (BlockArgument blockArg : block->getArguments()) {
2637 newBlock->addArgument(blockArg.getType(), blockArg.getLoc());
2638 mapper.
map(blockArg, newArg);
2639 LLVM_DEBUG(logger.startLine() <<
"[cf] remapped block argument "
2640 << blockArg <<
" to " << newArg <<
"\n");
2643 LLVM_DEBUG(logger.startLine()
2644 <<
"[cf] block " << block <<
" is a function entry block\n");
2647 for (
auto &op : *block)
2648 newBlock->push_back(op.
clone(mapper));
2652 auto remapOperands = [&](Operation *op) {
2654 if (Value mappedOp = mapper.
lookupOrNull(operand.get()))
2655 operand.set(mappedOp);
2658 succOp.set(mappedOp);
2660 for (
auto &block : body)
2661 block.walk(remapOperands);
2669 headerBlock->replaceAllUsesWith(mergeBlock);
2672 logger.startLine() <<
"[cf] after cloning and fixing references:\n";
2673 headerBlock->getParentOp()->print(logger.getOStream());
2674 logger.startLine() <<
"\n";
2678 if (!mergeBlock->args_empty()) {
2679 return mergeBlock->getParentOp()->emitError(
2680 "OpPhi in loop merge block unsupported");
2686 for (BlockArgument blockArg : headerBlock->getArguments())
2687 mergeBlock->addArgument(blockArg.getType(), blockArg.getLoc());
2691 SmallVector<Value, 4> blockArgs;
2692 if (!headerBlock->args_empty())
2693 blockArgs = {mergeBlock->args_begin(), mergeBlock->args_end()};
2697 builder.setInsertionPointToEnd(&body.front());
2698 spirv::BranchOp::create(builder, location, mapper.
lookupOrNull(headerBlock),
2699 ArrayRef<Value>(blockArgs));
2704 SmallVector<Value> valuesToYield;
2707 SmallVector<Value> outsideUses;
2721 for (BlockArgument blockArg : mergeBlock->getArguments()) {
2726 body.back().addArgument(blockArg.getType(), blockArg.getLoc());
2727 valuesToYield.push_back(body.back().getArguments().back());
2728 outsideUses.push_back(blockArg);
2733 LLVM_DEBUG(logger.startLine() <<
"[cf] cleaning up blocks after clone\n");
2736 for (
auto *block : constructBlocks)
2737 block->dropAllReferences();
2742 for (
Block *block : constructBlocks) {
2743 for (Operation &op : *block) {
2747 outsideUses.push_back(
result);
2750 for (BlockArgument &arg : block->getArguments()) {
2751 if (!arg.use_empty()) {
2753 outsideUses.push_back(arg);
2758 assert(valuesToYield.size() == outsideUses.size());
2762 if (!valuesToYield.empty()) {
2763 LLVM_DEBUG(logger.startLine()
2764 <<
"[cf] yielding values from the selection / loop region\n");
2767 auto mergeOps = body.back().getOps<spirv::MergeOp>();
2768 Operation *merge = llvm::getSingleElement(mergeOps);
2770 merge->setOperands(valuesToYield);
2778 builder.setInsertionPoint(&mergeBlock->front());
2780 Operation *newOp =
nullptr;
2783 newOp = spirv::LoopOp::create(builder, location,
2785 static_cast<spirv::LoopControl
>(control));
2787 newOp = spirv::SelectionOp::create(
2789 static_cast<spirv::SelectionControl
>(control));
2799 for (
unsigned i = 0, e = outsideUses.size(); i != e; ++i)
2800 outsideUses[i].replaceAllUsesWith(op->
getResult(i));
2806 mergeBlock->eraseArguments(0, mergeBlock->getNumArguments());
2813 for (
auto *block : constructBlocks) {
2814 if (!block->use_empty())
2815 return emitError(block->getParent()->getLoc(),
2816 "failed control flow structurization: "
2817 "block has uses outside of the "
2818 "enclosing selection/loop construct");
2819 for (Operation &op : *block)
2821 return op.
emitOpError(
"failed control flow structurization: value has "
2822 "uses outside of the "
2823 "enclosing selection/loop construct");
2824 for (BlockArgument &arg : block->getArguments())
2825 if (!arg.use_empty())
2826 return emitError(arg.getLoc(),
"failed control flow structurization: "
2827 "block argument has uses outside of the "
2828 "enclosing selection/loop construct");
2832 for (
auto *block : constructBlocks) {
2872 auto updateMergeInfo = [&](
Block *block) -> WalkResult {
2873 auto it = blockMergeInfo.find(block);
2874 if (it != blockMergeInfo.end()) {
2876 Location loc = it->second.loc;
2878 uint32_t nestedControl = it->second.control;
2882 return emitError(loc,
"failed control flow structurization: nested "
2883 "loop header block should be remapped!");
2885 Block *newContinue = it->second.continueBlock;
2889 return emitError(loc,
"failed control flow structurization: nested "
2890 "loop continue block should be remapped!");
2893 Block *newMerge = it->second.mergeBlock;
2895 newMerge = mappedTo;
2898 blockMergeInfo.
erase(it);
2899 blockMergeInfo.try_emplace(newHeader, loc, nestedControl, newMerge,
2906 if (block->walk(updateMergeInfo).wasInterrupted())
2914 LLVM_DEBUG(logger.startLine() <<
"[cf] changing entry block " << block
2915 <<
" to only contain a spirv.Branch op\n");
2919 builder.setInsertionPointToEnd(block);
2920 spirv::BranchOp::create(builder, location, mergeBlock);
2922 LLVM_DEBUG(logger.startLine() <<
"[cf] erasing block " << block <<
"\n");
2927 LLVM_DEBUG(logger.startLine()
2928 <<
"[cf] after structurizing construct with header block "
2929 << headerBlock <<
":\n"
2938 <<
"//----- [phi] start wiring up block arguments -----//\n";
2944 for (
const auto &info : blockPhiInfo) {
2945 Block *block = info.first.first;
2949 logger.startLine() <<
"[phi] block " << block <<
"\n";
2950 logger.startLine() <<
"[phi] before creating block argument:\n";
2952 logger.startLine() <<
"\n";
2958 opBuilder.setInsertionPoint(op);
2961 blockArgs.reserve(phiInfo.size());
2962 for (uint32_t valueId : phiInfo) {
2964 blockArgs.push_back(value);
2965 LLVM_DEBUG(logger.startLine() <<
"[phi] block argument " << value
2966 <<
" id = " << valueId <<
"\n");
2968 return emitError(unknownLoc,
"OpPhi references undefined value!");
2972 if (
auto branchOp = dyn_cast<spirv::BranchOp>(op)) {
2974 spirv::BranchOp::create(opBuilder, branchOp.getLoc(),
2975 branchOp.getTarget(), blockArgs);
2977 }
else if (
auto branchCondOp = dyn_cast<spirv::BranchConditionalOp>(op)) {
2978 assert((branchCondOp.getTrueBlock() ==
target ||
2979 branchCondOp.getFalseBlock() ==
target) &&
2980 "expected target to be either the true or false target");
2981 if (
target == branchCondOp.getTrueTarget())
2982 spirv::BranchConditionalOp::create(
2983 opBuilder, branchCondOp.getLoc(), branchCondOp.getCondition(),
2984 blockArgs, branchCondOp.getFalseBlockArguments(),
2985 branchCondOp.getBranchWeightsAttr(), branchCondOp.getTrueTarget(),
2986 branchCondOp.getFalseTarget());
2988 spirv::BranchConditionalOp::create(
2989 opBuilder, branchCondOp.getLoc(), branchCondOp.getCondition(),
2990 branchCondOp.getTrueBlockArguments(), blockArgs,
2991 branchCondOp.getBranchWeightsAttr(), branchCondOp.getTrueBlock(),
2992 branchCondOp.getFalseBlock());
2994 branchCondOp.erase();
2995 }
else if (
auto switchOp = dyn_cast<spirv::SwitchOp>(op)) {
2996 if (
target == switchOp.getDefaultTarget()) {
3000 spirv::SwitchOp::create(
3001 opBuilder, switchOp.getLoc(), switchOp.getSelector(),
3002 switchOp.getDefaultTarget(), blockArgs, literals,
3003 switchOp.getTargets(), targetOperands);
3007 auto it = llvm::find(targets,
target);
3008 assert(it != targets.end());
3009 size_t index = std::distance(targets.begin(), it);
3010 switchOp.getTargetOperandsMutable(
index).assign(blockArgs);
3013 return emitError(unknownLoc,
"unimplemented terminator for Phi creation");
3017 logger.startLine() <<
"[phi] after creating block argument:\n";
3019 logger.startLine() <<
"\n";
3022 blockPhiInfo.clear();
3027 <<
"//--- [phi] completed wiring up block arguments ---//\n";
3035 for (
auto [block, mergeInfo] : blockMergeInfoCopy) {
3037 if (mergeInfo.continueBlock)
3040 if (!block->mightHaveTerminator())
3043 Operation *terminator = block->getTerminator();
3046 if (!isa<spirv::BranchConditionalOp, spirv::SwitchOp>(terminator))
3050 bool splitHeaderMergeBlock =
false;
3051 for (
const auto &[_, mergeInfo] : blockMergeInfo) {
3052 if (mergeInfo.mergeBlock == block)
3053 splitHeaderMergeBlock =
true;
3060 if (!llvm::hasSingleElement(*block) || splitHeaderMergeBlock ||
3064 spirv::BranchOp::create(builder, block->getParent()->getLoc(), newBlock);
3068 blockMergeInfo.erase(block);
3069 blockMergeInfo.try_emplace(newBlock, mergeInfo);
3077 if (!options.enableControlFlowStructurization) {
3081 <<
"//----- [cf] skip structurizing control flow -----//\n";
3089 <<
"//----- [cf] start structurizing control flow -----//\n";
3094 logger.startLine() <<
"[cf] split conditional blocks\n";
3095 logger.startLine() <<
"\n";
3102 while (!blockMergeInfo.empty()) {
3103 Block *headerBlock = blockMergeInfo.
begin()->first;
3107 logger.startLine() <<
"[cf] header block " << headerBlock <<
":\n";
3108 headerBlock->
print(logger.getOStream());
3109 logger.startLine() <<
"\n";
3113 assert(mergeBlock &&
"merge block cannot be nullptr");
3115 return emitError(unknownLoc,
"OpPhi in loop merge block unimplemented");
3117 logger.startLine() <<
"[cf] merge block " << mergeBlock <<
":\n";
3118 mergeBlock->print(logger.getOStream());
3119 logger.startLine() <<
"\n";
3123 LLVM_DEBUG(
if (continueBlock) {
3124 logger.startLine() <<
"[cf] continue block " << continueBlock <<
":\n";
3125 continueBlock->print(logger.getOStream());
3126 logger.startLine() <<
"\n";
3130 blockMergeInfo.
erase(blockMergeInfo.begin());
3131 ControlFlowStructurizer structurizer(mergeInfo.
loc, mergeInfo.
control,
3132 blockMergeInfo, headerBlock,
3133 mergeBlock, continueBlock
3139 if (failed(structurizer.structurize()))
3146 <<
"//--- [cf] completed structurizing control flow ---//\n";
3159 auto fileName = debugInfoMap.lookup(debugLine->fileID).str();
3160 if (fileName.empty())
3161 fileName =
"<unknown>";
3173 if (operands.size() != 3)
3174 return emitError(unknownLoc,
"OpLine must have 3 operands");
3175 debugLine =
DebugLine{operands[0], operands[1], operands[2]};
3183 if (operands.size() < 2)
3184 return emitError(unknownLoc,
"OpString needs at least 2 operands");
3186 if (!debugInfoMap.lookup(operands[0]).empty())
3188 "duplicate debug string found for result <id> ")
3191 unsigned wordIndex = 1;
3193 if (wordIndex != operands.size())
3195 "unexpected trailing words in OpString instruction");
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 void setInherentOrDiscardableAttr(Operation *op, StringAttr name, Attribute value)
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.
This class represents an argument of a Block.
Block represents an ordered list of Operations.
void erase()
Unlink this Block from its parent region and delete it.
Block * splitBlock(iterator splitBefore)
Split the block into two blocks before the specified operation or iterator.
Operation * getTerminator()
Get the terminator operation of this block.
void print(raw_ostream &os)
bool isEntryBlock()
Return if this block is the entry block in the parent region.
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
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)
A symbol reference with a reference path containing a single element.
static FlatSymbolRefAttr get(StringAttr value)
Construct a symbol reference for the given value name.
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
auto lookupOrNull(T from) const
Lookup a mapped value within the map.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
NamedAttrList is array of NamedAttributes that tracks whether it is sorted and does some basic work t...
DictionaryAttr getDictionary(MLIRContext *context) const
Return a dictionary attribute for the underlying dictionary.
Attribute set(StringAttr name, Attribute value)
If the an attribute exists with the specified name, change it to the new value.
NamedAttribute represents a combination of a name and an Attribute value.
RAII guard to reset the insertion point of the builder when destroyed.
This class helps build Operations.
void setInherentAttr(Operation *op, StringAttr name, Attribute value) const
std::optional< Attribute > getInherentAttr(Operation *op, StringRef name) const
Lookup an inherent attribute by name, this method isn't recommended and may be removed in the future.
Operation is the basic unit of execution within MLIR.
MutableArrayRef< BlockOperand > getBlockOperands()
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
bool use_empty()
Returns true if this operation has no uses.
void setDiscardableAttr(StringAttr name, Attribute value)
Set a discardable attribute by name.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
MutableArrayRef< OpOperand > getOpOperands()
OperationName getName()
The name of an operation is the key identifier for it.
void print(raw_ostream &os, const OpPrintingFlags &flags={})
static Operation * create(Location location, OperationName name, TypeRange resultTypes, ValueRange operands, NamedAttrList &&attributes, PropertyRef properties, BlockRange successors, unsigned numRegions)
Create a new Operation with the specific fields.
result_range getResults()
Operation * clone(IRMapping &mapper, const CloneOptions &options=CloneOptions::all())
Create a deep copy of this operation, remapping any operands that use values outside of the operation...
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
void erase()
Remove this operation from its parent block and delete it.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
BlockListType & getBlocks()
BlockListType::iterator iterator
void takeBody(Region &other)
Takes body of another region (that region will have no body after this operation completes).
This class implements the successor iterators for Block.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
static WalkResult advance()
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 processSamplerType(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>.
LogicalResult processNamedBarrierType(ArrayRef< uint32_t > operands)
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)
static MatrixType get(Type columnType, uint32_t columnCount)
static NamedBarrierType get(MLIRContext *context)
static PointerType get(Type pointeeType, StorageClass storageClass)
static RuntimeArrayType get(Type elementType)
static SampledImageType get(Type imageType)
static SamplerType get(MLIRContext *context)
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)
The OpAsmOpInterface, see OpAsmInterface.td for more details.
SmallVector< Operation * > mergeOps
Computation function returning, for the op currently being tiled or fused, the per-iteration-domain-d...
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 getFuncParamAttrName()
Returns the attribute name for specifying function parameter and result attributes.
StringRef getFuncParamAlignmentAttrName()
Returns the attribute name for specifying function parameter alignment.
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.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
llvm::SetVector< T, Vector, Set, N > SetVector
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
std::string debugString(T &&op)
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.