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