2 // Copyright (C) 2014 LunarG, Inc.
4 // All rights reserved.
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions
10 // Redistributions of source code must retain the above copyright
11 // notice, this list of conditions and the following disclaimer.
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.
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.
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.
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
64 const Id NoResult = 0;
67 const Decoration NoPrecision = DecorationMax;
70 # define POTENTIALLY_UNUSED __attribute__((unused))
72 # define POTENTIALLY_UNUSED
76 const MemorySemanticsMask MemorySemanticsAllMemory =
77 (MemorySemanticsMask)(MemorySemanticsUniformMemoryMask |
78 MemorySemanticsSubgroupMemoryMask |
79 MemorySemanticsWorkgroupMemoryMask |
80 MemorySemanticsCrossWorkgroupMemoryMask |
81 MemorySemanticsAtomicCounterMemoryMask |
82 MemorySemanticsImageMemoryMask);
85 // SPIR-V IR instruction.
90 Instruction(Id resultId, Id typeId, Op opCode) : resultId(resultId), typeId(typeId), opCode(opCode), block(nullptr) { }
91 explicit Instruction(Op opCode) : resultId(NoResult), typeId(NoType), opCode(opCode), block(nullptr) { }
92 virtual ~Instruction() {}
93 void addIdOperand(Id id) { operands.push_back(id); }
94 void addImmediateOperand(unsigned int immediate) { operands.push_back(immediate); }
95 void addStringOperand(const char* str)
98 char* wordString = (char*)&word;
99 char* wordPtr = wordString;
106 if (charCount == 4) {
107 addImmediateOperand(word);
108 wordPtr = wordString;
113 // deal with partial last word
116 for (; charCount < 4; ++charCount)
118 addImmediateOperand(word);
121 void setBlock(Block* b) { block = b; }
122 Block* getBlock() const { return block; }
123 Op getOpCode() const { return opCode; }
124 int getNumOperands() const { return (int)operands.size(); }
125 Id getResultId() const { return resultId; }
126 Id getTypeId() const { return typeId; }
127 Id getIdOperand(int op) const { return operands[op]; }
128 unsigned int getImmediateOperand(int op) const { return operands[op]; }
130 // Write out the binary form.
131 void dump(std::vector<unsigned int>& out) const
133 // Compute the wordCount
134 unsigned int wordCount = 1;
139 wordCount += (unsigned int)operands.size();
141 // Write out the beginning of the instruction
142 out.push_back(((wordCount) << WordCountShift) | opCode);
144 out.push_back(typeId);
146 out.push_back(resultId);
148 // Write out the operands
149 for (int op = 0; op < (int)operands.size(); ++op)
150 out.push_back(operands[op]);
154 Instruction(const Instruction&);
158 std::vector<Id> operands;
168 Block(Id id, Function& parent);
173 Id getId() { return instructions.front()->getResultId(); }
175 Function& getParent() const { return parent; }
176 void addInstruction(std::unique_ptr<Instruction> inst);
177 void addPredecessor(Block* pred) { predecessors.push_back(pred); pred->successors.push_back(this);}
178 void addLocalVariable(std::unique_ptr<Instruction> inst) { localVariables.push_back(std::move(inst)); }
179 const std::vector<Block*>& getPredecessors() const { return predecessors; }
180 const std::vector<Block*>& getSuccessors() const { return successors; }
181 const std::vector<std::unique_ptr<Instruction> >& getInstructions() const {
184 void setUnreachable() { unreachable = true; }
185 bool isUnreachable() const { return unreachable; }
186 // Returns the block's merge instruction, if one exists (otherwise null).
187 const Instruction* getMergeInstruction() const {
188 if (instructions.size() < 2) return nullptr;
189 const Instruction* nextToLast = (instructions.cend() - 2)->get();
190 switch (nextToLast->getOpCode()) {
191 case OpSelectionMerge:
200 bool isTerminated() const
202 switch (instructions.back()->getOpCode()) {
204 case OpBranchConditional:
215 void dump(std::vector<unsigned int>& out) const
217 instructions[0]->dump(out);
218 for (int i = 0; i < (int)localVariables.size(); ++i)
219 localVariables[i]->dump(out);
220 for (int i = 1; i < (int)instructions.size(); ++i)
221 instructions[i]->dump(out);
226 Block& operator=(Block&);
228 // To enforce keeping parent and ownership in sync:
231 std::vector<std::unique_ptr<Instruction> > instructions;
232 std::vector<Block*> predecessors, successors;
233 std::vector<std::unique_ptr<Instruction> > localVariables;
236 // track whether this block is known to be uncreachable (not necessarily
237 // true for all unreachable blocks, but should be set at least
238 // for the extraneous ones introduced by the builder).
242 // Traverses the control-flow graph rooted at root in an order suited for
243 // readable code generation. Invokes callback at every node in the traversal
245 void inReadableOrder(Block* root, std::function<void(Block*)> callback);
248 // SPIR-V IR Function.
253 Function(Id id, Id resultType, Id functionType, Id firstParam, Module& parent);
256 for (int i = 0; i < (int)parameterInstructions.size(); ++i)
257 delete parameterInstructions[i];
259 for (int i = 0; i < (int)blocks.size(); ++i)
262 Id getId() const { return functionInstruction.getResultId(); }
263 Id getParamId(int p) { return parameterInstructions[p]->getResultId(); }
265 void addBlock(Block* block) { blocks.push_back(block); }
266 void removeBlock(Block* block)
268 auto found = find(blocks.begin(), blocks.end(), block);
269 assert(found != blocks.end());
274 Module& getParent() const { return parent; }
275 Block* getEntryBlock() const { return blocks.front(); }
276 Block* getLastBlock() const { return blocks.back(); }
277 const std::vector<Block*>& getBlocks() const { return blocks; }
278 void addLocalVariable(std::unique_ptr<Instruction> inst);
279 Id getReturnType() const { return functionInstruction.getTypeId(); }
281 void setImplicitThis() { implicitThis = true; }
282 bool hasImplicitThis() const { return implicitThis; }
284 void dump(std::vector<unsigned int>& out) const
287 functionInstruction.dump(out);
289 // OpFunctionParameter
290 for (int p = 0; p < (int)parameterInstructions.size(); ++p)
291 parameterInstructions[p]->dump(out);
294 inReadableOrder(blocks[0], [&out](const Block* b) { b->dump(out); });
295 Instruction end(0, 0, OpFunctionEnd);
300 Function(const Function&);
301 Function& operator=(Function&);
304 Instruction functionInstruction;
305 std::vector<Instruction*> parameterInstructions;
306 std::vector<Block*> blocks;
307 bool implicitThis; // true if this is a member function expecting to be passed a 'this' as the first argument
319 // TODO delete things
322 void addFunction(Function *fun) { functions.push_back(fun); }
324 void mapInstruction(Instruction *instruction)
326 spv::Id resultId = instruction->getResultId();
327 // map the instruction's result id
328 if (resultId >= idToInstruction.size())
329 idToInstruction.resize(resultId + 16);
330 idToInstruction[resultId] = instruction;
333 Instruction* getInstruction(Id id) const { return idToInstruction[id]; }
334 const std::vector<Function*>& getFunctions() const { return functions; }
335 spv::Id getTypeId(Id resultId) const { return idToInstruction[resultId]->getTypeId(); }
336 StorageClass getStorageClass(Id typeId) const
338 assert(idToInstruction[typeId]->getOpCode() == spv::OpTypePointer);
339 return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0);
342 void dump(std::vector<unsigned int>& out) const
344 for (int f = 0; f < (int)functions.size(); ++f)
345 functions[f]->dump(out);
349 Module(const Module&);
350 std::vector<Function*> functions;
352 // map from result id to instruction having that result id
353 std::vector<Instruction*> idToInstruction;
355 // map from a result id to its type id
359 // Implementation (it's here due to circular type definitions).
363 // - the OpFunction instruction
364 // - all the OpFunctionParameter instructions
365 __inline Function::Function(Id id, Id resultType, Id functionType, Id firstParamId, Module& parent)
366 : parent(parent), functionInstruction(id, resultType, OpFunction), implicitThis(false)
369 functionInstruction.addImmediateOperand(FunctionControlMaskNone);
370 functionInstruction.addIdOperand(functionType);
371 parent.mapInstruction(&functionInstruction);
372 parent.addFunction(this);
374 // OpFunctionParameter
375 Instruction* typeInst = parent.getInstruction(functionType);
376 int numParams = typeInst->getNumOperands() - 1;
377 for (int p = 0; p < numParams; ++p) {
378 Instruction* param = new Instruction(firstParamId + p, typeInst->getIdOperand(p + 1), OpFunctionParameter);
379 parent.mapInstruction(param);
380 parameterInstructions.push_back(param);
384 __inline void Function::addLocalVariable(std::unique_ptr<Instruction> inst)
386 Instruction* raw_instruction = inst.get();
387 blocks[0]->addLocalVariable(std::move(inst));
388 parent.mapInstruction(raw_instruction);
391 __inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
393 instructions.push_back(std::unique_ptr<Instruction>(new Instruction(id, NoType, OpLabel)));
394 instructions.back()->setBlock(this);
395 parent.getParent().mapInstruction(instructions.back().get());
398 __inline void Block::addInstruction(std::unique_ptr<Instruction> inst)
400 Instruction* raw_instruction = inst.get();
401 instructions.push_back(std::move(inst));
402 raw_instruction->setBlock(this);
403 if (raw_instruction->getResultId())
404 parent.getParent().mapInstruction(raw_instruction);
407 }; // end spv namespace