MLIR 24.0.0git
DeserializeOps.cpp
Go to the documentation of this file.
1//===- DeserializeOps.cpp - MLIR SPIR-V Deserialization (Ops) -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Deserializer methods for SPIR-V binary instructions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "Deserializer.h"
14
17#include "mlir/IR/Builders.h"
18#include "mlir/IR/Location.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/Support/Debug.h"
24#include <optional>
25
26using namespace mlir;
27
28#define DEBUG_TYPE "spirv-deserialization"
29
30//===----------------------------------------------------------------------===//
31// Utility Functions
32//===----------------------------------------------------------------------===//
33
34/// Extracts the opcode from the given first word of a SPIR-V instruction.
35static inline spirv::Opcode extractOpcode(uint32_t word) {
36 return static_cast<spirv::Opcode>(word & 0xffff);
37}
38
39/// Returns a NameLoc location from the given debug info string.
40static NameLoc getLocFromDebugInfoString(OpBuilder &builder, StringRef source) {
41 return NameLoc::get(builder.getStringAttr(source));
42}
43
44//===----------------------------------------------------------------------===//
45// Instruction
46//===----------------------------------------------------------------------===//
47
49 if (std::optional<std::pair<Attribute, Type>> constCompositeReplicateInfo =
51 Value &value = blockConstantMap[{opBuilder.getInsertionBlock(), id}];
52 if (!value)
53 value = spirv::EXTConstantCompositeReplicateOp::create(
54 opBuilder, unknownLoc, constCompositeReplicateInfo->second,
55 constCompositeReplicateInfo->first);
56 return value;
57 }
58 if (auto constInfo = getConstant(id)) {
59 // Materialize a `spirv.Constant` op once per block.
60 Value &value = blockConstantMap[{opBuilder.getInsertionBlock(), id}];
61 if (!value) {
62 Location loc = unknownLoc;
63 if (LocationAttr locAttr = constantLocMap.lookup(id))
64 loc = Location(locAttr);
65 value = spirv::ConstantOp::create(opBuilder, loc, constInfo->second,
66 constInfo->first);
67 }
68 return value;
69 }
70 if (auto varOp = getGlobalVariable(id)) {
71 auto addressOfOp =
72 spirv::AddressOfOp::create(opBuilder, unknownLoc, varOp.getType(),
73 SymbolRefAttr::get(varOp.getOperation()));
74 return addressOfOp.getPointer();
75 }
76 if (auto constOp = getSpecConstant(id)) {
77 auto referenceOfOp = spirv::ReferenceOfOp::create(
78 opBuilder, unknownLoc, constOp.getDefaultValue().getType(),
79 SymbolRefAttr::get(constOp.getOperation()));
80 return referenceOfOp.getReference();
81 }
82 if (SpecConstantCompositeOp specConstCompositeOp =
84 auto referenceOfOp = spirv::ReferenceOfOp::create(
85 opBuilder, unknownLoc, specConstCompositeOp.getType(),
86 SymbolRefAttr::get(specConstCompositeOp.getOperation()));
87 return referenceOfOp.getReference();
88 }
89 if (auto specConstCompositeReplicateOp =
91 auto referenceOfOp = spirv::ReferenceOfOp::create(
92 opBuilder, unknownLoc, specConstCompositeReplicateOp.getType(),
93 SymbolRefAttr::get(specConstCompositeReplicateOp.getOperation()));
94 return referenceOfOp.getReference();
95 }
96 if (auto specConstOperationInfo = getSpecConstantOperation(id)) {
98 id, specConstOperationInfo->enclodesOpcode,
99 specConstOperationInfo->resultTypeID,
100 specConstOperationInfo->enclosedOpOperands);
101 }
102 if (auto undef = getUndefType(id)) {
103 Value &value = blockConstantMap[{opBuilder.getInsertionBlock(), id}];
104 if (!value)
105 value = spirv::UndefOp::create(opBuilder, unknownLoc, undef);
106 return value;
107 }
108 if (auto [type, functionID] = getConstantFunctionPointer(id); type) {
109 Value &value = blockConstantMap[{opBuilder.getInsertionBlock(), id}];
110 if (!value)
111 value = spirv::INTELConstantFunctionPointerOp::create(
112 opBuilder, unknownLoc, type, getFunctionSymbol(functionID));
113 return value;
114 }
115 if (auto undefComposite = getUndefComposite(id)) {
116 std::pair<Block *, uint32_t> key = {opBuilder.getInsertionBlock(), id};
117 if (Value value = blockConstantMap.lookup(key))
118 return value;
119 // Recursion may rehash blockConstantMap, so insert last.
120 SmallVector<Value> constituents;
121 for (uint32_t constituentID : undefComposite->second)
122 constituents.push_back(getValue(constituentID));
123 Value value = spirv::CompositeConstructOp::create(
124 opBuilder, unknownLoc, undefComposite->first, constituents);
125 blockConstantMap[key] = value;
126 return value;
127 }
128 if (std::optional<spirv::GraphConstantARMOpMaterializationInfo>
129 graphConstantARMInfo = getGraphConstantARM(id)) {
130 IntegerAttr graphConstantID = graphConstantARMInfo->graphConstantID;
131 Type resultType = graphConstantARMInfo->resultType;
132 return spirv::GraphConstantARMOp::create(opBuilder, unknownLoc, resultType,
133 graphConstantID);
134 }
135 return valueMap.lookup(id);
136}
137
139 spirv::Opcode &opcode, ArrayRef<uint32_t> &operands,
140 std::optional<spirv::Opcode> expectedOpcode) {
141 auto binarySize = binary.size();
142 if (curOffset >= binarySize) {
143 return emitError(unknownLoc, "expected ")
144 << (expectedOpcode ? spirv::stringifyOpcode(*expectedOpcode)
145 : "more")
146 << " instruction";
147 }
148
149 // For each instruction, get its word count from the first word to slice it
150 // from the stream properly, and then dispatch to the instruction handler.
151
152 uint32_t wordCount = binary[curOffset] >> 16;
153
154 if (wordCount == 0)
155 return emitError(unknownLoc, "word count cannot be zero");
156
157 uint32_t nextOffset = curOffset + wordCount;
158 if (nextOffset > binarySize)
159 return emitError(unknownLoc, "insufficient words for the last instruction");
160
161 opcode = extractOpcode(binary[curOffset]);
162 operands = binary.slice(curOffset + 1, wordCount - 1);
163 curOffset = nextOffset;
164 return success();
165}
166
168 spirv::Opcode opcode, ArrayRef<uint32_t> &operands,
169 SmallVectorImpl<uint32_t> &mergedStorage) {
170 std::optional<spirv::Opcode> continuationOp = getContinuationOpcode(opcode);
171 if (!continuationOp)
172 return;
173
174 size_t binarySize = binary.size();
175 auto isNextContinuation = [&]() {
176 if (curOffset >= binarySize)
177 return false;
178 uint32_t wordCount = binary[curOffset] >> 16;
179 if (wordCount == 0 || curOffset + wordCount > binarySize)
180 return false;
181 return extractOpcode(binary[curOffset]) == *continuationOp;
182 };
183
184 if (!isNextContinuation())
185 return;
186
187 mergedStorage.assign(operands);
188 do {
189 spirv::Opcode contOpcode;
190 ArrayRef<uint32_t> contOperands;
191 if (failed(sliceInstruction(contOpcode, contOperands, *continuationOp)))
192 return;
193 llvm::append_range(mergedStorage, contOperands);
194 } while (isNextContinuation());
195 operands = mergedStorage;
196}
197
199 spirv::Opcode opcode, ArrayRef<uint32_t> operands, bool deferInstructions) {
200 LLVM_DEBUG(logger.startLine() << "[inst] processing instruction "
201 << spirv::stringifyOpcode(opcode) << "\n");
202
203 SmallVector<uint32_t, 0> mergedStorage;
204 mergeLongCompositeContinuations(opcode, operands, mergedStorage);
205
206 // First dispatch all the instructions whose opcode does not correspond to
207 // those that have a direct mirror in the SPIR-V dialect
208 switch (opcode) {
209 case spirv::Opcode::OpCapability:
210 return processCapability(operands);
211 case spirv::Opcode::OpExtension:
212 return processExtension(operands);
213 case spirv::Opcode::OpExtInst: {
215 operands.size() >= 4 ? extendedInstSets.find(operands[2])
216 : extendedInstSets.end();
217 if (setIt != extendedInstSets.end() && setIt->second == extGraphDebugInfo)
218 return processGraphDebugInfoExtInst(operands, deferInstructions);
219 return processExtInst(operands);
220 }
221 case spirv::Opcode::OpExtInstImport:
222 return processExtInstImport(operands);
223 case spirv::Opcode::OpMemberName:
224 return processMemberName(operands);
225 case spirv::Opcode::OpMemoryModel:
226 return processMemoryModel(operands);
227 case spirv::Opcode::OpEntryPoint:
228 case spirv::Opcode::OpExecutionMode:
229 case spirv::Opcode::OpExecutionModeId:
230 if (deferInstructions) {
231 deferredInstructions.emplace_back(opcode, operands);
232 return success();
233 }
234 break;
235 case spirv::Opcode::OpVariable:
236 if (isa<spirv::ModuleOp>(opBuilder.getBlock()->getParentOp())) {
237 return processGlobalVariable(opcode, operands);
238 }
239 if (operands.size() > 3 && undefCompositeMap.contains(operands[3])) {
240 return emitError(unknownLoc, "OpVariable initializer <id> ")
241 << operands[3]
242 << " has OpUndef constituents, which cannot be represented in "
243 "spirv.Variable";
244 }
245 break;
246 case spirv::Opcode::OpUntypedVariableKHR:
247 if (isa<spirv::ModuleOp>(opBuilder.getBlock()->getParentOp()))
248 return processGlobalVariable(opcode, operands);
249 break;
250 case spirv::Opcode::OpLine:
251 return processDebugLine(operands);
252 case spirv::Opcode::OpNoLine:
254 return success();
255 case spirv::Opcode::OpName:
256 return processName(operands);
257 case spirv::Opcode::OpString:
258 return processDebugString(operands);
259 case spirv::Opcode::OpModuleProcessed:
260 case spirv::Opcode::OpSource:
261 case spirv::Opcode::OpSourceContinued:
262 case spirv::Opcode::OpSourceExtension:
263 // TODO: This is debug information embedded in the binary which should be
264 // translated into the spirv.module.
265 return success();
266 case spirv::Opcode::OpTypeVoid:
267 case spirv::Opcode::OpTypeBool:
268 case spirv::Opcode::OpTypeInt:
269 case spirv::Opcode::OpTypeFloat:
270 case spirv::Opcode::OpTypeVector:
271 case spirv::Opcode::OpTypeMatrix:
272 case spirv::Opcode::OpTypeArray:
273 case spirv::Opcode::OpTypeFunction:
274 case spirv::Opcode::OpTypeImage:
275 case spirv::Opcode::OpTypeSampler:
276 case spirv::Opcode::OpTypeNamedBarrier:
277 case spirv::Opcode::OpTypeSampledImage:
278 case spirv::Opcode::OpTypeRuntimeArray:
279 case spirv::Opcode::OpTypeStruct:
280 case spirv::Opcode::OpTypePointer:
281 case spirv::Opcode::OpTypeUntypedPointerKHR:
282 case spirv::Opcode::OpTypeTensorARM:
283 case spirv::Opcode::OpTypeGraphARM:
284 case spirv::Opcode::OpTypeCooperativeMatrixKHR:
285 return processType(opcode, operands);
286 case spirv::Opcode::OpTypeForwardPointer:
287 return processTypeForwardPointer(operands);
288 case spirv::Opcode::OpConstant:
289 return processConstant(operands, /*isSpec=*/false);
290 case spirv::Opcode::OpSpecConstant:
291 return processConstant(operands, /*isSpec=*/true);
292 case spirv::Opcode::OpConstantComposite:
293 return processConstantComposite(operands);
294 case spirv::Opcode::OpConstantCompositeReplicateEXT:
296 case spirv::Opcode::OpSpecConstantComposite:
297 return processSpecConstantComposite(operands);
298 case spirv::Opcode::OpSpecConstantCompositeReplicateEXT:
300 case spirv::Opcode::OpSpecConstantOp:
301 return processSpecConstantOperation(operands);
302 case spirv::Opcode::OpConstantTrue:
303 return processConstantBool(/*isTrue=*/true, operands, /*isSpec=*/false);
304 case spirv::Opcode::OpSpecConstantTrue:
305 return processConstantBool(/*isTrue=*/true, operands, /*isSpec=*/true);
306 case spirv::Opcode::OpConstantFalse:
307 return processConstantBool(/*isTrue=*/false, operands, /*isSpec=*/false);
308 case spirv::Opcode::OpSpecConstantFalse:
309 return processConstantBool(/*isTrue=*/false, operands, /*isSpec=*/true);
310 case spirv::Opcode::OpConstantNull:
311 return processConstantNull(operands);
312 case spirv::Opcode::OpGraphConstantARM:
313 return processGraphConstantARM(operands);
314 case spirv::Opcode::OpDecorate:
315 case spirv::Opcode::OpDecorateId:
316 return processDecoration(operands);
317 case spirv::Opcode::OpMemberDecorate:
318 return processMemberDecoration(operands);
319 case spirv::Opcode::OpFunction:
320 return processFunction(operands);
321 case spirv::Opcode::OpGraphEntryPointARM:
322 if (deferInstructions) {
323 deferredInstructions.emplace_back(opcode, operands);
324 return success();
325 }
326 return processGraphEntryPointARM(operands);
327 case spirv::Opcode::OpGraphARM:
328 return processGraphARM(operands);
329 case spirv::Opcode::OpGraphSetOutputARM:
330 return processOpGraphSetOutputARM(operands);
331 case spirv::Opcode::OpGraphEndARM:
332 return processGraphEndARM(operands);
333 case spirv::Opcode::OpLabel:
334 return processLabel(operands);
335 case spirv::Opcode::OpBranch:
336 return processBranch(operands);
337 case spirv::Opcode::OpBranchConditional:
338 return processBranchConditional(operands);
339 case spirv::Opcode::OpSelectionMerge:
340 return processSelectionMerge(operands);
341 case spirv::Opcode::OpLoopMerge:
342 return processLoopMerge(operands);
343 case spirv::Opcode::OpPhi:
344 return processPhi(operands);
345 case spirv::Opcode::OpSwitch:
346 return processSwitch(operands);
347 case spirv::Opcode::OpUndef:
348 return processUndef(operands);
349 case spirv::Opcode::OpConstantFunctionPointerINTEL:
350 return processConstantFunctionPointer(operands);
351 default:
352 break;
353 }
354 return dispatchToAutogenDeserialization(opcode, operands);
355}
356
358 ArrayRef<uint32_t> words, StringRef opName, bool hasResult,
359 unsigned numOperands) {
360 SmallVector<Type, 1> resultTypes;
361 uint32_t valueID = 0;
362
363 size_t wordIndex = 0;
364 if (hasResult) {
365 if (wordIndex >= words.size())
366 return emitError(unknownLoc,
367 "expected result type <id> while deserializing for ")
368 << opName;
369
370 // Decode the type <id>
371 auto type = getType(words[wordIndex]);
372 if (!type)
373 return emitError(unknownLoc, "unknown type result <id>: ")
374 << words[wordIndex];
375 resultTypes.push_back(type);
376 ++wordIndex;
377
378 // Decode the result <id>
379 if (wordIndex >= words.size())
380 return emitError(unknownLoc,
381 "expected result <id> while deserializing for ")
382 << opName;
383 valueID = words[wordIndex];
384 ++wordIndex;
385 }
386
387 SmallVector<Value, 4> operands;
389
390 // Decode operands
391 size_t operandIndex = 0;
392 for (; operandIndex < numOperands && wordIndex < words.size();
393 ++operandIndex, ++wordIndex) {
394 auto arg = getValue(words[wordIndex]);
395 if (!arg)
396 return emitError(unknownLoc, "unknown result <id>: ") << words[wordIndex];
397 operands.push_back(arg);
398 }
399 if (operandIndex != numOperands) {
400 return emitError(
401 unknownLoc,
402 "found less operands than expected when deserializing for ")
403 << opName << "; only " << operandIndex << " of " << numOperands
404 << " processed";
405 }
406 if (wordIndex != words.size()) {
407 return emitError(
408 unknownLoc,
409 "found more operands than expected when deserializing for ")
410 << opName << "; only " << wordIndex << " of " << words.size()
411 << " processed";
412 }
413
414 // Attach attributes from decorations
415 if (decorations.count(valueID)) {
416 auto attrs = decorations[valueID].getAttrs();
417 attributes.append(attrs.begin(), attrs.end());
418 }
419
420 // Create the op and update bookkeeping maps
421 Location loc = createFileLineColLoc(opBuilder);
422 OperationState opState(loc, opName);
423 opState.addOperands(operands);
424 if (hasResult)
425 opState.addTypes(resultTypes);
426 opState.addAttributes(attributes);
427 Operation *op = opBuilder.create(opState);
428 if (hasResult)
429 valueMap[valueID] = op->getResult(0);
430
433
434 return success();
435}
436
438 if (operands.size() != 2) {
439 return emitError(unknownLoc, "OpUndef instruction must have two operands");
440 }
441 auto type = getType(operands[0]);
442 if (!type) {
443 return emitError(unknownLoc, "unknown type <id> with OpUndef instruction");
444 }
445 undefMap[operands[1]] = type;
446 return success();
447}
448
450 ArrayRef<uint32_t> operands) {
451 if (operands.size() != 3) {
452 return emitError(unknownLoc,
453 "OpConstantFunctionPointerINTEL must have 3 operands");
454 }
455 Type type = getType(operands[0]);
456 if (!type) {
457 return emitError(unknownLoc, "unknown type <id> with "
458 "OpConstantFunctionPointerINTEL instruction");
459 }
460 constantFunctionPointerMap[operands[1]] = {type, operands[2]};
461 return success();
462}
463
464LogicalResult
466 bool deferInstructions) {
467 if (deferInstructions) {
468 deferredInstructions.emplace_back(spirv::Opcode::OpExtInst, operands);
469 return success();
470 }
471
472 if (operands.size() < 4) {
473 return emitError(unknownLoc,
474 "OpExtInst must have at least 4 operands, result type "
475 "<id>, result <id>, set <id> and instruction opcode");
476 }
477
478 Type resultType = getType(operands[0]);
479 if (!resultType || !isVoidType(resultType))
480 return emitError(unknownLoc,
481 "DebugInfo instructions must have OpTypeVoid result type");
482
483 auto getDebugLoc = [&](uint32_t stringID) -> FailureOr<Location> {
485 debugInfoMap.find(stringID);
486 if (stringIt == debugInfoMap.end()) {
487 return emitError(unknownLoc, "undefined string <id> ")
488 << stringID << " in DebugInfo";
489 }
490 return Location(getLocFromDebugInfoString(opBuilder, stringIt->second));
491 };
492
493 if (!spirv::isValidGraphDebugInfoExtInst(operands[3]))
494 return emitError(unknownLoc, "unknown DebugInfo instruction opcode: ")
495 << operands[3];
496
497 auto instructionID = static_cast<spirv::GraphDebugInfoExtInst>(operands[3]);
498 switch (instructionID) {
500 if (operands.size() < 6)
501 return emitError(unknownLoc, "DebugGraph must have graph and string IDs");
502 uint32_t graphID = operands[4];
503 uint32_t stringID = operands[5];
505 graphMap.find(graphID);
506 if (graphIt == graphMap.end())
507 return emitError(unknownLoc, "undefined graph <id> ")
508 << graphID << " in DebugGraph";
509 FailureOr<Location> loc = getDebugLoc(stringID);
510 if (failed(loc))
511 return failure();
512 graphIt->second->setLoc(*loc);
513 break;
514 }
516 if (operands.size() < 7)
517 return emitError(unknownLoc, "DebugOperation must have graph, string and "
518 "instruction IDs");
519 uint32_t stringID = operands[5];
520 FailureOr<Location> loc = getDebugLoc(stringID);
521 if (failed(loc))
522 return failure();
523 SmallVector<uint32_t> operationIDs;
524 operationIDs.append(std::next(operands.begin(), 6), operands.end());
525 for (uint32_t operationID : operationIDs) {
526 DenseMap<uint32_t, Value>::iterator valueIt = valueMap.find(operationID);
527 if (valueIt == valueMap.end())
528 return emitError(unknownLoc, "undefined operation <id> ")
529 << operationID << " in DebugOperation";
530 valueIt->second.setLoc(*loc);
531 }
532 break;
533 }
535 if (operands.size() < 6)
536 return emitError(unknownLoc,
537 "DebugTensor must have tensor and string IDs");
538 uint32_t stringID = operands[5];
539 uint32_t tensorID = operands[4];
540 FailureOr<Location> loc = getDebugLoc(stringID);
541 if (failed(loc))
542 return failure();
543 if (constantMap.contains(tensorID)) {
544 constantLocMap[tensorID] = *loc;
545 break;
546 }
547 DenseMap<uint32_t, Value>::iterator valueIt = valueMap.find(tensorID);
548 if (valueIt == valueMap.end())
549 return emitError(unknownLoc, "undefined tensor <id> ")
550 << tensorID << " in DebugTensor";
551 valueIt->second.setLoc(*loc);
552 break;
553 }
554 }
555
556 return success();
557}
558
560 if (operands.size() < 4) {
561 return emitError(unknownLoc,
562 "OpExtInst must have at least 4 operands, result type "
563 "<id>, result <id>, set <id> and instruction opcode");
564 }
565 if (!extendedInstSets.count(operands[2])) {
566 return emitError(unknownLoc, "undefined set <id> in OpExtInst");
567 }
568 SmallVector<uint32_t, 4> slicedOperands;
569 slicedOperands.append(operands.begin(), std::next(operands.begin(), 2));
570 slicedOperands.append(std::next(operands.begin(), 4), operands.end());
572 extendedInstSets[operands[2]], operands[3], slicedOperands);
573}
574
575namespace mlir {
576namespace spirv {
577
578template <>
579LogicalResult
581 unsigned wordIndex = 0;
582 if (wordIndex >= words.size()) {
583 return emitError(unknownLoc,
584 "missing Execution Model specification in OpEntryPoint");
585 }
586 auto execModel = spirv::ExecutionModelAttr::get(
587 context, static_cast<spirv::ExecutionModel>(words[wordIndex++]));
588 if (wordIndex >= words.size()) {
589 return emitError(unknownLoc, "missing <id> in OpEntryPoint");
590 }
591 // Get the function <id>
592 auto fnID = words[wordIndex++];
593 // Get the function name
594 auto fnName = decodeStringLiteral(words, wordIndex);
595 // Verify that the function <id> matches the fnName
596 auto parsedFunc = getFunction(fnID);
597 if (!parsedFunc) {
598 return emitError(unknownLoc, "no function matching <id> ") << fnID;
599 }
600 if (parsedFunc.getName() != fnName) {
601 // The deserializer uses "spirv_fn_<id>" as the function name if the input
602 // SPIR-V blob does not contain a name for it. We should use a more clear
603 // indication for such case rather than relying on naming details.
604 if (!parsedFunc.getName().starts_with("spirv_fn_"))
605 return emitError(unknownLoc,
606 "function name mismatch between OpEntryPoint "
607 "and OpFunction with <id> ")
608 << fnID << ": " << fnName << " vs. " << parsedFunc.getName();
609 parsedFunc.setName(fnName);
610 }
612 while (wordIndex < words.size()) {
613 auto arg = getGlobalVariable(words[wordIndex]);
614 if (!arg) {
615 return emitError(unknownLoc, "undefined result <id> ")
616 << words[wordIndex] << " while decoding OpEntryPoint";
617 }
618 interface.push_back(SymbolRefAttr::get(arg.getOperation()));
619 wordIndex++;
620 }
621 spirv::EntryPointOp::create(
622 opBuilder, unknownLoc, execModel,
623 SymbolRefAttr::get(opBuilder.getContext(), fnName),
624 opBuilder.getArrayAttr(interface));
625 return success();
626}
627
628template <>
629LogicalResult
631 unsigned wordIndex = 0;
632 if (wordIndex >= words.size()) {
633 return emitError(unknownLoc,
634 "missing function result <id> in OpExecutionMode");
635 }
636 // Get the function <id> to get the name of the function
637 auto fnID = words[wordIndex++];
638 auto fn = getFunction(fnID);
639 if (!fn) {
640 return emitError(unknownLoc, "no function matching <id> ") << fnID;
641 }
642 // Get the Execution mode
643 if (wordIndex >= words.size()) {
644 return emitError(unknownLoc, "missing Execution Mode in OpExecutionMode");
645 }
646 auto execMode = spirv::ExecutionModeAttr::get(
647 context, static_cast<spirv::ExecutionMode>(words[wordIndex++]));
648
649 // Get the values
650 SmallVector<Attribute, 4> attrListElems;
651 while (wordIndex < words.size()) {
652 attrListElems.push_back(opBuilder.getI32IntegerAttr(words[wordIndex++]));
653 }
654 auto values = opBuilder.getArrayAttr(attrListElems);
655 spirv::ExecutionModeOp::create(
656 opBuilder, unknownLoc,
657 SymbolRefAttr::get(opBuilder.getContext(), fn.getName()), execMode,
658 values);
659 return success();
660}
661
662template <>
663LogicalResult
665 unsigned wordIndex = 0;
666 unsigned const wordsSize = words.size();
667 if (wordIndex >= wordsSize)
668 return emitError(unknownLoc,
669 "missing function result <id> in OpExecutionModeId");
670
671 // Get the function <id> to get the name of the function.
672 uint32_t fnID = words[wordIndex++];
673 FuncOp fn = getFunction(fnID);
674 if (!fn)
675 return emitError(unknownLoc, "no function matching <id> ") << fnID;
676
677 // Get the Execution mode.
678 if (wordIndex >= wordsSize)
679 return emitError(unknownLoc, "missing Execution Mode in OpExecutionModeId");
680
681 ExecutionModeAttr execMode = spirv::ExecutionModeAttr::get(
682 context, static_cast<spirv::ExecutionMode>(words[wordIndex++]));
683
684 // Get the values.
685 SmallVector<Attribute, 4> attrListElems;
686 while (wordIndex < words.size()) {
687 uint32_t id = words[wordIndex++];
688 if (Type type = getType(id)) {
689 attrListElems.push_back(TypeAttr::get(type));
690 } else if (std::optional<std::pair<Attribute, Type>> constInfo =
691 getConstant(id)) {
692 attrListElems.push_back(constInfo->first);
693 } else if (spirv::SpecConstantOp specConst = getSpecConstant(id)) {
694 attrListElems.push_back(SymbolRefAttr::get(specConst));
695 } else {
696 return emitError(unknownLoc, "unknown <id> ")
697 << id << " in OpExecutionModeId";
698 }
699 }
700 ArrayAttr values = opBuilder.getArrayAttr(attrListElems);
701 spirv::ExecutionModeIdOp::create(
702 opBuilder, unknownLoc,
703 SymbolRefAttr::get(opBuilder.getContext(), fn.getName()), execMode,
704 values);
705 return success();
706}
707
708template <>
709LogicalResult
711 if (operands.size() < 3) {
712 return emitError(unknownLoc,
713 "OpFunctionCall must have at least 3 operands");
714 }
715
716 Type resultType = getType(operands[0]);
717 if (!resultType) {
718 return emitError(unknownLoc, "undefined result type from <id> ")
719 << operands[0];
720 }
721
722 // Use null type to mean no result type.
723 if (isVoidType(resultType))
724 resultType = nullptr;
725
726 auto resultID = operands[1];
727 auto functionID = operands[2];
728
729 auto functionName = getFunctionSymbol(functionID);
730
731 SmallVector<Value, 4> arguments;
732 for (auto operand : llvm::drop_begin(operands, 3)) {
733 auto value = getValue(operand);
734 if (!value) {
735 return emitError(unknownLoc, "unknown <id> ")
736 << operand << " used by OpFunctionCall";
737 }
738 arguments.push_back(value);
739 }
740
741 auto opFunctionCall = spirv::FunctionCallOp::create(
742 opBuilder, unknownLoc, resultType,
743 SymbolRefAttr::get(opBuilder.getContext(), functionName), arguments);
744
745 if (auto it = decorations.find(resultID); it != decorations.end())
746 for (NamedAttribute attr : it->second)
747 opFunctionCall->setAttr(attr.getName(), attr.getValue());
748
749 if (resultType)
750 valueMap[resultID] = opFunctionCall.getResult(0);
751 return success();
752}
753
754template <>
756 ArrayRef<uint32_t> operands) {
757 if (operands.size() < 3) {
758 return emitError(
759 unknownLoc, "OpFunctionPointerCallINTEL must have at least 3 operands");
760 }
761
762 Type resultType = getType(operands[0]);
763 if (!resultType) {
764 return emitError(unknownLoc, "undefined result type from <id> ")
765 << operands[0];
766 }
767
768 if (isVoidType(resultType))
769 resultType = nullptr;
770
771 uint32_t resultID = operands[1];
773 for (uint32_t operand : llvm::drop_begin(operands, 2)) {
774 Value value = getValue(operand);
775 if (!value) {
776 return emitError(unknownLoc, "unknown <id> ")
777 << operand << " used by OpFunctionPointerCallINTEL";
778 }
779 values.push_back(value);
780 }
781
782 auto callOp = spirv::INTELFunctionPointerCallOp::create(
783 opBuilder, unknownLoc, resultType, values.front(),
784 ArrayRef(values).drop_front());
785
786 if (auto it = decorations.find(resultID); it != decorations.end())
787 for (NamedAttribute attr : it->second)
788 callOp->setAttr(attr.getName(), attr.getValue());
789
790 if (resultType)
791 valueMap[resultID] = callOp.getReturnValue();
792 return success();
793}
794
795template <>
796LogicalResult
798 SmallVector<Type, 1> resultTypes;
799 size_t wordIndex = 0;
800 SmallVector<Value, 4> operands;
802
803 if (wordIndex < words.size()) {
804 auto arg = getValue(words[wordIndex]);
805
806 if (!arg) {
807 return emitError(unknownLoc, "unknown result <id> : ")
808 << words[wordIndex];
809 }
810
811 operands.push_back(arg);
812 wordIndex++;
813 }
814
815 if (wordIndex < words.size()) {
816 auto arg = getValue(words[wordIndex]);
817
818 if (!arg) {
819 return emitError(unknownLoc, "unknown result <id> : ")
820 << words[wordIndex];
821 }
822
823 operands.push_back(arg);
824 wordIndex++;
825 }
826
827 bool isAlignedAttr = false;
828
829 if (wordIndex < words.size()) {
830 auto attrValue = words[wordIndex++];
831 auto attr = opBuilder.getAttr<spirv::MemoryAccessAttr>(
832 static_cast<spirv::MemoryAccess>(attrValue));
833 attributes.push_back(
834 opBuilder.getNamedAttr(attributeName<MemoryAccess>(), attr));
835 isAlignedAttr = (attrValue == 2);
836 }
837
838 if (isAlignedAttr && wordIndex < words.size()) {
839 attributes.push_back(opBuilder.getNamedAttr(
840 "alignment", opBuilder.getI32IntegerAttr(words[wordIndex++])));
841 }
842
843 if (wordIndex < words.size()) {
844 auto attrValue = words[wordIndex++];
845 auto attr = opBuilder.getAttr<spirv::MemoryAccessAttr>(
846 static_cast<spirv::MemoryAccess>(attrValue));
847 attributes.push_back(opBuilder.getNamedAttr("source_memory_access", attr));
848 }
849
850 if (wordIndex < words.size()) {
851 attributes.push_back(opBuilder.getNamedAttr(
852 "source_alignment", opBuilder.getI32IntegerAttr(words[wordIndex++])));
853 }
854
855 if (wordIndex != words.size()) {
856 return emitError(unknownLoc,
857 "found more operands than expected when deserializing "
858 "spirv::CopyMemoryOp, only ")
859 << wordIndex << " of " << words.size() << " processed";
860 }
861
862 Location loc = createFileLineColLoc(opBuilder);
863 spirv::CopyMemoryOp::Properties properties{};
864 spirv::CopyMemoryOp::populateDefaultProperties(
865 OperationName(spirv::CopyMemoryOp::getOperationName(),
866 opBuilder.getContext()),
867 properties);
868 if (failed(spirv::CopyMemoryOp::setPropertiesFromAttr(
869 properties, opBuilder.getDictionaryAttr(attributes),
870 [&]() { return emitError(loc); })))
871 return failure();
872 spirv::CopyMemoryOp::create(opBuilder, loc, resultTypes, operands, properties,
873 /*discardableAttributes=*/{});
874
875 return success();
876}
877
878template <>
880 ArrayRef<uint32_t> words) {
881 if (words.size() != 4) {
882 return emitError(unknownLoc,
883 "expected 4 words in GenericCastToPtrExplicitOp"
884 " but got : ")
885 << words.size();
886 }
887 SmallVector<Type, 1> resultTypes;
888 SmallVector<Value, 4> operands;
889 uint32_t valueID = 0;
890 auto type = getType(words[0]);
891
892 if (!type)
893 return emitError(unknownLoc, "unknown type result <id> : ") << words[0];
894 resultTypes.push_back(type);
895
896 valueID = words[1];
897
898 auto arg = getValue(words[2]);
899 if (!arg)
900 return emitError(unknownLoc, "unknown result <id> : ") << words[2];
901 operands.push_back(arg);
902
903 Location loc = createFileLineColLoc(opBuilder);
904 Operation *op = spirv::GenericCastToPtrExplicitOp::create(
905 opBuilder, loc, resultTypes, operands);
906 valueMap[valueID] = op->getResult(0);
907 return success();
908}
909
910template <>
911LogicalResult
913 if (words.size() != 2)
914 return emitError(unknownLoc, "OpAbortKHR must have two operands");
915
916 Type messageType = getType(words[0]);
917 if (!messageType)
918 return emitError(unknownLoc, "unknown type <id> : ") << words[0];
919
920 Value message = getValue(words[1]);
921 if (!message)
922 return emitError(unknownLoc, "unknown <id> : ") << words[1];
923
924 // Only the case where Message Type is the type of Message is modeled.
925 if (message.getType() != messageType)
926 return emitError(unknownLoc, "OpAbortKHR Message Type ")
927 << messageType << " differs from the type of Message "
928 << message.getType();
929
930 spirv::KHRAbortOp::create(opBuilder, createFileLineColLoc(opBuilder),
931 message);
932 clearDebugLine();
933 return success();
934}
935
936// Pull in auto-generated Deserializer::dispatchToAutogenDeserialization() and
937// various Deserializer::processOp<...>() specializations.
938#define GET_DESERIALIZATION_FNS
939#include "mlir/Dialect/SPIRV/IR/SPIRVSerialization.inc"
940
941} // namespace spirv
942} // namespace mlir
return success()
static spirv::Opcode extractOpcode(uint32_t word)
Extracts the opcode from the given first word of a SPIR-V instruction.
static NameLoc getLocFromDebugInfoString(OpBuilder &builder, StringRef source)
Returns a NameLoc location from the given debug info string.
StringAttr getStringAttr(const Twine &bytes)
Definition Builders.cpp:271
Location objects represent source locations information in MLIR.
Definition Location.h:32
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:166
StringAttr getName() const
Return the name of the attribute.
Attribute getValue() const
Return the value of the attribute.
Definition Attributes.h:181
This class helps build Operations.
Definition Builders.h:210
This class provides the API for ops that are known to be terminators.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:803
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
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.
Definition Operation.cpp:65
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
Value materializeSpecConstantOperation(uint32_t resultID, spirv::Opcode enclosedOpcode, uint32_t resultTypeID, ArrayRef< uint32_t > enclosedOpOperands)
Materializes/emits an OpSpecConstantOp instruction.
Value getValue(uint32_t id)
Get the Value associated with a result <id>.
std::optional< SpecConstOperationMaterializationInfo > getSpecConstantOperation(uint32_t id)
Gets the info needed to materialize the spec constant operation op associated with the given <id>.
LogicalResult dispatchToAutogenDeserialization(spirv::Opcode opcode, ArrayRef< uint32_t > words)
Method to dispatch to the specialized deserialization function for an operation in SPIR-V dialect tha...
LogicalResult processGraphDebugInfoExtInst(ArrayRef< uint32_t > operands, bool deferInstructions)
Processes a SPIR-V OpExtInst with given operands for a NonSemantic.Graph.DebugInfo instruction.
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 processGraphARM(ArrayRef< uint32_t > operands)
LogicalResult processConstantFunctionPointer(ArrayRef< uint32_t > operands)
Processes an OpConstantFunctionPointerINTEL instruction.
LogicalResult processLabel(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpLabel instruction with the given operands.
LogicalResult processExtInst(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpExtInst with given 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 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>.
spirv::EXTSpecConstantCompositeReplicateOp getSpecConstantCompositeReplicate(uint32_t id)
Gets the replicated composite specialization constant with the given result <id>.
LogicalResult processOp(ArrayRef< uint32_t > words)
Method to deserialize an operation in the SPIR-V dialect that is a mirror of an instruction in the SP...
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.
std::pair< Type, uint32_t > getConstantFunctionPointer(uint32_t id)
Gets the type and function <id> of an OpConstantFunctionPointerINTEL.
LogicalResult processGraphEntryPointARM(ArrayRef< uint32_t > operands)
LogicalResult processFunction(ArrayRef< uint32_t > operands)
Creates a deserializer for the given SPIR-V binary module.
bool isVoidType(Type type) const
Returns true if the given type is for SPIR-V void type.
LogicalResult processDebugString(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpString instruction with the given operands.
LogicalResult dispatchToExtensionSetAutogenDeserialization(StringRef extensionSetName, uint32_t instructionID, ArrayRef< uint32_t > words)
Dispatches the deserialization of extended instruction set operation based on the extended instructio...
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...
void mergeLongCompositeContinuations(spirv::Opcode opcode, ArrayRef< uint32_t > &operands, SmallVectorImpl< uint32_t > &mergedStorage)
If opcode is a SPV_INTEL_long_composites splittable opcode and the next binary instruction(s) are mat...
LogicalResult processTypeForwardPointer(ArrayRef< uint32_t > operands)
LogicalResult processSwitch(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpSwitch instruction with the given operands.
LogicalResult processOpWithoutGrammarAttr(ArrayRef< uint32_t > words, StringRef opName, bool hasResult, unsigned numOperands)
Processes a SPIR-V instruction from the given operands.
LogicalResult processGraphEndARM(ArrayRef< uint32_t > operands)
LogicalResult processConstantComposite(ArrayRef< uint32_t > operands)
Processes a SPIR-V OpConstantComposite instruction with the given 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 processUndef(ArrayRef< uint32_t > operands)
Processes a OpUndef instruction.
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>.
std::optional< spirv::Opcode > getContinuationOpcode(spirv::Opcode parent)
Returns the SPV_INTEL_long_composites continuation opcode that may follow parent, or std::nullopt if ...
constexpr bool isValidGraphDebugInfoExtInst(uint32_t opcode)
constexpr llvm::StringLiteral extGraphDebugInfo
Extension set name for non-semantic graph debug info.
StringRef decodeStringLiteral(ArrayRef< uint32_t > words, unsigned &wordIndex)
Decodes a string literal in words starting at wordIndex.
GraphDebugInfoExtInst
Instruction opcodes in the NonSemantic.Graph.DebugInfo.1 extended instruction set.
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
This represents an operation in an abstracted form, suitable for use with the builder APIs.
void addOperands(ValueRange newOperands)
void addAttributes(ArrayRef< NamedAttribute > newAttributes)
Add an array of named attributes.
void addTypes(ArrayRef< Type > newTypes)