1//===- Deserializer.h - MLIR SPIR-V Deserializer ----------------*- C++ -*-===//
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 declares the SPIR-V binary to MLIR SPIR-V module deserializer.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef MLIR_TARGET_SPIRV_DESERIALIZER_H
14#define MLIR_TARGET_SPIRV_DESERIALIZER_H
15
16#include "mlir/Dialect/SPIRV/IR/SPIRVEnums.h"
17#include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
18#include "mlir/IR/Builders.h"
19#include "mlir/Target/SPIRV/Deserialization.h"
20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/SetVector.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/Support/ScopedPrinter.h"
24#include <cstdint>
25#include <optional>
26
27namespace mlir {
28namespace spirv {
29
30//===----------------------------------------------------------------------===//
31// Utility Definitions
32//===----------------------------------------------------------------------===//
33
34/// A struct for containing a header block's merge and continue targets.
35///
36/// This struct is used to track original structured control flow info from
37/// SPIR-V blob. This info will be used to create
38/// spirv.mlir.selection/spirv.mlir.loop later.
39struct BlockMergeInfo {
40 Block *mergeBlock;
41 Block *continueBlock; // nullptr for spirv.mlir.selection
42 Location loc;
43 uint32_t control; // Selection/loop control
44
45 BlockMergeInfo(Location location, uint32_t control)
46 : mergeBlock(nullptr), continueBlock(nullptr), loc(location),
47 control(control) {}
48 BlockMergeInfo(Location location, uint32_t control, Block *m,
49 Block *c = nullptr)
50 : mergeBlock(m), continueBlock(c), loc(location), control(control) {}
51};
52
53/// A struct for containing OpLine instruction information.
54struct DebugLine {
55 uint32_t fileID;
56 uint32_t line;
57 uint32_t column;
58};
59
60/// Map from a selection/loop's header block to its merge (and continue) target.
61using BlockMergeInfoMap = DenseMap<Block *, BlockMergeInfo>;
62
63/// A "deferred struct type" is a struct type with one or more member types not
64/// known when the Deserializer first encounters the struct. This happens, for
65/// example, with recursive structs where a pointer to the struct type is
66/// forward declared through OpTypeForwardPointer in the SPIR-V module before
67/// the struct declaration; the actual pointer to struct type should be defined
68/// later through an OpTypePointer. For example, the following C struct:
69///
70/// struct A {
71/// A* next;
72/// };
73///
74/// would be represented in the SPIR-V module as:
75///
76/// OpName %A "A"
77/// OpTypeForwardPointer %APtr Generic
78/// %A = OpTypeStruct %APtr
79/// %APtr = OpTypePointer Generic %A
80///
81/// This means that the spirv::StructType cannot be fully constructed directly
82/// when the Deserializer encounters it. Instead we create a
83/// DeferredStructTypeInfo that contains all the information we know about the
84/// spirv::StructType. Once all forward references for the struct are resolved,
85/// the struct's body is set with all member info.
86struct DeferredStructTypeInfo {
87 spirv::StructType deferredStructType;
88
89 // A list of all unresolved member types for the struct. First element of each
90 // item is operand ID, second element is member index in the struct.
91 SmallVector<std::pair<uint32_t, unsigned>, 0> unresolvedMemberTypes;
92
93 // The list of member types. For unresolved members, this list contains
94 // place-holder empty types that will be updated later.
95 SmallVector<Type, 4> memberTypes;
96 SmallVector<spirv::StructType::OffsetInfo, 0> offsetInfo;
97 SmallVector<spirv::StructType::MemberDecorationInfo, 0> memberDecorationsInfo;
98};
99
100/// A struct that collects the info needed to materialize/emit a
101/// SpecConstantOperation op.
102struct SpecConstOperationMaterializationInfo {
103 spirv::Opcode enclodesOpcode;
104 uint32_t resultTypeID;
105 SmallVector<uint32_t> enclosedOpOperands;
106};
107
108//===----------------------------------------------------------------------===//
109// Deserializer Declaration
110//===----------------------------------------------------------------------===//
111
112/// A SPIR-V module serializer.
113///
114/// A SPIR-V binary module is a single linear stream of instructions; each
115/// instruction is composed of 32-bit words. The first word of an instruction
116/// records the total number of words of that instruction using the 16
117/// higher-order bits. So this deserializer uses that to get instruction
118/// boundary and parse instructions and build a SPIR-V ModuleOp gradually.
119///
120// TODO: clean up created ops on errors
121class Deserializer {
122public:
123 /// Creates a deserializer for the given SPIR-V `binary` module.
124 /// The SPIR-V ModuleOp will be created into `context.
125 explicit Deserializer(ArrayRef<uint32_t> binary, MLIRContext *context,
126 const DeserializationOptions &options);
127
128 /// Deserializes the remembered SPIR-V binary module.
129 LogicalResult deserialize();
130
131 /// Collects the final SPIR-V ModuleOp.
132 OwningOpRef<spirv::ModuleOp> collect();
133
134private:
135 //===--------------------------------------------------------------------===//
136 // Module structure
137 //===--------------------------------------------------------------------===//
138
139 /// Initializes the `module` ModuleOp in this deserializer instance.
140 OwningOpRef<spirv::ModuleOp> createModuleOp();
141
142 /// Processes SPIR-V module header in `binary`.
143 LogicalResult processHeader();
144
145 /// Processes the SPIR-V OpCapability with `operands` and updates bookkeeping
146 /// in the deserializer.
147 LogicalResult processCapability(ArrayRef<uint32_t> operands);
148
149 /// Processes the SPIR-V OpExtension with `operands` and updates bookkeeping
150 /// in the deserializer.
151 LogicalResult processExtension(ArrayRef<uint32_t> words);
152
153 /// Processes the SPIR-V OpExtInstImport with `operands` and updates
154 /// bookkeeping in the deserializer.
155 LogicalResult processExtInstImport(ArrayRef<uint32_t> words);
156
157 /// Attaches (version, capabilities, extensions) triple to `module` as an
158 /// attribute.
159 void attachVCETriple();
160
161 /// Processes the SPIR-V OpMemoryModel with `operands` and updates `module`.
162 LogicalResult processMemoryModel(ArrayRef<uint32_t> operands);
163
164 /// Process SPIR-V OpName with `operands`.
165 LogicalResult processName(ArrayRef<uint32_t> operands);
166
167 /// Processes an OpDecorate instruction.
168 LogicalResult processDecoration(ArrayRef<uint32_t> words);
169
170 // Processes an OpMemberDecorate instruction.
171 LogicalResult processMemberDecoration(ArrayRef<uint32_t> words);
172
173 /// Processes an OpMemberName instruction.
174 LogicalResult processMemberName(ArrayRef<uint32_t> words);
175
176 /// Gets the function op associated with a result <id> of OpFunction.
177 spirv::FuncOp getFunction(uint32_t id) { return funcMap.lookup(Val: id); }
178
179 /// Processes the SPIR-V function at the current `offset` into `binary`.
180 /// The operands to the OpFunction instruction is passed in as ``operands`.
181 /// This method processes each instruction inside the function and dispatches
182 /// them to their handler method accordingly.
183 LogicalResult processFunction(ArrayRef<uint32_t> operands);
184
185 /// Processes OpFunctionEnd and finalizes function. This wires up block
186 /// argument created from OpPhi instructions and also structurizes control
187 /// flow.
188 LogicalResult processFunctionEnd(ArrayRef<uint32_t> operands);
189
190 /// Gets the constant's attribute and type associated with the given <id>.
191 std::optional<std::pair<Attribute, Type>> getConstant(uint32_t id);
192
193 /// Gets the replicated composite constant's attribute and type associated
194 /// with the given <id>.
195 std::optional<std::pair<Attribute, Type>>
196 getConstantCompositeReplicate(uint32_t id);
197
198 /// Gets the info needed to materialize the spec constant operation op
199 /// associated with the given <id>.
200 std::optional<SpecConstOperationMaterializationInfo>
201 getSpecConstantOperation(uint32_t id);
202
203 /// Gets the constant's integer attribute with the given <id>. Returns a
204 /// null IntegerAttr if the given is not registered or does not correspond
205 /// to an integer constant.
206 IntegerAttr getConstantInt(uint32_t id);
207
208 /// Returns a symbol to be used for the function name with the given
209 /// result <id>. This tries to use the function's OpName if
210 /// exists; otherwise creates one based on the <id>.
211 std::string getFunctionSymbol(uint32_t id);
212
213 /// Returns a symbol to be used for the specialization constant with the given
214 /// result <id>. This tries to use the specialization constant's OpName if
215 /// exists; otherwise creates one based on the <id>.
216 std::string getSpecConstantSymbol(uint32_t id);
217
218 /// Gets the specialization constant with the given result <id>.
219 spirv::SpecConstantOp getSpecConstant(uint32_t id) {
220 return specConstMap.lookup(Val: id);
221 }
222
223 /// Gets the composite specialization constant with the given result <id>.
224 spirv::SpecConstantCompositeOp getSpecConstantComposite(uint32_t id) {
225 return specConstCompositeMap.lookup(Val: id);
226 }
227
228 /// Gets the replicated composite specialization constant with the given
229 /// result <id>.
230 spirv::EXTSpecConstantCompositeReplicateOp
231 getSpecConstantCompositeReplicate(uint32_t id) {
232 return specConstCompositeReplicateMap.lookup(Val: id);
233 }
234
235 /// Creates a spirv::SpecConstantOp.
236 spirv::SpecConstantOp createSpecConstant(Location loc, uint32_t resultID,
237 TypedAttr defaultValue);
238
239 /// Processes the OpVariable instructions at current `offset` into `binary`.
240 /// It is expected that this method is used for variables that are to be
241 /// defined at module scope and will be deserialized into a
242 /// spirv.GlobalVariable instruction.
243 LogicalResult processGlobalVariable(ArrayRef<uint32_t> operands);
244
245 /// Gets the global variable associated with a result <id> of OpVariable.
246 spirv::GlobalVariableOp getGlobalVariable(uint32_t id) {
247 return globalVariableMap.lookup(Val: id);
248 }
249
250 /// Sets the function argument's attributes. |argID| is the function
251 /// argument's result <id>, and |argIndex| is its index in the function's
252 /// argument list.
253 LogicalResult setFunctionArgAttrs(uint32_t argID,
254 SmallVectorImpl<Attribute> &argAttrs,
255 size_t argIndex);
256
257 /// Gets the symbol name from the name of decoration.
258 StringAttr getSymbolDecoration(StringRef decorationName) {
259 auto attrName = llvm::convertToSnakeFromCamelCase(input: decorationName);
260 return opBuilder.getStringAttr(bytes: attrName);
261 }
262
263 /// Move a conditional branch into a separate basic block to avoid unnecessary
264 /// sinking of defs that may be required outside a selection region. This
265 /// function also ensures that a single block cannot be a header block of one
266 /// selection construct and the merge block of another.
267 LogicalResult splitConditionalBlocks();
268
269 //===--------------------------------------------------------------------===//
270 // Type
271 //===--------------------------------------------------------------------===//
272
273 /// Gets type for a given result <id>.
274 Type getType(uint32_t id) { return typeMap.lookup(Val: id); }
275
276 /// Get the type associated with the result <id> of an OpUndef.
277 Type getUndefType(uint32_t id) { return undefMap.lookup(Val: id); }
278
279 /// Returns true if the given `type` is for SPIR-V void type.
280 bool isVoidType(Type type) const { return isa<NoneType>(Val: type); }
281
282 /// Processes a SPIR-V type instruction with given `opcode` and `operands` and
283 /// registers the type into `module`.
284 LogicalResult processType(spirv::Opcode opcode, ArrayRef<uint32_t> operands);
285
286 LogicalResult processOpTypePointer(ArrayRef<uint32_t> operands);
287
288 LogicalResult processArrayType(ArrayRef<uint32_t> operands);
289
290 LogicalResult processCooperativeMatrixTypeKHR(ArrayRef<uint32_t> operands);
291
292 LogicalResult processCooperativeMatrixTypeNV(ArrayRef<uint32_t> operands);
293
294 LogicalResult processFunctionType(ArrayRef<uint32_t> operands);
295
296 LogicalResult processImageType(ArrayRef<uint32_t> operands);
297
298 LogicalResult processSampledImageType(ArrayRef<uint32_t> operands);
299
300 LogicalResult processRuntimeArrayType(ArrayRef<uint32_t> operands);
301
302 LogicalResult processStructType(ArrayRef<uint32_t> operands);
303
304 LogicalResult processMatrixType(ArrayRef<uint32_t> operands);
305
306 LogicalResult processTensorARMType(ArrayRef<uint32_t> operands);
307
308 LogicalResult processTypeForwardPointer(ArrayRef<uint32_t> operands);
309
310 //===--------------------------------------------------------------------===//
311 // Constant
312 //===--------------------------------------------------------------------===//
313
314 /// Processes a SPIR-V Op{|Spec}Constant instruction with the given
315 /// `operands`. `isSpec` indicates whether this is a specialization constant.
316 LogicalResult processConstant(ArrayRef<uint32_t> operands, bool isSpec);
317
318 /// Processes a SPIR-V Op{|Spec}Constant{True|False} instruction with the
319 /// given `operands`. `isSpec` indicates whether this is a specialization
320 /// constant.
321 LogicalResult processConstantBool(bool isTrue, ArrayRef<uint32_t> operands,
322 bool isSpec);
323
324 /// Processes a SPIR-V OpConstantComposite instruction with the given
325 /// `operands`.
326 LogicalResult processConstantComposite(ArrayRef<uint32_t> operands);
327
328 /// Processes a SPIR-V OpConstantCompositeReplicateEXT instruction with
329 /// the given `operands`.
330 LogicalResult
331 processConstantCompositeReplicateEXT(ArrayRef<uint32_t> operands);
332
333 /// Processes a SPIR-V OpSpecConstantComposite instruction with the given
334 /// `operands`.
335 LogicalResult processSpecConstantComposite(ArrayRef<uint32_t> operands);
336
337 /// Processes a SPIR-V OpSpecConstantCompositeReplicateEXT instruction with
338 /// the given `operands`.
339 LogicalResult
340 processSpecConstantCompositeReplicateEXT(ArrayRef<uint32_t> operands);
341
342 /// Processes a SPIR-V OpSpecConstantOp instruction with the given
343 /// `operands`.
344 LogicalResult processSpecConstantOperation(ArrayRef<uint32_t> operands);
345
346 /// Materializes/emits an OpSpecConstantOp instruction.
347 Value materializeSpecConstantOperation(uint32_t resultID,
348 spirv::Opcode enclosedOpcode,
349 uint32_t resultTypeID,
350 ArrayRef<uint32_t> enclosedOpOperands);
351
352 /// Processes a SPIR-V OpConstantNull instruction with the given `operands`.
353 LogicalResult processConstantNull(ArrayRef<uint32_t> operands);
354
355 //===--------------------------------------------------------------------===//
356 // Debug
357 //===--------------------------------------------------------------------===//
358
359 /// Discontinues any source-level location information that might be active
360 /// from a previous OpLine instruction.
361 void clearDebugLine();
362
363 /// Creates a FileLineColLoc with the OpLine location information.
364 Location createFileLineColLoc(OpBuilder opBuilder);
365
366 /// Processes a SPIR-V OpLine instruction with the given `operands`.
367 LogicalResult processDebugLine(ArrayRef<uint32_t> operands);
368
369 /// Processes a SPIR-V OpString instruction with the given `operands`.
370 LogicalResult processDebugString(ArrayRef<uint32_t> operands);
371
372 //===--------------------------------------------------------------------===//
373 // Control flow
374 //===--------------------------------------------------------------------===//
375
376 /// Returns the block for the given label <id>.
377 Block *getBlock(uint32_t id) const { return blockMap.lookup(Val: id); }
378
379 // In SPIR-V, structured control flow is explicitly declared using merge
380 // instructions (OpSelectionMerge and OpLoopMerge). In the SPIR-V dialect,
381 // we use spirv.mlir.selection and spirv.mlir.loop to group structured control
382 // flow. The deserializer need to turn structured control flow marked with
383 // merge instructions into using spirv.mlir.selection/spirv.mlir.loop ops.
384 //
385 // Because structured control flow can nest and the basic block order have
386 // flexibility, we cannot isolate a structured selection/loop without
387 // deserializing all the blocks. So we use the following approach:
388 //
389 // 1. Deserialize all basic blocks in a function and create MLIR blocks for
390 // them into the function's region. In the meanwhile, keep a map between
391 // selection/loop header blocks to their corresponding merge (and continue)
392 // target blocks.
393 // 2. For each selection/loop header block, recursively get all basic blocks
394 // reachable (except the merge block) and put them in a newly created
395 // spirv.mlir.selection/spirv.mlir.loop's region. Structured control flow
396 // guarantees that we enter and exit in structured ways and the construct
397 // is nestable.
398 // 3. Put the new spirv.mlir.selection/spirv.mlir.loop op at the beginning of
399 // the
400 // old merge block and redirect all branches to the old header block to the
401 // old merge block (which contains the spirv.mlir.selection/spirv.mlir.loop
402 // op now).
403
404 /// For OpPhi instructions, we use block arguments to represent them. OpPhi
405 /// encodes a list of (value, predecessor) pairs. At the time of handling the
406 /// block containing an OpPhi instruction, the predecessor block might not be
407 /// processed yet, also the value sent by it. So we need to defer handling
408 /// the block argument from the predecessors. We use the following approach:
409 ///
410 /// 1. For each OpPhi instruction, add a block argument to the current block
411 /// in construction. Record the block argument in `valueMap` so its uses
412 /// can be resolved. For the list of (value, predecessor) pairs, update
413 /// `blockPhiInfo` for bookkeeping.
414 /// 2. After processing all blocks, loop over `blockPhiInfo` to fix up each
415 /// block recorded there to create the proper block arguments on their
416 /// terminators.
417
418 /// A data structure for containing a SPIR-V block's phi info. It will be
419 /// represented as block argument in SPIR-V dialect.
420 using BlockPhiInfo =
421 SmallVector<uint32_t, 2>; // The result <id> of the values sent
422
423 /// Gets or creates the block corresponding to the given label <id>. The newly
424 /// created block will always be placed at the end of the current function.
425 Block *getOrCreateBlock(uint32_t id);
426
427 LogicalResult processBranch(ArrayRef<uint32_t> operands);
428
429 LogicalResult processBranchConditional(ArrayRef<uint32_t> operands);
430
431 /// Processes a SPIR-V OpLabel instruction with the given `operands`.
432 LogicalResult processLabel(ArrayRef<uint32_t> operands);
433
434 /// Processes a SPIR-V OpSelectionMerge instruction with the given `operands`.
435 LogicalResult processSelectionMerge(ArrayRef<uint32_t> operands);
436
437 /// Processes a SPIR-V OpLoopMerge instruction with the given `operands`.
438 LogicalResult processLoopMerge(ArrayRef<uint32_t> operands);
439
440 /// Processes a SPIR-V OpPhi instruction with the given `operands`.
441 LogicalResult processPhi(ArrayRef<uint32_t> operands);
442
443 /// Creates block arguments on predecessors previously recorded when handling
444 /// OpPhi instructions.
445 LogicalResult wireUpBlockArgument();
446
447 /// Extracts blocks belonging to a structured selection/loop into a
448 /// spirv.mlir.selection/spirv.mlir.loop op. This method iterates until all
449 /// blocks declared as selection/loop headers are handled.
450 LogicalResult structurizeControlFlow();
451
452 //===--------------------------------------------------------------------===//
453 // Instruction
454 //===--------------------------------------------------------------------===//
455
456 /// Get the Value associated with a result <id>.
457 ///
458 /// This method materializes normal constants and inserts "casting" ops
459 /// (`spirv.mlir.addressof` and `spirv.mlir.referenceof`) to turn an symbol
460 /// into a SSA value for handling uses of module scope constants/variables in
461 /// functions.
462 Value getValue(uint32_t id);
463
464 /// Slices the first instruction out of `binary` and returns its opcode and
465 /// operands via `opcode` and `operands` respectively. Returns failure if
466 /// there is no more remaining instructions (`expectedOpcode` will be used to
467 /// compose the error message) or the next instruction is malformed.
468 LogicalResult
469 sliceInstruction(spirv::Opcode &opcode, ArrayRef<uint32_t> &operands,
470 std::optional<spirv::Opcode> expectedOpcode = std::nullopt);
471
472 /// Processes a SPIR-V instruction with the given `opcode` and `operands`.
473 /// This method is the main entrance for handling SPIR-V instruction; it
474 /// checks the instruction opcode and dispatches to the corresponding handler.
475 /// Processing of Some instructions (like OpEntryPoint and OpExecutionMode)
476 /// might need to be deferred, since they contain forward references to <id>s
477 /// in the deserialized binary, but module in SPIR-V dialect expects these to
478 /// be ssa-uses.
479 LogicalResult processInstruction(spirv::Opcode opcode,
480 ArrayRef<uint32_t> operands,
481 bool deferInstructions = true);
482
483 /// Processes a SPIR-V instruction from the given `operands`. It should
484 /// deserialize into an op with the given `opName` and `numOperands`.
485 /// This method is a generic one for dispatching any SPIR-V ops without
486 /// variadic operands and attributes in TableGen definitions.
487 LogicalResult processOpWithoutGrammarAttr(ArrayRef<uint32_t> words,
488 StringRef opName, bool hasResult,
489 unsigned numOperands);
490
491 /// Processes a OpUndef instruction. Adds a spirv.Undef operation at the
492 /// current insertion point.
493 LogicalResult processUndef(ArrayRef<uint32_t> operands);
494
495 /// Method to dispatch to the specialized deserialization function for an
496 /// operation in SPIR-V dialect that is a mirror of an instruction in the
497 /// SPIR-V spec. This is auto-generated from ODS. Dispatch is handled for
498 /// all operations in SPIR-V dialect that have hasOpcode == 1.
499 LogicalResult dispatchToAutogenDeserialization(spirv::Opcode opcode,
500 ArrayRef<uint32_t> words);
501
502 /// Processes a SPIR-V OpExtInst with given `operands`. This slices the
503 /// entries of `operands` that specify the extended instruction set <id> and
504 /// the instruction opcode. The op deserializer is then invoked using the
505 /// other entries.
506 LogicalResult processExtInst(ArrayRef<uint32_t> operands);
507
508 /// Dispatches the deserialization of extended instruction set operation based
509 /// on the extended instruction set name, and instruction opcode. This is
510 /// autogenerated from ODS.
511 LogicalResult
512 dispatchToExtensionSetAutogenDeserialization(StringRef extensionSetName,
513 uint32_t instructionID,
514 ArrayRef<uint32_t> words);
515
516 /// Method to deserialize an operation in the SPIR-V dialect that is a mirror
517 /// of an instruction in the SPIR-V spec. This is auto generated if hasOpcode
518 /// == 1 and autogenSerialization == 1 in ODS.
519 template <typename OpTy>
520 LogicalResult processOp(ArrayRef<uint32_t> words) {
521 return emitError(loc: unknownLoc, message: "unsupported deserialization for ")
522 << OpTy::getOperationName() << " op";
523 }
524
525private:
526 /// The SPIR-V binary module.
527 ArrayRef<uint32_t> binary;
528
529 /// Contains the data of the OpLine instruction which precedes the current
530 /// processing instruction.
531 std::optional<DebugLine> debugLine;
532
533 /// The current word offset into the binary module.
534 unsigned curOffset = 0;
535
536 /// MLIRContext to create SPIR-V ModuleOp into.
537 MLIRContext *context;
538
539 // TODO: create Location subclass for binary blob
540 Location unknownLoc;
541
542 /// The SPIR-V ModuleOp.
543 OwningOpRef<spirv::ModuleOp> module;
544
545 /// The current function under construction.
546 std::optional<spirv::FuncOp> curFunction;
547
548 /// The current block under construction.
549 Block *curBlock = nullptr;
550
551 OpBuilder opBuilder;
552
553 spirv::Version version = spirv::Version::V_1_0;
554
555 /// The list of capabilities used by the module.
556 llvm::SmallSetVector<spirv::Capability, 4> capabilities;
557
558 /// The list of extensions used by the module.
559 llvm::SmallSetVector<spirv::Extension, 2> extensions;
560
561 // Result <id> to type mapping.
562 DenseMap<uint32_t, Type> typeMap;
563
564 // Result <id> to constant attribute and type mapping.
565 ///
566 /// In the SPIR-V binary format, all constants are placed in the module and
567 /// shared by instructions at module level and in subsequent functions. But in
568 /// the SPIR-V dialect, we materialize the constant to where it's used in the
569 /// function. So when seeing a constant instruction in the binary format, we
570 /// don't immediately emit a constant op into the module, we keep its value
571 /// (and type) here. Later when it's used, we materialize the constant.
572 DenseMap<uint32_t, std::pair<Attribute, Type>> constantMap;
573
574 // Result <id> to replicated constant attribute and type mapping.
575 ///
576 /// In the SPIR-V binary format, OpConstantCompositeReplicateEXT is placed in
577 /// the module and shared by instructions at module level and in subsequent
578 /// functions. But in the SPIR-V dialect, this is materialized to where
579 /// it's used in the function. So when seeing a
580 /// OpConstantCompositeReplicateEXT in the binary format, we don't immediately
581 /// emit a `spirv.EXT.ConstantCompositeReplicate` op into the module, we keep
582 /// the id of its value and type here. Later when it's used, we materialize
583 /// the `spirv.EXT.ConstantCompositeReplicate`.
584 DenseMap<uint32_t, std::pair<Attribute, Type>> constantCompositeReplicateMap;
585
586 // Result <id> to spec constant mapping.
587 DenseMap<uint32_t, spirv::SpecConstantOp> specConstMap;
588
589 // Result <id> to composite spec constant mapping.
590 DenseMap<uint32_t, spirv::SpecConstantCompositeOp> specConstCompositeMap;
591
592 // Result <id> to replicated composite spec constant mapping.
593 DenseMap<uint32_t, spirv::EXTSpecConstantCompositeReplicateOp>
594 specConstCompositeReplicateMap;
595
596 /// Result <id> to info needed to materialize an OpSpecConstantOp
597 /// mapping.
598 DenseMap<uint32_t, SpecConstOperationMaterializationInfo>
599 specConstOperationMap;
600
601 // Result <id> to variable mapping.
602 DenseMap<uint32_t, spirv::GlobalVariableOp> globalVariableMap;
603
604 // Result <id> to function mapping.
605 DenseMap<uint32_t, spirv::FuncOp> funcMap;
606
607 // Result <id> to block mapping.
608 DenseMap<uint32_t, Block *> blockMap;
609
610 // Header block to its merge (and continue) target mapping.
611 BlockMergeInfoMap blockMergeInfo;
612
613 // For each pair of {predecessor, target} blocks, maps the pair of blocks to
614 // the list of phi arguments passed from predecessor to target.
615 DenseMap<std::pair<Block * /*predecessor*/, Block * /*target*/>, BlockPhiInfo>
616 blockPhiInfo;
617
618 // Result <id> to value mapping.
619 DenseMap<uint32_t, Value> valueMap;
620
621 // Mapping from result <id> to undef value of a type.
622 DenseMap<uint32_t, Type> undefMap;
623
624 // Result <id> to name mapping.
625 DenseMap<uint32_t, StringRef> nameMap;
626
627 // Result <id> to debug info mapping.
628 DenseMap<uint32_t, StringRef> debugInfoMap;
629
630 // Result <id> to decorations mapping.
631 DenseMap<uint32_t, NamedAttrList> decorations;
632
633 // Result <id> to type decorations.
634 DenseMap<uint32_t, uint32_t> typeDecorations;
635
636 // Result <id> to member decorations.
637 // decorated-struct-type-<id> ->
638 // (struct-member-index -> (decoration -> decoration-operands))
639 DenseMap<uint32_t,
640 DenseMap<uint32_t, DenseMap<spirv::Decoration, ArrayRef<uint32_t>>>>
641 memberDecorationMap;
642
643 // Result <id> to member name.
644 // struct-type-<id> -> (struct-member-index -> name)
645 DenseMap<uint32_t, DenseMap<uint32_t, StringRef>> memberNameMap;
646
647 // Result <id> to extended instruction set name.
648 DenseMap<uint32_t, StringRef> extendedInstSets;
649
650 // List of instructions that are processed in a deferred fashion (after an
651 // initial processing of the entire binary). Some operations like
652 // OpEntryPoint, and OpExecutionMode use forward references to function
653 // <id>s. In SPIR-V dialect the corresponding operations (spirv.EntryPoint and
654 // spirv.ExecutionMode) need these references resolved. So these instructions
655 // are deserialized and stored for processing once the entire binary is
656 // processed.
657 SmallVector<std::pair<spirv::Opcode, ArrayRef<uint32_t>>, 4>
658 deferredInstructions;
659
660 /// A list of IDs for all types forward-declared through OpTypeForwardPointer
661 /// instructions.
662 SetVector<uint32_t> typeForwardPointerIDs;
663
664 /// A list of all structs which have unresolved member types.
665 SmallVector<DeferredStructTypeInfo, 0> deferredStructTypesInfos;
666
667 /// Deserialization options.
668 DeserializationOptions options;
669
670#ifndef NDEBUG
671 /// A logger used to emit information during the deserialzation process.
672 llvm::ScopedPrinter logger;
673#endif
674};
675
676} // namespace spirv
677} // namespace mlir
678
679#endif // MLIR_TARGET_SPIRV_DESERIALIZER_H
680

source code of mlir/lib/Target/SPIRV/Deserialization/Deserializer.h