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
getNameString()192 const char *getNameString() const {
193 if (opCode == OpString) {
194 return (const char *)&operands[0];
195 } else {
196 assert(opCode == OpName);
197 return (const char *)&operands[1];
198 }
199 }
200
201 protected:
202 Instruction(const Instruction&);
203 Id resultId;
204 Id typeId;
205 Op opCode;
206 std::vector<Id> operands; // operands, both <id> and immediates (both are unsigned int)
207 std::vector<bool> idOperand; // true for operands that are <id>, false for immediates
208 Block* block;
209 };
210
211 //
212 // SPIR-V IR block.
213 //
214
215 struct DebugSourceLocation {
216 int line;
217 int column;
218 spv::Id fileId;
219 };
220
221 class Block {
222 public:
223 Block(Id id, Function& parent);
~Block()224 virtual ~Block()
225 {
226 }
227
getId()228 Id getId() { return instructions.front()->getResultId(); }
229
getParent()230 Function& getParent() const { return parent; }
231 // Returns true if the source location is actually updated.
232 // 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)233 bool updateDebugSourceLocation(int line, int column, spv::Id fileId) {
234 if (currentSourceLoc && currentSourceLoc->line == line && currentSourceLoc->column == column &&
235 currentSourceLoc->fileId == fileId) {
236 return false;
237 }
238
239 currentSourceLoc = DebugSourceLocation{line, column, fileId};
240 return true;
241 }
242 // Returns true if the scope is actually updated.
243 // Note we still need the builder to insert the debug scope instruction. This is just a tracker.
updateDebugScope(spv::Id scopeId)244 bool updateDebugScope(spv::Id scopeId) {
245 assert(scopeId);
246 if (currentDebugScope && *currentDebugScope == scopeId) {
247 return false;
248 }
249
250 currentDebugScope = scopeId;
251 return true;
252 }
253 void addInstruction(std::unique_ptr<Instruction> inst);
addPredecessor(Block * pred)254 void addPredecessor(Block* pred) { predecessors.push_back(pred); pred->successors.push_back(this);}
addLocalVariable(std::unique_ptr<Instruction> inst)255 void addLocalVariable(std::unique_ptr<Instruction> inst) { localVariables.push_back(std::move(inst)); }
getPredecessors()256 const std::vector<Block*>& getPredecessors() const { return predecessors; }
getSuccessors()257 const std::vector<Block*>& getSuccessors() const { return successors; }
getInstructions()258 std::vector<std::unique_ptr<Instruction> >& getInstructions() {
259 return instructions;
260 }
getLocalVariables()261 const std::vector<std::unique_ptr<Instruction> >& getLocalVariables() const { return localVariables; }
setUnreachable()262 void setUnreachable() { unreachable = true; }
isUnreachable()263 bool isUnreachable() const { return unreachable; }
264 // Returns the block's merge instruction, if one exists (otherwise null).
getMergeInstruction()265 const Instruction* getMergeInstruction() const {
266 if (instructions.size() < 2) return nullptr;
267 const Instruction* nextToLast = (instructions.cend() - 2)->get();
268 switch (nextToLast->getOpCode()) {
269 case OpSelectionMerge:
270 case OpLoopMerge:
271 return nextToLast;
272 default:
273 return nullptr;
274 }
275 return nullptr;
276 }
277
278 // Change this block into a canonical dead merge block. Delete instructions
279 // as necessary. A canonical dead merge block has only an OpLabel and an
280 // OpUnreachable.
rewriteAsCanonicalUnreachableMerge()281 void rewriteAsCanonicalUnreachableMerge() {
282 assert(localVariables.empty());
283 // Delete all instructions except for the label.
284 assert(instructions.size() > 0);
285 instructions.resize(1);
286 successors.clear();
287 addInstruction(std::unique_ptr<Instruction>(new Instruction(OpUnreachable)));
288 }
289 // Change this block into a canonical dead continue target branching to the
290 // given header ID. Delete instructions as necessary. A canonical dead continue
291 // target has only an OpLabel and an unconditional branch back to the corresponding
292 // header.
rewriteAsCanonicalUnreachableContinue(Block * header)293 void rewriteAsCanonicalUnreachableContinue(Block* header) {
294 assert(localVariables.empty());
295 // Delete all instructions except for the label.
296 assert(instructions.size() > 0);
297 instructions.resize(1);
298 successors.clear();
299 // Add OpBranch back to the header.
300 assert(header != nullptr);
301 Instruction* branch = new Instruction(OpBranch);
302 branch->addIdOperand(header->getId());
303 addInstruction(std::unique_ptr<Instruction>(branch));
304 successors.push_back(header);
305 }
306
isTerminated()307 bool isTerminated() const
308 {
309 switch (instructions.back()->getOpCode()) {
310 case OpBranch:
311 case OpBranchConditional:
312 case OpSwitch:
313 case OpKill:
314 case OpTerminateInvocation:
315 case OpReturn:
316 case OpReturnValue:
317 case OpUnreachable:
318 return true;
319 default:
320 return false;
321 }
322 }
323
dump(std::vector<unsigned int> & out)324 void dump(std::vector<unsigned int>& out) const
325 {
326 instructions[0]->dump(out);
327 for (int i = 0; i < (int)localVariables.size(); ++i)
328 localVariables[i]->dump(out);
329 for (int i = 1; i < (int)instructions.size(); ++i)
330 instructions[i]->dump(out);
331 }
332
333 protected:
334 Block(const Block&);
335 Block& operator=(Block&);
336
337 // To enforce keeping parent and ownership in sync:
338 friend Function;
339
340 std::vector<std::unique_ptr<Instruction> > instructions;
341 std::vector<Block*> predecessors, successors;
342 std::vector<std::unique_ptr<Instruction> > localVariables;
343 Function& parent;
344
345 // Track source location of the last source location marker instruction.
346 std::optional<DebugSourceLocation> currentSourceLoc;
347
348 // Track scope of the last debug scope instruction.
349 std::optional<spv::Id> currentDebugScope;
350
351 // track whether this block is known to be uncreachable (not necessarily
352 // true for all unreachable blocks, but should be set at least
353 // for the extraneous ones introduced by the builder).
354 bool unreachable;
355 };
356
357 // The different reasons for reaching a block in the inReadableOrder traversal.
358 enum ReachReason {
359 // Reachable from the entry block via transfers of control, i.e. branches.
360 ReachViaControlFlow = 0,
361 // A continue target that is not reachable via control flow.
362 ReachDeadContinue,
363 // A merge block that is not reachable via control flow.
364 ReachDeadMerge
365 };
366
367 // Traverses the control-flow graph rooted at root in an order suited for
368 // readable code generation. Invokes callback at every node in the traversal
369 // order. The callback arguments are:
370 // - the block,
371 // - the reason we reached the block,
372 // - if the reason was that block is an unreachable continue or unreachable merge block
373 // then the last parameter is the corresponding header block.
374 void inReadableOrder(Block* root, std::function<void(Block*, ReachReason, Block* header)> callback);
375
376 //
377 // SPIR-V IR Function.
378 //
379
380 class Function {
381 public:
382 Function(Id id, Id resultType, Id functionType, Id firstParam, LinkageType linkage, const std::string& name, Module& parent);
~Function()383 virtual ~Function()
384 {
385 for (int i = 0; i < (int)parameterInstructions.size(); ++i)
386 delete parameterInstructions[i];
387
388 for (int i = 0; i < (int)blocks.size(); ++i)
389 delete blocks[i];
390 }
getId()391 Id getId() const { return functionInstruction.getResultId(); }
getParamId(int p)392 Id getParamId(int p) const { return parameterInstructions[p]->getResultId(); }
getParamType(int p)393 Id getParamType(int p) const { return parameterInstructions[p]->getTypeId(); }
394
addBlock(Block * block)395 void addBlock(Block* block) { blocks.push_back(block); }
removeBlock(Block * block)396 void removeBlock(Block* block)
397 {
398 auto found = find(blocks.begin(), blocks.end(), block);
399 assert(found != blocks.end());
400 blocks.erase(found);
401 delete block;
402 }
403
getParent()404 Module& getParent() const { return parent; }
getEntryBlock()405 Block* getEntryBlock() const { return blocks.front(); }
getLastBlock()406 Block* getLastBlock() const { return blocks.back(); }
getBlocks()407 const std::vector<Block*>& getBlocks() const { return blocks; }
408 void addLocalVariable(std::unique_ptr<Instruction> inst);
getReturnType()409 Id getReturnType() const { return functionInstruction.getTypeId(); }
getFuncId()410 Id getFuncId() const { return functionInstruction.getResultId(); }
getFuncTypeId()411 Id getFuncTypeId() const { return functionInstruction.getIdOperand(1); }
setReturnPrecision(Decoration precision)412 void setReturnPrecision(Decoration precision)
413 {
414 if (precision == DecorationRelaxedPrecision)
415 reducedPrecisionReturn = true;
416 }
getReturnPrecision()417 Decoration getReturnPrecision() const
418 { return reducedPrecisionReturn ? DecorationRelaxedPrecision : NoPrecision; }
419
setDebugLineInfo(Id fileName,int line,int column)420 void setDebugLineInfo(Id fileName, int line, int column) {
421 lineInstruction = std::unique_ptr<Instruction>{new Instruction(OpLine)};
422 lineInstruction->reserveOperands(3);
423 lineInstruction->addIdOperand(fileName);
424 lineInstruction->addImmediateOperand(line);
425 lineInstruction->addImmediateOperand(column);
426 }
hasDebugLineInfo()427 bool hasDebugLineInfo() const { return lineInstruction != nullptr; }
428
setImplicitThis()429 void setImplicitThis() { implicitThis = true; }
hasImplicitThis()430 bool hasImplicitThis() const { return implicitThis; }
431
addParamPrecision(unsigned param,Decoration precision)432 void addParamPrecision(unsigned param, Decoration precision)
433 {
434 if (precision == DecorationRelaxedPrecision)
435 reducedPrecisionParams.insert(param);
436 }
getParamPrecision(unsigned param)437 Decoration getParamPrecision(unsigned param) const
438 {
439 return reducedPrecisionParams.find(param) != reducedPrecisionParams.end() ?
440 DecorationRelaxedPrecision : NoPrecision;
441 }
442
dump(std::vector<unsigned int> & out)443 void dump(std::vector<unsigned int>& out) const
444 {
445 // OpLine
446 if (lineInstruction != nullptr) {
447 lineInstruction->dump(out);
448 }
449
450 // OpFunction
451 functionInstruction.dump(out);
452
453 // OpFunctionParameter
454 for (int p = 0; p < (int)parameterInstructions.size(); ++p)
455 parameterInstructions[p]->dump(out);
456
457 // Blocks
458 inReadableOrder(blocks[0], [&out](const Block* b, ReachReason, Block*) { b->dump(out); });
459 Instruction end(0, 0, OpFunctionEnd);
460 end.dump(out);
461 }
462
getLinkType()463 LinkageType getLinkType() const { return linkType; }
getExportName()464 const char* getExportName() const { return exportName.c_str(); }
465
466 protected:
467 Function(const Function&);
468 Function& operator=(Function&);
469
470 Module& parent;
471 std::unique_ptr<Instruction> lineInstruction;
472 Instruction functionInstruction;
473 std::vector<Instruction*> parameterInstructions;
474 std::vector<Block*> blocks;
475 bool implicitThis; // true if this is a member function expecting to be passed a 'this' as the first argument
476 bool reducedPrecisionReturn;
477 std::set<int> reducedPrecisionParams; // list of parameter indexes that need a relaxed precision arg
478 LinkageType linkType;
479 std::string exportName;
480 };
481
482 //
483 // SPIR-V IR Module.
484 //
485
486 class Module {
487 public:
Module()488 Module() {}
~Module()489 virtual ~Module()
490 {
491 // TODO delete things
492 }
493
addFunction(Function * fun)494 void addFunction(Function *fun) { functions.push_back(fun); }
495
mapInstruction(Instruction * instruction)496 void mapInstruction(Instruction *instruction)
497 {
498 spv::Id resultId = instruction->getResultId();
499 // map the instruction's result id
500 if (resultId >= idToInstruction.size())
501 idToInstruction.resize(resultId + 16);
502 idToInstruction[resultId] = instruction;
503 }
504
getInstruction(Id id)505 Instruction* getInstruction(Id id) const { return idToInstruction[id]; }
getFunctions()506 const std::vector<Function*>& getFunctions() const { return functions; }
getTypeId(Id resultId)507 spv::Id getTypeId(Id resultId) const {
508 return idToInstruction[resultId] == nullptr ? NoType : idToInstruction[resultId]->getTypeId();
509 }
getStorageClass(Id typeId)510 StorageClass getStorageClass(Id typeId) const
511 {
512 assert(idToInstruction[typeId]->getOpCode() == spv::OpTypePointer);
513 return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0);
514 }
515
dump(std::vector<unsigned int> & out)516 void dump(std::vector<unsigned int>& out) const
517 {
518 for (int f = 0; f < (int)functions.size(); ++f)
519 functions[f]->dump(out);
520 }
521
522 protected:
523 Module(const Module&);
524 std::vector<Function*> functions;
525
526 // map from result id to instruction having that result id
527 std::vector<Instruction*> idToInstruction;
528
529 // map from a result id to its type id
530 };
531
532 //
533 // Implementation (it's here due to circular type definitions).
534 //
535
536 // Add both
537 // - the OpFunction instruction
538 // - all the OpFunctionParameter instructions
Function(Id id,Id resultType,Id functionType,Id firstParamId,LinkageType linkage,const std::string & name,Module & parent)539 __inline Function::Function(Id id, Id resultType, Id functionType, Id firstParamId, LinkageType linkage, const std::string& name, Module& parent)
540 : parent(parent), lineInstruction(nullptr),
541 functionInstruction(id, resultType, OpFunction), implicitThis(false),
542 reducedPrecisionReturn(false),
543 linkType(linkage)
544 {
545 // OpFunction
546 functionInstruction.reserveOperands(2);
547 functionInstruction.addImmediateOperand(FunctionControlMaskNone);
548 functionInstruction.addIdOperand(functionType);
549 parent.mapInstruction(&functionInstruction);
550 parent.addFunction(this);
551
552 // OpFunctionParameter
553 Instruction* typeInst = parent.getInstruction(functionType);
554 int numParams = typeInst->getNumOperands() - 1;
555 for (int p = 0; p < numParams; ++p) {
556 Instruction* param = new Instruction(firstParamId + p, typeInst->getIdOperand(p + 1), OpFunctionParameter);
557 parent.mapInstruction(param);
558 parameterInstructions.push_back(param);
559 }
560
561 // If importing/exporting, save the function name (without the mangled parameters) for the linkage decoration
562 if (linkType != LinkageTypeMax) {
563 exportName = name.substr(0, name.find_first_of('('));
564 }
565 }
566
addLocalVariable(std::unique_ptr<Instruction> inst)567 __inline void Function::addLocalVariable(std::unique_ptr<Instruction> inst)
568 {
569 Instruction* raw_instruction = inst.get();
570 blocks[0]->addLocalVariable(std::move(inst));
571 parent.mapInstruction(raw_instruction);
572 }
573
Block(Id id,Function & parent)574 __inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
575 {
576 instructions.push_back(std::unique_ptr<Instruction>(new Instruction(id, NoType, OpLabel)));
577 instructions.back()->setBlock(this);
578 parent.getParent().mapInstruction(instructions.back().get());
579 }
580
addInstruction(std::unique_ptr<Instruction> inst)581 __inline void Block::addInstruction(std::unique_ptr<Instruction> inst)
582 {
583 Instruction* raw_instruction = inst.get();
584 instructions.push_back(std::move(inst));
585 raw_instruction->setBlock(this);
586 if (raw_instruction->getResultId())
587 parent.getParent().mapInstruction(raw_instruction);
588 }
589
590 } // end spv namespace
591
592 #endif // spvIR_H
593