| 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 | /// Use `MapVector<>` to ensure a deterministic iteration order with a pointer |
| 62 | /// key. |
| 63 | using 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. |
| 88 | struct DeferredStructTypeInfo { |
| 89 | spirv::StructType deferredStructType; |
| 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. |
| 93 | SmallVector<std::pair<uint32_t, unsigned>, 0> unresolvedMemberTypes; |
| 94 | |
| 95 | // The list of member types. For unresolved members, this list contains |
| 96 | // place-holder empty types that will be updated later. |
| 97 | SmallVector<Type, 4> memberTypes; |
| 98 | SmallVector<spirv::StructType::OffsetInfo, 0> offsetInfo; |
| 99 | SmallVector<spirv::StructType::MemberDecorationInfo, 0> memberDecorationsInfo; |
| 100 | SmallVector<spirv::StructType::StructDecorationInfo, 0> structDecorationsInfo; |
| 101 | }; |
| 102 | |
| 103 | /// A struct that collects the info needed to materialize/emit a |
| 104 | /// SpecConstantOperation op. |
| 105 | struct SpecConstOperationMaterializationInfo { |
| 106 | spirv::Opcode enclodesOpcode; |
| 107 | uint32_t resultTypeID; |
| 108 | SmallVector<uint32_t> enclosedOpOperands; |
| 109 | }; |
| 110 | |
| 111 | /// A struct that collects the info needed to materialize/emit a |
| 112 | /// GraphConstantARMOp. |
| 113 | struct GraphConstantARMOpMaterializationInfo { |
| 114 | Type resultType; |
| 115 | IntegerAttr graphConstantID; |
| 116 | }; |
| 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 |
| 131 | class Deserializer { |
| 132 | public: |
| 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. |
| 142 | OwningOpRef<spirv::ModuleOp> collect(); |
| 143 | |
| 144 | private: |
| 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 (); |
| 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 | /// Resolves all OpDecorateId entries previously queued during |
| 181 | /// processDecoration. Called after all module ops have been deserialized so |
| 182 | /// the operand <id>s can be looked up as MLIR symbols. |
| 183 | LogicalResult resolveDeferredIdDecorations(); |
| 184 | |
| 185 | // Processes an OpMemberDecorate instruction. |
| 186 | LogicalResult processMemberDecoration(ArrayRef<uint32_t> words); |
| 187 | |
| 188 | /// Processes an OpMemberName instruction. |
| 189 | LogicalResult processMemberName(ArrayRef<uint32_t> words); |
| 190 | |
| 191 | /// Gets the function op associated with a result <id> of OpFunction. |
| 192 | spirv::FuncOp getFunction(uint32_t id) { return funcMap.lookup(Val: id); } |
| 193 | |
| 194 | /// Processes the SPIR-V function at the current `offset` into `binary`. |
| 195 | /// The operands to the OpFunction instruction is passed in as ``operands`. |
| 196 | /// This method processes each instruction inside the function and dispatches |
| 197 | /// them to their handler method accordingly. |
| 198 | LogicalResult processFunction(ArrayRef<uint32_t> operands); |
| 199 | |
| 200 | /// Processes OpFunctionEnd and finalizes function. This wires up block |
| 201 | /// argument created from OpPhi instructions and also structurizes control |
| 202 | /// flow. |
| 203 | LogicalResult processFunctionEnd(ArrayRef<uint32_t> operands); |
| 204 | |
| 205 | /// Gets the constant's attribute and type associated with the given <id>. |
| 206 | std::optional<std::pair<Attribute, Type>> getConstant(uint32_t id); |
| 207 | |
| 208 | /// Gets the replicated composite constant's attribute and type associated |
| 209 | /// with the given <id>. |
| 210 | std::optional<std::pair<Attribute, Type>> |
| 211 | getConstantCompositeReplicate(uint32_t id); |
| 212 | |
| 213 | /// Gets the info needed to materialize the spec constant operation op |
| 214 | /// associated with the given <id>. |
| 215 | std::optional<SpecConstOperationMaterializationInfo> |
| 216 | getSpecConstantOperation(uint32_t id); |
| 217 | |
| 218 | /// Gets the constant's integer attribute with the given <id>. Returns a |
| 219 | /// null IntegerAttr if the given is not registered or does not correspond |
| 220 | /// to an integer constant. |
| 221 | IntegerAttr getConstantInt(uint32_t id); |
| 222 | |
| 223 | /// Returns a symbol to be used for the function name with the given |
| 224 | /// result <id>. This tries to use the function's OpName if |
| 225 | /// exists; otherwise creates one based on the <id>. |
| 226 | std::string getFunctionSymbol(uint32_t id); |
| 227 | |
| 228 | /// Returns a symbol to be used for the graph name with the given |
| 229 | /// result <id>. This tries to use the graph's OpName if |
| 230 | /// exists; otherwise creates one based on the <id>. |
| 231 | std::string getGraphSymbol(uint32_t id); |
| 232 | |
| 233 | /// Returns a symbol to be used for the specialization constant with the |
| 234 | /// given result <id>. This tries to use the specialization constant's |
| 235 | /// OpName if exists; otherwise creates one based on the <id>. |
| 236 | std::string getSpecConstantSymbol(uint32_t id); |
| 237 | |
| 238 | /// Gets the specialization constant with the given result <id>. |
| 239 | spirv::SpecConstantOp getSpecConstant(uint32_t id) { |
| 240 | return specConstMap.lookup(Val: id); |
| 241 | } |
| 242 | |
| 243 | /// Gets the composite specialization constant with the given result <id>. |
| 244 | spirv::SpecConstantCompositeOp getSpecConstantComposite(uint32_t id) { |
| 245 | return specConstCompositeMap.lookup(Val: id); |
| 246 | } |
| 247 | |
| 248 | /// Gets the replicated composite specialization constant with the given |
| 249 | /// result <id>. |
| 250 | spirv::EXTSpecConstantCompositeReplicateOp |
| 251 | getSpecConstantCompositeReplicate(uint32_t id) { |
| 252 | return specConstCompositeReplicateMap.lookup(Val: id); |
| 253 | } |
| 254 | |
| 255 | /// Creates a spirv::SpecConstantOp. |
| 256 | spirv::SpecConstantOp createSpecConstant(Location loc, uint32_t resultID, |
| 257 | TypedAttr defaultValue); |
| 258 | |
| 259 | /// Gets the GraphConstantARM ID attribute and result type with the given |
| 260 | /// result <id>. |
| 261 | std::optional<spirv::GraphConstantARMOpMaterializationInfo> |
| 262 | getGraphConstantARM(uint32_t id); |
| 263 | |
| 264 | /// Processes the OpVariable instructions at current `offset` into `binary`. |
| 265 | /// It is expected that this method is used for variables that are to be |
| 266 | /// defined at module scope and will be deserialized into a |
| 267 | /// spirv.GlobalVariable instruction. |
| 268 | LogicalResult processGlobalVariable(ArrayRef<uint32_t> operands); |
| 269 | |
| 270 | /// Gets the global variable associated with a result <id> of OpVariable. |
| 271 | spirv::GlobalVariableOp getGlobalVariable(uint32_t id) { |
| 272 | return globalVariableMap.lookup(Val: id); |
| 273 | } |
| 274 | |
| 275 | /// Sets the function argument's attributes. |argID| is the function |
| 276 | /// argument's result <id>, and |argIndex| is its index in the function's |
| 277 | /// argument list. |
| 278 | LogicalResult setFunctionArgAttrs(uint32_t argID, |
| 279 | SmallVectorImpl<Attribute> &argAttrs, |
| 280 | size_t argIndex); |
| 281 | |
| 282 | /// Gets the symbol name from the name of decoration. |
| 283 | StringAttr getSymbolDecoration(StringRef decorationName) { |
| 284 | auto attrName = llvm::convertToSnakeFromCamelCase(input: decorationName); |
| 285 | return opBuilder.getStringAttr(bytes: attrName); |
| 286 | } |
| 287 | |
| 288 | /// Move a conditional branch or a switch into a separate basic block to avoid |
| 289 | /// unnecessary sinking of defs that may be required outside a selection |
| 290 | /// region. This function also ensures that a single block cannot be a header |
| 291 | /// block of one selection construct and the merge block of another. |
| 292 | LogicalResult (); |
| 293 | |
| 294 | //===--------------------------------------------------------------------===// |
| 295 | // Type |
| 296 | //===--------------------------------------------------------------------===// |
| 297 | |
| 298 | /// Gets type for a given result <id>. |
| 299 | Type getType(uint32_t id) { return typeMap.lookup(Val: id); } |
| 300 | |
| 301 | /// Get the type associated with the result <id> of an OpUndef. |
| 302 | Type getUndefType(uint32_t id) { return undefMap.lookup(Val: id); } |
| 303 | |
| 304 | /// Returns true if the given `type` is for SPIR-V void type. |
| 305 | bool isVoidType(Type type) const { return isa<NoneType>(Val: type); } |
| 306 | |
| 307 | /// Processes a SPIR-V type instruction with given `opcode` and `operands` and |
| 308 | /// registers the type into `module`. |
| 309 | LogicalResult processType(spirv::Opcode opcode, ArrayRef<uint32_t> operands); |
| 310 | |
| 311 | LogicalResult processOpTypePointer(ArrayRef<uint32_t> operands); |
| 312 | |
| 313 | LogicalResult processArrayType(ArrayRef<uint32_t> operands); |
| 314 | |
| 315 | LogicalResult processCooperativeMatrixTypeKHR(ArrayRef<uint32_t> operands); |
| 316 | |
| 317 | LogicalResult processCooperativeMatrixTypeNV(ArrayRef<uint32_t> operands); |
| 318 | |
| 319 | LogicalResult processFunctionType(ArrayRef<uint32_t> operands); |
| 320 | |
| 321 | LogicalResult processImageType(ArrayRef<uint32_t> operands); |
| 322 | |
| 323 | LogicalResult processSampledImageType(ArrayRef<uint32_t> operands); |
| 324 | |
| 325 | LogicalResult processSamplerType(ArrayRef<uint32_t> operands); |
| 326 | |
| 327 | LogicalResult processNamedBarrierType(ArrayRef<uint32_t> operands); |
| 328 | |
| 329 | LogicalResult processRuntimeArrayType(ArrayRef<uint32_t> operands); |
| 330 | |
| 331 | LogicalResult processStructType(ArrayRef<uint32_t> operands); |
| 332 | |
| 333 | LogicalResult processMatrixType(ArrayRef<uint32_t> operands); |
| 334 | |
| 335 | LogicalResult processTensorARMType(ArrayRef<uint32_t> operands); |
| 336 | |
| 337 | LogicalResult processGraphTypeARM(ArrayRef<uint32_t> operands); |
| 338 | |
| 339 | LogicalResult processGraphEntryPointARM(ArrayRef<uint32_t> operands); |
| 340 | |
| 341 | LogicalResult processGraphARM(ArrayRef<uint32_t> operands); |
| 342 | |
| 343 | LogicalResult processOpGraphSetOutputARM(ArrayRef<uint32_t> operands); |
| 344 | |
| 345 | LogicalResult processGraphEndARM(ArrayRef<uint32_t> operands); |
| 346 | |
| 347 | LogicalResult processTypeForwardPointer(ArrayRef<uint32_t> operands); |
| 348 | |
| 349 | //===--------------------------------------------------------------------===// |
| 350 | // Constant |
| 351 | //===--------------------------------------------------------------------===// |
| 352 | |
| 353 | /// Processes a SPIR-V Op{|Spec}Constant instruction with the given |
| 354 | /// `operands`. `isSpec` indicates whether this is a specialization constant. |
| 355 | LogicalResult processConstant(ArrayRef<uint32_t> operands, bool isSpec); |
| 356 | |
| 357 | /// Processes a SPIR-V Op{|Spec}Constant{True|False} instruction with the |
| 358 | /// given `operands`. `isSpec` indicates whether this is a specialization |
| 359 | /// constant. |
| 360 | LogicalResult processConstantBool(bool isTrue, ArrayRef<uint32_t> operands, |
| 361 | bool isSpec); |
| 362 | |
| 363 | /// Processes a SPIR-V OpConstantComposite instruction with the given |
| 364 | /// `operands`. |
| 365 | LogicalResult processConstantComposite(ArrayRef<uint32_t> operands); |
| 366 | |
| 367 | /// Processes a SPIR-V OpConstantCompositeReplicateEXT instruction with |
| 368 | /// the given `operands`. |
| 369 | LogicalResult |
| 370 | processConstantCompositeReplicateEXT(ArrayRef<uint32_t> operands); |
| 371 | |
| 372 | /// Processes a SPIR-V OpSpecConstantComposite instruction with the given |
| 373 | /// `operands`. |
| 374 | LogicalResult processSpecConstantComposite(ArrayRef<uint32_t> operands); |
| 375 | |
| 376 | /// Processes a SPIR-V OpSpecConstantCompositeReplicateEXT instruction with |
| 377 | /// the given `operands`. |
| 378 | LogicalResult |
| 379 | processSpecConstantCompositeReplicateEXT(ArrayRef<uint32_t> operands); |
| 380 | |
| 381 | /// Processes a SPIR-V OpSpecConstantOp instruction with the given |
| 382 | /// `operands`. |
| 383 | LogicalResult processSpecConstantOperation(ArrayRef<uint32_t> operands); |
| 384 | |
| 385 | /// Materializes/emits an OpSpecConstantOp instruction. |
| 386 | Value materializeSpecConstantOperation(uint32_t resultID, |
| 387 | spirv::Opcode enclosedOpcode, |
| 388 | uint32_t resultTypeID, |
| 389 | ArrayRef<uint32_t> enclosedOpOperands); |
| 390 | |
| 391 | /// Processes a SPIR-V OpConstantNull instruction with the given `operands`. |
| 392 | LogicalResult processConstantNull(ArrayRef<uint32_t> operands); |
| 393 | |
| 394 | /// Processes a SPIR-V OpGraphConstantARM instruction with the given |
| 395 | /// `operands`. |
| 396 | LogicalResult processGraphConstantARM(ArrayRef<uint32_t> operands); |
| 397 | |
| 398 | //===--------------------------------------------------------------------===// |
| 399 | // Debug |
| 400 | //===--------------------------------------------------------------------===// |
| 401 | |
| 402 | /// Discontinues any source-level location information that might be active |
| 403 | /// from a previous OpLine instruction. |
| 404 | void clearDebugLine(); |
| 405 | |
| 406 | /// Creates a FileLineColLoc with the OpLine location information. |
| 407 | Location createFileLineColLoc(OpBuilder opBuilder); |
| 408 | |
| 409 | /// Processes a SPIR-V OpLine instruction with the given `operands`. |
| 410 | LogicalResult processDebugLine(ArrayRef<uint32_t> operands); |
| 411 | |
| 412 | /// Processes a SPIR-V OpString instruction with the given `operands`. |
| 413 | LogicalResult processDebugString(ArrayRef<uint32_t> operands); |
| 414 | |
| 415 | //===--------------------------------------------------------------------===// |
| 416 | // Control flow |
| 417 | //===--------------------------------------------------------------------===// |
| 418 | |
| 419 | /// Returns the block for the given label <id>. |
| 420 | Block *getBlock(uint32_t id) const { return blockMap.lookup(Val: id); } |
| 421 | |
| 422 | // In SPIR-V, structured control flow is explicitly declared using merge |
| 423 | // instructions (OpSelectionMerge and OpLoopMerge). In the SPIR-V dialect, |
| 424 | // we use spirv.mlir.selection and spirv.mlir.loop to group structured control |
| 425 | // flow. The deserializer need to turn structured control flow marked with |
| 426 | // merge instructions into using spirv.mlir.selection/spirv.mlir.loop ops. |
| 427 | // |
| 428 | // Because structured control flow can nest and the basic block order have |
| 429 | // flexibility, we cannot isolate a structured selection/loop without |
| 430 | // deserializing all the blocks. So we use the following approach: |
| 431 | // |
| 432 | // 1. Deserialize all basic blocks in a function and create MLIR blocks for |
| 433 | // them into the function's region. In the meanwhile, keep a map between |
| 434 | // selection/loop header blocks to their corresponding merge (and continue) |
| 435 | // target blocks. |
| 436 | // 2. For each selection/loop header block, recursively get all basic blocks |
| 437 | // reachable (except the merge block) and put them in a newly created |
| 438 | // spirv.mlir.selection/spirv.mlir.loop's region. Structured control flow |
| 439 | // guarantees that we enter and exit in structured ways and the construct |
| 440 | // is nestable. |
| 441 | // 3. Put the new spirv.mlir.selection/spirv.mlir.loop op at the beginning of |
| 442 | // the |
| 443 | // old merge block and redirect all branches to the old header block to the |
| 444 | // old merge block (which contains the spirv.mlir.selection/spirv.mlir.loop |
| 445 | // op now). |
| 446 | |
| 447 | /// For OpPhi instructions, we use block arguments to represent them. OpPhi |
| 448 | /// encodes a list of (value, predecessor) pairs. At the time of handling the |
| 449 | /// block containing an OpPhi instruction, the predecessor block might not be |
| 450 | /// processed yet, also the value sent by it. So we need to defer handling |
| 451 | /// the block argument from the predecessors. We use the following approach: |
| 452 | /// |
| 453 | /// 1. For each OpPhi instruction, add a block argument to the current block |
| 454 | /// in construction. Record the block argument in `valueMap` so its uses |
| 455 | /// can be resolved. For the list of (value, predecessor) pairs, update |
| 456 | /// `blockPhiInfo` for bookkeeping. |
| 457 | /// 2. After processing all blocks, loop over `blockPhiInfo` to fix up each |
| 458 | /// block recorded there to create the proper block arguments on their |
| 459 | /// terminators. |
| 460 | |
| 461 | /// A data structure for containing a SPIR-V block's phi info. It will be |
| 462 | /// represented as block argument in SPIR-V dialect. |
| 463 | using BlockPhiInfo = |
| 464 | SmallVector<uint32_t, 2>; // The result <id> of the values sent |
| 465 | |
| 466 | /// Gets or creates the block corresponding to the given label <id>. The newly |
| 467 | /// created block will always be placed at the end of the current function. |
| 468 | Block *getOrCreateBlock(uint32_t id); |
| 469 | |
| 470 | LogicalResult processBranch(ArrayRef<uint32_t> operands); |
| 471 | |
| 472 | LogicalResult processBranchConditional(ArrayRef<uint32_t> operands); |
| 473 | |
| 474 | /// Processes a SPIR-V OpLabel instruction with the given `operands`. |
| 475 | LogicalResult processLabel(ArrayRef<uint32_t> operands); |
| 476 | |
| 477 | /// Processes a SPIR-V OpSelectionMerge instruction with the given `operands`. |
| 478 | LogicalResult processSelectionMerge(ArrayRef<uint32_t> operands); |
| 479 | |
| 480 | /// Processes a SPIR-V OpLoopMerge instruction with the given `operands`. |
| 481 | LogicalResult processLoopMerge(ArrayRef<uint32_t> operands); |
| 482 | |
| 483 | /// Processes a SPIR-V OpPhi instruction with the given `operands`. |
| 484 | LogicalResult processPhi(ArrayRef<uint32_t> operands); |
| 485 | |
| 486 | /// Processes a SPIR-V OpSwitch instruction with the given `operands`. |
| 487 | LogicalResult processSwitch(ArrayRef<uint32_t> operands); |
| 488 | |
| 489 | /// Creates block arguments on predecessors previously recorded when handling |
| 490 | /// OpPhi instructions. |
| 491 | LogicalResult wireUpBlockArgument(); |
| 492 | |
| 493 | /// Extracts blocks belonging to a structured selection/loop into a |
| 494 | /// spirv.mlir.selection/spirv.mlir.loop op. This method iterates until all |
| 495 | /// blocks declared as selection/loop headers are handled. |
| 496 | LogicalResult structurizeControlFlow(); |
| 497 | |
| 498 | /// Creates a block for graph with the given graphID. |
| 499 | LogicalResult createGraphBlock(uint32_t graphID); |
| 500 | |
| 501 | //===--------------------------------------------------------------------===// |
| 502 | // Instruction |
| 503 | //===--------------------------------------------------------------------===// |
| 504 | |
| 505 | /// Get the Value associated with a result <id>. |
| 506 | /// |
| 507 | /// This method materializes normal constants and inserts "casting" ops |
| 508 | /// (`spirv.mlir.addressof` and `spirv.mlir.referenceof`) to turn an symbol |
| 509 | /// into a SSA value for handling uses of module scope constants/variables in |
| 510 | /// functions. |
| 511 | Value getValue(uint32_t id); |
| 512 | |
| 513 | /// Slices the first instruction out of `binary` and returns its opcode and |
| 514 | /// operands via `opcode` and `operands` respectively. Returns failure if |
| 515 | /// there is no more remaining instructions (`expectedOpcode` will be used to |
| 516 | /// compose the error message) or the next instruction is malformed. |
| 517 | LogicalResult |
| 518 | sliceInstruction(spirv::Opcode &opcode, ArrayRef<uint32_t> &operands, |
| 519 | std::optional<spirv::Opcode> expectedOpcode = std::nullopt); |
| 520 | |
| 521 | /// If `opcode` is a SPV_INTEL_long_composites splittable opcode and the |
| 522 | /// next binary instruction(s) are matching `*ContinuedINTEL` ops, consumes |
| 523 | /// them and rebinds `operands` to a buffer (held in `mergedStorage`) |
| 524 | /// containing the parent + continuation operands concatenated. |
| 525 | void |
| 526 | mergeLongCompositeContinuations(spirv::Opcode opcode, |
| 527 | ArrayRef<uint32_t> &operands, |
| 528 | SmallVectorImpl<uint32_t> &mergedStorage); |
| 529 | |
| 530 | /// Processes a SPIR-V instruction with the given `opcode` and `operands`. |
| 531 | /// This method is the main entrance for handling SPIR-V instruction; it |
| 532 | /// checks the instruction opcode and dispatches to the corresponding handler. |
| 533 | /// Processing of Some instructions (like OpEntryPoint and OpExecutionMode) |
| 534 | /// might need to be deferred, since they contain forward references to <id>s |
| 535 | /// in the deserialized binary, but module in SPIR-V dialect expects these to |
| 536 | /// be ssa-uses. |
| 537 | LogicalResult processInstruction(spirv::Opcode opcode, |
| 538 | ArrayRef<uint32_t> operands, |
| 539 | bool deferInstructions = true); |
| 540 | |
| 541 | /// Processes a SPIR-V instruction from the given `operands`. It should |
| 542 | /// deserialize into an op with the given `opName` and `numOperands`. |
| 543 | /// This method is a generic one for dispatching any SPIR-V ops without |
| 544 | /// variadic operands and attributes in TableGen definitions. |
| 545 | LogicalResult processOpWithoutGrammarAttr(ArrayRef<uint32_t> words, |
| 546 | StringRef opName, bool hasResult, |
| 547 | unsigned numOperands); |
| 548 | |
| 549 | /// Processes a OpUndef instruction. Adds a spirv.Undef operation at the |
| 550 | /// current insertion point. |
| 551 | LogicalResult processUndef(ArrayRef<uint32_t> operands); |
| 552 | |
| 553 | /// Method to dispatch to the specialized deserialization function for an |
| 554 | /// operation in SPIR-V dialect that is a mirror of an instruction in the |
| 555 | /// SPIR-V spec. This is auto-generated from ODS. Dispatch is handled for |
| 556 | /// all operations in SPIR-V dialect that have hasOpcode == 1. |
| 557 | LogicalResult dispatchToAutogenDeserialization(spirv::Opcode opcode, |
| 558 | ArrayRef<uint32_t> words); |
| 559 | |
| 560 | /// Processes a SPIR-V OpExtInst with given `operands`. This slices the |
| 561 | /// entries of `operands` that specify the extended instruction set <id> and |
| 562 | /// the instruction opcode. The op deserializer is then invoked using the |
| 563 | /// other entries. |
| 564 | LogicalResult processExtInst(ArrayRef<uint32_t> operands); |
| 565 | |
| 566 | /// Processes a SPIR-V OpExtInst with given `operands` for a DebugInfo |
| 567 | /// extension instruction. |
| 568 | LogicalResult processDebugInfoExtInst(ArrayRef<uint32_t> operands, |
| 569 | bool deferInstructions); |
| 570 | |
| 571 | /// Dispatches the deserialization of extended instruction set operation based |
| 572 | /// on the extended instruction set name, and instruction opcode. This is |
| 573 | /// autogenerated from ODS. |
| 574 | LogicalResult |
| 575 | dispatchToExtensionSetAutogenDeserialization(StringRef extensionSetName, |
| 576 | uint32_t instructionID, |
| 577 | ArrayRef<uint32_t> words); |
| 578 | |
| 579 | /// Method to deserialize an operation in the SPIR-V dialect that is a mirror |
| 580 | /// of an instruction in the SPIR-V spec. This is auto generated if hasOpcode |
| 581 | /// == 1 and autogenSerialization == 1 in ODS. |
| 582 | template <typename OpTy> |
| 583 | LogicalResult processOp(ArrayRef<uint32_t> words) { |
| 584 | return emitError(loc: unknownLoc, message: "unsupported deserialization for " ) |
| 585 | << OpTy::getOperationName() << " op" ; |
| 586 | } |
| 587 | |
| 588 | private: |
| 589 | /// The SPIR-V binary module. |
| 590 | ArrayRef<uint32_t> binary; |
| 591 | |
| 592 | /// Contains the data of the OpLine instruction which precedes the current |
| 593 | /// processing instruction. |
| 594 | std::optional<DebugLine> debugLine; |
| 595 | |
| 596 | /// The current word offset into the binary module. |
| 597 | unsigned curOffset = 0; |
| 598 | |
| 599 | /// MLIRContext to create SPIR-V ModuleOp into. |
| 600 | MLIRContext *context; |
| 601 | |
| 602 | // TODO: create Location subclass for binary blob |
| 603 | Location unknownLoc; |
| 604 | |
| 605 | /// The SPIR-V ModuleOp. |
| 606 | OwningOpRef<spirv::ModuleOp> module; |
| 607 | |
| 608 | /// The current function under construction. |
| 609 | std::optional<spirv::FuncOp> curFunction; |
| 610 | |
| 611 | /// The current graph under construction. |
| 612 | std::optional<spirv::GraphARMOp> curGraph; |
| 613 | |
| 614 | /// The current block under construction. |
| 615 | Block *curBlock = nullptr; |
| 616 | |
| 617 | OpBuilder opBuilder; |
| 618 | |
| 619 | spirv::Version version = spirv::Version::V_1_0; |
| 620 | |
| 621 | /// The list of capabilities used by the module. |
| 622 | llvm::SmallSetVector<spirv::Capability, 4> capabilities; |
| 623 | |
| 624 | /// The list of extensions used by the module. |
| 625 | llvm::SmallSetVector<spirv::Extension, 2> extensions; |
| 626 | |
| 627 | // Result <id> to type mapping. |
| 628 | DenseMap<uint32_t, Type> typeMap; |
| 629 | |
| 630 | // Result <id> to constant attribute and type mapping. |
| 631 | /// |
| 632 | /// In the SPIR-V binary format, all constants are placed in the module and |
| 633 | /// shared by instructions at module level and in subsequent functions. But in |
| 634 | /// the SPIR-V dialect, we materialize the constant to where it's used in the |
| 635 | /// function. So when seeing a constant instruction in the binary format, we |
| 636 | /// don't immediately emit a constant op into the module, we keep its value |
| 637 | /// (and type) here. Later when it's used, we materialize the constant. |
| 638 | DenseMap<uint32_t, std::pair<Attribute, Type>> constantMap; |
| 639 | |
| 640 | // Result <id> to debug location for constants materialized from constantMap. |
| 641 | DenseMap<uint32_t, LocationAttr> constantLocMap; |
| 642 | |
| 643 | // Result <id> to replicated constant attribute and type mapping. |
| 644 | /// |
| 645 | /// In the SPIR-V binary format, OpConstantCompositeReplicateEXT is placed in |
| 646 | /// the module and shared by instructions at module level and in subsequent |
| 647 | /// functions. But in the SPIR-V dialect, this is materialized to where |
| 648 | /// it's used in the function. So when seeing a |
| 649 | /// OpConstantCompositeReplicateEXT in the binary format, we don't immediately |
| 650 | /// emit a `spirv.EXT.ConstantCompositeReplicate` op into the module, we keep |
| 651 | /// the id of its value and type here. Later when it's used, we materialize |
| 652 | /// the `spirv.EXT.ConstantCompositeReplicate`. |
| 653 | DenseMap<uint32_t, std::pair<Attribute, Type>> constantCompositeReplicateMap; |
| 654 | |
| 655 | // Result <id> to spec constant mapping. |
| 656 | DenseMap<uint32_t, spirv::SpecConstantOp> specConstMap; |
| 657 | |
| 658 | // Result <id> to composite spec constant mapping. |
| 659 | DenseMap<uint32_t, spirv::SpecConstantCompositeOp> specConstCompositeMap; |
| 660 | |
| 661 | // Result <id> to replicated composite spec constant mapping. |
| 662 | DenseMap<uint32_t, spirv::EXTSpecConstantCompositeReplicateOp> |
| 663 | specConstCompositeReplicateMap; |
| 664 | |
| 665 | /// Result <id> to info needed to materialize an OpSpecConstantOp |
| 666 | /// mapping. |
| 667 | DenseMap<uint32_t, SpecConstOperationMaterializationInfo> |
| 668 | specConstOperationMap; |
| 669 | |
| 670 | // Result <id> to GraphConstantARM ID attribute and result type. |
| 671 | DenseMap<uint32_t, spirv::GraphConstantARMOpMaterializationInfo> |
| 672 | graphConstantMap; |
| 673 | |
| 674 | // Result <id> to variable mapping. |
| 675 | DenseMap<uint32_t, spirv::GlobalVariableOp> globalVariableMap; |
| 676 | |
| 677 | // Result <id> to function mapping. |
| 678 | DenseMap<uint32_t, spirv::FuncOp> funcMap; |
| 679 | |
| 680 | // Result <id> to function mapping. |
| 681 | DenseMap<uint32_t, spirv::GraphARMOp> graphMap; |
| 682 | |
| 683 | // Result <id> to block mapping. |
| 684 | DenseMap<uint32_t, Block *> blockMap; |
| 685 | |
| 686 | // Header block to its merge (and continue) target mapping. |
| 687 | BlockMergeInfoMap blockMergeInfo; |
| 688 | |
| 689 | // For each pair of {predecessor, target} blocks, maps the pair of blocks to |
| 690 | // the list of phi arguments passed from predecessor to target. |
| 691 | DenseMap<std::pair<Block * /*predecessor*/, Block * /*target*/>, BlockPhiInfo> |
| 692 | blockPhiInfo; |
| 693 | |
| 694 | // Result <id> to value mapping. |
| 695 | DenseMap<uint32_t, Value> valueMap; |
| 696 | |
| 697 | // Mapping from result <id> to undef value of a type. |
| 698 | DenseMap<uint32_t, Type> undefMap; |
| 699 | |
| 700 | // Constant and undef ops already materialized in a block of the current |
| 701 | // function or graph. |
| 702 | DenseMap<std::pair<Block *, uint32_t>, Value> blockConstantMap; |
| 703 | |
| 704 | // Result <id> to name mapping. |
| 705 | DenseMap<uint32_t, StringRef> nameMap; |
| 706 | |
| 707 | // Result <id> to debug info mapping. |
| 708 | DenseMap<uint32_t, StringRef> debugInfoMap; |
| 709 | |
| 710 | // Result <id> to decorations mapping. |
| 711 | DenseMap<uint32_t, NamedAttrList> decorations; |
| 712 | |
| 713 | // FuncParamAttr decorations awaiting an OpFunctionParameter or OpFunction. |
| 714 | // Keeping them separate prevents unsupported targets from acquiring |
| 715 | // discardable attributes that would be silently dropped during serialization. |
| 716 | DenseMap<uint32_t, ArrayAttr> functionParameterAttrs; |
| 717 | |
| 718 | // Decoration entries from OpDecorateId whose operand <id>s must be resolved |
| 719 | // to MLIR symbols after all module ops have been deserialized. |
| 720 | struct DeferredIdDecoration { |
| 721 | uint32_t targetID; |
| 722 | spirv::Decoration decoration; |
| 723 | uint32_t operandID; |
| 724 | Location loc; |
| 725 | }; |
| 726 | SmallVector<DeferredIdDecoration> pendingIdDecorations; |
| 727 | |
| 728 | // Result <id> to type decorations. |
| 729 | DenseMap<uint32_t, uint32_t> typeDecorations; |
| 730 | |
| 731 | // Result <id> to member decorations. |
| 732 | // decorated-struct-type-<id> -> |
| 733 | // (struct-member-index -> (decoration -> decoration-operands)) |
| 734 | DenseMap<uint32_t, |
| 735 | DenseMap<uint32_t, DenseMap<spirv::Decoration, ArrayRef<uint32_t>>>> |
| 736 | memberDecorationMap; |
| 737 | |
| 738 | // Result <id> to member name. |
| 739 | // struct-type-<id> -> (struct-member-index -> name) |
| 740 | DenseMap<uint32_t, DenseMap<uint32_t, StringRef>> memberNameMap; |
| 741 | |
| 742 | // Result <id> to extended instruction set name. |
| 743 | DenseMap<uint32_t, StringRef> extendedInstSets; |
| 744 | |
| 745 | // List of instructions that are processed in a deferred fashion (after an |
| 746 | // initial processing of the entire binary). Some operations like |
| 747 | // OpEntryPoint, and OpExecutionMode use forward references to function |
| 748 | // <id>s. In SPIR-V dialect the corresponding operations (spirv.EntryPoint and |
| 749 | // spirv.ExecutionMode) need these references resolved. So these instructions |
| 750 | // are deserialized and stored for processing once the entire binary is |
| 751 | // processed. |
| 752 | SmallVector<std::pair<spirv::Opcode, ArrayRef<uint32_t>>, 4> |
| 753 | deferredInstructions; |
| 754 | |
| 755 | /// A list of IDs for all types forward-declared through OpTypeForwardPointer |
| 756 | /// instructions. |
| 757 | SetVector<uint32_t> typeForwardPointerIDs; |
| 758 | |
| 759 | /// A list of all structs which have unresolved member types. |
| 760 | SmallVector<DeferredStructTypeInfo, 0> deferredStructTypesInfos; |
| 761 | |
| 762 | /// Deserialization options. |
| 763 | DeserializationOptions options; |
| 764 | |
| 765 | /// List of IDs assigned to graph outputs. |
| 766 | SmallVector<Value> graphOutputs; |
| 767 | |
| 768 | #ifndef NDEBUG |
| 769 | /// A logger used to emit information during the deserialzation process. |
| 770 | llvm::ScopedPrinter logger; |
| 771 | #endif |
| 772 | }; |
| 773 | |
| 774 | } // namespace spirv |
| 775 | } // namespace mlir |
| 776 | |
| 777 | #endif // MLIR_TARGET_SPIRV_DESERIALIZER_H |
| 778 | |