2 // Copyright (C) 2014 LunarG, Inc.
3 // Copyright (C) 2015-2018 Google, Inc.
5 // All rights reserved.
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
11 // Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
14 // Redistributions in binary form must reproduce the above
15 // copyright notice, this list of conditions and the following
16 // disclaimer in the documentation and/or other materials provided
17 // with the distribution.
19 // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20 // contributors may be used to endorse or promote products derived
21 // from this software without specific prior written permission.
23 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34 // POSSIBILITY OF SUCH DAMAGE.
38 // Simple in-memory representation (IR) of SPIRV. Just for holding
39 // Each function's CFG of blocks. Has this hierarchy:
40 // - Module, which is a list of
41 // - Function, which is a list of
42 // - Block, which is a list of
65 const Id NoResult = 0;
68 const Decoration NoPrecision = DecorationMax;
71 # define POTENTIALLY_UNUSED __attribute__((unused))
73 # define POTENTIALLY_UNUSED
77 const MemorySemanticsMask MemorySemanticsAllMemory =
78 (MemorySemanticsMask)(MemorySemanticsUniformMemoryMask |
79 MemorySemanticsWorkgroupMemoryMask |
80 MemorySemanticsAtomicCounterMemoryMask |
81 MemorySemanticsImageMemoryMask);
84 bool isId; // true if word is an Id, false if word is an immediate
86 IdImmediate(bool i, unsigned w) : isId(i), word(w) {}
90 // SPIR-V IR instruction.
95 Instruction(Id resultId, Id typeId, Op opCode) : resultId(resultId), typeId(typeId), opCode(opCode), block(nullptr) { }
96 explicit Instruction(Op opCode) : resultId(NoResult), typeId(NoType), opCode(opCode), block(nullptr) { }
97 virtual ~Instruction() {}
98 void addIdOperand(Id id) {
99 operands.push_back(id);
100 idOperand.push_back(true);
102 void addImmediateOperand(unsigned int immediate) {
103 operands.push_back(immediate);
104 idOperand.push_back(false);
106 void setImmediateOperand(unsigned idx, unsigned int immediate) {
107 assert(!idOperand[idx]);
108 operands[idx] = immediate;
111 void addStringOperand(const char* str)
114 char* wordString = (char*)&word;
115 char* wordPtr = wordString;
122 if (charCount == 4) {
123 addImmediateOperand(word);
124 wordPtr = wordString;
129 // deal with partial last word
132 for (; charCount < 4; ++charCount)
134 addImmediateOperand(word);
137 bool isIdOperand(int op) const { return idOperand[op]; }
138 void setBlock(Block* b) { block = b; }
139 Block* getBlock() const { return block; }
140 Op getOpCode() const { return opCode; }
141 int getNumOperands() const
143 assert(operands.size() == idOperand.size());
144 return (int)operands.size();
146 Id getResultId() const { return resultId; }
147 Id getTypeId() const { return typeId; }
148 Id getIdOperand(int op) const {
149 assert(idOperand[op]);
152 unsigned int getImmediateOperand(int op) const {
153 assert(!idOperand[op]);
157 // Write out the binary form.
158 void dump(std::vector<unsigned int>& out) const
160 // Compute the wordCount
161 unsigned int wordCount = 1;
166 wordCount += (unsigned int)operands.size();
168 // Write out the beginning of the instruction
169 out.push_back(((wordCount) << WordCountShift) | opCode);
171 out.push_back(typeId);
173 out.push_back(resultId);
175 // Write out the operands
176 for (int op = 0; op < (int)operands.size(); ++op)
177 out.push_back(operands[op]);
181 Instruction(const Instruction&);
185 std::vector<Id> operands; // operands, both <id> and immediates (both are unsigned int)
186 std::vector<bool> idOperand; // true for operands that are <id>, false for immediates
196 Block(Id id, Function& parent);
201 Id getId() { return instructions.front()->getResultId(); }
203 Function& getParent() const { return parent; }
204 void addInstruction(std::unique_ptr<Instruction> inst);
205 void addPredecessor(Block* pred) { predecessors.push_back(pred); pred->successors.push_back(this);}
206 void addLocalVariable(std::unique_ptr<Instruction> inst) { localVariables.push_back(std::move(inst)); }
207 const std::vector<Block*>& getPredecessors() const { return predecessors; }
208 const std::vector<Block*>& getSuccessors() const { return successors; }
209 const std::vector<std::unique_ptr<Instruction> >& getInstructions() const {
212 const std::vector<std::unique_ptr<Instruction> >& getLocalVariables() const { return localVariables; }
213 void setUnreachable() { unreachable = true; }
214 bool isUnreachable() const { return unreachable; }
215 // Returns the block's merge instruction, if one exists (otherwise null).
216 const Instruction* getMergeInstruction() const {
217 if (instructions.size() < 2) return nullptr;
218 const Instruction* nextToLast = (instructions.cend() - 2)->get();
219 switch (nextToLast->getOpCode()) {
220 case OpSelectionMerge:
229 // Change this block into a canonical dead merge block. Delete instructions
230 // as necessary. A canonical dead merge block has only an OpLabel and an
232 void rewriteAsCanonicalUnreachableMerge() {
233 assert(localVariables.empty());
234 // Delete all instructions except for the label.
235 assert(instructions.size() > 0);
236 instructions.resize(1);
238 addInstruction(std::unique_ptr<Instruction>(new Instruction(OpUnreachable)));
240 // Change this block into a canonical dead continue target branching to the
241 // given header ID. Delete instructions as necessary. A canonical dead continue
242 // target has only an OpLabel and an unconditional branch back to the corresponding
244 void rewriteAsCanonicalUnreachableContinue(Block* header) {
245 assert(localVariables.empty());
246 // Delete all instructions except for the label.
247 assert(instructions.size() > 0);
248 instructions.resize(1);
250 // Add OpBranch back to the header.
251 assert(header != nullptr);
252 Instruction* branch = new Instruction(OpBranch);
253 branch->addIdOperand(header->getId());
254 addInstruction(std::unique_ptr<Instruction>(branch));
255 successors.push_back(header);
258 bool isTerminated() const
260 switch (instructions.back()->getOpCode()) {
262 case OpBranchConditional:
274 void dump(std::vector<unsigned int>& out) const
276 instructions[0]->dump(out);
277 for (int i = 0; i < (int)localVariables.size(); ++i)
278 localVariables[i]->dump(out);
279 for (int i = 1; i < (int)instructions.size(); ++i)
280 instructions[i]->dump(out);
285 Block& operator=(Block&);
287 // To enforce keeping parent and ownership in sync:
290 std::vector<std::unique_ptr<Instruction> > instructions;
291 std::vector<Block*> predecessors, successors;
292 std::vector<std::unique_ptr<Instruction> > localVariables;
295 // track whether this block is known to be uncreachable (not necessarily
296 // true for all unreachable blocks, but should be set at least
297 // for the extraneous ones introduced by the builder).
301 // The different reasons for reaching a block in the inReadableOrder traversal.
303 // Reachable from the entry block via transfers of control, i.e. branches.
304 ReachViaControlFlow = 0,
305 // A continue target that is not reachable via control flow.
307 // A merge block that is not reachable via control flow.
311 // Traverses the control-flow graph rooted at root in an order suited for
312 // readable code generation. Invokes callback at every node in the traversal
313 // order. The callback arguments are:
315 // - the reason we reached the block,
316 // - if the reason was that block is an unreachable continue or unreachable merge block
317 // then the last parameter is the corresponding header block.
318 void inReadableOrder(Block* root, std::function<void(Block*, ReachReason, Block* header)> callback);
321 // SPIR-V IR Function.
326 Function(Id id, Id resultType, Id functionType, Id firstParam, Module& parent);
329 for (int i = 0; i < (int)parameterInstructions.size(); ++i)
330 delete parameterInstructions[i];
332 for (int i = 0; i < (int)blocks.size(); ++i)
335 Id getId() const { return functionInstruction.getResultId(); }
336 Id getParamId(int p) const { return parameterInstructions[p]->getResultId(); }
337 Id getParamType(int p) const { return parameterInstructions[p]->getTypeId(); }
339 void addBlock(Block* block) { blocks.push_back(block); }
340 void removeBlock(Block* block)
342 auto found = find(blocks.begin(), blocks.end(), block);
343 assert(found != blocks.end());
348 Module& getParent() const { return parent; }
349 Block* getEntryBlock() const { return blocks.front(); }
350 Block* getLastBlock() const { return blocks.back(); }
351 const std::vector<Block*>& getBlocks() const { return blocks; }
352 void addLocalVariable(std::unique_ptr<Instruction> inst);
353 Id getReturnType() const { return functionInstruction.getTypeId(); }
355 void setImplicitThis() { implicitThis = true; }
356 bool hasImplicitThis() const { return implicitThis; }
358 void dump(std::vector<unsigned int>& out) const
361 functionInstruction.dump(out);
363 // OpFunctionParameter
364 for (int p = 0; p < (int)parameterInstructions.size(); ++p)
365 parameterInstructions[p]->dump(out);
368 inReadableOrder(blocks[0], [&out](const Block* b, ReachReason, Block*) { b->dump(out); });
369 Instruction end(0, 0, OpFunctionEnd);
374 Function(const Function&);
375 Function& operator=(Function&);
378 Instruction functionInstruction;
379 std::vector<Instruction*> parameterInstructions;
380 std::vector<Block*> blocks;
381 bool implicitThis; // true if this is a member function expecting to be passed a 'this' as the first argument
393 // TODO delete things
396 void addFunction(Function *fun) { functions.push_back(fun); }
398 void mapInstruction(Instruction *instruction)
400 spv::Id resultId = instruction->getResultId();
401 // map the instruction's result id
402 if (resultId >= idToInstruction.size())
403 idToInstruction.resize(resultId + 16);
404 idToInstruction[resultId] = instruction;
407 Instruction* getInstruction(Id id) const { return idToInstruction[id]; }
408 const std::vector<Function*>& getFunctions() const { return functions; }
409 spv::Id getTypeId(Id resultId) const {
410 return idToInstruction[resultId] == nullptr ? NoType : idToInstruction[resultId]->getTypeId();
412 StorageClass getStorageClass(Id typeId) const
414 assert(idToInstruction[typeId]->getOpCode() == spv::OpTypePointer);
415 return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0);
418 void dump(std::vector<unsigned int>& out) const
420 for (int f = 0; f < (int)functions.size(); ++f)
421 functions[f]->dump(out);
425 Module(const Module&);
426 std::vector<Function*> functions;
428 // map from result id to instruction having that result id
429 std::vector<Instruction*> idToInstruction;
431 // map from a result id to its type id
435 // Implementation (it's here due to circular type definitions).
439 // - the OpFunction instruction
440 // - all the OpFunctionParameter instructions
441 __inline Function::Function(Id id, Id resultType, Id functionType, Id firstParamId, Module& parent)
442 : parent(parent), functionInstruction(id, resultType, OpFunction), implicitThis(false)
445 functionInstruction.addImmediateOperand(FunctionControlMaskNone);
446 functionInstruction.addIdOperand(functionType);
447 parent.mapInstruction(&functionInstruction);
448 parent.addFunction(this);
450 // OpFunctionParameter
451 Instruction* typeInst = parent.getInstruction(functionType);
452 int numParams = typeInst->getNumOperands() - 1;
453 for (int p = 0; p < numParams; ++p) {
454 Instruction* param = new Instruction(firstParamId + p, typeInst->getIdOperand(p + 1), OpFunctionParameter);
455 parent.mapInstruction(param);
456 parameterInstructions.push_back(param);
460 __inline void Function::addLocalVariable(std::unique_ptr<Instruction> inst)
462 Instruction* raw_instruction = inst.get();
463 blocks[0]->addLocalVariable(std::move(inst));
464 parent.mapInstruction(raw_instruction);
467 __inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
469 instructions.push_back(std::unique_ptr<Instruction>(new Instruction(id, NoType, OpLabel)));
470 instructions.back()->setBlock(this);
471 parent.getParent().mapInstruction(instructions.back().get());
474 __inline void Block::addInstruction(std::unique_ptr<Instruction> inst)
476 Instruction* raw_instruction = inst.get();
477 instructions.push_back(std::move(inst));
478 raw_instruction->setBlock(this);
479 if (raw_instruction->getResultId())
480 parent.getParent().mapInstruction(raw_instruction);
483 } // end spv namespace