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 bool isId; // true if word is an Id, false if word is an immediate
88 // SPIR-V IR instruction.
93 Instruction(Id resultId, Id typeId, Op opCode) : resultId(resultId), typeId(typeId), opCode(opCode), block(nullptr) { }
94 explicit Instruction(Op opCode) : resultId(NoResult), typeId(NoType), opCode(opCode), block(nullptr) { }
95 virtual ~Instruction() {}
96 void addIdOperand(Id id) {
97 operands.push_back(id);
98 idOperand.push_back(true);
100 void addImmediateOperand(unsigned int immediate) {
101 operands.push_back(immediate);
102 idOperand.push_back(false);
104 void addStringOperand(const char* str)
107 char* wordString = (char*)&word;
108 char* wordPtr = wordString;
115 if (charCount == 4) {
116 addImmediateOperand(word);
117 wordPtr = wordString;
122 // deal with partial last word
125 for (; charCount < 4; ++charCount)
127 addImmediateOperand(word);
130 bool isIdOperand(int op) const { return idOperand[op]; }
131 void setBlock(Block* b) { block = b; }
132 Block* getBlock() const { return block; }
133 Op getOpCode() const { return opCode; }
134 int getNumOperands() const
136 assert(operands.size() == idOperand.size());
137 return (int)operands.size();
139 Id getResultId() const { return resultId; }
140 Id getTypeId() const { return typeId; }
141 Id getIdOperand(int op) const {
142 assert(idOperand[op]);
145 unsigned int getImmediateOperand(int op) const {
146 assert(!idOperand[op]);
150 // Write out the binary form.
151 void dump(std::vector<unsigned int>& out) const
153 // Compute the wordCount
154 unsigned int wordCount = 1;
159 wordCount += (unsigned int)operands.size();
161 // Write out the beginning of the instruction
162 out.push_back(((wordCount) << WordCountShift) | opCode);
164 out.push_back(typeId);
166 out.push_back(resultId);
168 // Write out the operands
169 for (int op = 0; op < (int)operands.size(); ++op)
170 out.push_back(operands[op]);
174 Instruction(const Instruction&);
178 std::vector<Id> operands; // operands, both <id> and immediates (both are unsigned int)
179 std::vector<bool> idOperand; // true for operands that are <id>, false for immediates
189 Block(Id id, Function& parent);
194 Id getId() { return instructions.front()->getResultId(); }
196 Function& getParent() const { return parent; }
197 void addInstruction(std::unique_ptr<Instruction> inst);
198 void addPredecessor(Block* pred) { predecessors.push_back(pred); pred->successors.push_back(this);}
199 void addLocalVariable(std::unique_ptr<Instruction> inst) { localVariables.push_back(std::move(inst)); }
200 const std::vector<Block*>& getPredecessors() const { return predecessors; }
201 const std::vector<Block*>& getSuccessors() const { return successors; }
202 const std::vector<std::unique_ptr<Instruction> >& getInstructions() const {
205 void setUnreachable() { unreachable = true; }
206 bool isUnreachable() const { return unreachable; }
207 // Returns the block's merge instruction, if one exists (otherwise null).
208 const Instruction* getMergeInstruction() const {
209 if (instructions.size() < 2) return nullptr;
210 const Instruction* nextToLast = (instructions.cend() - 2)->get();
211 switch (nextToLast->getOpCode()) {
212 case OpSelectionMerge:
221 bool isTerminated() const
223 switch (instructions.back()->getOpCode()) {
225 case OpBranchConditional:
236 void dump(std::vector<unsigned int>& out) const
238 instructions[0]->dump(out);
239 for (int i = 0; i < (int)localVariables.size(); ++i)
240 localVariables[i]->dump(out);
241 for (int i = 1; i < (int)instructions.size(); ++i)
242 instructions[i]->dump(out);
247 Block& operator=(Block&);
249 // To enforce keeping parent and ownership in sync:
252 std::vector<std::unique_ptr<Instruction> > instructions;
253 std::vector<Block*> predecessors, successors;
254 std::vector<std::unique_ptr<Instruction> > localVariables;
257 // track whether this block is known to be uncreachable (not necessarily
258 // true for all unreachable blocks, but should be set at least
259 // for the extraneous ones introduced by the builder).
263 // Traverses the control-flow graph rooted at root in an order suited for
264 // readable code generation. Invokes callback at every node in the traversal
266 void inReadableOrder(Block* root, std::function<void(Block*)> callback);
269 // SPIR-V IR Function.
274 Function(Id id, Id resultType, Id functionType, Id firstParam, Module& parent);
277 for (int i = 0; i < (int)parameterInstructions.size(); ++i)
278 delete parameterInstructions[i];
280 for (int i = 0; i < (int)blocks.size(); ++i)
283 Id getId() const { return functionInstruction.getResultId(); }
284 Id getParamId(int p) const { return parameterInstructions[p]->getResultId(); }
285 Id getParamType(int p) const { return parameterInstructions[p]->getTypeId(); }
287 void addBlock(Block* block) { blocks.push_back(block); }
288 void removeBlock(Block* block)
290 auto found = find(blocks.begin(), blocks.end(), block);
291 assert(found != blocks.end());
296 Module& getParent() const { return parent; }
297 Block* getEntryBlock() const { return blocks.front(); }
298 Block* getLastBlock() const { return blocks.back(); }
299 const std::vector<Block*>& getBlocks() const { return blocks; }
300 void addLocalVariable(std::unique_ptr<Instruction> inst);
301 Id getReturnType() const { return functionInstruction.getTypeId(); }
303 void setImplicitThis() { implicitThis = true; }
304 bool hasImplicitThis() const { return implicitThis; }
306 void dump(std::vector<unsigned int>& out) const
309 functionInstruction.dump(out);
311 // OpFunctionParameter
312 for (int p = 0; p < (int)parameterInstructions.size(); ++p)
313 parameterInstructions[p]->dump(out);
316 inReadableOrder(blocks[0], [&out](const Block* b) { b->dump(out); });
317 Instruction end(0, 0, OpFunctionEnd);
322 Function(const Function&);
323 Function& operator=(Function&);
326 Instruction functionInstruction;
327 std::vector<Instruction*> parameterInstructions;
328 std::vector<Block*> blocks;
329 bool implicitThis; // true if this is a member function expecting to be passed a 'this' as the first argument
341 // TODO delete things
344 void addFunction(Function *fun) { functions.push_back(fun); }
346 void mapInstruction(Instruction *instruction)
348 spv::Id resultId = instruction->getResultId();
349 // map the instruction's result id
350 if (resultId >= idToInstruction.size())
351 idToInstruction.resize(resultId + 16);
352 idToInstruction[resultId] = instruction;
355 Instruction* getInstruction(Id id) const { return idToInstruction[id]; }
356 const std::vector<Function*>& getFunctions() const { return functions; }
357 spv::Id getTypeId(Id resultId) const {
358 return idToInstruction[resultId] == nullptr ? NoType : idToInstruction[resultId]->getTypeId();
360 StorageClass getStorageClass(Id typeId) const
362 assert(idToInstruction[typeId]->getOpCode() == spv::OpTypePointer);
363 return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0);
366 void dump(std::vector<unsigned int>& out) const
368 for (int f = 0; f < (int)functions.size(); ++f)
369 functions[f]->dump(out);
373 Module(const Module&);
374 std::vector<Function*> functions;
376 // map from result id to instruction having that result id
377 std::vector<Instruction*> idToInstruction;
379 // map from a result id to its type id
383 // Implementation (it's here due to circular type definitions).
387 // - the OpFunction instruction
388 // - all the OpFunctionParameter instructions
389 __inline Function::Function(Id id, Id resultType, Id functionType, Id firstParamId, Module& parent)
390 : parent(parent), functionInstruction(id, resultType, OpFunction), implicitThis(false)
393 functionInstruction.addImmediateOperand(FunctionControlMaskNone);
394 functionInstruction.addIdOperand(functionType);
395 parent.mapInstruction(&functionInstruction);
396 parent.addFunction(this);
398 // OpFunctionParameter
399 Instruction* typeInst = parent.getInstruction(functionType);
400 int numParams = typeInst->getNumOperands() - 1;
401 for (int p = 0; p < numParams; ++p) {
402 Instruction* param = new Instruction(firstParamId + p, typeInst->getIdOperand(p + 1), OpFunctionParameter);
403 parent.mapInstruction(param);
404 parameterInstructions.push_back(param);
408 __inline void Function::addLocalVariable(std::unique_ptr<Instruction> inst)
410 Instruction* raw_instruction = inst.get();
411 blocks[0]->addLocalVariable(std::move(inst));
412 parent.mapInstruction(raw_instruction);
415 __inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
417 instructions.push_back(std::unique_ptr<Instruction>(new Instruction(id, NoType, OpLabel)));
418 instructions.back()->setBlock(this);
419 parent.getParent().mapInstruction(instructions.back().get());
422 __inline void Block::addInstruction(std::unique_ptr<Instruction> inst)
424 Instruction* raw_instruction = inst.get();
425 instructions.push_back(std::move(inst));
426 raw_instruction->setBlock(this);
427 if (raw_instruction->getResultId())
428 parent.getParent().mapInstruction(raw_instruction);
431 }; // end spv namespace