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
67 const Id NoResult = 0;
70 const unsigned int BadValue = 0xFFFFFFFF;
71 const Decoration NoPrecision = (Decoration)BadValue;
72 const MemorySemanticsMask MemorySemanticsAllMemory = (MemorySemanticsMask)0x3FF;
75 // SPIR-V IR instruction.
80 Instruction(Id resultId, Id typeId, Op opCode) : resultId(resultId), typeId(typeId), opCode(opCode), block(nullptr) { }
81 explicit Instruction(Op opCode) : resultId(NoResult), typeId(NoType), opCode(opCode), block(nullptr) { }
82 virtual ~Instruction() {}
83 void addIdOperand(Id id) { operands.push_back(id); }
84 void addImmediateOperand(unsigned int immediate) { operands.push_back(immediate); }
85 void addStringOperand(const char* str)
89 char* wordString = (char*)&word;
90 char* wordPtr = wordString;
98 addImmediateOperand(word);
104 // deal with partial last word
107 for (; charCount < 4; ++charCount)
109 addImmediateOperand(word);
112 void setBlock(Block* b) { block = b; }
113 Block* getBlock() const { return block; }
114 Op getOpCode() const { return opCode; }
115 int getNumOperands() const { return (int)operands.size(); }
116 Id getResultId() const { return resultId; }
117 Id getTypeId() const { return typeId; }
118 Id getIdOperand(int op) const { return operands[op]; }
119 unsigned int getImmediateOperand(int op) const { return operands[op]; }
120 const char* getStringOperand() const { return originalString.c_str(); }
122 // Write out the binary form.
123 void dump(std::vector<unsigned int>& out) const
125 // Compute the wordCount
126 unsigned int wordCount = 1;
131 wordCount += (unsigned int)operands.size();
133 // Write out the beginning of the instruction
134 out.push_back(((wordCount) << WordCountShift) | opCode);
136 out.push_back(typeId);
138 out.push_back(resultId);
140 // Write out the operands
141 for (int op = 0; op < (int)operands.size(); ++op)
142 out.push_back(operands[op]);
146 Instruction(const Instruction&);
150 std::vector<Id> operands;
151 std::string originalString; // could be optimized away; convenience for getting string operand
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 void setUnreachable() { unreachable = true; }
175 bool isUnreachable() const { return unreachable; }
176 // Returns the block's merge instruction, if one exists (otherwise null).
177 const Instruction* getMergeInstruction() const {
178 if (instructions.size() < 2) return nullptr;
179 const Instruction* nextToLast = (instructions.cend() - 2)->get();
180 switch (nextToLast->getOpCode()) {
181 case OpSelectionMerge:
190 bool isTerminated() const
192 switch (instructions.back()->getOpCode()) {
194 case OpBranchConditional:
205 void dump(std::vector<unsigned int>& out) const
207 // skip the degenerate unreachable blocks
208 // TODO: code gen: skip all unreachable blocks (transitive closure)
209 // (but, until that's done safer to keep non-degenerate unreachable blocks, in case others depend on something)
210 if (unreachable && instructions.size() <= 2)
213 instructions[0]->dump(out);
214 for (int i = 0; i < (int)localVariables.size(); ++i)
215 localVariables[i]->dump(out);
216 for (int i = 1; i < (int)instructions.size(); ++i)
217 instructions[i]->dump(out);
222 Block& operator=(Block&);
224 // To enforce keeping parent and ownership in sync:
227 std::vector<std::unique_ptr<Instruction> > instructions;
228 std::vector<Block*> predecessors, successors;
229 std::vector<std::unique_ptr<Instruction> > localVariables;
232 // track whether this block is known to be uncreachable (not necessarily
233 // true for all unreachable blocks, but should be set at least
234 // for the extraneous ones introduced by the builder).
238 // Traverses the control-flow graph rooted at root in an order suited for
239 // readable code generation. Invokes callback at every node in the traversal
241 void inReadableOrder(Block* root, std::function<void(Block*)> callback);
244 // SPIR-V IR Function.
249 Function(Id id, Id resultType, Id functionType, Id firstParam, Module& parent);
252 for (int i = 0; i < (int)parameterInstructions.size(); ++i)
253 delete parameterInstructions[i];
255 for (int i = 0; i < (int)blocks.size(); ++i)
258 Id getId() const { return functionInstruction.getResultId(); }
259 Id getParamId(int p) { return parameterInstructions[p]->getResultId(); }
261 void addBlock(Block* block) { blocks.push_back(block); }
262 void popBlock(Block*) { blocks.pop_back(); }
264 Module& getParent() const { return parent; }
265 Block* getEntryBlock() const { return blocks.front(); }
266 Block* getLastBlock() const { return blocks.back(); }
267 void addLocalVariable(std::unique_ptr<Instruction> inst);
268 Id getReturnType() const { return functionInstruction.getTypeId(); }
269 void dump(std::vector<unsigned int>& out) const
272 functionInstruction.dump(out);
274 // OpFunctionParameter
275 for (int p = 0; p < (int)parameterInstructions.size(); ++p)
276 parameterInstructions[p]->dump(out);
279 inReadableOrder(blocks[0], [&out](const Block* b) { b->dump(out); });
280 Instruction end(0, 0, OpFunctionEnd);
285 Function(const Function&);
286 Function& operator=(Function&);
289 Instruction functionInstruction;
290 std::vector<Instruction*> parameterInstructions;
291 std::vector<Block*> blocks;
303 // TODO delete things
306 void addFunction(Function *fun) { functions.push_back(fun); }
308 void mapInstruction(Instruction *instruction)
310 spv::Id resultId = instruction->getResultId();
311 // map the instruction's result id
312 if (resultId >= idToInstruction.size())
313 idToInstruction.resize(resultId + 16);
314 idToInstruction[resultId] = instruction;
317 Instruction* getInstruction(Id id) const { return idToInstruction[id]; }
318 spv::Id getTypeId(Id resultId) const { return idToInstruction[resultId]->getTypeId(); }
319 StorageClass getStorageClass(Id typeId) const
321 assert(idToInstruction[typeId]->getOpCode() == spv::OpTypePointer);
322 return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0);
325 void dump(std::vector<unsigned int>& out) const
327 for (int f = 0; f < (int)functions.size(); ++f)
328 functions[f]->dump(out);
332 Module(const Module&);
333 std::vector<Function*> functions;
335 // map from result id to instruction having that result id
336 std::vector<Instruction*> idToInstruction;
338 // map from a result id to its type id
342 // Implementation (it's here due to circular type definitions).
346 // - the OpFunction instruction
347 // - all the OpFunctionParameter instructions
348 __inline Function::Function(Id id, Id resultType, Id functionType, Id firstParamId, Module& parent)
349 : parent(parent), functionInstruction(id, resultType, OpFunction)
352 functionInstruction.addImmediateOperand(FunctionControlMaskNone);
353 functionInstruction.addIdOperand(functionType);
354 parent.mapInstruction(&functionInstruction);
355 parent.addFunction(this);
357 // OpFunctionParameter
358 Instruction* typeInst = parent.getInstruction(functionType);
359 int numParams = typeInst->getNumOperands() - 1;
360 for (int p = 0; p < numParams; ++p) {
361 Instruction* param = new Instruction(firstParamId + p, typeInst->getIdOperand(p + 1), OpFunctionParameter);
362 parent.mapInstruction(param);
363 parameterInstructions.push_back(param);
367 __inline void Function::addLocalVariable(std::unique_ptr<Instruction> inst)
369 Instruction* raw_instruction = inst.get();
370 blocks[0]->addLocalVariable(std::move(inst));
371 parent.mapInstruction(raw_instruction);
374 __inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
376 instructions.push_back(std::unique_ptr<Instruction>(new Instruction(id, NoType, OpLabel)));
377 instructions.back()->setBlock(this);
378 parent.getParent().mapInstruction(instructions.back().get());
381 __inline void Block::addInstruction(std::unique_ptr<Instruction> inst)
383 Instruction* raw_instruction = inst.get();
384 instructions.push_back(std::move(inst));
385 raw_instruction->setBlock(this);
386 if (raw_instruction->getResultId())
387 parent.getParent().mapInstruction(raw_instruction);
390 }; // end spv namespace