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) {
92 operands.push_back(id);
93 idOperand.push_back(true);
95 void addImmediateOperand(unsigned int immediate) {
96 operands.push_back(immediate);
97 idOperand.push_back(false);
99 void addStringOperand(const char* str)
102 char* wordString = (char*)&word;
103 char* wordPtr = wordString;
110 if (charCount == 4) {
111 addImmediateOperand(word);
112 wordPtr = wordString;
117 // deal with partial last word
120 for (; charCount < 4; ++charCount)
122 addImmediateOperand(word);
125 bool isIdOperand(int op) { return idOperand[op]; }
126 void setBlock(Block* b) { block = b; }
127 Block* getBlock() const { return block; }
128 Op getOpCode() const { return opCode; }
129 int getNumOperands() const
131 assert(operands.size() == idOperand.size());
132 return (int)operands.size();
134 Id getResultId() const { return resultId; }
135 Id getTypeId() const { return typeId; }
136 Id getIdOperand(int op) const {
137 assert(idOperand[op]);
140 unsigned int getImmediateOperand(int op) const {
141 assert(!idOperand[op]);
145 // Write out the binary form.
146 void dump(std::vector<unsigned int>& out) const
148 // Compute the wordCount
149 unsigned int wordCount = 1;
154 wordCount += (unsigned int)operands.size();
156 // Write out the beginning of the instruction
157 out.push_back(((wordCount) << WordCountShift) | opCode);
159 out.push_back(typeId);
161 out.push_back(resultId);
163 // Write out the operands
164 for (int op = 0; op < (int)operands.size(); ++op)
165 out.push_back(operands[op]);
169 Instruction(const Instruction&);
173 std::vector<Id> operands; // operands, both <id> and immediates (both are unsigned int)
174 std::vector<bool> idOperand; // true for operands that are <id>, false for immediates
184 Block(Id id, Function& parent);
189 Id getId() { return instructions.front()->getResultId(); }
191 Function& getParent() const { return parent; }
192 void addInstruction(std::unique_ptr<Instruction> inst);
193 void addPredecessor(Block* pred) { predecessors.push_back(pred); pred->successors.push_back(this);}
194 void addLocalVariable(std::unique_ptr<Instruction> inst) { localVariables.push_back(std::move(inst)); }
195 const std::vector<Block*>& getPredecessors() const { return predecessors; }
196 const std::vector<Block*>& getSuccessors() const { return successors; }
197 const std::vector<std::unique_ptr<Instruction> >& getInstructions() const {
200 void setUnreachable() { unreachable = true; }
201 bool isUnreachable() const { return unreachable; }
202 // Returns the block's merge instruction, if one exists (otherwise null).
203 const Instruction* getMergeInstruction() const {
204 if (instructions.size() < 2) return nullptr;
205 const Instruction* nextToLast = (instructions.cend() - 2)->get();
206 switch (nextToLast->getOpCode()) {
207 case OpSelectionMerge:
216 bool isTerminated() const
218 switch (instructions.back()->getOpCode()) {
220 case OpBranchConditional:
231 void dump(std::vector<unsigned int>& out) const
233 instructions[0]->dump(out);
234 for (int i = 0; i < (int)localVariables.size(); ++i)
235 localVariables[i]->dump(out);
236 for (int i = 1; i < (int)instructions.size(); ++i)
237 instructions[i]->dump(out);
242 Block& operator=(Block&);
244 // To enforce keeping parent and ownership in sync:
247 std::vector<std::unique_ptr<Instruction> > instructions;
248 std::vector<Block*> predecessors, successors;
249 std::vector<std::unique_ptr<Instruction> > localVariables;
252 // track whether this block is known to be uncreachable (not necessarily
253 // true for all unreachable blocks, but should be set at least
254 // for the extraneous ones introduced by the builder).
258 // Traverses the control-flow graph rooted at root in an order suited for
259 // readable code generation. Invokes callback at every node in the traversal
261 void inReadableOrder(Block* root, std::function<void(Block*)> callback);
264 // SPIR-V IR Function.
269 Function(Id id, Id resultType, Id functionType, Id firstParam, Module& parent);
272 for (int i = 0; i < (int)parameterInstructions.size(); ++i)
273 delete parameterInstructions[i];
275 for (int i = 0; i < (int)blocks.size(); ++i)
278 Id getId() const { return functionInstruction.getResultId(); }
279 Id getParamId(int p) const { return parameterInstructions[p]->getResultId(); }
280 Id getParamType(int p) const { return parameterInstructions[p]->getTypeId(); }
282 void addBlock(Block* block) { blocks.push_back(block); }
283 void removeBlock(Block* block)
285 auto found = find(blocks.begin(), blocks.end(), block);
286 assert(found != blocks.end());
291 Module& getParent() const { return parent; }
292 Block* getEntryBlock() const { return blocks.front(); }
293 Block* getLastBlock() const { return blocks.back(); }
294 const std::vector<Block*>& getBlocks() const { return blocks; }
295 void addLocalVariable(std::unique_ptr<Instruction> inst);
296 Id getReturnType() const { return functionInstruction.getTypeId(); }
298 void setImplicitThis() { implicitThis = true; }
299 bool hasImplicitThis() const { return implicitThis; }
301 void dump(std::vector<unsigned int>& out) const
304 functionInstruction.dump(out);
306 // OpFunctionParameter
307 for (int p = 0; p < (int)parameterInstructions.size(); ++p)
308 parameterInstructions[p]->dump(out);
311 inReadableOrder(blocks[0], [&out](const Block* b) { b->dump(out); });
312 Instruction end(0, 0, OpFunctionEnd);
317 Function(const Function&);
318 Function& operator=(Function&);
321 Instruction functionInstruction;
322 std::vector<Instruction*> parameterInstructions;
323 std::vector<Block*> blocks;
324 bool implicitThis; // true if this is a member function expecting to be passed a 'this' as the first argument
336 // TODO delete things
339 void addFunction(Function *fun) { functions.push_back(fun); }
341 void mapInstruction(Instruction *instruction)
343 spv::Id resultId = instruction->getResultId();
344 // map the instruction's result id
345 if (resultId >= idToInstruction.size())
346 idToInstruction.resize(resultId + 16);
347 idToInstruction[resultId] = instruction;
350 Instruction* getInstruction(Id id) const { return idToInstruction[id]; }
351 const std::vector<Function*>& getFunctions() const { return functions; }
352 spv::Id getTypeId(Id resultId) const { return idToInstruction[resultId]->getTypeId(); }
353 StorageClass getStorageClass(Id typeId) const
355 assert(idToInstruction[typeId]->getOpCode() == spv::OpTypePointer);
356 return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0);
359 void dump(std::vector<unsigned int>& out) const
361 for (int f = 0; f < (int)functions.size(); ++f)
362 functions[f]->dump(out);
366 Module(const Module&);
367 std::vector<Function*> functions;
369 // map from result id to instruction having that result id
370 std::vector<Instruction*> idToInstruction;
372 // map from a result id to its type id
376 // Implementation (it's here due to circular type definitions).
380 // - the OpFunction instruction
381 // - all the OpFunctionParameter instructions
382 __inline Function::Function(Id id, Id resultType, Id functionType, Id firstParamId, Module& parent)
383 : parent(parent), functionInstruction(id, resultType, OpFunction), implicitThis(false)
386 functionInstruction.addImmediateOperand(FunctionControlMaskNone);
387 functionInstruction.addIdOperand(functionType);
388 parent.mapInstruction(&functionInstruction);
389 parent.addFunction(this);
391 // OpFunctionParameter
392 Instruction* typeInst = parent.getInstruction(functionType);
393 int numParams = typeInst->getNumOperands() - 1;
394 for (int p = 0; p < numParams; ++p) {
395 Instruction* param = new Instruction(firstParamId + p, typeInst->getIdOperand(p + 1), OpFunctionParameter);
396 parent.mapInstruction(param);
397 parameterInstructions.push_back(param);
401 __inline void Function::addLocalVariable(std::unique_ptr<Instruction> inst)
403 Instruction* raw_instruction = inst.get();
404 blocks[0]->addLocalVariable(std::move(inst));
405 parent.mapInstruction(raw_instruction);
408 __inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
410 instructions.push_back(std::unique_ptr<Instruction>(new Instruction(id, NoType, OpLabel)));
411 instructions.back()->setBlock(this);
412 parent.getParent().mapInstruction(instructions.back().get());
415 __inline void Block::addInstruction(std::unique_ptr<Instruction> inst)
417 Instruction* raw_instruction = inst.get();
418 instructions.push_back(std::move(inst));
419 raw_instruction->setBlock(this);
420 if (raw_instruction->getResultId())
421 parent.getParent().mapInstruction(raw_instruction);
424 }; // end spv namespace