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