2 //Copyright (C) 2014 LunarG, Inc.
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.
36 // Author: John Kessenich, LunarG
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
68 const Id NoResult = 0;
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);
86 // SPIR-V IR instruction.
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)
100 char* wordString = (char*)&word;
101 char* wordPtr = wordString;
108 if (charCount == 4) {
109 addImmediateOperand(word);
110 wordPtr = wordString;
115 // deal with partial last word
118 for (; charCount < 4; ++charCount)
120 addImmediateOperand(word);
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(); }
133 // Write out the binary form.
134 void dump(std::vector<unsigned int>& out) const
136 // Compute the wordCount
137 unsigned int wordCount = 1;
142 wordCount += (unsigned int)operands.size();
144 // Write out the beginning of the instruction
145 out.push_back(((wordCount) << WordCountShift) | opCode);
147 out.push_back(typeId);
149 out.push_back(resultId);
151 // Write out the operands
152 for (int op = 0; op < (int)operands.size(); ++op)
153 out.push_back(operands[op]);
157 Instruction(const Instruction&);
161 std::vector<Id> operands;
162 std::string originalString; // could be optimized away; convenience for getting string operand
172 Block(Id id, Function& parent);
177 Id getId() { return instructions.front()->getResultId(); }
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 void setUnreachable() { unreachable = true; }
186 bool isUnreachable() const { return unreachable; }
187 // Returns the block's merge instruction, if one exists (otherwise null).
188 const Instruction* getMergeInstruction() const {
189 if (instructions.size() < 2) return nullptr;
190 const Instruction* nextToLast = (instructions.cend() - 2)->get();
191 switch (nextToLast->getOpCode()) {
192 case OpSelectionMerge:
201 bool isTerminated() const
203 switch (instructions.back()->getOpCode()) {
205 case OpBranchConditional:
216 void dump(std::vector<unsigned int>& out) const
218 instructions[0]->dump(out);
219 for (int i = 0; i < (int)localVariables.size(); ++i)
220 localVariables[i]->dump(out);
221 for (int i = 1; i < (int)instructions.size(); ++i)
222 instructions[i]->dump(out);
227 Block& operator=(Block&);
229 // To enforce keeping parent and ownership in sync:
232 std::vector<std::unique_ptr<Instruction> > instructions;
233 std::vector<Block*> predecessors, successors;
234 std::vector<std::unique_ptr<Instruction> > localVariables;
237 // track whether this block is known to be uncreachable (not necessarily
238 // true for all unreachable blocks, but should be set at least
239 // for the extraneous ones introduced by the builder).
243 // Traverses the control-flow graph rooted at root in an order suited for
244 // readable code generation. Invokes callback at every node in the traversal
246 void inReadableOrder(Block* root, std::function<void(Block*)> callback);
249 // SPIR-V IR Function.
254 Function(Id id, Id resultType, Id functionType, Id firstParam, Module& parent);
257 for (int i = 0; i < (int)parameterInstructions.size(); ++i)
258 delete parameterInstructions[i];
260 for (int i = 0; i < (int)blocks.size(); ++i)
263 Id getId() const { return functionInstruction.getResultId(); }
264 Id getParamId(int p) { return parameterInstructions[p]->getResultId(); }
266 void addBlock(Block* block) { blocks.push_back(block); }
267 void removeBlock(Block* block)
269 auto found = find(blocks.begin(), blocks.end(), block);
270 assert(found != blocks.end());
275 Module& getParent() const { return parent; }
276 Block* getEntryBlock() const { return blocks.front(); }
277 Block* getLastBlock() const { return blocks.back(); }
278 void addLocalVariable(std::unique_ptr<Instruction> inst);
279 Id getReturnType() const { return functionInstruction.getTypeId(); }
280 void dump(std::vector<unsigned int>& out) const
283 functionInstruction.dump(out);
285 // OpFunctionParameter
286 for (int p = 0; p < (int)parameterInstructions.size(); ++p)
287 parameterInstructions[p]->dump(out);
290 inReadableOrder(blocks[0], [&out](const Block* b) { b->dump(out); });
291 Instruction end(0, 0, OpFunctionEnd);
296 Function(const Function&);
297 Function& operator=(Function&);
300 Instruction functionInstruction;
301 std::vector<Instruction*> parameterInstructions;
302 std::vector<Block*> blocks;
314 // TODO delete things
317 void addFunction(Function *fun) { functions.push_back(fun); }
319 void mapInstruction(Instruction *instruction)
321 spv::Id resultId = instruction->getResultId();
322 // map the instruction's result id
323 if (resultId >= idToInstruction.size())
324 idToInstruction.resize(resultId + 16);
325 idToInstruction[resultId] = instruction;
328 Instruction* getInstruction(Id id) const { return idToInstruction[id]; }
329 spv::Id getTypeId(Id resultId) const { return idToInstruction[resultId]->getTypeId(); }
330 StorageClass getStorageClass(Id typeId) const
332 assert(idToInstruction[typeId]->getOpCode() == spv::OpTypePointer);
333 return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0);
336 void dump(std::vector<unsigned int>& out) const
338 for (int f = 0; f < (int)functions.size(); ++f)
339 functions[f]->dump(out);
343 Module(const Module&);
344 std::vector<Function*> functions;
346 // map from result id to instruction having that result id
347 std::vector<Instruction*> idToInstruction;
349 // map from a result id to its type id
353 // Implementation (it's here due to circular type definitions).
357 // - the OpFunction instruction
358 // - all the OpFunctionParameter instructions
359 __inline Function::Function(Id id, Id resultType, Id functionType, Id firstParamId, Module& parent)
360 : parent(parent), functionInstruction(id, resultType, OpFunction)
363 functionInstruction.addImmediateOperand(FunctionControlMaskNone);
364 functionInstruction.addIdOperand(functionType);
365 parent.mapInstruction(&functionInstruction);
366 parent.addFunction(this);
368 // OpFunctionParameter
369 Instruction* typeInst = parent.getInstruction(functionType);
370 int numParams = typeInst->getNumOperands() - 1;
371 for (int p = 0; p < numParams; ++p) {
372 Instruction* param = new Instruction(firstParamId + p, typeInst->getIdOperand(p + 1), OpFunctionParameter);
373 parent.mapInstruction(param);
374 parameterInstructions.push_back(param);
378 __inline void Function::addLocalVariable(std::unique_ptr<Instruction> inst)
380 Instruction* raw_instruction = inst.get();
381 blocks[0]->addLocalVariable(std::move(inst));
382 parent.mapInstruction(raw_instruction);
385 __inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
387 instructions.push_back(std::unique_ptr<Instruction>(new Instruction(id, NoType, OpLabel)));
388 instructions.back()->setBlock(this);
389 parent.getParent().mapInstruction(instructions.back().get());
392 __inline void Block::addInstruction(std::unique_ptr<Instruction> inst)
394 Instruction* raw_instruction = inst.get();
395 instructions.push_back(std::move(inst));
396 raw_instruction->setBlock(this);
397 if (raw_instruction->getResultId())
398 parent.getParent().mapInstruction(raw_instruction);
401 }; // end spv namespace