Merge remote-tracking branch 'upstream/master'
[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 unsigned int BadValue = 0xFFFFFFFF;
68 const Decoration NoPrecision = (Decoration)BadValue;
69 const MemorySemanticsMask MemorySemanticsAllMemory = 
70                 (MemorySemanticsMask)(MemorySemanticsSequentiallyConsistentMask |
71                                       MemorySemanticsUniformMemoryMask |
72                                       MemorySemanticsSubgroupMemoryMask |
73                                       MemorySemanticsWorkgroupMemoryMask |
74                                       MemorySemanticsCrossWorkgroupMemoryMask |
75                                       MemorySemanticsAtomicCounterMemoryMask |
76                                       MemorySemanticsImageMemoryMask);
77
78 //
79 // SPIR-V IR instruction.
80 //
81
82 class Instruction {
83 public:
84     Instruction(Id resultId, Id typeId, Op opCode) : resultId(resultId), typeId(typeId), opCode(opCode), block(nullptr) { }
85     explicit Instruction(Op opCode) : resultId(NoResult), typeId(NoType), opCode(opCode), block(nullptr) { }
86     virtual ~Instruction() {}
87     void addIdOperand(Id id) { operands.push_back(id); }
88     void addImmediateOperand(unsigned int immediate) { operands.push_back(immediate); }
89     void addStringOperand(const char* str)
90     {
91         originalString = str;
92         unsigned int word;
93         char* wordString = (char*)&word;
94         char* wordPtr = wordString;
95         int charCount = 0;
96         char c;
97         do {
98             c = *(str++);
99             *(wordPtr++) = c;
100             ++charCount;
101             if (charCount == 4) {
102                 addImmediateOperand(word);
103                 wordPtr = wordString;
104                 charCount = 0;
105             }
106         } while (c != 0);
107
108         // deal with partial last word
109         if (charCount > 0) {
110             // pad with 0s
111             for (; charCount < 4; ++charCount)
112                 *(wordPtr++) = 0;
113             addImmediateOperand(word);
114         }
115     }
116     void setBlock(Block* b) { block = b; }
117     Block* getBlock() const { return block; }
118     Op getOpCode() const { return opCode; }
119     int getNumOperands() const { return (int)operands.size(); }
120     Id getResultId() const { return resultId; }
121     Id getTypeId() const { return typeId; }
122     Id getIdOperand(int op) const { return operands[op]; }
123     unsigned int getImmediateOperand(int op) const { return operands[op]; }
124     const char* getStringOperand() const { return originalString.c_str(); }
125
126     // Write out the binary form.
127     void dump(std::vector<unsigned int>& out) const
128     {
129         // Compute the wordCount
130         unsigned int wordCount = 1;
131         if (typeId)
132             ++wordCount;
133         if (resultId)
134             ++wordCount;
135         wordCount += (unsigned int)operands.size();
136
137         // Write out the beginning of the instruction
138         out.push_back(((wordCount) << WordCountShift) | opCode);
139         if (typeId)
140             out.push_back(typeId);
141         if (resultId)
142             out.push_back(resultId);
143
144         // Write out the operands
145         for (int op = 0; op < (int)operands.size(); ++op)
146             out.push_back(operands[op]);
147     }
148
149 protected:
150     Instruction(const Instruction&);
151     Id resultId;
152     Id typeId;
153     Op opCode;
154     std::vector<Id> operands;
155     std::string originalString;        // could be optimized away; convenience for getting string operand
156     Block* block;
157 };
158
159 //
160 // SPIR-V IR block.
161 //
162
163 class Block {
164 public:
165     Block(Id id, Function& parent);
166     virtual ~Block()
167     {
168     }
169
170     Id getId() { return instructions.front()->getResultId(); }
171
172     Function& getParent() const { return parent; }
173     void addInstruction(std::unique_ptr<Instruction> inst);
174     void addPredecessor(Block* pred) { predecessors.push_back(pred); pred->successors.push_back(this);}
175     void addLocalVariable(std::unique_ptr<Instruction> inst) { localVariables.push_back(std::move(inst)); }
176     const std::vector<Block*>& getPredecessors() const { return predecessors; }
177     const std::vector<Block*>& getSuccessors() const { return successors; }
178     const std::vector<std::unique_ptr<Instruction> >& getInstructions() const {
179         return instructions;
180     }
181     void setUnreachable() { unreachable = true; }
182     bool isUnreachable() const { return unreachable; }
183     // Returns the block's merge instruction, if one exists (otherwise null).
184     const Instruction* getMergeInstruction() const {
185         if (instructions.size() < 2) return nullptr;
186         const Instruction* nextToLast = (instructions.cend() - 2)->get();
187         switch (nextToLast->getOpCode()) {
188             case OpSelectionMerge:
189             case OpLoopMerge:
190                 return nextToLast;
191             default:
192                 return nullptr;
193         }
194         return nullptr;
195     }
196
197     bool isTerminated() const
198     {
199         switch (instructions.back()->getOpCode()) {
200         case OpBranch:
201         case OpBranchConditional:
202         case OpSwitch:
203         case OpKill:
204         case OpReturn:
205         case OpReturnValue:
206             return true;
207         default:
208             return false;
209         }
210     }
211
212     void dump(std::vector<unsigned int>& out) const
213     {
214         instructions[0]->dump(out);
215         for (int i = 0; i < (int)localVariables.size(); ++i)
216             localVariables[i]->dump(out);
217         for (int i = 1; i < (int)instructions.size(); ++i)
218             instructions[i]->dump(out);
219     }
220
221 protected:
222     Block(const Block&);
223     Block& operator=(Block&);
224
225     // To enforce keeping parent and ownership in sync:
226     friend Function;
227
228     std::vector<std::unique_ptr<Instruction> > instructions;
229     std::vector<Block*> predecessors, successors;
230     std::vector<std::unique_ptr<Instruction> > localVariables;
231     Function& parent;
232
233     // track whether this block is known to be uncreachable (not necessarily 
234     // true for all unreachable blocks, but should be set at least
235     // for the extraneous ones introduced by the builder).
236     bool unreachable;
237 };
238
239 // Traverses the control-flow graph rooted at root in an order suited for
240 // readable code generation.  Invokes callback at every node in the traversal
241 // order.
242 void inReadableOrder(Block* root, std::function<void(Block*)> callback);
243
244 //
245 // SPIR-V IR Function.
246 //
247
248 class Function {
249 public:
250     Function(Id id, Id resultType, Id functionType, Id firstParam, Module& parent);
251     virtual ~Function()
252     {
253         for (int i = 0; i < (int)parameterInstructions.size(); ++i)
254             delete parameterInstructions[i];
255
256         for (int i = 0; i < (int)blocks.size(); ++i)
257             delete blocks[i];
258     }
259     Id getId() const { return functionInstruction.getResultId(); }
260     Id getParamId(int p) { return parameterInstructions[p]->getResultId(); }
261
262     void addBlock(Block* block) { blocks.push_back(block); }
263     void removeBlock(Block* block)
264     {
265         auto found = find(blocks.begin(), blocks.end(), block);
266         assert(found != blocks.end());
267         blocks.erase(found);
268         delete block;
269     }
270
271     Module& getParent() const { return parent; }
272     Block* getEntryBlock() const { return blocks.front(); }
273     Block* getLastBlock() const { return blocks.back(); }
274     const std::vector<Block*>& getBlocks() const { return blocks; }
275     void addLocalVariable(std::unique_ptr<Instruction> inst);
276     Id getReturnType() const { return functionInstruction.getTypeId(); }
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 };
301
302 //
303 // SPIR-V IR Module.
304 //
305
306 class Module {
307 public:
308     Module() {}
309     virtual ~Module()
310     {
311         // TODO delete things
312     }
313
314     void addFunction(Function *fun) { functions.push_back(fun); }
315
316     void mapInstruction(Instruction *instruction)
317     {
318         spv::Id resultId = instruction->getResultId();
319         // map the instruction's result id
320         if (resultId >= idToInstruction.size())
321             idToInstruction.resize(resultId + 16);
322         idToInstruction[resultId] = instruction;
323     }
324
325     Instruction* getInstruction(Id id) const { return idToInstruction[id]; }
326     const std::vector<Function*>& getFunctions() const { return functions; }
327     spv::Id getTypeId(Id resultId) const { return idToInstruction[resultId]->getTypeId(); }
328     StorageClass getStorageClass(Id typeId) const
329     {
330         assert(idToInstruction[typeId]->getOpCode() == spv::OpTypePointer);
331         return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0);
332     }
333
334     void dump(std::vector<unsigned int>& out) const
335     {
336         for (int f = 0; f < (int)functions.size(); ++f)
337             functions[f]->dump(out);
338     }
339
340 protected:
341     Module(const Module&);
342     std::vector<Function*> functions;
343
344     // map from result id to instruction having that result id
345     std::vector<Instruction*> idToInstruction;
346
347     // map from a result id to its type id
348 };
349
350 //
351 // Implementation (it's here due to circular type definitions).
352 //
353
354 // Add both
355 // - the OpFunction instruction
356 // - all the OpFunctionParameter instructions
357 __inline Function::Function(Id id, Id resultType, Id functionType, Id firstParamId, Module& parent)
358     : parent(parent), functionInstruction(id, resultType, OpFunction)
359 {
360     // OpFunction
361     functionInstruction.addImmediateOperand(FunctionControlMaskNone);
362     functionInstruction.addIdOperand(functionType);
363     parent.mapInstruction(&functionInstruction);
364     parent.addFunction(this);
365
366     // OpFunctionParameter
367     Instruction* typeInst = parent.getInstruction(functionType);
368     int numParams = typeInst->getNumOperands() - 1;
369     for (int p = 0; p < numParams; ++p) {
370         Instruction* param = new Instruction(firstParamId + p, typeInst->getIdOperand(p + 1), OpFunctionParameter);
371         parent.mapInstruction(param);
372         parameterInstructions.push_back(param);
373     }
374 }
375
376 __inline void Function::addLocalVariable(std::unique_ptr<Instruction> inst)
377 {
378     Instruction* raw_instruction = inst.get();
379     blocks[0]->addLocalVariable(std::move(inst));
380     parent.mapInstruction(raw_instruction);
381 }
382
383 __inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
384 {
385     instructions.push_back(std::unique_ptr<Instruction>(new Instruction(id, NoType, OpLabel)));
386     instructions.back()->setBlock(this);
387     parent.getParent().mapInstruction(instructions.back().get());
388 }
389
390 __inline void Block::addInstruction(std::unique_ptr<Instruction> inst)
391 {
392     Instruction* raw_instruction = inst.get();
393     instructions.push_back(std::move(inst));
394     raw_instruction->setBlock(this);
395     if (raw_instruction->getResultId())
396         parent.getParent().mapInstruction(raw_instruction);
397 }
398
399 };  // end spv namespace
400
401 #endif // spvIR_H