blob: 5ecb6ab9684c98aaf2770db4d3952b01cb8137c0 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
LoopDawg592860c2016-06-09 08:57:35 -06002//Copyright (C) 2014-2016 LunarG, Inc.
John Kessenich6c292d32016-02-15 20:58:50 -07003//Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
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//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060050}
John Kessenich140f3df2015-06-26 16:58:36 -060051
52// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020053#include "../glslang/MachineIndependent/localintermediate.h"
54#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060055#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050056#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060057
John Kessenich140f3df2015-06-26 16:58:36 -060058#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040060#include <list>
61#include <map>
62#include <stack>
63#include <string>
64#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060065
66namespace {
67
John Kessenich55e7d112015-11-15 21:33:39 -070068// For low-order part of the generator's magic number. Bump up
69// when there is a change in the style (e.g., if SSA form changes,
70// or a different instruction sequence to do something gets used).
71const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060072
qining4c912612016-04-01 10:35:16 -040073namespace {
74class SpecConstantOpModeGuard {
75public:
76 SpecConstantOpModeGuard(spv::Builder* builder)
77 : builder_(builder) {
78 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040079 }
80 ~SpecConstantOpModeGuard() {
81 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
82 : builder_->setToNormalCodeGenMode();
83 }
qining40887662016-04-03 22:20:42 -040084 void turnOnSpecConstantOpMode() {
85 builder_->setToSpecConstCodeGenMode();
86 }
qining4c912612016-04-01 10:35:16 -040087
88private:
89 spv::Builder* builder_;
90 bool previous_flag_;
91};
92}
93
John Kessenich140f3df2015-06-26 16:58:36 -060094//
95// The main holder of information for translating glslang to SPIR-V.
96//
97// Derives from the AST walking base class.
98//
99class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
100public:
Lei Zhang17535f72016-05-04 15:55:59 -0400101 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenich140f3df2015-06-26 16:58:36 -0600102 virtual ~TGlslangToSpvTraverser();
103
104 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
105 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
106 void visitConstantUnion(glslang::TIntermConstantUnion*);
107 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
108 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
109 void visitSymbol(glslang::TIntermSymbol* symbol);
110 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
111 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
112 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
113
John Kessenich7ba63412015-12-20 17:37:07 -0700114 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600115
116protected:
Rex Xubbceed72016-05-21 09:40:44 +0800117 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100118 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700119 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600120 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
121 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600122 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
123 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
124 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600125 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700126 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6090df02016-06-30 21:18:02 -0600127 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
128 glslang::TLayoutPacking, const glslang::TQualifier&);
129 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
130 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700131 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700132 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800133 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600134 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700135 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700136 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
137 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
138 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100139 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600140
John Kessenich6fccb3c2016-09-19 16:01:41 -0600141 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600142 void makeFunctions(const glslang::TIntermSequence&);
143 void makeGlobalInitializers(const glslang::TIntermSequence&);
144 void visitFunctions(const glslang::TIntermSequence&);
145 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800146 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600147 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
148 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600149 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
150
qining25262b32016-05-06 17:25:16 -0400151 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
152 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
153 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800154 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800155 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600156 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800157 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800158 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xub7072052016-09-26 15:53:40 +0800159 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600160 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800161 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600162 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
163 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700164 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600165 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700166 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400167 spv::Id createSpvConstant(const glslang::TIntermTyped&);
168 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600169 bool isTrivialLeaf(const glslang::TIntermTyped* node);
170 bool isTrivial(const glslang::TIntermTyped* node);
171 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800172 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600173
174 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600175 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700176 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600177 int sequenceDepth;
178
Lei Zhang17535f72016-05-04 15:55:59 -0400179 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400180
John Kessenich140f3df2015-06-26 16:58:36 -0600181 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
182 spv::Builder builder;
183 bool inMain;
184 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700185 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700186 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600187 const glslang::TIntermediate* glslangIntermediate;
188 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800189 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600190
John Kessenich2f273362015-07-18 22:34:27 -0600191 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600192 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600193 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700194 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600195 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600196 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600197};
198
199//
200// Helper functions for translating glslang representations to SPIR-V enumerants.
201//
202
203// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700204spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600205{
John Kessenich66e2faf2016-03-12 18:34:36 -0700206 switch (source) {
207 case glslang::EShSourceGlsl:
208 switch (profile) {
209 case ENoProfile:
210 case ECoreProfile:
211 case ECompatibilityProfile:
212 return spv::SourceLanguageGLSL;
213 case EEsProfile:
214 return spv::SourceLanguageESSL;
215 default:
216 return spv::SourceLanguageUnknown;
217 }
218 case glslang::EShSourceHlsl:
Dan Baker55d5f2d2016-08-15 16:05:45 -0400219 //Use SourceLanguageUnknown instead of SourceLanguageHLSL for now, until Vulkan knows what HLSL is
220 return spv::SourceLanguageUnknown;
John Kessenich140f3df2015-06-26 16:58:36 -0600221 default:
222 return spv::SourceLanguageUnknown;
223 }
224}
225
226// Translate glslang language (stage) to SPIR-V execution model.
227spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
228{
229 switch (stage) {
230 case EShLangVertex: return spv::ExecutionModelVertex;
231 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
232 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
233 case EShLangGeometry: return spv::ExecutionModelGeometry;
234 case EShLangFragment: return spv::ExecutionModelFragment;
235 case EShLangCompute: return spv::ExecutionModelGLCompute;
236 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700237 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600238 return spv::ExecutionModelFragment;
239 }
240}
241
242// Translate glslang type to SPIR-V storage class.
243spv::StorageClass TranslateStorageClass(const glslang::TType& type)
244{
245 if (type.getQualifier().isPipeInput())
246 return spv::StorageClassInput;
247 else if (type.getQualifier().isPipeOutput())
248 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700249 else if (type.getBasicType() == glslang::EbtSampler)
250 return spv::StorageClassUniformConstant;
251 else if (type.getBasicType() == glslang::EbtAtomicUint)
252 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600253 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700254 if (type.getQualifier().layoutPushConstant)
255 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600256 if (type.getBasicType() == glslang::EbtBlock)
257 return spv::StorageClassUniform;
258 else
259 return spv::StorageClassUniformConstant;
John Kessenich5aa59e22016-06-17 15:50:47 -0600260 // TODO: how are we distinguishing between default and non-default non-writable uniforms? Do default uniforms even exist?
John Kessenich140f3df2015-06-26 16:58:36 -0600261 } else {
262 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700263 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
264 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600265 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
266 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400267 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700268 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600269 return spv::StorageClassFunction;
270 }
271 }
272}
273
274// Translate glslang sampler type to SPIR-V dimensionality.
275spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
276{
277 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700278 case glslang::Esd1D: return spv::Dim1D;
279 case glslang::Esd2D: return spv::Dim2D;
280 case glslang::Esd3D: return spv::Dim3D;
281 case glslang::EsdCube: return spv::DimCube;
282 case glslang::EsdRect: return spv::DimRect;
283 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700284 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600285 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700286 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600287 return spv::Dim2D;
288 }
289}
290
John Kessenichf6640762016-08-01 19:44:00 -0600291// Translate glslang precision to SPIR-V precision decorations.
292spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600293{
John Kessenichf6640762016-08-01 19:44:00 -0600294 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700295 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600296 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600297 default:
298 return spv::NoPrecision;
299 }
300}
301
John Kessenichf6640762016-08-01 19:44:00 -0600302// Translate glslang type to SPIR-V precision decorations.
303spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
304{
305 return TranslatePrecisionDecoration(type.getQualifier().precision);
306}
307
John Kessenich140f3df2015-06-26 16:58:36 -0600308// Translate glslang type to SPIR-V block decorations.
309spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
310{
311 if (type.getBasicType() == glslang::EbtBlock) {
312 switch (type.getQualifier().storage) {
313 case glslang::EvqUniform: return spv::DecorationBlock;
314 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
315 case glslang::EvqVaryingIn: return spv::DecorationBlock;
316 case glslang::EvqVaryingOut: return spv::DecorationBlock;
317 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700318 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600319 break;
320 }
321 }
322
John Kessenich4016e382016-07-15 11:53:56 -0600323 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600324}
325
Rex Xu1da878f2016-02-21 20:59:01 +0800326// Translate glslang type to SPIR-V memory decorations.
327void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
328{
329 if (qualifier.coherent)
330 memory.push_back(spv::DecorationCoherent);
331 if (qualifier.volatil)
332 memory.push_back(spv::DecorationVolatile);
333 if (qualifier.restrict)
334 memory.push_back(spv::DecorationRestrict);
335 if (qualifier.readonly)
336 memory.push_back(spv::DecorationNonWritable);
337 if (qualifier.writeonly)
338 memory.push_back(spv::DecorationNonReadable);
339}
340
John Kessenich140f3df2015-06-26 16:58:36 -0600341// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700342spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600343{
344 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700345 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600346 case glslang::ElmRowMajor:
347 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700348 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600349 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700350 default:
351 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600352 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600353 }
354 } else {
355 switch (type.getBasicType()) {
356 default:
John Kessenich4016e382016-07-15 11:53:56 -0600357 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600358 break;
359 case glslang::EbtBlock:
360 switch (type.getQualifier().storage) {
361 case glslang::EvqUniform:
362 case glslang::EvqBuffer:
363 switch (type.getQualifier().layoutPacking) {
364 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600365 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
366 default:
John Kessenich4016e382016-07-15 11:53:56 -0600367 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600368 }
369 case glslang::EvqVaryingIn:
370 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700371 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600372 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600373 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700374 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600375 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600376 }
377 }
378 }
379}
380
381// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600382// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700383// should be applied.
Rex Xubbceed72016-05-21 09:40:44 +0800384spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600385{
Rex Xubbceed72016-05-21 09:40:44 +0800386 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700387 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600388 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800389 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700390 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700391 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600392 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800393#ifdef AMD_EXTENSIONS
394 else if (qualifier.explicitInterp)
395 return spv::DecorationExplicitInterpAMD;
396#endif
Rex Xubbceed72016-05-21 09:40:44 +0800397 else
John Kessenich4016e382016-07-15 11:53:56 -0600398 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800399}
400
401// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600402// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800403// should be applied.
404spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
405{
406 if (qualifier.patch)
407 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700408 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600409 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700410 else if (qualifier.sample) {
411 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600412 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700413 } else
John Kessenich4016e382016-07-15 11:53:56 -0600414 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600415}
416
John Kessenich92187592016-02-01 13:45:25 -0700417// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700418spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600419{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700420 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600421 return spv::DecorationInvariant;
422 else
John Kessenich4016e382016-07-15 11:53:56 -0600423 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600424}
425
qining9220dbb2016-05-04 17:34:38 -0400426// If glslang type is noContraction, return SPIR-V NoContraction decoration.
427spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
428{
429 if (qualifier.noContraction)
430 return spv::DecorationNoContraction;
431 else
John Kessenich4016e382016-07-15 11:53:56 -0600432 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400433}
434
David Netoa901ffe2016-06-08 14:11:40 +0100435// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
436// associated capabilities when required. For some built-in variables, a capability
437// is generated only when using the variable in an executable instruction, but not when
438// just declaring a struct member variable with it. This is true for PointSize,
439// ClipDistance, and CullDistance.
440spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600441{
442 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700443 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600444 // Defer adding the capability until the built-in is actually used.
445 if (! memberDeclaration) {
446 switch (glslangIntermediate->getStage()) {
447 case EShLangGeometry:
448 builder.addCapability(spv::CapabilityGeometryPointSize);
449 break;
450 case EShLangTessControl:
451 case EShLangTessEvaluation:
452 builder.addCapability(spv::CapabilityTessellationPointSize);
453 break;
454 default:
455 break;
456 }
John Kessenich92187592016-02-01 13:45:25 -0700457 }
458 return spv::BuiltInPointSize;
459
John Kessenichebb50532016-05-16 19:22:05 -0600460 // These *Distance capabilities logically belong here, but if the member is declared and
461 // then never used, consumers of SPIR-V prefer the capability not be declared.
462 // They are now generated when used, rather than here when declared.
463 // Potentially, the specification should be more clear what the minimum
464 // use needed is to trigger the capability.
465 //
John Kessenich92187592016-02-01 13:45:25 -0700466 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100467 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600468 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700469 return spv::BuiltInClipDistance;
470
471 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100472 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600473 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700474 return spv::BuiltInCullDistance;
475
476 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500477 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700478 return spv::BuiltInViewportIndex;
479
John Kessenich5e801132016-02-15 11:09:46 -0700480 case glslang::EbvSampleId:
481 builder.addCapability(spv::CapabilitySampleRateShading);
482 return spv::BuiltInSampleId;
483
484 case glslang::EbvSamplePosition:
485 builder.addCapability(spv::CapabilitySampleRateShading);
486 return spv::BuiltInSamplePosition;
487
488 case glslang::EbvSampleMask:
489 builder.addCapability(spv::CapabilitySampleRateShading);
490 return spv::BuiltInSampleMask;
491
John Kessenich78a45572016-07-08 14:05:15 -0600492 case glslang::EbvLayer:
493 builder.addCapability(spv::CapabilityGeometry);
494 return spv::BuiltInLayer;
495
John Kessenich140f3df2015-06-26 16:58:36 -0600496 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600497 case glslang::EbvVertexId: return spv::BuiltInVertexId;
498 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700499 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
500 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600501 case glslang::EbvBaseVertex:
502 case glslang::EbvBaseInstance:
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200503
John Kessenichda581a22015-10-14 14:10:30 -0600504 case glslang::EbvDrawId:
505 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600506 logger->missingFunctionality("shader draw parameters");
John Kessenich4016e382016-07-15 11:53:56 -0600507 return spv::BuiltInMax;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200508
509 case glslang::EbvPrimitiveId:
510 if (glslangIntermediate->getStage() == EShLangFragment)
511 builder.addCapability(spv::CapabilityGeometry);
512 return spv::BuiltInPrimitiveId;
513
John Kessenich140f3df2015-06-26 16:58:36 -0600514 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600515 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
516 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
517 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
518 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
519 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
520 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
521 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600522 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
523 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
524 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
525 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
526 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
527 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
528 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
529 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800530
Rex Xu574ab042016-04-14 16:53:07 +0800531 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800532 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800533 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
534 return spv::BuiltInSubgroupSize;
535
Rex Xu574ab042016-04-14 16:53:07 +0800536 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800537 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800538 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
539 return spv::BuiltInSubgroupLocalInvocationId;
540
Rex Xu574ab042016-04-14 16:53:07 +0800541 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800542 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
543 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
544 return spv::BuiltInSubgroupEqMaskKHR;
545
Rex Xu574ab042016-04-14 16:53:07 +0800546 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800547 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
548 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
549 return spv::BuiltInSubgroupGeMaskKHR;
550
Rex Xu574ab042016-04-14 16:53:07 +0800551 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800552 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
553 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
554 return spv::BuiltInSubgroupGtMaskKHR;
555
Rex Xu574ab042016-04-14 16:53:07 +0800556 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800557 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
558 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
559 return spv::BuiltInSubgroupLeMaskKHR;
560
Rex Xu574ab042016-04-14 16:53:07 +0800561 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800562 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
563 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
564 return spv::BuiltInSubgroupLtMaskKHR;
565
Rex Xu9d93a232016-05-05 12:30:44 +0800566#ifdef AMD_EXTENSIONS
567 case glslang::EbvBaryCoordNoPersp: return spv::BuiltInBaryCoordNoPerspAMD;
568 case glslang::EbvBaryCoordNoPerspCentroid: return spv::BuiltInBaryCoordNoPerspCentroidAMD;
569 case glslang::EbvBaryCoordNoPerspSample: return spv::BuiltInBaryCoordNoPerspSampleAMD;
570 case glslang::EbvBaryCoordSmooth: return spv::BuiltInBaryCoordSmoothAMD;
571 case glslang::EbvBaryCoordSmoothCentroid: return spv::BuiltInBaryCoordSmoothCentroidAMD;
572 case glslang::EbvBaryCoordSmoothSample: return spv::BuiltInBaryCoordSmoothSampleAMD;
573 case glslang::EbvBaryCoordPullModel: return spv::BuiltInBaryCoordPullModelAMD;
574#endif
John Kessenich4016e382016-07-15 11:53:56 -0600575 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600576 }
577}
578
Rex Xufc618912015-09-09 16:42:49 +0800579// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700580spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800581{
582 assert(type.getBasicType() == glslang::EbtSampler);
583
John Kessenich5d0fa972016-02-15 11:57:00 -0700584 // Check for capabilities
585 switch (type.getQualifier().layoutFormat) {
586 case glslang::ElfRg32f:
587 case glslang::ElfRg16f:
588 case glslang::ElfR11fG11fB10f:
589 case glslang::ElfR16f:
590 case glslang::ElfRgba16:
591 case glslang::ElfRgb10A2:
592 case glslang::ElfRg16:
593 case glslang::ElfRg8:
594 case glslang::ElfR16:
595 case glslang::ElfR8:
596 case glslang::ElfRgba16Snorm:
597 case glslang::ElfRg16Snorm:
598 case glslang::ElfRg8Snorm:
599 case glslang::ElfR16Snorm:
600 case glslang::ElfR8Snorm:
601
602 case glslang::ElfRg32i:
603 case glslang::ElfRg16i:
604 case glslang::ElfRg8i:
605 case glslang::ElfR16i:
606 case glslang::ElfR8i:
607
608 case glslang::ElfRgb10a2ui:
609 case glslang::ElfRg32ui:
610 case glslang::ElfRg16ui:
611 case glslang::ElfRg8ui:
612 case glslang::ElfR16ui:
613 case glslang::ElfR8ui:
614 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
615 break;
616
617 default:
618 break;
619 }
620
621 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800622 switch (type.getQualifier().layoutFormat) {
623 case glslang::ElfNone: return spv::ImageFormatUnknown;
624 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
625 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
626 case glslang::ElfR32f: return spv::ImageFormatR32f;
627 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
628 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
629 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
630 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
631 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
632 case glslang::ElfR16f: return spv::ImageFormatR16f;
633 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
634 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
635 case glslang::ElfRg16: return spv::ImageFormatRg16;
636 case glslang::ElfRg8: return spv::ImageFormatRg8;
637 case glslang::ElfR16: return spv::ImageFormatR16;
638 case glslang::ElfR8: return spv::ImageFormatR8;
639 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
640 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
641 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
642 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
643 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
644 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
645 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
646 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
647 case glslang::ElfR32i: return spv::ImageFormatR32i;
648 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
649 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
650 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
651 case glslang::ElfR16i: return spv::ImageFormatR16i;
652 case glslang::ElfR8i: return spv::ImageFormatR8i;
653 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
654 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
655 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
656 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
657 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
658 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
659 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
660 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
661 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
662 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600663 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800664 }
665}
666
qining25262b32016-05-06 17:25:16 -0400667// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700668// descriptor set.
669bool IsDescriptorResource(const glslang::TType& type)
670{
John Kessenichf7497e22016-03-08 21:36:22 -0700671 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700672 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700673 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700674
675 // non block...
676 // basically samplerXXX/subpass/sampler/texture are all included
677 // if they are the global-scope-class, not the function parameter
678 // (or local, if they ever exist) class.
679 if (type.getBasicType() == glslang::EbtSampler)
680 return type.getQualifier().isUniformOrBuffer();
681
682 // None of the above.
683 return false;
684}
685
John Kesseniche0b6cad2015-12-24 10:30:13 -0700686void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
687{
688 if (child.layoutMatrix == glslang::ElmNone)
689 child.layoutMatrix = parent.layoutMatrix;
690
691 if (parent.invariant)
692 child.invariant = true;
693 if (parent.nopersp)
694 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800695#ifdef AMD_EXTENSIONS
696 if (parent.explicitInterp)
697 child.explicitInterp = true;
698#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700699 if (parent.flat)
700 child.flat = true;
701 if (parent.centroid)
702 child.centroid = true;
703 if (parent.patch)
704 child.patch = true;
705 if (parent.sample)
706 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800707 if (parent.coherent)
708 child.coherent = true;
709 if (parent.volatil)
710 child.volatil = true;
711 if (parent.restrict)
712 child.restrict = true;
713 if (parent.readonly)
714 child.readonly = true;
715 if (parent.writeonly)
716 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700717}
718
John Kessenichf2b7f332016-09-01 17:05:23 -0600719bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700720{
John Kessenich7b9fa252016-01-21 18:56:57 -0700721 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600722 // - struct members might inherit from a struct declaration
723 // (note that non-block structs don't explicitly inherit,
724 // only implicitly, meaning no decoration involved)
725 // - affect decorations on the struct members
726 // (note smooth does not, and expecting something like volatile
727 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700728 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600729 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700730}
731
John Kessenich140f3df2015-06-26 16:58:36 -0600732//
733// Implement the TGlslangToSpvTraverser class.
734//
735
Lei Zhang17535f72016-05-04 15:55:59 -0400736TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600737 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
738 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400739 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600740 inMain(false), mainTerminated(false), linkageOnly(false),
741 glslangIntermediate(glslangIntermediate)
742{
743 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
744
745 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700746 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600747 stdBuiltins = builder.import("GLSL.std.450");
748 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600749 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
750 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600751
752 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600753 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
754 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600755 builder.addSourceExtension(it->c_str());
756
757 // Add the top-level modes for this shader.
758
John Kessenich92187592016-02-01 13:45:25 -0700759 if (glslangIntermediate->getXfbMode()) {
760 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600761 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700762 }
John Kessenich140f3df2015-06-26 16:58:36 -0600763
764 unsigned int mode;
765 switch (glslangIntermediate->getStage()) {
766 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600767 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600768 break;
769
770 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600771 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600772 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
773 break;
774
775 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600776 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600777 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700778 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
779 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
780 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600781 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600782 }
John Kessenich4016e382016-07-15 11:53:56 -0600783 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600784 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
785
John Kesseniche6903322015-10-13 16:29:02 -0600786 switch (glslangIntermediate->getVertexSpacing()) {
787 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
788 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
789 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600790 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600791 }
John Kessenich4016e382016-07-15 11:53:56 -0600792 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600793 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
794
795 switch (glslangIntermediate->getVertexOrder()) {
796 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
797 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600798 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600799 }
John Kessenich4016e382016-07-15 11:53:56 -0600800 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600801 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
802
803 if (glslangIntermediate->getPointMode())
804 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600805 break;
806
807 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600808 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600809 switch (glslangIntermediate->getInputPrimitive()) {
810 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
811 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
812 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700813 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600814 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600815 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600816 }
John Kessenich4016e382016-07-15 11:53:56 -0600817 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600818 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600819
John Kessenich140f3df2015-06-26 16:58:36 -0600820 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
821
822 switch (glslangIntermediate->getOutputPrimitive()) {
823 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
824 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
825 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600826 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600827 }
John Kessenich4016e382016-07-15 11:53:56 -0600828 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600829 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
830 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
831 break;
832
833 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600834 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600835 if (glslangIntermediate->getPixelCenterInteger())
836 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600837
John Kessenich140f3df2015-06-26 16:58:36 -0600838 if (glslangIntermediate->getOriginUpperLeft())
839 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600840 else
841 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600842
843 if (glslangIntermediate->getEarlyFragmentTests())
844 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
845
846 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600847 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
848 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600849 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600850 }
John Kessenich4016e382016-07-15 11:53:56 -0600851 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600852 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
853
854 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
855 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600856 break;
857
858 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600859 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600860 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
861 glslangIntermediate->getLocalSize(1),
862 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600863 break;
864
865 default:
866 break;
867 }
868
869}
870
John Kessenich7ba63412015-12-20 17:37:07 -0700871// Finish everything and dump
872void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
873{
874 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100875 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
876 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700877
qiningda397332016-03-09 19:54:03 -0500878 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700879 builder.dump(out);
880}
881
John Kessenich140f3df2015-06-26 16:58:36 -0600882TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
883{
884 if (! mainTerminated) {
885 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
886 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600887 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600888 }
889}
890
891//
892// Implement the traversal functions.
893//
894// Return true from interior nodes to have the external traversal
895// continue on to children. Return false if children were
896// already processed.
897//
898
899//
qining25262b32016-05-06 17:25:16 -0400900// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600901// - uniform/input reads
902// - output writes
903// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
904// - something simple that degenerates into the last bullet
905//
906void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
907{
qining75d1d802016-04-06 14:42:01 -0400908 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
909 if (symbol->getType().getQualifier().isSpecConstant())
910 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
911
John Kessenich140f3df2015-06-26 16:58:36 -0600912 // getSymbolId() will set up all the IO decorations on the first call.
913 // Formal function parameters were mapped during makeFunctions().
914 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700915
916 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
917 if (builder.isPointer(id)) {
918 spv::StorageClass sc = builder.getStorageClass(id);
919 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
920 iOSet.insert(id);
921 }
922
923 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700924 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600925 // Prepare to generate code for the access
926
927 // L-value chains will be computed left to right. We're on the symbol now,
928 // which is the left-most part of the access chain, so now is "clear" time,
929 // followed by setting the base.
930 builder.clearAccessChain();
931
932 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700933 // except for
John Kessenich4bf71552016-09-02 11:20:21 -0600934 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -0700935 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -0600936 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -0700937 // These are also pure R-values.
938 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -0600939 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -0600940 builder.setAccessChainRValue(id);
941 else
942 builder.setAccessChainLValue(id);
943 }
944}
945
946bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
947{
qining40887662016-04-03 22:20:42 -0400948 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
949 if (node->getType().getQualifier().isSpecConstant())
950 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
951
John Kessenich140f3df2015-06-26 16:58:36 -0600952 // First, handle special cases
953 switch (node->getOp()) {
954 case glslang::EOpAssign:
955 case glslang::EOpAddAssign:
956 case glslang::EOpSubAssign:
957 case glslang::EOpMulAssign:
958 case glslang::EOpVectorTimesMatrixAssign:
959 case glslang::EOpVectorTimesScalarAssign:
960 case glslang::EOpMatrixTimesScalarAssign:
961 case glslang::EOpMatrixTimesMatrixAssign:
962 case glslang::EOpDivAssign:
963 case glslang::EOpModAssign:
964 case glslang::EOpAndAssign:
965 case glslang::EOpInclusiveOrAssign:
966 case glslang::EOpExclusiveOrAssign:
967 case glslang::EOpLeftShiftAssign:
968 case glslang::EOpRightShiftAssign:
969 // A bin-op assign "a += b" means the same thing as "a = a + b"
970 // where a is evaluated before b. For a simple assignment, GLSL
971 // says to evaluate the left before the right. So, always, left
972 // node then right node.
973 {
974 // get the left l-value, save it away
975 builder.clearAccessChain();
976 node->getLeft()->traverse(this);
977 spv::Builder::AccessChain lValue = builder.getAccessChain();
978
979 // evaluate the right
980 builder.clearAccessChain();
981 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700982 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600983
984 if (node->getOp() != glslang::EOpAssign) {
985 // the left is also an r-value
986 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700987 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600988
989 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -0600990 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -0400991 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600992 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
993 node->getType().getBasicType());
994
995 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700996 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600997 }
998
999 // store the result
1000 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001001 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001002
1003 // assignments are expressions having an rValue after they are evaluated...
1004 builder.clearAccessChain();
1005 builder.setAccessChainRValue(rValue);
1006 }
1007 return false;
1008 case glslang::EOpIndexDirect:
1009 case glslang::EOpIndexDirectStruct:
1010 {
1011 // Get the left part of the access chain.
1012 node->getLeft()->traverse(this);
1013
1014 // Add the next element in the chain
1015
David Netoa901ffe2016-06-08 14:11:40 +01001016 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001017 if (! node->getLeft()->getType().isArray() &&
1018 node->getLeft()->getType().isVector() &&
1019 node->getOp() == glslang::EOpIndexDirect) {
1020 // This is essentially a hard-coded vector swizzle of size 1,
1021 // so short circuit the access-chain stuff with a swizzle.
1022 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001023 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001024 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001025 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001026 int spvIndex = glslangIndex;
1027 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1028 node->getOp() == glslang::EOpIndexDirectStruct)
1029 {
1030 // This may be, e.g., an anonymous block-member selection, which generally need
1031 // index remapping due to hidden members in anonymous blocks.
1032 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1033 assert(remapper.size() > 0);
1034 spvIndex = remapper[glslangIndex];
1035 }
John Kessenichebb50532016-05-16 19:22:05 -06001036
David Netoa901ffe2016-06-08 14:11:40 +01001037 // normal case for indexing array or structure or block
1038 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1039
1040 // Add capabilities here for accessing PointSize and clip/cull distance.
1041 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001042 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001043 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001044 }
1045 }
1046 return false;
1047 case glslang::EOpIndexIndirect:
1048 {
1049 // Structure or array or vector indirection.
1050 // Will use native SPIR-V access-chain for struct and array indirection;
1051 // matrices are arrays of vectors, so will also work for a matrix.
1052 // Will use the access chain's 'component' for variable index into a vector.
1053
1054 // This adapter is building access chains left to right.
1055 // Set up the access chain to the left.
1056 node->getLeft()->traverse(this);
1057
1058 // save it so that computing the right side doesn't trash it
1059 spv::Builder::AccessChain partial = builder.getAccessChain();
1060
1061 // compute the next index in the chain
1062 builder.clearAccessChain();
1063 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001064 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001065
1066 // restore the saved access chain
1067 builder.setAccessChain(partial);
1068
1069 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001070 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001071 else
John Kessenichfa668da2015-09-13 14:46:30 -06001072 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001073 }
1074 return false;
1075 case glslang::EOpVectorSwizzle:
1076 {
1077 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001078 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001079 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001080 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001081 }
1082 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001083 case glslang::EOpLogicalOr:
1084 case glslang::EOpLogicalAnd:
1085 {
1086
1087 // These may require short circuiting, but can sometimes be done as straight
1088 // binary operations. The right operand must be short circuited if it has
1089 // side effects, and should probably be if it is complex.
1090 if (isTrivial(node->getRight()->getAsTyped()))
1091 break; // handle below as a normal binary operation
1092 // otherwise, we need to do dynamic short circuiting on the right operand
1093 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1094 builder.clearAccessChain();
1095 builder.setAccessChainRValue(result);
1096 }
1097 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001098 default:
1099 break;
1100 }
1101
1102 // Assume generic binary op...
1103
John Kessenich32cfd492016-02-02 12:37:46 -07001104 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001105 builder.clearAccessChain();
1106 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001107 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001108
John Kessenich32cfd492016-02-02 12:37:46 -07001109 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001110 builder.clearAccessChain();
1111 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001112 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001113
John Kessenich32cfd492016-02-02 12:37:46 -07001114 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001115 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001116 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001117 convertGlslangToSpvType(node->getType()), left, right,
1118 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001119
John Kessenich50e57562015-12-21 21:21:11 -07001120 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001121 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001122 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001123 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001124 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001125 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001126 return false;
1127 }
John Kessenich140f3df2015-06-26 16:58:36 -06001128}
1129
1130bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1131{
qining40887662016-04-03 22:20:42 -04001132 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1133 if (node->getType().getQualifier().isSpecConstant())
1134 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1135
John Kessenichfc51d282015-08-19 13:34:18 -06001136 spv::Id result = spv::NoResult;
1137
1138 // try texturing first
1139 result = createImageTextureFunctionCall(node);
1140 if (result != spv::NoResult) {
1141 builder.clearAccessChain();
1142 builder.setAccessChainRValue(result);
1143
1144 return false; // done with this node
1145 }
1146
1147 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001148
1149 if (node->getOp() == glslang::EOpArrayLength) {
1150 // Quite special; won't want to evaluate the operand.
1151
1152 // Normal .length() would have been constant folded by the front-end.
1153 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001154 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001155 assert(node->getOperand()->getType().isRuntimeSizedArray());
1156 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1157 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001158 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1159 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001160
1161 builder.clearAccessChain();
1162 builder.setAccessChainRValue(length);
1163
1164 return false;
1165 }
1166
John Kessenichfc51d282015-08-19 13:34:18 -06001167 // Start by evaluating the operand
1168
John Kessenich8c8505c2016-07-26 12:50:38 -06001169 // Does it need a swizzle inversion? If so, evaluation is inverted;
1170 // operate first on the swizzle base, then apply the swizzle.
1171 spv::Id invertedType = spv::NoType;
1172 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1173 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1174 invertedType = getInvertedSwizzleType(*node->getOperand());
1175
John Kessenich140f3df2015-06-26 16:58:36 -06001176 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001177 if (invertedType != spv::NoType)
1178 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1179 else
1180 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001181
Rex Xufc618912015-09-09 16:42:49 +08001182 spv::Id operand = spv::NoResult;
1183
1184 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1185 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001186 node->getOp() == glslang::EOpAtomicCounter ||
1187 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001188 operand = builder.accessChainGetLValue(); // Special case l-value operands
1189 else
John Kessenich32cfd492016-02-02 12:37:46 -07001190 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001191
John Kessenichf6640762016-08-01 19:44:00 -06001192 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001193 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001194
1195 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001196 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001197 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001198
1199 // if not, then possibly an operation
1200 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001201 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001202
1203 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001204 if (invertedType)
1205 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1206
John Kessenich140f3df2015-06-26 16:58:36 -06001207 builder.clearAccessChain();
1208 builder.setAccessChainRValue(result);
1209
1210 return false; // done with this node
1211 }
1212
1213 // it must be a special case, check...
1214 switch (node->getOp()) {
1215 case glslang::EOpPostIncrement:
1216 case glslang::EOpPostDecrement:
1217 case glslang::EOpPreIncrement:
1218 case glslang::EOpPreDecrement:
1219 {
1220 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001221 spv::Id one = 0;
1222 if (node->getBasicType() == glslang::EbtFloat)
1223 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001224 else if (node->getBasicType() == glslang::EbtDouble)
1225 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001226#ifdef AMD_EXTENSIONS
1227 else if (node->getBasicType() == glslang::EbtFloat16)
1228 one = builder.makeFloat16Constant(1.0F);
1229#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001230 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1231 one = builder.makeInt64Constant(1);
1232 else
1233 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001234 glslang::TOperator op;
1235 if (node->getOp() == glslang::EOpPreIncrement ||
1236 node->getOp() == glslang::EOpPostIncrement)
1237 op = glslang::EOpAdd;
1238 else
1239 op = glslang::EOpSub;
1240
John Kessenichf6640762016-08-01 19:44:00 -06001241 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001242 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001243 convertGlslangToSpvType(node->getType()), operand, one,
1244 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001245 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001246
1247 // The result of operation is always stored, but conditionally the
1248 // consumed result. The consumed result is always an r-value.
1249 builder.accessChainStore(result);
1250 builder.clearAccessChain();
1251 if (node->getOp() == glslang::EOpPreIncrement ||
1252 node->getOp() == glslang::EOpPreDecrement)
1253 builder.setAccessChainRValue(result);
1254 else
1255 builder.setAccessChainRValue(operand);
1256 }
1257
1258 return false;
1259
1260 case glslang::EOpEmitStreamVertex:
1261 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1262 return false;
1263 case glslang::EOpEndStreamPrimitive:
1264 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1265 return false;
1266
1267 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001268 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001269 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001270 }
John Kessenich140f3df2015-06-26 16:58:36 -06001271}
1272
1273bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1274{
qining27e04a02016-04-14 16:40:20 -04001275 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1276 if (node->getType().getQualifier().isSpecConstant())
1277 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1278
John Kessenichfc51d282015-08-19 13:34:18 -06001279 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001280 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1281 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001282
1283 // try texturing
1284 result = createImageTextureFunctionCall(node);
1285 if (result != spv::NoResult) {
1286 builder.clearAccessChain();
1287 builder.setAccessChainRValue(result);
1288
1289 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001290 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001291 // "imageStore" is a special case, which has no result
1292 return false;
1293 }
John Kessenichfc51d282015-08-19 13:34:18 -06001294
John Kessenich140f3df2015-06-26 16:58:36 -06001295 glslang::TOperator binOp = glslang::EOpNull;
1296 bool reduceComparison = true;
1297 bool isMatrix = false;
1298 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001299 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001300
1301 assert(node->getOp());
1302
John Kessenichf6640762016-08-01 19:44:00 -06001303 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001304
1305 switch (node->getOp()) {
1306 case glslang::EOpSequence:
1307 {
1308 if (preVisit)
1309 ++sequenceDepth;
1310 else
1311 --sequenceDepth;
1312
1313 if (sequenceDepth == 1) {
1314 // If this is the parent node of all the functions, we want to see them
1315 // early, so all call points have actual SPIR-V functions to reference.
1316 // In all cases, still let the traverser visit the children for us.
1317 makeFunctions(node->getAsAggregate()->getSequence());
1318
John Kessenich6fccb3c2016-09-19 16:01:41 -06001319 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001320 // anything else gets there, so visit out of order, doing them all now.
1321 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1322
1323 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1324 // so do them manually.
1325 visitFunctions(node->getAsAggregate()->getSequence());
1326
1327 return false;
1328 }
1329
1330 return true;
1331 }
1332 case glslang::EOpLinkerObjects:
1333 {
1334 if (visit == glslang::EvPreVisit)
1335 linkageOnly = true;
1336 else
1337 linkageOnly = false;
1338
1339 return true;
1340 }
1341 case glslang::EOpComma:
1342 {
1343 // processing from left to right naturally leaves the right-most
1344 // lying around in the access chain
1345 glslang::TIntermSequence& glslangOperands = node->getSequence();
1346 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1347 glslangOperands[i]->traverse(this);
1348
1349 return false;
1350 }
1351 case glslang::EOpFunction:
1352 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001353 if (isShaderEntryPoint(node)) {
John Kessenich140f3df2015-06-26 16:58:36 -06001354 inMain = true;
1355 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001356 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001357 } else {
1358 handleFunctionEntry(node);
1359 }
1360 } else {
1361 if (inMain)
1362 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001363 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001364 inMain = false;
1365 }
1366
1367 return true;
1368 case glslang::EOpParameters:
1369 // Parameters will have been consumed by EOpFunction processing, but not
1370 // the body, so we still visited the function node's children, making this
1371 // child redundant.
1372 return false;
1373 case glslang::EOpFunctionCall:
1374 {
1375 if (node->isUserDefined())
1376 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001377 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1378 if (result) {
1379 builder.clearAccessChain();
1380 builder.setAccessChainRValue(result);
1381 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001382 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001383
1384 return false;
1385 }
1386 case glslang::EOpConstructMat2x2:
1387 case glslang::EOpConstructMat2x3:
1388 case glslang::EOpConstructMat2x4:
1389 case glslang::EOpConstructMat3x2:
1390 case glslang::EOpConstructMat3x3:
1391 case glslang::EOpConstructMat3x4:
1392 case glslang::EOpConstructMat4x2:
1393 case glslang::EOpConstructMat4x3:
1394 case glslang::EOpConstructMat4x4:
1395 case glslang::EOpConstructDMat2x2:
1396 case glslang::EOpConstructDMat2x3:
1397 case glslang::EOpConstructDMat2x4:
1398 case glslang::EOpConstructDMat3x2:
1399 case glslang::EOpConstructDMat3x3:
1400 case glslang::EOpConstructDMat3x4:
1401 case glslang::EOpConstructDMat4x2:
1402 case glslang::EOpConstructDMat4x3:
1403 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001404#ifdef AMD_EXTENSIONS
1405 case glslang::EOpConstructF16Mat2x2:
1406 case glslang::EOpConstructF16Mat2x3:
1407 case glslang::EOpConstructF16Mat2x4:
1408 case glslang::EOpConstructF16Mat3x2:
1409 case glslang::EOpConstructF16Mat3x3:
1410 case glslang::EOpConstructF16Mat3x4:
1411 case glslang::EOpConstructF16Mat4x2:
1412 case glslang::EOpConstructF16Mat4x3:
1413 case glslang::EOpConstructF16Mat4x4:
1414#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001415 isMatrix = true;
1416 // fall through
1417 case glslang::EOpConstructFloat:
1418 case glslang::EOpConstructVec2:
1419 case glslang::EOpConstructVec3:
1420 case glslang::EOpConstructVec4:
1421 case glslang::EOpConstructDouble:
1422 case glslang::EOpConstructDVec2:
1423 case glslang::EOpConstructDVec3:
1424 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001425#ifdef AMD_EXTENSIONS
1426 case glslang::EOpConstructFloat16:
1427 case glslang::EOpConstructF16Vec2:
1428 case glslang::EOpConstructF16Vec3:
1429 case glslang::EOpConstructF16Vec4:
1430#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001431 case glslang::EOpConstructBool:
1432 case glslang::EOpConstructBVec2:
1433 case glslang::EOpConstructBVec3:
1434 case glslang::EOpConstructBVec4:
1435 case glslang::EOpConstructInt:
1436 case glslang::EOpConstructIVec2:
1437 case glslang::EOpConstructIVec3:
1438 case glslang::EOpConstructIVec4:
1439 case glslang::EOpConstructUint:
1440 case glslang::EOpConstructUVec2:
1441 case glslang::EOpConstructUVec3:
1442 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001443 case glslang::EOpConstructInt64:
1444 case glslang::EOpConstructI64Vec2:
1445 case glslang::EOpConstructI64Vec3:
1446 case glslang::EOpConstructI64Vec4:
1447 case glslang::EOpConstructUint64:
1448 case glslang::EOpConstructU64Vec2:
1449 case glslang::EOpConstructU64Vec3:
1450 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001451 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001452 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001453 {
1454 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001455 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001456 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001457 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001458 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001459 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001460 std::vector<spv::Id> constituents;
1461 for (int c = 0; c < (int)arguments.size(); ++c)
1462 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001463 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001464 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001465 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001466 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001467 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001468
1469 builder.clearAccessChain();
1470 builder.setAccessChainRValue(constructed);
1471
1472 return false;
1473 }
1474
1475 // These six are component-wise compares with component-wise results.
1476 // Forward on to createBinaryOperation(), requesting a vector result.
1477 case glslang::EOpLessThan:
1478 case glslang::EOpGreaterThan:
1479 case glslang::EOpLessThanEqual:
1480 case glslang::EOpGreaterThanEqual:
1481 case glslang::EOpVectorEqual:
1482 case glslang::EOpVectorNotEqual:
1483 {
1484 // Map the operation to a binary
1485 binOp = node->getOp();
1486 reduceComparison = false;
1487 switch (node->getOp()) {
1488 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1489 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1490 default: binOp = node->getOp(); break;
1491 }
1492
1493 break;
1494 }
1495 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001496 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001497 binOp = glslang::EOpMul;
1498 break;
1499 case glslang::EOpOuterProduct:
1500 // two vectors multiplied to make a matrix
1501 binOp = glslang::EOpOuterProduct;
1502 break;
1503 case glslang::EOpDot:
1504 {
qining25262b32016-05-06 17:25:16 -04001505 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001506 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001507 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001508 binOp = glslang::EOpMul;
1509 break;
1510 }
1511 case glslang::EOpMod:
1512 // when an aggregate, this is the floating-point mod built-in function,
1513 // which can be emitted by the one in createBinaryOperation()
1514 binOp = glslang::EOpMod;
1515 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001516 case glslang::EOpEmitVertex:
1517 case glslang::EOpEndPrimitive:
1518 case glslang::EOpBarrier:
1519 case glslang::EOpMemoryBarrier:
1520 case glslang::EOpMemoryBarrierAtomicCounter:
1521 case glslang::EOpMemoryBarrierBuffer:
1522 case glslang::EOpMemoryBarrierImage:
1523 case glslang::EOpMemoryBarrierShared:
1524 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001525 case glslang::EOpAllMemoryBarrierWithGroupSync:
1526 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1527 case glslang::EOpWorkgroupMemoryBarrier:
1528 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001529 noReturnValue = true;
1530 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1531 break;
1532
John Kessenich426394d2015-07-23 10:22:48 -06001533 case glslang::EOpAtomicAdd:
1534 case glslang::EOpAtomicMin:
1535 case glslang::EOpAtomicMax:
1536 case glslang::EOpAtomicAnd:
1537 case glslang::EOpAtomicOr:
1538 case glslang::EOpAtomicXor:
1539 case glslang::EOpAtomicExchange:
1540 case glslang::EOpAtomicCompSwap:
1541 atomic = true;
1542 break;
1543
John Kessenich140f3df2015-06-26 16:58:36 -06001544 default:
1545 break;
1546 }
1547
1548 //
1549 // See if it maps to a regular operation.
1550 //
John Kessenich140f3df2015-06-26 16:58:36 -06001551 if (binOp != glslang::EOpNull) {
1552 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1553 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1554 assert(left && right);
1555
1556 builder.clearAccessChain();
1557 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001558 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001559
1560 builder.clearAccessChain();
1561 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001562 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001563
qining25262b32016-05-06 17:25:16 -04001564 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001565 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001566 left->getType().getBasicType(), reduceComparison);
1567
1568 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001569 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001570 builder.clearAccessChain();
1571 builder.setAccessChainRValue(result);
1572
1573 return false;
1574 }
1575
John Kessenich426394d2015-07-23 10:22:48 -06001576 //
1577 // Create the list of operands.
1578 //
John Kessenich140f3df2015-06-26 16:58:36 -06001579 glslang::TIntermSequence& glslangOperands = node->getSequence();
1580 std::vector<spv::Id> operands;
1581 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001582 // special case l-value operands; there are just a few
1583 bool lvalue = false;
1584 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001585 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001586 case glslang::EOpModf:
1587 if (arg == 1)
1588 lvalue = true;
1589 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001590 case glslang::EOpInterpolateAtSample:
1591 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001592#ifdef AMD_EXTENSIONS
1593 case glslang::EOpInterpolateAtVertex:
1594#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001595 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001596 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001597
1598 // Does it need a swizzle inversion? If so, evaluation is inverted;
1599 // operate first on the swizzle base, then apply the swizzle.
1600 if (glslangOperands[0]->getAsOperator() &&
1601 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1602 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1603 }
Rex Xu7a26c172015-12-08 17:12:09 +08001604 break;
Rex Xud4782c12015-09-06 16:30:11 +08001605 case glslang::EOpAtomicAdd:
1606 case glslang::EOpAtomicMin:
1607 case glslang::EOpAtomicMax:
1608 case glslang::EOpAtomicAnd:
1609 case glslang::EOpAtomicOr:
1610 case glslang::EOpAtomicXor:
1611 case glslang::EOpAtomicExchange:
1612 case glslang::EOpAtomicCompSwap:
1613 if (arg == 0)
1614 lvalue = true;
1615 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001616 case glslang::EOpAddCarry:
1617 case glslang::EOpSubBorrow:
1618 if (arg == 2)
1619 lvalue = true;
1620 break;
1621 case glslang::EOpUMulExtended:
1622 case glslang::EOpIMulExtended:
1623 if (arg >= 2)
1624 lvalue = true;
1625 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001626 default:
1627 break;
1628 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001629 builder.clearAccessChain();
1630 if (invertedType != spv::NoType && arg == 0)
1631 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1632 else
1633 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001634 if (lvalue)
1635 operands.push_back(builder.accessChainGetLValue());
1636 else
John Kessenich32cfd492016-02-02 12:37:46 -07001637 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001638 }
John Kessenich426394d2015-07-23 10:22:48 -06001639
1640 if (atomic) {
1641 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001642 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001643 } else {
1644 // Pass through to generic operations.
1645 switch (glslangOperands.size()) {
1646 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001647 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001648 break;
1649 case 1:
qining25262b32016-05-06 17:25:16 -04001650 result = createUnaryOperation(
1651 node->getOp(), precision,
1652 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001653 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001654 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001655 break;
1656 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001657 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001658 break;
1659 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001660 if (invertedType)
1661 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001662 }
1663
1664 if (noReturnValue)
1665 return false;
1666
1667 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001668 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001669 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001670 } else {
1671 builder.clearAccessChain();
1672 builder.setAccessChainRValue(result);
1673 return false;
1674 }
1675}
1676
1677bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1678{
1679 // This path handles both if-then-else and ?:
1680 // The if-then-else has a node type of void, while
1681 // ?: has a non-void node type
1682 spv::Id result = 0;
1683 if (node->getBasicType() != glslang::EbtVoid) {
1684 // don't handle this as just on-the-fly temporaries, because there will be two names
1685 // and better to leave SSA to later passes
1686 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1687 }
1688
1689 // emit the condition before doing anything with selection
1690 node->getCondition()->traverse(this);
1691
1692 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001693 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001694
1695 if (node->getTrueBlock()) {
1696 // emit the "then" statement
1697 node->getTrueBlock()->traverse(this);
1698 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001699 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001700 }
1701
1702 if (node->getFalseBlock()) {
1703 ifBuilder.makeBeginElse();
1704 // emit the "else" statement
1705 node->getFalseBlock()->traverse(this);
1706 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001707 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001708 }
1709
1710 ifBuilder.makeEndIf();
1711
1712 if (result) {
1713 // GLSL only has r-values as the result of a :?, but
1714 // if we have an l-value, that can be more efficient if it will
1715 // become the base of a complex r-value expression, because the
1716 // next layer copies r-values into memory to use the access-chain mechanism
1717 builder.clearAccessChain();
1718 builder.setAccessChainLValue(result);
1719 }
1720
1721 return false;
1722}
1723
1724bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1725{
1726 // emit and get the condition before doing anything with switch
1727 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001728 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001729
1730 // browse the children to sort out code segments
1731 int defaultSegment = -1;
1732 std::vector<TIntermNode*> codeSegments;
1733 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1734 std::vector<int> caseValues;
1735 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1736 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1737 TIntermNode* child = *c;
1738 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001739 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001740 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001741 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001742 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1743 } else
1744 codeSegments.push_back(child);
1745 }
1746
qining25262b32016-05-06 17:25:16 -04001747 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001748 // statements between the last case and the end of the switch statement
1749 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1750 (int)codeSegments.size() == defaultSegment)
1751 codeSegments.push_back(nullptr);
1752
1753 // make the switch statement
1754 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001755 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001756
1757 // emit all the code in the segments
1758 breakForLoop.push(false);
1759 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1760 builder.nextSwitchSegment(segmentBlocks, s);
1761 if (codeSegments[s])
1762 codeSegments[s]->traverse(this);
1763 else
1764 builder.addSwitchBreak();
1765 }
1766 breakForLoop.pop();
1767
1768 builder.endSwitch(segmentBlocks);
1769
1770 return false;
1771}
1772
1773void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1774{
1775 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001776 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001777
1778 builder.clearAccessChain();
1779 builder.setAccessChainRValue(constant);
1780}
1781
1782bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1783{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001784 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001785 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001786 // Spec requires back edges to target header blocks, and every header block
1787 // must dominate its merge block. Make a header block first to ensure these
1788 // conditions are met. By definition, it will contain OpLoopMerge, followed
1789 // by a block-ending branch. But we don't want to put any other body/test
1790 // instructions in it, since the body/test may have arbitrary instructions,
1791 // including merges of its own.
1792 builder.setBuildPoint(&blocks.head);
1793 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001794 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001795 spv::Block& test = builder.makeNewBlock();
1796 builder.createBranch(&test);
1797
1798 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001799 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001800 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001801 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001802 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1803
1804 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001805 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001806 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001807 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001808 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001809 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001810
1811 builder.setBuildPoint(&blocks.continue_target);
1812 if (node->getTerminal())
1813 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001814 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001815 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001816 builder.createBranch(&blocks.body);
1817
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001818 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001819 builder.setBuildPoint(&blocks.body);
1820 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001821 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001822 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001823 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001824
1825 builder.setBuildPoint(&blocks.continue_target);
1826 if (node->getTerminal())
1827 node->getTerminal()->traverse(this);
1828 if (node->getTest()) {
1829 node->getTest()->traverse(this);
1830 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001831 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001832 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001833 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001834 // TODO: unless there was a break/return/discard instruction
1835 // somewhere in the body, this is an infinite loop, so we should
1836 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001837 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001838 }
John Kessenich140f3df2015-06-26 16:58:36 -06001839 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001840 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001841 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001842 return false;
1843}
1844
1845bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1846{
1847 if (node->getExpression())
1848 node->getExpression()->traverse(this);
1849
1850 switch (node->getFlowOp()) {
1851 case glslang::EOpKill:
1852 builder.makeDiscard();
1853 break;
1854 case glslang::EOpBreak:
1855 if (breakForLoop.top())
1856 builder.createLoopExit();
1857 else
1858 builder.addSwitchBreak();
1859 break;
1860 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001861 builder.createLoopContinue();
1862 break;
1863 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06001864 if (node->getExpression()) {
1865 const glslang::TType& glslangReturnType = node->getExpression()->getType();
1866 spv::Id returnId = accessChainLoad(glslangReturnType);
1867 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
1868 builder.clearAccessChain();
1869 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
1870 builder.setAccessChainLValue(copyId);
1871 multiTypeStore(glslangReturnType, returnId);
1872 returnId = builder.createLoad(copyId);
1873 }
1874 builder.makeReturn(false, returnId);
1875 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06001876 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001877
1878 builder.clearAccessChain();
1879 break;
1880
1881 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001882 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001883 break;
1884 }
1885
1886 return false;
1887}
1888
1889spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1890{
qining25262b32016-05-06 17:25:16 -04001891 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001892 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001893 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001894 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001895 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001896 }
1897
1898 // Now, handle actual variables
1899 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1900 spv::Id spvType = convertGlslangToSpvType(node->getType());
1901
1902 const char* name = node->getName().c_str();
1903 if (glslang::IsAnonymous(name))
1904 name = "";
1905
1906 return builder.createVariable(storageClass, spvType, name);
1907}
1908
1909// Return type Id of the sampled type.
1910spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1911{
1912 switch (sampler.type) {
1913 case glslang::EbtFloat: return builder.makeFloatType(32);
1914 case glslang::EbtInt: return builder.makeIntType(32);
1915 case glslang::EbtUint: return builder.makeUintType(32);
1916 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001917 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001918 return builder.makeFloatType(32);
1919 }
1920}
1921
John Kessenich8c8505c2016-07-26 12:50:38 -06001922// If node is a swizzle operation, return the type that should be used if
1923// the swizzle base is first consumed by another operation, before the swizzle
1924// is applied.
1925spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
1926{
1927 if (node.getAsOperator() &&
1928 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1929 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
1930 else
1931 return spv::NoType;
1932}
1933
1934// When inverting a swizzle with a parent op, this function
1935// will apply the swizzle operation to a completed parent operation.
1936spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
1937{
1938 std::vector<unsigned> swizzle;
1939 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
1940 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
1941}
1942
John Kessenich8c8505c2016-07-26 12:50:38 -06001943// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
1944void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
1945{
1946 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
1947 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1948 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
1949}
1950
John Kessenich3ac051e2015-12-20 11:29:16 -07001951// Convert from a glslang type to an SPV type, by calling into a
1952// recursive version of this function. This establishes the inherited
1953// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001954spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1955{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001956 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001957}
1958
1959// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001960// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001961// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001962spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001963{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001964 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001965
1966 switch (type.getBasicType()) {
1967 case glslang::EbtVoid:
1968 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001969 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001970 break;
1971 case glslang::EbtFloat:
1972 spvType = builder.makeFloatType(32);
1973 break;
1974 case glslang::EbtDouble:
1975 spvType = builder.makeFloatType(64);
1976 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001977#ifdef AMD_EXTENSIONS
1978 case glslang::EbtFloat16:
1979 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
1980 builder.addCapability(spv::CapabilityFloat16);
1981 spvType = builder.makeFloatType(16);
1982 break;
1983#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001984 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001985 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1986 // a 32-bit int where non-0 means true.
1987 if (explicitLayout != glslang::ElpNone)
1988 spvType = builder.makeUintType(32);
1989 else
1990 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001991 break;
1992 case glslang::EbtInt:
1993 spvType = builder.makeIntType(32);
1994 break;
1995 case glslang::EbtUint:
1996 spvType = builder.makeUintType(32);
1997 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001998 case glslang::EbtInt64:
1999 builder.addCapability(spv::CapabilityInt64);
2000 spvType = builder.makeIntType(64);
2001 break;
2002 case glslang::EbtUint64:
2003 builder.addCapability(spv::CapabilityInt64);
2004 spvType = builder.makeUintType(64);
2005 break;
John Kessenich426394d2015-07-23 10:22:48 -06002006 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002007 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002008 spvType = builder.makeUintType(32);
2009 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002010 case glslang::EbtSampler:
2011 {
2012 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002013 if (sampler.sampler) {
2014 // pure sampler
2015 spvType = builder.makeSamplerType();
2016 } else {
2017 // an image is present, make its type
2018 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2019 sampler.image ? 2 : 1, TranslateImageFormat(type));
2020 if (sampler.combined) {
2021 // already has both image and sampler, make the combined type
2022 spvType = builder.makeSampledImageType(spvType);
2023 }
John Kessenich55e7d112015-11-15 21:33:39 -07002024 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002025 }
John Kessenich140f3df2015-06-26 16:58:36 -06002026 break;
2027 case glslang::EbtStruct:
2028 case glslang::EbtBlock:
2029 {
2030 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002031 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002032
2033 // Try to share structs for different layouts, but not yet for other
2034 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002035 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002036 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002037 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002038 break;
2039
2040 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002041 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002042 memberRemapper[glslangMembers].resize(glslangMembers->size());
2043 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002044 }
2045 break;
2046 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002047 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002048 break;
2049 }
2050
2051 if (type.isMatrix())
2052 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2053 else {
2054 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2055 if (type.getVectorSize() > 1)
2056 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2057 }
2058
2059 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002060 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2061
John Kessenichc9a80832015-09-12 12:17:44 -06002062 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002063 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002064 // We need to decorate array strides for types needing explicit layout, except blocks.
2065 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002066 // Use a dummy glslang type for querying internal strides of
2067 // arrays of arrays, but using just a one-dimensional array.
2068 glslang::TType simpleArrayType(type, 0); // deference type of the array
2069 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2070 simpleArrayType.getArraySizes().dereference();
2071
2072 // Will compute the higher-order strides here, rather than making a whole
2073 // pile of types and doing repetitive recursion on their contents.
2074 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2075 }
John Kessenichf8842e52016-01-04 19:22:56 -07002076
2077 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002078 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002079 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002080 if (stride > 0)
2081 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002082 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002083 }
2084 } else {
2085 // single-dimensional array, and don't yet have stride
2086
John Kessenichf8842e52016-01-04 19:22:56 -07002087 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002088 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2089 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002090 }
John Kessenich31ed4832015-09-09 17:51:38 -06002091
John Kessenichc9a80832015-09-12 12:17:44 -06002092 // Do the outer dimension, which might not be known for a runtime-sized array
2093 if (type.isRuntimeSizedArray()) {
2094 spvType = builder.makeRuntimeArray(spvType);
2095 } else {
2096 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002097 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002098 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002099 if (stride > 0)
2100 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002101 }
2102
2103 return spvType;
2104}
2105
John Kessenich6090df02016-06-30 21:18:02 -06002106
2107// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2108// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2109// Mutually recursive with convertGlslangToSpvType().
2110spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2111 const glslang::TTypeList* glslangMembers,
2112 glslang::TLayoutPacking explicitLayout,
2113 const glslang::TQualifier& qualifier)
2114{
2115 // Create a vector of struct types for SPIR-V to consume
2116 std::vector<spv::Id> spvMembers;
2117 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2118 int locationOffset = 0; // for use across struct members, when they are called recursively
2119 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2120 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2121 if (glslangMember.hiddenMember()) {
2122 ++memberDelta;
2123 if (type.getBasicType() == glslang::EbtBlock)
2124 memberRemapper[glslangMembers][i] = -1;
2125 } else {
2126 if (type.getBasicType() == glslang::EbtBlock)
2127 memberRemapper[glslangMembers][i] = i - memberDelta;
2128 // modify just this child's view of the qualifier
2129 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2130 InheritQualifiers(memberQualifier, qualifier);
2131
2132 // manually inherit location; it's more complex
2133 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2134 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2135 if (qualifier.hasLocation())
2136 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2137
2138 // recurse
2139 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2140 }
2141 }
2142
2143 // Make the SPIR-V type
2144 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002145 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002146 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2147
2148 // Decorate it
2149 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2150
2151 return spvType;
2152}
2153
2154void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2155 const glslang::TTypeList* glslangMembers,
2156 glslang::TLayoutPacking explicitLayout,
2157 const glslang::TQualifier& qualifier,
2158 spv::Id spvType)
2159{
2160 // Name and decorate the non-hidden members
2161 int offset = -1;
2162 int locationOffset = 0; // for use within the members of this struct
2163 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2164 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2165 int member = i;
2166 if (type.getBasicType() == glslang::EbtBlock)
2167 member = memberRemapper[glslangMembers][i];
2168
2169 // modify just this child's view of the qualifier
2170 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2171 InheritQualifiers(memberQualifier, qualifier);
2172
2173 // using -1 above to indicate a hidden member
2174 if (member >= 0) {
2175 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2176 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2177 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2178 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2179 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2180 if (type.getBasicType() == glslang::EbtBlock) {
2181 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2182 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2183 }
2184 }
2185 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2186
2187 if (qualifier.storage == glslang::EvqBuffer) {
2188 std::vector<spv::Decoration> memory;
2189 TranslateMemoryDecoration(memberQualifier, memory);
2190 for (unsigned int i = 0; i < memory.size(); ++i)
2191 addMemberDecoration(spvType, member, memory[i]);
2192 }
2193
John Kessenich2f47bc92016-06-30 21:47:35 -06002194 // Compute location decoration; tricky based on whether inheritance is at play and
2195 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002196 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2197 // probably move to the linker stage of the front end proper, and just have the
2198 // answer sitting already distributed throughout the individual member locations.
2199 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002200 // Ignore member locations if the container is an array, as that's
2201 // ill-specified and decisions have been made to not allow this anyway.
2202 // The object itself must have a location, and that comes out from decorating the object,
2203 // not the type (this code decorates types).
2204 if (! type.isArray()) {
2205 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2206 // struct members should not have explicit locations
2207 assert(type.getBasicType() != glslang::EbtStruct);
2208 location = memberQualifier.layoutLocation;
2209 } else if (type.getBasicType() != glslang::EbtBlock) {
2210 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2211 // The members, and their nested types, must not themselves have Location decorations.
2212 } else if (qualifier.hasLocation()) // inheritance
2213 location = qualifier.layoutLocation + locationOffset;
2214 }
John Kessenich6090df02016-06-30 21:18:02 -06002215 if (location >= 0)
2216 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2217
John Kessenich2f47bc92016-06-30 21:47:35 -06002218 if (qualifier.hasLocation()) // track for upcoming inheritance
2219 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2220
John Kessenich6090df02016-06-30 21:18:02 -06002221 // component, XFB, others
2222 if (glslangMember.getQualifier().hasComponent())
2223 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2224 if (glslangMember.getQualifier().hasXfbOffset())
2225 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2226 else if (explicitLayout != glslang::ElpNone) {
2227 // figure out what to do with offset, which is accumulating
2228 int nextOffset;
2229 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2230 if (offset >= 0)
2231 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2232 offset = nextOffset;
2233 }
2234
2235 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2236 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2237
2238 // built-in variable decorations
2239 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002240 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002241 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2242 }
2243 }
2244
2245 // Decorate the structure
2246 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2247 addDecoration(spvType, TranslateBlockDecoration(type));
2248 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2249 builder.addCapability(spv::CapabilityGeometryStreams);
2250 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2251 }
2252 if (glslangIntermediate->getXfbMode()) {
2253 builder.addCapability(spv::CapabilityTransformFeedback);
2254 if (type.getQualifier().hasXfbStride())
2255 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2256 if (type.getQualifier().hasXfbBuffer())
2257 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2258 }
2259}
2260
John Kessenich6c292d32016-02-15 20:58:50 -07002261// Turn the expression forming the array size into an id.
2262// This is not quite trivial, because of specialization constants.
2263// Sometimes, a raw constant is turned into an Id, and sometimes
2264// a specialization constant expression is.
2265spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2266{
2267 // First, see if this is sized with a node, meaning a specialization constant:
2268 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2269 if (specNode != nullptr) {
2270 builder.clearAccessChain();
2271 specNode->traverse(this);
2272 return accessChainLoad(specNode->getAsTyped()->getType());
2273 }
qining25262b32016-05-06 17:25:16 -04002274
John Kessenich6c292d32016-02-15 20:58:50 -07002275 // Otherwise, need a compile-time (front end) size, get it:
2276 int size = arraySizes.getDimSize(dim);
2277 assert(size > 0);
2278 return builder.makeUintConstant(size);
2279}
2280
John Kessenich103bef92016-02-08 21:38:15 -07002281// Wrap the builder's accessChainLoad to:
2282// - localize handling of RelaxedPrecision
2283// - use the SPIR-V inferred type instead of another conversion of the glslang type
2284// (avoids unnecessary work and possible type punning for structures)
2285// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002286spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2287{
John Kessenich103bef92016-02-08 21:38:15 -07002288 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2289 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2290
2291 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002292 if (type.getBasicType() == glslang::EbtBool) {
2293 if (builder.isScalarType(nominalTypeId)) {
2294 // Conversion for bool
2295 spv::Id boolType = builder.makeBoolType();
2296 if (nominalTypeId != boolType)
2297 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2298 } else if (builder.isVectorType(nominalTypeId)) {
2299 // Conversion for bvec
2300 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2301 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2302 if (nominalTypeId != bvecType)
2303 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2304 }
2305 }
John Kessenich103bef92016-02-08 21:38:15 -07002306
2307 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002308}
2309
Rex Xu27253232016-02-23 17:51:09 +08002310// Wrap the builder's accessChainStore to:
2311// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002312//
2313// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002314void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2315{
2316 // Need to convert to abstract types when necessary
2317 if (type.getBasicType() == glslang::EbtBool) {
2318 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2319
2320 if (builder.isScalarType(nominalTypeId)) {
2321 // Conversion for bool
2322 spv::Id boolType = builder.makeBoolType();
2323 if (nominalTypeId != boolType) {
2324 spv::Id zero = builder.makeUintConstant(0);
2325 spv::Id one = builder.makeUintConstant(1);
2326 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2327 }
2328 } else if (builder.isVectorType(nominalTypeId)) {
2329 // Conversion for bvec
2330 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2331 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2332 if (nominalTypeId != bvecType) {
2333 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2334 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2335 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2336 }
2337 }
2338 }
2339
2340 builder.accessChainStore(rvalue);
2341}
2342
John Kessenich4bf71552016-09-02 11:20:21 -06002343// For storing when types match at the glslang level, but not might match at the
2344// SPIR-V level.
2345//
2346// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002347// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002348// as in a member-decorated way.
2349//
2350// NOTE: This function can handle any store request; if it's not special it
2351// simplifies to a simple OpStore.
2352//
2353// Implicitly uses the existing builder.accessChain as the storage target.
2354void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2355{
John Kessenichb3e24e42016-09-11 12:33:43 -06002356 // we only do the complex path here if it's an aggregate
2357 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002358 accessChainStore(type, rValue);
2359 return;
2360 }
2361
John Kessenichb3e24e42016-09-11 12:33:43 -06002362 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002363 spv::Id rType = builder.getTypeId(rValue);
2364 spv::Id lValue = builder.accessChainGetLValue();
2365 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2366 if (lType == rType) {
2367 accessChainStore(type, rValue);
2368 return;
2369 }
2370
John Kessenichb3e24e42016-09-11 12:33:43 -06002371 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002372 // where the two types were the same type in GLSL. This requires member
2373 // by member copy, recursively.
2374
John Kessenichb3e24e42016-09-11 12:33:43 -06002375 // If an array, copy element by element.
2376 if (type.isArray()) {
2377 glslang::TType glslangElementType(type, 0);
2378 spv::Id elementRType = builder.getContainedTypeId(rType);
2379 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2380 // get the source member
2381 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002382
John Kessenichb3e24e42016-09-11 12:33:43 -06002383 // set up the target storage
2384 builder.clearAccessChain();
2385 builder.setAccessChainLValue(lValue);
2386 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002387
John Kessenichb3e24e42016-09-11 12:33:43 -06002388 // store the member
2389 multiTypeStore(glslangElementType, elementRValue);
2390 }
2391 } else {
2392 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002393
John Kessenichb3e24e42016-09-11 12:33:43 -06002394 // loop over structure members
2395 const glslang::TTypeList& members = *type.getStruct();
2396 for (int m = 0; m < (int)members.size(); ++m) {
2397 const glslang::TType& glslangMemberType = *members[m].type;
2398
2399 // get the source member
2400 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2401 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2402
2403 // set up the target storage
2404 builder.clearAccessChain();
2405 builder.setAccessChainLValue(lValue);
2406 builder.accessChainPush(builder.makeIntConstant(m));
2407
2408 // store the member
2409 multiTypeStore(glslangMemberType, memberRValue);
2410 }
John Kessenich4bf71552016-09-02 11:20:21 -06002411 }
2412}
2413
John Kessenichf85e8062015-12-19 13:57:10 -07002414// Decide whether or not this type should be
2415// decorated with offsets and strides, and if so
2416// whether std140 or std430 rules should be applied.
2417glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002418{
John Kessenichf85e8062015-12-19 13:57:10 -07002419 // has to be a block
2420 if (type.getBasicType() != glslang::EbtBlock)
2421 return glslang::ElpNone;
2422
2423 // has to be a uniform or buffer block
2424 if (type.getQualifier().storage != glslang::EvqUniform &&
2425 type.getQualifier().storage != glslang::EvqBuffer)
2426 return glslang::ElpNone;
2427
2428 // return the layout to use
2429 switch (type.getQualifier().layoutPacking) {
2430 case glslang::ElpStd140:
2431 case glslang::ElpStd430:
2432 return type.getQualifier().layoutPacking;
2433 default:
2434 return glslang::ElpNone;
2435 }
John Kessenich31ed4832015-09-09 17:51:38 -06002436}
2437
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002438// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002439int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002440{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002441 int size;
John Kessenich49987892015-12-29 17:11:44 -07002442 int stride;
2443 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002444
2445 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002446}
2447
John Kessenich49987892015-12-29 17:11:44 -07002448// Given a matrix type, or array (of array) of matrixes type, returns the integer stride required for that matrix
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002449// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002450int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002451{
John Kessenich49987892015-12-29 17:11:44 -07002452 glslang::TType elementType;
2453 elementType.shallowCopy(matrixType);
2454 elementType.clearArraySizes();
2455
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002456 int size;
John Kessenich49987892015-12-29 17:11:44 -07002457 int stride;
2458 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2459
2460 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002461}
2462
John Kessenich5e4b1242015-08-06 22:53:06 -06002463// Given a member type of a struct, realign the current offset for it, and compute
2464// the next (not yet aligned) offset for the next member, which will get aligned
2465// on the next call.
2466// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2467// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2468// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002469void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002470 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002471{
2472 // this will get a positive value when deemed necessary
2473 nextOffset = -1;
2474
John Kessenich5e4b1242015-08-06 22:53:06 -06002475 // override anything in currentOffset with user-set offset
2476 if (memberType.getQualifier().hasOffset())
2477 currentOffset = memberType.getQualifier().layoutOffset;
2478
2479 // It could be that current linker usage in glslang updated all the layoutOffset,
2480 // in which case the following code does not matter. But, that's not quite right
2481 // once cross-compilation unit GLSL validation is done, as the original user
2482 // settings are needed in layoutOffset, and then the following will come into play.
2483
John Kessenichf85e8062015-12-19 13:57:10 -07002484 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002485 if (! memberType.getQualifier().hasOffset())
2486 currentOffset = -1;
2487
2488 return;
2489 }
2490
John Kessenichf85e8062015-12-19 13:57:10 -07002491 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002492 if (currentOffset < 0)
2493 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002494
John Kessenich5e4b1242015-08-06 22:53:06 -06002495 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2496 // but possibly not yet correctly aligned.
2497
2498 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002499 int dummyStride;
2500 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002501 glslang::RoundToPow2(currentOffset, memberAlignment);
2502 nextOffset = currentOffset + memberSize;
2503}
2504
David Netoa901ffe2016-06-08 14:11:40 +01002505void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002506{
David Netoa901ffe2016-06-08 14:11:40 +01002507 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2508 switch (glslangBuiltIn)
2509 {
2510 case glslang::EbvClipDistance:
2511 case glslang::EbvCullDistance:
2512 case glslang::EbvPointSize:
2513 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2514 // Alternately, we could just call this for any glslang built-in, since the
2515 // capability already guards against duplicates.
2516 TranslateBuiltInDecoration(glslangBuiltIn, false);
2517 break;
2518 default:
2519 // Capabilities were already generated when the struct was declared.
2520 break;
2521 }
John Kessenichebb50532016-05-16 19:22:05 -06002522}
2523
John Kessenich6fccb3c2016-09-19 16:01:41 -06002524bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002525{
John Kessenicheee9d532016-09-19 18:09:30 -06002526 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002527}
2528
2529// Make all the functions, skeletally, without actually visiting their bodies.
2530void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2531{
2532 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2533 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002534 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002535 continue;
2536
2537 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002538 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002539 //
qining25262b32016-05-06 17:25:16 -04002540 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002541 // function. What it is an address of varies:
2542 //
John Kessenich4bf71552016-09-02 11:20:21 -06002543 // - "in" parameters not marked as "const" can be written to without modifying the calling
2544 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002545 //
2546 // - "const in" parameters can just be the r-value, as no writes need occur.
2547 //
John Kessenich4bf71552016-09-02 11:20:21 -06002548 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2549 // GLSL has copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
John Kessenich140f3df2015-06-26 16:58:36 -06002550
2551 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002552 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002553 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2554
2555 for (int p = 0; p < (int)parameters.size(); ++p) {
2556 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2557 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002558 if (paramType.isOpaque())
2559 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2560 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002561 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2562 else
John Kessenich4bf71552016-09-02 11:20:21 -06002563 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002564 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002565 paramTypes.push_back(typeId);
2566 }
2567
2568 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002569 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2570 convertGlslangToSpvType(glslFunction->getType()),
2571 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002572
2573 // Track function to emit/call later
2574 functionMap[glslFunction->getName().c_str()] = function;
2575
2576 // Set the parameter id's
2577 for (int p = 0; p < (int)parameters.size(); ++p) {
2578 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2579 // give a name too
2580 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2581 }
2582 }
2583}
2584
2585// Process all the initializers, while skipping the functions and link objects
2586void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2587{
2588 builder.setBuildPoint(shaderEntry->getLastBlock());
2589 for (int i = 0; i < (int)initializers.size(); ++i) {
2590 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2591 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2592
2593 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002594 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002595 initializer->traverse(this);
2596 }
2597 }
2598}
2599
2600// Process all the functions, while skipping initializers.
2601void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2602{
2603 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2604 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2605 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2606 node->traverse(this);
2607 }
2608}
2609
2610void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2611{
qining25262b32016-05-06 17:25:16 -04002612 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002613 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002614 currentFunction = functionMap[node->getName().c_str()];
2615 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002616 builder.setBuildPoint(functionBlock);
2617}
2618
Rex Xu04db3f52015-09-16 11:44:02 +08002619void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002620{
Rex Xufc618912015-09-09 16:42:49 +08002621 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002622
2623 glslang::TSampler sampler = {};
2624 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002625 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002626 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2627 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2628 }
2629
John Kessenich140f3df2015-06-26 16:58:36 -06002630 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2631 builder.clearAccessChain();
2632 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002633
2634 // Special case l-value operands
2635 bool lvalue = false;
2636 switch (node.getOp()) {
2637 case glslang::EOpImageAtomicAdd:
2638 case glslang::EOpImageAtomicMin:
2639 case glslang::EOpImageAtomicMax:
2640 case glslang::EOpImageAtomicAnd:
2641 case glslang::EOpImageAtomicOr:
2642 case glslang::EOpImageAtomicXor:
2643 case glslang::EOpImageAtomicExchange:
2644 case glslang::EOpImageAtomicCompSwap:
2645 if (i == 0)
2646 lvalue = true;
2647 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002648 case glslang::EOpSparseImageLoad:
2649 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2650 lvalue = true;
2651 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002652 case glslang::EOpSparseTexture:
2653 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2654 lvalue = true;
2655 break;
2656 case glslang::EOpSparseTextureClamp:
2657 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2658 lvalue = true;
2659 break;
2660 case glslang::EOpSparseTextureLod:
2661 case glslang::EOpSparseTextureOffset:
2662 if (i == 3)
2663 lvalue = true;
2664 break;
2665 case glslang::EOpSparseTextureFetch:
2666 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2667 lvalue = true;
2668 break;
2669 case glslang::EOpSparseTextureFetchOffset:
2670 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2671 lvalue = true;
2672 break;
2673 case glslang::EOpSparseTextureLodOffset:
2674 case glslang::EOpSparseTextureGrad:
2675 case glslang::EOpSparseTextureOffsetClamp:
2676 if (i == 4)
2677 lvalue = true;
2678 break;
2679 case glslang::EOpSparseTextureGradOffset:
2680 case glslang::EOpSparseTextureGradClamp:
2681 if (i == 5)
2682 lvalue = true;
2683 break;
2684 case glslang::EOpSparseTextureGradOffsetClamp:
2685 if (i == 6)
2686 lvalue = true;
2687 break;
2688 case glslang::EOpSparseTextureGather:
2689 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2690 lvalue = true;
2691 break;
2692 case glslang::EOpSparseTextureGatherOffset:
2693 case glslang::EOpSparseTextureGatherOffsets:
2694 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2695 lvalue = true;
2696 break;
Rex Xufc618912015-09-09 16:42:49 +08002697 default:
2698 break;
2699 }
2700
Rex Xu6b86d492015-09-16 17:48:22 +08002701 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002702 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002703 else
John Kessenich32cfd492016-02-02 12:37:46 -07002704 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002705 }
2706}
2707
John Kessenichfc51d282015-08-19 13:34:18 -06002708void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002709{
John Kessenichfc51d282015-08-19 13:34:18 -06002710 builder.clearAccessChain();
2711 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002712 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002713}
John Kessenich140f3df2015-06-26 16:58:36 -06002714
John Kessenichfc51d282015-08-19 13:34:18 -06002715spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2716{
Rex Xufc618912015-09-09 16:42:49 +08002717 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002718 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002719 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002720 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002721
John Kessenichfc51d282015-08-19 13:34:18 -06002722 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002723 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2724 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2725 std::vector<spv::Id> arguments;
2726 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002727 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002728 else
2729 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002730 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002731
2732 spv::Builder::TextureParameters params = { };
2733 params.sampler = arguments[0];
2734
Rex Xu04db3f52015-09-16 11:44:02 +08002735 glslang::TCrackedTextureOp cracked;
2736 node->crackTexture(sampler, cracked);
2737
John Kessenichfc51d282015-08-19 13:34:18 -06002738 // Check for queries
2739 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002740 // a sampled image needs to have the image extracted first
2741 if (builder.isSampledImage(params.sampler))
2742 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002743 switch (node->getOp()) {
2744 case glslang::EOpImageQuerySize:
2745 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002746 if (arguments.size() > 1) {
2747 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002748 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002749 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002750 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002751 case glslang::EOpImageQuerySamples:
2752 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002753 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002754 case glslang::EOpTextureQueryLod:
2755 params.coords = arguments[1];
2756 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2757 case glslang::EOpTextureQueryLevels:
2758 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002759 case glslang::EOpSparseTexelsResident:
2760 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002761 default:
2762 assert(0);
2763 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002764 }
John Kessenich140f3df2015-06-26 16:58:36 -06002765 }
2766
Rex Xufc618912015-09-09 16:42:49 +08002767 // Check for image functions other than queries
2768 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002769 std::vector<spv::Id> operands;
2770 auto opIt = arguments.begin();
2771 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002772
2773 // Handle subpass operations
2774 // TODO: GLSL should change to have the "MS" only on the type rather than the
2775 // built-in function.
2776 if (cracked.subpass) {
2777 // add on the (0,0) coordinate
2778 spv::Id zero = builder.makeIntConstant(0);
2779 std::vector<spv::Id> comps;
2780 comps.push_back(zero);
2781 comps.push_back(zero);
2782 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2783 if (sampler.ms) {
2784 operands.push_back(spv::ImageOperandsSampleMask);
2785 operands.push_back(*(opIt++));
2786 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002787 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002788 }
2789
John Kessenich56bab042015-09-16 10:54:31 -06002790 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002791 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002792 if (sampler.ms) {
2793 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002794 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002795 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002796 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2797 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002798 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002799 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002800 if (sampler.ms) {
2801 operands.push_back(*(opIt + 1));
2802 operands.push_back(spv::ImageOperandsSampleMask);
2803 operands.push_back(*opIt);
2804 } else
2805 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002806 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002807 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2808 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002809 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002810 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2811 builder.addCapability(spv::CapabilitySparseResidency);
2812 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2813 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2814
2815 if (sampler.ms) {
2816 operands.push_back(spv::ImageOperandsSampleMask);
2817 operands.push_back(*opIt++);
2818 }
2819
2820 // Create the return type that was a special structure
2821 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002822 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002823 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2824 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2825
2826 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2827
2828 // Decode the return type
2829 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2830 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002831 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002832 // Process image atomic operations
2833
2834 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2835 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002836 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002837
John Kessenich8c8505c2016-07-26 12:50:38 -06002838 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002839 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002840
2841 std::vector<spv::Id> operands;
2842 operands.push_back(pointer);
2843 for (; opIt != arguments.end(); ++opIt)
2844 operands.push_back(*opIt);
2845
John Kessenich8c8505c2016-07-26 12:50:38 -06002846 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002847 }
2848 }
2849
2850 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002851 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002852 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2853
John Kessenichfc51d282015-08-19 13:34:18 -06002854 // check for bias argument
2855 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002856 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002857 int nonBiasArgCount = 2;
2858 if (cracked.offset)
2859 ++nonBiasArgCount;
2860 if (cracked.grad)
2861 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002862 if (cracked.lodClamp)
2863 ++nonBiasArgCount;
2864 if (sparse)
2865 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002866
2867 if ((int)arguments.size() > nonBiasArgCount)
2868 bias = true;
2869 }
2870
John Kessenicha5c33d62016-06-02 23:45:21 -06002871 // See if the sampler param should really be just the SPV image part
2872 if (cracked.fetch) {
2873 // a fetch needs to have the image extracted first
2874 if (builder.isSampledImage(params.sampler))
2875 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2876 }
2877
John Kessenichfc51d282015-08-19 13:34:18 -06002878 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002879
John Kessenichfc51d282015-08-19 13:34:18 -06002880 params.coords = arguments[1];
2881 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002882 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002883
2884 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002885 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002886 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002887 ++extraArgs;
2888 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002889 params.Dref = arguments[2];
2890 ++extraArgs;
2891 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002892 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002893 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002894 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002895 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002896 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002897 dRefComp = builder.getNumComponents(params.coords) - 1;
2898 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002899 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2900 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002901
2902 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002903 if (cracked.lod) {
2904 params.lod = arguments[2];
2905 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002906 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2907 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2908 noImplicitLod = true;
2909 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002910
2911 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002912 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002913 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002914 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002915 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002916
2917 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002918 if (cracked.grad) {
2919 params.gradX = arguments[2 + extraArgs];
2920 params.gradY = arguments[3 + extraArgs];
2921 extraArgs += 2;
2922 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002923
2924 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002925 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002926 params.offset = arguments[2 + extraArgs];
2927 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002928 } else if (cracked.offsets) {
2929 params.offsets = arguments[2 + extraArgs];
2930 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002931 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002932
2933 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002934 if (cracked.lodClamp) {
2935 params.lodClamp = arguments[2 + extraArgs];
2936 ++extraArgs;
2937 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002938
2939 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002940 if (sparse) {
2941 params.texelOut = arguments[2 + extraArgs];
2942 ++extraArgs;
2943 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002944
2945 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002946 if (bias) {
2947 params.bias = arguments[2 + extraArgs];
2948 ++extraArgs;
2949 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002950
2951 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002952 if (cracked.gather && ! sampler.shadow) {
2953 // default component is 0, if missing, otherwise an argument
2954 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002955 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002956 ++extraArgs;
2957 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002958 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002959 }
2960 }
John Kessenichfc51d282015-08-19 13:34:18 -06002961
John Kessenich65336482016-06-16 14:06:26 -06002962 // projective component (might not to move)
2963 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2964 // are divided by the last component of P."
2965 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2966 // unused components will appear after all used components."
2967 if (cracked.proj) {
2968 int projSourceComp = builder.getNumComponents(params.coords) - 1;
2969 int projTargetComp;
2970 switch (sampler.dim) {
2971 case glslang::Esd1D: projTargetComp = 1; break;
2972 case glslang::Esd2D: projTargetComp = 2; break;
2973 case glslang::EsdRect: projTargetComp = 2; break;
2974 default: projTargetComp = projSourceComp; break;
2975 }
2976 // copy the projective coordinate if we have to
2977 if (projTargetComp != projSourceComp) {
2978 spv::Id projComp = builder.createCompositeExtract(params.coords,
2979 builder.getScalarTypeId(builder.getTypeId(params.coords)),
2980 projSourceComp);
2981 params.coords = builder.createCompositeInsert(projComp, params.coords,
2982 builder.getTypeId(params.coords), projTargetComp);
2983 }
2984 }
2985
John Kessenich8c8505c2016-07-26 12:50:38 -06002986 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002987}
2988
2989spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2990{
2991 // Grab the function's pointer from the previously created function
2992 spv::Function* function = functionMap[node->getName().c_str()];
2993 if (! function)
2994 return 0;
2995
2996 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2997 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2998
2999 // See comments in makeFunctions() for details about the semantics for parameter passing.
3000 //
3001 // These imply we need a four step process:
3002 // 1. Evaluate the arguments
3003 // 2. Allocate and make copies of in, out, and inout arguments
3004 // 3. Make the call
3005 // 4. Copy back the results
3006
3007 // 1. Evaluate the arguments
3008 std::vector<spv::Builder::AccessChain> lValues;
3009 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003010 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003011 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003012 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003013 // build l-value
3014 builder.clearAccessChain();
3015 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003016 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003017 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07003018 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003019 // save l-value
3020 lValues.push_back(builder.getAccessChain());
3021 } else {
3022 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003023 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003024 }
3025 }
3026
3027 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3028 // copy the original into that space.
3029 //
3030 // Also, build up the list of actual arguments to pass in for the call
3031 int lValueCount = 0;
3032 int rValueCount = 0;
3033 std::vector<spv::Id> spvArgs;
3034 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003035 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003036 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07003037 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003038 builder.setAccessChain(lValues[lValueCount]);
3039 arg = builder.accessChainGetLValue();
3040 ++lValueCount;
3041 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003042 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003043 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3044 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3045 // need to copy the input into output space
3046 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003047 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003048 builder.clearAccessChain();
3049 builder.setAccessChainLValue(arg);
3050 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003051 }
3052 ++lValueCount;
3053 } else {
3054 arg = rValues[rValueCount];
3055 ++rValueCount;
3056 }
3057 spvArgs.push_back(arg);
3058 }
3059
3060 // 3. Make the call.
3061 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003062 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003063
3064 // 4. Copy back out an "out" arguments.
3065 lValueCount = 0;
3066 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003067 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003068 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3069 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3070 spv::Id copy = builder.createLoad(spvArgs[a]);
3071 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003072 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003073 }
3074 ++lValueCount;
3075 }
3076 }
3077
3078 return result;
3079}
3080
3081// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003082spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3083 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003084 spv::Id typeId, spv::Id left, spv::Id right,
3085 glslang::TBasicType typeProxy, bool reduceComparison)
3086{
Rex Xu8ff43de2016-04-22 16:51:45 +08003087 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003088#ifdef AMD_EXTENSIONS
3089 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3090#else
John Kessenich140f3df2015-06-26 16:58:36 -06003091 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003092#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003093 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003094
3095 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003096 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003097 bool comparison = false;
3098
3099 switch (op) {
3100 case glslang::EOpAdd:
3101 case glslang::EOpAddAssign:
3102 if (isFloat)
3103 binOp = spv::OpFAdd;
3104 else
3105 binOp = spv::OpIAdd;
3106 break;
3107 case glslang::EOpSub:
3108 case glslang::EOpSubAssign:
3109 if (isFloat)
3110 binOp = spv::OpFSub;
3111 else
3112 binOp = spv::OpISub;
3113 break;
3114 case glslang::EOpMul:
3115 case glslang::EOpMulAssign:
3116 if (isFloat)
3117 binOp = spv::OpFMul;
3118 else
3119 binOp = spv::OpIMul;
3120 break;
3121 case glslang::EOpVectorTimesScalar:
3122 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003123 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003124 if (builder.isVector(right))
3125 std::swap(left, right);
3126 assert(builder.isScalar(right));
3127 needMatchingVectors = false;
3128 binOp = spv::OpVectorTimesScalar;
3129 } else
3130 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003131 break;
3132 case glslang::EOpVectorTimesMatrix:
3133 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003134 binOp = spv::OpVectorTimesMatrix;
3135 break;
3136 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003137 binOp = spv::OpMatrixTimesVector;
3138 break;
3139 case glslang::EOpMatrixTimesScalar:
3140 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003141 binOp = spv::OpMatrixTimesScalar;
3142 break;
3143 case glslang::EOpMatrixTimesMatrix:
3144 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003145 binOp = spv::OpMatrixTimesMatrix;
3146 break;
3147 case glslang::EOpOuterProduct:
3148 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003149 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003150 break;
3151
3152 case glslang::EOpDiv:
3153 case glslang::EOpDivAssign:
3154 if (isFloat)
3155 binOp = spv::OpFDiv;
3156 else if (isUnsigned)
3157 binOp = spv::OpUDiv;
3158 else
3159 binOp = spv::OpSDiv;
3160 break;
3161 case glslang::EOpMod:
3162 case glslang::EOpModAssign:
3163 if (isFloat)
3164 binOp = spv::OpFMod;
3165 else if (isUnsigned)
3166 binOp = spv::OpUMod;
3167 else
3168 binOp = spv::OpSMod;
3169 break;
3170 case glslang::EOpRightShift:
3171 case glslang::EOpRightShiftAssign:
3172 if (isUnsigned)
3173 binOp = spv::OpShiftRightLogical;
3174 else
3175 binOp = spv::OpShiftRightArithmetic;
3176 break;
3177 case glslang::EOpLeftShift:
3178 case glslang::EOpLeftShiftAssign:
3179 binOp = spv::OpShiftLeftLogical;
3180 break;
3181 case glslang::EOpAnd:
3182 case glslang::EOpAndAssign:
3183 binOp = spv::OpBitwiseAnd;
3184 break;
3185 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003186 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003187 binOp = spv::OpLogicalAnd;
3188 break;
3189 case glslang::EOpInclusiveOr:
3190 case glslang::EOpInclusiveOrAssign:
3191 binOp = spv::OpBitwiseOr;
3192 break;
3193 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003194 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003195 binOp = spv::OpLogicalOr;
3196 break;
3197 case glslang::EOpExclusiveOr:
3198 case glslang::EOpExclusiveOrAssign:
3199 binOp = spv::OpBitwiseXor;
3200 break;
3201 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003202 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003203 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003204 break;
3205
3206 case glslang::EOpLessThan:
3207 case glslang::EOpGreaterThan:
3208 case glslang::EOpLessThanEqual:
3209 case glslang::EOpGreaterThanEqual:
3210 case glslang::EOpEqual:
3211 case glslang::EOpNotEqual:
3212 case glslang::EOpVectorEqual:
3213 case glslang::EOpVectorNotEqual:
3214 comparison = true;
3215 break;
3216 default:
3217 break;
3218 }
3219
John Kessenich7c1aa102015-10-15 13:29:11 -06003220 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003221 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003222 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003223 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003224 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003225
3226 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003227 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003228 builder.promoteScalar(precision, left, right);
3229
qining25262b32016-05-06 17:25:16 -04003230 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3231 addDecoration(result, noContraction);
3232 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003233 }
3234
3235 if (! comparison)
3236 return 0;
3237
John Kessenich7c1aa102015-10-15 13:29:11 -06003238 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003239
John Kessenich4583b612016-08-07 19:14:22 -06003240 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3241 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003242 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003243
3244 switch (op) {
3245 case glslang::EOpLessThan:
3246 if (isFloat)
3247 binOp = spv::OpFOrdLessThan;
3248 else if (isUnsigned)
3249 binOp = spv::OpULessThan;
3250 else
3251 binOp = spv::OpSLessThan;
3252 break;
3253 case glslang::EOpGreaterThan:
3254 if (isFloat)
3255 binOp = spv::OpFOrdGreaterThan;
3256 else if (isUnsigned)
3257 binOp = spv::OpUGreaterThan;
3258 else
3259 binOp = spv::OpSGreaterThan;
3260 break;
3261 case glslang::EOpLessThanEqual:
3262 if (isFloat)
3263 binOp = spv::OpFOrdLessThanEqual;
3264 else if (isUnsigned)
3265 binOp = spv::OpULessThanEqual;
3266 else
3267 binOp = spv::OpSLessThanEqual;
3268 break;
3269 case glslang::EOpGreaterThanEqual:
3270 if (isFloat)
3271 binOp = spv::OpFOrdGreaterThanEqual;
3272 else if (isUnsigned)
3273 binOp = spv::OpUGreaterThanEqual;
3274 else
3275 binOp = spv::OpSGreaterThanEqual;
3276 break;
3277 case glslang::EOpEqual:
3278 case glslang::EOpVectorEqual:
3279 if (isFloat)
3280 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003281 else if (isBool)
3282 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003283 else
3284 binOp = spv::OpIEqual;
3285 break;
3286 case glslang::EOpNotEqual:
3287 case glslang::EOpVectorNotEqual:
3288 if (isFloat)
3289 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003290 else if (isBool)
3291 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003292 else
3293 binOp = spv::OpINotEqual;
3294 break;
3295 default:
3296 break;
3297 }
3298
qining25262b32016-05-06 17:25:16 -04003299 if (binOp != spv::OpNop) {
3300 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3301 addDecoration(result, noContraction);
3302 return builder.setPrecision(result, precision);
3303 }
John Kessenich140f3df2015-06-26 16:58:36 -06003304
3305 return 0;
3306}
3307
John Kessenich04bb8a02015-12-12 12:28:14 -07003308//
3309// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3310// These can be any of:
3311//
3312// matrix * scalar
3313// scalar * matrix
3314// matrix * matrix linear algebraic
3315// matrix * vector
3316// vector * matrix
3317// matrix * matrix componentwise
3318// matrix op matrix op in {+, -, /}
3319// matrix op scalar op in {+, -, /}
3320// scalar op matrix op in {+, -, /}
3321//
qining25262b32016-05-06 17:25:16 -04003322spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07003323{
3324 bool firstClass = true;
3325
3326 // First, handle first-class matrix operations (* and matrix/scalar)
3327 switch (op) {
3328 case spv::OpFDiv:
3329 if (builder.isMatrix(left) && builder.isScalar(right)) {
3330 // turn matrix / scalar into a multiply...
3331 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3332 op = spv::OpMatrixTimesScalar;
3333 } else
3334 firstClass = false;
3335 break;
3336 case spv::OpMatrixTimesScalar:
3337 if (builder.isMatrix(right))
3338 std::swap(left, right);
3339 assert(builder.isScalar(right));
3340 break;
3341 case spv::OpVectorTimesMatrix:
3342 assert(builder.isVector(left));
3343 assert(builder.isMatrix(right));
3344 break;
3345 case spv::OpMatrixTimesVector:
3346 assert(builder.isMatrix(left));
3347 assert(builder.isVector(right));
3348 break;
3349 case spv::OpMatrixTimesMatrix:
3350 assert(builder.isMatrix(left));
3351 assert(builder.isMatrix(right));
3352 break;
3353 default:
3354 firstClass = false;
3355 break;
3356 }
3357
qining25262b32016-05-06 17:25:16 -04003358 if (firstClass) {
3359 spv::Id result = builder.createBinOp(op, typeId, left, right);
3360 addDecoration(result, noContraction);
3361 return builder.setPrecision(result, precision);
3362 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003363
LoopDawg592860c2016-06-09 08:57:35 -06003364 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003365 // The result type of all of them is the same type as the (a) matrix operand.
3366 // The algorithm is to:
3367 // - break the matrix(es) into vectors
3368 // - smear any scalar to a vector
3369 // - do vector operations
3370 // - make a matrix out the vector results
3371 switch (op) {
3372 case spv::OpFAdd:
3373 case spv::OpFSub:
3374 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003375 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003376 case spv::OpFMul:
3377 {
3378 // one time set up...
3379 bool leftMat = builder.isMatrix(left);
3380 bool rightMat = builder.isMatrix(right);
3381 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3382 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3383 spv::Id scalarType = builder.getScalarTypeId(typeId);
3384 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3385 std::vector<spv::Id> results;
3386 spv::Id smearVec = spv::NoResult;
3387 if (builder.isScalar(left))
3388 smearVec = builder.smearScalar(precision, left, vecType);
3389 else if (builder.isScalar(right))
3390 smearVec = builder.smearScalar(precision, right, vecType);
3391
3392 // do each vector op
3393 for (unsigned int c = 0; c < numCols; ++c) {
3394 std::vector<unsigned int> indexes;
3395 indexes.push_back(c);
3396 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3397 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003398 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3399 addDecoration(result, noContraction);
3400 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003401 }
3402
3403 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003404 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003405 }
3406 default:
3407 assert(0);
3408 return spv::NoResult;
3409 }
3410}
3411
qining25262b32016-05-06 17:25:16 -04003412spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06003413{
3414 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003415 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003416 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003417 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003418#ifdef AMD_EXTENSIONS
3419 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3420#else
Rex Xu04db3f52015-09-16 11:44:02 +08003421 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003422#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003423
3424 switch (op) {
3425 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003426 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003427 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003428 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003429 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003430 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003431 unaryOp = spv::OpSNegate;
3432 break;
3433
3434 case glslang::EOpLogicalNot:
3435 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003436 unaryOp = spv::OpLogicalNot;
3437 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003438 case glslang::EOpBitwiseNot:
3439 unaryOp = spv::OpNot;
3440 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003441
John Kessenich140f3df2015-06-26 16:58:36 -06003442 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003443 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003444 break;
3445 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003446 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003447 break;
3448 case glslang::EOpTranspose:
3449 unaryOp = spv::OpTranspose;
3450 break;
3451
3452 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003453 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003454 break;
3455 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003456 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003457 break;
3458 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003459 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003460 break;
3461 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003462 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003463 break;
3464 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003465 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003466 break;
3467 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003468 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003469 break;
3470 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003471 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003472 break;
3473 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003474 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003475 break;
3476
3477 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003478 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003479 break;
3480 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003481 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003482 break;
3483 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003484 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003485 break;
3486 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003487 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003488 break;
3489 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003490 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003491 break;
3492 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003493 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003494 break;
3495
3496 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003497 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003498 break;
3499 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003500 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003501 break;
3502
3503 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003504 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003505 break;
3506 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003507 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003508 break;
3509 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003510 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003511 break;
3512 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003513 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003514 break;
3515 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003516 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003517 break;
3518 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003519 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003520 break;
3521
3522 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003523 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003524 break;
3525 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003526 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003527 break;
3528 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003529 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003530 break;
3531 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003532 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003533 break;
3534 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003535 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003536 break;
3537 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003538 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003539 break;
3540
3541 case glslang::EOpIsNan:
3542 unaryOp = spv::OpIsNan;
3543 break;
3544 case glslang::EOpIsInf:
3545 unaryOp = spv::OpIsInf;
3546 break;
LoopDawg592860c2016-06-09 08:57:35 -06003547 case glslang::EOpIsFinite:
3548 unaryOp = spv::OpIsFinite;
3549 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003550
Rex Xucbc426e2015-12-15 16:03:10 +08003551 case glslang::EOpFloatBitsToInt:
3552 case glslang::EOpFloatBitsToUint:
3553 case glslang::EOpIntBitsToFloat:
3554 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003555 case glslang::EOpDoubleBitsToInt64:
3556 case glslang::EOpDoubleBitsToUint64:
3557 case glslang::EOpInt64BitsToDouble:
3558 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003559 unaryOp = spv::OpBitcast;
3560 break;
3561
John Kessenich140f3df2015-06-26 16:58:36 -06003562 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003563 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003564 break;
3565 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003566 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003567 break;
3568 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003569 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003570 break;
3571 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003572 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003573 break;
3574 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003575 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003576 break;
3577 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003578 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003579 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003580 case glslang::EOpPackSnorm4x8:
3581 libCall = spv::GLSLstd450PackSnorm4x8;
3582 break;
3583 case glslang::EOpUnpackSnorm4x8:
3584 libCall = spv::GLSLstd450UnpackSnorm4x8;
3585 break;
3586 case glslang::EOpPackUnorm4x8:
3587 libCall = spv::GLSLstd450PackUnorm4x8;
3588 break;
3589 case glslang::EOpUnpackUnorm4x8:
3590 libCall = spv::GLSLstd450UnpackUnorm4x8;
3591 break;
3592 case glslang::EOpPackDouble2x32:
3593 libCall = spv::GLSLstd450PackDouble2x32;
3594 break;
3595 case glslang::EOpUnpackDouble2x32:
3596 libCall = spv::GLSLstd450UnpackDouble2x32;
3597 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003598
Rex Xu8ff43de2016-04-22 16:51:45 +08003599 case glslang::EOpPackInt2x32:
3600 case glslang::EOpUnpackInt2x32:
3601 case glslang::EOpPackUint2x32:
3602 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003603 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003604 break;
3605
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003606#ifdef AMD_EXTENSIONS
3607 case glslang::EOpPackFloat2x16:
3608 case glslang::EOpUnpackFloat2x16:
3609 unaryOp = spv::OpBitcast;
3610 break;
3611#endif
3612
John Kessenich140f3df2015-06-26 16:58:36 -06003613 case glslang::EOpDPdx:
3614 unaryOp = spv::OpDPdx;
3615 break;
3616 case glslang::EOpDPdy:
3617 unaryOp = spv::OpDPdy;
3618 break;
3619 case glslang::EOpFwidth:
3620 unaryOp = spv::OpFwidth;
3621 break;
3622 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003623 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003624 unaryOp = spv::OpDPdxFine;
3625 break;
3626 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003627 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003628 unaryOp = spv::OpDPdyFine;
3629 break;
3630 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003631 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003632 unaryOp = spv::OpFwidthFine;
3633 break;
3634 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003635 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003636 unaryOp = spv::OpDPdxCoarse;
3637 break;
3638 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003639 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003640 unaryOp = spv::OpDPdyCoarse;
3641 break;
3642 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003643 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003644 unaryOp = spv::OpFwidthCoarse;
3645 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003646 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003647 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003648 libCall = spv::GLSLstd450InterpolateAtCentroid;
3649 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003650 case glslang::EOpAny:
3651 unaryOp = spv::OpAny;
3652 break;
3653 case glslang::EOpAll:
3654 unaryOp = spv::OpAll;
3655 break;
3656
3657 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003658 if (isFloat)
3659 libCall = spv::GLSLstd450FAbs;
3660 else
3661 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003662 break;
3663 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003664 if (isFloat)
3665 libCall = spv::GLSLstd450FSign;
3666 else
3667 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003668 break;
3669
John Kessenichfc51d282015-08-19 13:34:18 -06003670 case glslang::EOpAtomicCounterIncrement:
3671 case glslang::EOpAtomicCounterDecrement:
3672 case glslang::EOpAtomicCounter:
3673 {
3674 // Handle all of the atomics in one place, in createAtomicOperation()
3675 std::vector<spv::Id> operands;
3676 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003677 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003678 }
3679
John Kessenichfc51d282015-08-19 13:34:18 -06003680 case glslang::EOpBitFieldReverse:
3681 unaryOp = spv::OpBitReverse;
3682 break;
3683 case glslang::EOpBitCount:
3684 unaryOp = spv::OpBitCount;
3685 break;
3686 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003687 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003688 break;
3689 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003690 if (isUnsigned)
3691 libCall = spv::GLSLstd450FindUMsb;
3692 else
3693 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003694 break;
3695
Rex Xu574ab042016-04-14 16:53:07 +08003696 case glslang::EOpBallot:
3697 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003698 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003699 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003700 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003701#ifdef AMD_EXTENSIONS
3702 case glslang::EOpMinInvocations:
3703 case glslang::EOpMaxInvocations:
3704 case glslang::EOpAddInvocations:
3705 case glslang::EOpMinInvocationsNonUniform:
3706 case glslang::EOpMaxInvocationsNonUniform:
3707 case glslang::EOpAddInvocationsNonUniform:
3708#endif
Rex Xu51596642016-09-21 18:56:12 +08003709 {
3710 std::vector<spv::Id> operands;
3711 operands.push_back(operand);
3712 return createInvocationsOperation(op, typeId, operands, typeProxy);
3713 }
Rex Xu9d93a232016-05-05 12:30:44 +08003714
3715#ifdef AMD_EXTENSIONS
3716 case glslang::EOpMbcnt:
3717 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3718 libCall = spv::MbcntAMD;
3719 break;
3720
3721 case glslang::EOpCubeFaceIndex:
3722 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3723 libCall = spv::CubeFaceIndexAMD;
3724 break;
3725
3726 case glslang::EOpCubeFaceCoord:
3727 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3728 libCall = spv::CubeFaceCoordAMD;
3729 break;
3730#endif
Rex Xu338b1852016-05-05 20:38:33 +08003731
John Kessenich140f3df2015-06-26 16:58:36 -06003732 default:
3733 return 0;
3734 }
3735
3736 spv::Id id;
3737 if (libCall >= 0) {
3738 std::vector<spv::Id> args;
3739 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003740 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003741 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003742 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003743 }
John Kessenich140f3df2015-06-26 16:58:36 -06003744
qining25262b32016-05-06 17:25:16 -04003745 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003746 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003747}
3748
John Kessenich7a53f762016-01-20 11:19:27 -07003749// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003750spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07003751{
3752 // Handle unary operations vector by vector.
3753 // The result type is the same type as the original type.
3754 // The algorithm is to:
3755 // - break the matrix into vectors
3756 // - apply the operation to each vector
3757 // - make a matrix out the vector results
3758
3759 // get the types sorted out
3760 int numCols = builder.getNumColumns(operand);
3761 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003762 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3763 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003764 std::vector<spv::Id> results;
3765
3766 // do each vector op
3767 for (int c = 0; c < numCols; ++c) {
3768 std::vector<unsigned int> indexes;
3769 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003770 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3771 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3772 addDecoration(destVec, noContraction);
3773 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003774 }
3775
3776 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003777 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003778}
3779
Rex Xu73e3ce72016-04-27 18:48:17 +08003780spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destType, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06003781{
3782 spv::Op convOp = spv::OpNop;
3783 spv::Id zero = 0;
3784 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003785 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003786
3787 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3788
3789 switch (op) {
3790 case glslang::EOpConvIntToBool:
3791 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003792 case glslang::EOpConvInt64ToBool:
3793 case glslang::EOpConvUint64ToBool:
3794 zero = (op == glslang::EOpConvInt64ToBool ||
3795 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003796 zero = makeSmearedConstant(zero, vectorSize);
3797 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3798
3799 case glslang::EOpConvFloatToBool:
3800 zero = builder.makeFloatConstant(0.0F);
3801 zero = makeSmearedConstant(zero, vectorSize);
3802 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3803
3804 case glslang::EOpConvDoubleToBool:
3805 zero = builder.makeDoubleConstant(0.0);
3806 zero = makeSmearedConstant(zero, vectorSize);
3807 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3808
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003809#ifdef AMD_EXTENSIONS
3810 case glslang::EOpConvFloat16ToBool:
3811 zero = builder.makeFloat16Constant(0.0F);
3812 zero = makeSmearedConstant(zero, vectorSize);
3813 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3814#endif
3815
John Kessenich140f3df2015-06-26 16:58:36 -06003816 case glslang::EOpConvBoolToFloat:
3817 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003818 zero = builder.makeFloatConstant(0.0F);
3819 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06003820 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003821
John Kessenich140f3df2015-06-26 16:58:36 -06003822 case glslang::EOpConvBoolToDouble:
3823 convOp = spv::OpSelect;
3824 zero = builder.makeDoubleConstant(0.0);
3825 one = builder.makeDoubleConstant(1.0);
3826 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003827
3828#ifdef AMD_EXTENSIONS
3829 case glslang::EOpConvBoolToFloat16:
3830 convOp = spv::OpSelect;
3831 zero = builder.makeFloat16Constant(0.0F);
3832 one = builder.makeFloat16Constant(1.0F);
3833 break;
3834#endif
3835
John Kessenich140f3df2015-06-26 16:58:36 -06003836 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003837 case glslang::EOpConvBoolToInt64:
3838 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3839 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003840 convOp = spv::OpSelect;
3841 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003842
John Kessenich140f3df2015-06-26 16:58:36 -06003843 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003844 case glslang::EOpConvBoolToUint64:
3845 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3846 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003847 convOp = spv::OpSelect;
3848 break;
3849
3850 case glslang::EOpConvIntToFloat:
3851 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003852 case glslang::EOpConvInt64ToFloat:
3853 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003854#ifdef AMD_EXTENSIONS
3855 case glslang::EOpConvIntToFloat16:
3856 case glslang::EOpConvInt64ToFloat16:
3857#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003858 convOp = spv::OpConvertSToF;
3859 break;
3860
3861 case glslang::EOpConvUintToFloat:
3862 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003863 case glslang::EOpConvUint64ToFloat:
3864 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003865#ifdef AMD_EXTENSIONS
3866 case glslang::EOpConvUintToFloat16:
3867 case glslang::EOpConvUint64ToFloat16:
3868#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003869 convOp = spv::OpConvertUToF;
3870 break;
3871
3872 case glslang::EOpConvDoubleToFloat:
3873 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003874#ifdef AMD_EXTENSIONS
3875 case glslang::EOpConvDoubleToFloat16:
3876 case glslang::EOpConvFloat16ToDouble:
3877 case glslang::EOpConvFloatToFloat16:
3878 case glslang::EOpConvFloat16ToFloat:
3879#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003880 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003881 if (builder.isMatrixType(destType))
3882 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003883 break;
3884
3885 case glslang::EOpConvFloatToInt:
3886 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003887 case glslang::EOpConvFloatToInt64:
3888 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003889#ifdef AMD_EXTENSIONS
3890 case glslang::EOpConvFloat16ToInt:
3891 case glslang::EOpConvFloat16ToInt64:
3892#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003893 convOp = spv::OpConvertFToS;
3894 break;
3895
3896 case glslang::EOpConvUintToInt:
3897 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003898 case glslang::EOpConvUint64ToInt64:
3899 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003900 if (builder.isInSpecConstCodeGenMode()) {
3901 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08003902 zero = (op == glslang::EOpConvUint64ToInt64 ||
3903 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003904 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003905 // Use OpIAdd, instead of OpBitcast to do the conversion when
3906 // generating for OpSpecConstantOp instruction.
3907 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3908 }
3909 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003910 convOp = spv::OpBitcast;
3911 break;
3912
3913 case glslang::EOpConvFloatToUint:
3914 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003915 case glslang::EOpConvFloatToUint64:
3916 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003917#ifdef AMD_EXTENSIONS
3918 case glslang::EOpConvFloat16ToUint:
3919 case glslang::EOpConvFloat16ToUint64:
3920#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003921 convOp = spv::OpConvertFToU;
3922 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003923
3924 case glslang::EOpConvIntToInt64:
3925 case glslang::EOpConvInt64ToInt:
3926 convOp = spv::OpSConvert;
3927 break;
3928
3929 case glslang::EOpConvUintToUint64:
3930 case glslang::EOpConvUint64ToUint:
3931 convOp = spv::OpUConvert;
3932 break;
3933
3934 case glslang::EOpConvIntToUint64:
3935 case glslang::EOpConvInt64ToUint:
3936 case glslang::EOpConvUint64ToInt:
3937 case glslang::EOpConvUintToInt64:
3938 // OpSConvert/OpUConvert + OpBitCast
3939 switch (op) {
3940 case glslang::EOpConvIntToUint64:
3941 convOp = spv::OpSConvert;
3942 type = builder.makeIntType(64);
3943 break;
3944 case glslang::EOpConvInt64ToUint:
3945 convOp = spv::OpSConvert;
3946 type = builder.makeIntType(32);
3947 break;
3948 case glslang::EOpConvUint64ToInt:
3949 convOp = spv::OpUConvert;
3950 type = builder.makeUintType(32);
3951 break;
3952 case glslang::EOpConvUintToInt64:
3953 convOp = spv::OpUConvert;
3954 type = builder.makeUintType(64);
3955 break;
3956 default:
3957 assert(0);
3958 break;
3959 }
3960
3961 if (vectorSize > 0)
3962 type = builder.makeVectorType(type, vectorSize);
3963
3964 operand = builder.createUnaryOp(convOp, type, operand);
3965
3966 if (builder.isInSpecConstCodeGenMode()) {
3967 // Build zero scalar or vector for OpIAdd.
3968 zero = (op == glslang::EOpConvIntToUint64 ||
3969 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3970 zero = makeSmearedConstant(zero, vectorSize);
3971 // Use OpIAdd, instead of OpBitcast to do the conversion when
3972 // generating for OpSpecConstantOp instruction.
3973 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3974 }
3975 // For normal run-time conversion instruction, use OpBitcast.
3976 convOp = spv::OpBitcast;
3977 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003978 default:
3979 break;
3980 }
3981
3982 spv::Id result = 0;
3983 if (convOp == spv::OpNop)
3984 return result;
3985
3986 if (convOp == spv::OpSelect) {
3987 zero = makeSmearedConstant(zero, vectorSize);
3988 one = makeSmearedConstant(one, vectorSize);
3989 result = builder.createTriOp(convOp, destType, operand, one, zero);
3990 } else
3991 result = builder.createUnaryOp(convOp, destType, operand);
3992
John Kessenich32cfd492016-02-02 12:37:46 -07003993 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003994}
3995
3996spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3997{
3998 if (vectorSize == 0)
3999 return constant;
4000
4001 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4002 std::vector<spv::Id> components;
4003 for (int c = 0; c < vectorSize; ++c)
4004 components.push_back(constant);
4005 return builder.makeCompositeConstant(vectorTypeId, components);
4006}
4007
John Kessenich426394d2015-07-23 10:22:48 -06004008// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004009spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich426394d2015-07-23 10:22:48 -06004010{
4011 spv::Op opCode = spv::OpNop;
4012
4013 switch (op) {
4014 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004015 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004016 opCode = spv::OpAtomicIAdd;
4017 break;
4018 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004019 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004020 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004021 break;
4022 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004023 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004024 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004025 break;
4026 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004027 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004028 opCode = spv::OpAtomicAnd;
4029 break;
4030 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004031 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004032 opCode = spv::OpAtomicOr;
4033 break;
4034 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004035 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004036 opCode = spv::OpAtomicXor;
4037 break;
4038 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004039 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004040 opCode = spv::OpAtomicExchange;
4041 break;
4042 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004043 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004044 opCode = spv::OpAtomicCompareExchange;
4045 break;
4046 case glslang::EOpAtomicCounterIncrement:
4047 opCode = spv::OpAtomicIIncrement;
4048 break;
4049 case glslang::EOpAtomicCounterDecrement:
4050 opCode = spv::OpAtomicIDecrement;
4051 break;
4052 case glslang::EOpAtomicCounter:
4053 opCode = spv::OpAtomicLoad;
4054 break;
4055 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004056 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004057 break;
4058 }
4059
4060 // Sort out the operands
4061 // - mapping from glslang -> SPV
4062 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004063 // - compare-exchange swaps the value and comparator
4064 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004065 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4066 auto opIt = operands.begin(); // walk the glslang operands
4067 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004068 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4069 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4070 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004071 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4072 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004073 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004074 spvAtomicOperands.push_back(*(opIt + 1));
4075 spvAtomicOperands.push_back(*opIt);
4076 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004077 }
John Kessenich426394d2015-07-23 10:22:48 -06004078
John Kessenich3e60a6f2015-09-14 22:45:16 -06004079 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004080 for (; opIt != operands.end(); ++opIt)
4081 spvAtomicOperands.push_back(*opIt);
4082
4083 return builder.createOp(opCode, typeId, spvAtomicOperands);
4084}
4085
John Kessenich91cef522016-05-05 16:45:40 -06004086// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004087spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004088{
Rex Xu9d93a232016-05-05 12:30:44 +08004089 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004090#ifdef AMD_EXTENSIONS
4091 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4092#else
Rex Xu9d93a232016-05-05 12:30:44 +08004093 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004094#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004095
Rex Xu51596642016-09-21 18:56:12 +08004096 spv::Op opCode = spv::OpNop;
John Kessenich91cef522016-05-05 16:45:40 -06004097
Rex Xu51596642016-09-21 18:56:12 +08004098 std::vector<spv::Id> spvGroupOperands;
4099 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation) {
4100 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4101 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
4102 } else {
4103 builder.addCapability(spv::CapabilityGroups);
4104
4105 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004106#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +08004107 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
4108 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
4109 spvGroupOperands.push_back(spv::GroupOperationReduce);
Rex Xu9d93a232016-05-05 12:30:44 +08004110#endif
Rex Xu51596642016-09-21 18:56:12 +08004111 }
4112
4113 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4114 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004115
4116 switch (op) {
4117 case glslang::EOpAnyInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004118 opCode = spv::OpGroupAny;
4119 break;
John Kessenich91cef522016-05-05 16:45:40 -06004120 case glslang::EOpAllInvocations:
Rex Xu51596642016-09-21 18:56:12 +08004121 opCode = spv::OpGroupAll;
4122 break;
John Kessenich91cef522016-05-05 16:45:40 -06004123 case glslang::EOpAllInvocationsEqual:
4124 {
Rex Xu51596642016-09-21 18:56:12 +08004125 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, spvGroupOperands);
4126 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004127
4128 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
4129 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
4130 }
Rex Xu51596642016-09-21 18:56:12 +08004131
4132 case glslang::EOpReadInvocation:
4133 opCode = spv::OpGroupBroadcast;
Rex Xub7072052016-09-26 15:53:40 +08004134 if (builder.isVectorType(typeId))
4135 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004136 break;
4137 case glslang::EOpReadFirstInvocation:
4138 opCode = spv::OpSubgroupFirstInvocationKHR;
4139 break;
4140 case glslang::EOpBallot:
4141 {
4142 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4143 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4144 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4145 //
4146 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4147 //
4148 spv::Id uintType = builder.makeUintType(32);
4149 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4150 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4151
4152 std::vector<spv::Id> components;
4153 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4154 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4155
4156 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4157 return builder.createUnaryOp(spv::OpBitcast, typeId,
4158 builder.createCompositeConstruct(uvec2Type, components));
4159 }
4160
Rex Xu9d93a232016-05-05 12:30:44 +08004161#ifdef AMD_EXTENSIONS
4162 case glslang::EOpMinInvocations:
4163 case glslang::EOpMaxInvocations:
4164 case glslang::EOpAddInvocations:
Rex Xu9d93a232016-05-05 12:30:44 +08004165 if (op == glslang::EOpMinInvocations) {
4166 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004167 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004168 else {
4169 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004170 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004171 else
Rex Xu51596642016-09-21 18:56:12 +08004172 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004173 }
4174 } else if (op == glslang::EOpMaxInvocations) {
4175 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004176 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004177 else {
4178 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004179 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004180 else
Rex Xu51596642016-09-21 18:56:12 +08004181 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004182 }
4183 } else {
4184 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004185 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004186 else
Rex Xu51596642016-09-21 18:56:12 +08004187 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004188 }
4189
Rex Xu2bbbe062016-08-23 15:41:05 +08004190 if (builder.isVectorType(typeId))
Rex Xub7072052016-09-26 15:53:40 +08004191 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004192
4193 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004194 case glslang::EOpMinInvocationsNonUniform:
4195 case glslang::EOpMaxInvocationsNonUniform:
4196 case glslang::EOpAddInvocationsNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004197 if (op == glslang::EOpMinInvocationsNonUniform) {
4198 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004199 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004200 else {
4201 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004202 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004203 else
Rex Xu51596642016-09-21 18:56:12 +08004204 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004205 }
4206 }
4207 else if (op == glslang::EOpMaxInvocationsNonUniform) {
4208 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004209 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004210 else {
4211 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004212 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004213 else
Rex Xu51596642016-09-21 18:56:12 +08004214 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004215 }
4216 }
4217 else {
4218 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004219 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004220 else
Rex Xu51596642016-09-21 18:56:12 +08004221 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004222 }
4223
Rex Xu2bbbe062016-08-23 15:41:05 +08004224 if (builder.isVectorType(typeId))
Rex Xub7072052016-09-26 15:53:40 +08004225 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004226
4227 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004228#endif
John Kessenich91cef522016-05-05 16:45:40 -06004229 default:
4230 logger->missingFunctionality("invocation operation");
4231 return spv::NoResult;
4232 }
Rex Xu51596642016-09-21 18:56:12 +08004233
4234 assert(opCode != spv::OpNop);
4235 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004236}
4237
Rex Xu2bbbe062016-08-23 15:41:05 +08004238// Create group invocation operations on a vector
Rex Xub7072052016-09-26 15:53:40 +08004239spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004240{
Rex Xub7072052016-09-26 15:53:40 +08004241#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004242 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4243 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004244 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004245 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4246 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4247 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004248#else
4249 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4250 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
4251 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast);
4252#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004253
4254 // Handle group invocation operations scalar by scalar.
4255 // The result type is the same type as the original type.
4256 // The algorithm is to:
4257 // - break the vector into scalars
4258 // - apply the operation to each scalar
4259 // - make a vector out the scalar results
4260
4261 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004262 int numComponents = builder.getNumComponents(operands[0]);
4263 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004264 std::vector<spv::Id> results;
4265
4266 // do each scalar op
4267 for (int comp = 0; comp < numComponents; ++comp) {
4268 std::vector<unsigned int> indexes;
4269 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004270 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xu2bbbe062016-08-23 15:41:05 +08004271
Rex Xub7072052016-09-26 15:53:40 +08004272 std::vector<spv::Id> spvGroupOperands;
4273 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
4274 if (op == spv::OpGroupBroadcast) {
4275 spvGroupOperands.push_back(scalar);
4276 spvGroupOperands.push_back(operands[1]);
4277 } else {
4278 spvGroupOperands.push_back(spv::GroupOperationReduce);
4279 spvGroupOperands.push_back(scalar);
4280 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004281
Rex Xub7072052016-09-26 15:53:40 +08004282 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004283 }
4284
4285 // put the pieces together
4286 return builder.createCompositeConstruct(typeId, results);
4287}
Rex Xu2bbbe062016-08-23 15:41:05 +08004288
John Kessenich5e4b1242015-08-06 22:53:06 -06004289spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004290{
Rex Xu8ff43de2016-04-22 16:51:45 +08004291 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004292#ifdef AMD_EXTENSIONS
4293 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4294#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004295 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004296#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004297
John Kessenich140f3df2015-06-26 16:58:36 -06004298 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004299 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004300 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004301 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004302 spv::Id typeId0 = 0;
4303 if (consumedOperands > 0)
4304 typeId0 = builder.getTypeId(operands[0]);
4305 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004306
4307 switch (op) {
4308 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004309 if (isFloat)
4310 libCall = spv::GLSLstd450FMin;
4311 else if (isUnsigned)
4312 libCall = spv::GLSLstd450UMin;
4313 else
4314 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004315 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004316 break;
4317 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004318 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004319 break;
4320 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004321 if (isFloat)
4322 libCall = spv::GLSLstd450FMax;
4323 else if (isUnsigned)
4324 libCall = spv::GLSLstd450UMax;
4325 else
4326 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004327 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004328 break;
4329 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004330 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004331 break;
4332 case glslang::EOpDot:
4333 opCode = spv::OpDot;
4334 break;
4335 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004336 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004337 break;
4338
4339 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004340 if (isFloat)
4341 libCall = spv::GLSLstd450FClamp;
4342 else if (isUnsigned)
4343 libCall = spv::GLSLstd450UClamp;
4344 else
4345 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004346 builder.promoteScalar(precision, operands.front(), operands[1]);
4347 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004348 break;
4349 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004350 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4351 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004352 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004353 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004354 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004355 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004356 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004357 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004358 break;
4359 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004360 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004361 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004362 break;
4363 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004364 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004365 builder.promoteScalar(precision, operands[0], operands[2]);
4366 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004367 break;
4368
4369 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004370 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004371 break;
4372 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004373 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004374 break;
4375 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004376 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004377 break;
4378 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004379 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004380 break;
4381 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004382 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004383 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004384 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004385 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004386 libCall = spv::GLSLstd450InterpolateAtSample;
4387 break;
4388 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004389 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004390 libCall = spv::GLSLstd450InterpolateAtOffset;
4391 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004392 case glslang::EOpAddCarry:
4393 opCode = spv::OpIAddCarry;
4394 typeId = builder.makeStructResultType(typeId0, typeId0);
4395 consumedOperands = 2;
4396 break;
4397 case glslang::EOpSubBorrow:
4398 opCode = spv::OpISubBorrow;
4399 typeId = builder.makeStructResultType(typeId0, typeId0);
4400 consumedOperands = 2;
4401 break;
4402 case glslang::EOpUMulExtended:
4403 opCode = spv::OpUMulExtended;
4404 typeId = builder.makeStructResultType(typeId0, typeId0);
4405 consumedOperands = 2;
4406 break;
4407 case glslang::EOpIMulExtended:
4408 opCode = spv::OpSMulExtended;
4409 typeId = builder.makeStructResultType(typeId0, typeId0);
4410 consumedOperands = 2;
4411 break;
4412 case glslang::EOpBitfieldExtract:
4413 if (isUnsigned)
4414 opCode = spv::OpBitFieldUExtract;
4415 else
4416 opCode = spv::OpBitFieldSExtract;
4417 break;
4418 case glslang::EOpBitfieldInsert:
4419 opCode = spv::OpBitFieldInsert;
4420 break;
4421
4422 case glslang::EOpFma:
4423 libCall = spv::GLSLstd450Fma;
4424 break;
4425 case glslang::EOpFrexp:
4426 libCall = spv::GLSLstd450FrexpStruct;
4427 if (builder.getNumComponents(operands[0]) == 1)
4428 frexpIntType = builder.makeIntegerType(32, true);
4429 else
4430 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4431 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4432 consumedOperands = 1;
4433 break;
4434 case glslang::EOpLdexp:
4435 libCall = spv::GLSLstd450Ldexp;
4436 break;
4437
Rex Xu574ab042016-04-14 16:53:07 +08004438 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004439 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004440
Rex Xu9d93a232016-05-05 12:30:44 +08004441#ifdef AMD_EXTENSIONS
4442 case glslang::EOpSwizzleInvocations:
4443 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4444 libCall = spv::SwizzleInvocationsAMD;
4445 break;
4446 case glslang::EOpSwizzleInvocationsMasked:
4447 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4448 libCall = spv::SwizzleInvocationsMaskedAMD;
4449 break;
4450 case glslang::EOpWriteInvocation:
4451 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4452 libCall = spv::WriteInvocationAMD;
4453 break;
4454
4455 case glslang::EOpMin3:
4456 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4457 if (isFloat)
4458 libCall = spv::FMin3AMD;
4459 else {
4460 if (isUnsigned)
4461 libCall = spv::UMin3AMD;
4462 else
4463 libCall = spv::SMin3AMD;
4464 }
4465 break;
4466 case glslang::EOpMax3:
4467 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4468 if (isFloat)
4469 libCall = spv::FMax3AMD;
4470 else {
4471 if (isUnsigned)
4472 libCall = spv::UMax3AMD;
4473 else
4474 libCall = spv::SMax3AMD;
4475 }
4476 break;
4477 case glslang::EOpMid3:
4478 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4479 if (isFloat)
4480 libCall = spv::FMid3AMD;
4481 else {
4482 if (isUnsigned)
4483 libCall = spv::UMid3AMD;
4484 else
4485 libCall = spv::SMid3AMD;
4486 }
4487 break;
4488
4489 case glslang::EOpInterpolateAtVertex:
4490 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4491 libCall = spv::InterpolateAtVertexAMD;
4492 break;
4493#endif
4494
John Kessenich140f3df2015-06-26 16:58:36 -06004495 default:
4496 return 0;
4497 }
4498
4499 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004500 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004501 // Use an extended instruction from the standard library.
4502 // Construct the call arguments, without modifying the original operands vector.
4503 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4504 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004505 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004506 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004507 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004508 case 0:
4509 // should all be handled by visitAggregate and createNoArgOperation
4510 assert(0);
4511 return 0;
4512 case 1:
4513 // should all be handled by createUnaryOperation
4514 assert(0);
4515 return 0;
4516 case 2:
4517 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4518 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004519 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004520 // anything 3 or over doesn't have l-value operands, so all should be consumed
4521 assert(consumedOperands == operands.size());
4522 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004523 break;
4524 }
4525 }
4526
John Kessenich55e7d112015-11-15 21:33:39 -07004527 // Decode the return types that were structures
4528 switch (op) {
4529 case glslang::EOpAddCarry:
4530 case glslang::EOpSubBorrow:
4531 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4532 id = builder.createCompositeExtract(id, typeId0, 0);
4533 break;
4534 case glslang::EOpUMulExtended:
4535 case glslang::EOpIMulExtended:
4536 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4537 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4538 break;
4539 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004540 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004541 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4542 id = builder.createCompositeExtract(id, typeId0, 0);
4543 break;
4544 default:
4545 break;
4546 }
4547
John Kessenich32cfd492016-02-02 12:37:46 -07004548 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004549}
4550
Rex Xu9d93a232016-05-05 12:30:44 +08004551// Intrinsics with no arguments (or no return value, and no precision).
4552spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004553{
4554 // TODO: get the barrier operands correct
4555
4556 switch (op) {
4557 case glslang::EOpEmitVertex:
4558 builder.createNoResultOp(spv::OpEmitVertex);
4559 return 0;
4560 case glslang::EOpEndPrimitive:
4561 builder.createNoResultOp(spv::OpEndPrimitive);
4562 return 0;
4563 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004564 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004565 return 0;
4566 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004567 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004568 return 0;
4569 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004570 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004571 return 0;
4572 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004573 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004574 return 0;
4575 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004576 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004577 return 0;
4578 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004579 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004580 return 0;
4581 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004582 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004583 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004584 case glslang::EOpAllMemoryBarrierWithGroupSync:
4585 // Control barrier with non-"None" semantic is also a memory barrier.
4586 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4587 return 0;
4588 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4589 // Control barrier with non-"None" semantic is also a memory barrier.
4590 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4591 return 0;
4592 case glslang::EOpWorkgroupMemoryBarrier:
4593 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4594 return 0;
4595 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4596 // Control barrier with non-"None" semantic is also a memory barrier.
4597 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4598 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004599#ifdef AMD_EXTENSIONS
4600 case glslang::EOpTime:
4601 {
4602 std::vector<spv::Id> args; // Dummy arguments
4603 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4604 return builder.setPrecision(id, precision);
4605 }
4606#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004607 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004608 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004609 return 0;
4610 }
4611}
4612
4613spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4614{
John Kessenich2f273362015-07-18 22:34:27 -06004615 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004616 spv::Id id;
4617 if (symbolValues.end() != iter) {
4618 id = iter->second;
4619 return id;
4620 }
4621
4622 // it was not found, create it
4623 id = createSpvVariable(symbol);
4624 symbolValues[symbol->getId()] = id;
4625
Rex Xuc884b4a2016-06-29 15:03:44 +08004626 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004627 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004628 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004629 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004630 if (symbol->getType().getQualifier().hasSpecConstantId())
4631 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004632 if (symbol->getQualifier().hasIndex())
4633 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4634 if (symbol->getQualifier().hasComponent())
4635 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4636 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004637 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004638 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004639 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004640 if (symbol->getQualifier().hasXfbBuffer())
4641 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4642 if (symbol->getQualifier().hasXfbOffset())
4643 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4644 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004645 // atomic counters use this:
4646 if (symbol->getQualifier().hasOffset())
4647 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004648 }
4649
scygan2c864272016-05-18 18:09:17 +02004650 if (symbol->getQualifier().hasLocation())
4651 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004652 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004653 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004654 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004655 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004656 }
John Kessenich140f3df2015-06-26 16:58:36 -06004657 if (symbol->getQualifier().hasSet())
4658 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004659 else if (IsDescriptorResource(symbol->getType())) {
4660 // default to 0
4661 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4662 }
John Kessenich140f3df2015-06-26 16:58:36 -06004663 if (symbol->getQualifier().hasBinding())
4664 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004665 if (symbol->getQualifier().hasAttachment())
4666 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004667 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004668 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004669 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004670 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004671 if (symbol->getQualifier().hasXfbBuffer())
4672 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4673 }
4674
Rex Xu1da878f2016-02-21 20:59:01 +08004675 if (symbol->getType().isImage()) {
4676 std::vector<spv::Decoration> memory;
4677 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4678 for (unsigned int i = 0; i < memory.size(); ++i)
4679 addDecoration(id, memory[i]);
4680 }
4681
John Kessenich140f3df2015-06-26 16:58:36 -06004682 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004683 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004684 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004685 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004686
John Kessenich140f3df2015-06-26 16:58:36 -06004687 return id;
4688}
4689
John Kessenich55e7d112015-11-15 21:33:39 -07004690// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004691void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4692{
John Kessenich4016e382016-07-15 11:53:56 -06004693 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004694 builder.addDecoration(id, dec);
4695}
4696
John Kessenich55e7d112015-11-15 21:33:39 -07004697// If 'dec' is valid, add a one-operand decoration to an object
4698void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4699{
John Kessenich4016e382016-07-15 11:53:56 -06004700 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004701 builder.addDecoration(id, dec, value);
4702}
4703
4704// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004705void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4706{
John Kessenich4016e382016-07-15 11:53:56 -06004707 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004708 builder.addMemberDecoration(id, (unsigned)member, dec);
4709}
4710
John Kessenich92187592016-02-01 13:45:25 -07004711// If 'dec' is valid, add a one-operand decoration to a struct member
4712void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4713{
John Kessenich4016e382016-07-15 11:53:56 -06004714 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004715 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4716}
4717
John Kessenich55e7d112015-11-15 21:33:39 -07004718// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004719// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004720//
4721// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4722//
4723// Recursively walk the nodes. The nodes form a tree whose leaves are
4724// regular constants, which themselves are trees that createSpvConstant()
4725// recursively walks. So, this function walks the "top" of the tree:
4726// - emit specialization constant-building instructions for specConstant
4727// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004728spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004729{
John Kessenich7cc0e282016-03-20 00:46:02 -06004730 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004731
qining4f4bb812016-04-03 23:55:17 -04004732 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004733 if (! node.getQualifier().specConstant) {
4734 // hand off to the non-spec-constant path
4735 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4736 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004737 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004738 nextConst, false);
4739 }
4740
4741 // We now know we have a specialization constant to build
4742
John Kessenichd94c0032016-05-30 19:29:40 -06004743 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004744 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4745 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4746 std::vector<spv::Id> dimConstId;
4747 for (int dim = 0; dim < 3; ++dim) {
4748 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4749 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4750 if (specConst)
4751 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4752 }
4753 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4754 }
4755
4756 // An AST node labelled as specialization constant should be a symbol node.
4757 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4758 if (auto* sn = node.getAsSymbolNode()) {
4759 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004760 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4761 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4762 // will set the builder into spec constant op instruction generating mode.
4763 sub_tree->traverse(this);
4764 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004765 } else if (auto* const_union_array = &sn->getConstArray()){
4766 int nextConst = 0;
4767 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004768 }
4769 }
qining4f4bb812016-04-03 23:55:17 -04004770
4771 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4772 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004773 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004774 exit(1);
4775 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004776}
4777
John Kessenich140f3df2015-06-26 16:58:36 -06004778// Use 'consts' as the flattened glslang source of scalar constants to recursively
4779// build the aggregate SPIR-V constant.
4780//
4781// If there are not enough elements present in 'consts', 0 will be substituted;
4782// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4783//
qining08408382016-03-21 09:51:37 -04004784spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004785{
4786 // vector of constants for SPIR-V
4787 std::vector<spv::Id> spvConsts;
4788
4789 // Type is used for struct and array constants
4790 spv::Id typeId = convertGlslangToSpvType(glslangType);
4791
4792 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004793 glslang::TType elementType(glslangType, 0);
4794 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004795 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004796 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004797 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004798 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004799 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004800 } else if (glslangType.getStruct()) {
4801 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4802 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004803 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004804 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004805 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4806 bool zero = nextConst >= consts.size();
4807 switch (glslangType.getBasicType()) {
4808 case glslang::EbtInt:
4809 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4810 break;
4811 case glslang::EbtUint:
4812 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4813 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004814 case glslang::EbtInt64:
4815 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4816 break;
4817 case glslang::EbtUint64:
4818 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4819 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004820 case glslang::EbtFloat:
4821 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4822 break;
4823 case glslang::EbtDouble:
4824 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4825 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004826#ifdef AMD_EXTENSIONS
4827 case glslang::EbtFloat16:
4828 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4829 break;
4830#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004831 case glslang::EbtBool:
4832 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4833 break;
4834 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004835 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004836 break;
4837 }
4838 ++nextConst;
4839 }
4840 } else {
4841 // we have a non-aggregate (scalar) constant
4842 bool zero = nextConst >= consts.size();
4843 spv::Id scalar = 0;
4844 switch (glslangType.getBasicType()) {
4845 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004846 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004847 break;
4848 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004849 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004850 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004851 case glslang::EbtInt64:
4852 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4853 break;
4854 case glslang::EbtUint64:
4855 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4856 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004857 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004858 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004859 break;
4860 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004861 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004862 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004863#ifdef AMD_EXTENSIONS
4864 case glslang::EbtFloat16:
4865 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
4866 break;
4867#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004868 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004869 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004870 break;
4871 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004872 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004873 break;
4874 }
4875 ++nextConst;
4876 return scalar;
4877 }
4878
4879 return builder.makeCompositeConstant(typeId, spvConsts);
4880}
4881
John Kessenich7c1aa102015-10-15 13:29:11 -06004882// Return true if the node is a constant or symbol whose reading has no
4883// non-trivial observable cost or effect.
4884bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4885{
4886 // don't know what this is
4887 if (node == nullptr)
4888 return false;
4889
4890 // a constant is safe
4891 if (node->getAsConstantUnion() != nullptr)
4892 return true;
4893
4894 // not a symbol means non-trivial
4895 if (node->getAsSymbolNode() == nullptr)
4896 return false;
4897
4898 // a symbol, depends on what's being read
4899 switch (node->getType().getQualifier().storage) {
4900 case glslang::EvqTemporary:
4901 case glslang::EvqGlobal:
4902 case glslang::EvqIn:
4903 case glslang::EvqInOut:
4904 case glslang::EvqConst:
4905 case glslang::EvqConstReadOnly:
4906 case glslang::EvqUniform:
4907 return true;
4908 default:
4909 return false;
4910 }
qining25262b32016-05-06 17:25:16 -04004911}
John Kessenich7c1aa102015-10-15 13:29:11 -06004912
4913// A node is trivial if it is a single operation with no side effects.
4914// Error on the side of saying non-trivial.
4915// Return true if trivial.
4916bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4917{
4918 if (node == nullptr)
4919 return false;
4920
4921 // symbols and constants are trivial
4922 if (isTrivialLeaf(node))
4923 return true;
4924
4925 // otherwise, it needs to be a simple operation or one or two leaf nodes
4926
4927 // not a simple operation
4928 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4929 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4930 if (binaryNode == nullptr && unaryNode == nullptr)
4931 return false;
4932
4933 // not on leaf nodes
4934 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4935 return false;
4936
4937 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4938 return false;
4939 }
4940
4941 switch (node->getAsOperator()->getOp()) {
4942 case glslang::EOpLogicalNot:
4943 case glslang::EOpConvIntToBool:
4944 case glslang::EOpConvUintToBool:
4945 case glslang::EOpConvFloatToBool:
4946 case glslang::EOpConvDoubleToBool:
4947 case glslang::EOpEqual:
4948 case glslang::EOpNotEqual:
4949 case glslang::EOpLessThan:
4950 case glslang::EOpGreaterThan:
4951 case glslang::EOpLessThanEqual:
4952 case glslang::EOpGreaterThanEqual:
4953 case glslang::EOpIndexDirect:
4954 case glslang::EOpIndexDirectStruct:
4955 case glslang::EOpLogicalXor:
4956 case glslang::EOpAny:
4957 case glslang::EOpAll:
4958 return true;
4959 default:
4960 return false;
4961 }
4962}
4963
4964// Emit short-circuiting code, where 'right' is never evaluated unless
4965// the left side is true (for &&) or false (for ||).
4966spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4967{
4968 spv::Id boolTypeId = builder.makeBoolType();
4969
4970 // emit left operand
4971 builder.clearAccessChain();
4972 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004973 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004974
4975 // Operands to accumulate OpPhi operands
4976 std::vector<spv::Id> phiOperands;
4977 // accumulate left operand's phi information
4978 phiOperands.push_back(leftId);
4979 phiOperands.push_back(builder.getBuildPoint()->getId());
4980
4981 // Make the two kinds of operation symmetric with a "!"
4982 // || => emit "if (! left) result = right"
4983 // && => emit "if ( left) result = right"
4984 //
4985 // TODO: this runtime "not" for || could be avoided by adding functionality
4986 // to 'builder' to have an "else" without an "then"
4987 if (op == glslang::EOpLogicalOr)
4988 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4989
4990 // make an "if" based on the left value
4991 spv::Builder::If ifBuilder(leftId, builder);
4992
4993 // emit right operand as the "then" part of the "if"
4994 builder.clearAccessChain();
4995 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004996 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004997
4998 // accumulate left operand's phi information
4999 phiOperands.push_back(rightId);
5000 phiOperands.push_back(builder.getBuildPoint()->getId());
5001
5002 // finish the "if"
5003 ifBuilder.makeEndIf();
5004
5005 // phi together the two results
5006 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5007}
5008
Rex Xu9d93a232016-05-05 12:30:44 +08005009// Return type Id of the imported set of extended instructions corresponds to the name.
5010// Import this set if it has not been imported yet.
5011spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5012{
5013 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5014 return extBuiltinMap[name];
5015 else {
Rex Xu51596642016-09-21 18:56:12 +08005016 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005017 spv::Id extBuiltins = builder.import(name);
5018 extBuiltinMap[name] = extBuiltins;
5019 return extBuiltins;
5020 }
5021}
5022
John Kessenich140f3df2015-06-26 16:58:36 -06005023}; // end anonymous namespace
5024
5025namespace glslang {
5026
John Kessenich68d78fd2015-07-12 19:28:10 -06005027void GetSpirvVersion(std::string& version)
5028{
John Kessenich9e55f632015-07-15 10:03:39 -06005029 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005030 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005031 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005032 version = buf;
5033}
5034
John Kessenich140f3df2015-06-26 16:58:36 -06005035// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005036void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005037{
5038 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005039 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06005040 for (int i = 0; i < (int)spirv.size(); ++i) {
5041 unsigned int word = spirv[i];
5042 out.write((const char*)&word, 4);
5043 }
5044 out.close();
5045}
5046
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005047// Write SPIR-V out to a text file with 32-bit hexadecimal words
5048void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
5049{
5050 std::ofstream out;
5051 out.open(baseName, std::ios::binary | std::ios::out);
5052 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
5053 const int WORDS_PER_LINE = 8;
5054 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5055 out << "\t";
5056 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5057 const unsigned int word = spirv[i + j];
5058 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5059 if (i + j + 1 < (int)spirv.size()) {
5060 out << ",";
5061 }
5062 }
5063 out << std::endl;
5064 }
5065 out.close();
5066}
5067
John Kessenich140f3df2015-06-26 16:58:36 -06005068//
5069// Set up the glslang traversal
5070//
5071void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5072{
Lei Zhang17535f72016-05-04 15:55:59 -04005073 spv::SpvBuildLogger logger;
5074 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005075}
5076
Lei Zhang17535f72016-05-04 15:55:59 -04005077void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005078{
John Kessenich140f3df2015-06-26 16:58:36 -06005079 TIntermNode* root = intermediate.getTreeRoot();
5080
5081 if (root == 0)
5082 return;
5083
5084 glslang::GetThreadPoolAllocator().push();
5085
Lei Zhang17535f72016-05-04 15:55:59 -04005086 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005087
5088 root->traverse(&it);
5089
5090 it.dumpSpv(spirv);
5091
5092 glslang::GetThreadPoolAllocator().pop();
5093}
5094
5095}; // end namespace glslang