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 moduleOp(createModuleOp()), opBuilder(moduleOp->getRegion()),
76LogicalResult spirv::Deserializer::deserialize() {
80 <<
"//+++---------- start deserialization ----------+++//\n";
83 if (
failed(processHeader()))
86 spirv::Opcode opcode = spirv::Opcode::OpNop;
87 ArrayRef<uint32_t> operands;
88 auto binarySize = binary.size();
89 while (curOffset < binarySize) {
99 assert(curOffset == binarySize &&
100 "deserializer should never index beyond the binary end");
102 for (
auto &deferred : deferredInstructions) {
108 if (
failed(resolveDeferredIdDecorations()))
111 if (!functionParameterAttrs.empty())
112 return emitError(unknownLoc,
"FuncParamAttr decoration on result <id> ")
113 << functionParameterAttrs.begin()->first
114 <<
" is not supported: expected OpFunctionParameter or OpFunction";
118 LLVM_DEBUG(logger.startLine()
119 <<
"//+++-------- completed deserialization --------+++//\n");
123OwningOpRef<spirv::ModuleOp> spirv::Deserializer::collect() {
124 return std::move(moduleOp);
131OwningOpRef<spirv::ModuleOp> spirv::Deserializer::createModuleOp() {
132 OpBuilder builder(context);
133 OperationState state(unknownLoc, spirv::ModuleOp::getOperationName());
134 spirv::ModuleOp::build(builder, state);
138LogicalResult spirv::Deserializer::processHeader() {
141 "SPIR-V binary module must have a 5-word header");
144 return emitError(unknownLoc,
"incorrect magic number");
147 uint32_t majorVersion = (binary[1] << 8) >> 24;
148 uint32_t minorVersion = (binary[1] << 16) >> 24;
149 if (majorVersion == 1) {
150 switch (minorVersion) {
151#define MIN_VERSION_CASE(v) \
153 version = spirv::Version::V_1_##v; \
163#undef MIN_VERSION_CASE
165 return emitError(unknownLoc,
"unsupported SPIR-V minor version: ")
169 return emitError(unknownLoc,
"unsupported SPIR-V major version: ")
179spirv::Deserializer::processCapability(ArrayRef<uint32_t> operands) {
180 if (operands.size() != 1)
181 return emitError(unknownLoc,
"OpCapability must have one parameter");
183 auto cap = spirv::symbolizeCapability(operands[0]);
185 return emitError(unknownLoc,
"unknown capability: ") << operands[0];
187 capabilities.insert(*cap);
191LogicalResult spirv::Deserializer::processExtension(ArrayRef<uint32_t> words) {
195 "OpExtension must have a literal string for the extension name");
198 unsigned wordIndex = 0;
200 if (wordIndex != words.size())
202 "unexpected trailing words in OpExtension instruction");
203 auto ext = spirv::symbolizeExtension(extName);
205 return emitError(unknownLoc,
"unknown extension: ") << extName;
207 extensions.insert(*ext);
212spirv::Deserializer::processExtInstImport(ArrayRef<uint32_t> words) {
213 if (words.size() < 2) {
215 "OpExtInstImport must have a result <id> and a literal "
216 "string for the extended instruction set name");
219 unsigned wordIndex = 1;
221 if (wordIndex != words.size()) {
223 "unexpected trailing words in OpExtInstImport");
228void spirv::Deserializer::attachVCETriple() {
230 version, capabilities.getArrayRef(), extensions.getArrayRef(), context));
234spirv::Deserializer::processMemoryModel(ArrayRef<uint32_t> operands) {
235 if (operands.size() != 2)
236 return emitError(unknownLoc,
"OpMemoryModel must have two operands");
238 moduleOp->setAddressingModel(
239 static_cast<spirv::AddressingModel
>(operands.front()));
241 moduleOp->setMemoryModel(
static_cast<spirv::MemoryModel
>(operands.back()));
246template <
typename AttrTy,
typename EnumAttrTy,
typename EnumTy>
250 StringAttr symbol, StringRef decorationName, StringRef cacheControlKind) {
251 if (words.size() != 4) {
252 return emitError(loc,
"OpDecorate with ")
253 << decorationName <<
" needs a cache control integer literal and a "
254 << cacheControlKind <<
" cache control literal";
256 unsigned cacheLevel = words[2];
257 auto cacheControlAttr =
static_cast<EnumTy
>(words[3]);
258 auto value = opBuilder.
getAttr<AttrTy>(cacheLevel, cacheControlAttr);
261 dyn_cast_or_null<ArrayAttr>(decorations[words[0]].
get(symbol)))
262 llvm::append_range(attrs, attrList);
263 attrs.push_back(value);
264 decorations[words[0]].set(symbol, opBuilder.
getArrayAttr(attrs));
268LogicalResult spirv::Deserializer::processDecoration(ArrayRef<uint32_t> words) {
272 if (words.size() < 2) {
274 unknownLoc,
"OpDecorate must have at least result <id> and Decoration");
276 auto decorationName =
277 stringifyDecoration(
static_cast<spirv::Decoration
>(words[1]));
278 if (decorationName.empty()) {
279 return emitError(unknownLoc,
"invalid Decoration code : ") << words[1];
281 auto symbol = getSymbolDecoration(decorationName);
282 switch (
static_cast<spirv::Decoration
>(words[1])) {
283 case spirv::Decoration::FPFastMathMode:
284 if (words.size() != 3) {
285 return emitError(unknownLoc,
"OpDecorate with ")
286 << decorationName <<
" needs a single integer literal";
288 decorations[words[0]].set(
289 symbol, FPFastMathModeAttr::get(opBuilder.getContext(),
290 static_cast<FPFastMathMode
>(words[2])));
292 case spirv::Decoration::FPRoundingMode:
293 if (words.size() != 3) {
294 return emitError(unknownLoc,
"OpDecorate with ")
295 << decorationName <<
" needs a single integer literal";
297 decorations[words[0]].set(
298 symbol, FPRoundingModeAttr::get(opBuilder.getContext(),
299 static_cast<FPRoundingMode
>(words[2])));
301 case spirv::Decoration::FuncParamAttr: {
302 if (words.size() != 3)
304 "OpDecorate with FuncParamAttr needs a single "
305 "function parameter attribute");
306 auto value = spirv::symbolizeFunctionParameterAttribute(words[2]);
308 return emitError(unknownLoc,
"invalid FunctionParameterAttribute code: ")
310 SmallVector<Attribute> attrs;
311 if (
auto previous = functionParameterAttrs.lookup(words[0]))
312 llvm::append_range(attrs, previous);
314 spirv::FunctionParameterAttributeAttr::get(context, *value));
315 functionParameterAttrs[words[0]] = opBuilder.getArrayAttr(attrs);
318 case spirv::Decoration::Alignment:
319 case spirv::Decoration::MaxByteOffset:
320 case spirv::Decoration::DescriptorSet:
321 case spirv::Decoration::Binding:
322 case spirv::Decoration::Location:
323 case spirv::Decoration::SpecId:
324 case spirv::Decoration::Index:
325 case spirv::Decoration::Offset:
326 case spirv::Decoration::XfbBuffer:
327 case spirv::Decoration::XfbStride:
328 if (words.size() != 3) {
329 return emitError(unknownLoc,
"OpDecorate with ")
330 << decorationName <<
" needs a single integer literal";
332 decorations[words[0]].set(
333 symbol, opBuilder.getI32IntegerAttr(
static_cast<int32_t
>(words[2])));
335 case spirv::Decoration::BuiltIn:
336 if (words.size() != 3) {
337 return emitError(unknownLoc,
"OpDecorate with ")
338 << decorationName <<
" needs a single integer literal";
340 decorations[words[0]].set(
341 symbol, opBuilder.getStringAttr(
342 stringifyBuiltIn(
static_cast<spirv::BuiltIn
>(words[2]))));
344 case spirv::Decoration::ArrayStride:
345 if (words.size() != 3) {
346 return emitError(unknownLoc,
"OpDecorate with ")
347 << decorationName <<
" needs a single integer literal";
349 typeDecorations[words[0]] = words[2];
351 case spirv::Decoration::LinkageAttributes: {
352 if (words.size() < 4) {
353 return emitError(unknownLoc,
"OpDecorate with ")
355 <<
" needs at least 1 string and 1 integer literal";
363 unsigned wordIndex = 2;
365 auto linkageTypeAttr = opBuilder.getAttr<::mlir::spirv::LinkageTypeAttr>(
366 static_cast<::mlir::spirv::LinkageType
>(words[wordIndex++]));
367 auto linkageAttr = opBuilder.getAttr<::mlir::spirv::LinkageAttributesAttr>(
368 StringAttr::get(context, linkageName), linkageTypeAttr);
369 decorations[words[0]].set(symbol, dyn_cast<Attribute>(linkageAttr));
372 case spirv::Decoration::Aliased:
373 case spirv::Decoration::AliasedPointer:
374 case spirv::Decoration::Block:
375 case spirv::Decoration::BufferBlock:
376 case spirv::Decoration::Centroid:
377 case spirv::Decoration::CPacked:
378 case spirv::Decoration::Flat:
379 case spirv::Decoration::NonReadable:
380 case spirv::Decoration::NonUniform:
381 case spirv::Decoration::NonWritable:
382 case spirv::Decoration::NoPerspective:
383 case spirv::Decoration::NoSignedWrap:
384 case spirv::Decoration::NoUnsignedWrap:
385 case spirv::Decoration::RelaxedPrecision:
386 case spirv::Decoration::Restrict:
387 case spirv::Decoration::RestrictPointer:
388 case spirv::Decoration::NoContraction:
389 case spirv::Decoration::Constant:
390 case spirv::Decoration::Invariant:
391 case spirv::Decoration::Patch:
392 case spirv::Decoration::Coherent:
393 case spirv::Decoration::Volatile:
394 case spirv::Decoration::SaturatedConversion:
395 if (words.size() != 2) {
396 return emitError(unknownLoc,
"OpDecorate with ")
397 << decorationName <<
" needs a single target <id>";
399 decorations[words[0]].set(symbol, opBuilder.getUnitAttr());
401 case spirv::Decoration::CacheControlLoadINTEL: {
403 CacheControlLoadINTELAttr, LoadCacheControlAttr, LoadCacheControl>(
404 unknownLoc, opBuilder, decorations, words, symbol, decorationName,
410 case spirv::Decoration::CacheControlStoreINTEL: {
412 CacheControlStoreINTELAttr, StoreCacheControlAttr, StoreCacheControl>(
413 unknownLoc, opBuilder, decorations, words, symbol, decorationName,
419 case spirv::Decoration::AlignmentId:
420 case spirv::Decoration::MaxByteOffsetId:
421 case spirv::Decoration::CounterBuffer:
422 if (words.size() != 3) {
423 return emitError(unknownLoc,
"OpDecorateId with ")
424 << decorationName <<
" needs a single <id> operand";
426 pendingIdDecorations.push_back({words[0],
427 static_cast<spirv::Decoration
>(words[1]),
428 words[2], unknownLoc});
431 return emitError(unknownLoc,
"unhandled Decoration : '") << decorationName;
436LogicalResult spirv::Deserializer::resolveDeferredIdDecorations() {
437 for (
const DeferredIdDecoration &entry : pendingIdDecorations) {
438 StringRef decorationName = stringifyDecoration(entry.decoration);
439 StringAttr symbol = getSymbolDecoration(decorationName);
443 StringRef operandSymName;
444 if (spirv::GlobalVariableOp varOp =
445 globalVariableMap.lookup(entry.operandID))
446 operandSymName = varOp.getSymName();
447 else if (spirv::SpecConstantOp specOp =
448 specConstMap.lookup(entry.operandID))
449 operandSymName = specOp.getSymName();
451 return emitError(entry.loc,
"OpDecorateId with ")
452 << decorationName <<
" references <id> " << entry.operandID
453 <<
" which is not a global variable or specialization constant";
460 Operation *targetOp =
nullptr;
461 if (spirv::GlobalVariableOp varOp =
462 globalVariableMap.lookup(entry.targetID))
464 else if (spirv::SpecConstantOp specOp = specConstMap.lookup(entry.targetID))
466 else if (spirv::FuncOp fnOp = funcMap.lookup(entry.targetID))
468 else if (Value v = valueMap.lookup(entry.targetID))
469 targetOp = v.getDefiningOp();
472 return emitError(entry.loc,
"OpDecorateId with ")
473 << decorationName <<
" references unknown target <id> "
482spirv::Deserializer::processMemberDecoration(ArrayRef<uint32_t> words) {
484 if (words.size() < 3) {
486 "OpMemberDecorate must have at least 3 operands");
489 auto decoration =
static_cast<spirv::Decoration
>(words[2]);
490 if (decoration == spirv::Decoration::Offset && words.size() != 4) {
492 " missing offset specification in OpMemberDecorate with "
493 "Offset decoration");
495 ArrayRef<uint32_t> decorationOperands;
496 if (words.size() > 3) {
497 decorationOperands = words.slice(3);
499 memberDecorationMap[words[0]][words[1]][decoration] = decorationOperands;
503LogicalResult spirv::Deserializer::processMemberName(ArrayRef<uint32_t> words) {
504 if (words.size() < 3) {
505 return emitError(unknownLoc,
"OpMemberName must have at least 3 operands");
507 unsigned wordIndex = 2;
509 if (wordIndex != words.size()) {
511 "unexpected trailing words in OpMemberName instruction");
513 memberNameMap[words[0]][words[1]] = name;
519 spirv::DecorationAttr foundDecorationAttr;
521 if (
auto it = functionParameterAttrs.find(argID);
522 it != functionParameterAttrs.end()) {
524 functionParameterAttrs.erase(it);
528 spirv::Decoration::Alignment))) {
533 if (!isa<UnitAttr>(decAttr.getValue()))
534 return emitError(unknownLoc,
"unhandled decoration '")
535 << decAttr.getName().getValue()
536 <<
"' on function argument with result <id> " << argID;
539 if (foundDecorationAttr)
540 return emitError(unknownLoc,
"already found a decoration for function "
541 "argument with result <id> ")
544 std::optional<spirv::Decoration> decoration = spirv::symbolizeDecoration(
545 llvm::convertToCamelFromSnakeCase(decAttr.getName(),
true));
547 return emitError(unknownLoc,
"unknown decoration '")
548 << decAttr.getName().getValue()
549 <<
"' on function argument with result <id> " << argID;
550 foundDecorationAttr = spirv::DecorationAttr::get(context, *decoration);
553 if (foundDecorationAttr)
554 attributes.
set(spirv::DecorationAttr::name, foundDecorationAttr);
562 return emitError(unknownLoc,
"found function inside function");
566 if (operands.size() != 4) {
567 return emitError(unknownLoc,
"OpFunction must have 4 parameters");
571 return emitError(unknownLoc,
"undefined result type from <id> ")
575 uint32_t fnID = operands[1];
576 if (funcMap.count(fnID)) {
577 return emitError(unknownLoc,
"duplicate function definition/declaration");
580 auto fnControl = spirv::symbolizeFunctionControl(operands[2]);
582 return emitError(unknownLoc,
"unknown Function Control: ") << operands[2];
586 if (!fnType || !isa<FunctionType>(fnType)) {
587 return emitError(unknownLoc,
"unknown function type from <id> ")
590 auto functionType = cast<FunctionType>(fnType);
592 if ((
isVoidType(resultType) && functionType.getNumResults() != 0) ||
593 (functionType.getNumResults() == 1 &&
594 functionType.getResult(0) != resultType)) {
595 return emitError(unknownLoc,
"mismatch in function type ")
596 << functionType <<
" and return type " << resultType <<
" specified";
600 auto funcOp = spirv::FuncOp::create(opBuilder, unknownLoc, fnName,
601 functionType, fnControl.value());
602 if (
auto it = functionParameterAttrs.find(fnID);
603 it != functionParameterAttrs.end()) {
604 if (functionType.getNumResults() == 0)
606 "FuncParamAttr decoration requires a non-void function "
609 functionParameterAttrs.erase(it);
612 if (decorations.count(fnID)) {
613 for (
auto attr : decorations[fnID].getAttrs()) {
617 curFunction = funcMap[fnID] = funcOp;
618 auto *entryBlock = funcOp.addEntryBlock();
621 <<
"//===-------------------------------------------===//\n";
622 logger.startLine() <<
"[fn] name: " << fnName <<
"\n";
623 logger.startLine() <<
"[fn] type: " << fnType <<
"\n";
624 logger.startLine() <<
"[fn] ID: " << fnID <<
"\n";
625 logger.startLine() <<
"[fn] entry block: " << entryBlock <<
"\n";
630 argAttrs.resize(functionType.getNumInputs());
633 if (functionType.getNumInputs()) {
634 for (
size_t i = 0, e = functionType.getNumInputs(); i != e; ++i) {
635 auto argType = functionType.getInput(i);
636 spirv::Opcode opcode = spirv::Opcode::OpNop;
639 spirv::Opcode::OpFunctionParameter))) {
642 if (opcode != spirv::Opcode::OpFunctionParameter) {
645 "missing OpFunctionParameter instruction for argument ")
648 if (operands.size() != 2) {
651 "expected result type and result <id> for OpFunctionParameter");
653 auto argDefinedType =
getType(operands[0]);
654 if (!argDefinedType || argDefinedType != argType) {
656 "mismatch in argument type between function type "
658 << functionType <<
" and argument type definition "
659 << argDefinedType <<
" at argument " << i;
662 return emitError(unknownLoc,
"duplicate definition of result <id> ")
669 auto argValue = funcOp.getArgument(i);
670 valueMap[operands[1]] = argValue;
674 if (llvm::any_of(argAttrs, [](
Attribute attr) {
675 auto argAttr = cast<DictionaryAttr>(attr);
676 return !argAttr.empty();
678 funcOp.setArgAttrsAttr(ArrayAttr::get(context, argAttrs));
683 auto linkageAttr = funcOp.getLinkageAttributes();
684 auto hasImportLinkage =
685 linkageAttr && (linkageAttr.value().getLinkageType().
getValue() ==
686 spirv::LinkageType::Import);
687 if (hasImportLinkage)
694 spirv::Opcode opcode = spirv::Opcode::OpNop;
703 spirv::Opcode::OpFunctionEnd))) {
706 if (opcode == spirv::Opcode::OpFunctionEnd) {
709 if (opcode != spirv::Opcode::OpLabel) {
710 return emitError(unknownLoc,
"a basic block must start with OpLabel");
712 if (instOperands.size() != 1) {
713 return emitError(unknownLoc,
"OpLabel should only have result <id>");
715 blockMap[instOperands[0]] = entryBlock;
723 spirv::Opcode::OpFunctionEnd)) &&
724 opcode != spirv::Opcode::OpFunctionEnd) {
729 if (opcode != spirv::Opcode::OpFunctionEnd) {
739 if (!operands.empty()) {
740 return emitError(unknownLoc,
"unexpected operands for OpFunctionEnd");
750 blockConstantMap.clear();
752 curFunction = std::nullopt;
757 <<
"//===-------------------------------------------===//\n";
764 if (operands.size() < 2) {
766 "missing graph defintion in OpGraphEntryPointARM");
769 unsigned wordIndex = 0;
770 uint32_t graphID = operands[wordIndex++];
771 if (!graphMap.contains(graphID)) {
773 "missing graph definition/declaration with id ")
777 spirv::GraphARMOp graphARM = graphMap[graphID];
779 graphARM.setSymName(name);
780 graphARM.setEntryPoint(
true);
783 for (
int64_t size = operands.size(); wordIndex < size; ++wordIndex) {
785 interface.push_back(SymbolRefAttr::get(arg.getOperation()));
787 return emitError(unknownLoc,
"undefined result <id> ")
788 << operands[wordIndex] <<
" while decoding OpGraphEntryPoint";
794 opBuilder.setInsertionPoint(graphARM);
795 spirv::GraphEntryPointARMOp::create(
796 opBuilder, unknownLoc, SymbolRefAttr::get(opBuilder.getContext(), name),
797 opBuilder.getArrayAttr(interface));
805 return emitError(unknownLoc,
"found graph inside graph");
808 if (operands.size() < 2) {
809 return emitError(unknownLoc,
"OpGraphARM must have at least 2 parameters");
813 if (!type || !isa<GraphType>(type)) {
814 return emitError(unknownLoc,
"unknown graph type from <id> ")
817 auto graphType = cast<GraphType>(type);
818 if (graphType.getNumResults() <= 0) {
819 return emitError(unknownLoc,
"expected at least one result");
822 uint32_t graphID = operands[1];
823 if (graphMap.count(graphID)) {
824 return emitError(unknownLoc,
"duplicate graph definition/declaration");
829 spirv::GraphARMOp::create(opBuilder, unknownLoc, graphName, graphType);
830 curGraph = graphMap[graphID] = graphOp;
831 Block *entryBlock = graphOp.addEntryBlock();
834 <<
"//===-------------------------------------------===//\n";
835 logger.startLine() <<
"[graph] name: " << graphName <<
"\n";
836 logger.startLine() <<
"[graph] type: " << graphType <<
"\n";
837 logger.startLine() <<
"[graph] ID: " << graphID <<
"\n";
838 logger.startLine() <<
"[graph] entry block: " << entryBlock <<
"\n";
843 for (
auto [
index, argType] : llvm::enumerate(graphType.getInputs())) {
844 spirv::Opcode opcode;
847 spirv::Opcode::OpGraphInputARM))) {
850 if (operands.size() != 3) {
851 return emitError(unknownLoc,
"expected result type, result <id> and "
852 "input index for OpGraphInputARM");
856 if (!argDefinedType) {
857 return emitError(unknownLoc,
"unknown operand type <id> ") << operands[0];
860 if (argDefinedType != argType) {
862 "mismatch in argument type between graph type "
864 << graphType <<
" and argument type definition " << argDefinedType
865 <<
" at argument " <<
index;
868 return emitError(unknownLoc,
"duplicate definition of result <id> ")
873 if (!inputIndexAttr) {
875 "unable to read inputIndex value from constant op ")
878 BlockArgument argValue = graphOp.getArgument(inputIndexAttr.getInt());
879 valueMap[operands[1]] = argValue;
882 graphOutputs.resize(graphType.getNumResults());
888 blockMap[graphID] = entryBlock;
895 spirv::Opcode opcode;
905 }
while (opcode != spirv::Opcode::OpGraphEndARM);
912 if (operands.size() != 2) {
915 "expected value id and output index for OpGraphSetOutputARM");
918 uint32_t
id = operands[0];
921 return emitError(unknownLoc,
"could not find result <id> ") << id;
925 if (!outputIndexAttr) {
927 "unable to read outputIndex value from constant op ")
930 graphOutputs[outputIndexAttr.getInt()] = value;
937 spirv::GraphOutputsARMOp::create(opBuilder, unknownLoc, graphOutputs);
940 if (!operands.empty()) {
941 return emitError(unknownLoc,
"unexpected operands for OpGraphEndARM");
944 blockConstantMap.clear();
946 curGraph = std::nullopt;
947 graphOutputs.clear();
952 <<
"//===-------------------------------------------===//\n";
957std::optional<std::pair<Attribute, Type>>
959 auto constIt = constantMap.find(
id);
960 if (constIt != constantMap.end())
961 return constIt->getSecond();
963 auto replicatedConstIt = constantCompositeReplicateMap.find(
id);
964 if (replicatedConstIt == constantCompositeReplicateMap.end())
967 auto [value, type] = replicatedConstIt->getSecond();
968 auto shapedType = dyn_cast<ShapedType>(type);
974std::optional<std::pair<Attribute, Type>>
976 if (
auto it = constantCompositeReplicateMap.find(
id);
977 it != constantCompositeReplicateMap.end())
982std::optional<spirv::SpecConstOperationMaterializationInfo>
984 auto constIt = specConstOperationMap.find(
id);
985 if (constIt == specConstOperationMap.end())
987 return constIt->getSecond();
990std::optional<std::pair<Type, SmallVector<uint32_t>>>
992 if (
auto it = undefCompositeMap.find(
id); it != undefCompositeMap.end())
998 auto funcName = nameMap.lookup(
id).str();
999 if (funcName.empty()) {
1000 funcName =
"spirv_fn_" + std::to_string(
id);
1006 std::string graphName = nameMap.lookup(
id).str();
1007 if (graphName.empty()) {
1008 graphName =
"spirv_graph_" + std::to_string(
id);
1014 auto constName = nameMap.lookup(
id).str();
1015 if (constName.empty()) {
1016 constName =
"spirv_spec_const_" + std::to_string(
id);
1021spirv::SpecConstantOp
1023 TypedAttr defaultValue) {
1025 auto op = spirv::SpecConstantOp::create(opBuilder, unknownLoc, symName,
1028 if (decorations.count(resultID)) {
1029 for (
auto attr : decorations[resultID].getAttrs())
1032 specConstMap[resultID] = op;
1036std::optional<spirv::GraphConstantARMOpMaterializationInfo>
1038 auto graphConstIt = graphConstantMap.find(
id);
1039 if (graphConstIt == graphConstantMap.end())
1040 return std::nullopt;
1041 return graphConstIt->getSecond();
1047 StringRef opName = spirv::stringifyOpcode(opcode);
1048 bool isUntyped = opcode == spirv::Opcode::OpUntypedVariableKHR;
1049 unsigned wordIndex = 0;
1050 if (operands.size() < 3) {
1052 <<
" needs at least 3 operands, type, <id> and storage class";
1056 auto type =
getType(operands[wordIndex]);
1058 return emitError(unknownLoc,
"unknown result type <id> : ")
1059 << operands[wordIndex];
1061 std::optional<spirv::StorageClass> ptrStorageClass;
1063 if (
auto ptrType = dyn_cast<spirv::UntypedPointerType>(type))
1064 ptrStorageClass = ptrType.getStorageClass();
1065 }
else if (
auto ptrType = dyn_cast<spirv::PointerType>(type)) {
1066 ptrStorageClass = ptrType.getStorageClass();
1068 if (!ptrStorageClass) {
1069 return emitError(unknownLoc,
"expected a result type <id> to be a ")
1070 << (isUntyped ?
"spirv.untyped_ptr" :
"spirv.ptr")
1071 <<
", found : " << type;
1076 auto variableID = operands[wordIndex];
1077 auto variableName = nameMap.lookup(variableID).str();
1078 if (variableName.empty()) {
1079 variableName =
"spirv_var_" + std::to_string(variableID);
1084 auto storageClass =
static_cast<spirv::StorageClass
>(operands[wordIndex]);
1085 if (*ptrStorageClass != storageClass) {
1086 return emitError(unknownLoc,
"mismatch in storage class of pointer type ")
1087 << type <<
" and that specified in " << opName
1088 <<
" instruction : " << stringifyStorageClass(storageClass);
1094 if (isUntyped && wordIndex < operands.size()) {
1097 return emitError(unknownLoc,
"unknown data type <id> : ")
1098 << operands[wordIndex];
1100 dataType = TypeAttr::get(objectType);
1107 if (wordIndex < operands.size()) {
1117 return emitError(unknownLoc,
"unknown <id> ")
1118 << operands[wordIndex] <<
"used as initializer";
1120 initializer = SymbolRefAttr::get(op);
1123 if (wordIndex != operands.size()) {
1125 "found more operands than expected when deserializing ")
1126 << opName <<
" instruction, only " << wordIndex <<
" of "
1127 << operands.size() <<
" processed";
1130 auto varOp = spirv::GlobalVariableOp::create(
1131 opBuilder, loc, TypeAttr::get(type),
1132 opBuilder.getStringAttr(variableName), initializer);
1134 varOp.setDataTypeAttr(dataType);
1137 if (decorations.count(variableID)) {
1138 for (
auto attr : decorations[variableID].getAttrs())
1141 globalVariableMap[variableID] = varOp;
1150 return dyn_cast<IntegerAttr>(constInfo->first);
1154 if (operands.size() < 2) {
1155 return emitError(unknownLoc,
"OpName needs at least 2 operands");
1158 unsigned wordIndex = 1;
1160 if (wordIndex != operands.size()) {
1162 "unexpected trailing words in OpName instruction");
1167 nameMap.emplace_or_assign(operands[0], name);
1178 if (operands.empty()) {
1179 return emitError(unknownLoc,
"type instruction with opcode ")
1180 << spirv::stringifyOpcode(opcode) <<
" needs at least one <id>";
1185 if (typeMap.count(operands[0])) {
1186 return emitError(unknownLoc,
"duplicate definition for result <id> ")
1191 case spirv::Opcode::OpTypeVoid:
1192 if (operands.size() != 1)
1193 return emitError(unknownLoc,
"OpTypeVoid must have no parameters");
1194 typeMap[operands[0]] = opBuilder.getNoneType();
1196 case spirv::Opcode::OpTypeBool:
1197 if (operands.size() != 1)
1198 return emitError(unknownLoc,
"OpTypeBool must have no parameters");
1199 typeMap[operands[0]] = opBuilder.getI1Type();
1201 case spirv::Opcode::OpTypeInt: {
1202 if (operands.size() != 3)
1204 unknownLoc,
"OpTypeInt must have bitwidth and signedness parameters");
1213 auto sign = operands[2] == 1 ? IntegerType::SignednessSemantics::Signed
1214 : IntegerType::SignednessSemantics::Signless;
1215 typeMap[operands[0]] = IntegerType::get(context, operands[1], sign);
1217 case spirv::Opcode::OpTypeFloat: {
1218 if (operands.size() != 2 && operands.size() != 3)
1220 "OpTypeFloat expects either 2 operands (type, bitwidth) "
1221 "or 3 operands (type, bitwidth, encoding), but got ")
1223 uint32_t bitWidth = operands[1];
1226 if (operands.size() == 2) {
1229 floatTy = opBuilder.getF16Type();
1232 floatTy = opBuilder.getF32Type();
1235 floatTy = opBuilder.getF64Type();
1238 return emitError(unknownLoc,
"unsupported OpTypeFloat bitwidth: ")
1243 if (operands.size() == 3) {
1244 if (spirv::FPEncoding(operands[2]) == spirv::FPEncoding::BFloat16KHR &&
1246 floatTy = opBuilder.getBF16Type();
1247 else if (spirv::FPEncoding(operands[2]) ==
1248 spirv::FPEncoding::Float8E4M3EXT &&
1250 floatTy = opBuilder.getF8E4M3FNType();
1251 else if (spirv::FPEncoding(operands[2]) ==
1252 spirv::FPEncoding::Float8E5M2EXT &&
1254 floatTy = opBuilder.getF8E5M2Type();
1255 else if (spirv::FPEncoding(operands[2]) ==
1256 spirv::FPEncoding::Float4E2M1EXT &&
1258 floatTy = Float4E2M1FNType::get(context);
1259 else if (spirv::FPEncoding(operands[2]) ==
1260 spirv::FPEncoding::Float6E2M3EXT &&
1262 floatTy = Float6E2M3FNType::get(context);
1263 else if (spirv::FPEncoding(operands[2]) ==
1264 spirv::FPEncoding::Float6E3M2EXT &&
1266 floatTy = Float6E3M2FNType::get(context);
1267 else if (spirv::FPEncoding(operands[2]) ==
1268 spirv::FPEncoding::Float8UnsignedE8M0EXT &&
1270 floatTy = opBuilder.getF8E8M0Type();
1272 return emitError(unknownLoc,
"unsupported OpTypeFloat FP encoding: ")
1273 << operands[2] <<
" and bitWidth " << bitWidth;
1276 typeMap[operands[0]] = floatTy;
1278 case spirv::Opcode::OpTypeVector: {
1279 if (operands.size() != 3) {
1282 "OpTypeVector must have element type and count parameters");
1286 return emitError(unknownLoc,
"OpTypeVector references undefined <id> ")
1289 typeMap[operands[0]] = VectorType::get({operands[2]}, elementTy);
1291 case spirv::Opcode::OpTypePointer: {
1294 case spirv::Opcode::OpTypeArray:
1296 case spirv::Opcode::OpTypeCooperativeMatrixKHR:
1298 case spirv::Opcode::OpTypeFunction:
1300 case spirv::Opcode::OpTypeImage:
1302 case spirv::Opcode::OpTypeSampler:
1304 case spirv::Opcode::OpTypeNamedBarrier:
1306 case spirv::Opcode::OpTypeUntypedPointerKHR:
1308 case spirv::Opcode::OpTypeSampledImage:
1310 case spirv::Opcode::OpTypeRuntimeArray:
1312 case spirv::Opcode::OpTypeStruct:
1314 case spirv::Opcode::OpTypeMatrix:
1316 case spirv::Opcode::OpTypeTensorARM:
1318 case spirv::Opcode::OpTypeGraphARM:
1321 return emitError(unknownLoc,
"unhandled type instruction");
1328 if (operands.size() != 3)
1329 return emitError(unknownLoc,
"OpTypePointer must have two parameters");
1331 auto pointeeType =
getType(operands[2]);
1333 return emitError(unknownLoc,
"unknown OpTypePointer pointee type <id> ")
1336 uint32_t typePointerID = operands[0];
1337 auto storageClass =
static_cast<spirv::StorageClass
>(operands[1]);
1340 context, pointeeType, storageClass);
1343 typeMap[typePointerID] = pointerType;
1345 for (
auto *deferredStructIt = std::begin(deferredStructTypesInfos);
1346 deferredStructIt != std::end(deferredStructTypesInfos);) {
1347 for (
auto *unresolvedMemberIt =
1348 std::begin(deferredStructIt->unresolvedMemberTypes);
1349 unresolvedMemberIt !=
1350 std::end(deferredStructIt->unresolvedMemberTypes);) {
1351 if (unresolvedMemberIt->first == typePointerID) {
1355 deferredStructIt->memberTypes[unresolvedMemberIt->second] =
1356 typeMap[typePointerID];
1357 unresolvedMemberIt =
1358 deferredStructIt->unresolvedMemberTypes.erase(unresolvedMemberIt);
1360 ++unresolvedMemberIt;
1364 if (deferredStructIt->unresolvedMemberTypes.empty()) {
1366 auto structType = deferredStructIt->deferredStructType;
1368 assert(structType &&
"expected a spirv::StructType");
1369 assert(structType.isIdentified() &&
"expected an indentified struct");
1371 if (failed(structType.trySetBody(
1372 deferredStructIt->memberTypes, deferredStructIt->offsetInfo,
1373 deferredStructIt->memberDecorationsInfo,
1374 deferredStructIt->structDecorationsInfo)))
1377 deferredStructIt = deferredStructTypesInfos.erase(deferredStructIt);
1388 if (operands.size() != 3) {
1390 "OpTypeArray must have element type and count parameters");
1395 return emitError(unknownLoc,
"OpTypeArray references undefined <id> ")
1403 return emitError(unknownLoc,
"OpTypeArray count <id> ")
1404 << operands[2] <<
"can only come from normal constant right now";
1407 if (
auto intVal = dyn_cast<IntegerAttr>(countInfo->first)) {
1408 count = intVal.getValue().getZExtValue();
1410 return emitError(unknownLoc,
"OpTypeArray count must come from a "
1411 "scalar integer constant instruction");
1415 elementTy, count, typeDecorations.lookup(operands[0]));
1421 assert(!operands.empty() &&
"No operands for processing function type");
1422 if (operands.size() == 1) {
1423 return emitError(unknownLoc,
"missing return type for OpTypeFunction");
1425 auto returnType =
getType(operands[1]);
1427 return emitError(unknownLoc,
"unknown return type in OpTypeFunction");
1430 for (
size_t i = 2, e = operands.size(); i < e; ++i) {
1431 auto ty =
getType(operands[i]);
1433 return emitError(unknownLoc,
"unknown argument type in OpTypeFunction");
1435 argTypes.push_back(ty);
1441 typeMap[operands[0]] = FunctionType::get(context, argTypes, returnTypes);
1447 if (operands.size() != 6) {
1449 "OpTypeCooperativeMatrixKHR must have element type, "
1450 "scope, row and column parameters, and use");
1456 "OpTypeCooperativeMatrixKHR references undefined <id> ")
1460 std::optional<spirv::Scope> scope =
1465 "OpTypeCooperativeMatrixKHR references undefined scope <id> ")
1474 return emitError(unknownLoc,
"OpTypeCooperativeMatrixKHR `Rows` references "
1475 "undefined constant <id> ")
1479 return emitError(unknownLoc,
"OpTypeCooperativeMatrixKHR `Columns` "
1480 "references undefined constant <id> ")
1484 return emitError(unknownLoc,
"OpTypeCooperativeMatrixKHR `Use` references "
1485 "undefined constant <id> ")
1488 unsigned rows = rowsAttr.getInt();
1489 unsigned columns = columnsAttr.getInt();
1491 std::optional<spirv::CooperativeMatrixUseKHR> use =
1492 spirv::symbolizeCooperativeMatrixUseKHR(useAttr.getInt());
1496 "OpTypeCooperativeMatrixKHR references undefined use <id> ")
1501 [&] {
return emitError(unknownLoc); }, context, elementTy, rows, columns,
1503 return success(
static_cast<bool>(typeMap[operands[0]]));
1508 if (operands.size() != 2) {
1509 return emitError(unknownLoc,
"OpTypeRuntimeArray must have two operands");
1514 "OpTypeRuntimeArray references undefined <id> ")
1518 memberType, typeDecorations.lookup(operands[0]));
1526 if (operands.empty()) {
1527 return emitError(unknownLoc,
"OpTypeStruct must have at least result <id>");
1530 if (operands.size() == 1) {
1532 typeMap[operands[0]] =
1541 for (
auto op : llvm::drop_begin(operands, 1)) {
1543 bool typeForwardPtr = (typeForwardPointerIDs.count(op) != 0);
1545 if (!memberType && !typeForwardPtr)
1546 return emitError(unknownLoc,
"OpTypeStruct references undefined <id> ")
1550 unresolvedMemberTypes.emplace_back(op, memberTypes.size());
1552 memberTypes.push_back(memberType);
1557 if (memberDecorationMap.count(operands[0])) {
1558 auto &allMemberDecorations = memberDecorationMap[operands[0]];
1559 for (
auto memberIndex : llvm::seq<uint32_t>(0, memberTypes.size())) {
1560 if (allMemberDecorations.count(memberIndex)) {
1561 for (
auto &memberDecoration : allMemberDecorations[memberIndex]) {
1563 if (memberDecoration.first == spirv::Decoration::Offset) {
1565 if (offsetInfo.empty()) {
1566 offsetInfo.resize(memberTypes.size());
1568 offsetInfo[memberIndex] = memberDecoration.second[0];
1570 auto intType = mlir::IntegerType::get(context, 32);
1571 if (!memberDecoration.second.empty()) {
1572 memberDecorationsInfo.emplace_back(
1573 memberIndex, memberDecoration.first,
1574 IntegerAttr::get(intType, memberDecoration.second[0]));
1576 memberDecorationsInfo.emplace_back(
1577 memberIndex, memberDecoration.first, UnitAttr::get(context));
1586 if (decorations.count(operands[0])) {
1589 std::optional<spirv::Decoration> decoration = spirv::symbolizeDecoration(
1590 llvm::convertToCamelFromSnakeCase(decorationAttr.getName(),
true));
1591 assert(decoration.has_value());
1592 structDecorationsInfo.emplace_back(decoration.value(),
1593 decorationAttr.getValue());
1597 uint32_t structID = operands[0];
1598 std::string structIdentifier = nameMap.lookup(structID).str();
1600 if (structIdentifier.empty()) {
1601 assert(unresolvedMemberTypes.empty() &&
1602 "didn't expect unresolved member types");
1604 memberTypes, offsetInfo, memberDecorationsInfo, structDecorationsInfo);
1607 typeMap[structID] = structTy;
1609 if (!unresolvedMemberTypes.empty())
1610 deferredStructTypesInfos.push_back(
1611 {structTy, std::move(unresolvedMemberTypes), std::move(memberTypes),
1612 std::move(offsetInfo), std::move(memberDecorationsInfo),
1613 std::move(structDecorationsInfo)});
1614 else if (failed(structTy.trySetBody(memberTypes, offsetInfo,
1615 memberDecorationsInfo,
1616 structDecorationsInfo)))
1627 if (operands.size() != 3) {
1629 return emitError(unknownLoc,
"OpTypeMatrix must have 3 operands"
1630 " (result_id, column_type, and column_count)");
1636 "OpTypeMatrix references undefined column type.")
1640 uint32_t colsCount = operands[2];
1642 [&] {
return emitError(unknownLoc); }, elementTy, colsCount);
1643 return success(
static_cast<bool>(typeMap[operands[0]]));
1648 unsigned size = operands.size();
1649 if (size < 2 || size > 4)
1650 return emitError(unknownLoc,
"OpTypeTensorARM must have 2-4 operands "
1651 "(result_id, element_type, (rank), (shape)) ")
1657 "OpTypeTensorARM references undefined element type ")
1667 return emitError(unknownLoc,
"OpTypeTensorARM rank must come from a "
1668 "scalar integer constant instruction");
1669 unsigned rank = rankAttr.getValue().getZExtValue();
1676 std::optional<std::pair<Attribute, Type>> shapeInfo =
1679 return emitError(unknownLoc,
"OpTypeTensorARM shape must come from a "
1680 "constant instruction of type OpTypeArray");
1682 ArrayAttr shapeArrayAttr = dyn_cast<ArrayAttr>(shapeInfo->first);
1684 for (
auto dimAttr : shapeArrayAttr.getValue()) {
1685 auto dimIntAttr = dyn_cast<IntegerAttr>(dimAttr);
1687 return emitError(unknownLoc,
"OpTypeTensorARM shape has an invalid "
1689 shape.push_back(dimIntAttr.getValue().getSExtValue());
1697 unsigned size = operands.size();
1699 return emitError(unknownLoc,
"OpTypeGraphARM must have at least 2 operands "
1700 "(result_id, num_inputs, (inout0_type, "
1701 "inout1_type, ...))")
1704 uint32_t numInputs = operands[1];
1707 for (
unsigned i = 2; i < size; ++i) {
1711 "OpTypeGraphARM references undefined element type.")
1714 if (i - 2 >= numInputs) {
1715 returnTypes.push_back(inOutTy);
1717 argTypes.push_back(inOutTy);
1720 typeMap[operands[0]] = GraphType::get(context, argTypes, returnTypes);
1726 if (operands.size() != 2)
1728 "OpTypeForwardPointer instruction must have two operands");
1730 typeForwardPointerIDs.insert(operands[0]);
1740 if (operands.size() != 8)
1743 "OpTypeImage with non-eight operands are not supported yet");
1747 return emitError(unknownLoc,
"OpTypeImage references undefined <id>: ")
1750 auto dim = spirv::symbolizeDim(operands[2]);
1752 return emitError(unknownLoc,
"unknown Dim for OpTypeImage: ")
1755 auto depthInfo = spirv::symbolizeImageDepthInfo(operands[3]);
1757 return emitError(unknownLoc,
"unknown Depth for OpTypeImage: ")
1760 auto arrayedInfo = spirv::symbolizeImageArrayedInfo(operands[4]);
1762 return emitError(unknownLoc,
"unknown Arrayed for OpTypeImage: ")
1765 auto samplingInfo = spirv::symbolizeImageSamplingInfo(operands[5]);
1767 return emitError(unknownLoc,
"unknown MS for OpTypeImage: ") << operands[5];
1769 auto samplerUseInfo = spirv::symbolizeImageSamplerUseInfo(operands[6]);
1770 if (!samplerUseInfo)
1771 return emitError(unknownLoc,
"unknown Sampled for OpTypeImage: ")
1774 auto format = spirv::symbolizeImageFormat(operands[7]);
1776 return emitError(unknownLoc,
"unknown Format for OpTypeImage: ")
1780 [&] {
return emitError(unknownLoc); }, context,
1781 std::make_tuple(elementTy, dim.value(), depthInfo.value(),
1782 arrayedInfo.value(), samplingInfo.value(),
1783 samplerUseInfo.value(), format.value()));
1784 return success(
static_cast<bool>(typeMap[operands[0]]));
1789 if (operands.size() != 2)
1790 return emitError(unknownLoc,
"OpTypeSampledImage must have two operands");
1795 "OpTypeSampledImage references undefined <id>: ")
1804 if (operands.size() != 1)
1805 return emitError(unknownLoc,
"OpTypeSampler must have no parameters");
1813 if (operands.size() != 1)
1814 return emitError(unknownLoc,
"OpTypeNamedBarrier must have no parameters");
1822 if (operands.size() != 2)
1824 "OpTypeUntypedPointerKHR must have one parameter");
1827 context,
static_cast<spirv::StorageClass
>(operands[1]));
1837 StringRef opname = isSpec ?
"OpSpecConstant" :
"OpConstant";
1839 if (operands.size() < 2) {
1841 << opname <<
" must have type <id> and result <id>";
1843 if (operands.size() < 3) {
1845 << opname <<
" must have at least 1 more parameter";
1850 return emitError(unknownLoc,
"undefined result type from <id> ")
1854 auto checkOperandSizeForBitwidth = [&](
unsigned bitwidth) -> LogicalResult {
1855 if (bitwidth == 64) {
1856 if (operands.size() == 4) {
1860 << opname <<
" should have 2 parameters for 64-bit values";
1862 if (bitwidth <= 32) {
1863 if (operands.size() == 3) {
1869 <<
" should have 1 parameter for values with no more than 32 bits";
1871 return emitError(unknownLoc,
"unsupported OpConstant bitwidth: ")
1875 auto resultID = operands[1];
1877 if (
auto intType = dyn_cast<IntegerType>(resultType)) {
1878 auto bitwidth = intType.getWidth();
1879 if (failed(checkOperandSizeForBitwidth(bitwidth))) {
1884 if (bitwidth == 64) {
1891 } words = {operands[2], operands[3]};
1892 value = APInt(64, llvm::bit_cast<uint64_t>(words),
true);
1893 }
else if (bitwidth <= 32) {
1894 value = APInt(bitwidth, operands[2],
true,
1898 auto attr = opBuilder.getIntegerAttr(intType, value);
1905 constantMap.try_emplace(resultID, attr, intType);
1911 if (
auto floatType = dyn_cast<FloatType>(resultType)) {
1912 auto bitwidth = floatType.getWidth();
1913 if (failed(checkOperandSizeForBitwidth(bitwidth))) {
1918 if (floatType.isF64()) {
1925 } words = {operands[2], operands[3]};
1926 value = APFloat(llvm::bit_cast<double>(words));
1927 }
else if (floatType.isF32()) {
1928 value = APFloat(llvm::bit_cast<float>(operands[2]));
1929 }
else if (floatType.isF16()) {
1930 APInt data(16, operands[2]);
1931 value = APFloat(APFloat::IEEEhalf(), data);
1932 }
else if (floatType.isBF16()) {
1933 APInt data(16, operands[2]);
1934 value = APFloat(APFloat::BFloat(), data);
1935 }
else if (floatType.isF8E4M3FN()) {
1936 APInt data(8, operands[2]);
1937 value = APFloat(APFloat::Float8E4M3FN(), data);
1938 }
else if (floatType.isF8E5M2()) {
1939 APInt data(8, operands[2]);
1940 value = APFloat(APFloat::Float8E5M2(), data);
1941 }
else if (isa<Float4E2M1FNType>(floatType)) {
1942 value = APFloat(APFloat::Float4E2M1FN(), APInt(4, operands[2]));
1943 }
else if (isa<Float6E2M3FNType>(floatType)) {
1944 value = APFloat(APFloat::Float6E2M3FN(), APInt(6, operands[2]));
1945 }
else if (isa<Float6E3M2FNType>(floatType)) {
1946 value = APFloat(APFloat::Float6E3M2FN(), APInt(6, operands[2]));
1947 }
else if (isa<Float8E8M0FNUType>(floatType)) {
1948 value = APFloat(APFloat::Float8E8M0FNU(), APInt(8, operands[2]));
1951 auto attr = opBuilder.getFloatAttr(floatType, value);
1957 constantMap.try_emplace(resultID, attr, floatType);
1963 return emitError(unknownLoc,
"OpConstant can only generate values of "
1964 "scalar integer or floating-point type");
1969 if (operands.size() != 2) {
1971 << (isSpec ?
"Spec" :
"") <<
"Constant"
1972 << (isTrue ?
"True" :
"False")
1973 <<
" must have type <id> and result <id>";
1976 auto attr = opBuilder.getBoolAttr(isTrue);
1977 auto resultID = operands[1];
1983 constantMap.try_emplace(resultID, attr, opBuilder.getI1Type());
1991 if (operands.size() < 2) {
1993 "OpConstantComposite must have type <id> and result <id>");
1997 return emitError(unknownLoc,
"undefined result type from <id> ")
2003 auto structType = dyn_cast<spirv::StructType>(resultType);
2004 if (operands.size() < 3 &&
2005 (!structType || structType.getNumElements() != 0)) {
2007 "OpConstantComposite must have at least 1 parameter");
2012 isa<VectorType, spirv::ArrayType, spirv::StructType>(resultType);
2014 elements.reserve(constituents.size());
2015 for (
auto [
index,
id] : llvm::enumerate(constituents)) {
2016 std::optional<std::pair<Attribute, Type>> elementInfo =
getConstant(
id);
2018 if (canHoldUndef && (
getUndefType(
id) || undefCompositeMap.contains(
id)))
2022 return emitError(unknownLoc,
"OpConstantComposite component #")
2023 <<
index <<
" <id> " <<
id
2024 <<
" is an OpUndef, which cannot be represented in "
2027 if (undefCompositeMap.contains(
id)) {
2028 return emitError(unknownLoc,
"OpConstantComposite component #")
2029 <<
index <<
" <id> " <<
id
2030 <<
" has OpUndef constituents, which cannot be represented in "
2033 return emitError(unknownLoc,
"OpConstantComposite component #")
2034 <<
index <<
" <id> " <<
id <<
" must come from a normal constant";
2036 elements.push_back(elementInfo->first);
2039 auto resultID = operands[1];
2040 if (elements.size() != constituents.size()) {
2041 undefCompositeMap.try_emplace(resultID, resultType,
2046 if (
auto tensorType = dyn_cast<TensorArmType>(resultType)) {
2049 if (
auto denseElemAttr = dyn_cast<DenseElementsAttr>(element)) {
2050 for (
auto value : denseElemAttr.getValues<
Attribute>())
2051 flattenedElems.push_back(value);
2053 flattenedElems.push_back(element);
2057 constantMap.try_emplace(resultID, attr, tensorType);
2058 }
else if (
auto shapedType = dyn_cast<ShapedType>(resultType)) {
2062 constantMap.try_emplace(resultID, attr, shapedType);
2063 }
else if (isa<spirv::ArrayType, spirv::StructType>(resultType)) {
2064 auto attr = opBuilder.getArrayAttr(elements);
2065 constantMap.try_emplace(resultID, attr, resultType);
2067 return emitError(unknownLoc,
"unsupported OpConstantComposite type: ")
2076 if (operands.size() != 3) {
2079 "OpConstantCompositeReplicateEXT expects 3 operands but found ")
2085 return emitError(unknownLoc,
"undefined result type from <id> ")
2089 auto compositeType = dyn_cast<CompositeType>(resultType);
2090 if (!compositeType) {
2092 "result type from <id> is not a composite type")
2096 uint32_t resultID = operands[1];
2097 uint32_t constantID = operands[2];
2099 std::optional<std::pair<Attribute, Type>> replicatedConstantCompositeInfo =
2101 if (replicatedConstantCompositeInfo.has_value()) {
2102 constantCompositeReplicateMap.try_emplace(
2103 resultID, replicatedConstantCompositeInfo.value().first, resultType);
2107 std::optional<std::pair<Attribute, Type>> constantInfo =
2109 if (constantInfo.has_value()) {
2110 constantCompositeReplicateMap.try_emplace(
2111 resultID, constantInfo.value().first, resultType);
2115 return emitError(unknownLoc,
"OpConstantCompositeReplicateEXT operand <id> ")
2117 <<
" must come from a normal constant or a "
2118 "OpConstantCompositeReplicateEXT";
2123 if (operands.size() < 2) {
2126 "OpSpecConstantComposite must have type <id> and result <id>");
2128 if (operands.size() < 3) {
2130 "OpSpecConstantComposite must have at least 1 parameter");
2135 return emitError(unknownLoc,
"undefined result type from <id> ")
2139 auto resultID = operands[1];
2143 elements.reserve(operands.size() - 2);
2144 for (
auto [
index,
id] : llvm::enumerate(operands.drop_front(2))) {
2149 return emitError(unknownLoc,
"OpSpecConstantComposite component #")
2150 <<
index <<
" <id> " <<
id
2151 <<
" cannot be represented in spirv.SpecConstantComposite";
2153 elements.push_back(SymbolRefAttr::get(elementOp));
2156 auto op = spirv::SpecConstantCompositeOp::create(
2157 opBuilder, unknownLoc, TypeAttr::get(resultType), symName,
2158 opBuilder.getArrayAttr(elements),
nullptr);
2159 specConstCompositeMap[resultID] = op;
2166 if (operands.size() != 3) {
2167 return emitError(unknownLoc,
"OpSpecConstantCompositeReplicateEXT expects "
2168 "3 operands but found ")
2174 return emitError(unknownLoc,
"undefined result type from <id> ")
2178 auto compositeType = dyn_cast<CompositeType>(resultType);
2179 if (!compositeType) {
2181 "result type from <id> is not a composite type")
2185 uint32_t resultID = operands[1];
2188 spirv::SpecConstantOp constituentSpecConstantOp =
2190 if (!constituentSpecConstantOp) {
2191 return emitError(unknownLoc,
"OpSpecConstantCompositeReplicateEXT operand "
2194 <<
" cannot be represented in "
2195 "spirv.EXT.SpecConstantCompositeReplicate";
2197 auto op = spirv::EXTSpecConstantCompositeReplicateOp::create(
2198 opBuilder, unknownLoc, TypeAttr::get(resultType), symName,
2199 SymbolRefAttr::get(constituentSpecConstantOp),
2202 specConstCompositeReplicateMap[resultID] = op;
2209 if (operands.size() < 3)
2210 return emitError(unknownLoc,
"OpConstantOperation must have type <id>, "
2211 "result <id>, and operand opcode");
2213 uint32_t resultTypeID = operands[0];
2216 return emitError(unknownLoc,
"undefined result type from <id> ")
2219 uint32_t resultID = operands[1];
2220 spirv::Opcode enclosedOpcode =
static_cast<spirv::Opcode
>(operands[2]);
2221 auto emplaceResult = specConstOperationMap.try_emplace(
2224 enclosedOpcode, resultTypeID,
2227 if (!emplaceResult.second)
2228 return emitError(unknownLoc,
"value with <id>: ")
2229 << resultID <<
" is probably defined before.";
2235 uint32_t resultID, spirv::Opcode enclosedOpcode, uint32_t resultTypeID,
2251 llvm::SaveAndRestore valueMapGuard(valueMap, newValueMap);
2252 constexpr uint32_t fakeID =
static_cast<uint32_t
>(-3);
2255 enclosedOpResultTypeAndOperands.push_back(resultTypeID);
2256 enclosedOpResultTypeAndOperands.push_back(fakeID);
2257 enclosedOpResultTypeAndOperands.append(enclosedOpOperands.begin(),
2258 enclosedOpOperands.end());
2273 auto specConstOperationOp =
2274 spirv::SpecConstantOperationOp::create(opBuilder, loc, resultType);
2276 Region &body = specConstOperationOp.getBody();
2278 body.
getBlocks().splice(body.
end(), curBlock->getParent()->getBlocks(),
2285 opBuilder.setInsertionPointToEnd(&block);
2287 spirv::YieldOp::create(opBuilder, loc, block.
front().
getResult(0));
2288 return specConstOperationOp.getResult();
2293 if (operands.size() != 2) {
2295 "OpConstantNull must only have type <id> and result <id>");
2300 return emitError(unknownLoc,
"undefined result type from <id> ")
2304 auto resultID = operands[1];
2306 if (resultType.
isIntOrFloat() || isa<VectorType>(resultType)) {
2307 attr = opBuilder.getZeroAttr(resultType);
2308 }
else if (
auto tensorType = dyn_cast<TensorArmType>(resultType)) {
2309 if (
auto element = opBuilder.getZeroAttr(tensorType.getElementType()))
2311 }
else if (isa<spirv::ArrayType, spirv::PointerType, spirv::StructType>(
2313 attr = spirv::NullAttr::get(resultType);
2319 constantMap.try_emplace(resultID, attr, resultType);
2323 return emitError(unknownLoc,
"unsupported OpConstantNull type: ")
2329 if (operands.size() < 3) {
2331 <<
"OpGraphConstantARM must have at least 2 operands";
2336 return emitError(unknownLoc,
"undefined result type from <id> ")
2340 uint32_t resultID = operands[1];
2342 if (!dyn_cast<spirv::TensorArmType>(resultType)) {
2343 return emitError(unknownLoc,
"result must be of type OpTypeTensorARM");
2346 APInt graph_constant_id = APInt(32, operands[2],
true);
2347 Type i32Ty = opBuilder.getIntegerType(32);
2348 IntegerAttr attr = opBuilder.getIntegerAttr(i32Ty, graph_constant_id);
2349 graphConstantMap.try_emplace(
2361 LLVM_DEBUG(logger.startLine() <<
"[block] got exiting block for id = " <<
id
2362 <<
" @ " << block <<
"\n");
2369 auto *block = curFunction->addBlock();
2370 LLVM_DEBUG(logger.startLine() <<
"[block] created block for id = " <<
id
2371 <<
" @ " << block <<
"\n");
2372 return blockMap[id] = block;
2377 return emitError(unknownLoc,
"OpBranch must appear inside a block");
2380 if (operands.size() != 1) {
2381 return emitError(unknownLoc,
"OpBranch must take exactly one target label");
2389 spirv::BranchOp::create(opBuilder, loc,
target);
2399 "OpBranchConditional must appear inside a block");
2402 if (operands.size() != 3 && operands.size() != 5) {
2404 "OpBranchConditional must have condition, true label, "
2405 "false label, and optionally two branch weights");
2408 auto condition =
getValue(operands[0]);
2412 std::optional<std::pair<uint32_t, uint32_t>> weights;
2413 if (operands.size() == 5) {
2414 weights = std::make_pair(operands[3], operands[4]);
2420 spirv::BranchConditionalOp::create(
2421 opBuilder, loc, condition, trueBlock,
2431 return emitError(unknownLoc,
"OpLabel must appear inside a function");
2434 if (operands.size() != 1) {
2435 return emitError(unknownLoc,
"OpLabel should only have result <id>");
2438 auto labelID = operands[0];
2441 LLVM_DEBUG(logger.startLine()
2442 <<
"[block] populating block " << block <<
"\n");
2444 assert(block->empty() &&
"re-deserialize the same block!");
2446 opBuilder.setInsertionPointToStart(block);
2447 blockMap[labelID] = curBlock = block;
2454 return emitError(unknownLoc,
"a graph block must appear inside a graph");
2459 LLVM_DEBUG(logger.startLine()
2460 <<
"[block] populating block " << block <<
"\n");
2462 assert(block->
empty() &&
"re-deserialize the same block!");
2464 opBuilder.setInsertionPointToStart(block);
2465 blockMap[graphID] = curBlock = block;
2473 return emitError(unknownLoc,
"OpSelectionMerge must appear in a block");
2476 if (operands.size() < 2) {
2479 "OpSelectionMerge must specify merge target and selection control");
2484 auto selectionControl = operands[1];
2486 if (!blockMergeInfo.try_emplace(curBlock, loc, selectionControl, mergeBlock)
2490 "a block cannot have more than one OpSelectionMerge instruction");
2499 return emitError(unknownLoc,
"OpLoopMerge must appear in a block");
2502 if (operands.size() < 3) {
2503 return emitError(unknownLoc,
"OpLoopMerge must specify merge target, "
2504 "continue target and loop control");
2510 uint32_t loopControl = operands[2];
2513 .try_emplace(curBlock, loc, loopControl, mergeBlock, continueBlock)
2517 "a block cannot have more than one OpLoopMerge instruction");
2525 return emitError(unknownLoc,
"OpPhi must appear in a block");
2528 if (operands.size() < 4) {
2529 return emitError(unknownLoc,
"OpPhi must specify result type, result <id>, "
2530 "and variable-parent pairs");
2535 BlockArgument blockArg = curBlock->addArgument(blockArgType, unknownLoc);
2536 valueMap[operands[1]] = blockArg;
2537 LLVM_DEBUG(logger.startLine()
2538 <<
"[phi] created block argument " << blockArg
2539 <<
" id = " << operands[1] <<
" of type " << blockArgType <<
"\n");
2543 for (
unsigned i = 2, e = operands.size(); i < e; i += 2) {
2544 uint32_t value = operands[i];
2546 std::pair<Block *, Block *> predecessorTargetPair{predecessor, curBlock};
2547 blockPhiInfo[predecessorTargetPair].push_back(value);
2548 LLVM_DEBUG(logger.startLine() <<
"[phi] predecessor @ " << predecessor
2549 <<
" with arg id = " << value <<
"\n");
2557 return emitError(unknownLoc,
"OpSwitch must appear in a block");
2559 if (operands.size() < 2)
2560 return emitError(unknownLoc,
"OpSwitch must at least specify selector and "
2561 "a default target");
2565 return emitError(unknownLoc,
"unknown OpSwitch selector <id>: ")
2567 auto selectorType = dyn_cast<IntegerType>(selector.
getType());
2569 return emitError(unknownLoc,
"OpSwitch selector must be an integer");
2573 unsigned bitWidth = selectorType.getWidth();
2574 unsigned literalWords = llvm::divideCeil(bitWidth, 32);
2575 unsigned wordsPerCase = literalWords + 1;
2576 if ((operands.size() - 2) % wordsPerCase != 0)
2577 return emitError(unknownLoc,
"OpSwitch must specify selector, default "
2578 "target and any number of literal and label "
2579 "<id> pairs, where each literal of a ")
2580 << bitWidth <<
"-bit selector spans " << literalWords <<
" word(s)";
2587 for (
unsigned i = 2, e = operands.size(); i < e; i += wordsPerCase) {
2589 if (bitWidth <= 32) {
2593 literal = APInt(bitWidth, operands[i],
true,
2596 literal = APInt(bitWidth, 0);
2597 for (
unsigned w = 0; w < literalWords; ++w)
2598 literal.insertBits(APInt(32, operands[i + w]), w * 32);
2600 literals.push_back(literal);
2605 spirv::SwitchOp::create(opBuilder, loc, selector, defaultBlock,
2615class ControlFlowStructurizer {
2618 ControlFlowStructurizer(
Location loc, uint32_t control,
2621 llvm::ScopedPrinter &logger)
2622 : location(loc), control(control), blockMergeInfo(mergeInfo),
2623 headerBlock(header), mergeBlock(merge), continueBlock(cont),
2626 ControlFlowStructurizer(
Location loc, uint32_t control,
2629 : location(loc), control(control), blockMergeInfo(mergeInfo),
2630 headerBlock(header), mergeBlock(merge), continueBlock(cont) {}
2640 LogicalResult structurize();
2645 spirv::SelectionOp createSelectionOp(uint32_t selectionControl);
2648 spirv::LoopOp createLoopOp(uint32_t loopControl);
2651 void collectBlocksInConstruct();
2660 Block *continueBlock;
2666 llvm::ScopedPrinter &logger;
2672ControlFlowStructurizer::createSelectionOp(uint32_t selectionControl) {
2675 OpBuilder builder(&mergeBlock->front());
2677 auto control =
static_cast<spirv::SelectionControl
>(selectionControl);
2678 auto selectionOp = spirv::SelectionOp::create(builder, location, control);
2679 selectionOp.addMergeBlock(builder);
2684spirv::LoopOp ControlFlowStructurizer::createLoopOp(uint32_t loopControl) {
2687 OpBuilder builder(&mergeBlock->front());
2689 auto control =
static_cast<spirv::LoopControl
>(loopControl);
2690 auto loopOp = spirv::LoopOp::create(builder, location, control);
2691 loopOp.addEntryAndMergeBlock(builder);
2696void ControlFlowStructurizer::collectBlocksInConstruct() {
2697 assert(constructBlocks.empty() &&
"expected empty constructBlocks");
2700 constructBlocks.insert(headerBlock);
2704 for (
unsigned i = 0; i < constructBlocks.size(); ++i) {
2705 for (
auto *successor : constructBlocks[i]->getSuccessors())
2706 if (successor != mergeBlock)
2707 constructBlocks.insert(successor);
2711LogicalResult ControlFlowStructurizer::structurize() {
2712 Operation *op =
nullptr;
2713 bool isLoop = continueBlock !=
nullptr;
2715 if (
auto loopOp = createLoopOp(control))
2716 op = loopOp.getOperation();
2718 if (
auto selectionOp = createSelectionOp(control))
2719 op = selectionOp.getOperation();
2728 mapper.
map(mergeBlock, &body.
back());
2730 collectBlocksInConstruct();
2751 OpBuilder builder(body);
2752 for (
auto *block : constructBlocks) {
2755 auto *newBlock = builder.createBlock(&body.
back());
2756 mapper.
map(block, newBlock);
2757 LLVM_DEBUG(logger.startLine() <<
"[cf] cloned block " << newBlock
2758 <<
" from block " << block <<
"\n");
2760 for (BlockArgument blockArg : block->getArguments()) {
2762 newBlock->addArgument(blockArg.getType(), blockArg.getLoc());
2763 mapper.
map(blockArg, newArg);
2764 LLVM_DEBUG(logger.startLine() <<
"[cf] remapped block argument "
2765 << blockArg <<
" to " << newArg <<
"\n");
2768 LLVM_DEBUG(logger.startLine()
2769 <<
"[cf] block " << block <<
" is a function entry block\n");
2772 for (
auto &op : *block)
2773 newBlock->push_back(op.
clone(mapper));
2777 auto remapOperands = [&](Operation *op) {
2779 if (Value mappedOp = mapper.
lookupOrNull(operand.get()))
2780 operand.set(mappedOp);
2783 succOp.set(mappedOp);
2785 for (
auto &block : body)
2786 block.walk(remapOperands);
2794 headerBlock->replaceAllUsesWith(mergeBlock);
2797 logger.startLine() <<
"[cf] after cloning and fixing references:\n";
2798 headerBlock->getParentOp()->print(logger.getOStream());
2799 logger.startLine() <<
"\n";
2803 if (!mergeBlock->args_empty()) {
2804 return mergeBlock->getParentOp()->emitError(
2805 "OpPhi in loop merge block unsupported");
2811 for (BlockArgument blockArg : headerBlock->getArguments())
2812 mergeBlock->addArgument(blockArg.getType(), blockArg.getLoc());
2816 SmallVector<Value, 4> blockArgs;
2817 if (!headerBlock->args_empty())
2818 blockArgs = {mergeBlock->args_begin(), mergeBlock->args_end()};
2822 builder.setInsertionPointToEnd(&body.front());
2823 spirv::BranchOp::create(builder, location, mapper.
lookupOrNull(headerBlock),
2824 ArrayRef<Value>(blockArgs));
2829 SmallVector<Value> valuesToYield;
2832 SmallVector<Value> outsideUses;
2846 for (BlockArgument blockArg : mergeBlock->getArguments()) {
2851 body.back().addArgument(blockArg.getType(), blockArg.getLoc());
2852 valuesToYield.push_back(body.back().getArguments().back());
2853 outsideUses.push_back(blockArg);
2858 LLVM_DEBUG(logger.startLine() <<
"[cf] cleaning up blocks after clone\n");
2861 for (
auto *block : constructBlocks)
2862 block->dropAllReferences();
2867 for (
Block *block : constructBlocks) {
2868 for (Operation &op : *block) {
2872 outsideUses.push_back(
result);
2875 for (BlockArgument &arg : block->getArguments()) {
2876 if (!arg.use_empty()) {
2878 outsideUses.push_back(arg);
2883 assert(valuesToYield.size() == outsideUses.size());
2887 if (!valuesToYield.empty()) {
2888 LLVM_DEBUG(logger.startLine()
2889 <<
"[cf] yielding values from the selection / loop region\n");
2892 auto mergeOps = body.back().getOps<spirv::MergeOp>();
2893 Operation *merge = llvm::getSingleElement(mergeOps);
2895 merge->setOperands(valuesToYield);
2903 builder.setInsertionPoint(&mergeBlock->front());
2905 Operation *newOp =
nullptr;
2908 newOp = spirv::LoopOp::create(builder, location,
2910 static_cast<spirv::LoopControl
>(control));
2912 newOp = spirv::SelectionOp::create(
2914 static_cast<spirv::SelectionControl
>(control));
2924 for (
unsigned i = 0, e = outsideUses.size(); i != e; ++i)
2925 outsideUses[i].replaceAllUsesWith(op->
getResult(i));
2931 mergeBlock->eraseArguments(0, mergeBlock->getNumArguments());
2938 for (
auto *block : constructBlocks) {
2939 if (!block->use_empty())
2940 return emitError(block->getParent()->getLoc(),
2941 "failed control flow structurization: "
2942 "block has uses outside of the "
2943 "enclosing selection/loop construct");
2944 for (Operation &op : *block)
2946 return op.
emitOpError(
"failed control flow structurization: value has "
2947 "uses outside of the "
2948 "enclosing selection/loop construct");
2949 for (BlockArgument &arg : block->getArguments())
2950 if (!arg.use_empty())
2951 return emitError(arg.getLoc(),
"failed control flow structurization: "
2952 "block argument has uses outside of the "
2953 "enclosing selection/loop construct");
2957 for (
auto *block : constructBlocks) {
2997 auto updateMergeInfo = [&](
Block *block) -> WalkResult {
2998 auto it = blockMergeInfo.find(block);
2999 if (it != blockMergeInfo.end()) {
3001 Location loc = it->second.loc;
3003 uint32_t nestedControl = it->second.control;
3007 return emitError(loc,
"failed control flow structurization: nested "
3008 "loop header block should be remapped!");
3010 Block *newContinue = it->second.continueBlock;
3014 return emitError(loc,
"failed control flow structurization: nested "
3015 "loop continue block should be remapped!");
3018 Block *newMerge = it->second.mergeBlock;
3020 newMerge = mappedTo;
3023 blockMergeInfo.
erase(it);
3024 blockMergeInfo.try_emplace(newHeader, loc, nestedControl, newMerge,
3031 if (block->walk(updateMergeInfo).wasInterrupted())
3039 LLVM_DEBUG(logger.startLine() <<
"[cf] changing entry block " << block
3040 <<
" to only contain a spirv.Branch op\n");
3044 builder.setInsertionPointToEnd(block);
3045 spirv::BranchOp::create(builder, location, mergeBlock);
3047 LLVM_DEBUG(logger.startLine() <<
"[cf] erasing block " << block <<
"\n");
3052 LLVM_DEBUG(logger.startLine()
3053 <<
"[cf] after structurizing construct with header block "
3054 << headerBlock <<
":\n"
3063 <<
"//----- [phi] start wiring up block arguments -----//\n";
3069 for (
const auto &info : blockPhiInfo) {
3070 Block *block = info.first.first;
3074 logger.startLine() <<
"[phi] block " << block <<
"\n";
3075 logger.startLine() <<
"[phi] before creating block argument:\n";
3077 logger.startLine() <<
"\n";
3083 opBuilder.setInsertionPoint(op);
3086 blockArgs.reserve(phiInfo.size());
3087 for (uint32_t valueId : phiInfo) {
3089 blockArgs.push_back(value);
3090 LLVM_DEBUG(logger.startLine() <<
"[phi] block argument " << value
3091 <<
" id = " << valueId <<
"\n");
3093 return emitError(unknownLoc,
"OpPhi references undefined value!");
3097 if (
auto branchOp = dyn_cast<spirv::BranchOp>(op)) {
3099 spirv::BranchOp::create(opBuilder, branchOp.getLoc(),
3100 branchOp.getTarget(), blockArgs);
3102 }
else if (
auto branchCondOp = dyn_cast<spirv::BranchConditionalOp>(op)) {
3103 assert((branchCondOp.getTrueBlock() ==
target ||
3104 branchCondOp.getFalseBlock() ==
target) &&
3105 "expected target to be either the true or false target");
3106 if (
target == branchCondOp.getTrueTarget())
3107 spirv::BranchConditionalOp::create(
3108 opBuilder, branchCondOp.getLoc(), branchCondOp.getCondition(),
3109 blockArgs, branchCondOp.getFalseBlockArguments(),
3110 branchCondOp.getBranchWeightsAttr(), branchCondOp.getTrueTarget(),
3111 branchCondOp.getFalseTarget());
3113 spirv::BranchConditionalOp::create(
3114 opBuilder, branchCondOp.getLoc(), branchCondOp.getCondition(),
3115 branchCondOp.getTrueBlockArguments(), blockArgs,
3116 branchCondOp.getBranchWeightsAttr(), branchCondOp.getTrueBlock(),
3117 branchCondOp.getFalseBlock());
3119 branchCondOp.erase();
3120 }
else if (
auto switchOp = dyn_cast<spirv::SwitchOp>(op)) {
3121 if (
target == switchOp.getDefaultTarget()) {
3125 spirv::SwitchOp::create(
3126 opBuilder, switchOp.getLoc(), switchOp.getSelector(),
3127 switchOp.getDefaultTarget(), blockArgs, literals,
3128 switchOp.getTargets(), targetOperands);
3132 auto it = llvm::find(targets,
target);
3133 assert(it != targets.end());
3134 size_t index = std::distance(targets.begin(), it);
3135 switchOp.getTargetOperandsMutable(
index).assign(blockArgs);
3138 return emitError(unknownLoc,
"unimplemented terminator for Phi creation");
3142 logger.startLine() <<
"[phi] after creating block argument:\n";
3144 logger.startLine() <<
"\n";
3147 blockPhiInfo.clear();
3152 <<
"//--- [phi] completed wiring up block arguments ---//\n";
3160 for (
auto [block, mergeInfo] : blockMergeInfoCopy) {
3162 if (mergeInfo.continueBlock)
3165 if (!block->mightHaveTerminator())
3168 Operation *terminator = block->getTerminator();
3171 if (!isa<spirv::BranchConditionalOp, spirv::SwitchOp>(terminator))
3175 bool splitHeaderMergeBlock =
false;
3176 for (
const auto &[_, mergeInfo] : blockMergeInfo) {
3177 if (mergeInfo.mergeBlock == block)
3178 splitHeaderMergeBlock =
true;
3185 if (!llvm::hasSingleElement(*block) || splitHeaderMergeBlock ||
3189 spirv::BranchOp::create(builder, block->getParent()->getLoc(), newBlock);
3193 blockMergeInfo.erase(block);
3194 blockMergeInfo.try_emplace(newBlock, mergeInfo);
3202 if (!options.enableControlFlowStructurization) {
3206 <<
"//----- [cf] skip structurizing control flow -----//\n";
3214 <<
"//----- [cf] start structurizing control flow -----//\n";
3219 logger.startLine() <<
"[cf] split conditional blocks\n";
3220 logger.startLine() <<
"\n";
3227 while (!blockMergeInfo.empty()) {
3228 Block *headerBlock = blockMergeInfo.
begin()->first;
3232 logger.startLine() <<
"[cf] header block " << headerBlock <<
":\n";
3233 headerBlock->
print(logger.getOStream());
3234 logger.startLine() <<
"\n";
3238 assert(mergeBlock &&
"merge block cannot be nullptr");
3240 return emitError(unknownLoc,
"OpPhi in loop merge block unimplemented");
3242 logger.startLine() <<
"[cf] merge block " << mergeBlock <<
":\n";
3243 mergeBlock->print(logger.getOStream());
3244 logger.startLine() <<
"\n";
3248 LLVM_DEBUG(
if (continueBlock) {
3249 logger.startLine() <<
"[cf] continue block " << continueBlock <<
":\n";
3250 continueBlock->print(logger.getOStream());
3251 logger.startLine() <<
"\n";
3255 blockMergeInfo.
erase(blockMergeInfo.begin());
3256 ControlFlowStructurizer structurizer(mergeInfo.
loc, mergeInfo.
control,
3257 blockMergeInfo, headerBlock,
3258 mergeBlock, continueBlock
3264 if (failed(structurizer.structurize()))
3271 <<
"//--- [cf] completed structurizing control flow ---//\n";
3284 auto fileName = debugInfoMap.lookup(debugLine->fileID).str();
3285 if (fileName.empty())
3286 fileName =
"<unknown>";
3298 if (operands.size() != 3)
3299 return emitError(unknownLoc,
"OpLine must have 3 operands");
3300 debugLine =
DebugLine{operands[0], operands[1], operands[2]};
3308 if (operands.size() < 2)
3309 return emitError(unknownLoc,
"OpString needs at least 2 operands");
3311 if (!debugInfoMap.lookup(operands[0]).empty())
3313 "duplicate debug string found for result <id> ")
3316 unsigned wordIndex = 1;
3318 if (wordIndex != operands.size())
3320 "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 getChecked(function_ref< InFlightDiagnostic()> emitError, MLIRContext *context, 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)
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)
LogicalResult processGlobalVariable(spirv::Opcode opcode, ArrayRef< uint32_t > operands)
Processes the OpVariable or OpUntypedVariableKHR instructions at current offset into binary.
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 processUntypedPointerType(ArrayRef< uint32_t > 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.
Type getUndefType(uint32_t id)
Get the type associated with the result <id> of an OpUndef.
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.
std::optional< std::pair< Type, SmallVector< uint32_t > > > getUndefComposite(uint32_t id)
Gets the type and constituent <id>s of the undef composite with the given <id>.
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 getChecked(function_ref< InFlightDiagnostic()> emitError, MLIRContext *context, std::tuple< Type, Dim, ImageDepthInfo, ImageArrayedInfo, ImageSamplingInfo, ImageSamplerUseInfo, ImageFormat > value)
static MatrixType getChecked(function_ref< InFlightDiagnostic()> emitError, Type columnType, uint32_t columnCount)
static NamedBarrierType get(MLIRContext *context)
static PointerType getChecked(function_ref< InFlightDiagnostic()> emitError, MLIRContext *context, 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)
static UntypedPointerType get(MLIRContext *context, StorageClass storageClass)
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.
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.