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;
68 const MemorySemanticsMask MemorySemanticsAllMemory =
69 (MemorySemanticsMask)(MemorySemanticsSequentiallyConsistentMask |
70 MemorySemanticsUniformMemoryMask |
71 MemorySemanticsSubgroupMemoryMask |
72 MemorySemanticsWorkgroupMemoryMask |
73 MemorySemanticsCrossWorkgroupMemoryMask |
74 MemorySemanticsAtomicCounterMemoryMask |
75 MemorySemanticsImageMemoryMask);
78 // SPIR-V IR instruction.
83 Instruction(Id resultId, Id typeId, Op opCode) : resultId(resultId), typeId(typeId), opCode(opCode), block(nullptr) { }
84 explicit Instruction(Op opCode) : resultId(NoResult), typeId(NoType), opCode(opCode), block(nullptr) { }
85 virtual ~Instruction() {}
86 void addIdOperand(Id id) { operands.push_back(id); }
87 void addImmediateOperand(unsigned int immediate) { operands.push_back(immediate); }
88 void addStringOperand(const char* str)
91 char* wordString = (char*)&word;
92 char* wordPtr = wordString;
100 addImmediateOperand(word);
101 wordPtr = wordString;
106 // deal with partial last word
109 for (; charCount < 4; ++charCount)
111 addImmediateOperand(word);
114 void setBlock(Block* b) { block = b; }
115 Block* getBlock() const { return block; }
116 Op getOpCode() const { return opCode; }
117 int getNumOperands() const { return (int)operands.size(); }
118 Id getResultId() const { return resultId; }
119 Id getTypeId() const { return typeId; }
120 Id getIdOperand(int op) const { return operands[op]; }
121 unsigned int getImmediateOperand(int op) const { return operands[op]; }
123 // Write out the binary form.
124 void dump(std::vector<unsigned int>& out) const
126 // Compute the wordCount
127 unsigned int wordCount = 1;
132 wordCount += (unsigned int)operands.size();
134 // Write out the beginning of the instruction
135 out.push_back(((wordCount) << WordCountShift) | opCode);
137 out.push_back(typeId);
139 out.push_back(resultId);
141 // Write out the operands
142 for (int op = 0; op < (int)operands.size(); ++op)
143 out.push_back(operands[op]);
147 Instruction(const Instruction&);
151 std::vector<Id> operands;
161 Block(Id id, Function& parent);
166 Id getId() { return instructions.front()->getResultId(); }
168 Function& getParent() const { return parent; }
169 void addInstruction(std::unique_ptr<Instruction> inst);
170 void addPredecessor(Block* pred) { predecessors.push_back(pred); pred->successors.push_back(this);}
171 void addLocalVariable(std::unique_ptr<Instruction> inst) { localVariables.push_back(std::move(inst)); }
172 const std::vector<Block*>& getPredecessors() const { return predecessors; }
173 const std::vector<Block*>& getSuccessors() const { return successors; }
174 const std::vector<std::unique_ptr<Instruction> >& getInstructions() const {
177 void setUnreachable() { unreachable = true; }
178 bool isUnreachable() const { return unreachable; }
179 // Returns the block's merge instruction, if one exists (otherwise null).
180 const Instruction* getMergeInstruction() const {
181 if (instructions.size() < 2) return nullptr;
182 const Instruction* nextToLast = (instructions.cend() - 2)->get();
183 switch (nextToLast->getOpCode()) {
184 case OpSelectionMerge:
193 bool isTerminated() const
195 switch (instructions.back()->getOpCode()) {
197 case OpBranchConditional:
208 void dump(std::vector<unsigned int>& out) const
210 instructions[0]->dump(out);
211 for (int i = 0; i < (int)localVariables.size(); ++i)
212 localVariables[i]->dump(out);
213 for (int i = 1; i < (int)instructions.size(); ++i)
214 instructions[i]->dump(out);
219 Block& operator=(Block&);
221 // To enforce keeping parent and ownership in sync:
224 std::vector<std::unique_ptr<Instruction> > instructions;
225 std::vector<Block*> predecessors, successors;
226 std::vector<std::unique_ptr<Instruction> > localVariables;
229 // track whether this block is known to be uncreachable (not necessarily
230 // true for all unreachable blocks, but should be set at least
231 // for the extraneous ones introduced by the builder).
235 // Traverses the control-flow graph rooted at root in an order suited for
236 // readable code generation. Invokes callback at every node in the traversal
238 void inReadableOrder(Block* root, std::function<void(Block*)> callback);
241 // SPIR-V IR Function.
246 Function(Id id, Id resultType, Id functionType, Id firstParam, Module& parent);
249 for (int i = 0; i < (int)parameterInstructions.size(); ++i)
250 delete parameterInstructions[i];
252 for (int i = 0; i < (int)blocks.size(); ++i)
255 Id getId() const { return functionInstruction.getResultId(); }
256 Id getParamId(int p) { return parameterInstructions[p]->getResultId(); }
258 void addBlock(Block* block) { blocks.push_back(block); }
259 void removeBlock(Block* block)
261 auto found = find(blocks.begin(), blocks.end(), block);
262 assert(found != blocks.end());
267 Module& getParent() const { return parent; }
268 Block* getEntryBlock() const { return blocks.front(); }
269 Block* getLastBlock() const { return blocks.back(); }
270 const std::vector<Block*>& getBlocks() const { return blocks; }
271 void addLocalVariable(std::unique_ptr<Instruction> inst);
272 Id getReturnType() const { return functionInstruction.getTypeId(); }
274 void setImplicitThis() { implicitThis = true; }
275 bool hasImplicitThis() const { return implicitThis; }
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;
300 bool implicitThis; // true if this is a member function expecting to be passed a 'this' as the first argument
312 // TODO delete things
315 void addFunction(Function *fun) { functions.push_back(fun); }
317 void mapInstruction(Instruction *instruction)
319 spv::Id resultId = instruction->getResultId();
320 // map the instruction's result id
321 if (resultId >= idToInstruction.size())
322 idToInstruction.resize(resultId + 16);
323 idToInstruction[resultId] = instruction;
326 Instruction* getInstruction(Id id) const { return idToInstruction[id]; }
327 const std::vector<Function*>& getFunctions() const { return functions; }
328 spv::Id getTypeId(Id resultId) const { return idToInstruction[resultId]->getTypeId(); }
329 StorageClass getStorageClass(Id typeId) const
331 assert(idToInstruction[typeId]->getOpCode() == spv::OpTypePointer);
332 return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0);
335 void dump(std::vector<unsigned int>& out) const
337 for (int f = 0; f < (int)functions.size(); ++f)
338 functions[f]->dump(out);
342 Module(const Module&);
343 std::vector<Function*> functions;
345 // map from result id to instruction having that result id
346 std::vector<Instruction*> idToInstruction;
348 // map from a result id to its type id
352 // Implementation (it's here due to circular type definitions).
356 // - the OpFunction instruction
357 // - all the OpFunctionParameter instructions
358 __inline Function::Function(Id id, Id resultType, Id functionType, Id firstParamId, Module& parent)
359 : parent(parent), functionInstruction(id, resultType, OpFunction), implicitThis(false)
362 functionInstruction.addImmediateOperand(FunctionControlMaskNone);
363 functionInstruction.addIdOperand(functionType);
364 parent.mapInstruction(&functionInstruction);
365 parent.addFunction(this);
367 // OpFunctionParameter
368 Instruction* typeInst = parent.getInstruction(functionType);
369 int numParams = typeInst->getNumOperands() - 1;
370 for (int p = 0; p < numParams; ++p) {
371 Instruction* param = new Instruction(firstParamId + p, typeInst->getIdOperand(p + 1), OpFunctionParameter);
372 parent.mapInstruction(param);
373 parameterInstructions.push_back(param);
377 __inline void Function::addLocalVariable(std::unique_ptr<Instruction> inst)
379 Instruction* raw_instruction = inst.get();
380 blocks[0]->addLocalVariable(std::move(inst));
381 parent.mapInstruction(raw_instruction);
384 __inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
386 instructions.push_back(std::unique_ptr<Instruction>(new Instruction(id, NoType, OpLabel)));
387 instructions.back()->setBlock(this);
388 parent.getParent().mapInstruction(instructions.back().get());
391 __inline void Block::addInstruction(std::unique_ptr<Instruction> inst)
393 Instruction* raw_instruction = inst.get();
394 instructions.push_back(std::move(inst));
395 raw_instruction->setBlock(this);
396 if (raw_instruction->getResultId())
397 parent.getParent().mapInstruction(raw_instruction);
400 }; // end spv namespace