• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright (C) 2014 LunarG, Inc.
3 // Copyright (C) 2015-2018 Google, Inc.
4 //
5 // All rights reserved.
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
11 //    Redistributions of source code must retain the above copyright
12 //    notice, this list of conditions and the following disclaimer.
13 //
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.
18 //
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.
22 //
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.
35 
36 // SPIRV-IR
37 //
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
43 //        - Instruction
44 //
45 
46 #pragma once
47 #ifndef spvIR_H
48 #define spvIR_H
49 
50 #include "spirv.hpp"
51 
52 #include <algorithm>
53 #include <cassert>
54 #include <functional>
55 #include <iostream>
56 #include <memory>
57 #include <vector>
58 #include <set>
59 #include <optional>
60 
61 namespace spv {
62 
63 class Block;
64 class Function;
65 class Module;
66 
67 const Id NoResult = 0;
68 const Id NoType = 0;
69 
70 const Decoration NoPrecision = DecorationMax;
71 
72 #ifdef __GNUC__
73 #   define POTENTIALLY_UNUSED __attribute__((unused))
74 #else
75 #   define POTENTIALLY_UNUSED
76 #endif
77 
78 POTENTIALLY_UNUSED
79 const MemorySemanticsMask MemorySemanticsAllMemory =
80                 (MemorySemanticsMask)(MemorySemanticsUniformMemoryMask |
81                                       MemorySemanticsWorkgroupMemoryMask |
82                                       MemorySemanticsAtomicCounterMemoryMask |
83                                       MemorySemanticsImageMemoryMask);
84 
85 struct IdImmediate {
86     bool isId;      // true if word is an Id, false if word is an immediate
87     unsigned word;
IdImmediateIdImmediate88     IdImmediate(bool i, unsigned w) : isId(i), word(w) {}
89 };
90 
91 //
92 // SPIR-V IR instruction.
93 //
94 
95 class Instruction {
96 public:
Instruction(Id resultId,Id typeId,Op opCode)97     Instruction(Id resultId, Id typeId, Op opCode) : resultId(resultId), typeId(typeId), opCode(opCode), block(nullptr) { }
Instruction(Op opCode)98     explicit Instruction(Op opCode) : resultId(NoResult), typeId(NoType), opCode(opCode), block(nullptr) { }
~Instruction()99     virtual ~Instruction() {}
reserveOperands(size_t count)100     void reserveOperands(size_t count) {
101         operands.reserve(count);
102         idOperand.reserve(count);
103     }
addIdOperand(Id id)104     void addIdOperand(Id id) {
105         // ids can't be 0
106         assert(id);
107         operands.push_back(id);
108         idOperand.push_back(true);
109     }
110     // This method is potentially dangerous as it can break assumptions
111     // about SSA and lack of forward references.
setIdOperand(unsigned idx,Id id)112     void setIdOperand(unsigned idx, Id id) {
113         assert(id);
114         assert(idOperand[idx]);
115         operands[idx] = id;
116     }
117 
addImmediateOperand(unsigned int immediate)118     void addImmediateOperand(unsigned int immediate) {
119         operands.push_back(immediate);
120         idOperand.push_back(false);
121     }
setImmediateOperand(unsigned idx,unsigned int immediate)122     void setImmediateOperand(unsigned idx, unsigned int immediate) {
123         assert(!idOperand[idx]);
124         operands[idx] = immediate;
125     }
126 
addStringOperand(const char * str)127     void addStringOperand(const char* str)
128     {
129         unsigned int word = 0;
130         unsigned int shiftAmount = 0;
131         char c;
132 
133         do {
134             c = *(str++);
135             word |= ((unsigned int)c) << shiftAmount;
136             shiftAmount += 8;
137             if (shiftAmount == 32) {
138                 addImmediateOperand(word);
139                 word = 0;
140                 shiftAmount = 0;
141             }
142         } while (c != 0);
143 
144         // deal with partial last word
145         if (shiftAmount > 0) {
146             addImmediateOperand(word);
147         }
148     }
isIdOperand(int op)149     bool isIdOperand(int op) const { return idOperand[op]; }
setBlock(Block * b)150     void setBlock(Block* b) { block = b; }
getBlock()151     Block* getBlock() const { return block; }
getOpCode()152     Op getOpCode() const { return opCode; }
getNumOperands()153     int getNumOperands() const
154     {
155         assert(operands.size() == idOperand.size());
156         return (int)operands.size();
157     }
getResultId()158     Id getResultId() const { return resultId; }
getTypeId()159     Id getTypeId() const { return typeId; }
getIdOperand(int op)160     Id getIdOperand(int op) const {
161         assert(idOperand[op]);
162         return operands[op];
163     }
getImmediateOperand(int op)164     unsigned int getImmediateOperand(int op) const {
165         assert(!idOperand[op]);
166         return operands[op];
167     }
168 
169     // Write out the binary form.
dump(std::vector<unsigned int> & out)170     void dump(std::vector<unsigned int>& out) const
171     {
172         // Compute the wordCount
173         unsigned int wordCount = 1;
174         if (typeId)
175             ++wordCount;
176         if (resultId)
177             ++wordCount;
178         wordCount += (unsigned int)operands.size();
179 
180         // Write out the beginning of the instruction
181         out.push_back(((wordCount) << WordCountShift) | opCode);
182         if (typeId)
183             out.push_back(typeId);
184         if (resultId)
185             out.push_back(resultId);
186 
187         // Write out the operands
188         for (int op = 0; op < (int)operands.size(); ++op)
189             out.push_back(operands[op]);
190     }
191 
192 protected:
193     Instruction(const Instruction&);
194     Id resultId;
195     Id typeId;
196     Op opCode;
197     std::vector<Id> operands;     // operands, both <id> and immediates (both are unsigned int)
198     std::vector<bool> idOperand;  // true for operands that are <id>, false for immediates
199     Block* block;
200 };
201 
202 //
203 // SPIR-V IR block.
204 //
205 
206 struct DebugSourceLocation {
207     int line;
208     int column;
209     spv::Id fileId;
210 };
211 
212 class Block {
213 public:
214     Block(Id id, Function& parent);
~Block()215     virtual ~Block()
216     {
217     }
218 
getId()219     Id getId() { return instructions.front()->getResultId(); }
220 
getParent()221     Function& getParent() const { return parent; }
222     // Returns true if the source location is actually updated.
223     // Note we still need the builder to insert the line marker instruction. This is just a tracker.
updateDebugSourceLocation(int line,int column,spv::Id fileId)224     bool updateDebugSourceLocation(int line, int column, spv::Id fileId) {
225         if (currentSourceLoc && currentSourceLoc->line == line && currentSourceLoc->column == column &&
226             currentSourceLoc->fileId == fileId) {
227             return false;
228         }
229 
230         currentSourceLoc = DebugSourceLocation{line, column, fileId};
231         return true;
232     }
233     // Returns true if the scope is actually updated.
234     // Note we still need the builder to insert the debug scope instruction. This is just a tracker.
updateDebugScope(spv::Id scopeId)235     bool updateDebugScope(spv::Id scopeId) {
236         assert(scopeId);
237         if (currentDebugScope && *currentDebugScope == scopeId) {
238             return false;
239         }
240 
241         currentDebugScope = scopeId;
242         return true;
243     }
244     void addInstruction(std::unique_ptr<Instruction> inst);
addPredecessor(Block * pred)245     void addPredecessor(Block* pred) { predecessors.push_back(pred); pred->successors.push_back(this);}
addLocalVariable(std::unique_ptr<Instruction> inst)246     void addLocalVariable(std::unique_ptr<Instruction> inst) { localVariables.push_back(std::move(inst)); }
getPredecessors()247     const std::vector<Block*>& getPredecessors() const { return predecessors; }
getSuccessors()248     const std::vector<Block*>& getSuccessors() const { return successors; }
getInstructions()249     std::vector<std::unique_ptr<Instruction> >& getInstructions() {
250         return instructions;
251     }
getLocalVariables()252     const std::vector<std::unique_ptr<Instruction> >& getLocalVariables() const { return localVariables; }
setUnreachable()253     void setUnreachable() { unreachable = true; }
isUnreachable()254     bool isUnreachable() const { return unreachable; }
255     // Returns the block's merge instruction, if one exists (otherwise null).
getMergeInstruction()256     const Instruction* getMergeInstruction() const {
257         if (instructions.size() < 2) return nullptr;
258         const Instruction* nextToLast = (instructions.cend() - 2)->get();
259         switch (nextToLast->getOpCode()) {
260             case OpSelectionMerge:
261             case OpLoopMerge:
262                 return nextToLast;
263             default:
264                 return nullptr;
265         }
266         return nullptr;
267     }
268 
269     // Change this block into a canonical dead merge block.  Delete instructions
270     // as necessary.  A canonical dead merge block has only an OpLabel and an
271     // OpUnreachable.
rewriteAsCanonicalUnreachableMerge()272     void rewriteAsCanonicalUnreachableMerge() {
273         assert(localVariables.empty());
274         // Delete all instructions except for the label.
275         assert(instructions.size() > 0);
276         instructions.resize(1);
277         successors.clear();
278         addInstruction(std::unique_ptr<Instruction>(new Instruction(OpUnreachable)));
279     }
280     // Change this block into a canonical dead continue target branching to the
281     // given header ID.  Delete instructions as necessary.  A canonical dead continue
282     // target has only an OpLabel and an unconditional branch back to the corresponding
283     // header.
rewriteAsCanonicalUnreachableContinue(Block * header)284     void rewriteAsCanonicalUnreachableContinue(Block* header) {
285         assert(localVariables.empty());
286         // Delete all instructions except for the label.
287         assert(instructions.size() > 0);
288         instructions.resize(1);
289         successors.clear();
290         // Add OpBranch back to the header.
291         assert(header != nullptr);
292         Instruction* branch = new Instruction(OpBranch);
293         branch->addIdOperand(header->getId());
294         addInstruction(std::unique_ptr<Instruction>(branch));
295         successors.push_back(header);
296     }
297 
isTerminated()298     bool isTerminated() const
299     {
300         switch (instructions.back()->getOpCode()) {
301         case OpBranch:
302         case OpBranchConditional:
303         case OpSwitch:
304         case OpKill:
305         case OpTerminateInvocation:
306         case OpReturn:
307         case OpReturnValue:
308         case OpUnreachable:
309             return true;
310         default:
311             return false;
312         }
313     }
314 
dump(std::vector<unsigned int> & out)315     void dump(std::vector<unsigned int>& out) const
316     {
317         instructions[0]->dump(out);
318         for (int i = 0; i < (int)localVariables.size(); ++i)
319             localVariables[i]->dump(out);
320         for (int i = 1; i < (int)instructions.size(); ++i)
321             instructions[i]->dump(out);
322     }
323 
324 protected:
325     Block(const Block&);
326     Block& operator=(Block&);
327 
328     // To enforce keeping parent and ownership in sync:
329     friend Function;
330 
331     std::vector<std::unique_ptr<Instruction> > instructions;
332     std::vector<Block*> predecessors, successors;
333     std::vector<std::unique_ptr<Instruction> > localVariables;
334     Function& parent;
335 
336     // Track source location of the last source location marker instruction.
337     std::optional<DebugSourceLocation> currentSourceLoc;
338 
339     // Track scope of the last debug scope instruction.
340     std::optional<spv::Id> currentDebugScope;
341 
342     // track whether this block is known to be uncreachable (not necessarily
343     // true for all unreachable blocks, but should be set at least
344     // for the extraneous ones introduced by the builder).
345     bool unreachable;
346 };
347 
348 // The different reasons for reaching a block in the inReadableOrder traversal.
349 enum ReachReason {
350     // Reachable from the entry block via transfers of control, i.e. branches.
351     ReachViaControlFlow = 0,
352     // A continue target that is not reachable via control flow.
353     ReachDeadContinue,
354     // A merge block that is not reachable via control flow.
355     ReachDeadMerge
356 };
357 
358 // Traverses the control-flow graph rooted at root in an order suited for
359 // readable code generation.  Invokes callback at every node in the traversal
360 // order.  The callback arguments are:
361 // - the block,
362 // - the reason we reached the block,
363 // - if the reason was that block is an unreachable continue or unreachable merge block
364 //   then the last parameter is the corresponding header block.
365 void inReadableOrder(Block* root, std::function<void(Block*, ReachReason, Block* header)> callback);
366 
367 //
368 // SPIR-V IR Function.
369 //
370 
371 class Function {
372 public:
373     Function(Id id, Id resultType, Id functionType, Id firstParam, LinkageType linkage, const std::string& name, Module& parent);
~Function()374     virtual ~Function()
375     {
376         for (int i = 0; i < (int)parameterInstructions.size(); ++i)
377             delete parameterInstructions[i];
378 
379         for (int i = 0; i < (int)blocks.size(); ++i)
380             delete blocks[i];
381     }
getId()382     Id getId() const { return functionInstruction.getResultId(); }
getParamId(int p)383     Id getParamId(int p) const { return parameterInstructions[p]->getResultId(); }
getParamType(int p)384     Id getParamType(int p) const { return parameterInstructions[p]->getTypeId(); }
385 
addBlock(Block * block)386     void addBlock(Block* block) { blocks.push_back(block); }
removeBlock(Block * block)387     void removeBlock(Block* block)
388     {
389         auto found = find(blocks.begin(), blocks.end(), block);
390         assert(found != blocks.end());
391         blocks.erase(found);
392         delete block;
393     }
394 
getParent()395     Module& getParent() const { return parent; }
getEntryBlock()396     Block* getEntryBlock() const { return blocks.front(); }
getLastBlock()397     Block* getLastBlock() const { return blocks.back(); }
getBlocks()398     const std::vector<Block*>& getBlocks() const { return blocks; }
399     void addLocalVariable(std::unique_ptr<Instruction> inst);
getReturnType()400     Id getReturnType() const { return functionInstruction.getTypeId(); }
getFuncId()401     Id getFuncId() const { return functionInstruction.getResultId(); }
getFuncTypeId()402     Id getFuncTypeId() const { return functionInstruction.getIdOperand(1); }
setReturnPrecision(Decoration precision)403     void setReturnPrecision(Decoration precision)
404     {
405         if (precision == DecorationRelaxedPrecision)
406             reducedPrecisionReturn = true;
407     }
getReturnPrecision()408     Decoration getReturnPrecision() const
409         { return reducedPrecisionReturn ? DecorationRelaxedPrecision : NoPrecision; }
410 
setDebugLineInfo(Id fileName,int line,int column)411     void setDebugLineInfo(Id fileName, int line, int column) {
412         lineInstruction = std::unique_ptr<Instruction>{new Instruction(OpLine)};
413         lineInstruction->reserveOperands(3);
414         lineInstruction->addIdOperand(fileName);
415         lineInstruction->addImmediateOperand(line);
416         lineInstruction->addImmediateOperand(column);
417     }
hasDebugLineInfo()418     bool hasDebugLineInfo() const { return lineInstruction != nullptr; }
419 
setImplicitThis()420     void setImplicitThis() { implicitThis = true; }
hasImplicitThis()421     bool hasImplicitThis() const { return implicitThis; }
422 
addParamPrecision(unsigned param,Decoration precision)423     void addParamPrecision(unsigned param, Decoration precision)
424     {
425         if (precision == DecorationRelaxedPrecision)
426             reducedPrecisionParams.insert(param);
427     }
getParamPrecision(unsigned param)428     Decoration getParamPrecision(unsigned param) const
429     {
430         return reducedPrecisionParams.find(param) != reducedPrecisionParams.end() ?
431             DecorationRelaxedPrecision : NoPrecision;
432     }
433 
dump(std::vector<unsigned int> & out)434     void dump(std::vector<unsigned int>& out) const
435     {
436         // OpLine
437         if (lineInstruction != nullptr) {
438             lineInstruction->dump(out);
439         }
440 
441         // OpFunction
442         functionInstruction.dump(out);
443 
444         // OpFunctionParameter
445         for (int p = 0; p < (int)parameterInstructions.size(); ++p)
446             parameterInstructions[p]->dump(out);
447 
448         // Blocks
449         inReadableOrder(blocks[0], [&out](const Block* b, ReachReason, Block*) { b->dump(out); });
450         Instruction end(0, 0, OpFunctionEnd);
451         end.dump(out);
452     }
453 
getLinkType()454     LinkageType getLinkType() const { return linkType; }
getExportName()455     const char* getExportName() const { return exportName.c_str(); }
456 
457 protected:
458     Function(const Function&);
459     Function& operator=(Function&);
460 
461     Module& parent;
462     std::unique_ptr<Instruction> lineInstruction;
463     Instruction functionInstruction;
464     std::vector<Instruction*> parameterInstructions;
465     std::vector<Block*> blocks;
466     bool implicitThis;  // true if this is a member function expecting to be passed a 'this' as the first argument
467     bool reducedPrecisionReturn;
468     std::set<int> reducedPrecisionParams;  // list of parameter indexes that need a relaxed precision arg
469     LinkageType linkType;
470     std::string exportName;
471 };
472 
473 //
474 // SPIR-V IR Module.
475 //
476 
477 class Module {
478 public:
Module()479     Module() {}
~Module()480     virtual ~Module()
481     {
482         // TODO delete things
483     }
484 
addFunction(Function * fun)485     void addFunction(Function *fun) { functions.push_back(fun); }
486 
mapInstruction(Instruction * instruction)487     void mapInstruction(Instruction *instruction)
488     {
489         spv::Id resultId = instruction->getResultId();
490         // map the instruction's result id
491         if (resultId >= idToInstruction.size())
492             idToInstruction.resize(resultId + 16);
493         idToInstruction[resultId] = instruction;
494     }
495 
getInstruction(Id id)496     Instruction* getInstruction(Id id) const { return idToInstruction[id]; }
getFunctions()497     const std::vector<Function*>& getFunctions() const { return functions; }
getTypeId(Id resultId)498     spv::Id getTypeId(Id resultId) const {
499         return idToInstruction[resultId] == nullptr ? NoType : idToInstruction[resultId]->getTypeId();
500     }
getStorageClass(Id typeId)501     StorageClass getStorageClass(Id typeId) const
502     {
503         assert(idToInstruction[typeId]->getOpCode() == spv::OpTypePointer);
504         return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0);
505     }
506 
dump(std::vector<unsigned int> & out)507     void dump(std::vector<unsigned int>& out) const
508     {
509         for (int f = 0; f < (int)functions.size(); ++f)
510             functions[f]->dump(out);
511     }
512 
513 protected:
514     Module(const Module&);
515     std::vector<Function*> functions;
516 
517     // map from result id to instruction having that result id
518     std::vector<Instruction*> idToInstruction;
519 
520     // map from a result id to its type id
521 };
522 
523 //
524 // Implementation (it's here due to circular type definitions).
525 //
526 
527 // Add both
528 // - the OpFunction instruction
529 // - all the OpFunctionParameter instructions
Function(Id id,Id resultType,Id functionType,Id firstParamId,LinkageType linkage,const std::string & name,Module & parent)530 __inline Function::Function(Id id, Id resultType, Id functionType, Id firstParamId, LinkageType linkage, const std::string& name, Module& parent)
531     : parent(parent), lineInstruction(nullptr),
532       functionInstruction(id, resultType, OpFunction), implicitThis(false),
533       reducedPrecisionReturn(false),
534       linkType(linkage)
535 {
536     // OpFunction
537     functionInstruction.reserveOperands(2);
538     functionInstruction.addImmediateOperand(FunctionControlMaskNone);
539     functionInstruction.addIdOperand(functionType);
540     parent.mapInstruction(&functionInstruction);
541     parent.addFunction(this);
542 
543     // OpFunctionParameter
544     Instruction* typeInst = parent.getInstruction(functionType);
545     int numParams = typeInst->getNumOperands() - 1;
546     for (int p = 0; p < numParams; ++p) {
547         Instruction* param = new Instruction(firstParamId + p, typeInst->getIdOperand(p + 1), OpFunctionParameter);
548         parent.mapInstruction(param);
549         parameterInstructions.push_back(param);
550     }
551 
552     // If importing/exporting, save the function name (without the mangled parameters) for the linkage decoration
553     if (linkType != LinkageTypeMax) {
554         exportName = name.substr(0, name.find_first_of('('));
555     }
556 }
557 
addLocalVariable(std::unique_ptr<Instruction> inst)558 __inline void Function::addLocalVariable(std::unique_ptr<Instruction> inst)
559 {
560     Instruction* raw_instruction = inst.get();
561     blocks[0]->addLocalVariable(std::move(inst));
562     parent.mapInstruction(raw_instruction);
563 }
564 
Block(Id id,Function & parent)565 __inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
566 {
567     instructions.push_back(std::unique_ptr<Instruction>(new Instruction(id, NoType, OpLabel)));
568     instructions.back()->setBlock(this);
569     parent.getParent().mapInstruction(instructions.back().get());
570 }
571 
addInstruction(std::unique_ptr<Instruction> inst)572 __inline void Block::addInstruction(std::unique_ptr<Instruction> inst)
573 {
574     Instruction* raw_instruction = inst.get();
575     instructions.push_back(std::move(inst));
576     raw_instruction->setBlock(this);
577     if (raw_instruction->getResultId())
578         parent.getParent().mapInstruction(raw_instruction);
579 }
580 
581 }  // end spv namespace
582 
583 #endif // spvIR_H
584