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.
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 unsigned int BadValue = 0xFFFFFFFF;
68 const Decoration NoPrecision = (Decoration)BadValue;
69 const MemorySemanticsMask MemorySemanticsAllMemory =
70 (MemorySemanticsMask)(MemorySemanticsSequentiallyConsistentMask |
71 MemorySemanticsUniformMemoryMask |
72 MemorySemanticsSubgroupMemoryMask |
73 MemorySemanticsWorkgroupMemoryMask |
74 MemorySemanticsCrossWorkgroupMemoryMask |
75 MemorySemanticsAtomicCounterMemoryMask |
76 MemorySemanticsImageMemoryMask);
79 // SPIR-V IR instruction.
84 Instruction(Id resultId, Id typeId, Op opCode) : resultId(resultId), typeId(typeId), opCode(opCode), block(nullptr) { }
85 explicit Instruction(Op opCode) : resultId(NoResult), typeId(NoType), opCode(opCode), block(nullptr) { }
86 virtual ~Instruction() {}
87 void addIdOperand(Id id) { operands.push_back(id); }
88 void addImmediateOperand(unsigned int immediate) { operands.push_back(immediate); }
89 void addStringOperand(const char* str)
93 char* wordString = (char*)&word;
94 char* wordPtr = wordString;
101 if (charCount == 4) {
102 addImmediateOperand(word);
103 wordPtr = wordString;
108 // deal with partial last word
111 for (; charCount < 4; ++charCount)
113 addImmediateOperand(word);
116 void setBlock(Block* b) { block = b; }
117 Block* getBlock() const { return block; }
118 Op getOpCode() const { return opCode; }
119 int getNumOperands() const { return (int)operands.size(); }
120 Id getResultId() const { return resultId; }
121 Id getTypeId() const { return typeId; }
122 Id getIdOperand(int op) const { return operands[op]; }
123 unsigned int getImmediateOperand(int op) const { return operands[op]; }
124 const char* getStringOperand() const { return originalString.c_str(); }
126 // Write out the binary form.
127 void dump(std::vector<unsigned int>& out) const
129 // Compute the wordCount
130 unsigned int wordCount = 1;
135 wordCount += (unsigned int)operands.size();
137 // Write out the beginning of the instruction
138 out.push_back(((wordCount) << WordCountShift) | opCode);
140 out.push_back(typeId);
142 out.push_back(resultId);
144 // Write out the operands
145 for (int op = 0; op < (int)operands.size(); ++op)
146 out.push_back(operands[op]);
150 Instruction(const Instruction&);
154 std::vector<Id> operands;
155 std::string originalString; // could be optimized away; convenience for getting string operand
165 Block(Id id, Function& parent);
170 Id getId() { return instructions.front()->getResultId(); }
172 Function& getParent() const { return parent; }
173 void addInstruction(std::unique_ptr<Instruction> inst);
174 void addPredecessor(Block* pred) { predecessors.push_back(pred); pred->successors.push_back(this);}
175 void addLocalVariable(std::unique_ptr<Instruction> inst) { localVariables.push_back(std::move(inst)); }
176 const std::vector<Block*>& getPredecessors() const { return predecessors; }
177 const std::vector<Block*>& getSuccessors() const { return successors; }
178 const std::vector<std::unique_ptr<Instruction> >& getInstructions() const {
181 void setUnreachable() { unreachable = true; }
182 bool isUnreachable() const { return unreachable; }
183 // Returns the block's merge instruction, if one exists (otherwise null).
184 const Instruction* getMergeInstruction() const {
185 if (instructions.size() < 2) return nullptr;
186 const Instruction* nextToLast = (instructions.cend() - 2)->get();
187 switch (nextToLast->getOpCode()) {
188 case OpSelectionMerge:
197 bool isTerminated() const
199 switch (instructions.back()->getOpCode()) {
201 case OpBranchConditional:
212 void dump(std::vector<unsigned int>& out) const
214 instructions[0]->dump(out);
215 for (int i = 0; i < (int)localVariables.size(); ++i)
216 localVariables[i]->dump(out);
217 for (int i = 1; i < (int)instructions.size(); ++i)
218 instructions[i]->dump(out);
223 Block& operator=(Block&);
225 // To enforce keeping parent and ownership in sync:
228 std::vector<std::unique_ptr<Instruction> > instructions;
229 std::vector<Block*> predecessors, successors;
230 std::vector<std::unique_ptr<Instruction> > localVariables;
233 // track whether this block is known to be uncreachable (not necessarily
234 // true for all unreachable blocks, but should be set at least
235 // for the extraneous ones introduced by the builder).
239 // Traverses the control-flow graph rooted at root in an order suited for
240 // readable code generation. Invokes callback at every node in the traversal
242 void inReadableOrder(Block* root, std::function<void(Block*)> callback);
245 // SPIR-V IR Function.
250 Function(Id id, Id resultType, Id functionType, Id firstParam, Module& parent);
253 for (int i = 0; i < (int)parameterInstructions.size(); ++i)
254 delete parameterInstructions[i];
256 for (int i = 0; i < (int)blocks.size(); ++i)
259 Id getId() const { return functionInstruction.getResultId(); }
260 Id getParamId(int p) { return parameterInstructions[p]->getResultId(); }
262 void addBlock(Block* block) { blocks.push_back(block); }
263 void removeBlock(Block* block)
265 auto found = find(blocks.begin(), blocks.end(), block);
266 assert(found != blocks.end());
271 Module& getParent() const { return parent; }
272 Block* getEntryBlock() const { return blocks.front(); }
273 Block* getLastBlock() const { return blocks.back(); }
274 const std::vector<Block*>& getBlocks() const { return blocks; }
275 void addLocalVariable(std::unique_ptr<Instruction> inst);
276 Id getReturnType() const { return functionInstruction.getTypeId(); }
277 void dump(std::vector<unsigned int>& out) const
280 functionInstruction.dump(out);
282 // OpFunctionParameter
283 for (int p = 0; p < (int)parameterInstructions.size(); ++p)
284 parameterInstructions[p]->dump(out);
287 inReadableOrder(blocks[0], [&out](const Block* b) { b->dump(out); });
288 Instruction end(0, 0, OpFunctionEnd);
293 Function(const Function&);
294 Function& operator=(Function&);
297 Instruction functionInstruction;
298 std::vector<Instruction*> parameterInstructions;
299 std::vector<Block*> blocks;
311 // TODO delete things
314 void addFunction(Function *fun) { functions.push_back(fun); }
316 void mapInstruction(Instruction *instruction)
318 spv::Id resultId = instruction->getResultId();
319 // map the instruction's result id
320 if (resultId >= idToInstruction.size())
321 idToInstruction.resize(resultId + 16);
322 idToInstruction[resultId] = instruction;
325 Instruction* getInstruction(Id id) const { return idToInstruction[id]; }
326 const std::vector<Function*>& getFunctions() const { return functions; }
327 spv::Id getTypeId(Id resultId) const { return idToInstruction[resultId]->getTypeId(); }
328 StorageClass getStorageClass(Id typeId) const
330 assert(idToInstruction[typeId]->getOpCode() == spv::OpTypePointer);
331 return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0);
334 void dump(std::vector<unsigned int>& out) const
336 for (int f = 0; f < (int)functions.size(); ++f)
337 functions[f]->dump(out);
341 Module(const Module&);
342 std::vector<Function*> functions;
344 // map from result id to instruction having that result id
345 std::vector<Instruction*> idToInstruction;
347 // map from a result id to its type id
351 // Implementation (it's here due to circular type definitions).
355 // - the OpFunction instruction
356 // - all the OpFunctionParameter instructions
357 __inline Function::Function(Id id, Id resultType, Id functionType, Id firstParamId, Module& parent)
358 : parent(parent), functionInstruction(id, resultType, OpFunction)
361 functionInstruction.addImmediateOperand(FunctionControlMaskNone);
362 functionInstruction.addIdOperand(functionType);
363 parent.mapInstruction(&functionInstruction);
364 parent.addFunction(this);
366 // OpFunctionParameter
367 Instruction* typeInst = parent.getInstruction(functionType);
368 int numParams = typeInst->getNumOperands() - 1;
369 for (int p = 0; p < numParams; ++p) {
370 Instruction* param = new Instruction(firstParamId + p, typeInst->getIdOperand(p + 1), OpFunctionParameter);
371 parent.mapInstruction(param);
372 parameterInstructions.push_back(param);
376 __inline void Function::addLocalVariable(std::unique_ptr<Instruction> inst)
378 Instruction* raw_instruction = inst.get();
379 blocks[0]->addLocalVariable(std::move(inst));
380 parent.mapInstruction(raw_instruction);
383 __inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
385 instructions.push_back(std::unique_ptr<Instruction>(new Instruction(id, NoType, OpLabel)));
386 instructions.back()->setBlock(this);
387 parent.getParent().mapInstruction(instructions.back().get());
390 __inline void Block::addInstruction(std::unique_ptr<Instruction> inst)
392 Instruction* raw_instruction = inst.get();
393 instructions.push_back(std::move(inst));
394 raw_instruction->setBlock(this);
395 if (raw_instruction->getResultId())
396 parent.getParent().mapInstruction(raw_instruction);
399 }; // end spv namespace