Merge pull request #100 from mawww/scanner-optim
[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 //
36 // Author: John Kessenich, LunarG
37 //
38
39 // SPIRV-IR
40 //
41 // Simple in-memory representation (IR) of SPIRV.  Just for holding
42 // Each function's CFG of blocks.  Has this hierarchy:
43 //  - Module, which is a list of 
44 //    - Function, which is a list of 
45 //      - Block, which is a list of 
46 //        - Instruction
47 //
48
49 #pragma once
50 #ifndef spvIR_H
51 #define spvIR_H
52
53 #include "spirv.hpp"
54
55 #include <vector>
56 #include <iostream>
57 #include <assert.h>
58
59 namespace spv {
60
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 = (MemorySemanticsMask)0x3FF;
70
71 //
72 // SPIR-V IR instruction.
73 //
74
75 class Instruction {
76 public:
77     Instruction(Id resultId, Id typeId, Op opCode) : resultId(resultId), typeId(typeId), opCode(opCode) { }
78     explicit Instruction(Op opCode) : resultId(NoResult), typeId(NoType), opCode(opCode) { }
79     virtual ~Instruction() {}
80     void addIdOperand(Id id) { operands.push_back(id); }
81     void addImmediateOperand(unsigned int immediate) { operands.push_back(immediate); }
82     void addStringOperand(const char* str)
83     {
84         originalString = str;
85         unsigned int word;
86         char* wordString = (char*)&word;
87         char* wordPtr = wordString;
88         int charCount = 0;
89         char c;
90         do {
91             c = *(str++);
92             *(wordPtr++) = c;
93             ++charCount;
94             if (charCount == 4) {
95                 addImmediateOperand(word);
96                 wordPtr = wordString;
97                 charCount = 0;
98             }
99         } while (c != 0);
100
101         // deal with partial last word
102         if (charCount > 0) {
103             // pad with 0s
104             for (; charCount < 4; ++charCount)
105                 *(wordPtr++) = 0;
106             addImmediateOperand(word);
107         }
108     }
109     Op getOpCode() const { return opCode; }
110     int getNumOperands() const { return (int)operands.size(); }
111     Id getResultId() const { return resultId; }
112     Id getTypeId() const { return typeId; }
113     Id getIdOperand(int op) const { return operands[op]; }
114     unsigned int getImmediateOperand(int op) const { return operands[op]; }
115     const char* getStringOperand() const { return originalString.c_str(); }
116
117     // Write out the binary form.
118     void dump(std::vector<unsigned int>& out) const
119     {
120         // Compute the wordCount
121         unsigned int wordCount = 1;
122         if (typeId)
123             ++wordCount;
124         if (resultId)
125             ++wordCount;
126         wordCount += (unsigned int)operands.size();
127
128         // Write out the beginning of the instruction
129         out.push_back(((wordCount) << WordCountShift) | opCode);
130         if (typeId)
131             out.push_back(typeId);
132         if (resultId)
133             out.push_back(resultId);
134
135         // Write out the operands
136         for (int op = 0; op < (int)operands.size(); ++op)
137             out.push_back(operands[op]);
138     }
139
140 protected:
141     Instruction(const Instruction&);
142     Id resultId;
143     Id typeId;
144     Op opCode;
145     std::vector<Id> operands;
146     std::string originalString;        // could be optimized away; convenience for getting string operand
147 };
148
149 //
150 // SPIR-V IR block.
151 //
152
153 class Block {
154 public:
155     Block(Id id, Function& parent);
156     virtual ~Block()
157     {
158         // TODO: free instructions
159     }
160     
161     Id getId() { return instructions.front()->getResultId(); }
162
163     Function& getParent() const { return parent; }
164     void addInstruction(Instruction* inst);
165     void addPredecessor(Block* pred) { predecessors.push_back(pred); }
166     void addLocalVariable(Instruction* inst) { localVariables.push_back(inst); }
167     int getNumPredecessors() const { return (int)predecessors.size(); }
168     void setUnreachable() { unreachable = true; }
169     bool isUnreachable() const { return unreachable; }
170
171     bool isTerminated() const
172     {
173         switch (instructions.back()->getOpCode()) {
174         case OpBranch:
175         case OpBranchConditional:
176         case OpSwitch:
177         case OpKill:
178         case OpReturn:
179         case OpReturnValue:
180             return true;
181         default:
182             return false;
183         }
184     }
185
186     void dump(std::vector<unsigned int>& out) const
187     {
188         // skip the degenerate unreachable blocks
189         // TODO: code gen: skip all unreachable blocks (transitive closure)
190         //                 (but, until that's done safer to keep non-degenerate unreachable blocks, in case others depend on something)
191         if (unreachable && instructions.size() <= 2)
192             return;
193
194         instructions[0]->dump(out);
195         for (int i = 0; i < (int)localVariables.size(); ++i)
196             localVariables[i]->dump(out);
197         for (int i = 1; i < (int)instructions.size(); ++i)
198             instructions[i]->dump(out);
199     }
200
201 protected:
202     Block(const Block&);
203     Block& operator=(Block&);
204
205     // To enforce keeping parent and ownership in sync:
206     friend Function;
207
208     std::vector<Instruction*> instructions;
209     std::vector<Block*> predecessors;
210     std::vector<Instruction*> localVariables;
211     Function& parent;
212
213     // track whether this block is known to be uncreachable (not necessarily 
214     // true for all unreachable blocks, but should be set at least
215     // for the extraneous ones introduced by the builder).
216     bool unreachable;
217 };
218
219 //
220 // SPIR-V IR Function.
221 //
222
223 class Function {
224 public:
225     Function(Id id, Id resultType, Id functionType, Id firstParam, Module& parent);
226     virtual ~Function()
227     {
228         for (int i = 0; i < (int)parameterInstructions.size(); ++i)
229             delete parameterInstructions[i];
230
231         for (int i = 0; i < (int)blocks.size(); ++i)
232             delete blocks[i];
233     }
234     Id getId() const { return functionInstruction.getResultId(); }
235     Id getParamId(int p) { return parameterInstructions[p]->getResultId(); }
236
237     void addBlock(Block* block) { blocks.push_back(block); }
238     void popBlock(Block*) { blocks.pop_back(); }
239
240     Module& getParent() const { return parent; }
241     Block* getEntryBlock() const { return blocks.front(); }
242     Block* getLastBlock() const { return blocks.back(); }
243     void addLocalVariable(Instruction* inst);
244     Id getReturnType() const { return functionInstruction.getTypeId(); }
245     void dump(std::vector<unsigned int>& out) const
246     {
247         // OpFunction
248         functionInstruction.dump(out);
249
250         // OpFunctionParameter
251         for (int p = 0; p < (int)parameterInstructions.size(); ++p)
252             parameterInstructions[p]->dump(out);
253
254         // Blocks
255         for (int b = 0; b < (int)blocks.size(); ++b)
256             blocks[b]->dump(out);
257         Instruction end(0, 0, OpFunctionEnd);
258         end.dump(out);
259     }
260
261 protected:
262     Function(const Function&);
263     Function& operator=(Function&);
264
265     Module& parent;
266     Instruction functionInstruction;
267     std::vector<Instruction*> parameterInstructions;
268     std::vector<Block*> blocks;
269 };
270
271 //
272 // SPIR-V IR Module.
273 //
274
275 class Module {
276 public:
277     Module() {}
278     virtual ~Module()
279     {
280         // TODO delete things
281     }
282
283     void addFunction(Function *fun) { functions.push_back(fun); }
284
285     void mapInstruction(Instruction *instruction)
286     {
287         spv::Id resultId = instruction->getResultId();
288         // map the instruction's result id
289         if (resultId >= idToInstruction.size())
290             idToInstruction.resize(resultId + 16);
291         idToInstruction[resultId] = instruction;
292     }
293
294     Instruction* getInstruction(Id id) const { return idToInstruction[id]; }
295     spv::Id getTypeId(Id resultId) const { return idToInstruction[resultId]->getTypeId(); }
296     StorageClass getStorageClass(Id typeId) const { return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0); }
297     void dump(std::vector<unsigned int>& out) const
298     {
299         for (int f = 0; f < (int)functions.size(); ++f)
300             functions[f]->dump(out);
301     }
302
303 protected:
304     Module(const Module&);
305     std::vector<Function*> functions;
306
307     // map from result id to instruction having that result id
308     std::vector<Instruction*> idToInstruction;
309
310     // map from a result id to its type id
311 };
312
313 //
314 // Implementation (it's here due to circular type definitions).
315 //
316
317 // Add both
318 // - the OpFunction instruction
319 // - all the OpFunctionParameter instructions
320 __inline Function::Function(Id id, Id resultType, Id functionType, Id firstParamId, Module& parent)
321     : parent(parent), functionInstruction(id, resultType, OpFunction)
322 {
323     // OpFunction
324     functionInstruction.addImmediateOperand(FunctionControlMaskNone);
325     functionInstruction.addIdOperand(functionType);
326     parent.mapInstruction(&functionInstruction);
327     parent.addFunction(this);
328
329     // OpFunctionParameter
330     Instruction* typeInst = parent.getInstruction(functionType);
331     int numParams = typeInst->getNumOperands() - 1;
332     for (int p = 0; p < numParams; ++p) {
333         Instruction* param = new Instruction(firstParamId + p, typeInst->getIdOperand(p + 1), OpFunctionParameter);
334         parent.mapInstruction(param);
335         parameterInstructions.push_back(param);
336     }
337 }
338
339 __inline void Function::addLocalVariable(Instruction* inst)
340 {
341     blocks[0]->addLocalVariable(inst);
342     parent.mapInstruction(inst);
343 }
344
345 __inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
346 {
347     instructions.push_back(new Instruction(id, NoType, OpLabel));
348 }
349
350 __inline void Block::addInstruction(Instruction* inst)
351 {
352     instructions.push_back(inst);
353     if (inst->getResultId())
354         parent.getParent().mapInstruction(inst);
355 }
356
357 };  // end spv namespace
358
359 #endif // spvIR_H