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