Merge pull request #911 from KhronosGroup/debug-info
[platform/upstream/glslang.git] / SPIRV / spvIR.h
1 //
2 // Copyright (C) 2014 LunarG, Inc.
3 //
4 // All rights reserved.
5 //
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions
8 // are met:
9 //
10 //    Redistributions of source code must retain the above copyright
11 //    notice, this list of conditions and the following disclaimer.
12 //
13 //    Redistributions in binary form must reproduce the above
14 //    copyright notice, this list of conditions and the following
15 //    disclaimer in the documentation and/or other materials provided
16 //    with the distribution.
17 //
18 //    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
19 //    contributors may be used to endorse or promote products derived
20 //    from this software without specific prior written permission.
21 //
22 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
32 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 // POSSIBILITY OF SUCH DAMAGE.
34
35 // SPIRV-IR
36 //
37 // Simple in-memory representation (IR) of SPIRV.  Just for holding
38 // Each function's CFG of blocks.  Has this hierarchy:
39 //  - Module, which is a list of
40 //    - Function, which is a list of
41 //      - Block, which is a list of
42 //        - Instruction
43 //
44
45 #pragma once
46 #ifndef spvIR_H
47 #define spvIR_H
48
49 #include "spirv.hpp"
50
51 #include <algorithm>
52 #include <cassert>
53 #include <functional>
54 #include <iostream>
55 #include <memory>
56 #include <vector>
57
58 namespace spv {
59
60 class Block;
61 class Function;
62 class Module;
63
64 const Id NoResult = 0;
65 const Id NoType = 0;
66
67 const Decoration NoPrecision = DecorationMax;
68 const MemorySemanticsMask MemorySemanticsAllMemory =
69                 (MemorySemanticsMask)(MemorySemanticsSequentiallyConsistentMask |
70                                       MemorySemanticsUniformMemoryMask |
71                                       MemorySemanticsSubgroupMemoryMask |
72                                       MemorySemanticsWorkgroupMemoryMask |
73                                       MemorySemanticsCrossWorkgroupMemoryMask |
74                                       MemorySemanticsAtomicCounterMemoryMask |
75                                       MemorySemanticsImageMemoryMask);
76
77 //
78 // SPIR-V IR instruction.
79 //
80
81 class Instruction {
82 public:
83     Instruction(Id resultId, Id typeId, Op opCode) : resultId(resultId), typeId(typeId), opCode(opCode), block(nullptr) { }
84     explicit Instruction(Op opCode) : resultId(NoResult), typeId(NoType), opCode(opCode), block(nullptr) { }
85     virtual ~Instruction() {}
86     void addIdOperand(Id id) { operands.push_back(id); }
87     void addImmediateOperand(unsigned int immediate) { operands.push_back(immediate); }
88     void addStringOperand(const char* str)
89     {
90         unsigned int word;
91         char* wordString = (char*)&word;
92         char* wordPtr = wordString;
93         int charCount = 0;
94         char c;
95         do {
96             c = *(str++);
97             *(wordPtr++) = c;
98             ++charCount;
99             if (charCount == 4) {
100                 addImmediateOperand(word);
101                 wordPtr = wordString;
102                 charCount = 0;
103             }
104         } while (c != 0);
105
106         // deal with partial last word
107         if (charCount > 0) {
108             // pad with 0s
109             for (; charCount < 4; ++charCount)
110                 *(wordPtr++) = 0;
111             addImmediateOperand(word);
112         }
113     }
114     void setBlock(Block* b) { block = b; }
115     Block* getBlock() const { return block; }
116     Op getOpCode() const { return opCode; }
117     int getNumOperands() const { return (int)operands.size(); }
118     Id getResultId() const { return resultId; }
119     Id getTypeId() const { return typeId; }
120     Id getIdOperand(int op) const { return operands[op]; }
121     unsigned int getImmediateOperand(int op) const { return operands[op]; }
122
123     // Write out the binary form.
124     void dump(std::vector<unsigned int>& out) const
125     {
126         // Compute the wordCount
127         unsigned int wordCount = 1;
128         if (typeId)
129             ++wordCount;
130         if (resultId)
131             ++wordCount;
132         wordCount += (unsigned int)operands.size();
133
134         // Write out the beginning of the instruction
135         out.push_back(((wordCount) << WordCountShift) | opCode);
136         if (typeId)
137             out.push_back(typeId);
138         if (resultId)
139             out.push_back(resultId);
140
141         // Write out the operands
142         for (int op = 0; op < (int)operands.size(); ++op)
143             out.push_back(operands[op]);
144     }
145
146 protected:
147     Instruction(const Instruction&);
148     Id resultId;
149     Id typeId;
150     Op opCode;
151     std::vector<Id> operands;
152     Block* block;
153 };
154
155 //
156 // SPIR-V IR block.
157 //
158
159 class Block {
160 public:
161     Block(Id id, Function& parent);
162     virtual ~Block()
163     {
164     }
165
166     Id getId() { return instructions.front()->getResultId(); }
167
168     Function& getParent() const { return parent; }
169     void addInstruction(std::unique_ptr<Instruction> inst);
170     void addPredecessor(Block* pred) { predecessors.push_back(pred); pred->successors.push_back(this);}
171     void addLocalVariable(std::unique_ptr<Instruction> inst) { localVariables.push_back(std::move(inst)); }
172     const std::vector<Block*>& getPredecessors() const { return predecessors; }
173     const std::vector<Block*>& getSuccessors() const { return successors; }
174     const std::vector<std::unique_ptr<Instruction> >& getInstructions() const {
175         return instructions;
176     }
177     void setUnreachable() { unreachable = true; }
178     bool isUnreachable() const { return unreachable; }
179     // Returns the block's merge instruction, if one exists (otherwise null).
180     const Instruction* getMergeInstruction() const {
181         if (instructions.size() < 2) return nullptr;
182         const Instruction* nextToLast = (instructions.cend() - 2)->get();
183         switch (nextToLast->getOpCode()) {
184             case OpSelectionMerge:
185             case OpLoopMerge:
186                 return nextToLast;
187             default:
188                 return nullptr;
189         }
190         return nullptr;
191     }
192
193     bool isTerminated() const
194     {
195         switch (instructions.back()->getOpCode()) {
196         case OpBranch:
197         case OpBranchConditional:
198         case OpSwitch:
199         case OpKill:
200         case OpReturn:
201         case OpReturnValue:
202             return true;
203         default:
204             return false;
205         }
206     }
207
208     void dump(std::vector<unsigned int>& out) const
209     {
210         instructions[0]->dump(out);
211         for (int i = 0; i < (int)localVariables.size(); ++i)
212             localVariables[i]->dump(out);
213         for (int i = 1; i < (int)instructions.size(); ++i)
214             instructions[i]->dump(out);
215     }
216
217 protected:
218     Block(const Block&);
219     Block& operator=(Block&);
220
221     // To enforce keeping parent and ownership in sync:
222     friend Function;
223
224     std::vector<std::unique_ptr<Instruction> > instructions;
225     std::vector<Block*> predecessors, successors;
226     std::vector<std::unique_ptr<Instruction> > localVariables;
227     Function& parent;
228
229     // track whether this block is known to be uncreachable (not necessarily
230     // true for all unreachable blocks, but should be set at least
231     // for the extraneous ones introduced by the builder).
232     bool unreachable;
233 };
234
235 // Traverses the control-flow graph rooted at root in an order suited for
236 // readable code generation.  Invokes callback at every node in the traversal
237 // order.
238 void inReadableOrder(Block* root, std::function<void(Block*)> callback);
239
240 //
241 // SPIR-V IR Function.
242 //
243
244 class Function {
245 public:
246     Function(Id id, Id resultType, Id functionType, Id firstParam, Module& parent);
247     virtual ~Function()
248     {
249         for (int i = 0; i < (int)parameterInstructions.size(); ++i)
250             delete parameterInstructions[i];
251
252         for (int i = 0; i < (int)blocks.size(); ++i)
253             delete blocks[i];
254     }
255     Id getId() const { return functionInstruction.getResultId(); }
256     Id getParamId(int p) { return parameterInstructions[p]->getResultId(); }
257
258     void addBlock(Block* block) { blocks.push_back(block); }
259     void removeBlock(Block* block)
260     {
261         auto found = find(blocks.begin(), blocks.end(), block);
262         assert(found != blocks.end());
263         blocks.erase(found);
264         delete block;
265     }
266
267     Module& getParent() const { return parent; }
268     Block* getEntryBlock() const { return blocks.front(); }
269     Block* getLastBlock() const { return blocks.back(); }
270     const std::vector<Block*>& getBlocks() const { return blocks; }
271     void addLocalVariable(std::unique_ptr<Instruction> inst);
272     Id getReturnType() const { return functionInstruction.getTypeId(); }
273
274     void setImplicitThis() { implicitThis = true; }
275     bool hasImplicitThis() const { return implicitThis; }
276
277     void dump(std::vector<unsigned int>& out) const
278     {
279         // OpFunction
280         functionInstruction.dump(out);
281
282         // OpFunctionParameter
283         for (int p = 0; p < (int)parameterInstructions.size(); ++p)
284             parameterInstructions[p]->dump(out);
285
286         // Blocks
287         inReadableOrder(blocks[0], [&out](const Block* b) { b->dump(out); });
288         Instruction end(0, 0, OpFunctionEnd);
289         end.dump(out);
290     }
291
292 protected:
293     Function(const Function&);
294     Function& operator=(Function&);
295
296     Module& parent;
297     Instruction functionInstruction;
298     std::vector<Instruction*> parameterInstructions;
299     std::vector<Block*> blocks;
300     bool implicitThis;  // true if this is a member function expecting to be passed a 'this' as the first argument
301 };
302
303 //
304 // SPIR-V IR Module.
305 //
306
307 class Module {
308 public:
309     Module() {}
310     virtual ~Module()
311     {
312         // TODO delete things
313     }
314
315     void addFunction(Function *fun) { functions.push_back(fun); }
316
317     void mapInstruction(Instruction *instruction)
318     {
319         spv::Id resultId = instruction->getResultId();
320         // map the instruction's result id
321         if (resultId >= idToInstruction.size())
322             idToInstruction.resize(resultId + 16);
323         idToInstruction[resultId] = instruction;
324     }
325
326     Instruction* getInstruction(Id id) const { return idToInstruction[id]; }
327     const std::vector<Function*>& getFunctions() const { return functions; }
328     spv::Id getTypeId(Id resultId) const { return idToInstruction[resultId]->getTypeId(); }
329     StorageClass getStorageClass(Id typeId) const
330     {
331         assert(idToInstruction[typeId]->getOpCode() == spv::OpTypePointer);
332         return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0);
333     }
334
335     void dump(std::vector<unsigned int>& out) const
336     {
337         for (int f = 0; f < (int)functions.size(); ++f)
338             functions[f]->dump(out);
339     }
340
341 protected:
342     Module(const Module&);
343     std::vector<Function*> functions;
344
345     // map from result id to instruction having that result id
346     std::vector<Instruction*> idToInstruction;
347
348     // map from a result id to its type id
349 };
350
351 //
352 // Implementation (it's here due to circular type definitions).
353 //
354
355 // Add both
356 // - the OpFunction instruction
357 // - all the OpFunctionParameter instructions
358 __inline Function::Function(Id id, Id resultType, Id functionType, Id firstParamId, Module& parent)
359     : parent(parent), functionInstruction(id, resultType, OpFunction), implicitThis(false)
360 {
361     // OpFunction
362     functionInstruction.addImmediateOperand(FunctionControlMaskNone);
363     functionInstruction.addIdOperand(functionType);
364     parent.mapInstruction(&functionInstruction);
365     parent.addFunction(this);
366
367     // OpFunctionParameter
368     Instruction* typeInst = parent.getInstruction(functionType);
369     int numParams = typeInst->getNumOperands() - 1;
370     for (int p = 0; p < numParams; ++p) {
371         Instruction* param = new Instruction(firstParamId + p, typeInst->getIdOperand(p + 1), OpFunctionParameter);
372         parent.mapInstruction(param);
373         parameterInstructions.push_back(param);
374     }
375 }
376
377 __inline void Function::addLocalVariable(std::unique_ptr<Instruction> inst)
378 {
379     Instruction* raw_instruction = inst.get();
380     blocks[0]->addLocalVariable(std::move(inst));
381     parent.mapInstruction(raw_instruction);
382 }
383
384 __inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
385 {
386     instructions.push_back(std::unique_ptr<Instruction>(new Instruction(id, NoType, OpLabel)));
387     instructions.back()->setBlock(this);
388     parent.getParent().mapInstruction(instructions.back().get());
389 }
390
391 __inline void Block::addInstruction(std::unique_ptr<Instruction> inst)
392 {
393     Instruction* raw_instruction = inst.get();
394     instructions.push_back(std::move(inst));
395     raw_instruction->setBlock(this);
396     if (raw_instruction->getResultId())
397         parent.getParent().mapInstruction(raw_instruction);
398 }
399
400 };  // end spv namespace
401
402 #endif // spvIR_H