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 MemorySemanticsWorkgroupMemoryMask |
79 MemorySemanticsAtomicCounterMemoryMask |
80 MemorySemanticsImageMemoryMask);
83 // SPIR-V IR instruction.
88 Instruction(Id resultId, Id typeId, Op opCode) : resultId(resultId), typeId(typeId), opCode(opCode), block(nullptr) { }
89 explicit Instruction(Op opCode) : resultId(NoResult), typeId(NoType), opCode(opCode), block(nullptr) { }
90 virtual ~Instruction() {}
91 void addIdOperand(Id id) { operands.push_back(id); }
92 void addImmediateOperand(unsigned int immediate) { operands.push_back(immediate); }
93 void addStringOperand(const char* str)
96 char* wordString = (char*)&word;
97 char* wordPtr = wordString;
104 if (charCount == 4) {
105 addImmediateOperand(word);
106 wordPtr = wordString;
111 // deal with partial last word
114 for (; charCount < 4; ++charCount)
116 addImmediateOperand(word);
119 void setBlock(Block* b) { block = b; }
120 Block* getBlock() const { return block; }
121 Op getOpCode() const { return opCode; }
122 int getNumOperands() const { return (int)operands.size(); }
123 Id getResultId() const { return resultId; }
124 Id getTypeId() const { return typeId; }
125 Id getIdOperand(int op) const { return operands[op]; }
126 unsigned int getImmediateOperand(int op) const { return operands[op]; }
128 // Write out the binary form.
129 void dump(std::vector<unsigned int>& out) const
131 // Compute the wordCount
132 unsigned int wordCount = 1;
137 wordCount += (unsigned int)operands.size();
139 // Write out the beginning of the instruction
140 out.push_back(((wordCount) << WordCountShift) | opCode);
142 out.push_back(typeId);
144 out.push_back(resultId);
146 // Write out the operands
147 for (int op = 0; op < (int)operands.size(); ++op)
148 out.push_back(operands[op]);
152 Instruction(const Instruction&);
156 std::vector<Id> operands;
166 Block(Id id, Function& parent);
171 Id getId() { return instructions.front()->getResultId(); }
173 Function& getParent() const { return parent; }
174 void addInstruction(std::unique_ptr<Instruction> inst);
175 void addPredecessor(Block* pred) { predecessors.push_back(pred); pred->successors.push_back(this);}
176 void addLocalVariable(std::unique_ptr<Instruction> inst) { localVariables.push_back(std::move(inst)); }
177 const std::vector<Block*>& getPredecessors() const { return predecessors; }
178 const std::vector<Block*>& getSuccessors() const { return successors; }
179 const std::vector<std::unique_ptr<Instruction> >& getInstructions() const {
182 void setUnreachable() { unreachable = true; }
183 bool isUnreachable() const { return unreachable; }
184 // Returns the block's merge instruction, if one exists (otherwise null).
185 const Instruction* getMergeInstruction() const {
186 if (instructions.size() < 2) return nullptr;
187 const Instruction* nextToLast = (instructions.cend() - 2)->get();
188 switch (nextToLast->getOpCode()) {
189 case OpSelectionMerge:
198 bool isTerminated() const
200 switch (instructions.back()->getOpCode()) {
202 case OpBranchConditional:
213 void dump(std::vector<unsigned int>& out) const
215 instructions[0]->dump(out);
216 for (int i = 0; i < (int)localVariables.size(); ++i)
217 localVariables[i]->dump(out);
218 for (int i = 1; i < (int)instructions.size(); ++i)
219 instructions[i]->dump(out);
224 Block& operator=(Block&);
226 // To enforce keeping parent and ownership in sync:
229 std::vector<std::unique_ptr<Instruction> > instructions;
230 std::vector<Block*> predecessors, successors;
231 std::vector<std::unique_ptr<Instruction> > localVariables;
234 // track whether this block is known to be uncreachable (not necessarily
235 // true for all unreachable blocks, but should be set at least
236 // for the extraneous ones introduced by the builder).
240 // Traverses the control-flow graph rooted at root in an order suited for
241 // readable code generation. Invokes callback at every node in the traversal
243 void inReadableOrder(Block* root, std::function<void(Block*)> callback);
246 // SPIR-V IR Function.
251 Function(Id id, Id resultType, Id functionType, Id firstParam, Module& parent);
254 for (int i = 0; i < (int)parameterInstructions.size(); ++i)
255 delete parameterInstructions[i];
257 for (int i = 0; i < (int)blocks.size(); ++i)
260 Id getId() const { return functionInstruction.getResultId(); }
261 Id getParamId(int p) { return parameterInstructions[p]->getResultId(); }
263 void addBlock(Block* block) { blocks.push_back(block); }
264 void removeBlock(Block* block)
266 auto found = find(blocks.begin(), blocks.end(), block);
267 assert(found != blocks.end());
272 Module& getParent() const { return parent; }
273 Block* getEntryBlock() const { return blocks.front(); }
274 Block* getLastBlock() const { return blocks.back(); }
275 const std::vector<Block*>& getBlocks() const { return blocks; }
276 void addLocalVariable(std::unique_ptr<Instruction> inst);
277 Id getReturnType() const { return functionInstruction.getTypeId(); }
279 void setImplicitThis() { implicitThis = true; }
280 bool hasImplicitThis() const { return implicitThis; }
282 void dump(std::vector<unsigned int>& out) const
285 functionInstruction.dump(out);
287 // OpFunctionParameter
288 for (int p = 0; p < (int)parameterInstructions.size(); ++p)
289 parameterInstructions[p]->dump(out);
292 inReadableOrder(blocks[0], [&out](const Block* b) { b->dump(out); });
293 Instruction end(0, 0, OpFunctionEnd);
298 Function(const Function&);
299 Function& operator=(Function&);
302 Instruction functionInstruction;
303 std::vector<Instruction*> parameterInstructions;
304 std::vector<Block*> blocks;
305 bool implicitThis; // true if this is a member function expecting to be passed a 'this' as the first argument
317 // TODO delete things
320 void addFunction(Function *fun) { functions.push_back(fun); }
322 void mapInstruction(Instruction *instruction)
324 spv::Id resultId = instruction->getResultId();
325 // map the instruction's result id
326 if (resultId >= idToInstruction.size())
327 idToInstruction.resize(resultId + 16);
328 idToInstruction[resultId] = instruction;
331 Instruction* getInstruction(Id id) const { return idToInstruction[id]; }
332 const std::vector<Function*>& getFunctions() const { return functions; }
333 spv::Id getTypeId(Id resultId) const { return idToInstruction[resultId]->getTypeId(); }
334 StorageClass getStorageClass(Id typeId) const
336 assert(idToInstruction[typeId]->getOpCode() == spv::OpTypePointer);
337 return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0);
340 void dump(std::vector<unsigned int>& out) const
342 for (int f = 0; f < (int)functions.size(); ++f)
343 functions[f]->dump(out);
347 Module(const Module&);
348 std::vector<Function*> functions;
350 // map from result id to instruction having that result id
351 std::vector<Instruction*> idToInstruction;
353 // map from a result id to its type id
357 // Implementation (it's here due to circular type definitions).
361 // - the OpFunction instruction
362 // - all the OpFunctionParameter instructions
363 __inline Function::Function(Id id, Id resultType, Id functionType, Id firstParamId, Module& parent)
364 : parent(parent), functionInstruction(id, resultType, OpFunction), implicitThis(false)
367 functionInstruction.addImmediateOperand(FunctionControlMaskNone);
368 functionInstruction.addIdOperand(functionType);
369 parent.mapInstruction(&functionInstruction);
370 parent.addFunction(this);
372 // OpFunctionParameter
373 Instruction* typeInst = parent.getInstruction(functionType);
374 int numParams = typeInst->getNumOperands() - 1;
375 for (int p = 0; p < numParams; ++p) {
376 Instruction* param = new Instruction(firstParamId + p, typeInst->getIdOperand(p + 1), OpFunctionParameter);
377 parent.mapInstruction(param);
378 parameterInstructions.push_back(param);
382 __inline void Function::addLocalVariable(std::unique_ptr<Instruction> inst)
384 Instruction* raw_instruction = inst.get();
385 blocks[0]->addLocalVariable(std::move(inst));
386 parent.mapInstruction(raw_instruction);
389 __inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
391 instructions.push_back(std::unique_ptr<Instruction>(new Instruction(id, NoType, OpLabel)));
392 instructions.back()->setBlock(this);
393 parent.getParent().mapInstruction(instructions.back().get());
396 __inline void Block::addInstruction(std::unique_ptr<Instruction> inst)
398 Instruction* raw_instruction = inst.get();
399 instructions.push_back(std::move(inst));
400 raw_instruction->setBlock(this);
401 if (raw_instruction->getResultId())
402 parent.getParent().mapInstruction(raw_instruction);
405 }; // end spv namespace