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 | |
27 | namespace mlir { |
28 | namespace 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. |
39 | struct 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. |
54 | struct 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. |
61 | using 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. |
86 | struct 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. |
102 | struct 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 |
121 | class Deserializer { |
122 | public: |
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 | |
134 | private: |
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 (); |
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(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 info needed to materialize the spec constant operation op |
194 | /// associated with the given <id>. |
195 | std::optional<SpecConstOperationMaterializationInfo> |
196 | getSpecConstantOperation(uint32_t id); |
197 | |
198 | /// Gets the constant's integer attribute with the given <id>. Returns a |
199 | /// null IntegerAttr if the given is not registered or does not correspond |
200 | /// to an integer constant. |
201 | IntegerAttr getConstantInt(uint32_t id); |
202 | |
203 | /// Returns a symbol to be used for the function name with the given |
204 | /// result <id>. This tries to use the function's OpName if |
205 | /// exists; otherwise creates one based on the <id>. |
206 | std::string getFunctionSymbol(uint32_t id); |
207 | |
208 | /// Returns a symbol to be used for the specialization constant with the given |
209 | /// result <id>. This tries to use the specialization constant's OpName if |
210 | /// exists; otherwise creates one based on the <id>. |
211 | std::string getSpecConstantSymbol(uint32_t id); |
212 | |
213 | /// Gets the specialization constant with the given result <id>. |
214 | spirv::SpecConstantOp getSpecConstant(uint32_t id) { |
215 | return specConstMap.lookup(id); |
216 | } |
217 | |
218 | /// Gets the composite specialization constant with the given result <id>. |
219 | spirv::SpecConstantCompositeOp getSpecConstantComposite(uint32_t id) { |
220 | return specConstCompositeMap.lookup(id); |
221 | } |
222 | |
223 | /// Creates a spirv::SpecConstantOp. |
224 | spirv::SpecConstantOp createSpecConstant(Location loc, uint32_t resultID, |
225 | TypedAttr defaultValue); |
226 | |
227 | /// Processes the OpVariable instructions at current `offset` into `binary`. |
228 | /// It is expected that this method is used for variables that are to be |
229 | /// defined at module scope and will be deserialized into a |
230 | /// spirv.GlobalVariable instruction. |
231 | LogicalResult processGlobalVariable(ArrayRef<uint32_t> operands); |
232 | |
233 | /// Gets the global variable associated with a result <id> of OpVariable. |
234 | spirv::GlobalVariableOp getGlobalVariable(uint32_t id) { |
235 | return globalVariableMap.lookup(id); |
236 | } |
237 | |
238 | /// Sets the function argument's attributes. |argID| is the function |
239 | /// argument's result <id>, and |argIndex| is its index in the function's |
240 | /// argument list. |
241 | LogicalResult setFunctionArgAttrs(uint32_t argID, |
242 | SmallVectorImpl<Attribute> &argAttrs, |
243 | size_t argIndex); |
244 | |
245 | /// Gets the symbol name from the name of decoration. |
246 | StringAttr getSymbolDecoration(StringRef decorationName) { |
247 | auto attrName = llvm::convertToSnakeFromCamelCase(input: decorationName); |
248 | return opBuilder.getStringAttr(attrName); |
249 | } |
250 | |
251 | /// Move a conditional branch into a separate basic block to avoid unnecessary |
252 | /// sinking of defs that may be required outside a selection region. This |
253 | /// function also ensures that a single block cannot be a header block of one |
254 | /// selection construct and the merge block of another. |
255 | LogicalResult splitConditionalBlocks(); |
256 | |
257 | //===--------------------------------------------------------------------===// |
258 | // Type |
259 | //===--------------------------------------------------------------------===// |
260 | |
261 | /// Gets type for a given result <id>. |
262 | Type getType(uint32_t id) { return typeMap.lookup(Val: id); } |
263 | |
264 | /// Get the type associated with the result <id> of an OpUndef. |
265 | Type getUndefType(uint32_t id) { return undefMap.lookup(Val: id); } |
266 | |
267 | /// Returns true if the given `type` is for SPIR-V void type. |
268 | bool isVoidType(Type type) const { return isa<NoneType>(Val: type); } |
269 | |
270 | /// Processes a SPIR-V type instruction with given `opcode` and `operands` and |
271 | /// registers the type into `module`. |
272 | LogicalResult processType(spirv::Opcode opcode, ArrayRef<uint32_t> operands); |
273 | |
274 | LogicalResult processOpTypePointer(ArrayRef<uint32_t> operands); |
275 | |
276 | LogicalResult processArrayType(ArrayRef<uint32_t> operands); |
277 | |
278 | LogicalResult processCooperativeMatrixTypeKHR(ArrayRef<uint32_t> operands); |
279 | |
280 | LogicalResult processCooperativeMatrixTypeNV(ArrayRef<uint32_t> operands); |
281 | |
282 | LogicalResult processFunctionType(ArrayRef<uint32_t> operands); |
283 | |
284 | LogicalResult processImageType(ArrayRef<uint32_t> operands); |
285 | |
286 | LogicalResult processSampledImageType(ArrayRef<uint32_t> operands); |
287 | |
288 | LogicalResult processRuntimeArrayType(ArrayRef<uint32_t> operands); |
289 | |
290 | LogicalResult processStructType(ArrayRef<uint32_t> operands); |
291 | |
292 | LogicalResult processMatrixType(ArrayRef<uint32_t> operands); |
293 | |
294 | LogicalResult processTypeForwardPointer(ArrayRef<uint32_t> operands); |
295 | |
296 | //===--------------------------------------------------------------------===// |
297 | // Constant |
298 | //===--------------------------------------------------------------------===// |
299 | |
300 | /// Processes a SPIR-V Op{|Spec}Constant instruction with the given |
301 | /// `operands`. `isSpec` indicates whether this is a specialization constant. |
302 | LogicalResult processConstant(ArrayRef<uint32_t> operands, bool isSpec); |
303 | |
304 | /// Processes a SPIR-V Op{|Spec}Constant{True|False} instruction with the |
305 | /// given `operands`. `isSpec` indicates whether this is a specialization |
306 | /// constant. |
307 | LogicalResult processConstantBool(bool isTrue, ArrayRef<uint32_t> operands, |
308 | bool isSpec); |
309 | |
310 | /// Processes a SPIR-V OpConstantComposite instruction with the given |
311 | /// `operands`. |
312 | LogicalResult processConstantComposite(ArrayRef<uint32_t> operands); |
313 | |
314 | /// Processes a SPIR-V OpSpecConstantComposite instruction with the given |
315 | /// `operands`. |
316 | LogicalResult processSpecConstantComposite(ArrayRef<uint32_t> operands); |
317 | |
318 | /// Processes a SPIR-V OpSpecConstantOp instruction with the given |
319 | /// `operands`. |
320 | LogicalResult processSpecConstantOperation(ArrayRef<uint32_t> operands); |
321 | |
322 | /// Materializes/emits an OpSpecConstantOp instruction. |
323 | Value materializeSpecConstantOperation(uint32_t resultID, |
324 | spirv::Opcode enclosedOpcode, |
325 | uint32_t resultTypeID, |
326 | ArrayRef<uint32_t> enclosedOpOperands); |
327 | |
328 | /// Processes a SPIR-V OpConstantNull instruction with the given `operands`. |
329 | LogicalResult processConstantNull(ArrayRef<uint32_t> operands); |
330 | |
331 | //===--------------------------------------------------------------------===// |
332 | // Debug |
333 | //===--------------------------------------------------------------------===// |
334 | |
335 | /// Discontinues any source-level location information that might be active |
336 | /// from a previous OpLine instruction. |
337 | void clearDebugLine(); |
338 | |
339 | /// Creates a FileLineColLoc with the OpLine location information. |
340 | Location createFileLineColLoc(OpBuilder opBuilder); |
341 | |
342 | /// Processes a SPIR-V OpLine instruction with the given `operands`. |
343 | LogicalResult processDebugLine(ArrayRef<uint32_t> operands); |
344 | |
345 | /// Processes a SPIR-V OpString instruction with the given `operands`. |
346 | LogicalResult processDebugString(ArrayRef<uint32_t> operands); |
347 | |
348 | //===--------------------------------------------------------------------===// |
349 | // Control flow |
350 | //===--------------------------------------------------------------------===// |
351 | |
352 | /// Returns the block for the given label <id>. |
353 | Block *getBlock(uint32_t id) const { return blockMap.lookup(Val: id); } |
354 | |
355 | // In SPIR-V, structured control flow is explicitly declared using merge |
356 | // instructions (OpSelectionMerge and OpLoopMerge). In the SPIR-V dialect, |
357 | // we use spirv.mlir.selection and spirv.mlir.loop to group structured control |
358 | // flow. The deserializer need to turn structured control flow marked with |
359 | // merge instructions into using spirv.mlir.selection/spirv.mlir.loop ops. |
360 | // |
361 | // Because structured control flow can nest and the basic block order have |
362 | // flexibility, we cannot isolate a structured selection/loop without |
363 | // deserializing all the blocks. So we use the following approach: |
364 | // |
365 | // 1. Deserialize all basic blocks in a function and create MLIR blocks for |
366 | // them into the function's region. In the meanwhile, keep a map between |
367 | // selection/loop header blocks to their corresponding merge (and continue) |
368 | // target blocks. |
369 | // 2. For each selection/loop header block, recursively get all basic blocks |
370 | // reachable (except the merge block) and put them in a newly created |
371 | // spirv.mlir.selection/spirv.mlir.loop's region. Structured control flow |
372 | // guarantees that we enter and exit in structured ways and the construct |
373 | // is nestable. |
374 | // 3. Put the new spirv.mlir.selection/spirv.mlir.loop op at the beginning of |
375 | // the |
376 | // old merge block and redirect all branches to the old header block to the |
377 | // old merge block (which contains the spirv.mlir.selection/spirv.mlir.loop |
378 | // op now). |
379 | |
380 | /// For OpPhi instructions, we use block arguments to represent them. OpPhi |
381 | /// encodes a list of (value, predecessor) pairs. At the time of handling the |
382 | /// block containing an OpPhi instruction, the predecessor block might not be |
383 | /// processed yet, also the value sent by it. So we need to defer handling |
384 | /// the block argument from the predecessors. We use the following approach: |
385 | /// |
386 | /// 1. For each OpPhi instruction, add a block argument to the current block |
387 | /// in construction. Record the block argument in `valueMap` so its uses |
388 | /// can be resolved. For the list of (value, predecessor) pairs, update |
389 | /// `blockPhiInfo` for bookkeeping. |
390 | /// 2. After processing all blocks, loop over `blockPhiInfo` to fix up each |
391 | /// block recorded there to create the proper block arguments on their |
392 | /// terminators. |
393 | |
394 | /// A data structure for containing a SPIR-V block's phi info. It will be |
395 | /// represented as block argument in SPIR-V dialect. |
396 | using BlockPhiInfo = |
397 | SmallVector<uint32_t, 2>; // The result <id> of the values sent |
398 | |
399 | /// Gets or creates the block corresponding to the given label <id>. The newly |
400 | /// created block will always be placed at the end of the current function. |
401 | Block *getOrCreateBlock(uint32_t id); |
402 | |
403 | LogicalResult processBranch(ArrayRef<uint32_t> operands); |
404 | |
405 | LogicalResult processBranchConditional(ArrayRef<uint32_t> operands); |
406 | |
407 | /// Processes a SPIR-V OpLabel instruction with the given `operands`. |
408 | LogicalResult processLabel(ArrayRef<uint32_t> operands); |
409 | |
410 | /// Processes a SPIR-V OpSelectionMerge instruction with the given `operands`. |
411 | LogicalResult processSelectionMerge(ArrayRef<uint32_t> operands); |
412 | |
413 | /// Processes a SPIR-V OpLoopMerge instruction with the given `operands`. |
414 | LogicalResult processLoopMerge(ArrayRef<uint32_t> operands); |
415 | |
416 | /// Processes a SPIR-V OpPhi instruction with the given `operands`. |
417 | LogicalResult processPhi(ArrayRef<uint32_t> operands); |
418 | |
419 | /// Creates block arguments on predecessors previously recorded when handling |
420 | /// OpPhi instructions. |
421 | LogicalResult wireUpBlockArgument(); |
422 | |
423 | /// Extracts blocks belonging to a structured selection/loop into a |
424 | /// spirv.mlir.selection/spirv.mlir.loop op. This method iterates until all |
425 | /// blocks declared as selection/loop headers are handled. |
426 | LogicalResult structurizeControlFlow(); |
427 | |
428 | //===--------------------------------------------------------------------===// |
429 | // Instruction |
430 | //===--------------------------------------------------------------------===// |
431 | |
432 | /// Get the Value associated with a result <id>. |
433 | /// |
434 | /// This method materializes normal constants and inserts "casting" ops |
435 | /// (`spirv.mlir.addressof` and `spirv.mlir.referenceof`) to turn an symbol |
436 | /// into a SSA value for handling uses of module scope constants/variables in |
437 | /// functions. |
438 | Value getValue(uint32_t id); |
439 | |
440 | /// Slices the first instruction out of `binary` and returns its opcode and |
441 | /// operands via `opcode` and `operands` respectively. Returns failure if |
442 | /// there is no more remaining instructions (`expectedOpcode` will be used to |
443 | /// compose the error message) or the next instruction is malformed. |
444 | LogicalResult |
445 | sliceInstruction(spirv::Opcode &opcode, ArrayRef<uint32_t> &operands, |
446 | std::optional<spirv::Opcode> expectedOpcode = std::nullopt); |
447 | |
448 | /// Processes a SPIR-V instruction with the given `opcode` and `operands`. |
449 | /// This method is the main entrance for handling SPIR-V instruction; it |
450 | /// checks the instruction opcode and dispatches to the corresponding handler. |
451 | /// Processing of Some instructions (like OpEntryPoint and OpExecutionMode) |
452 | /// might need to be deferred, since they contain forward references to <id>s |
453 | /// in the deserialized binary, but module in SPIR-V dialect expects these to |
454 | /// be ssa-uses. |
455 | LogicalResult processInstruction(spirv::Opcode opcode, |
456 | ArrayRef<uint32_t> operands, |
457 | bool deferInstructions = true); |
458 | |
459 | /// Processes a SPIR-V instruction from the given `operands`. It should |
460 | /// deserialize into an op with the given `opName` and `numOperands`. |
461 | /// This method is a generic one for dispatching any SPIR-V ops without |
462 | /// variadic operands and attributes in TableGen definitions. |
463 | LogicalResult processOpWithoutGrammarAttr(ArrayRef<uint32_t> words, |
464 | StringRef opName, bool hasResult, |
465 | unsigned numOperands); |
466 | |
467 | /// Processes a OpUndef instruction. Adds a spirv.Undef operation at the |
468 | /// current insertion point. |
469 | LogicalResult processUndef(ArrayRef<uint32_t> operands); |
470 | |
471 | /// Method to dispatch to the specialized deserialization function for an |
472 | /// operation in SPIR-V dialect that is a mirror of an instruction in the |
473 | /// SPIR-V spec. This is auto-generated from ODS. Dispatch is handled for |
474 | /// all operations in SPIR-V dialect that have hasOpcode == 1. |
475 | LogicalResult dispatchToAutogenDeserialization(spirv::Opcode opcode, |
476 | ArrayRef<uint32_t> words); |
477 | |
478 | /// Processes a SPIR-V OpExtInst with given `operands`. This slices the |
479 | /// entries of `operands` that specify the extended instruction set <id> and |
480 | /// the instruction opcode. The op deserializer is then invoked using the |
481 | /// other entries. |
482 | LogicalResult processExtInst(ArrayRef<uint32_t> operands); |
483 | |
484 | /// Dispatches the deserialization of extended instruction set operation based |
485 | /// on the extended instruction set name, and instruction opcode. This is |
486 | /// autogenerated from ODS. |
487 | LogicalResult |
488 | dispatchToExtensionSetAutogenDeserialization(StringRef extensionSetName, |
489 | uint32_t instructionID, |
490 | ArrayRef<uint32_t> words); |
491 | |
492 | /// Method to deserialize an operation in the SPIR-V dialect that is a mirror |
493 | /// of an instruction in the SPIR-V spec. This is auto generated if hasOpcode |
494 | /// == 1 and autogenSerialization == 1 in ODS. |
495 | template <typename OpTy> |
496 | LogicalResult processOp(ArrayRef<uint32_t> words) { |
497 | return emitError(loc: unknownLoc, message: "unsupported deserialization for " ) |
498 | << OpTy::getOperationName() << " op" ; |
499 | } |
500 | |
501 | private: |
502 | /// The SPIR-V binary module. |
503 | ArrayRef<uint32_t> binary; |
504 | |
505 | /// Contains the data of the OpLine instruction which precedes the current |
506 | /// processing instruction. |
507 | std::optional<DebugLine> debugLine; |
508 | |
509 | /// The current word offset into the binary module. |
510 | unsigned curOffset = 0; |
511 | |
512 | /// MLIRContext to create SPIR-V ModuleOp into. |
513 | MLIRContext *context; |
514 | |
515 | // TODO: create Location subclass for binary blob |
516 | Location unknownLoc; |
517 | |
518 | /// The SPIR-V ModuleOp. |
519 | OwningOpRef<spirv::ModuleOp> module; |
520 | |
521 | /// The current function under construction. |
522 | std::optional<spirv::FuncOp> curFunction; |
523 | |
524 | /// The current block under construction. |
525 | Block *curBlock = nullptr; |
526 | |
527 | OpBuilder opBuilder; |
528 | |
529 | spirv::Version version = spirv::Version::V_1_0; |
530 | |
531 | /// The list of capabilities used by the module. |
532 | llvm::SmallSetVector<spirv::Capability, 4> capabilities; |
533 | |
534 | /// The list of extensions used by the module. |
535 | llvm::SmallSetVector<spirv::Extension, 2> extensions; |
536 | |
537 | // Result <id> to type mapping. |
538 | DenseMap<uint32_t, Type> typeMap; |
539 | |
540 | // Result <id> to constant attribute and type mapping. |
541 | /// |
542 | /// In the SPIR-V binary format, all constants are placed in the module and |
543 | /// shared by instructions at module level and in subsequent functions. But in |
544 | /// the SPIR-V dialect, we materialize the constant to where it's used in the |
545 | /// function. So when seeing a constant instruction in the binary format, we |
546 | /// don't immediately emit a constant op into the module, we keep its value |
547 | /// (and type) here. Later when it's used, we materialize the constant. |
548 | DenseMap<uint32_t, std::pair<Attribute, Type>> constantMap; |
549 | |
550 | // Result <id> to spec constant mapping. |
551 | DenseMap<uint32_t, spirv::SpecConstantOp> specConstMap; |
552 | |
553 | // Result <id> to composite spec constant mapping. |
554 | DenseMap<uint32_t, spirv::SpecConstantCompositeOp> specConstCompositeMap; |
555 | |
556 | /// Result <id> to info needed to materialize an OpSpecConstantOp |
557 | /// mapping. |
558 | DenseMap<uint32_t, SpecConstOperationMaterializationInfo> |
559 | specConstOperationMap; |
560 | |
561 | // Result <id> to variable mapping. |
562 | DenseMap<uint32_t, spirv::GlobalVariableOp> globalVariableMap; |
563 | |
564 | // Result <id> to function mapping. |
565 | DenseMap<uint32_t, spirv::FuncOp> funcMap; |
566 | |
567 | // Result <id> to block mapping. |
568 | DenseMap<uint32_t, Block *> blockMap; |
569 | |
570 | // Header block to its merge (and continue) target mapping. |
571 | BlockMergeInfoMap blockMergeInfo; |
572 | |
573 | // For each pair of {predecessor, target} blocks, maps the pair of blocks to |
574 | // the list of phi arguments passed from predecessor to target. |
575 | DenseMap<std::pair<Block * /*predecessor*/, Block * /*target*/>, BlockPhiInfo> |
576 | blockPhiInfo; |
577 | |
578 | // Result <id> to value mapping. |
579 | DenseMap<uint32_t, Value> valueMap; |
580 | |
581 | // Mapping from result <id> to undef value of a type. |
582 | DenseMap<uint32_t, Type> undefMap; |
583 | |
584 | // Result <id> to name mapping. |
585 | DenseMap<uint32_t, StringRef> nameMap; |
586 | |
587 | // Result <id> to debug info mapping. |
588 | DenseMap<uint32_t, StringRef> debugInfoMap; |
589 | |
590 | // Result <id> to decorations mapping. |
591 | DenseMap<uint32_t, NamedAttrList> decorations; |
592 | |
593 | // Result <id> to type decorations. |
594 | DenseMap<uint32_t, uint32_t> typeDecorations; |
595 | |
596 | // Result <id> to member decorations. |
597 | // decorated-struct-type-<id> -> |
598 | // (struct-member-index -> (decoration -> decoration-operands)) |
599 | DenseMap<uint32_t, |
600 | DenseMap<uint32_t, DenseMap<spirv::Decoration, ArrayRef<uint32_t>>>> |
601 | memberDecorationMap; |
602 | |
603 | // Result <id> to member name. |
604 | // struct-type-<id> -> (struct-member-index -> name) |
605 | DenseMap<uint32_t, DenseMap<uint32_t, StringRef>> memberNameMap; |
606 | |
607 | // Result <id> to extended instruction set name. |
608 | DenseMap<uint32_t, StringRef> extendedInstSets; |
609 | |
610 | // List of instructions that are processed in a deferred fashion (after an |
611 | // initial processing of the entire binary). Some operations like |
612 | // OpEntryPoint, and OpExecutionMode use forward references to function |
613 | // <id>s. In SPIR-V dialect the corresponding operations (spirv.EntryPoint and |
614 | // spirv.ExecutionMode) need these references resolved. So these instructions |
615 | // are deserialized and stored for processing once the entire binary is |
616 | // processed. |
617 | SmallVector<std::pair<spirv::Opcode, ArrayRef<uint32_t>>, 4> |
618 | deferredInstructions; |
619 | |
620 | /// A list of IDs for all types forward-declared through OpTypeForwardPointer |
621 | /// instructions. |
622 | SetVector<uint32_t> typeForwardPointerIDs; |
623 | |
624 | /// A list of all structs which have unresolved member types. |
625 | SmallVector<DeferredStructTypeInfo, 0> deferredStructTypesInfos; |
626 | |
627 | /// Deserialization options. |
628 | DeserializationOptions options; |
629 | |
630 | #ifndef NDEBUG |
631 | /// A logger used to emit information during the deserialzation process. |
632 | llvm::ScopedPrinter logger; |
633 | #endif |
634 | }; |
635 | |
636 | } // namespace spirv |
637 | } // namespace mlir |
638 | |
639 | #endif // MLIR_TARGET_SPIRV_DESERIALIZER_H |
640 | |