1 //===- Serializer.h - MLIR SPIR-V Serializer ------------------------------===//
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 MLIR SPIR-V module to SPIR-V binary serializer.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef MLIR_LIB_TARGET_SPIRV_SERIALIZATION_SERIALIZER_H
14 #define MLIR_LIB_TARGET_SPIRV_SERIALIZATION_SERIALIZER_H
15 
16 #include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
17 #include "mlir/IR/Builders.h"
18 #include "mlir/Target/SPIRV/Serialization.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/Support/raw_ostream.h"
22 
23 namespace mlir {
24 namespace spirv {
25 
26 void encodeInstructionInto(SmallVectorImpl<uint32_t> &binary, spirv::Opcode op,
27                            ArrayRef<uint32_t> operands);
28 
29 /// A SPIR-V module serializer.
30 ///
31 /// A SPIR-V binary module is a single linear stream of instructions; each
32 /// instruction is composed of 32-bit words with the layout:
33 ///
34 ///   | <word-count>|<opcode> |  <operand>   |  <operand>   | ... |
35 ///   | <------ word -------> | <-- word --> | <-- word --> | ... |
36 ///
37 /// For the first word, the 16 high-order bits are the word count of the
38 /// instruction, the 16 low-order bits are the opcode enumerant. The
39 /// instructions then belong to different sections, which must be laid out in
40 /// the particular order as specified in "2.4 Logical Layout of a Module" of
41 /// the SPIR-V spec.
42 class Serializer {
43 public:
44   /// Creates a serializer for the given SPIR-V `module`.
45   explicit Serializer(spirv::ModuleOp module,
46                       const SerializationOptions &options);
47 
48   /// Serializes the remembered SPIR-V module.
49   LogicalResult serialize();
50 
51   /// Collects the final SPIR-V `binary`.
52   void collect(SmallVectorImpl<uint32_t> &binary);
53 
54 #ifndef NDEBUG
55   /// (For debugging) prints each value and its corresponding result <id>.
56   void printValueIDMap(raw_ostream &os);
57 #endif
58 
59 private:
60   // Note that there are two main categories of methods in this class:
61   // * process*() methods are meant to fully serialize a SPIR-V module entity
62   //   (header, type, op, etc.). They update internal vectors containing
63   //   different binary sections. They are not meant to be called except the
64   //   top-level serialization loop.
65   // * prepare*() methods are meant to be helpers that prepare for serializing
66   //   certain entity. They may or may not update internal vectors containing
67   //   different binary sections. They are meant to be called among themselves
68   //   or by other process*() methods for subtasks.
69 
70   //===--------------------------------------------------------------------===//
71   // <id>
72   //===--------------------------------------------------------------------===//
73 
74   // Note that it is illegal to use id <0> in SPIR-V binary module. Various
75   // methods in this class, if using SPIR-V word (uint32_t) as interface,
76   // check or return id <0> to indicate error in processing.
77 
78   /// Consumes the next unused <id>. This method will never return 0.
79   uint32_t getNextID() { return nextID++; }
80 
81   //===--------------------------------------------------------------------===//
82   // Module structure
83   //===--------------------------------------------------------------------===//
84 
85   uint32_t getSpecConstID(StringRef constName) const {
86     return specConstIDMap.lookup(constName);
87   }
88 
89   uint32_t getVariableID(StringRef varName) const {
90     return globalVarIDMap.lookup(varName);
91   }
92 
93   uint32_t getFunctionID(StringRef fnName) const {
94     return funcIDMap.lookup(fnName);
95   }
96 
97   /// Gets the <id> for the function with the given name. Assigns the next
98   /// available <id> if the function haven't been deserialized.
99   uint32_t getOrCreateFunctionID(StringRef fnName);
100 
101   void processCapability();
102 
103   void processDebugInfo();
104 
105   void processExtension();
106 
107   void processMemoryModel();
108 
109   LogicalResult processConstantOp(spirv::ConstantOp op);
110 
111   LogicalResult processSpecConstantOp(spirv::SpecConstantOp op);
112 
113   LogicalResult
114   processSpecConstantCompositeOp(spirv::SpecConstantCompositeOp op);
115 
116   LogicalResult
117   processSpecConstantOperationOp(spirv::SpecConstantOperationOp op);
118 
119   /// SPIR-V dialect supports OpUndef using spv.UndefOp that produces a SSA
120   /// value to use with other operations. The SPIR-V spec recommends that
121   /// OpUndef be generated at module level. The serialization generates an
122   /// OpUndef for each type needed at module level.
123   LogicalResult processUndefOp(spirv::UndefOp op);
124 
125   /// Emit OpName for the given `resultID`.
126   LogicalResult processName(uint32_t resultID, StringRef name);
127 
128   /// Processes a SPIR-V function op.
129   LogicalResult processFuncOp(spirv::FuncOp op);
130 
131   LogicalResult processVariableOp(spirv::VariableOp op);
132 
133   /// Process a SPIR-V GlobalVariableOp
134   LogicalResult processGlobalVariableOp(spirv::GlobalVariableOp varOp);
135 
136   /// Process attributes that translate to decorations on the result <id>
137   LogicalResult processDecoration(Location loc, uint32_t resultID,
138                                   NamedAttribute attr);
139 
140   template <typename DType>
141   LogicalResult processTypeDecoration(Location loc, DType type,
142                                       uint32_t resultId) {
143     return emitError(loc, "unhandled decoration for type:") << type;
144   }
145 
146   /// Process member decoration
147   LogicalResult processMemberDecoration(
148       uint32_t structID,
149       const spirv::StructType::MemberDecorationInfo &memberDecorationInfo);
150 
151   //===--------------------------------------------------------------------===//
152   // Types
153   //===--------------------------------------------------------------------===//
154 
155   uint32_t getTypeID(Type type) const { return typeIDMap.lookup(type); }
156 
157   Type getVoidType() { return mlirBuilder.getNoneType(); }
158 
159   bool isVoidType(Type type) const { return type.isa<NoneType>(); }
160 
161   /// Returns true if the given type is a pointer type to a struct in some
162   /// interface storage class.
163   bool isInterfaceStructPtrType(Type type) const;
164 
165   /// Main dispatch method for serializing a type. The result <id> of the
166   /// serialized type will be returned as `typeID`.
167   LogicalResult processType(Location loc, Type type, uint32_t &typeID);
168   LogicalResult processTypeImpl(Location loc, Type type, uint32_t &typeID,
169                                 SetVector<StringRef> &serializationCtx);
170 
171   /// Method for preparing basic SPIR-V type serialization. Returns the type's
172   /// opcode and operands for the instruction via `typeEnum` and `operands`.
173   LogicalResult prepareBasicType(Location loc, Type type, uint32_t resultID,
174                                  spirv::Opcode &typeEnum,
175                                  SmallVectorImpl<uint32_t> &operands,
176                                  bool &deferSerialization,
177                                  SetVector<StringRef> &serializationCtx);
178 
179   LogicalResult prepareFunctionType(Location loc, FunctionType type,
180                                     spirv::Opcode &typeEnum,
181                                     SmallVectorImpl<uint32_t> &operands);
182 
183   //===--------------------------------------------------------------------===//
184   // Constant
185   //===--------------------------------------------------------------------===//
186 
187   uint32_t getConstantID(Attribute value) const {
188     return constIDMap.lookup(value);
189   }
190 
191   /// Main dispatch method for processing a constant with the given `constType`
192   /// and `valueAttr`. `constType` is needed here because we can interpret the
193   /// `valueAttr` as a different type than the type of `valueAttr` itself; for
194   /// example, ArrayAttr, whose type is NoneType, is used for spirv::ArrayType
195   /// constants.
196   uint32_t prepareConstant(Location loc, Type constType, Attribute valueAttr);
197 
198   /// Prepares array attribute serialization. This method emits corresponding
199   /// OpConstant* and returns the result <id> associated with it. Returns 0 if
200   /// failed.
201   uint32_t prepareArrayConstant(Location loc, Type constType, ArrayAttr attr);
202 
203   /// Prepares bool/int/float DenseElementsAttr serialization. This method
204   /// iterates the DenseElementsAttr to construct the constant array, and
205   /// returns the result <id>  associated with it. Returns 0 if failed. Note
206   /// that the size of `index` must match the rank.
207   /// TODO: Consider to enhance splat elements cases. For splat cases,
208   /// we don't need to loop over all elements, especially when the splat value
209   /// is zero. We can use OpConstantNull when the value is zero.
210   uint32_t prepareDenseElementsConstant(Location loc, Type constType,
211                                         DenseElementsAttr valueAttr, int dim,
212                                         MutableArrayRef<uint64_t> index);
213 
214   /// Prepares scalar attribute serialization. This method emits corresponding
215   /// OpConstant* and returns the result <id> associated with it. Returns 0 if
216   /// the attribute is not for a scalar bool/integer/float value. If `isSpec` is
217   /// true, then the constant will be serialized as a specialization constant.
218   uint32_t prepareConstantScalar(Location loc, Attribute valueAttr,
219                                  bool isSpec = false);
220 
221   uint32_t prepareConstantBool(Location loc, BoolAttr boolAttr,
222                                bool isSpec = false);
223 
224   uint32_t prepareConstantInt(Location loc, IntegerAttr intAttr,
225                               bool isSpec = false);
226 
227   uint32_t prepareConstantFp(Location loc, FloatAttr floatAttr,
228                              bool isSpec = false);
229 
230   //===--------------------------------------------------------------------===//
231   // Control flow
232   //===--------------------------------------------------------------------===//
233 
234   /// Returns the result <id> for the given block.
235   uint32_t getBlockID(Block *block) const { return blockIDMap.lookup(block); }
236 
237   /// Returns the result <id> for the given block. If no <id> has been assigned,
238   /// assigns the next available <id>
239   uint32_t getOrCreateBlockID(Block *block);
240 
241   /// Processes the given `block` and emits SPIR-V instructions for all ops
242   /// inside. Does not emit OpLabel for this block if `omitLabel` is true.
243   /// `actionBeforeTerminator` is a callback that will be invoked before
244   /// handling the terminator op. It can be used to inject the Op*Merge
245   /// instruction if this is a SPIR-V selection/loop header block.
246   LogicalResult
247   processBlock(Block *block, bool omitLabel = false,
248                function_ref<LogicalResult()> actionBeforeTerminator = nullptr);
249 
250   /// Emits OpPhi instructions for the given block if it has block arguments.
251   LogicalResult emitPhiForBlockArguments(Block *block);
252 
253   LogicalResult processSelectionOp(spirv::SelectionOp selectionOp);
254 
255   LogicalResult processLoopOp(spirv::LoopOp loopOp);
256 
257   LogicalResult processBranchConditionalOp(spirv::BranchConditionalOp);
258 
259   LogicalResult processBranchOp(spirv::BranchOp branchOp);
260 
261   //===--------------------------------------------------------------------===//
262   // Operations
263   //===--------------------------------------------------------------------===//
264 
265   LogicalResult encodeExtensionInstruction(Operation *op,
266                                            StringRef extensionSetName,
267                                            uint32_t opcode,
268                                            ArrayRef<uint32_t> operands);
269 
270   uint32_t getValueID(Value val) const { return valueIDMap.lookup(val); }
271 
272   LogicalResult processAddressOfOp(spirv::AddressOfOp addressOfOp);
273 
274   LogicalResult processReferenceOfOp(spirv::ReferenceOfOp referenceOfOp);
275 
276   /// Main dispatch method for serializing an operation.
277   LogicalResult processOperation(Operation *op);
278 
279   /// Serializes an operation `op` as core instruction with `opcode` if
280   /// `extInstSet` is empty. Otherwise serializes it as an extended instruction
281   /// with `opcode` from `extInstSet`.
282   /// This method is a generic one for dispatching any SPIR-V ops that has no
283   /// variadic operands and attributes in TableGen definitions.
284   LogicalResult processOpWithoutGrammarAttr(Operation *op, StringRef extInstSet,
285                                             uint32_t opcode);
286 
287   /// Dispatches to the serialization function for an operation in SPIR-V
288   /// dialect that is a mirror of an instruction in the SPIR-V spec. This is
289   /// auto-generated from ODS. Dispatch is handled for all operations in SPIR-V
290   /// dialect that have hasOpcode == 1.
291   LogicalResult dispatchToAutogenSerialization(Operation *op);
292 
293   /// Serializes an operation in the SPIR-V dialect that is a mirror of an
294   /// instruction in the SPIR-V spec. This is auto generated if hasOpcode == 1
295   /// and autogenSerialization == 1 in ODS.
296   template <typename OpTy> LogicalResult processOp(OpTy op) {
297     return op.emitError("unsupported op serialization");
298   }
299 
300   //===--------------------------------------------------------------------===//
301   // Utilities
302   //===--------------------------------------------------------------------===//
303 
304   /// Emits an OpDecorate instruction to decorate the given `target` with the
305   /// given `decoration`.
306   LogicalResult emitDecoration(uint32_t target, spirv::Decoration decoration,
307                                ArrayRef<uint32_t> params = {});
308 
309   /// Emits an OpLine instruction with the given `loc` location information into
310   /// the given `binary` vector.
311   LogicalResult emitDebugLine(SmallVectorImpl<uint32_t> &binary, Location loc);
312 
313 private:
314   /// The SPIR-V module to be serialized.
315   spirv::ModuleOp module;
316 
317   /// An MLIR builder for getting MLIR constructs.
318   mlir::Builder mlirBuilder;
319 
320   /// Serialization options.
321   SerializationOptions options;
322 
323   /// A flag which indicates if the last processed instruction was a merge
324   /// instruction.
325   /// According to SPIR-V spec: "If a branch merge instruction is used, the last
326   /// OpLine in the block must be before its merge instruction".
327   bool lastProcessedWasMergeInst = false;
328 
329   /// The <id> of the OpString instruction, which specifies a file name, for
330   /// use by other debug instructions.
331   uint32_t fileID = 0;
332 
333   /// The next available result <id>.
334   uint32_t nextID = 1;
335 
336   // The following are for different SPIR-V instruction sections. They follow
337   // the logical layout of a SPIR-V module.
338 
339   SmallVector<uint32_t, 4> capabilities;
340   SmallVector<uint32_t, 0> extensions;
341   SmallVector<uint32_t, 0> extendedSets;
342   SmallVector<uint32_t, 3> memoryModel;
343   SmallVector<uint32_t, 0> entryPoints;
344   SmallVector<uint32_t, 4> executionModes;
345   SmallVector<uint32_t, 0> debug;
346   SmallVector<uint32_t, 0> names;
347   SmallVector<uint32_t, 0> decorations;
348   SmallVector<uint32_t, 0> typesGlobalValues;
349   SmallVector<uint32_t, 0> functions;
350 
351   /// Recursive struct references are serialized as OpTypePointer instructions
352   /// to the recursive struct type. However, the OpTypePointer instruction
353   /// cannot be emitted before the recursive struct's OpTypeStruct.
354   /// RecursiveStructPointerInfo stores the data needed to emit such
355   /// OpTypePointer instructions after forward references to such types.
356   struct RecursiveStructPointerInfo {
357     uint32_t pointerTypeID;
358     spirv::StorageClass storageClass;
359   };
360 
361   // Maps spirv::StructType to its recursive reference member info.
362   DenseMap<Type, SmallVector<RecursiveStructPointerInfo, 0>>
363       recursiveStructInfos;
364 
365   /// `functionHeader` contains all the instructions that must be in the first
366   /// block in the function, and `functionBody` contains the rest. After
367   /// processing FuncOp, the encoded instructions of a function are appended to
368   /// `functions`. An example of instructions in `functionHeader` in order:
369   /// OpFunction ...
370   /// OpFunctionParameter ...
371   /// OpFunctionParameter ...
372   /// OpLabel ...
373   /// OpVariable ...
374   /// OpVariable ...
375   SmallVector<uint32_t, 0> functionHeader;
376   SmallVector<uint32_t, 0> functionBody;
377 
378   /// Map from type used in SPIR-V module to their <id>s.
379   DenseMap<Type, uint32_t> typeIDMap;
380 
381   /// Map from constant values to their <id>s.
382   DenseMap<Attribute, uint32_t> constIDMap;
383 
384   /// Map from specialization constant names to their <id>s.
385   llvm::StringMap<uint32_t> specConstIDMap;
386 
387   /// Map from GlobalVariableOps name to <id>s.
388   llvm::StringMap<uint32_t> globalVarIDMap;
389 
390   /// Map from FuncOps name to <id>s.
391   llvm::StringMap<uint32_t> funcIDMap;
392 
393   /// Map from blocks to their <id>s.
394   DenseMap<Block *, uint32_t> blockIDMap;
395 
396   /// Map from the Type to the <id> that represents undef value of that type.
397   DenseMap<Type, uint32_t> undefValIDMap;
398 
399   /// Map from results of normal operations to their <id>s.
400   DenseMap<Value, uint32_t> valueIDMap;
401 
402   /// Map from extended instruction set name to <id>s.
403   llvm::StringMap<uint32_t> extendedInstSetIDMap;
404 
405   /// Map from values used in OpPhi instructions to their offset in the
406   /// `functions` section.
407   ///
408   /// When processing a block with arguments, we need to emit OpPhi
409   /// instructions to record the predecessor block <id>s and the values they
410   /// send to the block in question. But it's not guaranteed all values are
411   /// visited and thus assigned result <id>s. So we need this list to capture
412   /// the offsets into `functions` where a value is used so that we can fix it
413   /// up later after processing all the blocks in a function.
414   ///
415   /// More concretely, say if we are visiting the following blocks:
416   ///
417   /// ```mlir
418   /// ^phi(%arg0: i32):
419   ///   ...
420   /// ^parent1:
421   ///   ...
422   ///   spv.Branch ^phi(%val0: i32)
423   /// ^parent2:
424   ///   ...
425   ///   spv.Branch ^phi(%val1: i32)
426   /// ```
427   ///
428   /// When we are serializing the `^phi` block, we need to emit at the beginning
429   /// of the block OpPhi instructions which has the following parameters:
430   ///
431   /// OpPhi id-for-i32 id-for-%arg0 id-for-%val0 id-for-^parent1
432   ///                               id-for-%val1 id-for-^parent2
433   ///
434   /// But we don't know the <id> for %val0 and %val1 yet. One way is to visit
435   /// all the blocks twice and use the first visit to assign an <id> to each
436   /// value. But it's paying the overheads just for OpPhi emission. Instead,
437   /// we still visit the blocks once for emission. When we emit the OpPhi
438   /// instructions, we use 0 as a placeholder for the <id>s for %val0 and %val1.
439   /// At the same time, we record their offsets in the emitted binary (which is
440   /// placed inside `functions`) here. And then after emitting all blocks, we
441   /// replace the dummy <id> 0 with the real result <id> by overwriting
442   /// `functions[offset]`.
443   DenseMap<Value, SmallVector<size_t, 1>> deferredPhiValues;
444 };
445 } // namespace spirv
446 } // namespace mlir
447 
448 #endif // MLIR_LIB_TARGET_SPIRV_SERIALIZATION_SERIALIZER_H
449