Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/thirdparty/glslang/SPIRV/spvIR.h
22071 views
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.hpp11"
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 = Decoration::Max;
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)(MemorySemanticsMask::UniformMemory |
81
MemorySemanticsMask::WorkgroupMemory |
82
MemorySemanticsMask::AtomicCounterMemory |
83
MemorySemanticsMask::ImageMemory);
84
85
struct IdImmediate {
86
bool isId; // true if word is an Id, false if word is an immediate
87
unsigned word;
88
IdImmediate(bool i, unsigned w) : isId(i), word(w) {}
89
IdImmediate(bool i, spv::MemoryAccessMask w) : isId(i), word((unsigned)w) {}
90
IdImmediate(bool i, spv::TensorAddressingOperandsMask w) : isId(i), word((unsigned)w) {}
91
IdImmediate(bool i, spv::ImageOperandsMask w) : isId(i), word((unsigned)w) {}
92
IdImmediate(bool i, spv::CooperativeMatrixOperandsMask w) : isId(i), word((unsigned)w) {}
93
};
94
95
//
96
// SPIR-V IR instruction.
97
//
98
99
class Instruction {
100
public:
101
Instruction(Id resultId, Id typeId, Op opCode) : resultId(resultId), typeId(typeId), opCode(opCode), block(nullptr) { }
102
explicit Instruction(Op opCode) : resultId(NoResult), typeId(NoType), opCode(opCode), block(nullptr) { }
103
virtual ~Instruction() {}
104
void reserveOperands(size_t count) {
105
operands.reserve(count);
106
idOperand.reserve(count);
107
}
108
void addIdOperand(Id id) {
109
// ids can't be 0
110
assert(id);
111
operands.push_back(id);
112
idOperand.push_back(true);
113
}
114
// This method is potentially dangerous as it can break assumptions
115
// about SSA and lack of forward references.
116
void setIdOperand(unsigned idx, Id id) {
117
assert(id);
118
assert(idOperand[idx]);
119
operands[idx] = id;
120
}
121
122
void addImmediateOperand(unsigned int immediate) {
123
operands.push_back(immediate);
124
idOperand.push_back(false);
125
}
126
127
void addImmediateOperand(spv::StorageClass immediate) {
128
addImmediateOperand((unsigned)immediate);
129
}
130
131
void addImmediateOperand(spv::ExecutionMode immediate) {
132
addImmediateOperand((unsigned)immediate);
133
}
134
135
void addImmediateOperand(spv::ExecutionModel immediate) {
136
addImmediateOperand((unsigned)immediate);
137
}
138
139
void addImmediateOperand(spv::Decoration immediate) {
140
addImmediateOperand((unsigned)immediate);
141
}
142
143
void addImmediateOperand(spv::LinkageType immediate) {
144
addImmediateOperand((unsigned)immediate);
145
}
146
147
void addImmediateOperand(spv::MemoryAccessMask immediate) {
148
addImmediateOperand((unsigned)immediate);
149
}
150
151
void addImmediateOperand(spv::Capability immediate) {
152
addImmediateOperand((unsigned)immediate);
153
}
154
155
void addImmediateOperand(spv::AddressingModel immediate) {
156
addImmediateOperand((unsigned)immediate);
157
}
158
159
void addImmediateOperand(spv::MemoryModel immediate) {
160
addImmediateOperand((unsigned)immediate);
161
}
162
163
void addImmediateOperand(spv::FPEncoding immediate) {
164
addImmediateOperand((unsigned)immediate);
165
}
166
167
void addImmediateOperand(spv::SourceLanguage immediate) {
168
addImmediateOperand((unsigned)immediate);
169
}
170
171
void addImmediateOperand(spv::Dim immediate) {
172
addImmediateOperand((unsigned)immediate);
173
}
174
175
void addImmediateOperand(spv::FunctionControlMask immediate){
176
addImmediateOperand((unsigned)immediate);
177
}
178
179
void addImmediateOperand(spv::SelectionControlMask immediate) {
180
addImmediateOperand((unsigned)immediate);
181
}
182
183
void addImmediateOperand(spv::LoopControlMask immediate) {
184
addImmediateOperand((unsigned)immediate);
185
}
186
187
void setImmediateOperand(unsigned idx, unsigned int immediate) {
188
assert(!idOperand[idx]);
189
operands[idx] = immediate;
190
}
191
192
void addStringOperand(const char* str)
193
{
194
unsigned int word = 0;
195
unsigned int shiftAmount = 0;
196
unsigned char c;
197
198
do {
199
c = *(str++);
200
word |= ((unsigned int)c) << shiftAmount;
201
shiftAmount += 8;
202
if (shiftAmount == 32) {
203
addImmediateOperand(word);
204
word = 0;
205
shiftAmount = 0;
206
}
207
} while (c != 0);
208
209
// deal with partial last word
210
if (shiftAmount > 0) {
211
addImmediateOperand(word);
212
}
213
}
214
bool isIdOperand(int op) const { return idOperand[op]; }
215
void setBlock(Block* b) { block = b; }
216
Block* getBlock() const { return block; }
217
Op getOpCode() const { return opCode; }
218
int getNumOperands() const
219
{
220
assert(operands.size() == idOperand.size());
221
return (int)operands.size();
222
}
223
Id getResultId() const { return resultId; }
224
Id getTypeId() const { return typeId; }
225
Id getIdOperand(int op) const {
226
assert(idOperand[op]);
227
return operands[op];
228
}
229
unsigned int getImmediateOperand(int op) const {
230
assert(!idOperand[op]);
231
return operands[op];
232
}
233
234
// Write out the binary form.
235
void dump(std::vector<unsigned int>& out) const
236
{
237
// Compute the wordCount
238
unsigned int wordCount = 1;
239
if (typeId)
240
++wordCount;
241
if (resultId)
242
++wordCount;
243
wordCount += (unsigned int)operands.size();
244
245
// Write out the beginning of the instruction
246
out.push_back(((wordCount) << WordCountShift) | (unsigned)opCode);
247
if (typeId)
248
out.push_back(typeId);
249
if (resultId)
250
out.push_back(resultId);
251
252
// Write out the operands
253
for (int op = 0; op < (int)operands.size(); ++op)
254
out.push_back(operands[op]);
255
}
256
257
const char *getNameString() const {
258
if (opCode == Op::OpString) {
259
return (const char *)&operands[0];
260
} else {
261
assert(opCode == Op::OpName);
262
return (const char *)&operands[1];
263
}
264
}
265
266
protected:
267
Instruction(const Instruction&);
268
Id resultId;
269
Id typeId;
270
Op opCode;
271
std::vector<Id> operands; // operands, both <id> and immediates (both are unsigned int)
272
std::vector<bool> idOperand; // true for operands that are <id>, false for immediates
273
Block* block;
274
};
275
276
//
277
// SPIR-V IR block.
278
//
279
280
struct DebugSourceLocation {
281
int line;
282
int column;
283
spv::Id fileId;
284
};
285
286
class Block {
287
public:
288
Block(Id id, Function& parent);
289
virtual ~Block()
290
{
291
}
292
293
Id getId() { return instructions.front()->getResultId(); }
294
295
Function& getParent() const { return parent; }
296
// Returns true if the source location is actually updated.
297
// Note we still need the builder to insert the line marker instruction. This is just a tracker.
298
bool updateDebugSourceLocation(int line, int column, spv::Id fileId) {
299
if (currentSourceLoc && currentSourceLoc->line == line && currentSourceLoc->column == column &&
300
currentSourceLoc->fileId == fileId) {
301
return false;
302
}
303
304
currentSourceLoc = DebugSourceLocation{line, column, fileId};
305
return true;
306
}
307
// Returns true if the scope is actually updated.
308
// Note we still need the builder to insert the debug scope instruction. This is just a tracker.
309
bool updateDebugScope(spv::Id scopeId) {
310
assert(scopeId);
311
if (currentDebugScope && *currentDebugScope == scopeId) {
312
return false;
313
}
314
315
currentDebugScope = scopeId;
316
return true;
317
}
318
void addInstruction(std::unique_ptr<Instruction> inst);
319
void addPredecessor(Block* pred) { predecessors.push_back(pred); pred->successors.push_back(this);}
320
void addLocalVariable(std::unique_ptr<Instruction> inst) { localVariables.push_back(std::move(inst)); }
321
const std::vector<Block*>& getPredecessors() const { return predecessors; }
322
const std::vector<Block*>& getSuccessors() const { return successors; }
323
std::vector<std::unique_ptr<Instruction> >& getInstructions() {
324
return instructions;
325
}
326
const std::vector<std::unique_ptr<Instruction> >& getLocalVariables() const { return localVariables; }
327
void setUnreachable() { unreachable = true; }
328
bool isUnreachable() const { return unreachable; }
329
// Returns the block's merge instruction, if one exists (otherwise null).
330
const Instruction* getMergeInstruction() const {
331
if (instructions.size() < 2) return nullptr;
332
const Instruction* nextToLast = (instructions.cend() - 2)->get();
333
switch (nextToLast->getOpCode()) {
334
case Op::OpSelectionMerge:
335
case Op::OpLoopMerge:
336
return nextToLast;
337
default:
338
return nullptr;
339
}
340
return nullptr;
341
}
342
343
// Change this block into a canonical dead merge block. Delete instructions
344
// as necessary. A canonical dead merge block has only an OpLabel and an
345
// OpUnreachable.
346
void rewriteAsCanonicalUnreachableMerge() {
347
assert(localVariables.empty());
348
// Delete all instructions except for the label.
349
assert(instructions.size() > 0);
350
instructions.resize(1);
351
successors.clear();
352
addInstruction(std::unique_ptr<Instruction>(new Instruction(Op::OpUnreachable)));
353
}
354
// Change this block into a canonical dead continue target branching to the
355
// given header ID. Delete instructions as necessary. A canonical dead continue
356
// target has only an OpLabel and an unconditional branch back to the corresponding
357
// header.
358
void rewriteAsCanonicalUnreachableContinue(Block* header) {
359
assert(localVariables.empty());
360
// Delete all instructions except for the label.
361
assert(instructions.size() > 0);
362
instructions.resize(1);
363
successors.clear();
364
// Add OpBranch back to the header.
365
assert(header != nullptr);
366
Instruction* branch = new Instruction(Op::OpBranch);
367
branch->addIdOperand(header->getId());
368
addInstruction(std::unique_ptr<Instruction>(branch));
369
successors.push_back(header);
370
}
371
372
bool isTerminated() const
373
{
374
switch (instructions.back()->getOpCode()) {
375
case Op::OpBranch:
376
case Op::OpBranchConditional:
377
case Op::OpSwitch:
378
case Op::OpKill:
379
case Op::OpTerminateInvocation:
380
case Op::OpReturn:
381
case Op::OpReturnValue:
382
case Op::OpUnreachable:
383
return true;
384
default:
385
return false;
386
}
387
}
388
389
void dump(std::vector<unsigned int>& out) const
390
{
391
instructions[0]->dump(out);
392
for (int i = 0; i < (int)localVariables.size(); ++i)
393
localVariables[i]->dump(out);
394
for (int i = 1; i < (int)instructions.size(); ++i)
395
instructions[i]->dump(out);
396
}
397
398
protected:
399
Block(const Block&);
400
Block& operator=(Block&);
401
402
// To enforce keeping parent and ownership in sync:
403
friend Function;
404
405
std::vector<std::unique_ptr<Instruction> > instructions;
406
std::vector<Block*> predecessors, successors;
407
std::vector<std::unique_ptr<Instruction> > localVariables;
408
Function& parent;
409
410
// Track source location of the last source location marker instruction.
411
std::optional<DebugSourceLocation> currentSourceLoc;
412
413
// Track scope of the last debug scope instruction.
414
std::optional<spv::Id> currentDebugScope;
415
416
// track whether this block is known to be uncreachable (not necessarily
417
// true for all unreachable blocks, but should be set at least
418
// for the extraneous ones introduced by the builder).
419
bool unreachable;
420
};
421
422
// The different reasons for reaching a block in the inReadableOrder traversal.
423
enum ReachReason {
424
// Reachable from the entry block via transfers of control, i.e. branches.
425
ReachViaControlFlow = 0,
426
// A continue target that is not reachable via control flow.
427
ReachDeadContinue,
428
// A merge block that is not reachable via control flow.
429
ReachDeadMerge
430
};
431
432
// Traverses the control-flow graph rooted at root in an order suited for
433
// readable code generation. Invokes callback at every node in the traversal
434
// order. The callback arguments are:
435
// - the block,
436
// - the reason we reached the block,
437
// - if the reason was that block is an unreachable continue or unreachable merge block
438
// then the last parameter is the corresponding header block.
439
void inReadableOrder(Block* root, std::function<void(Block*, ReachReason, Block* header)> callback);
440
441
//
442
// SPIR-V IR Function.
443
//
444
445
class Function {
446
public:
447
Function(Id id, Id resultType, Id functionType, Id firstParam, LinkageType linkage, const std::string& name, Module& parent);
448
virtual ~Function()
449
{
450
for (int i = 0; i < (int)parameterInstructions.size(); ++i)
451
delete parameterInstructions[i];
452
453
for (int i = 0; i < (int)blocks.size(); ++i)
454
delete blocks[i];
455
}
456
Id getId() const { return functionInstruction.getResultId(); }
457
Id getParamId(int p) const { return parameterInstructions[p]->getResultId(); }
458
Id getParamType(int p) const { return parameterInstructions[p]->getTypeId(); }
459
460
void addBlock(Block* block) { blocks.push_back(block); }
461
void removeBlock(Block* block)
462
{
463
auto found = find(blocks.begin(), blocks.end(), block);
464
assert(found != blocks.end());
465
blocks.erase(found);
466
delete block;
467
}
468
469
Module& getParent() const { return parent; }
470
Block* getEntryBlock() const { return blocks.front(); }
471
Block* getLastBlock() const { return blocks.back(); }
472
const std::vector<Block*>& getBlocks() const { return blocks; }
473
void addLocalVariable(std::unique_ptr<Instruction> inst);
474
Id getReturnType() const { return functionInstruction.getTypeId(); }
475
Id getFuncId() const { return functionInstruction.getResultId(); }
476
Id getFuncTypeId() const { return functionInstruction.getIdOperand(1); }
477
void setReturnPrecision(Decoration precision)
478
{
479
if (precision == Decoration::RelaxedPrecision)
480
reducedPrecisionReturn = true;
481
}
482
Decoration getReturnPrecision() const
483
{ return reducedPrecisionReturn ? Decoration::RelaxedPrecision : NoPrecision; }
484
485
void setDebugLineInfo(Id fileName, int line, int column) {
486
lineInstruction = std::unique_ptr<Instruction>{new Instruction(Op::OpLine)};
487
lineInstruction->reserveOperands(3);
488
lineInstruction->addIdOperand(fileName);
489
lineInstruction->addImmediateOperand(line);
490
lineInstruction->addImmediateOperand(column);
491
}
492
bool hasDebugLineInfo() const { return lineInstruction != nullptr; }
493
494
void setImplicitThis() { implicitThis = true; }
495
bool hasImplicitThis() const { return implicitThis; }
496
497
void addParamPrecision(unsigned param, Decoration precision)
498
{
499
if (precision == Decoration::RelaxedPrecision)
500
reducedPrecisionParams.insert(param);
501
}
502
Decoration getParamPrecision(unsigned param) const
503
{
504
return reducedPrecisionParams.find(param) != reducedPrecisionParams.end() ?
505
Decoration::RelaxedPrecision : NoPrecision;
506
}
507
508
void dump(std::vector<unsigned int>& out) const
509
{
510
// OpLine
511
if (lineInstruction != nullptr) {
512
lineInstruction->dump(out);
513
}
514
515
// OpFunction
516
functionInstruction.dump(out);
517
518
// OpFunctionParameter
519
for (int p = 0; p < (int)parameterInstructions.size(); ++p)
520
parameterInstructions[p]->dump(out);
521
522
// Blocks
523
inReadableOrder(blocks[0], [&out](const Block* b, ReachReason, Block*) { b->dump(out); });
524
Instruction end(0, 0, Op::OpFunctionEnd);
525
end.dump(out);
526
}
527
528
LinkageType getLinkType() const { return linkType; }
529
const char* getExportName() const { return exportName.c_str(); }
530
531
protected:
532
Function(const Function&);
533
Function& operator=(Function&);
534
535
Module& parent;
536
std::unique_ptr<Instruction> lineInstruction;
537
Instruction functionInstruction;
538
std::vector<Instruction*> parameterInstructions;
539
std::vector<Block*> blocks;
540
bool implicitThis; // true if this is a member function expecting to be passed a 'this' as the first argument
541
bool reducedPrecisionReturn;
542
std::set<int> reducedPrecisionParams; // list of parameter indexes that need a relaxed precision arg
543
LinkageType linkType;
544
std::string exportName;
545
};
546
547
//
548
// SPIR-V IR Module.
549
//
550
551
class Module {
552
public:
553
Module() {}
554
virtual ~Module()
555
{
556
// TODO delete things
557
}
558
559
void addFunction(Function *fun) { functions.push_back(fun); }
560
561
void mapInstruction(Instruction *instruction)
562
{
563
spv::Id resultId = instruction->getResultId();
564
// map the instruction's result id
565
if (resultId >= idToInstruction.size())
566
idToInstruction.resize(resultId + 16);
567
idToInstruction[resultId] = instruction;
568
}
569
570
Instruction* getInstruction(Id id) const { return idToInstruction[id]; }
571
const std::vector<Function*>& getFunctions() const { return functions; }
572
spv::Id getTypeId(Id resultId) const {
573
return idToInstruction[resultId] == nullptr ? NoType : idToInstruction[resultId]->getTypeId();
574
}
575
StorageClass getStorageClass(Id typeId) const
576
{
577
assert(idToInstruction[typeId]->getOpCode() == spv::Op::OpTypePointer);
578
return (StorageClass)idToInstruction[typeId]->getImmediateOperand(0);
579
}
580
581
void dump(std::vector<unsigned int>& out) const
582
{
583
for (int f = 0; f < (int)functions.size(); ++f)
584
functions[f]->dump(out);
585
}
586
587
protected:
588
Module(const Module&);
589
std::vector<Function*> functions;
590
591
// map from result id to instruction having that result id
592
std::vector<Instruction*> idToInstruction;
593
594
// map from a result id to its type id
595
};
596
597
//
598
// Implementation (it's here due to circular type definitions).
599
//
600
601
// Add both
602
// - the OpFunction instruction
603
// - all the OpFunctionParameter instructions
604
__inline Function::Function(Id id, Id resultType, Id functionType, Id firstParamId, LinkageType linkage, const std::string& name, Module& parent)
605
: parent(parent), lineInstruction(nullptr),
606
functionInstruction(id, resultType, Op::OpFunction), implicitThis(false),
607
reducedPrecisionReturn(false),
608
linkType(linkage)
609
{
610
// OpFunction
611
functionInstruction.reserveOperands(2);
612
functionInstruction.addImmediateOperand(FunctionControlMask::MaskNone);
613
functionInstruction.addIdOperand(functionType);
614
parent.mapInstruction(&functionInstruction);
615
parent.addFunction(this);
616
617
// OpFunctionParameter
618
Instruction* typeInst = parent.getInstruction(functionType);
619
int numParams = typeInst->getNumOperands() - 1;
620
for (int p = 0; p < numParams; ++p) {
621
Instruction* param = new Instruction(firstParamId + p, typeInst->getIdOperand(p + 1), Op::OpFunctionParameter);
622
parent.mapInstruction(param);
623
parameterInstructions.push_back(param);
624
}
625
626
// If importing/exporting, save the function name (without the mangled parameters) for the linkage decoration
627
if (linkType != LinkageType::Max) {
628
exportName = name.substr(0, name.find_first_of('('));
629
}
630
}
631
632
__inline void Function::addLocalVariable(std::unique_ptr<Instruction> inst)
633
{
634
Instruction* raw_instruction = inst.get();
635
blocks[0]->addLocalVariable(std::move(inst));
636
parent.mapInstruction(raw_instruction);
637
}
638
639
__inline Block::Block(Id id, Function& parent) : parent(parent), unreachable(false)
640
{
641
instructions.push_back(std::unique_ptr<Instruction>(new Instruction(id, NoType, Op::OpLabel)));
642
instructions.back()->setBlock(this);
643
parent.getParent().mapInstruction(instructions.back().get());
644
}
645
646
__inline void Block::addInstruction(std::unique_ptr<Instruction> inst)
647
{
648
Instruction* raw_instruction = inst.get();
649
instructions.push_back(std::move(inst));
650
raw_instruction->setBlock(this);
651
if (raw_instruction->getResultId())
652
parent.getParent().mapInstruction(raw_instruction);
653
}
654
655
} // end spv namespace
656
657
#endif // spvIR_H
658
659